@go-labs-sg/bb 3.24.0 → 3.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5481,7 +5481,7 @@ function parseSupplierUpdatePayload(raw) {
5481
5481
  }
5482
5482
  __name(parseSupplierUpdatePayload, "parseSupplierUpdatePayload"), __name2(parseSupplierUpdatePayload, "parseSupplierUpdatePayload");
5483
5483
  var normalizeItemPayload = __name2((input) => {
5484
- const normalized = { ...input, name: parseQuickBooksName(input.name), ...typeof input.cost == "number" && Number.isFinite(input.cost) ? { cost: String(input.cost) } : {} };
5484
+ const normalized = { ...input, name: parseQuickBooksName(input.name), ...typeof input.cost == "number" && Number.isFinite(input.cost) ? { cost: input.cost.toLocaleString("en-US", { useGrouping: !1, maximumFractionDigits: 20 }) } : {} };
5485
5485
  return normalizePlainTextRichTextField({ input: normalized, textField: "description", richTextField: "descriptionRichText" });
5486
5486
  }, "normalizeItemPayload");
5487
5487
  function parseItemCreatePayload(raw) {
@@ -5501,9 +5501,10 @@ function parseContactUpdatePayload(raw) {
5501
5501
  }
5502
5502
  __name(parseContactUpdatePayload, "parseContactUpdatePayload"), __name2(parseContactUpdatePayload, "parseContactUpdatePayload");
5503
5503
  function parseCompanyUpdatePayload(raw) {
5504
- const input = requireObject(raw, "update-company payload"), billingEmails = parseCompanyBillingEmails(
5505
- input.billingEmails
5506
- );
5504
+ const input = requireObject(
5505
+ raw,
5506
+ "update-company payload"
5507
+ ), billingEmails = parseCompanyBillingEmails(input.billingEmails);
5507
5508
  if (input.confirmDistinct !== void 0 && typeof input.confirmDistinct != "boolean") throw validationError("confirmDistinct must be a boolean.");
5508
5509
  return { id: requiredString(input.id, "id"), name: parseQuickBooksName(input.name), website: requiredString(input.website, "website"), ...input.confirmDistinct === void 0 ? {} : { confirmDistinct: input.confirmDistinct }, ...billingEmails === void 0 ? {} : { billingEmails } };
5509
5510
  }
@@ -5539,17 +5540,15 @@ var parseCompanyBillingEmails = __name2((raw) => {
5539
5540
  const missing = requiredPermissions.map((effect) => "--allow-".concat(effect));
5540
5541
  throw new CliRuntimeError("CONFIRMATION_REQUIRED", "Non-interactive sensitive commands require an explicit target and all applicable allow flags.", { details: { action: request.action, effects: requiredPermissions, missingFlags: missing } });
5541
5542
  }
5542
- if (requiredPermissions.length === 0) return {
5543
- confirmed: !0,
5544
- requiredPermissions
5545
- };
5543
+ if (requiredPermissions.length === 0) return { confirmed: !0, requiredPermissions };
5546
5544
  const preview = formatConfirmationPreview(request);
5547
5545
  if (runtime.stderr.write("".concat(preview, "\n")), runtime.prompt === void 0) throw new CliRuntimeError("CONFIRMATION_REQUIRED", "This command needs an interactive confirmation prompt.");
5548
5546
  if (await runtime.prompt("Type CONFIRM to continue: ") !== "CONFIRM") throw new CliRuntimeError("ABORTED", "Command aborted by user.");
5549
5547
  return { confirmed: !0, preview, requiredPermissions };
5550
- }, "confirmSensitiveCommand"), sensitiveKeys = /* @__PURE__ */ new Set(["apikey", "authorization", "bb_api_key", "password", "paymentproof", "paymentproofattachments", "paymentproofpath", "paymentreference", "payload", "proof", "receipt", "secret", "token"]), serialize = __name2((value) => "".concat(JSON.stringify(value, null, 2), "\n"), "serialize"), createSuccessEnvelope = __name2((data, invocation) => ({ ok: !0, data, meta: { command: invocation.command, cliVersion: invocation.cliVersion, apiBaseUrl: invocation.apiBaseUrl } }), "createSuccessEnvelope"), emitCliSuccess = __name2((runtime, invocation, data) => (runtime.stdout.write(serialize(
5551
- invocation.legacy ? data : createSuccessEnvelope(data, invocation)
5552
- )), 0), "emitCliSuccess"), emitCliError = __name2((runtime, invocation, error2) => {
5548
+ }, "confirmSensitiveCommand"), sensitiveKeys = /* @__PURE__ */ new Set(["apikey", "authorization", "bb_api_key", "password", "paymentproof", "paymentproofattachments", "paymentproofpath", "paymentreference", "payload", "proof", "receipt", "secret", "token"]), serialize = __name2((value) => "".concat(JSON.stringify(value, null, 2), "\n"), "serialize"), createSuccessEnvelope = __name2((data, invocation) => ({ ok: !0, data, meta: { command: invocation.command, cliVersion: invocation.cliVersion, apiBaseUrl: invocation.apiBaseUrl } }), "createSuccessEnvelope"), emitCliSuccess = __name2(
5549
+ (runtime, invocation, data) => (runtime.stdout.write(serialize(invocation.legacy ? data : createSuccessEnvelope(data, invocation))), 0),
5550
+ "emitCliSuccess"
5551
+ ), emitCliError = __name2((runtime, invocation, error2) => {
5553
5552
  const normalized = normalizeCliError(error2);
5554
5553
  if (invocation.legacy) runtime.stderr.write(serialize({ error: normalized.message }));
5555
5554
  else {
@@ -5570,12 +5569,9 @@ var createProcessRuntime = __name2(() => ({ stdout: { write: __name2((value) =>
5570
5569
  } finally {
5571
5570
  prompt.close();
5572
5571
  }
5573
- }, "prompt"), now: __name2(() => /* @__PURE__ */ new Date(), "now") }), "createProcessRuntime"), activeSession, setActiveCliSession = __name2(
5574
- (session) => {
5575
- activeSession = { ...session, confirmedEffects: /* @__PURE__ */ new Set() };
5576
- },
5577
- "setActiveCliSession"
5578
- ), clearActiveCliSession = __name2(() => {
5572
+ }, "prompt"), now: __name2(() => /* @__PURE__ */ new Date(), "now") }), "createProcessRuntime"), activeSession, setActiveCliSession = __name2((session) => {
5573
+ activeSession = { ...session, confirmedEffects: /* @__PURE__ */ new Set() };
5574
+ }, "setActiveCliSession"), clearActiveCliSession = __name2(() => {
5579
5575
  activeSession = void 0;
5580
5576
  }, "clearActiveCliSession"), getActiveCliSession = __name2(() => activeSession, "getActiveCliSession"), requireSession = __name2(() => {
5581
5577
  if (activeSession === void 0) throw new Error("Budget Builder CLI runtime session is not configured.");
@@ -5589,26 +5585,26 @@ var createProcessRuntime = __name2(() => ({ stdout: { write: __name2((value) =>
5589
5585
  }, "emitCommandResult"), emitCommandError = __name2((error2) => {
5590
5586
  const session = requireSession();
5591
5587
  return emitCliError(session.runtime, session.invocation, error2);
5592
- }, "emitCommandError"), confirmCurrentCommand = __name2(async (input) => {
5593
- const session = requireSession(), unconfirmedEffects = (input.effects ?? session.effects).filter((effect) => !session.confirmedEffects.has(effect));
5594
- if (unconfirmedEffects.length !== 0) {
5595
- await confirmSensitiveCommand(session.runtime, { action: input.action, target: input.target, details: input.details, effects: unconfirmedEffects, permissions: session.permissions });
5596
- for (const effect of unconfirmedEffects) session.confirmedEffects.add(effect);
5597
- }
5598
- }, "confirmCurrentCommand");
5599
- import { contentType } from "mime-types";
5600
- var BUDGET = ApprovalType2.BUDGET, BILL = ApprovalType2.BILL, SUPPLIER = ApprovalType2.SUPPLIER, QUOTATION = ApprovalType2.QUOTATION, CUSTOMER_INVOICE = ApprovalType2.CUSTOMER_INVOICE, ASANA_WON_LOST_SECTION_GIDS = /* @__PURE__ */ new Set(["1211678338364908", "1211678338364907"]), MAX_ASANA_LEAD_CANDIDATES = 5, ASANA_SEARCH_DETAIL_LIMIT = 15, getAllPendingApprovals = __name2(
5601
- async () => {
5602
- const approvals = [];
5603
- let cursor;
5604
- do {
5605
- const page = await api2.budget.getPendingApprovals.query({ limit: 100, cursor });
5606
- approvals.push(...page.items), cursor = page.pageInfo.nextCursor ?? void 0;
5607
- } while (cursor);
5608
- return approvals;
5588
+ }, "emitCommandError"), confirmCurrentCommand = __name2(
5589
+ async (input) => {
5590
+ const session = requireSession(), unconfirmedEffects = (input.effects ?? session.effects).filter((effect) => !session.confirmedEffects.has(effect));
5591
+ if (unconfirmedEffects.length !== 0) {
5592
+ await confirmSensitiveCommand(session.runtime, { action: input.action, target: input.target, details: input.details, effects: unconfirmedEffects, permissions: session.permissions });
5593
+ for (const effect of unconfirmedEffects) session.confirmedEffects.add(effect);
5594
+ }
5609
5595
  },
5610
- "getAllPendingApprovals"
5611
- ), getPendingApproval = __name2(async (approvalId) => {
5596
+ "confirmCurrentCommand"
5597
+ );
5598
+ import { contentType } from "mime-types";
5599
+ var BUDGET = ApprovalType2.BUDGET, BILL = ApprovalType2.BILL, SUPPLIER = ApprovalType2.SUPPLIER, QUOTATION = ApprovalType2.QUOTATION, CUSTOMER_INVOICE = ApprovalType2.CUSTOMER_INVOICE, ASANA_WON_LOST_SECTION_GIDS = /* @__PURE__ */ new Set(["1211678338364908", "1211678338364907"]), MAX_ASANA_LEAD_CANDIDATES = 5, ASANA_SEARCH_DETAIL_LIMIT = 15, getAllPendingApprovals = __name2(async () => {
5600
+ const approvals = [];
5601
+ let cursor;
5602
+ do {
5603
+ const page = await api2.budget.getPendingApprovals.query({ limit: 100, cursor });
5604
+ approvals.push(...page.items), cursor = page.pageInfo.nextCursor ?? void 0;
5605
+ } while (cursor);
5606
+ return approvals;
5607
+ }, "getAllPendingApprovals"), getPendingApproval = __name2(async (approvalId) => {
5612
5608
  out(await api2.budget.getPendingApproval.query({ approvalId }));
5613
5609
  }, "getPendingApproval"), createApprovalEmailDeliveryReport = __name2((delivery) => {
5614
5610
  if (!delivery) return { queued: !1, sent: !1, count: 0, queuedCount: 0, sentCount: 0, skippedCount: 0, error: "No approval email delivery was queued" };
@@ -5621,7 +5617,10 @@ function isPendingRequest(n) {
5621
5617
  __name(isPendingRequest, "isPendingRequest"), __name2(isPendingRequest, "isPendingRequest");
5622
5618
  var out = __name2((data) => {
5623
5619
  emitCommandResult(data);
5624
- }, "out"), isRecord2 = __name2((value) => typeof value == "object" && value !== null && !Array.isArray(value), "isRecord2"), stringField = __name2((record, key) => {
5620
+ }, "out"), isRecord2 = __name2(
5621
+ (value) => typeof value == "object" && value !== null && !Array.isArray(value),
5622
+ "isRecord2"
5623
+ ), stringField = __name2((record, key) => {
5625
5624
  const value = record[key];
5626
5625
  return typeof value == "string" && value.trim() ? value.trim() : void 0;
5627
5626
  }, "stringField"), asanaSectionsForTask = __name2((task) => !isRecord2(task) || !Array.isArray(task.memberships) ? [] : task.memberships.flatMap((membership) => !isRecord2(membership) || !isRecord2(membership.section) ? [] : [{ gid: stringField(membership.section, "gid"), name: stringField(membership.section, "name") }]), "asanaSectionsForTask"), isWonOrLostAsanaTask = __name2((task) => asanaSectionsForTask(task).some((section) => {
@@ -5662,9 +5661,7 @@ var out = __name2((data) => {
5662
5661
  const sectionText = candidate.sections.map((section) => section.name ?? section.gid).filter(Boolean).join(", ") || "stage unavailable", dateText = candidate.modifiedAt ? "modified ".concat(new Date(candidate.modifiedAt).toISOString()) : candidate.createdAt ? "created ".concat(new Date(candidate.createdAt).toISOString()) : "date unavailable";
5663
5662
  return "".concat(sectionText, "; ").concat(dateText, "; ").concat(candidate.gid);
5664
5663
  }, "formatAsanaCandidateMetadata"), promptForAsanaLeadCandidate = __name2(async (candidates) => {
5665
- if (candidates.length === 0) throw new Error(
5666
- "create-project requires an existing Asana deal task in the Deals project; none matched. For a new direct client, create the deal task using the website form first, then pass --asanaTaskId or --asanaSearch."
5667
- );
5664
+ if (candidates.length === 0) throw new Error("create-project requires an existing Asana deal task in the Deals project; none matched. For a new direct client, create the deal task using the website form first, then pass --asanaTaskId or --asanaSearch.");
5668
5665
  if (!process.stdin.isTTY || !process.stderr.isTTY) throw new Error("create-project requires an existing Asana deal task: pass --asanaTaskId in non-interactive runs. Create the deal task using the website form first for a new direct client. Interactive runs can choose from matching tasks.");
5669
5666
  console.error("Select the Asana lead task to link to this project:"), candidates.forEach((candidate, index) => {
5670
5667
  console.error("".concat(index + 1, ". ").concat(candidate.name, " (").concat(formatAsanaCandidateMetadata(candidate), ")"));
@@ -5673,7 +5670,9 @@ var out = __name2((data) => {
5673
5670
  try {
5674
5671
  for (; ; ) {
5675
5672
  const trimmed = (await rl.question("Choose 1-".concat(candidates.length, ", or q to abort: "))).trim().toLowerCase();
5676
- if (trimmed === "q" || trimmed === "quit") throw new Error("Aborted.");
5673
+ if (trimmed === "q" || trimmed === "quit") throw new Error(
5674
+ "Aborted."
5675
+ );
5677
5676
  const selected = Number.parseInt(trimmed, 10);
5678
5677
  if (Number.isInteger(selected) && selected >= 1 && selected <= candidates.length) {
5679
5678
  const candidate = candidates[selected - 1];
@@ -5698,13 +5697,14 @@ var out = __name2((data) => {
5698
5697
  const resolvedContentType = attachmentContentTypeForFileName(fileName);
5699
5698
  if (resolvedContentType === "image/webp") throw new Error("Unsupported QuickBooks bill attachment type: ".concat(fileName, ". Use PDF, GIF, JPEG, or PNG."));
5700
5699
  return resolvedContentType;
5701
- }, "billAttachmentContentTypeForFileName"), PAYMENT_PROOF_MAX_SIZE = 20 * 1024 * 1024, QUOTATION_ATTACHMENT_MAX_SIZE = 20 * 1024 * 1024, quotationAttachmentContentTypeForFileName = __name2((fileName) => {
5702
- const resolvedContentType = contentTypeHeaderForFileName(
5703
- fileName
5704
- );
5705
- if (resolvedContentType === "application/pdf" || resolvedContentType === "image/jpeg" || resolvedContentType === "image/png") return resolvedContentType;
5706
- throw new Error("Unsupported quotation attachment type: ".concat(fileName, ". Use PDF, JPEG, or PNG."));
5707
- }, "quotationAttachmentContentTypeForFileName"), LOCKED_BUDGET_STATUSES_REQUIRING_CONFIRMATION = /* @__PURE__ */ new Set([BudgetStatus2.ESTIMATE_CREATED, BudgetStatus2.ESTIMATE_SENT, BudgetStatus2.ESTIMATE_ACCEPTED, BudgetStatus2.ESTIMATE_REJECTED, BudgetStatus2.ESTIMATE_CLOSED]), lockedBudgetStatusLabels = { ESTIMATE_CREATED: "Estimate Created", ESTIMATE_SENT: "Estimate Sent", ESTIMATE_ACCEPTED: "Estimate Accepted", ESTIMATE_REJECTED: "Estimate Rejected", ESTIMATE_CLOSED: "Estimate Closed" }, lockedBudgetStatusLabel = __name2((status) => status in lockedBudgetStatusLabels ? lockedBudgetStatusLabels[status] : status, "lockedBudgetStatusLabel"), buildSensitiveWorkflowPreview = __name2(({ action, entity, details }) => {
5700
+ }, "billAttachmentContentTypeForFileName"), PAYMENT_PROOF_MAX_SIZE = 20 * 1024 * 1024, QUOTATION_ATTACHMENT_MAX_SIZE = 20 * 1024 * 1024, quotationAttachmentContentTypeForFileName = __name2(
5701
+ (fileName) => {
5702
+ const resolvedContentType = contentTypeHeaderForFileName(fileName);
5703
+ if (resolvedContentType === "application/pdf" || resolvedContentType === "image/jpeg" || resolvedContentType === "image/png") return resolvedContentType;
5704
+ throw new Error("Unsupported quotation attachment type: ".concat(fileName, ". Use PDF, JPEG, or PNG."));
5705
+ },
5706
+ "quotationAttachmentContentTypeForFileName"
5707
+ ), LOCKED_BUDGET_STATUSES_REQUIRING_CONFIRMATION = /* @__PURE__ */ new Set([BudgetStatus2.ESTIMATE_CREATED, BudgetStatus2.ESTIMATE_SENT, BudgetStatus2.ESTIMATE_ACCEPTED, BudgetStatus2.ESTIMATE_REJECTED, BudgetStatus2.ESTIMATE_CLOSED]), lockedBudgetStatusLabels = { ESTIMATE_CREATED: "Estimate Created", ESTIMATE_SENT: "Estimate Sent", ESTIMATE_ACCEPTED: "Estimate Accepted", ESTIMATE_REJECTED: "Estimate Rejected", ESTIMATE_CLOSED: "Estimate Closed" }, lockedBudgetStatusLabel = __name2((status) => status in lockedBudgetStatusLabels ? lockedBudgetStatusLabels[status] : status, "lockedBudgetStatusLabel"), buildSensitiveWorkflowPreview = __name2(({ action, entity, details }) => {
5708
5708
  const effects = details ?? "may change workflow state or send notifications";
5709
5709
  return ["Budget Builder workflow preview", "Action: ".concat(action), "Target: ".concat(entity), "Effects: ".concat(effects)].join("\n");
5710
5710
  }, "buildSensitiveWorkflowPreview"), assertSensitiveWorkflowConfirmed = __name2(async (input) => {
@@ -5745,9 +5745,7 @@ var out = __name2((data) => {
5745
5745
  return await api2.project.updateProject.mutate(input);
5746
5746
  } catch (error2) {
5747
5747
  if (input.confirmEstimateInvalidation === !0 || !(error2 instanceof Error) || !error2.message.startsWith("This project change affects")) throw error2;
5748
- return await assertSensitiveWorkflowConfirmed(
5749
- { action: "Update project and reject existing estimates", entity: "project ".concat(input.id), details: error2.message }
5750
- ), api2.project.updateProject.mutate({ ...input, confirmEstimateInvalidation: !0 });
5748
+ return await assertSensitiveWorkflowConfirmed({ action: "Update project and reject existing estimates", entity: "project ".concat(input.id), details: error2.message }), api2.project.updateProject.mutate({ ...input, confirmEstimateInvalidation: !0 });
5751
5749
  }
5752
5750
  }, "updateProjectWithEstimateInvalidationConfirmation"), listBudgets = __name2(async (input) => {
5753
5751
  out(await api2.budget.getAllBudgets.query(input));
@@ -5760,9 +5758,7 @@ async function getBudget(id, opts) {
5760
5758
  }
5761
5759
  __name(getBudget, "getBudget"), __name2(getBudget, "getBudget");
5762
5760
  async function updateBudgetStatus(budgetId, status, opts) {
5763
- await assertSensitiveWorkflowConfirmed({ action: "Update budget status", entity: "budget ".concat(budgetId), details: "to ".concat(
5764
- status
5765
- ) }), await confirmLockedBudgetChangeByBudgetId(budgetId, "Update budget status");
5761
+ await assertSensitiveWorkflowConfirmed({ action: "Update budget status", entity: "budget ".concat(budgetId), details: "to ".concat(status) }), await confirmLockedBudgetChangeByBudgetId(budgetId, "Update budget status");
5766
5762
  const result = await api2.budget.updateBudgetStatus.mutate({ id: budgetId, status, ...opts?.projectManagerId !== void 0 && { projectManagerId: opts.projectManagerId }, ...opts?.markProjectWon !== void 0 && { markProjectWon: opts.markProjectWon }, ...opts?.projectStatusOnCommercialRejection !== void 0 && { projectStatusOnCommercialRejection: opts.projectStatusOnCommercialRejection }, ...opts?.projectInvoiceSettings !== void 0 && { projectInvoiceSettings: opts.projectInvoiceSettings } });
5767
5763
  out({ ...result, invoiceSetup: result.newStatus === BudgetStatus2.ESTIMATE_ACCEPTED && result.hasQuickbooksEstimate ? invoiceSplitSetupNextAction(budgetId) : null });
5768
5764
  }
@@ -5781,12 +5777,9 @@ var assertBudgetActionReadiness = __name2(async ({ budgetId, requireQuickbooksPr
5781
5777
  }
5782
5778
  }, "runBudgetPreflight"), listBills = __name2(async (input) => {
5783
5779
  out(await api2.bill.getAll.query({ ...input, statuses: billStatusesForApi(input.statuses), search: input.search?.trim() || void 0, createdByIds: input.createdByIds?.length ? input.createdByIds : void 0 }));
5784
- }, "listBills"), countBills = __name2(
5785
- async (input) => {
5786
- out(await api2.bill.getCounts.query({ ...input, statuses: billStatusesForApi(input.statuses), search: input.search?.trim() || void 0, createdByIds: input.createdByIds?.length ? input.createdByIds : void 0 }));
5787
- },
5788
- "countBills"
5789
- );
5780
+ }, "listBills"), countBills = __name2(async (input) => {
5781
+ out(await api2.bill.getCounts.query({ ...input, statuses: billStatusesForApi(input.statuses), search: input.search?.trim() || void 0, createdByIds: input.createdByIds?.length ? input.createdByIds : void 0 }));
5782
+ }, "countBills");
5790
5783
  async function approveBill(billId, overBudgetOverrideReason) {
5791
5784
  await assertSensitiveWorkflowConfirmed({ action: "Approve bill", entity: "bill ".concat(billId), details: "and send requester reply email" });
5792
5785
  const approval = (await getAllPendingApprovals()).filter((n) => isPendingRequest(n) && n.type === BILL && (n.billId === billId || n.bill?.id === billId))[0];
@@ -5801,7 +5794,9 @@ async function approveBill(billId, overBudgetOverrideReason) {
5801
5794
  const delivery = result.emailDelivery;
5802
5795
  email2 = createApprovalEmailDeliveryReport(delivery);
5803
5796
  } catch (error2) {
5804
- email2 = createApprovalEmailDeliveryFailure(error2 instanceof Error ? error2.message : String(error2));
5797
+ email2 = createApprovalEmailDeliveryFailure(
5798
+ error2 instanceof Error ? error2.message : String(error2)
5799
+ );
5805
5800
  }
5806
5801
  out({ ...result, email: email2 });
5807
5802
  }
@@ -5827,9 +5822,7 @@ async function createBillApproval(billId) {
5827
5822
  if (approvalIds.length === 0) email2 = createApprovalEmailDeliveryFailure("No approval ids returned");
5828
5823
  else try {
5829
5824
  const delivery = result.emailDelivery;
5830
- email2 = createApprovalEmailDeliveryReport(
5831
- delivery
5832
- );
5825
+ email2 = createApprovalEmailDeliveryReport(delivery);
5833
5826
  } catch (error2) {
5834
5827
  email2 = createApprovalEmailDeliveryFailure(error2 instanceof Error ? error2.message : String(error2));
5835
5828
  }
@@ -5846,10 +5839,7 @@ var validateBillStatusUpdateOptions = __name2((opts) => {
5846
5839
  if (cleanup) try {
5847
5840
  await cleanup();
5848
5841
  } catch (cleanupError) {
5849
- throw new AggregateError(
5850
- [error2, cleanupError],
5851
- "Bill status update failed and its staged payment proof could not be cleaned up."
5852
- );
5842
+ throw new AggregateError([error2, cleanupError], "Bill status update failed and its staged payment proof could not be cleaned up.");
5853
5843
  }
5854
5844
  throw error2;
5855
5845
  }, "rethrowAfterStagedPaymentProofCleanup"), stageBillPaymentProof = __name2(async (projectId, filePath) => {
@@ -5889,7 +5879,10 @@ var listExternalBillPaymentAccounts = __name2(async () => {
5889
5879
  }, "listExternalBillPaymentAccounts"), refreshExternalBillPaymentAccounts = __name2(async () => {
5890
5880
  await confirmCurrentCommand({ action: "refresh QuickBooks payment accounts", target: "the cached external payment-account list", effects: ["state-change"], details: "Queue a read of QuickBooks bank and credit-card accounts; nothing is written to QuickBooks." }), out(await api2.bill.refreshExternalPaymentAccounts.mutate());
5891
5881
  }, "refreshExternalBillPaymentAccounts"), recordExternalBillPayment = __name2(async (opts) => {
5892
- if (!opts.paymentReference.trim() || !opts.paymentAccount.trim() || !new __cliRegExp("^\\d{4}-\\d{2}-\\d{2}$", "").test(opts.paymentDate) || new Date("".concat(opts.paymentDate, "T00:00:00Z")).toISOString().slice(0, 10) !== opts.paymentDate) throw new Error("Supply --paymentReference, --paymentDate YYYY-MM-DD, and --paymentAccount <QBO account ID>.");
5882
+ if (!opts.paymentReference.trim() || !opts.paymentAccount.trim() || !new __cliRegExp(
5883
+ "^\\d{4}-\\d{2}-\\d{2}$",
5884
+ ""
5885
+ ).test(opts.paymentDate) || new Date("".concat(opts.paymentDate, "T00:00:00Z")).toISOString().slice(0, 10) !== opts.paymentDate) throw new Error("Supply --paymentReference, --paymentDate YYYY-MM-DD, and --paymentAccount <QBO account ID>.");
5893
5886
  await assertSensitiveWorkflowConfirmed({ action: "Record external payment (no email)", entity: "bill ".concat(opts.id), details: "already paid on ".concat(opts.paymentDate, "; reference ").concat(opts.paymentReference, "; QBO account ").concat(opts.paymentAccount, ". No money is transferred.") });
5894
5887
  const bill = await api2.bill.getPayment.query({ id: opts.id }), proof = !bill.externalPayment && opts.paymentProofPath ? await stageBillPaymentProof(bill.projectId, opts.paymentProofPath) : void 0;
5895
5888
  try {
@@ -5954,15 +5947,12 @@ var uploadSingleBillAttachmentFromPath = __name2(async (billId, filePath, type =
5954
5947
  async function uploadBillAttachmentsFromPaths(billId, filePaths, type = AttachmentType.BILL) {
5955
5948
  if (filePaths.length === 0) throw new Error("At least one bill attachment file path is required");
5956
5949
  const results = [];
5957
- for (const filePath of filePaths) results.push(await uploadSingleBillAttachmentFromPath(billId, filePath, type));
5958
- out({
5959
- success: !0,
5950
+ for (const filePath of filePaths) results.push(await uploadSingleBillAttachmentFromPath(
5960
5951
  billId,
5961
- type,
5962
- count: results.length,
5963
- attachments: results.map((result) => result.attachment),
5964
- results
5965
- });
5952
+ filePath,
5953
+ type
5954
+ ));
5955
+ out({ success: !0, billId, type, count: results.length, attachments: results.map((result) => result.attachment), results });
5966
5956
  }
5967
5957
  __name(uploadBillAttachmentsFromPaths, "uploadBillAttachmentsFromPaths"), __name2(uploadBillAttachmentsFromPaths, "uploadBillAttachmentsFromPaths");
5968
5958
  async function uploadBillDocumentsFromPaths({ billId, invoicePaths = [], paymentProofPaths = [] }) {
@@ -5971,12 +5961,12 @@ async function uploadBillDocumentsFromPaths({ billId, invoicePaths = [], payment
5971
5961
  for (const filePath of invoicePaths) invoiceResults.push(await uploadSingleBillAttachmentFromPath(billId, filePath, AttachmentType.BILL));
5972
5962
  const paymentProofResults = [];
5973
5963
  for (const filePath of paymentProofPaths) paymentProofResults.push(await uploadSingleBillAttachmentFromPath(billId, filePath, AttachmentType.BILL_PAYMENT_PROOF));
5974
- out({ success: !0, billId, count: invoiceResults.length + paymentProofResults.length, invoiceAttachments: invoiceResults.map((result) => result.attachment), paymentProofAttachments: paymentProofResults.map((result) => result.attachment), results: [...invoiceResults, ...paymentProofResults] });
5964
+ out({ success: !0, billId, count: invoiceResults.length + paymentProofResults.length, invoiceAttachments: invoiceResults.map((result) => result.attachment), paymentProofAttachments: paymentProofResults.map((result) => result.attachment), results: [
5965
+ ...invoiceResults,
5966
+ ...paymentProofResults
5967
+ ] });
5975
5968
  }
5976
- __name(uploadBillDocumentsFromPaths, "uploadBillDocumentsFromPaths"), __name2(
5977
- uploadBillDocumentsFromPaths,
5978
- "uploadBillDocumentsFromPaths"
5979
- );
5969
+ __name(uploadBillDocumentsFromPaths, "uploadBillDocumentsFromPaths"), __name2(uploadBillDocumentsFromPaths, "uploadBillDocumentsFromPaths");
5980
5970
  async function uploadQuotationAttachmentFromPath(projectId, filePath) {
5981
5971
  const buf = await readFile2(filePath), fileName = basename(filePath);
5982
5972
  if (buf.byteLength > QUOTATION_ATTACHMENT_MAX_SIZE) throw new Error("Quotation attachment must be 20MB or smaller.");
@@ -5993,25 +5983,23 @@ async function uploadBudgetAttachmentFromPath(budgetId, filePath) {
5993
5983
  await confirmLockedBudgetChangeByBudgetId(budgetId, "Upload budget attachment");
5994
5984
  const buf = await readFile2(filePath), fileName = basename(filePath), size = buf.byteLength, attachmentContentType = attachmentContentTypeForFileName(fileName), { uploadUrl, key } = await api2.attachment.requestBudgetAttachmentUpload.mutate({ budgetId, contentType: attachmentContentType, fileName, size }), res = await fetch(uploadUrl, { method: "PUT", body: buf, headers: { "Content-Type": attachmentContentType } });
5995
5985
  if (!res.ok) throw new Error("S3 upload failed: HTTP ".concat(res.status, " ").concat((await res.text()).slice(0, 500)));
5996
- const confirmed = await api2.attachment.confirmBudgetAttachment.mutate({ budgetId, key, name: fileName, size });
5986
+ const confirmed = await api2.attachment.confirmBudgetAttachment.mutate(
5987
+ { budgetId, key, name: fileName, size }
5988
+ );
5997
5989
  out(confirmed);
5998
5990
  }
5999
- __name(uploadBudgetAttachmentFromPath, "uploadBudgetAttachmentFromPath"), __name2(
6000
- uploadBudgetAttachmentFromPath,
6001
- "uploadBudgetAttachmentFromPath"
6002
- );
5991
+ __name(uploadBudgetAttachmentFromPath, "uploadBudgetAttachmentFromPath"), __name2(uploadBudgetAttachmentFromPath, "uploadBudgetAttachmentFromPath");
6003
5992
  async function uploadBudgetWinProofFromPath(budgetId, filePath, opts) {
6004
5993
  await assertSensitiveWorkflowConfirmed({ action: "Mark budget won", entity: "budget ".concat(budgetId), details: "by uploading proof and setting status to ESTIMATE_ACCEPTED" }), await confirmLockedBudgetChangeByBudgetId(budgetId, "Mark budget won");
6005
5994
  const buf = await readFile2(filePath), fileName = basename(filePath), size = buf.byteLength, attachmentContentType = attachmentContentTypeForFileName(fileName), { uploadUrl, key } = await api2.attachment.requestBudgetWinProofUpload.mutate({ budgetId, contentType: attachmentContentType, fileName, size }), res = await fetch(uploadUrl, { method: "PUT", body: buf, headers: { "Content-Type": attachmentContentType } });
6006
5995
  if (!res.ok) throw new Error("S3 upload failed: HTTP ".concat(res.status, " ").concat((await res.text()).slice(0, 500)));
6007
- await api2.attachment.confirmBudgetWinProofAttachment.mutate({ budgetId, key, name: fileName, size });
6008
- const result = await api2.budget.updateBudgetStatus.mutate({
6009
- id: budgetId,
6010
- status: BudgetStatus2.ESTIMATE_ACCEPTED,
6011
- ...opts?.projectManagerId !== void 0 && { projectManagerId: opts.projectManagerId },
6012
- ...opts?.markProjectWon !== void 0 && { markProjectWon: opts.markProjectWon },
6013
- ...opts?.projectInvoiceSettings !== void 0 && { projectInvoiceSettings: opts.projectInvoiceSettings }
5996
+ await api2.attachment.confirmBudgetWinProofAttachment.mutate({
5997
+ budgetId,
5998
+ key,
5999
+ name: fileName,
6000
+ size
6014
6001
  });
6002
+ const result = await api2.budget.updateBudgetStatus.mutate({ id: budgetId, status: BudgetStatus2.ESTIMATE_ACCEPTED, ...opts?.projectManagerId !== void 0 && { projectManagerId: opts.projectManagerId }, ...opts?.markProjectWon !== void 0 && { markProjectWon: opts.markProjectWon }, ...opts?.projectInvoiceSettings !== void 0 && { projectInvoiceSettings: opts.projectInvoiceSettings } });
6015
6003
  out({ ...result, invoiceSetup: result.hasQuickbooksEstimate ? invoiceSplitSetupNextAction(budgetId) : null });
6016
6004
  }
6017
6005
  __name(uploadBudgetWinProofFromPath, "uploadBudgetWinProofFromPath"), __name2(uploadBudgetWinProofFromPath, "uploadBudgetWinProofFromPath");
@@ -6025,10 +6013,7 @@ async function getBillDetails(id) {
6025
6013
  }
6026
6014
  __name(getBillDetails, "getBillDetails"), __name2(getBillDetails, "getBillDetails");
6027
6015
  async function getBudgetItemsOnly(budgetId, opts) {
6028
- const includeInactive = opts?.includeInactive ?? !1, [items, totals] = await Promise.all([api2.budget.getBudgetItems.query({ budgetId, includeInactive }), api2.budget.getBudgetItemTotals.query({
6029
- budgetId,
6030
- includeInactive
6031
- })]);
6016
+ const includeInactive = opts?.includeInactive ?? !1, [items, totals] = await Promise.all([api2.budget.getBudgetItems.query({ budgetId, includeInactive }), api2.budget.getBudgetItemTotals.query({ budgetId, includeInactive })]);
6032
6017
  out({ ...items, totals });
6033
6018
  }
6034
6019
  __name(getBudgetItemsOnly, "getBudgetItemsOnly"), __name2(getBudgetItemsOnly, "getBudgetItemsOnly");
@@ -6045,7 +6030,10 @@ async function updateBudgetItem(input) {
6045
6030
  }
6046
6031
  __name(updateBudgetItem, "updateBudgetItem"), __name2(updateBudgetItem, "updateBudgetItem");
6047
6032
  async function removeBudgetItem(budgetItemId) {
6048
- await confirmLockedBudgetChangeByBudgetItemId(budgetItemId, "Remove budget item");
6033
+ await confirmLockedBudgetChangeByBudgetItemId(
6034
+ budgetItemId,
6035
+ "Remove budget item"
6036
+ );
6049
6037
  const result = await api2.budgetItem.removeBudgetItem.mutate({ budgetItemId });
6050
6038
  out(result);
6051
6039
  }
@@ -6076,9 +6064,7 @@ async function createBudgetApproval(budgetId, preflight) {
6076
6064
  await assertSensitiveWorkflowConfirmed({ action: "Create budget approval request", entity: "budget ".concat(budgetId), details: "and send approval request emails" }), await confirmLockedBudgetChangeByBudgetId(budgetId, "Create budget approval"), await runBudgetPreflight(budgetId, preflight), await assertBudgetActionReadiness({ budgetId, requireQuickbooksProject: !1, actionLabel: "request approval" });
6077
6065
  const result = await api2.budget.createBudgetApproval.mutate({ budgetId }), approvalIds = (result.results ?? []).map((item) => ({ id: item.id }));
6078
6066
  let email2;
6079
- if (approvalIds.length === 0) email2 = createApprovalEmailDeliveryFailure(
6080
- "No approval ids returned"
6081
- );
6067
+ if (approvalIds.length === 0) email2 = createApprovalEmailDeliveryFailure("No approval ids returned");
6082
6068
  else try {
6083
6069
  const delivery = result.emailDelivery;
6084
6070
  email2 = createApprovalEmailDeliveryReport(delivery);
@@ -6111,14 +6097,14 @@ async function createBudgetFromPayload(raw) {
6111
6097
  try {
6112
6098
  result = await api2.budget.createBudget.mutate(input);
6113
6099
  } catch (error2) {
6114
- throw budgetCreateUncertainError(error2, input) || error2;
6100
+ throw budgetCreateUncertainError(
6101
+ error2,
6102
+ input
6103
+ ) || error2;
6115
6104
  }
6116
6105
  out(result);
6117
6106
  }
6118
- __name(createBudgetFromPayload, "createBudgetFromPayload"), __name2(
6119
- createBudgetFromPayload,
6120
- "createBudgetFromPayload"
6121
- );
6107
+ __name(createBudgetFromPayload, "createBudgetFromPayload"), __name2(createBudgetFromPayload, "createBudgetFromPayload");
6122
6108
  async function updateBudgetFromPayload(raw) {
6123
6109
  const input = parseUpdateBudgetPayload(raw);
6124
6110
  await confirmLockedBudgetChangeByBudgetId(input.id, "Update budget");
@@ -6188,9 +6174,7 @@ var deleteBudgetDiscount = __name2(async (budgetId) => {
6188
6174
  const result = await api2.budget.deleteBudgetDiscount.mutate({ budgetId });
6189
6175
  out(result);
6190
6176
  }, "deleteBudgetDiscount"), deleteBudgetCommission = __name2(async (budgetId) => {
6191
- await assertSensitiveWorkflowConfirmed(
6192
- { action: "Remove budget commission", entity: "budget ".concat(budgetId), details: "and return the budget to DRAFT" }
6193
- );
6177
+ await assertSensitiveWorkflowConfirmed({ action: "Remove budget commission", entity: "budget ".concat(budgetId), details: "and return the budget to DRAFT" });
6194
6178
  const result = await api2.budget.deleteBudgetCommission.mutate({ budgetId });
6195
6179
  out(result);
6196
6180
  }, "deleteBudgetCommission"), setBudgetItemsNotUtilized = __name2(async (budgetItemIds, notUtilized) => {
@@ -6280,7 +6264,10 @@ async function getQuotationDetails(id) {
6280
6264
  const result = await api2.quotation.getById.query({ id });
6281
6265
  out(result);
6282
6266
  }
6283
- __name(getQuotationDetails, "getQuotationDetails"), __name2(getQuotationDetails, "getQuotationDetails");
6267
+ __name(getQuotationDetails, "getQuotationDetails"), __name2(
6268
+ getQuotationDetails,
6269
+ "getQuotationDetails"
6270
+ );
6284
6271
  var getQuotationLineItems = __name2(async (input) => {
6285
6272
  out(await api2.quotation.getLineItems.query(input));
6286
6273
  }, "getQuotationLineItems");
@@ -6301,7 +6288,10 @@ async function submitQuotation(id, overBudgetOverrideReason) {
6301
6288
  const result = await api2.quotation.submitForApproval.mutate({ id, overBudgetOverrideReason });
6302
6289
  out(result);
6303
6290
  }
6304
- __name(submitQuotation, "submitQuotation"), __name2(submitQuotation, "submitQuotation");
6291
+ __name(submitQuotation, "submitQuotation"), __name2(
6292
+ submitQuotation,
6293
+ "submitQuotation"
6294
+ );
6305
6295
  async function downloadQuotationPdf(id, fileRole) {
6306
6296
  const result = await api2.quotation.getSignedDownloadUrl.query({ id, fileRole });
6307
6297
  out(result);
@@ -6336,23 +6326,20 @@ var checkCustomerInvoiceReadiness = __name2(async (budgetId) => {
6336
6326
  out(await api2.customerInvoice.getHistory.query(input));
6337
6327
  }, "getCustomerInvoiceHistory"), getCustomerInvoicePayments = __name2(async (invoiceId) => {
6338
6328
  out(await api2.customerInvoice.getPayments.query({ invoiceId }));
6339
- }, "getCustomerInvoicePayments"), getCustomerInvoiceEmailContext = __name2(
6340
- async (batchId) => {
6341
- const result = await api2.customerInvoice.getInvoiceEmailContext.query({ batchId });
6342
- out(result);
6343
- },
6344
- "getCustomerInvoiceEmailContext"
6345
- ), previewQboCustomerInvoice = __name2(async (input) => {
6329
+ }, "getCustomerInvoicePayments"), getCustomerInvoiceEmailContext = __name2(async (batchId) => {
6330
+ const result = await api2.customerInvoice.getInvoiceEmailContext.query({ batchId });
6331
+ out(result);
6332
+ }, "getCustomerInvoiceEmailContext"), previewQboCustomerInvoice = __name2(async (input) => {
6346
6333
  const result = await api2.customerInvoice.previewExistingInvoice.mutate(input);
6347
6334
  out(result);
6348
6335
  }, "previewQboCustomerInvoice"), importQboCustomerInvoice = __name2(async (input) => {
6349
6336
  await confirmCurrentCommand({ action: "Link existing QuickBooks invoice", target: "QuickBooks invoice ".concat(input.qboInvoiceId, " to budget ").concat(input.budgetId), details: "records the reviewed invoice in Budget Builder only; QuickBooks access is read-only; preserves original evidence and revalidates the preview token".concat(input.confirmEstimateLineage ? "; you confirm this invoice, which has no QuickBooks estimate link, belongs to this budget's estimate" : "") });
6350
- const result = await api2.customerInvoice.linkExistingInvoice.mutate(input);
6337
+ const result = await api2.customerInvoice.linkExistingInvoice.mutate(
6338
+ input
6339
+ );
6351
6340
  out(result);
6352
6341
  }, "importQboCustomerInvoice"), createCustomerInvoice = __name2(async (raw) => {
6353
- const input = parseCreateCustomerInvoicePayload(
6354
- raw
6355
- ), readiness = await api2.customerInvoice.getInvoiceReadiness.query({ budgetId: input.budgetId, includePreview: !0 });
6342
+ const input = parseCreateCustomerInvoicePayload(raw), readiness = await api2.customerInvoice.getInvoiceReadiness.query({ budgetId: input.budgetId, includePreview: !0 });
6356
6343
  if (!readiness.ready) throw new CliRuntimeError("VALIDATION", readiness.issues.join("; ") || "Invoice is not ready for creation.");
6357
6344
  await assertSensitiveWorkflowConfirmed({ action: "Create customer invoice", entity: "budget ".concat(input.budgetId), details: "queues ".concat(input.splits.length, " invoice(s) for creation in QuickBooks from the budget's remaining uninvoiced balance: ").concat(input.splits.map((split) => "".concat(split.label, " (").concat(split.percentage, "% of the estimate), due ").concat(new Date(split.dueDate).toISOString().slice(0, 10))).join("; "), ". Admin creation is auto-approved; other creators request approval. No customer email is sent.") });
6358
6345
  const result = await api2.customerInvoice.createInvoiceBatch.mutate(input);
@@ -6364,7 +6351,9 @@ var checkCustomerInvoiceReadiness = __name2(async (budgetId) => {
6364
6351
  const result = await api2.customerInvoice.discardCreatingInvoiceBatch.mutate({ batchId });
6365
6352
  out(result);
6366
6353
  }, "discardCreatingCustomerInvoice"), deleteCustomerInvoice = __name2(async (batchId) => {
6367
- await assertSensitiveWorkflowConfirmed({ action: "Delete customer invoice", entity: "invoice batch ".concat(batchId), details: "queues deletion of its invoices in QuickBooks; the local batch is removed once QuickBooks confirms; paid invoices are blocked until their QBO payments are reversed; removing approved coverage may reopen the estimate" });
6354
+ await assertSensitiveWorkflowConfirmed(
6355
+ { action: "Delete customer invoice", entity: "invoice batch ".concat(batchId), details: "queues deletion of its invoices in QuickBooks; the local batch is removed once QuickBooks confirms; paid invoices are blocked until their QBO payments are reversed; removing approved coverage may reopen the estimate" }
6356
+ );
6368
6357
  const result = await api2.customerInvoice.deleteInvoiceBatch.mutate({ batchId });
6369
6358
  out(result);
6370
6359
  }, "deleteCustomerInvoice"), voidCustomerInvoice = __name2(async (batchId) => {
@@ -6410,13 +6399,10 @@ async function updateBillFromPayload(raw) {
6410
6399
  out(result);
6411
6400
  }
6412
6401
  __name(updateBillFromPayload, "updateBillFromPayload"), __name2(updateBillFromPayload, "updateBillFromPayload");
6413
- var validateBillSelectionFromPayload = __name2(
6414
- async (raw, quotationFlags) => {
6415
- const input = parseValidateBillSelectionPayload(raw, quotationFlags), result = await api2.bill.validateSelection.mutate(input);
6416
- out(result);
6417
- },
6418
- "validateBillSelectionFromPayload"
6419
- ), linkBillQuotations = __name2(async (billId, raw) => {
6402
+ var validateBillSelectionFromPayload = __name2(async (raw, quotationFlags) => {
6403
+ const input = parseValidateBillSelectionPayload(raw, quotationFlags), result = await api2.bill.validateSelection.mutate(input);
6404
+ out(result);
6405
+ }, "validateBillSelectionFromPayload"), linkBillQuotations = __name2(async (billId, raw) => {
6420
6406
  const input = parseLinkBillQuotationsPayload(billId, raw), result = await api2.bill.linkQuotations.mutate(input);
6421
6407
  out(result);
6422
6408
  }, "linkBillQuotations"), updateBillPaymentEvidenceFromPayload = __name2(async (raw) => {
@@ -6430,7 +6416,9 @@ async function deleteBillById(id) {
6430
6416
  __name(deleteBillById, "deleteBillById"), __name2(deleteBillById, "deleteBillById");
6431
6417
  async function createSupplierFromPayload(raw) {
6432
6418
  const input = parseSupplierCreatePayload(raw);
6433
- await assertSensitiveWorkflowConfirmed({ action: "Create supplier and request approval if required", entity: "supplier ".concat(input.name), details: "creates the supplier first; pending-approval suppliers also request approval and send emails" });
6419
+ await assertSensitiveWorkflowConfirmed(
6420
+ { action: "Create supplier and request approval if required", entity: "supplier ".concat(input.name), details: "creates the supplier first; pending-approval suppliers also request approval and send emails" }
6421
+ );
6434
6422
  let created;
6435
6423
  try {
6436
6424
  created = await api2.supplier.createSupplier.mutate(input);
@@ -6458,7 +6446,11 @@ async function createSupplierFromPayload(raw) {
6458
6446
  } catch (error2) {
6459
6447
  emailResult = createApprovalEmailDeliveryFailure(error2 instanceof Error ? error2.message : String(error2));
6460
6448
  }
6461
- out({ ...created, supplierApproval: { requested: !0, approvalCount: approvalIds.length, email: emailResult } });
6449
+ out({ ...created, supplierApproval: {
6450
+ requested: !0,
6451
+ approvalCount: approvalIds.length,
6452
+ email: emailResult
6453
+ } });
6462
6454
  }
6463
6455
  __name(createSupplierFromPayload, "createSupplierFromPayload"), __name2(createSupplierFromPayload, "createSupplierFromPayload");
6464
6456
  async function updateSupplierFromPayload(raw) {
@@ -6479,13 +6471,12 @@ async function updateItemFromPayload(raw) {
6479
6471
  }
6480
6472
  __name(updateItemFromPayload, "updateItemFromPayload"), __name2(updateItemFromPayload, "updateItemFromPayload");
6481
6473
  async function createContactPersonFromPayload(raw) {
6482
- const input = parseContactCreatePayload(raw), result = await api2.contactPerson.createContactPerson.mutate(input);
6474
+ const input = parseContactCreatePayload(
6475
+ raw
6476
+ ), result = await api2.contactPerson.createContactPerson.mutate(input);
6483
6477
  out(result);
6484
6478
  }
6485
- __name(createContactPersonFromPayload, "createContactPersonFromPayload"), __name2(
6486
- createContactPersonFromPayload,
6487
- "createContactPersonFromPayload"
6488
- );
6479
+ __name(createContactPersonFromPayload, "createContactPersonFromPayload"), __name2(createContactPersonFromPayload, "createContactPersonFromPayload");
6489
6480
  async function updateContactPersonFromPayload(raw) {
6490
6481
  const input = parseContactUpdatePayload(raw), result = await api2.contactPerson.updateContactPerson.mutate(input);
6491
6482
  out(result);
@@ -6521,10 +6512,9 @@ async function approveBudget(budgetId) {
6521
6512
  }
6522
6513
  __name(approveBudget, "approveBudget"), __name2(approveBudget, "approveBudget");
6523
6514
  async function rejectBudget(budgetId, reason) {
6524
- await assertSensitiveWorkflowConfirmed({ action: "Reject budget", entity: "budget ".concat(budgetId), details: 'with reason "'.concat(
6525
- reason,
6526
- '" and send requester reply email'
6527
- ) });
6515
+ await assertSensitiveWorkflowConfirmed(
6516
+ { action: "Reject budget", entity: "budget ".concat(budgetId), details: 'with reason "'.concat(reason, '" and send requester reply email') }
6517
+ );
6528
6518
  const approval = (await getAllPendingApprovals()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.BUDGET && (n.budgetId === budgetId || n.budget?.id === budgetId))[0];
6529
6519
  if (!approval) throw new Error("No pending budget approval found for this budget and approver.");
6530
6520
  const result = await api2.budget.updateBudgetApproval.mutate({ budgetApprovalId: approval.id, status: ExtendedApprovalStatus.REJECTED, rejectionReason: reason });
@@ -6562,11 +6552,7 @@ async function approveSupplier(supplierId) {
6562
6552
  await assertSensitiveWorkflowConfirmed({ action: "Re-approve supplier", entity: "supplier ".concat(supplierId), effects: ["state-change", "external-write"], details: supplier.active ? "and queue its QuickBooks vendor sync (it is usable once QuickBooks confirms); append a new approval and retain earlier history; no requester reply email is sent" : "and queue its QuickBooks vendor sync; append a new approval and retain earlier history; it remains archived and no requester reply email is sent" }), out(await api2.supplier.reapproveSupplier.mutate({ supplierId }));
6563
6553
  return;
6564
6554
  }
6565
- await assertSensitiveWorkflowConfirmed({
6566
- action: "Approve supplier",
6567
- entity: "supplier ".concat(supplierId),
6568
- details: "and send requester reply email"
6569
- });
6555
+ await assertSensitiveWorkflowConfirmed({ action: "Approve supplier", entity: "supplier ".concat(supplierId), details: "and send requester reply email" });
6570
6556
  const approval = (await getAllPendingApprovals()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.SUPPLIER && (n.supplierId === supplierId || n.supplier?.id === supplierId))[0];
6571
6557
  if (!approval) throw new Error("No pending supplier approval found.");
6572
6558
  const result = await api2.supplier.updateSupplierApproval.mutate({ supplierApprovalId: approval.id, status: ExtendedApprovalStatus.APPROVED });
@@ -6581,7 +6567,11 @@ async function approveSupplier(supplierId) {
6581
6567
  }
6582
6568
  __name(approveSupplier, "approveSupplier"), __name2(approveSupplier, "approveSupplier");
6583
6569
  async function rejectSupplier(supplierId, reason) {
6584
- await assertSensitiveWorkflowConfirmed({ action: "Reject supplier", entity: "supplier ".concat(supplierId), details: 'with reason "'.concat(reason, '" and send requester reply email') });
6570
+ await assertSensitiveWorkflowConfirmed({
6571
+ action: "Reject supplier",
6572
+ entity: "supplier ".concat(supplierId),
6573
+ details: 'with reason "'.concat(reason, '" and send requester reply email')
6574
+ });
6585
6575
  const approval = (await getAllPendingApprovals()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.SUPPLIER && (n.supplierId === supplierId || n.supplier?.id === supplierId))[0];
6586
6576
  if (!approval) throw new Error("No pending supplier approval found.");
6587
6577
  const result = await api2.supplier.updateSupplierApproval.mutate({ supplierApprovalId: approval.id, status: ExtendedApprovalStatus.REJECTED, rejectionReason: reason });
@@ -6630,12 +6620,13 @@ async function rejectQuotation(quotationId, reason) {
6630
6620
  out(result);
6631
6621
  }
6632
6622
  __name(rejectQuotation, "rejectQuotation"), __name2(rejectQuotation, "rejectQuotation");
6633
- var listCompanies = __name2(async (input) => {
6634
- const result = await api2.company.getCompanies.query(input);
6635
- out(
6636
- result
6637
- );
6638
- }, "listCompanies"), countCompanies = __name2(async (input) => {
6623
+ var listCompanies = __name2(
6624
+ async (input) => {
6625
+ const result = await api2.company.getCompanies.query(input);
6626
+ out(result);
6627
+ },
6628
+ "listCompanies"
6629
+ ), countCompanies = __name2(async (input) => {
6639
6630
  const result = await api2.company.getCompanyCounts.query(input);
6640
6631
  out(result);
6641
6632
  }, "countCompanies");
@@ -6659,12 +6650,9 @@ var searchExistingCompanies = __name2(async (input) => {
6659
6650
  }, "listProjects"), countProjects = __name2(async (input) => {
6660
6651
  const result = await api2.project.getProjectCounts.query(input);
6661
6652
  out(result);
6662
- }, "countProjects"), listProjectHubs = __name2(
6663
- async (input) => {
6664
- out(await api2.project.getAllProjectHubs.query(input));
6665
- },
6666
- "listProjectHubs"
6667
- ), countProjectHubs = __name2(async (input) => {
6653
+ }, "countProjects"), listProjectHubs = __name2(async (input) => {
6654
+ out(await api2.project.getAllProjectHubs.query(input));
6655
+ }, "listProjectHubs"), countProjectHubs = __name2(async (input) => {
6668
6656
  out(await api2.project.getProjectHubCounts.query(input));
6669
6657
  }, "countProjectHubs");
6670
6658
  async function getProject(id) {
@@ -6685,10 +6673,10 @@ var getProjectHubStatus = __name2(async (projectId) => {
6685
6673
  out(result);
6686
6674
  }, "syncProjectHubCommercialDocuments");
6687
6675
  async function createProject(opts) {
6688
- const name = parseQuickBooksName(opts.name), asanaTaskId = await resolveCreateProjectAsanaTaskId({ name, asanaTaskId: opts.asanaTaskId, asanaSearch: opts.asanaSearch }), result = await api2.project.createProject.mutate({ name, description: opts.description, companyId: opts.companyId, contactPersonId: opts.contactPersonId, insideSalesId: opts.insideSalesId, businessDevelopmentId: opts.businessDevelopmentId, projectManagerId: opts.projectManagerId, venue: opts.venue, pax: opts.pax, asanaTaskId, dateRange: { from: new Date(opts.startDate), to: opts.endDate ? new Date(opts.endDate) : void 0 } });
6689
- out(
6690
- result
6691
- );
6676
+ const name = parseQuickBooksName(opts.name), asanaTaskId = await resolveCreateProjectAsanaTaskId({ name, asanaTaskId: opts.asanaTaskId, asanaSearch: opts.asanaSearch }), result = await api2.project.createProject.mutate({ name, description: opts.description, companyId: opts.companyId, contactPersonId: opts.contactPersonId, insideSalesId: opts.insideSalesId, businessDevelopmentId: opts.businessDevelopmentId, projectManagerId: opts.projectManagerId, venue: opts.venue, pax: opts.pax, asanaTaskId, dateRange: { from: new Date(
6677
+ opts.startDate
6678
+ ), to: opts.endDate ? new Date(opts.endDate) : void 0 } });
6679
+ out(result);
6692
6680
  }
6693
6681
  __name(createProject, "createProject"), __name2(createProject, "createProject");
6694
6682
  async function updateProjectStatus(id, status, opts) {
@@ -6704,17 +6692,18 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6704
6692
  await assertSensitiveWorkflowConfirmed({ action: "Reconcile project", entity: "project ".concat(projectId), details: "rerun all reconciliation checks and mark it RECONCILED" });
6705
6693
  const result = await api2.project.reconcile.mutate({ projectId });
6706
6694
  out(result);
6707
- }, "reconcileProject"), completeProject = __name2(
6708
- async (projectId) => {
6709
- await updateProjectStatus(projectId, ProjectStatus2.COMPLETED);
6710
- },
6711
- "completeProject"
6712
- ), importQuickBooksProjectId = __name2(async (projectId, projectUrl) => {
6695
+ }, "reconcileProject"), completeProject = __name2(async (projectId) => {
6696
+ await updateProjectStatus(projectId, ProjectStatus2.COMPLETED);
6697
+ }, "completeProject"), importQuickBooksProjectId = __name2(async (projectId, projectUrl) => {
6713
6698
  const result = await api2.project.importQboProjectId.mutate({ projectId, projectUrl });
6714
6699
  out(result);
6715
6700
  }, "importQuickBooksProjectId"), listWebhookEventTypes = __name2(async () => {
6716
6701
  out(await api2.webhook.listEventTypes.query());
6717
- }, "listWebhookEventTypes"), listWebhookEndpoints = __name2(async () => {
6702
+ }, "listWebhookEventTypes"), listMobilePushDevices = __name2(async () => {
6703
+ out(await api2.mobilePush.listDevices.query({}));
6704
+ }, "listMobilePushDevices"), unregisterMobilePushDevice = __name2(async (sessionId) => {
6705
+ out(await api2.mobilePush.unregisterDevice.mutate({ sessionId }));
6706
+ }, "unregisterMobilePushDevice"), listWebhookEndpoints = __name2(async () => {
6718
6707
  out(await api2.webhook.listEndpoints.query());
6719
6708
  }, "listWebhookEndpoints"), getWebhookEndpoint = __name2(async (id) => {
6720
6709
  out(await api2.webhook.getEndpoint.query({ id }));
@@ -6724,9 +6713,7 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6724
6713
  }, "createWebhookEndpoint"), updateWebhookEndpoint = __name2(async (input) => {
6725
6714
  out(await api2.webhook.updateEndpoint.mutate(input));
6726
6715
  }, "updateWebhookEndpoint"), deleteWebhookEndpoint = __name2(async (id) => {
6727
- await assertSensitiveWorkflowConfirmed(
6728
- { action: "Delete webhook endpoint and its delivery history", entity: "webhook endpoint ".concat(id) }
6729
- ), out(await api2.webhook.deleteEndpoint.mutate({ id }));
6716
+ await assertSensitiveWorkflowConfirmed({ action: "Delete webhook endpoint and its delivery history", entity: "webhook endpoint ".concat(id) }), out(await api2.webhook.deleteEndpoint.mutate({ id }));
6730
6717
  }, "deleteWebhookEndpoint"), rotateWebhookSecret = __name2(async (input) => {
6731
6718
  await assertSensitiveWorkflowConfirmed({ action: "Rotate webhook signing secret", entity: "webhook endpoint ".concat(input.id), details: "previous secrets keep signing for ".concat(input.previousSecretTtlHours ?? 24, "h") });
6732
6719
  const result = await api2.webhook.rotateSecret.mutate(input);
@@ -6737,12 +6724,9 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6737
6724
  out(await api2.webhook.listDeliveries.query(input));
6738
6725
  }, "listWebhookDeliveries"), getWebhookDelivery = __name2(async (deliveryId) => {
6739
6726
  out(await api2.webhook.getDelivery.query({ deliveryId }));
6740
- }, "getWebhookDelivery"), replayWebhookDelivery = __name2(
6741
- async (deliveryId) => {
6742
- out(await api2.webhook.replayDelivery.mutate({ deliveryId }));
6743
- },
6744
- "replayWebhookDelivery"
6745
- ), listIntegrationOperations = __name2(async (input) => {
6727
+ }, "getWebhookDelivery"), replayWebhookDelivery = __name2(async (deliveryId) => {
6728
+ out(await api2.webhook.replayDelivery.mutate({ deliveryId }));
6729
+ }, "replayWebhookDelivery"), listIntegrationOperations = __name2(async (input) => {
6746
6730
  const result = await api2.integration.listOperations.query(input);
6747
6731
  out(result);
6748
6732
  }, "listIntegrationOperations"), getIntegrationOperation = __name2(async (operationId) => {
@@ -6755,16 +6739,17 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6755
6739
  const result = await api2.integration.retryOperation.mutate({ operationId, confirmExternalStateReconciled, outboundEmailResolution, providerMessageId });
6756
6740
  out(result);
6757
6741
  }, "retryIntegrationOperation"), reconcileResourceOperation = __name2(async (operationId) => {
6758
- await assertSensitiveWorkflowConfirmed({ action: "Verify QuickBooks resource outcome", entity: "operation ".concat(operationId), details: "verify the saved receipt or read QuickBooks when the attempt is uncertain, then queue local update/archive/reactivation finalization without repeating the provider mutation" });
6742
+ await assertSensitiveWorkflowConfirmed({
6743
+ action: "Verify QuickBooks resource outcome",
6744
+ entity: "operation ".concat(operationId),
6745
+ details: "verify the saved receipt or read QuickBooks when the attempt is uncertain, then queue local update/archive/reactivation finalization without repeating the provider mutation"
6746
+ });
6759
6747
  const result = await api2.integration.reconcileResourceOperation.mutate({ operationId });
6760
6748
  out(result);
6761
- }, "reconcileResourceOperation"), listInboundSources = __name2(
6762
- async (input) => {
6763
- const result = await api2.inbound.listSources.query(input);
6764
- out(result);
6765
- },
6766
- "listInboundSources"
6767
- ), countInboundSources = __name2(async (input) => {
6749
+ }, "reconcileResourceOperation"), listInboundSources = __name2(async (input) => {
6750
+ const result = await api2.inbound.listSources.query(input);
6751
+ out(result);
6752
+ }, "listInboundSources"), countInboundSources = __name2(async (input) => {
6768
6753
  const result = await api2.inbound.countSources.query(input);
6769
6754
  out(result);
6770
6755
  }, "countInboundSources"), createInboundSource = __name2(async (input) => {
@@ -6790,10 +6775,13 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6790
6775
  }, "saveInboundMappingVersion"), saveInboundAutomationConfig = __name2(async (input) => {
6791
6776
  const result = await api2.inbound.saveAutomationConfig.mutate(input);
6792
6777
  out(result);
6793
- }, "saveInboundAutomationConfig"), updateInboundProcessing = __name2(async (input) => {
6794
- const result = await api2.inbound.updateProcessing.mutate(input);
6795
- out(result);
6796
- }, "updateInboundProcessing");
6778
+ }, "saveInboundAutomationConfig"), updateInboundProcessing = __name2(
6779
+ async (input) => {
6780
+ const result = await api2.inbound.updateProcessing.mutate(input);
6781
+ out(result);
6782
+ },
6783
+ "updateInboundProcessing"
6784
+ );
6797
6785
  async function listContacts(companyId) {
6798
6786
  const contacts = await api2.contactPerson.getContactPersonByCompanyId.query({ companyId });
6799
6787
  out(contacts);
@@ -6817,7 +6805,9 @@ var getItemQuickBooksSyncStatus = __name2(async (itemId) => {
6817
6805
  }, "listItemCategories"), countItemCategories = __name2(async (input) => {
6818
6806
  out(await api2.itemCategory.getCounts.query(input));
6819
6807
  }, "countItemCategories"), getSupplierAnalytics = __name2(async (input) => {
6820
- out(await api2.dashboard.getSupplierTableData.query(input));
6808
+ out(await api2.dashboard.getSupplierTableData.query(
6809
+ input
6810
+ ));
6821
6811
  }, "getSupplierAnalytics"), countSupplierAnalytics = __name2(async (input) => {
6822
6812
  out(await api2.dashboard.getSupplierTableCounts.query(input));
6823
6813
  }, "countSupplierAnalytics");
@@ -6885,9 +6875,12 @@ var getRecentErrors = __name2(async (input) => {
6885
6875
  out(await api2.errorLog.getRecentErrors.query(input));
6886
6876
  }, "getRecentErrors"), getError = __name2(async (errorId) => {
6887
6877
  out(await api2.errorLog.getErrorById.query({ errorId }));
6888
- }, "getError"), countErrors = __name2(async (input) => {
6889
- out(await api2.errorLog.countErrors.query(input));
6890
- }, "countErrors");
6878
+ }, "getError"), countErrors = __name2(
6879
+ async (input) => {
6880
+ out(await api2.errorLog.countErrors.query(input));
6881
+ },
6882
+ "countErrors"
6883
+ );
6891
6884
  async function getErrorMetrics() {
6892
6885
  const result = await api2.errorLog.getErrorMetrics.query({});
6893
6886
  out(result);
@@ -6979,10 +6972,7 @@ __name(parseJsonObjectFlag, "parseJsonObjectFlag"), __name2(parseJsonObjectFlag,
6979
6972
  function parseOptionalNumber(raw, label) {
6980
6973
  if (raw === void 0 || raw === "") return;
6981
6974
  const n = typeof raw == "number" ? raw : Number.parseFloat(String(raw).trim());
6982
- if (!Number.isFinite(n)) throw new CliRuntimeError("VALIDATION", "".concat(
6983
- label,
6984
- " must be a number."
6985
- ));
6975
+ if (!Number.isFinite(n)) throw new CliRuntimeError("VALIDATION", "".concat(label, " must be a number."));
6986
6976
  return n;
6987
6977
  }
6988
6978
  __name(parseOptionalNumber, "parseOptionalNumber"), __name2(parseOptionalNumber, "parseOptionalNumber");
@@ -7002,70 +6992,110 @@ tionId":"<asana-won-id>","asanaLostSectionId":"<asana-lost-id>","googleCalendarI
7002
6992
  const help = payloadHelp[command];
7003
6993
  return help ? ["Payload fields (--payload JSON)", " Required: ".concat(help.required), " Optional: ".concat(help.optional), " Example: bb ".concat(command).concat(command === "link-bill-quotations" ? " <billId>" : command.startsWith("save-inbound-") ? " <sourceId>" : "", " --payload '").concat(help.example, "'"), ""] : [];
7004
6994
  }, "formatPayloadHelp"), globalCommandOptions = [{ name: "--help", description: "Show help for this command." }, { name: "--quiet", description: "Suppress non-error diagnostics." }, { name: "--debug", description: "Emit sanitized diagnostic traces." }, { name: "--api-url", description: "Override the Budget Builder API base URL." }, { name: "--no-browser", description: "Print the authorization URL without opening a browser." }, { name: "--allow-state-change", description: "Allow a Budget Builder state change in non-interactive use." }, { name: "--allow-email", description: "Allow sending email in non-interactive use." }, { name: "--allow-external-write", description: "Allow writes to external systems in non-interactive use." }, { name: "--allow-delete", description: "Allow deleting data in non-interactive use." }, { name: "--allow-financial-write", description: "Allow financial-record changes in non-interactive use." }], mutationPrefixes = ["add-", "approve-", "archive-", "attach-", "cl\
7005
- eanup-", "complete-", "create-", "delete-", "discard-", "import-", "link-", "mark-", "patch-", "reactivate-", "reconcile-", "record-", "refresh-", "reject-", "remove-", "replace-", "rename-", "reorder-", "restore-", "retry-", "revoke-", "save-", "send-", "stage-", "setup-", "submit-", "sync-", "update-", "use-existing-", "upload-", "void-"], emailTargets = /* @__PURE__ */ new Set(["approve-bill", "approve-budget", "approve-customer-invoice", "approve-supplier", "create-bill", "create-bill-approval", "create-budget-approval", "create-customer-invoice", "create-supplier", "reject-bill", "reject-budget", "reject-customer-invoice", "reject-supplier", "send-estimate-email", "send-estimate-to-contact-person", "send-customer-invoice-to-contact-person", "update-bill-status", "update-supplier"]), externalWriteTargets = /* @__PURE__ */ new Set(["update-customer-invoice-details", "update-customer-invoice-qbo-drift", "record-external-bill-payment", "approve-bill", "approve-customer-invoice", "appr\
7006
- ove-supplier", "complete-project", "create-bill", "create-company", "use-existing-company", "create-estimate", "create-placeholder-bill", "create-customer-invoice", "create-item", "create-item-category", "create-project", "create-supplier", "delete-bill", "delete-budget", "delete-company", "delete-customer-invoice", "delete-item", "delete-project", "delete-suppliers", "discard-customer-invoice", "import-qbo-project", "mark-budget-items-not-utilized", "mark-budget-won", "reconcile-project", "reject-customer-invoice", "reactivate-suppliers", "restore-budget-item", "restore-budget-version", "retry-integration-operation", "setup-project-hub", "sync-project-hub-commercial-documents", "sync-customer-invoice", "update-bill", "update-budget-status", "update-company", "update-item", "update-item-category", "update-project", "update-project-status", "update-supplier", "void-customer-invoice"]), financialWriteTargets = /* @__PURE__ */ new Set(["update-customer-invoice-qbo-drift", "record-external\
7007
- -bill-payment", "import-qbo-customer-invoice", "link-bill-quotations", "approve-bill", "approve-customer-invoice", "complete-project", "create-bill", "create-customer-invoice", "create-estimate", "create-placeholder-bill", "delete-budget-commission", "delete-budget-discount", "delete-bill", "delete-budget", "delete-customer-invoice", "mark-budget-items-not-utilized", "mark-budget-won", "mark-customer-invoice-sent-externally", "patch-bill-payment", "reject-customer-invoice", "restore-budget-item", "restore-budget-version", "replace-budget-item", "sync-customer-invoice", "update-bill", "update-bill-payment-evidence", "update-bill-status", "update-budget-commission", "update-budget-discount", "update-budget-status", "update-project-status", "void-customer-invoice"]), deleteTargets = /* @__PURE__ */ new Set(["cleanup-staged-bill-attachments", "delete-webhook-endpoint", "cleanup-staged-quotation-attachments", "discard-customer-invoice", "complete-project", "mark-budget-items-not-utilized", "\
7008
- remove-budget-item", "restore-budget-version", "update-project-status"]), explicitEffects = { "resubmit-customer-invoice": ["state-change", "external-write", "financial-write", "email"], "request-bill-review": ["state-change", "external-write"], "rotate-webhook-secret": ["state-change"], "replay-webhook-delivery": ["state-change", "external-write"] }, effectsFor = __name2((legacyTarget) => {
6995
+ eanup-", "complete-", "create-", "delete-", "discard-", "import-", "link-", "mark-", "patch-", "reactivate-", "reconcile-", "record-", "refresh-", "reject-", "remove-", "replace-", "rename-", "reorder-", "restore-", "retry-", "revoke-", "save-", "send-", "stage-", "setup-", "submit-", "sync-", "update-", "use-existing-", "upload-", "void-"], emailTargets = /* @__PURE__ */ new Set(["approve-bill", "approve-budget", "approve-customer-invoice", "approve-supplier", "create-bill", "create-bill-approval", "create-budget-approval", "create-customer-invoice", "create-supplier", "reject-bill", "reject-budget", "reject-customer-invoice", "reject-supplier", "send-estimate-email", "send-estimate-to-contact-person", "send-customer-invoice-to-contact-person", "update-bill-status", "update-supplier"]), externalWriteTargets = /* @__PURE__ */ new Set([
6996
+ "update-customer-invoice-details",
6997
+ "update-customer-invoice-qbo-drift",
6998
+ "record-external-bill-payment",
6999
+ "approve-bill",
7000
+ "approve-customer-invoice",
7001
+ "approve-supplier",
7002
+ "complete-project",
7003
+ "create-bill",
7004
+ "create-company",
7005
+ "use-existing-company",
7006
+ "create-estimate",
7007
+ "create-placeholder-bill",
7008
+ "create-customer-invoice",
7009
+ "create-item",
7010
+ "create-item-category",
7011
+ "create-project",
7012
+ "create-supplier",
7013
+ "delete-bill",
7014
+ "delete-budget",
7015
+ "delete-company",
7016
+ "delete-customer-invoice",
7017
+ "delete-item",
7018
+ "delete-project",
7019
+ "delete-suppliers",
7020
+ "discard-customer-invoice",
7021
+ "import-qbo-project",
7022
+ "mark-budget-items-not-utilized",
7023
+ "mark-budget-won",
7024
+ "reconcile-project",
7025
+ "reject-customer-invoice",
7026
+ "reactivate-suppliers",
7027
+ "restore-budget-item",
7028
+ "restore-budget-version",
7029
+ "retry-integration-operation",
7030
+ "setup-project-hub",
7031
+ "sync-project-hub-commercial-documents",
7032
+ "sync-customer-invoice",
7033
+ "update-bill",
7034
+ "update-budget-status",
7035
+ "update-company",
7036
+ "update-item",
7037
+ "update-item-category",
7038
+ "update-project",
7039
+ "update-project-status",
7040
+ "update-supplier",
7041
+ "void-customer-invoice"
7042
+ ]), financialWriteTargets = /* @__PURE__ */ new Set(["update-customer-invoice-qbo-drift", "record-external-bill-payment", "import-qbo-customer-invoice", "link-bill-quotations", "approve-bill", "approve-customer-invoice", "complete-project", "create-bill", "create-customer-invoice", "create-estimate", "create-placeholder-bill", "delete-budget-commission", "delete-budget-discount", "delete-bill", "delete-budget", "delete-customer-invoice", "mark-budget-items-not-utilized", "mark-budget-won", "mark-customer-invoice-sent-externally", "patch-bill-payment", "reject-customer-invoice", "restore-budget-item", "restore-budget-version", "replace-budget-item", "sync-customer-invoice", "update-bill", "update-bill-payment-evidence", "update-bill-status", "update-budget-commission", "update-budget-discount", "update-budget-status", "update-project-status", "void-customer-invoice"]), deleteTargets = /* @__PURE__ */ new Set(["cleanup-staged-bill-attachments", "delete-webhook-endpoint", "cleanup-staged-\
7043
+ quotation-attachments", "discard-customer-invoice", "complete-project", "mark-budget-items-not-utilized", "remove-budget-item", "restore-budget-version", "update-project-status"]), explicitEffects = { "resubmit-customer-invoice": ["state-change", "external-write", "financial-write", "email"], "request-bill-review": ["state-change", "external-write"], "rotate-webhook-secret": ["state-change"], "replay-webhook-delivery": ["state-change", "external-write"] }, effectsFor = __name2((legacyTarget) => {
7009
7044
  const explicit = explicitEffects[legacyTarget];
7010
7045
  if (explicit) return explicit;
7011
7046
  const effects = /* @__PURE__ */ new Set();
7012
- return mutationPrefixes.some((prefix) => legacyTarget.startsWith(prefix)) && effects.add("state-change"), (legacyTarget.startsWith("delete-") || deleteTargets.has(legacyTarget)) && effects.add("delete"), emailTargets.has(legacyTarget) && effects.add("email"), externalWriteTargets.has(legacyTarget) && effects.add("external-write"), financialWriteTargets.has(legacyTarget) && effects.add("financial-write"), [...effects];
7047
+ return mutationPrefixes.some((prefix) => legacyTarget.startsWith(
7048
+ prefix
7049
+ )) && effects.add("state-change"), (legacyTarget.startsWith("delete-") || deleteTargets.has(legacyTarget)) && effects.add("delete"), emailTargets.has(legacyTarget) && effects.add("email"), externalWriteTargets.has(legacyTarget) && effects.add("external-write"), financialWriteTargets.has(legacyTarget) && effects.add("financial-write"), [...effects];
7013
7050
  }, "effectsFor"), titleCase = __name2((value) => value.split("-").map((word) => "".concat(word.slice(0, 1).toUpperCase()).concat(word.slice(1))).join(" "), "titleCase"), SUMMARIES = /* @__PURE__ */ new Map([["update-budget-status", "Update budget status. APPROVED requires a current Lead/Admin role; budget management permission alone is insufficient. Ordinary users must request approval. Status changes invalidate old pending requests."], ["approve-budget", "Decide your assigned pending budget approval as a current Lead/Admin. Material edits supersede old requests; inspect the latest content and use a fresh request after edits."], ["reject-budget", "Decide your assigned pending budget approval as a current Lead/Admin. Material edits supersede old requests; inspect the latest content and use a fresh request after edits."], ["create-budget-approval", "Request budget approval for the current content, superseding older pending requests. Existing Lead/Admin autoapproval remains available."], [
7014
7051
  "update-budget-item-supplier", "Change a budget item's eligible supplier/GST snapshot as a material financial edit. Supersede pending approvals and apply the standard budget-to-DRAFT reset policy; inspect and request approval again. An unchanged supplier is a no-op."], ["submit-quotation", "Submit a quotation for signing and approval. Claim the captured revision and exact allocation selection; concurrent edits, budget-item deletion or restore cascades conflict instead of attaching old signed PDFs. Refresh and resubmit the current content. The signed PDF is stamped by a queued job (pdfProcessing: PROCESSING until linked); a file whose PDF conversion failed must be uploaded again first. The result includes gstMismatch (null, or the basis, expected GST, saved GST and their difference; see create-quotation); it is a warning only and the approval email shows it to approvers."], ["approve-quotation", "Approve your assigned pending quotation as a current Admin. Claim the captured revision and\
7015
7052
  exact allocation selection after signing; concurrent changes conflict and roll back the decision, signed-PDF job and email/outbox. Refresh and review the current content before retrying. The final signed PDF is stamped by a queued job (pdfProcessing); a stopped earlier PDF step blocks approval until it is retried."], ["approve-supplier", "Approve a pending supplier request and send a requester reply email, or directly re-approve a rejected supplier as Admin/Lead without a pending request or email. The QuickBooks vendor is created, linked or updated by a queued job (quickBooksSyncQueued, operationId); the supplier stays PENDING_APPROVAL until QuickBooks confirms, and archived suppliers remain archived. Argument: <supplierId>."], ["list-approvals", "List one page of requests currently assigned to you and pending approval, oldest first. Returns { items, pageInfo }; follow nextCursor with unchanged --type. --page/--perPage are rejected."], ["get-pending-approval", "Read one request still \
7016
7053
  pending your approval, or null if it is no longer pending/assigned. Argument: <approvalId>."], ["get-bill-review", "Read current advisory AI bill review and evidence. Passive; no provider calls. Argument: <billId>."], ["request-bill-review", "Queue an advisory AI review of a bill pending your approval. No financial decision is made. <billId> [--requestId <id>]"], ["get-bill-details", "Get a bill's summary as shown in the web app: status, amounts, people, payment and line totals. Use get-bill-line-items, get-bill-approvals, get-bill-attachments or get-bill-payment for more detail. Argument: <billId>."], ["get-bill-line-items", "List a bill's line items with budget-item and quotation-allocation detail. <billId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-bill-approvals", "List a bill's approval requests with approver, requester and responder. <billId> [--limit 1-50] [--cursor <token>] Newest first. Returns { items, pageInfo };\
7017
- follow nextCursor."], [
7018
- "get-bill-payment",
7019
- "Get a bill's payment status, reference, date, tracking URL, QuickBooks link and external payment. Argument: <billId>."
7020
- ], ["get-quotation", "Get a quotation as shown in the web app: status, documentOnly (true for a $0 supplier document that is never a bill quotation source and does not count as coverage), amounts, people, line totals, files and approvals. pdfProcessing is { status: PROCESSING | FAILED, step: NORMALIZE | STAMP, operationId, error } while a queued PDF conversion or signing step has not linked its PDF, else null. gstMismatch is null, or { basis, expectedGstAmount, enteredGstAmount, difference, message } when the saved GST is non-zero and more than $0.05 away from the expected GST (TAXABLE_LINES: the bill calculation for the quoted lines; FULL_SUBTOTAL: 9% of the subtotal); check it before approving. Use get-quotation-line-items for budget-item detail. Argument: <quotationId>."], ["get-customer-invoice", "Get an invoice batch as shown in the web app: status, totals, people, approvals and invoice summaries. Use get-customer-invoice-invoices, get-customer-invoice-lines, get-customer-invoice-\
7021
- approvals or get-customer-invoice-history for more detail. Argument: <batchId>."], ["get-customer-invoice-invoices", "List a batch's invoices with QuickBooks id/doc number, issue/due dates, amounts, sync state and sender. Argument: <batchId>."], ["get-customer-invoice-lines", "List one invoice's lines (name, description, QuickBooks item/tax code, quantity, amounts). <invoiceId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-customer-invoice-approvals", "List an invoice batch's approval requests with approver, requester and responder. <batchId> [--limit 1-50] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-customer-invoice-history", "List an invoice batch's status history (batch/invoice status changes, source, note, actor). <batchId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-customer-invoice-payments", "List the payments Qui\
7022
- ckBooks applied to one invoice: payment id, date, reference, amount applied, total and attachment names. Argument: <invoiceId> (from get-customer-invoice-invoices). Live QuickBooks read."], ["get-quotation-line-items", "List a quotation's line items with budget-item, supplier and budget detail. <quotationId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-bill-attachments", "List bill attachments with cursor pagination. <billId> [--limit 1-50] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-budget-categories", "List budget categories with cursor pagination. [--q] [--limit 1-100] [--cursor <token>] Active categories, name A\u2013Z. Returns { items, pageInfo }; follow nextCursor with the same --q."], ["get-supplier-overview", "Get a supplier's profile, approvals, pending update, attachments and tab counts (usageCount, _count.items). Skips usage rows, spending and items; use get-supplier-us\
7023
- age or get-supplier-items for those."], ["get-supplier-usage", "Get a supplier's usage rows (accepted/closed budget lines and lines with its actual spending) plus spending, actualSpending and estimatedSpending."], ["get-supplier-items", "Get the inventory items catalogued under a supplier."], ["get-supplier-analytics", "List supplier analytics rows with cursor pagination. [--name] [--status CSV] [--gstRegistered true|false] [--createdBy <text>] [--timeFrame ALL|LAST_YEAR|LAST_6_MONTHS|LAST_3_MONTHS|CUSTOM] [--startDate <ISO> --endDate <ISO>] [--sortBy name|gstRegistered|status|phone|email|updatedAt|createdAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Admin. Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected."], ["list-api-keys", "List API keys with cursor pagination. [--userId <userId>] [--limit 1-100] [--cursor <token>] (newest first, { items, pageInfo }; defaults to t\
7024
- he caller; admin required for another user)"], ["list-claims", "List reimbursable claims with cursor pagination. Same flags as list-bills (--limit 1-100, --cursor, --direction forward|backward); ignores --isClaimable. Returns { items, pageInfo }."], ["list-bills", "List bills with cursor pagination. [--projectId] [--budgetId] [--status CSV] [--search <text>] [--isClaimable true|false] [--createdByIds <csv>] [--sortBy createdAt|amount|status] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Returns { items, pageInfo }; pass nextCursor with --direction forward or previousCursor with --direction backward, keeping the same filters and sort. --page/--pageSize/--perPage are rejected."], ["list-customer-invoices", "List customer invoice batches with cursor pagination. [budgetId] [--projectId <id>] [--companyIds CSV] [--projectIds CSV] [--budgetIds CSV] [--createdByIds CSV] [--status CSV] [--search] [--sortBy createdAt|status|totalInvoiceAmount|approvalExp\
7025
- iresAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected. No scope flag lists invoices globally. --projectId uses the project scope. A positional budgetId is a backward-compatible shortcut for --budgetIds."], ["list-quotations", "List quotations with cursor pagination. [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Newest first; returns { items, pageInfo }; each row carries documentOnly (document-only $0 quotations are listed and counted like any other). Follow nextCursor/previousCursor with the same filters. --page/--pageSize/--perPage are rejected; --requesterIds remains an alias for --createdBy."], ["list-users", "List users with cursor pagination. [--q] [--projectTeamOnly true|false] [--limit 1-100] [--cursor <token>] N\
7026
- ame A\u2013Z. Returns { items, pageInfo }; follow nextCursor with the same --q and --projectTeamOnly. --projectTeamOnly true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager. --page/--perPage are rejected."], ["list-companies", "List companies with cursor pagination. Returns { items, pageInfo }; default sort is createdAt descending with limit 20. Pass nextCursor forward or previousCursor backward unchanged. Legacy page/perPage flags are rejected."], ["count-companies", "Count companies independently from list pagination. Returns { totalCount, counts: { active: { true, false } } }; accepts filters only and rejects pagination/sorting flags."], ["list-projects", "List projects with cursor pagination. Returns { items, pageInfo }; default sort is createdAt descending with limit 20. Supports legacy --status plus optional --statuses, WON-date filters (--wonFrom, --wonTo, --wonWithinDays) and --sortBy wonAt; pass nextCursor\
7027
- forward or previousCursor backward unchanged. Legacy page/perPage flags are rejected."], ["count-projects", "Count projects independently from list pagination. Returns { totalCount, counts: { status, active: { true, false } } }; accepts project filters only and rejects pagination/sorting flags."], ["search-existing-companies", "Search BB and QuickBooks companies without writes. --query <name> [--limit 1-50] [--cursor <token>]. Returns { items, totalCount, pageInfo }; follow pageInfo.nextCursor with the same --query. Legacy --page is rejected."], ["use-existing-company", "Reuse a company in BB and QuickBooks, creating only its missing counterpart. Supply --companyId <bbId> and/or --quickbooksId <qboId>; both explicitly connect records with different names. Importing a QuickBooks-only company also needs --name <QuickBooks name from search-existing-companies>. --website <url> fills a missing QBO import website only. --confirmDistinct true confirms no similar record represents this entity\
7028
- . BB saves the company now; its QuickBooks customer is checked, found or created and linked by a queued job (quickBooksSyncQueued, operationId). Estimates, invoices and QuickBooks projects wait for that link."], ["create-company", "Create or reuse a company in BB and QuickBooks. --name <name> --website <url> [--billingEmails '<json-array>'] (up to 50 invoice Cc defaults, stored in BB only for new companies; reused company defaults are preserved). Similar names require --confirmDistinct true; inactive companies are never reactivated. BB saves the company now; its QuickBooks customer is found or created by a queued job (quickBooksSyncQueued, operationId), which stops if similar QuickBooks customers exist without --confirmDistinct."], ["create-project", "Create a project linked to an existing Asana Deals lead task. Supply --asanaTaskId in non-interactive use; interactive use searches for and selects a lead task (optionally --asanaSearch). For a new direct client, create the lead task usin\
7029
- g the website form first."], ["create-supplier", "Create a supplier using --payload JSON; pending-approval suppliers also request approval and send emails. Reusing an archived name requires Admin; normal users and Leads must ask an Admin to reactivate it before editing. Recreation preserves the existing approval status and creator. Lead/Admin-created suppliers (and archived-name revivals) queue their QuickBooks vendor create or link (quickBooksSyncQueued, operationId) and become usable once QuickBooks confirms; the request makes no QuickBooks call."], ["preview-qbo-customer-invoice", "Preview an available QuickBooks invoice selected for a BB budget using read-only QBO access. Arguments: <budgetId> <qboInvoiceId> [--confirmEstimateLineage true]. Use --confirmEstimateLineage only after confirming an invoice with no QuickBooks estimate link belongs to this budget's estimate."], ["preview-customer-invoice-amount", "Preview amount before GST, GST, and total for a percentage of an accepted e\
7030
- stimate. Arguments: <budgetId> <percentage-of-estimate>."], ["list-available-qbo-customer-invoices", "List unlinked QuickBooks invoices available for an accepted or closed estimate. Argument: <budgetId>."], ["resubmit-customer-invoice", "Resubmit a confirmed expired-and-voided BB invoice as its original requester. Argument: <batchId>. Queues one replacement using the current estimate, original percentage, due date and details; retries return the same replacement. No customer email."], ["create-customer-invoice", "Create one invoice from an eligible budget using --payload JSON with invoice date, due date, billing address, customer memo, and a percentage of the original estimate that does not exceed its remaining coverage."], ["import-qbo-customer-invoice", "Link an existing QuickBooks invoice in BB only after reviewing preview-qbo. Arguments: <budgetId> <qboInvoiceId> --token <previewToken> [--confirmEstimateLineage true] (repeat the preview's flag). Supports closed estimates; no QBO wr\
7031
- ites or emails."], ["whoami", "Show the active API-key identity."], ["list-budgets", "List one cursor page of budgets ({ items, pageInfo }; --limit/--cursor/--direction). Omit --active for active budgets only; use --active false or --active all for Admin-only historical reads."], ["list-items", "List one cursor page of catalogue items ({ items, pageInfo }; --limit/--cursor/--direction, optional --sortBy/--sortDir). --page/--perPage are rejected."], ["list-item-categories", "List one cursor page of active item categories ({ items, pageInfo }; --limit/--cursor/--direction, optional --name/--sortBy/--sortDir). --page/--perPage are rejected."], ["create-item-category", "Admin only. Create (or reactivate) an item category. Budget Builder saves it now and a queued job creates or links the QuickBooks category (quickBooksSyncQueued, operationId); the request makes no QuickBooks call."], ["update-item-category", "Rename an item category. Budget Builder saves the name immediately; a category lin\
7032
- ked to QuickBooks is renamed there by a queued job (quickBooksSyncQueued: true, operationId), never during the request."], ["count-item-categories", "Count active item categories matching --name: { totalCount }."], ["list-webhook-deliveries", "Admin-only: list webhook deliveries newest first. Returns { items, pageInfo }; follow pageInfo.nextCursor (or previousCursor with --direction backward). Cursors are opaque and filter-bound; raw delivery ids are rejected."], ["list-integration-operations", "List one cursor page of integration operations, newest first ({ items, pageInfo }; --limit/--cursor/--direction). --page/--perPage are rejected. Admin only."], ["count-integration-operations", "Provider filter options for integration operations: { filterOptions }. No total; filter flags are accepted but do not change the result. Admin only."], ["count-items", "Count catalogue items matching filters: total plus category and supplier facets (each ignores its own filter)."], ["count-budgets", "Cou\
7033
- nt budgets matching filters: totalCount plus status and active facets. Omit --active for active budgets only."], ["get-budget", "Get a budget by ID. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read."], ["get-budget-items", "Get line items for a budget. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read."], ["get-budget-details", "Get budget details. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read."], ["create-bill", "Create a bill or claim with an approved supplier. All amount fields exclude GST: amount is the portion billed; extractedAmount is the full invoice subtotal; lineAmounts and quotationAllocations also exclude GST. Example: 1800 + 162 GST = 1962 total requires amount=1800 and extractedAmount=1800 for a full bill. The CLI does not strip GST from input. If the selected quotations cannot split the bill amount across every selected l\
7034
- ine (a line without a quoted amount that cannot be derived from the quotation total), pass lineAmounts; updates that keep the same amount and lines reuse the existing line amounts. --draft-only guarantees DRAFT without email or external writes; otherwise unpaid creation skips email permission but keeps external-write permission. The result includes quotationOverBillingWarnings; a non-empty list means linked non-rejected bills exceed a quotation's quoted amount. It is a warning only and the write still succeeds. An Admin's unpaid bill is approved on creation and its QuickBooks bill is created by a queued job: the result has quickBooksSyncQueued: true and operationId; follow it with list-integration-operations. The request itself never writes to QuickBooks. Quotations with documentOnly: true (a $0 supplier document) are never valid bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted."], ["record-external-bill-payment", "Record an already-ma\
7035
- de payment on an APPROVED bill or claim, with no email and no money transfer. Requires <billId> --paymentReference --paymentDate YYYY-MM-DD --paymentAccount <QBO account ID> [--paymentProof receipt.pdf]. The account must be in the cached list (list-external-payment-accounts); the request makes no QuickBooks call. An inactive account (inactiveAccounts) only links the bill's existing QuickBooks payment when the bill is already settled; if there is none, the job is refused before anything is created and the bill goes back to APPROVED. Reuses settled QBO payment links or queues one dated payment from the selected account; the queued job re-checks the account in QuickBooks and stops in the Integration Queue if it is not active. Exact retries are safe; do not pay again while reconciliation is pending."], ["mark-customer-invoice-sent-externally", "Admin only. Record an APPROVED customer invoice as SENT (source EXTERNAL) because it was emailed to the customer outside Budget Builder. Sends no e\
7036
- mail and writes nothing to QuickBooks. Requires <invoiceId> --sentAt <ISO datetime, not in the future, not before approval> --recipients a@x.com,b@y.com [--note <message reference>]."], ["list-external-payment-accounts", "List active QuickBooks bank and credit-card account IDs for recording external payments (admin only), from Budget Builder's cached list: { accounts, cacheState, inactiveAccounts, refreshedAt, refresh }. inactiveAccounts can only link an already-settled bill's existing payment. No QuickBooks call. The worker refreshes the list automatically every day and after a QuickBooks company change; cacheState is READY, NOT_LOADED (first load pending), REALM_CHANGED (refreshing after a company change; no accounts served and external payments refused until it lands) or DISCONNECTED."], ["refresh-external-payment-accounts", "Admin only. Queue a refresh of the cached QuickBooks payment-account list ({ operationId, status: QUEUED }); a refresh already waiting is reused. Optional: the\
7037
- worker already refreshes the list every day and after a QuickBooks company change. Check refreshedAt with list-external-payment-accounts."], ["update-bill", "Update a bill or claim with a partial payload including id; omitted fields are preserved. Comment-only updates are allowed on approved/paid bills without altering financial data or QuickBooks. All amount fields exclude GST: amount is the portion billed; extractedAmount is the full invoice subtotal; lineAmounts and quotationAllocations also exclude GST. Example: 1800 + 162 GST = 1962 total requires amount=1800 and extractedAmount=1800 for a full bill. The CLI does not strip GST from input. If the selected quotations cannot split the bill amount across every selected line (a line without a quoted amount that cannot be derived from the quotation total), pass lineAmounts; updates that keep the same amount and lines reuse the existing line amounts. Re-read and verify both amount fields and allocations after correcting a gross/net mist\
7038
- ake. The result includes quotationOverBillingWarnings; a non-empty list means linked non-rejected bills exceed a quotation's quoted amount. It is a warning only and the write still succeeds. Quotations with documentOnly: true (a $0 supplier document) are never valid bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted."], ["validate-bill-selection", "Validate the approved supplier and selected bill line items. Supplier bills need approved quotation sources (quotationIds, legacy quotationId, or quotationAllocations with lineAmounts) for every line that is not quotation-exempt (Go Internal lines, or projects/budgets created before the quotation cutoff). With billId, lines already on the bill keep their stored sources unless new sources are supplied. Exemption is decided by the server, so there is no --quotation-exempt flag here. Amounts (amount, lineAmounts, quotationAllocations) are ex-GST dollars with at most 2 decimal places. Returns { su\
7039
- ccess, quotationOverBillingWarnings }: a non-empty warning list means the selection would bill a quotation above its quoted amount (counting other non-rejected bills); this is a warning only and does not fail validation. Quotations with documentOnly: true (a $0 supplier document) are never valid bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted."], ["create-quotation", 'Create a quotation with an approved supplier using --payload JSON. Include projectId, budgetId, supplierId, budgetItemIds, amountWithoutGst, gstAmount, and one uploaded attachment in attachments. Multiple budget items require lineAmounts: [{"budgetItemId":"<first-id>","amount":750},{"budgetItemId":"<second-id>","amount":450}], covering every selected budget-item ID exactly once and summing to amountWithoutGst. Amounts exclude GST; use gstAmount: 0 for no GST. Example: amountWithoutGst: 1200 with line amounts 750 and 450. The upload is checked and converted to PDF by a qu\
7040
- eued job (pdfProcessing in the result and in get-quotation). The result includes gstMismatch: null, or { basis, expectedGstAmount, enteredGstAmount, difference, message } when gstAmount is non-zero and more than $0.05 away from the expected GST. basis TAXABLE_LINES uses the bill calculation for the quoted lines (9% of each in-scope line, rounded per line; none for a non-GST-registered supplier); FULL_SUBTOTAL is 9% of amountWithoutGst, used when line amounts are unknown. It is a warning only (GST 0 is always accepted) and the write still succeeds. Document-only quotation (a $0 supplier document, for example a supplier contract or proposal with no price): set documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and every lineAmounts amount 0 (lineAmounts may be omitted; the API fills zeros). It uses the normal draft, submit, sign and Admin approve flow with the attachment, appears in list/get output with documentOnly: true, counts in quotation lists and approval queues, but does no\
7041
- t count as quotation coverage: a budget line covered only by it still counts as unquoted, and it is never a valid bill quotation source (create-bill, update-bill, validate-bill-selection and link-bill-quotations are rejected by the API). Without documentOnly (default false), amountWithoutGst must be positive.'], ["cleanup-staged-quotation-attachments", "Queue independent cleanup operations for unattached staged quotation uploads; returns operation IDs and queued/skipped counts, not deletion confirmation. Arguments: <projectId> --keys <csv>."], ["update-quotation", 'Update a DRAFT or REJECTED quotation using --payload JSON with id and the complete creation payload. Multiple budget items require lineAmounts: [{"budgetItemId":"<first-id>","amount":750},{"budgetItemId":"<second-id>","amount":450}], covering every budgetItemIds entry exactly once and summing to amountWithoutGst. Amounts exclude GST; use gstAmount: 0 for no GST. The result includes gstMismatch: null, or { basis, expectedGstA\
7042
- mount, enteredGstAmount, difference, message } when gstAmount is non-zero and more than $0.05 away from the expected GST. basis TAXABLE_LINES uses the bill calculation for the quoted lines (9% of each in-scope line, rounded per line; none for a non-GST-registered supplier); FULL_SUBTOTAL is 9% of amountWithoutGst, used when line amounts are unknown. It is a warning only (GST 0 is always accepted) and the write still succeeds. Update is a full replace: send documentOnly: true again when updating a document-only quotation (documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and zero lineAmounts; default false requires a positive amountWithoutGst), or it is treated as a priced quotation. Document-only quotations are never valid bill quotation sources and do not count as quotation coverage.'], ["download-customer-invoice-pdf", "Download a customer invoice PDF when permitted."], ["send-customer-invoice-to-contact-person", "Send a customer invoice and update the project billing email. \
7043
- Omit payload cc to use company billing defaults; an explicit list replaces them and [] removes them. Required internal Cc still applies."], ["update-company", "Save company fields in BB and queue independent QuickBooks name/website synchronization; returns operation ID, not provider completion. Optional payload billingEmails: email string array (max 50), omit to preserve defaults or [] to clear. Billing emails stay in BB; estimates are unchanged."], ["get-company-quickbooks-sync-status", "Read saved company synchronization status without provider calls or polling; use companyId."], ["get-item-quickbooks-sync-status", "Read saved item QuickBooks synchronization status without provider calls or polling; use itemId."], ["create-webhook-endpoint", "Admin-only: subscribe an HTTPS endpoint to BB events. --name --url --events <type|prefix.*|*,...>. Prints the whsec_ signing secret once; deliveries use Standard Webhooks headers."], ["rotate-webhook-secret", "Admin-only: issue a new signing sec\
7044
- ret; older secrets keep signing for --previousSecretTtlHours (default 24). Prints the new secret once. Argument: <endpointId>."], ["send-webhook-test-event", "Admin-only: send a signed webhook.test event to one endpoint. Argument: <endpointId>."], ["replay-webhook-delivery", "Admin-only: resend a finished webhook delivery with the same eventId on a fresh attempt chain. Argument: <deliveryId>."], ["get-error", "Admin-only: one error log with full diagnostics (stack, cause, request details, metadata, AI summary, resolution). Argument: <errorId>. error recent list returns table columns only."], ["get-webhook-delivery", "Admin-only: one webhook delivery with payload and attempts (status codes, errors, durations). Argument: <deliveryId>."], ["list-webhook-event-types", "List the outbound webhook event catalogue with group and live/planned status."], ["reconcile-resource-operation", "Admin-only check of a saved QuickBooks invoice/company/item job outcome; reads the provider only when uncerta\
7045
- in. Applied changes are finished locally without repeating the provider mutation; provably unapplied ones are queued again. Argument: <operationId>."], ["get-integration-operation", "Admin-only read of one integration job: who queued it, the records it is for with app links, saved QuickBooks progress, admin actions and Retry state. No provider calls. Argument: <operationId>."], ["retry-integration-operation", "Admin-only retry of a failed integration job. QuickBooks jobs with a saved attempt check QuickBooks first: applied changes finish without resending, provably unapplied ones are sent again, unprovable ones stay stopped with the reason. Argument: <operationId>."]]), summaryFor = __name2((legacyTarget) => {
7054
+ follow nextCursor."], ["get-bill-payment", "Get a bill's payment status, reference, date, tracking URL, QuickBooks link and external payment. Argument: <billId>."], ["get-quotation", "Get a quotation as shown in the web app: status, documentOnly (true for a $0 supplier document that is never a bill quotation source and does not count as coverage), amounts, people, line totals, files and approvals. pdfProcessing is { status: PROCESSING | FAILED, step: NORMALIZE | STAMP, operationId, error } while a queued PDF conversion or signing step has not linked its PDF, else null. gstMismatch is null, or { basis, expectedGstAmount, enteredGstAmount, difference, message } when the saved GST is non-zero and more than $0.05 away from the expected GST (TAXABLE_LINES: the bill calculation for the quoted lines; FULL_SUBTOTAL: 9% of the subtotal); check it before approving. Use get-quotation-line-items for budget-item detail. Argument: <quotationId>."], ["get-customer-invoice", "Get an invoice batch as \
7055
+ shown in the web app: status, totals, people, approvals and invoice summaries. Use get-customer-invoice-invoices, get-customer-invoice-lines, get-customer-invoice-approvals or get-customer-invoice-history for more detail. Argument: <batchId>."], ["get-customer-invoice-invoices", "List a batch's invoices with QuickBooks id/doc number, issue/due dates, amounts, sync state and sender. Argument: <batchId>."], ["get-customer-invoice-lines", "List one invoice's lines (name, description, QuickBooks item/tax code, quantity, amounts). <invoiceId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-customer-invoice-approvals", "List an invoice batch's approval requests with approver, requester and responder. <batchId> [--limit 1-50] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-customer-invoice-history", "List an invoice batch's status history (batch/invoice status changes, source, note, actor). <ba\
7056
+ tchId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-customer-invoice-payments", "List the payments QuickBooks applied to one invoice: payment id, date, reference, amount applied, total and attachment names. Argument: <invoiceId> (from get-customer-invoice-invoices). Live QuickBooks read."], ["get-quotation-line-items", "List a quotation's line items with budget-item, supplier and budget detail. <quotationId> [--limit 1-100] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-bill-attachments", "List bill attachments with cursor pagination. <billId> [--limit 1-50] [--cursor <token>] Newest first. Returns { items, pageInfo }; follow nextCursor."], ["get-budget-categories", "List budget categories with cursor pagination. [--q] [--limit 1-100] [--cursor <token>] Active categories, name A\u2013Z. Returns { items, pageInfo }; follow nextCursor with the same --q."], ["get-supplier-overview", "Ge\
7057
+ t a supplier's profile, approvals, pending update, attachments and tab counts (usageCount, _count.items). Skips usage rows, spending and items; use get-supplier-usage or get-supplier-items for those."], ["get-supplier-usage", "Get a supplier's usage rows (accepted/closed budget lines and lines with its actual spending) plus spending, actualSpending and estimatedSpending."], ["get-supplier-items", "Get the inventory items catalogued under a supplier."], ["get-supplier-analytics", "List supplier analytics rows with cursor pagination. [--name] [--status CSV] [--gstRegistered true|false] [--createdBy <text>] [--timeFrame ALL|LAST_YEAR|LAST_6_MONTHS|LAST_3_MONTHS|CUSTOM] [--startDate <ISO> --endDate <ISO>] [--sortBy name|gstRegistered|status|phone|email|updatedAt|createdAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Admin. Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected."],
7058
+ ["list-api-keys", "List API keys with cursor pagination. [--userId <userId>] [--limit 1-100] [--cursor <token>] (newest first, { items, pageInfo }; defaults to the caller; admin required for another user)"], ["list-claims", "List reimbursable claims with cursor pagination. Same flags as list-bills (--limit 1-100, --cursor, --direction forward|backward); ignores --isClaimable. Returns { items, pageInfo }."], ["list-bills", "List bills with cursor pagination. [--projectId] [--budgetId] [--status CSV] [--search <text>] [--isClaimable true|false] [--createdByIds <csv>] [--sortBy createdAt|amount|status] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Returns { items, pageInfo }; pass nextCursor with --direction forward or previousCursor with --direction backward, keeping the same filters and sort. --page/--pageSize/--perPage are rejected."], ["list-customer-invoices", "List customer invoice batches with cursor pagination. [budgetId] [--projectId <id>]\
7059
+ [--companyIds CSV] [--projectIds CSV] [--budgetIds CSV] [--createdByIds CSV] [--status CSV] [--search] [--sortBy createdAt|status|totalInvoiceAmount|approvalExpiresAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected. No scope flag lists invoices globally. --projectId uses the project scope. A positional budgetId is a backward-compatible shortcut for --budgetIds."], ["list-quotations", "List quotations with cursor pagination. [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--limit 1-100] [--cursor <token>] [--direction forward|backward] Newest first; returns { items, pageInfo }; each row carries documentOnly (document-only $0 quotations are listed and counted like any other). Follow nextCursor/previousCursor with the same filters. --page/--pageSize/--perPage are rejected; --requesterIds \
7060
+ remains an alias for --createdBy."], ["list-users", "List users with cursor pagination. [--q] [--projectTeamOnly true|false] [--limit 1-100] [--cursor <token>] Name A\u2013Z. Returns { items, pageInfo }; follow nextCursor with the same --q and --projectTeamOnly. --projectTeamOnly true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager. --page/--perPage are rejected."], ["list-companies", "List companies with cursor pagination. Returns { items, pageInfo }; default sort is createdAt descending with limit 20. Pass nextCursor forward or previousCursor backward unchanged. Legacy page/perPage flags are rejected."], ["count-companies", "Count companies independently from list pagination. Returns { totalCount, counts: { active: { true, false } } }; accepts filters only and rejects pagination/sorting flags."], ["list-projects", "List projects with cursor pagination. Returns { items, pageInfo }; default sort is createdAt descen\
7061
+ ding with limit 20. Supports legacy --status plus optional --statuses, WON-date filters (--wonFrom, --wonTo, --wonWithinDays) and --sortBy wonAt; pass nextCursor forward or previousCursor backward unchanged. Legacy page/perPage flags are rejected."], ["count-projects", "Count projects independently from list pagination. Returns { totalCount, counts: { status, active: { true, false } } }; accepts project filters only and rejects pagination/sorting flags."], ["search-existing-companies", "Search BB and QuickBooks companies without writes. --query <name> [--limit 1-50] [--cursor <token>]. Returns { items, totalCount, pageInfo }; follow pageInfo.nextCursor with the same --query. Legacy --page is rejected."], ["use-existing-company", "Reuse a company in BB and QuickBooks, creating only its missing counterpart. Supply --companyId <bbId> and/or --quickbooksId <qboId>; both explicitly connect records with different names. Importing a QuickBooks-only company also needs --name <QuickBooks name f\
7062
+ rom search-existing-companies>. --website <url> fills a missing QBO import website only. --confirmDistinct true confirms no similar record represents this entity. BB saves the company now; its QuickBooks customer is checked, found or created and linked by a queued job (quickBooksSyncQueued, operationId). Estimates, invoices and QuickBooks projects wait for that link."], ["create-company", "Create or reuse a company in BB and QuickBooks. --name <name> --website <url> [--billingEmails '<json-array>'] (up to 50 invoice Cc defaults, stored in BB only for new companies; reused company defaults are preserved). Similar names require --confirmDistinct true; inactive companies are never reactivated. BB saves the company now; its QuickBooks customer is found or created by a queued job (quickBooksSyncQueued, operationId), which stops if similar QuickBooks customers exist without --confirmDistinct."], ["create-project", "Create a project linked to an existing Asana Deals lead task. Supply --asanaT\
7063
+ askId in non-interactive use; interactive use searches for and selects a lead task (optionally --asanaSearch). For a new direct client, create the lead task using the website form first."], ["create-supplier", "Create a supplier using --payload JSON; pending-approval suppliers also request approval and send emails. Reusing an archived name requires Admin; normal users and Leads must ask an Admin to reactivate it before editing. Recreation preserves the existing approval status and creator. Lead/Admin-created suppliers (and archived-name revivals) queue their QuickBooks vendor create or link (quickBooksSyncQueued, operationId) and become usable once QuickBooks confirms; the request makes no QuickBooks call."], ["preview-qbo-customer-invoice", "Preview an available QuickBooks invoice selected for a BB budget using read-only QBO access. Arguments: <budgetId> <qboInvoiceId> [--confirmEstimateLineage true]. Use --confirmEstimateLineage only after confirming an invoice with no QuickBooks est\
7064
+ imate link belongs to this budget's estimate."], ["preview-customer-invoice-amount", "Preview amount before GST, GST, and total for a percentage of an accepted estimate. Arguments: <budgetId> <percentage-of-estimate>."], ["list-available-qbo-customer-invoices", "List unlinked QuickBooks invoices available for an accepted or closed estimate. Argument: <budgetId>."], ["resubmit-customer-invoice", "Resubmit a confirmed expired-and-voided BB invoice as its original requester. Argument: <batchId>. Queues one replacement using the current estimate, original percentage, due date and details; retries return the same replacement. No customer email."], ["create-customer-invoice", "Create one invoice from an eligible budget using --payload JSON with invoice date, due date, billing address, customer memo, and a percentage of the original estimate that does not exceed its remaining coverage."], ["import-qbo-customer-invoice", "Link an existing QuickBooks invoice in BB only after reviewing preview-q\
7065
+ bo. Arguments: <budgetId> <qboInvoiceId> --token <previewToken> [--confirmEstimateLineage true] (repeat the preview's flag). Supports closed estimates; no QBO writes or emails."], ["whoami", "Show the active API-key identity."], ["list-budgets", "List one cursor page of budgets ({ items, pageInfo }; --limit/--cursor/--direction). Omit --active for active budgets only; use --active false or --active all for Admin-only historical reads."], ["list-items", "List one cursor page of catalogue items ({ items, pageInfo }; --limit/--cursor/--direction, optional --sortBy/--sortDir). --page/--perPage are rejected."], ["list-item-categories", "List one cursor page of active item categories ({ items, pageInfo }; --limit/--cursor/--direction, optional --name/--sortBy/--sortDir). --page/--perPage are rejected."], ["create-item-category", "Admin only. Create (or reactivate) an item category. Budget Builder saves it now and a queued job creates or links the QuickBooks category (quickBooksSyncQueued, op\
7066
+ erationId); the request makes no QuickBooks call."], ["update-item-category", "Rename an item category. Budget Builder saves the name immediately; a category linked to QuickBooks is renamed there by a queued job (quickBooksSyncQueued: true, operationId), never during the request."], ["count-item-categories", "Count active item categories matching --name: { totalCount }."], ["list-webhook-deliveries", "Admin-only: list webhook deliveries newest first. Returns { items, pageInfo }; follow pageInfo.nextCursor (or previousCursor with --direction backward). Cursors are opaque and filter-bound; raw delivery ids are rejected."], ["list-integration-operations", "List one cursor page of integration operations, newest first ({ items, pageInfo }; --limit/--cursor/--direction). --page/--perPage are rejected. Admin only."], ["count-integration-operations", "Provider filter options for integration operations: { filterOptions }. No total; filter flags are accepted but do not change the result. Admin o\
7067
+ nly."], ["count-items", "Count catalogue items matching filters: total plus category and supplier facets (each ignores its own filter)."], ["count-budgets", "Count budgets matching filters: totalCount plus status and active facets. Omit --active for active budgets only."], ["get-budget", "Get a budget by ID. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read."], ["get-budget-items", "Get line items for a budget. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read."], ["get-budget-details", "Get budget details. Omit --includeInactive for active budgets only; --includeInactive is an Admin-only historical read."], ["create-bill", "Create a bill or claim with an approved supplier. All amount fields exclude GST: amount is the portion billed; extractedAmount is the full invoice subtotal; lineAmounts and quotationAllocations also exclude GST. Example: 1800 + 162 GST = 1962 total requires amount=1800\
7068
+ and extractedAmount=1800 for a full bill. The CLI does not strip GST from input. If the selected quotations cannot split the bill amount across every selected line (a line without a quoted amount that cannot be derived from the quotation total), pass lineAmounts; updates that keep the same amount and lines reuse the existing line amounts. --draft-only guarantees DRAFT without email or external writes; otherwise unpaid creation skips email permission but keeps external-write permission. The result includes quotationOverBillingWarnings; a non-empty list means linked non-rejected bills exceed a quotation's quoted amount. It is a warning only and the write still succeeds. An Admin's unpaid bill is approved on creation and its QuickBooks bill is created by a queued job: the result has quickBooksSyncQueued: true and operationId; follow it with list-integration-operations. The request itself never writes to QuickBooks. Quotations with documentOnly: true (a $0 supplier document) are never val\
7069
+ id bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted."], ["record-external-bill-payment", "Record an already-made payment on an APPROVED bill or claim, with no email and no money transfer. Requires <billId> --paymentReference --paymentDate YYYY-MM-DD --paymentAccount <QBO account ID> [--paymentProof receipt.pdf]. The account must be in the cached list (list-external-payment-accounts); the request makes no QuickBooks call. An inactive account (inactiveAccounts) only links the bill's existing QuickBooks payment when the bill is already settled; if there is none, the job is refused before anything is created and the bill goes back to APPROVED. Reuses settled QBO payment links or queues one dated payment from the selected account; the queued job re-checks the account in QuickBooks and stops in the Integration Queue if it is not active. Exact retries are safe; do not pay again while reconciliation is pending."], ["mark-customer-invoice-sent-\
7070
+ externally", "Admin only. Record an APPROVED customer invoice as SENT (source EXTERNAL) because it was emailed to the customer outside Budget Builder. Sends no email and writes nothing to QuickBooks. Requires <invoiceId> --sentAt <ISO datetime, not in the future, not before approval> --recipients a@x.com,b@y.com [--note <message reference>]."], ["list-external-payment-accounts", "List active QuickBooks bank and credit-card account IDs for recording external payments (admin only), from Budget Builder's cached list: { accounts, cacheState, inactiveAccounts, refreshedAt, refresh }. inactiveAccounts can only link an already-settled bill's existing payment. No QuickBooks call. The worker refreshes the list automatically every day and after a QuickBooks company change; cacheState is READY, NOT_LOADED (first load pending), REALM_CHANGED (refreshing after a company change; no accounts served and external payments refused until it lands) or DISCONNECTED."], ["refresh-external-payment-accounts",
7071
+ "Admin only. Queue a refresh of the cached QuickBooks payment-account list ({ operationId, status: QUEUED }); a refresh already waiting is reused. Optional: the worker already refreshes the list every day and after a QuickBooks company change. Check refreshedAt with list-external-payment-accounts."], ["update-bill", "Update a bill or claim with a partial payload including id; omitted fields are preserved. Comment-only updates are allowed on approved/paid bills without altering financial data or QuickBooks. All amount fields exclude GST: amount is the portion billed; extractedAmount is the full invoice subtotal; lineAmounts and quotationAllocations also exclude GST. Example: 1800 + 162 GST = 1962 total requires amount=1800 and extractedAmount=1800 for a full bill. The CLI does not strip GST from input. If the selected quotations cannot split the bill amount across every selected line (a line without a quoted amount that cannot be derived from the quotation total), pass lineAmounts; upda\
7072
+ tes that keep the same amount and lines reuse the existing line amounts. Re-read and verify both amount fields and allocations after correcting a gross/net mistake. The result includes quotationOverBillingWarnings; a non-empty list means linked non-rejected bills exceed a quotation's quoted amount. It is a warning only and the write still succeeds. Quotations with documentOnly: true (a $0 supplier document) are never valid bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted."], ["validate-bill-selection", "Validate the approved supplier and selected bill line items. Supplier bills need approved quotation sources (quotationIds, legacy quotationId, or quotationAllocations with lineAmounts) for every line that is not quotation-exempt (Go Internal lines, or projects/budgets created before the quotation cutoff). With billId, lines already on the bill keep their stored sources unless new sources are supplied. Exemption is decided by the server,\
7073
+ so there is no --quotation-exempt flag here. Amounts (amount, lineAmounts, quotationAllocations) are ex-GST dollars with at most 2 decimal places. Returns { success, quotationOverBillingWarnings }: a non-empty warning list means the selection would bill a quotation above its quoted amount (counting other non-rejected bills); this is a warning only and does not fail validation. Quotations with documentOnly: true (a $0 supplier document) are never valid bill quotation sources and are rejected; a budget line covered only by one still counts as unquoted."], ["create-quotation", 'Create a quotation with an approved supplier using --payload JSON. Include projectId, budgetId, supplierId, budgetItemIds, amountWithoutGst, gstAmount, and one uploaded attachment in attachments. Multiple budget items require lineAmounts: [{"budgetItemId":"<first-id>","amount":750},{"budgetItemId":"<second-id>","amount":450}], covering every selected budget-item ID exactly once and summing to amountWithoutGst. Amo\
7074
+ unts exclude GST; use gstAmount: 0 for no GST. Example: amountWithoutGst: 1200 with line amounts 750 and 450. The upload is checked and converted to PDF by a queued job (pdfProcessing in the result and in get-quotation). The result includes gstMismatch: null, or { basis, expectedGstAmount, enteredGstAmount, difference, message } when gstAmount is non-zero and more than $0.05 away from the expected GST. basis TAXABLE_LINES uses the bill calculation for the quoted lines (9% of each in-scope line, rounded per line; none for a non-GST-registered supplier); FULL_SUBTOTAL is 9% of amountWithoutGst, used when line amounts are unknown. It is a warning only (GST 0 is always accepted) and the write still succeeds. Document-only quotation (a $0 supplier document, for example a supplier contract or proposal with no price): set documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and every lineAmounts amount 0 (lineAmounts may be omitted; the API fills zeros). It uses the normal draft, submit,\
7075
+ sign and Admin approve flow with the attachment, appears in list/get output with documentOnly: true, counts in quotation lists and approval queues, but does not count as quotation coverage: a budget line covered only by it still counts as unquoted, and it is never a valid bill quotation source (create-bill, update-bill, validate-bill-selection and link-bill-quotations are rejected by the API). Without documentOnly (default false), amountWithoutGst must be positive.'], ["cleanup-staged-quotation-attachments", "Queue independent cleanup operations for unattached staged quotation uploads; returns operation IDs and queued/skipped counts, not deletion confirmation. Arguments: <projectId> --keys <csv>."], ["update-quotation", 'Update a DRAFT or REJECTED quotation using --payload JSON with id and the complete creation payload. Multiple budget items require lineAmounts: [{"budgetItemId":"<first-id>","amount":750},{"budgetItemId":"<second-id>","amount":450}], covering every budgetItemIds entry\
7076
+ exactly once and summing to amountWithoutGst. Amounts exclude GST; use gstAmount: 0 for no GST. The result includes gstMismatch: null, or { basis, expectedGstAmount, enteredGstAmount, difference, message } when gstAmount is non-zero and more than $0.05 away from the expected GST. basis TAXABLE_LINES uses the bill calculation for the quoted lines (9% of each in-scope line, rounded per line; none for a non-GST-registered supplier); FULL_SUBTOTAL is 9% of amountWithoutGst, used when line amounts are unknown. It is a warning only (GST 0 is always accepted) and the write still succeeds. Update is a full replace: send documentOnly: true again when updating a document-only quotation (documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and zero lineAmounts; default false requires a positive amountWithoutGst), or it is treated as a priced quotation. Document-only quotations are never valid bill quotation sources and do not count as quotation coverage.'], ["download-customer-invoice-pdf",
7077
+ "Download a customer invoice PDF when permitted."], ["send-customer-invoice-to-contact-person", "Send a customer invoice and update the project billing email. Omit payload cc to use company billing defaults; an explicit list replaces them and [] removes them. Required internal Cc still applies."], ["update-company", "Save company fields in BB and queue independent QuickBooks name/website synchronization; returns operation ID, not provider completion. Optional payload billingEmails: email string array (max 50), omit to preserve defaults or [] to clear. Billing emails stay in BB; estimates are unchanged."], ["get-company-quickbooks-sync-status", "Read saved company synchronization status without provider calls or polling; use companyId."], ["get-item-quickbooks-sync-status", "Read saved item QuickBooks synchronization status without provider calls or polling; use itemId."], ["create-webhook-endpoint", "Admin-only: subscribe an HTTPS endpoint to BB events. --name --url --events <type|pref\
7078
+ ix.*|*,...>. Prints the whsec_ signing secret once; deliveries use Standard Webhooks headers."], ["rotate-webhook-secret", "Admin-only: issue a new signing secret; older secrets keep signing for --previousSecretTtlHours (default 24). Prints the new secret once. Argument: <endpointId>."], ["send-webhook-test-event", "Admin-only: send a signed webhook.test event to one endpoint. Argument: <endpointId>."], ["replay-webhook-delivery", "Admin-only: resend a finished webhook delivery with the same eventId on a fresh attempt chain. Argument: <deliveryId>."], ["get-error", "Admin-only: one error log with full diagnostics (stack, cause, request details, metadata, AI summary, resolution). Argument: <errorId>. error recent list returns table columns only."], ["get-webhook-delivery", "Admin-only: one webhook delivery with payload and attempts (status codes, errors, durations). Argument: <deliveryId>."], ["list-webhook-event-types", "List the outbound webhook event catalogue with group and live/pla\
7079
+ nned status."], ["reconcile-resource-operation", "Admin-only check of a saved QuickBooks invoice/company/item job outcome; reads the provider only when uncertain. Applied changes are finished locally without repeating the provider mutation; provably unapplied ones are queued again. Argument: <operationId>."], ["get-integration-operation", "Admin-only read of one integration job: who queued it, the records it is for with app links, saved QuickBooks progress, admin actions and Retry state. No provider calls. Argument: <operationId>."], ["retry-integration-operation", "Admin-only retry of a failed integration job. QuickBooks jobs with a saved attempt check QuickBooks first: applied changes finish without resending, provably unapplied ones are sent again, unprovable ones stay stopped with the reason. Argument: <operationId>."]]), summaryFor = __name2((legacyTarget) => {
7046
7080
  const summary = SUMMARIES.get(legacyTarget);
7047
7081
  return summary !== void 0 ? summary : legacyTarget.startsWith("list-") ? "List ".concat(legacyTarget.slice(5).replaceAll("-", " "), ".") : legacyTarget.startsWith("get-") ? "Get ".concat(legacyTarget.slice(4).replaceAll("-", " "), ".") : "".concat(titleCase(legacyTarget), ".");
7048
- }, "summaryFor"), aliasesFor = __name2(
7049
- (legacyTarget, aliases) => [...new Set([legacyTarget, ...aliases].flatMap((alias) => [alias, alias.replaceAll("-", "_")]))],
7050
- "aliasesFor"
7051
- ), legacyCommand = __name2((legacyTarget, path2, aliases = [], commandOptions = []) => ({ path: path2, legacyAliases: aliasesFor(legacyTarget, aliases), summary: summaryFor(legacyTarget), options: [...globalCommandOptions, ...commandOptions], effects: effectsFor(legacyTarget), legacyTarget }), "legacyCommand"), budgetPreflightOptions = [{ name: "--companyPayload <json>", description: "Company update JSON object with id, name, and website fields." }, { name: "--contactPayload <json>", description: "Contact update JSON object with companyId, title, firstName, lastName, email, and mobile fields." }, { name: "--eventPayload <json>", description: "Event timing JSON object with date, startTime, and endTime fields." }], authCommand = __name2((action, summary) => ({ path: ["auth", action], legacyAliases: [], summary, options: globalCommandOptions, effects: [], load: __name2(async () => async () => ({}), "load") }), "authCommand"), registry2 = [
7052
- authCommand(
7053
- "login",
7054
- "Authorize this device through Budget Builder in your browser."
7055
- ),
7082
+ }, "summaryFor"), aliasesFor = __name2((legacyTarget, aliases) => [...new Set([legacyTarget, ...aliases].flatMap((alias) => [alias, alias.replaceAll("-", "_")]))], "aliasesFor"), legacyCommand = __name2((legacyTarget, path2, aliases = [], commandOptions = []) => ({ path: path2, legacyAliases: aliasesFor(legacyTarget, aliases), summary: summaryFor(legacyTarget), options: [...globalCommandOptions, ...commandOptions], effects: effectsFor(legacyTarget), legacyTarget }), "legacyCommand"), budgetPreflightOptions = [{ name: "--companyPayload <json>", description: "Company update JSON object with id, name, and website fields." }, { name: "--contactPayload <json>", description: "Contact update JSON object with companyId, title, firstName, lastName, email, and mobile fields." }, { name: "--eventPayload <json>", description: "Event timing JSON object with date, startTime, and endTime fields." }], authCommand = __name2((action, summary) => ({ path: ["auth", action], legacyAliases: [], summary, options: globalCommandOptions,
7083
+ effects: [], load: __name2(async () => async () => ({}), "load") }), "authCommand"), registry2 = [
7084
+ authCommand("login", "Authorize this device through Budget Builder in your browser."),
7056
7085
  authCommand("status", "Show the active CLI authentication method and session status."),
7057
7086
  authCommand("logout", "Revoke the interactive CLI session and remove its local credential."),
7058
7087
  legacyCommand("whoami", ["auth", "whoami"]),
7088
+ { path: ["mobile-push", "status"], legacyAliases: [], summary: "Show push availability and your active Android push registrations.", options: globalCommandOptions, effects: [], legacyTarget: "mobile-push-status" },
7089
+ { path: ["mobile-push", "unregister"], legacyAliases: [], summary: "Unregister notifications for one of your active Android devices. Argument: <sessionId>.", options: globalCommandOptions, effects: ["state-change"], legacyTarget: "mobile-push-unregister" },
7059
7090
  legacyCommand("list-budgets", ["budget", "list"], [], [{ name: "--active <true|false|all>", description: "Omit for active budgets only; false or all requires Admin access." }, { name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort." }, { name: "--direction <forward|backward>", description: "forward (default) or backward; backward needs --cursor." }]),
7060
7091
  legacyCommand("count-budgets", ["budget", "count"], [], [{ name: "--active <true|false|all>", description: "Omit for active budgets only; false or all requires Admin access." }]),
7061
- legacyCommand(
7062
- "get-budget",
7063
- ["budget", "get"],
7064
- [],
7065
- [{ name: "--includeInactive", description: "Include inactive historical budgets; Admin only." }]
7066
- ),
7092
+ legacyCommand("get-budget", ["budget", "get"], [], [{ name: "--includeInactive", description: "Include inactive historical budgets; Admin only." }]),
7067
7093
  legacyCommand("upload-budget-attachment", ["budget", "attachment", "upload"]),
7068
- legacyCommand("mark-budget-won", ["budget", "won", "mark"]),
7094
+ legacyCommand("mark-budget-won", [
7095
+ "budget",
7096
+ "won",
7097
+ "mark"
7098
+ ]),
7069
7099
  legacyCommand("get-budget-items", ["budget", "item", "list"], [], [{ name: "--includeInactive", description: "Include inactive historical budgets; Admin only." }]),
7070
7100
  legacyCommand("get-budget-details", ["budget", "detail", "get"], [], [{ name: "--includeInactive", description: "Include inactive historical budgets; Admin only." }]),
7071
7101
  legacyCommand("get-budget-categories", ["budget", "category", "list"], [], [{ name: "--q <text>", description: "Search active category names (name A\u2013Z). A bare --q is rejected; use -q/--quiet to hide logs." }, { name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }]),
@@ -7092,10 +7122,7 @@ in. Applied changes are finished locally without repeating the provider mutation
7092
7122
  legacyCommand("update-budget-commission", ["budget", "commission", "update"]),
7093
7123
  legacyCommand("update-budget-discount", ["budget", "discount", "update"]),
7094
7124
  legacyCommand("delete-budget-commission", ["budget", "commission", "delete"]),
7095
- legacyCommand(
7096
- "delete-budget-discount",
7097
- ["budget", "discount", "delete"]
7098
- ),
7125
+ legacyCommand("delete-budget-discount", ["budget", "discount", "delete"]),
7099
7126
  legacyCommand("mark-budget-items-not-utilized", ["budget", "item", "mark-not-utilized"]),
7100
7127
  legacyCommand("restore-budget-item", ["budget", "item", "restore"]),
7101
7128
  legacyCommand("create-placeholder-bill", ["budget", "item", "placeholder-bill", "create"]),
@@ -7103,7 +7130,10 @@ in. Applied changes are finished locally without repeating the provider mutation
7103
7130
  legacyCommand("list-claims", ["claim", "list"], [], [{ name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort." }, { name: "--direction <forward|backward>", description: "forward (default) or backward; backward needs --cursor." }]),
7104
7131
  legacyCommand("count-bills", ["bill", "count"]),
7105
7132
  legacyCommand("count-claims", ["claim", "count"]),
7106
- legacyCommand("create-bill-approval", ["bill", "approval", "create"]),
7133
+ legacyCommand(
7134
+ "create-bill-approval",
7135
+ ["bill", "approval", "create"]
7136
+ ),
7107
7137
  legacyCommand("create-bill", ["bill", "create"], [], [{ name: "--draft-only", description: "Create a draft for every role; no approval, email, or QuickBooks writes. Conflicts with alreadyPaid: true." }, { name: "--quotation-exempt", description: "Explicitly request an eligible server-validated supplier-bill quotation exemption. Cannot be combined with quotation IDs." }]),
7108
7138
  legacyCommand("validate-bill-selection", ["bill", "selection", "validate"], [], [{ name: "--quotationIds <csv>", description: "Approved quotation IDs for a supplier bill. Each selected budget item must be covered once." }, { name: "--quotationId <id>", description: "Legacy syntax for selecting one approved quotation." }]),
7109
7139
  legacyCommand("link-bill-quotations", ["bill", "quotation", "link"], ["billId"], [{ name: "--payload <json>", description: "Explicit quotationAllocations for split source coverage on the bill's stored line amounts; documentOnly quotations are rejected." }, { name: "--quotationIds <csv>", description: "Approved quotation IDs to link across the bill's disjoint line coverage; documentOnly quotations are rejected." }]),
@@ -7131,21 +7161,13 @@ in. Applied changes are finished locally without repeating the provider mutation
7131
7161
  legacyCommand("list-quotations", ["quotation", "list"], [], [{ name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort." }, { name: "--direction <forward|backward>", description: "forward (default) or backward; backward needs --cursor." }]),
7132
7162
  legacyCommand("count-quotations", ["quotation", "count"]),
7133
7163
  legacyCommand("get-quotation", ["quotation", "get"]),
7134
- legacyCommand(
7135
- "get-quotation-line-items",
7136
- ["quotation", "line-item", "list"],
7137
- [],
7138
- [{ name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }]
7139
- ),
7164
+ legacyCommand("get-quotation-line-items", ["quotation", "line-item", "list"], [], [{ name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }]),
7140
7165
  legacyCommand("upload-quotation-attachment", ["quotation", "attachment", "upload"]),
7141
7166
  legacyCommand("cleanup-staged-quotation-attachments", ["quotation", "attachment", "staged", "cleanup"]),
7142
7167
  legacyCommand("create-quotation", ["quotation", "create"], [], [{ name: "--payload", description: "Quotation JSON including lineAmounts for multiple selected budget items; see the payload format above. Set documentOnly: true with zero amounts for a $0 supplier document.", required: !0 }]),
7143
7168
  legacyCommand("update-quotation", ["quotation", "update"], [], [{ name: "--payload", description: "Complete quotation JSON plus id, including lineAmounts for multiple selected budget items. Send documentOnly: true again when updating a document-only quotation.", required: !0 }]),
7144
7169
  legacyCommand("delete-quotation", ["quotation", "delete"]),
7145
- legacyCommand(
7146
- "submit-quotation",
7147
- ["quotation", "submit"]
7148
- ),
7170
+ legacyCommand("submit-quotation", ["quotation", "submit"]),
7149
7171
  legacyCommand("approve-quotation", ["quotation", "approve"]),
7150
7172
  legacyCommand("reject-quotation", ["quotation", "reject"]),
7151
7173
  legacyCommand("download-quotation-pdf", ["quotation", "pdf", "download"]),
@@ -7159,10 +7181,7 @@ in. Applied changes are finished locally without repeating the provider mutation
7159
7181
  legacyCommand("get-customer-invoice-invoices", ["customer-invoice", "invoice", "list"]),
7160
7182
  legacyCommand("get-customer-invoice-lines", ["customer-invoice", "line", "list"], [], [{ name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }]),
7161
7183
  legacyCommand("get-customer-invoice-approvals", ["customer-invoice", "approval", "list"], [], [{ name: "--limit <1-50>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }]),
7162
- legacyCommand("get-customer-invoice-history", ["customer-invoice", "history", "list"], [], [
7163
- { name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." },
7164
- { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }
7165
- ]),
7184
+ legacyCommand("get-customer-invoice-history", ["customer-invoice", "history", "list"], [], [{ name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }]),
7166
7185
  legacyCommand("get-customer-invoice-payments", ["customer-invoice", "payments", "list"]),
7167
7186
  legacyCommand("get-customer-invoice-email-context", ["customer-invoice", "email-context", "get"]),
7168
7187
  legacyCommand("preview-qbo-customer-invoice", ["customer-invoice", "preview-qbo"]),
@@ -7182,15 +7201,15 @@ in. Applied changes are finished locally without repeating the provider mutation
7182
7201
  legacyCommand("mark-customer-invoice-sent-externally", ["customer-invoice", "mark-sent-externally"]),
7183
7202
  legacyCommand("list-approvals", ["approval", "list"], ["get-pending-approvals"], [{ name: "--type <type>", description: "Filter budget, supplier, bill, quotation, customer_invoice, or all." }, { name: "--limit <number>", description: "Page size 1\u2013100; default 50." }, { name: "--cursor <token>", description: "Opaque cursor from pageInfo." }, { name: "--direction <direction>", description: "forward (default) or backward; backward requires a cursor." }]),
7184
7203
  legacyCommand("get-pending-approval", ["approval", "get"]),
7185
- legacyCommand("approve-bill", [
7186
- "bill",
7187
- "approve"
7188
- ]),
7204
+ legacyCommand("approve-bill", ["bill", "approve"]),
7189
7205
  legacyCommand("reject-bill", ["bill", "reject"]),
7190
7206
  legacyCommand("approve-budget", ["budget", "approve"]),
7191
7207
  legacyCommand("reject-budget", ["budget", "reject"]),
7192
7208
  legacyCommand("approve-supplier", ["supplier", "approve"]),
7193
- legacyCommand("reject-supplier", ["supplier", "reject"]),
7209
+ legacyCommand(
7210
+ "reject-supplier",
7211
+ ["supplier", "reject"]
7212
+ ),
7194
7213
  legacyCommand("get-supplier-details", ["supplier", "detail", "get"]),
7195
7214
  legacyCommand("get-supplier-overview", ["supplier", "overview", "get"]),
7196
7215
  legacyCommand("get-supplier-usage", ["supplier", "usage", "get"]),
@@ -7226,7 +7245,12 @@ sor; pass nextCursor forward or previousCursor backward unchanged." }, { name: "
7226
7245
  legacyCommand("update-contact-person", ["contact", "update"]),
7227
7246
  legacyCommand("list-suppliers", ["supplier", "list"], [], [{ name: "--name <text>", description: "Filter supplier name or email." }, { name: "--createdBy <csv>", description: "Filter by creator IDs." }, { name: "--gstRegistered <true|false>", description: "Filter GST registration." }, { name: "--status <csv>", description: "Filter approval statuses; ALL means no status filter." }, { name: "--supplierTags <csv>", description: "Filter by supplier tag IDs." }, { name: "--active <true|false>", description: "Active by default; false selects archived." }, { name: "--limit <1-100>", description: "Bounded page size (default 10). Retired page/perPage flags are rejected." }, { name: "--cursor <token>", description: "Opaque nextCursor or previousCursor from items/pageInfo." }, { name: "--direction <forward|backward>", description: "Forward by default; backward requires a cursor." }, { name: "--sortBy <field>", description: "name, email, phone, gstRegistered, status, active, createdAt or updated\
7228
7247
  At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by default." }, { name: "--sort <json>", description: "Ordered {id,desc} array for multi-column sorting; cannot combine with sortBy/sortDir." }]),
7229
- legacyCommand("count-suppliers", ["supplier", "count"], [], [{ name: "--name <text>", description: "Filter supplier name or email." }, { name: "--createdBy <csv>", description: "Filter by creator IDs." }, { name: "--gstRegistered <true|false>", description: "Filter GST registration." }, { name: "--status <csv>", description: "Filter approval statuses." }, { name: "--supplierTags <csv>", description: "Filter by supplier tag IDs." }, { name: "--active <true|false>", description: "Active by default; false selects archived. No pagination/sort flags." }]),
7248
+ legacyCommand(
7249
+ "count-suppliers",
7250
+ ["supplier", "count"],
7251
+ [],
7252
+ [{ name: "--name <text>", description: "Filter supplier name or email." }, { name: "--createdBy <csv>", description: "Filter by creator IDs." }, { name: "--gstRegistered <true|false>", description: "Filter GST registration." }, { name: "--status <csv>", description: "Filter approval statuses." }, { name: "--supplierTags <csv>", description: "Filter by supplier tag IDs." }, { name: "--active <true|false>", description: "Active by default; false selects archived. No pagination/sort flags." }]
7253
+ ),
7230
7254
  legacyCommand("create-supplier", ["supplier", "create"]),
7231
7255
  legacyCommand("update-supplier", ["supplier", "update"]),
7232
7256
  legacyCommand("delete-suppliers", ["supplier", "delete"]),
@@ -7240,20 +7264,25 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7240
7264
  legacyCommand("list-items", ["item", "list"], [], [{ name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort." }, { name: "--direction <forward|backward>", description: "forward (default) or backward; backward needs --cursor." }]),
7241
7265
  legacyCommand("count-items", ["item", "count"]),
7242
7266
  legacyCommand("get-item", ["item", "get"]),
7243
- legacyCommand("get-item-quickbooks-sync-status", ["item", "sync", "status"]),
7267
+ legacyCommand(
7268
+ "get-item-quickbooks-sync-status",
7269
+ ["item", "sync", "status"]
7270
+ ),
7244
7271
  legacyCommand("create-item", ["item", "create"]),
7245
7272
  legacyCommand("update-item", ["item", "update"]),
7246
7273
  legacyCommand("archive-items", ["item", "archive"]),
7247
7274
  legacyCommand("delete-item", ["item", "delete"]),
7248
7275
  legacyCommand("list-item-categories", ["item", "category", "list"], [], [{ name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor (or previousCursor with --direction backward) from the last page, unchanged; keep the same filters and sort." }, { name: "--direction <forward|backward>", description: "forward (default) or backward; backward needs --cursor." }]),
7249
7276
  legacyCommand("count-item-categories", ["item", "category", "count"]),
7250
- legacyCommand(
7251
- "create-item-category",
7252
- ["item", "category", "create"]
7253
- ),
7277
+ legacyCommand("create-item-category", ["item", "category", "create"]),
7254
7278
  legacyCommand("update-item-category", ["item", "category", "update"]),
7255
7279
  legacyCommand("delete-item-categories", ["item", "category", "delete"]),
7256
- legacyCommand("list-users", ["user", "list"], [], [{ name: "--q <text>", description: "Search user names and emails (name A\u2013Z). A bare --q is rejected; use -q/--quiet to hide logs." }, { name: "--projectTeamOnly <true|false>", description: "true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager." }, { name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }]),
7280
+ legacyCommand(
7281
+ "list-users",
7282
+ ["user", "list"],
7283
+ [],
7284
+ [{ name: "--q <text>", description: "Search user names and emails (name A\u2013Z). A bare --q is rejected; use -q/--quiet to hide logs." }, { name: "--projectTeamOnly <true|false>", description: "true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager." }, { name: "--limit <1-100>", description: "Rows per page. Output is { items, pageInfo }." }, { name: "--cursor <token>", description: "pageInfo.nextCursor from the last page, unchanged; pages forward only." }]
7285
+ ),
7257
7286
  legacyCommand("count-users", ["user", "count"]),
7258
7287
  legacyCommand("create-user", ["user", "create"]),
7259
7288
  legacyCommand("create-api-key", ["user", "api-key", "create"]),
@@ -7281,10 +7310,7 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7281
7310
  legacyCommand("update-webhook-endpoint", ["webhook", "endpoint", "update"]),
7282
7311
  legacyCommand("delete-webhook-endpoint", ["webhook", "endpoint", "delete"]),
7283
7312
  legacyCommand("rotate-webhook-secret", ["webhook", "secret", "rotate"]),
7284
- legacyCommand(
7285
- "send-webhook-test-event",
7286
- ["webhook", "endpoint", "test"]
7287
- ),
7313
+ legacyCommand("send-webhook-test-event", ["webhook", "endpoint", "test"]),
7288
7314
  legacyCommand("list-webhook-deliveries", ["webhook", "delivery", "list"], [], [{ name: "--endpointId <id>", description: "Only deliveries to this endpoint." }, { name: "--status <PENDING|SUCCEEDED|FAILED,...>", description: "Comma-separated delivery statuses." }, { name: "--eventType <type>", description: "Exact event type, e.g. bill.approved." }, { name: "--limit <n>", description: "Rows per cursor page (1..100; default 20)." }, { name: "--cursor <token>", description: "Opaque token from pageInfo.nextCursor or pageInfo.previousCursor; bound to the same filters." }, { name: "--direction <value>", description: "forward or backward (default forward; backward requires cursor)." }]),
7289
7315
  legacyCommand("get-webhook-delivery", ["webhook", "delivery", "get"]),
7290
7316
  legacyCommand("replay-webhook-delivery", ["webhook", "delivery", "replay"]),
@@ -7293,12 +7319,7 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7293
7319
  legacyCommand("create-inbound-source", ["inbound", "source", "create"]),
7294
7320
  legacyCommand("get-inbound-source", ["inbound", "source", "get"]),
7295
7321
  legacyCommand("update-inbound-source", ["inbound", "source", "update"]),
7296
- legacyCommand(
7297
- "list-inbound-submissions",
7298
- ["inbound", "submission", "list"],
7299
- [],
7300
- [{ name: "--limit <number>", description: "Page size from 1 to 100 (default 25). Returns submissions, hasMore and nextCursor; no total." }, { name: "--cursor <token>", description: "Pass the previous response's nextCursor unchanged. Omit for newest submissions. Replaces --page/--perPage." }, { name: "--sourceId <id>", description: "Filter submissions to this source; keep the same filter while following cursors." }]
7301
- ),
7322
+ legacyCommand("list-inbound-submissions", ["inbound", "submission", "list"], [], [{ name: "--limit <number>", description: "Page size from 1 to 100 (default 25). Returns submissions, hasMore and nextCursor; no total." }, { name: "--cursor <token>", description: "Pass the previous response's nextCursor unchanged. Omit for newest submissions. Replaces --page/--perPage." }, { name: "--sourceId <id>", description: "Filter submissions to this source; keep the same filter while following cursors." }]),
7302
7323
  legacyCommand("count-inbound-submissions", ["inbound", "submission", "count"], [], [{ name: "--sourceId <id>", description: "Optional source filter. Returns an independently calculated exact totalCount, not a list snapshot." }]),
7303
7324
  legacyCommand("get-inbound-submission", ["inbound", "submission", "get"]),
7304
7325
  legacyCommand("save-inbound-mapping", ["inbound", "mapping", "save"]),
@@ -7324,43 +7345,63 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7324
7345
  }
7325
7346
  }
7326
7347
  }, "assertRegistry");
7327
- assertRegistry(
7328
- registry2
7329
- );
7348
+ assertRegistry(registry2);
7330
7349
  var commandRegistry = registry2, resolveCommand = __name2((argv) => {
7331
- const normalizedArgv = argv.map(normalizeToken), canonical = [...commandRegistry].sort((left, right) => right.path.length - left.path.length).find((command) => normalizedPath(command.path).every((segment, index) => normalizedArgv[index] === segment));
7350
+ const normalizedArgv = argv.map(normalizeToken), canonical = [...commandRegistry].sort((left, right) => right.path.length - left.path.length).find((command) => normalizedPath(
7351
+ command.path
7352
+ ).every((segment, index) => normalizedArgv[index] === segment));
7332
7353
  if (canonical) return { command: canonical, argv: argv.slice(canonical.path.length), invokedAs: argv.slice(0, canonical.path.length), isLegacyAlias: !1 };
7333
7354
  const rawAlias = argv[0];
7334
7355
  if (!rawAlias) return;
7335
7356
  const normalizedAlias = normalizeToken(rawAlias), legacy = commandRegistry.find((command) => command.legacyAliases.some((alias) => normalizeToken(alias) === normalizedAlias));
7336
7357
  if (legacy) return { command: legacy, argv: argv.slice(1), invokedAs: [rawAlias], isLegacyAlias: !0 };
7337
7358
  }, "resolveCommand"), updateBeforeUse = "First step before each task: update to the latest published release with 'bun add --global @go-labs-sg/bb@latest', then run 'bb version' and 'bb --help' before using commands. Update once per task. If updating fails, stop and report it. Preserve an explicitly requested pinned or development/staging version.", createHumanHelp = __name2((command) => {
7338
- if (command) return [updateBeforeUse, "", "Usage: bb ".concat(command.path.join(" "), " [options] [args]"), "", command.summary, "", "Legacy aliases: ".concat(command.legacyAliases.join(", ")), "", "Options", ...command.options.map((option) => " ".concat(option.name, "\n ").concat(option.description)), "", ...formatPayloadHelp(command.legacyTarget ?? ""), "Use `bb help --legacy` for additional command arguments."].join("\n");
7359
+ if (command) return [
7360
+ updateBeforeUse,
7361
+ "",
7362
+ "Usage: bb ".concat(command.path.join(" "), " [options] [args]"),
7363
+ "",
7364
+ command.summary,
7365
+ "",
7366
+ "Legacy aliases: ".concat(command.legacyAliases.join(", ")),
7367
+ "",
7368
+ "Options",
7369
+ ...command.options.map((option) => " ".concat(option.name, "\n ").concat(option.description)),
7370
+ "",
7371
+ ...formatPayloadHelp(command.legacyTarget ?? ""),
7372
+ "Use `bb help --legacy` for additional command arguments."
7373
+ ].join("\n");
7339
7374
  const lines = commandRegistry.map((command2) => {
7340
7375
  const canonical = "bb ".concat(command2.path.join(" ")), aliases = command2.legacyAliases.filter((alias) => alias.includes("-")).map((alias) => "bb ".concat(alias)).join(", ");
7341
7376
  return " ".concat(canonical, "\n ").concat(command2.summary).concat(aliases ? " Legacy: ".concat(aliases, ".") : "");
7342
7377
  });
7343
7378
  return ["bb \u2014 Budget Builder CLI", "", updateBeforeUse, "", "Usage: bb <resource> <operation> [options] [args]", "", "Global options", ...globalCommandOptions.map((option) => " ".concat(option.name, "\n ").concat(option.description)), "", "Canonical commands", ...lines, "", "Use `bb completion <shell>` to generate shell completion scripts."].join("\n");
7344
- }, "createHumanHelp"), completionWords = __name2(() => {
7345
- const words = /* @__PURE__ */ new Set();
7346
- for (const command of commandRegistry) {
7347
- for (const segment of command.path) words.add(segment);
7348
- for (const alias of command.legacyAliases) words.add(alias);
7349
- }
7350
- return words.add("help"), words.add("version"), words.add("completion"), [...words].sort();
7351
- }, "completionWords"), createCompletionScript = __name2((shell) => {
7352
- const words = completionWords().join(" ");
7353
- switch (shell) {
7354
- case "bash":
7355
- return "# bash completion for bb\n_bb() {\n COMPREPLY=( $(compgen -W '".concat(words, '\' -- "${COMP_WORDS[COMP_CWORD]}") )\n}\ncomplete -F _bb bb\n');
7356
- case "zsh":
7357
- return "#compdef bb\n_bb() {\n local -a commands\n commands=(".concat(words, ")\n _describe 'bb command' commands\n}\ncompdef _bb bb\n");
7358
- case "fish":
7359
- return completionWords().map((word) => "complete -c bb -f -a '".concat(word, "'")).join("\n").concat("\n");
7360
- case "powershell":
7361
- return "Register-ArgumentCompleter -Native -CommandName bb -ScriptBlock {\n param($wordToComplete)\n '".concat(words, "'.Split(' ') | Where-Object { $_ -like \"$wordToComplete*\" }\n}\n");
7362
- }
7363
- }, "createCompletionScript"), SUPPLIER_ANALYTICS_SORT_IDS = ["name", "gstRegistered", "status", "phone", "email", "updatedAt", "createdAt"];
7379
+ }, "createHumanHelp"), completionWords = __name2(
7380
+ () => {
7381
+ const words = /* @__PURE__ */ new Set();
7382
+ for (const command of commandRegistry) {
7383
+ for (const segment of command.path) words.add(segment);
7384
+ for (const alias of command.legacyAliases) words.add(alias);
7385
+ }
7386
+ return words.add("help"), words.add("version"), words.add("completion"), [...words].sort();
7387
+ },
7388
+ "completionWords"
7389
+ ), createCompletionScript = __name2(
7390
+ (shell) => {
7391
+ const words = completionWords().join(" ");
7392
+ switch (shell) {
7393
+ case "bash":
7394
+ return "# bash completion for bb\n_bb() {\n COMPREPLY=( $(compgen -W '".concat(words, '\' -- "${COMP_WORDS[COMP_CWORD]}") )\n}\ncomplete -F _bb bb\n');
7395
+ case "zsh":
7396
+ return "#compdef bb\n_bb() {\n local -a commands\n commands=(".concat(words, ")\n _describe 'bb command' commands\n}\ncompdef _bb bb\n");
7397
+ case "fish":
7398
+ return completionWords().map((word) => "complete -c bb -f -a '".concat(word, "'")).join("\n").concat("\n");
7399
+ case "powershell":
7400
+ return "Register-ArgumentCompleter -Native -CommandName bb -ScriptBlock {\n param($wordToComplete)\n '".concat(words, "'.Split(' ') | Where-Object { $_ -like \"$wordToComplete*\" }\n}\n");
7401
+ }
7402
+ },
7403
+ "createCompletionScript"
7404
+ ), SUPPLIER_ANALYTICS_SORT_IDS = ["name", "gstRegistered", "status", "phone", "email", "updatedAt", "createdAt"];
7364
7405
  function parsePositiveIntFlag(value, flagName) {
7365
7406
  if (value === void 0) return;
7366
7407
  const parsed = Number.parseInt(String(value), 10);
@@ -7389,35 +7430,25 @@ var COMPANY_SORT_FIELDS = ["name", "createdAt"], COMPANY_SORT_DIRECTIONS = ["asc
7389
7430
  if (value === void 0) return "forward";
7390
7431
  if (value !== "forward" && value !== "backward") throw new Error('--direction must be "forward" or "backward".');
7391
7432
  return value;
7392
- }, "parseCompanyDirection"), parseCompanyListFlags = __name2((flags) => {
7393
- rejectCompanyPageFlags(flags, "list");
7394
- for (const key of ["name", "createdBy", "createdByIds", "active", "limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7395
- const cursor = getFlag(flags, "cursor"), direction = parseCompanyDirection(getFlag(flags, "direction"));
7396
- if (direction === "backward" && cursor === void 0) throw new Error("--direction backward requires --cursor <token>.");
7397
- if (cursor === "") throw new Error("--cursor requires a non-empty token.");
7398
- return {
7399
- name: getFlag(flags, "name"),
7400
- createdBy: getFlag(flags, "createdBy"),
7401
- createdByIds: parseCommaSeparatedIds(getFlag(flags, "createdByIds")),
7402
- active: parseOptionalBoolFlag(flags, "active"),
7403
- limit: parseCompanyLimit(getFlag(flags, "limit")),
7404
- cursor,
7405
- direction,
7406
- sortBy: parseCompanySortBy(getFlag(flags, "sortBy")),
7407
- sortDir: parseCompanySortDir(getFlag(flags, "sortDir"))
7408
- };
7409
- }, "parseCompanyListFlags"), parseCompanyCountFlags = __name2((flags) => {
7433
+ }, "parseCompanyDirection"), parseCompanyListFlags = __name2(
7434
+ (flags) => {
7435
+ rejectCompanyPageFlags(flags, "list");
7436
+ for (const key of ["name", "createdBy", "createdByIds", "active", "limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7437
+ const cursor = getFlag(flags, "cursor"), direction = parseCompanyDirection(getFlag(flags, "direction"));
7438
+ if (direction === "backward" && cursor === void 0) throw new Error("--direction backward requires --cursor <token>.");
7439
+ if (cursor === "") throw new Error("--cursor requires a non-empty token.");
7440
+ return { name: getFlag(flags, "name"), createdBy: getFlag(flags, "createdBy"), createdByIds: parseCommaSeparatedIds(getFlag(flags, "createdByIds")), active: parseOptionalBoolFlag(flags, "active"), limit: parseCompanyLimit(getFlag(flags, "limit")), cursor, direction, sortBy: parseCompanySortBy(getFlag(flags, "sortBy")), sortDir: parseCompanySortDir(getFlag(flags, "sortDir")) };
7441
+ },
7442
+ "parseCompanyListFlags"
7443
+ ), parseCompanyCountFlags = __name2((flags) => {
7410
7444
  rejectCompanyPageFlags(flags, "count");
7411
7445
  for (const key of ["name", "createdBy", "createdByIds", "active", "limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7412
7446
  if (flags.limit !== void 0 || flags.cursor !== void 0 || flags.direction !== void 0) throw new Error("company count does not accept list pagination flags.");
7413
7447
  if (flags.sortBy !== void 0 || flags.sortDir !== void 0) throw new Error("company count does not accept list sorting flags.");
7414
7448
  return { name: getFlag(flags, "name"), createdBy: getFlag(flags, "createdBy"), createdByIds: parseCommaSeparatedIds(getFlag(flags, "createdByIds")), active: parseOptionalBoolFlag(flags, "active") };
7415
- }, "parseCompanyCountFlags"), PROJECT_SORT_FIELDS = ["name", "createdAt", "status", "companyName", "wonAt"], PROJECT_SORT_DIRECTIONS = ["asc", "desc"], PROJECT_PAGE_FLAGS = ["page", "perPage", "pageSize", "page-size", "per-page", "page_size", "per_page"], rejectProjectPageFlags = __name2(
7416
- (flags, command) => {
7417
- for (const key of PROJECT_PAGE_FLAGS) if (flags[key] !== void 0) throw new Error("--".concat(key, " is not supported by project ").concat(command, "; use --limit and --cursor for list or project count for totals."));
7418
- },
7419
- "rejectProjectPageFlags"
7420
- ), parseProjectLimit = __name2((value) => {
7449
+ }, "parseCompanyCountFlags"), PROJECT_SORT_FIELDS = ["name", "createdAt", "status", "companyName", "wonAt"], PROJECT_SORT_DIRECTIONS = ["asc", "desc"], PROJECT_PAGE_FLAGS = ["page", "perPage", "pageSize", "page-size", "per-page", "page_size", "per_page"], rejectProjectPageFlags = __name2((flags, command) => {
7450
+ for (const key of PROJECT_PAGE_FLAGS) if (flags[key] !== void 0) throw new Error("--".concat(key, " is not supported by project ").concat(command, "; use --limit and --cursor for list or project count for totals."));
7451
+ }, "rejectProjectPageFlags"), parseProjectLimit = __name2((value) => {
7421
7452
  if (value === void 0) return 20;
7422
7453
  const parsed = Number(String(value));
7423
7454
  if (!Number.isInteger(parsed) || parsed < 1 || parsed > 100) throw new Error("--limit must be an integer from 1 to 100.");
@@ -7430,12 +7461,15 @@ var COMPANY_SORT_FIELDS = ["name", "createdAt"], COMPANY_SORT_DIRECTIONS = ["asc
7430
7461
  if (value === void 0) return "desc";
7431
7462
  if (!PROJECT_SORT_DIRECTIONS.includes(value)) throw new Error('Invalid --sortDir "'.concat(value, '". Use one of: ').concat(PROJECT_SORT_DIRECTIONS.join(", "), "."));
7432
7463
  return value;
7433
- }, "parseProjectSortDir"), parseProjectWonWithinDays = __name2((value) => {
7434
- if (value === void 0) return;
7435
- const parsed = Number(value);
7436
- if (!Number.isInteger(parsed) || parsed < 1 || parsed > 3650) throw new Error("--wonWithinDays must be an integer from 1 to 3650.");
7437
- return parsed;
7438
- }, "parseProjectWonWithinDays"), parseProjectDirection = __name2((value) => {
7464
+ }, "parseProjectSortDir"), parseProjectWonWithinDays = __name2(
7465
+ (value) => {
7466
+ if (value === void 0) return;
7467
+ const parsed = Number(value);
7468
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 3650) throw new Error("--wonWithinDays must be an integer from 1 to 3650.");
7469
+ return parsed;
7470
+ },
7471
+ "parseProjectWonWithinDays"
7472
+ ), parseProjectDirection = __name2((value) => {
7439
7473
  if (value === void 0) return "forward";
7440
7474
  if (value !== "forward" && value !== "backward") throw new Error('--direction must be "forward" or "backward".');
7441
7475
  return value;
@@ -7445,13 +7479,19 @@ var COMPANY_SORT_FIELDS = ["name", "createdAt"], COMPANY_SORT_DIRECTIONS = ["asc
7445
7479
  const cursor = getFlag(flags, "cursor"), direction = parseProjectDirection(getFlag(flags, "direction"));
7446
7480
  if (direction === "backward" && cursor === void 0) throw new Error("--direction backward requires --cursor <token>.");
7447
7481
  if (cursor === "") throw new Error("--cursor requires a non-empty token.");
7448
- return { companyId: getFlag(flags, "companyId"), name: getFlag(flags, "name"), status: parseOptionalExtendedProjectStatus(getFlag(flags, "status")), statuses: parseCommaSeparatedProjectStatuses(getFlag(flags, "statuses")), active: parseOptionalBoolFlag(flags, "active"), wonFrom: parseOptionalIsoDateFlag(getFlag(flags, "wonFrom"), "--wonFrom"), wonTo: parseOptionalIsoDateFlag(getFlag(flags, "wonTo"), "--wonTo", { endOfDay: !0 }), wonWithinDays: parseProjectWonWithinDays(getFlag(flags, "wonWithinDays")), limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sortBy: parseProjectSortBy(getFlag(flags, "sortBy")), sortDir: parseProjectSortDir(getFlag(flags, "sortDir")) };
7482
+ return { companyId: getFlag(flags, "companyId"), name: getFlag(flags, "name"), status: parseOptionalExtendedProjectStatus(getFlag(flags, "status")), statuses: parseCommaSeparatedProjectStatuses(getFlag(flags, "statuses")), active: parseOptionalBoolFlag(
7483
+ flags,
7484
+ "active"
7485
+ ), wonFrom: parseOptionalIsoDateFlag(getFlag(flags, "wonFrom"), "--wonFrom"), wonTo: parseOptionalIsoDateFlag(getFlag(flags, "wonTo"), "--wonTo", { endOfDay: !0 }), wonWithinDays: parseProjectWonWithinDays(getFlag(flags, "wonWithinDays")), limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sortBy: parseProjectSortBy(getFlag(flags, "sortBy")), sortDir: parseProjectSortDir(getFlag(flags, "sortDir")) };
7449
7486
  }, "parseProjectListFlags"), parseProjectCountFlags = __name2((flags) => {
7450
7487
  rejectProjectPageFlags(flags, "count");
7451
7488
  for (const key of ["companyId", "name", "status", "statuses", "active", "wonFrom", "wonTo", "wonWithinDays", "limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7452
7489
  if (flags.limit !== void 0 || flags.cursor !== void 0 || flags.direction !== void 0) throw new Error("project count does not accept list pagination flags.");
7453
7490
  if (flags.sortBy !== void 0 || flags.sortDir !== void 0) throw new Error("project count does not accept list sorting flags.");
7454
- return { companyId: getFlag(flags, "companyId"), name: getFlag(flags, "name"), status: parseOptionalExtendedProjectStatus(getFlag(flags, "status")), statuses: parseCommaSeparatedProjectStatuses(getFlag(flags, "statuses")), active: parseOptionalBoolFlag(flags, "active"), wonFrom: parseOptionalIsoDateFlag(getFlag(flags, "wonFrom"), "--wonFrom"), wonTo: parseOptionalIsoDateFlag(getFlag(flags, "wonTo"), "--wonTo", { endOfDay: !0 }), wonWithinDays: parseProjectWonWithinDays(getFlag(flags, "wonWithinDays")) };
7491
+ return { companyId: getFlag(flags, "companyId"), name: getFlag(
7492
+ flags,
7493
+ "name"
7494
+ ), status: parseOptionalExtendedProjectStatus(getFlag(flags, "status")), statuses: parseCommaSeparatedProjectStatuses(getFlag(flags, "statuses")), active: parseOptionalBoolFlag(flags, "active"), wonFrom: parseOptionalIsoDateFlag(getFlag(flags, "wonFrom"), "--wonFrom"), wonTo: parseOptionalIsoDateFlag(getFlag(flags, "wonTo"), "--wonTo", { endOfDay: !0 }), wonWithinDays: parseProjectWonWithinDays(getFlag(flags, "wonWithinDays")) };
7455
7495
  }, "parseProjectCountFlags");
7456
7496
  function parseOptionalBoolFlag(flags, key) {
7457
7497
  const v = flags[key];
@@ -7468,7 +7508,8 @@ function parseBudgetActiveFlag(flags) {
7468
7508
  if (raw === !0) throw new Error("--active requires true, false, or all.");
7469
7509
  const value = String(raw).toLowerCase();
7470
7510
  if (value === "all") return "all";
7471
- if (value === "true" || value === "1") return !0;
7511
+ if (value === "true" || value === "1")
7512
+ return !0;
7472
7513
  if (value === "false" || value === "0") return !1;
7473
7514
  throw new Error("--active must be true, false, or all.");
7474
7515
  }
@@ -7483,9 +7524,7 @@ __name(parseCustomerInvoiceSortBy, "parseCustomerInvoiceSortBy"), __name2(parseC
7483
7524
  function parseCommercialRejectionProjectStatus(flags) {
7484
7525
  const raw = flags.projectStatusOnCommercialRejection;
7485
7526
  if (raw === void 0) return;
7486
- if (raw === !0) throw new Error(
7487
- "--projectStatusOnCommercialRejection requires PITCH or LOST."
7488
- );
7527
+ if (raw === !0) throw new Error("--projectStatusOnCommercialRejection requires PITCH or LOST.");
7489
7528
  const status = String(raw).toUpperCase();
7490
7529
  if (status === ProjectStatus2.PITCH || status === ProjectStatus2.LOST) return status;
7491
7530
  throw new Error("--projectStatusOnCommercialRejection must be PITCH or LOST.");
@@ -7499,10 +7538,7 @@ var rejectRetiredPageFlags = __name2((flags) => {
7499
7538
  rejectRetiredPageFlags(flags);
7500
7539
  for (const key of ["limit", "cursor"]) rejectBareFlag(flags, key);
7501
7540
  if (flags.direction !== void 0) throw new Error("".concat(command, " pages forward only; follow pageInfo.nextCursor with --cursor."));
7502
- const cursor = getFlag(
7503
- flags,
7504
- "cursor"
7505
- );
7541
+ const cursor = getFlag(flags, "cursor");
7506
7542
  if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7507
7543
  const limitFlag = getFlag(flags, "limit"), limit = limitFlag === void 0 ? void 0 : Number(limitFlag);
7508
7544
  if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > maxLimit)) throw new Error("--limit must be an integer from 1 to ".concat(maxLimit, "."));
@@ -7510,13 +7546,12 @@ var rejectRetiredPageFlags = __name2((flags) => {
7510
7546
  }, "parseDetailFeedPage"), parseBillFilterFlags = __name2((flags) => {
7511
7547
  const statusRaw = getFlag(flags, "status"), createdByIdsRaw = getFlag(flags, "createdByIds"), searchRaw = getFlag(flags, "search");
7512
7548
  return { projectId: getFlag(flags, "projectId"), budgetId: getFlag(flags, "budgetId"), statuses: parseCommaSeparatedBillStatuses(statusRaw !== void 0 ? String(statusRaw) : void 0), search: searchRaw !== void 0 ? String(searchRaw) : void 0, isClaimable: parseOptionalBoolFlag(flags, "isClaimable"), createdByIds: parseCommaSeparatedIds(createdByIdsRaw !== void 0 ? String(createdByIdsRaw) : void 0) };
7513
- }, "parseBillFilterFlags"), parseQuotationFilterFlags = __name2(
7514
- (flags) => {
7515
- const createdByRaw = getFlag(flags, "createdBy") ?? getFlag(flags, "requesterIds"), searchRaw = getFlag(flags, "search");
7516
- return { projectId: getFlag(flags, "projectId"), budgetId: getFlag(flags, "budgetId"), supplierId: getFlag(flags, "supplierId"), status: parseCommaSeparatedQuotationStatuses(getFlag(flags, "status")), createdBy: parseCommaSeparatedIds(createdByRaw), search: searchRaw !== void 0 && String(searchRaw).trim() || void 0 };
7517
- },
7518
- "parseQuotationFilterFlags"
7519
- );
7549
+ }, "parseBillFilterFlags"), parseQuotationFilterFlags = __name2((flags) => {
7550
+ const createdByRaw = getFlag(flags, "createdBy") ?? getFlag(flags, "requesterIds"), searchRaw = getFlag(flags, "search");
7551
+ return { projectId: getFlag(flags, "projectId"), budgetId: getFlag(flags, "budgetId"), supplierId: getFlag(flags, "supplierId"), status: parseCommaSeparatedQuotationStatuses(
7552
+ getFlag(flags, "status")
7553
+ ), createdBy: parseCommaSeparatedIds(createdByRaw), search: searchRaw !== void 0 && String(searchRaw).trim() || void 0 };
7554
+ }, "parseQuotationFilterFlags");
7520
7555
  function parseListBillsFlags(flags) {
7521
7556
  rejectRetiredPageFlags(flags);
7522
7557
  for (const key of ["limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
@@ -7526,7 +7561,10 @@ function parseListBillsFlags(flags) {
7526
7561
  if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7527
7562
  return { ...parseBillFilterFlags(flags), sortBy: parseOptionalBillListSortBy(sortByRaw !== void 0 ? String(sortByRaw) : void 0), sortDir: parseOptionalBillListSortDir(sortDirRaw !== void 0 ? String(sortDirRaw) : void 0), limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction };
7528
7563
  }
7529
- __name(parseListBillsFlags, "parseListBillsFlags"), __name2(parseListBillsFlags, "parseListBillsFlags");
7564
+ __name(parseListBillsFlags, "parseListBillsFlags"), __name2(
7565
+ parseListBillsFlags,
7566
+ "parseListBillsFlags"
7567
+ );
7530
7568
  function parseCountBillsFlags(flags) {
7531
7569
  rejectRetiredPageFlags(flags);
7532
7570
  for (const key of ["limit", "cursor", "direction", "sortBy", "sortDir"]) if (flags[key] !== void 0) throw new Error("bill count does not accept --".concat(key, "; totals use filters only."));
@@ -7542,15 +7580,16 @@ function parseOptionalSupplierSortBy(raw) {
7542
7580
  }
7543
7581
  __name(parseOptionalSupplierSortBy, "parseOptionalSupplierSortBy"), __name2(parseOptionalSupplierSortBy, "parseOptionalSupplierSortBy");
7544
7582
  var parseSupplierFilters = __name2((flags) => {
7545
- for (const key of ["name", "createdBy", "gstRegistered", "status", "supplierTags", "active"]) rejectBareFlag(flags, key);
7583
+ for (const key of ["name", "createdBy", "gstRegistered", "status", "supplierTags", "active"]) rejectBareFlag(
7584
+ flags,
7585
+ key
7586
+ );
7546
7587
  return { name: getFlag(flags, "name"), createdBy: parseCommaSeparatedIds(getFlag(flags, "createdBy")), gstRegistered: parseOptionalBoolFlag(flags, "gstRegistered") ?? null, status: parseCommaSeparatedSupplierStatuses(getFlag(flags, "status")), supplierTags: parseCommaSeparatedIds(getFlag(flags, "supplierTags")), active: parseOptionalBoolFlag(flags, "active") ?? !0 };
7547
7588
  }, "parseSupplierFilters"), rejectSupplierPageFlags = __name2((flags) => {
7548
7589
  for (const key of PROJECT_PAGE_FLAGS) if (flags[key] !== void 0) throw new Error("--".concat(key, " is retired for suppliers; use --limit/--cursor or supplier count for totals."));
7549
7590
  }, "rejectSupplierPageFlags"), parseSupplierListSortEntries = __name2((sortRaw) => {
7550
7591
  const parsed = parseJsonFlag(sortRaw, "--sort");
7551
- if (!Array.isArray(
7552
- parsed
7553
- ) || parsed.length > 8) throw new Error("--sort must be a JSON array of at most eight {id, desc} entries.");
7592
+ if (!Array.isArray(parsed) || parsed.length > 8) throw new Error("--sort must be a JSON array of at most eight {id, desc} entries.");
7554
7593
  return parsed.map((item) => {
7555
7594
  if (typeof item != "object" || item === null || !("id" in item) || !("desc" in item) || typeof item.id != "string" || typeof item.desc != "boolean" || Object.keys(item).some((key) => key !== "id" && key !== "desc")) throw new Error("Invalid --sort entry; use {id, desc}.");
7556
7595
  const id = parseOptionalSupplierSortBy(item.id);
@@ -7565,26 +7604,25 @@ var parseSupplierFilters = __name2((flags) => {
7565
7604
  }
7566
7605
  const sortBy = parseOptionalSupplierSortBy(getFlag(flags, "sortBy")), sortDir = parseOptionalBillListSortDir(getFlag(flags, "sortDir"));
7567
7606
  return [{ id: sortBy ?? "createdAt", desc: (sortDir ?? "desc") === "desc" }];
7568
- }, "parseSupplierListSort"), parseListSuppliersFlags = __name2(
7569
- (flags) => {
7570
- rejectSupplierPageFlags(flags);
7571
- for (const key of ["limit", "cursor", "direction", "sort", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7572
- const limit = getFlag(flags, "limit") === void 0 ? 10 : parseProjectLimit(getFlag(flags, "limit")), cursor = getFlag(flags, "cursor");
7573
- if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7574
- const direction = parseProjectDirection(getFlag(flags, "direction"));
7575
- if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7576
- const sort = parseSupplierListSort(flags);
7577
- return { ...parseSupplierFilters(flags), limit, cursor, direction, sort };
7578
- },
7579
- "parseListSuppliersFlags"
7580
- ), parseCountSuppliersFlags = __name2((flags) => {
7607
+ }, "parseSupplierListSort"), parseListSuppliersFlags = __name2((flags) => {
7608
+ rejectSupplierPageFlags(flags);
7609
+ for (const key of ["limit", "cursor", "direction", "sort", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7610
+ const limit = getFlag(flags, "limit") === void 0 ? 10 : parseProjectLimit(getFlag(flags, "limit")), cursor = getFlag(flags, "cursor");
7611
+ if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7612
+ const direction = parseProjectDirection(getFlag(flags, "direction"));
7613
+ if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7614
+ const sort = parseSupplierListSort(flags);
7615
+ return { ...parseSupplierFilters(flags), limit, cursor, direction, sort };
7616
+ }, "parseListSuppliersFlags"), parseCountSuppliersFlags = __name2((flags) => {
7581
7617
  rejectSupplierPageFlags(flags);
7582
7618
  for (const key of ["limit", "cursor", "direction", "sort", "sortBy", "sortDir"]) if (flags[key] !== void 0) throw new Error("supplier count does not accept --".concat(key, "; totals use filters only."));
7583
7619
  return parseSupplierFilters(flags);
7584
7620
  }, "parseCountSuppliersFlags");
7585
7621
  function parseDashboardQueryFlags(flags) {
7586
7622
  const roleRaw = getFlag(flags, "role"), timeFrameRaw = getFlag(flags, "timeFrame");
7587
- return { userId: getFlag(flags, "userId"), role: parseOptionalDashboardRole(roleRaw !== void 0 ? String(roleRaw) : void 0), deals: parseOptionalDeals(getFlag(flags, "deals")), timeFrame: parseOptionalTimeFrame(timeFrameRaw !== void 0 ? String(timeFrameRaw) : void 0), startDate: getFlag(flags, "startDate"), endDate: getFlag(flags, "endDate") };
7623
+ return { userId: getFlag(flags, "userId"), role: parseOptionalDashboardRole(roleRaw !== void 0 ? String(roleRaw) : void 0), deals: parseOptionalDeals(
7624
+ getFlag(flags, "deals")
7625
+ ), timeFrame: parseOptionalTimeFrame(timeFrameRaw !== void 0 ? String(timeFrameRaw) : void 0), startDate: getFlag(flags, "startDate"), endDate: getFlag(flags, "endDate") };
7588
7626
  }
7589
7627
  __name(parseDashboardQueryFlags, "parseDashboardQueryFlags"), __name2(parseDashboardQueryFlags, "parseDashboardQueryFlags");
7590
7628
  function printLegacyHelp(runtime) {
@@ -7620,14 +7658,11 @@ ks vendor: quickBooksSyncQueued, operationId)\n update-supplier --pa
7620
7658
  json>' (item.updateItem; must include id)\n archive-items --ids <csv> (item.archiveItems; Budget Builder only; max 100; users can archive their own items, leads/admins any item; open estimates retain snapshot lines and require resolution before send/acceptance)\n delete-item <id> (item.deleteItem; admin; archives in Budget Builder and makes the item inactive in QuickBooks; blocked while used by an open estimate)\n get-supplier-details <supplierId>\n get-supplier-overview <supplierId> (supplier.getSupplierOverview; profile, approvals, attachments and tab counts; no usage or items)\n get-supplier-usage <supplierId> (supplier.getSupplierUsage; usage rows and spending)\n get-supplier-items <supplierId> (supplier.getSupplierItems; inventory items)\n get-supplier-analytics [--name] [--status CSV] [--gstRegistered true|false] [--createdBy <text>] [--timeFrame ALL|LAST_YEAR|LAST_6_MONTHS|LAST_3_MONTHS|CUSTOM] [--startDate <ISO> --endDate <ISO>] [--sortB\
7621
7659
  y name|gstRegistered|status|phone|email|updatedAt|createdAt] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Admin. Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n count-supplier-analytics [--name] [--status] [--gstRegistered] [--createdBy] [--timeFrame] [--startDate --endDate] Admin. totalCount for the same filters\n list-items [--name] [--includeQuickBooksDeactivationPending true] [--sortBy createdAt|updatedAt|name|cost|itemCategory|supplier] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n count-items [same filter flags as list-items] total plus category and supplier facets\n get-item <id>\n get-item-quickbooks-sync-status <itemId> (saved status only; no provi\
7622
7660
  der call or polling)\n list-item-categories [--name] [--sortBy createdAt|name|itemCount|createdBy] [--sortDir asc|desc] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Active categories only; returns { items, pageInfo }. Follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n count-item-categories [--name] totalCount of active categories\n create-item-category --name (admin; saves the category and queues its QuickBooks create: quickBooksSyncQueued, operationId)\n update-item-category --id --name (authenticated; renames in BB now and queues the QuickBooks rename: quickBooksSyncQueued, operationId)\n delete-item-categories --ids <csv> (itemCategory.deleteItemCategories; admin; empty categories only)\n\nDashboard & users\n whoami Show the user identity and role for the active API key.\n list-users [--q] [--projectTeamOnly true|false] [--limit 1-100] [--cursor <t\
7623
- oken>]\n Name A\u2013Z. Returns { items, pageInfo }; follow nextCursor with the same --q and --projectTeamOnly. --page/--perPage are rejected.\n --projectTeamOnly true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager.\n count-users [--q] [--projectTeamOnly true|false] totalCount for the same search\n create-user --email <email> [--name <name>] [--role ").concat(
7624
- userRolesForHelp.join("|"),
7625
- '] (admin; API-only service identity with no Google sign-in)\n create-api-key --name <label> [--userId <userId>] (defaults to the caller; admin required for another user; raw key is shown once)\n list-api-keys [--userId <userId>] [--limit 1-100] [--cursor <token>] (newest first, { items, pageInfo }; defaults to the caller; admin required for another user)\n revoke-api-key <apiKeyId> [--userId <userId>] (defaults to the caller; admin required for another user)\n get-user-performance [--userId] (admin)\n get-dashboard [--userId] [--role BD|CREATOR|INSIDE_SALES|ALL] [--deals ALL|SUCCESSFUL|LOST] [--timeFrame] [--startDate] [--endDate] (admin)\n get-monthly-metrics [same optional flags as get-dashboard] (admin; dashboard.getMonthlyMetrics)\n get-system-overview [same optional flags as get-dashboard] (admin; dashboard.getSystemOverview)\n get-estimate-performance [same optional flags as get-dashboard] (admin; dashboar\
7626
- d.getEstimatePerformance)\n get-financial-overview [same optional flags as dashboard; role uses BudgetRole enum] (admin)\n\nErrors\n get-recent-errors [--cursor] [--direction forward|backward] [--limit] [--severity] [--status] [--timeFrame] (admin)\n count-errors [--severity] [--status] [--timeFrame] (admin)\n get-error <errorId> Full diagnostics: stack, cause, request, metadata (admin)\n get-error-metrics (admin)\n\nAutomation (admin)\n list-integration-operations [--search] [--destination <provider,...>] [--status <PENDING|PROCESSING|FAILED|COMPLETED,...>] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Newest first; returns { items, pageInfo }. Follow nextCursor/previousCursor with the same filters. --page/--perPage are rejected.\n count-integration-operations [same filter flags] provider filter options only (no total; filters do not change the result)\n get-integration-operation <operationId> (one job: who queued it\
7627
- , what it is for, saved progress, Retry state)\n retry-integration-operation <operationId> [--confirmExternalStateReconciled true|false] [--outboundEmailResolution ACCEPTED|NOT_ACCEPTED_RETRY] [--providerMessageId <id>] (QuickBooks jobs with a saved attempt check QuickBooks first: applied changes finish without resending, unapplied ones are sent again)\n reconcile-resource-operation <operationId> (admin: check a QuickBooks invoice/company/item job outcome without retrying; same check Retry runs first)\n\nWebhooks (admin)\n list-webhook-event-types (event catalogue: type, group, live|planned)\n list-webhook-endpoints\n get-webhook-endpoint <endpointId>\n create-webhook-endpoint --name <name> --url <https-url> --events <type|prefix.*|*,...> [--enabled true|false] (prints the signing secret once)\n update-webhook-endpoint <endpointId> [--name] [--url] [--events <...>] [--enabled true|false]\n delete-webhook-endpoint <endpointId>\n rotate-webhook-secret <endpointId> [--previousSecretTtl\
7628
- Hours <0-168>] (prints the new secret once)\n send-webhook-test-event <endpointId>\n list-webhook-deliveries [--endpointId] [--status <PENDING|SUCCEEDED|FAILED,...>] [--eventType] [--limit 1-100] [--cursor <token>] [--direction forward|backward] (newest first; prints items + pageInfo)\n get-webhook-delivery <deliveryId> (attempts with response codes)\n replay-webhook-delivery <deliveryId> (same eventId, new attempt chain)\n\nHistorical / benchmarks\n get-approved-budgets [--projectId] [--limit] [--minRevenue] [--maxRevenue]\n get-budget-category-benchmarks <categoryId> [--limit]\n get-item-pricing-history [--itemName] [--categoryId] [--supplierId] [--limit]\n get-supplier-pricing-history <supplierId> [--itemCategoryId] [--limit]\n\nOutput: JSON to stdout. Errors to stderr; exit 1 on failure.\n\nMCP parity: every MCP tool maps to one command above. The CLI also exposes\n reorder-budget-items and update-budget-item-supplier (web UI\u2013oriented tRPC).\n You may use MCP-style snake_case\
7629
- (e.g. bb list_bills) \u2014 normalized to kebab-case.\n\nNote: MCP also exposes a Prisma schema resource; the CLI has no equivalent.\n\nNot covered vs MCP get_budget: "get-budget" also fetches line items in one call.\n'
7630
- ).trim();
7661
+ oken>]\n Name A\u2013Z. Returns { items, pageInfo }; follow nextCursor with the same --q and --projectTeamOnly. --page/--perPage are rejected.\n --projectTeamOnly true lists only active @getout.sg users, the only accounts accepted as Inside Sales, Business Development or Project Manager.\n count-users [--q] [--projectTeamOnly true|false] totalCount for the same search\n create-user --email <email> [--name <name>] [--role ").concat(userRolesForHelp.join("|"), '] (admin; API-only service identity with no Google sign-in)\n create-api-key --name <label> [--userId <userId>] (defaults to the caller; admin required for another user; raw key is shown once)\n list-api-keys [--userId <userId>] [--limit 1-100] [--cursor <token>] (newest first, { items, pageInfo }; defaults to the caller; admin required for another user)\n revoke-api-key <apiKeyId> [--userId <userId>] (defaults to the caller; admin required for another user)\n g\
7662
+ et-user-performance [--userId] (admin)\n get-dashboard [--userId] [--role BD|CREATOR|INSIDE_SALES|ALL] [--deals ALL|SUCCESSFUL|LOST] [--timeFrame] [--startDate] [--endDate] (admin)\n get-monthly-metrics [same optional flags as get-dashboard] (admin; dashboard.getMonthlyMetrics)\n get-system-overview [same optional flags as get-dashboard] (admin; dashboard.getSystemOverview)\n get-estimate-performance [same optional flags as get-dashboard] (admin; dashboard.getEstimatePerformance)\n get-financial-overview [same optional flags as dashboard; role uses BudgetRole enum] (admin)\n\nErrors\n get-recent-errors [--cursor] [--direction forward|backward] [--limit] [--severity] [--status] [--timeFrame] (admin)\n count-errors [--severity] [--status] [--timeFrame] (admin)\n get-error <errorId> Full diagnostics: stack, cause, request, metadata (admin)\n get-error-metrics (admin)\n\nAutomation (admin)\n list-integration-\
7663
+ operations [--search] [--destination <provider,...>] [--status <PENDING|PROCESSING|FAILED|COMPLETED,...>] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Newest first; returns { items, pageInfo }. Follow nextCursor/previousCursor with the same filters. --page/--perPage are rejected.\n count-integration-operations [same filter flags] provider filter options only (no total; filters do not change the result)\n get-integration-operation <operationId> (one job: who queued it, what it is for, saved progress, Retry state)\n retry-integration-operation <operationId> [--confirmExternalStateReconciled true|false] [--outboundEmailResolution ACCEPTED|NOT_ACCEPTED_RETRY] [--providerMessageId <id>] (QuickBooks jobs with a saved attempt check QuickBooks first: applied changes finish without resending, unapplied ones are sent again)\n reconcile-resource-operation <operationId> (admin: check a QuickBooks invoice/company/item job outcome without retrying; same check Retry runs\
7664
+ first)\n\nWebhooks (admin)\n list-webhook-event-types (event catalogue: type, group, live|planned)\n list-webhook-endpoints\n get-webhook-endpoint <endpointId>\n create-webhook-endpoint --name <name> --url <https-url> --events <type|prefix.*|*,...> [--enabled true|false] (prints the signing secret once)\n update-webhook-endpoint <endpointId> [--name] [--url] [--events <...>] [--enabled true|false]\n delete-webhook-endpoint <endpointId>\n rotate-webhook-secret <endpointId> [--previousSecretTtlHours <0-168>] (prints the new secret once)\n send-webhook-test-event <endpointId>\n list-webhook-deliveries [--endpointId] [--status <PENDING|SUCCEEDED|FAILED,...>] [--eventType] [--limit 1-100] [--cursor <token>] [--direction forward|backward] (newest first; prints items + pageInfo)\n get-webhook-delivery <deliveryId> (attempts with response codes)\n replay-webhook-delivery <deliveryId> (same eventId, new attempt chain)\n\nHistorical / benchmarks\n get-approved-budgets [--projectId] [--\
7665
+ limit] [--minRevenue] [--maxRevenue]\n get-budget-category-benchmarks <categoryId> [--limit]\n get-item-pricing-history [--itemName] [--categoryId] [--supplierId] [--limit]\n get-supplier-pricing-history <supplierId> [--itemCategoryId] [--limit]\n\nOutput: JSON to stdout. Errors to stderr; exit 1 on failure.\n\nMCP parity: every MCP tool maps to one command above. The CLI also exposes\n reorder-budget-items and update-budget-item-supplier (web UI\u2013oriented tRPC).\n You may use MCP-style snake_case (e.g. bb list_bills) \u2014 normalized to kebab-case.\n\nNote: MCP also exposes a Prisma schema resource; the CLI has no equivalent.\n\nNot covered vs MCP get_budget: "get-budget" also fetches line items in one call.\n').trim();
7631
7666
  runtime.stdout.write("".concat(help, "\n"));
7632
7667
  }
7633
7668
  __name(printLegacyHelp, "printLegacyHelp"), __name2(printLegacyHelp, "printLegacyHelp");
@@ -7669,7 +7704,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7669
7704
  continue;
7670
7705
  }
7671
7706
  if (isRuntimeOnlyArgument(value)) {
7672
- booleanFlagValues.has(argv[index + 1] ?? "") && index++;
7707
+ booleanFlagValues.has(
7708
+ argv[index + 1] ?? ""
7709
+ ) && index++;
7673
7710
  continue;
7674
7711
  }
7675
7712
  commandArgv.push(value);
@@ -7678,34 +7715,34 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7678
7715
  return { apiBaseUrl, commandArgv };
7679
7716
  }, "parseRootArguments"), effectPermissionsFromArgv = __name2((argv) => ({ allowStateChange: isEnabledFlag(argv, "--allow-state-change"), allowEmail: isEnabledFlag(argv, "--allow-email"), allowExternalWrite: isEnabledFlag(argv, "--allow-external-write"), allowDelete: isEnabledFlag(argv, "--allow-delete"), allowFinancialWrite: isEnabledFlag(argv, "--allow-financial-write") }), "effectPermissionsFromArgv"), isCompletionShell = __name2((value) => value === "bash" || value === "zsh" || value === "fish" || value === "powershell", "isCompletionShell"), legacyArgvForCommand = __name2((argv, resolvedCommand) => {
7680
7717
  const legacyTarget = resolvedCommand.command.legacyTarget;
7681
- if (legacyTarget === void 0) throw new CliRuntimeError(
7682
- "INTERNAL",
7683
- "Command ".concat(resolvedCommand.command.path.join(" "), " has no dispatcher target.")
7684
- );
7718
+ if (legacyTarget === void 0) throw new CliRuntimeError("INTERNAL", "Command ".concat(resolvedCommand.command.path.join(" "), " has no dispatcher target."));
7685
7719
  return [argv[0] ?? "node", argv[1] ?? "bb", legacyTarget, ...resolvedCommand.argv.filter((value) => !isRuntimeOnlyArgument(value))];
7686
- }, "legacyArgvForCommand"), normalizeDispatcherError = __name2((error2) => error2 instanceof Error && new __cliRegExp("\\brequires\\b|\\bmust be\\b|\\bmust include\\b|^Invalid\\b|^Missing\\b|^--", "").test(error2.message) ? new CliRuntimeError("VALIDATION", error2.message) : error2, "normalizeDispatcherError"), commandConfirmationTarget = __name2((resolvedCommand) => {
7720
+ }, "legacyArgvForCommand"), normalizeDispatcherError = __name2(
7721
+ (error2) => error2 instanceof Error && new __cliRegExp("\\brequires\\b|\\bmust be\\b|\\bmust include\\b|^Invalid\\b|^Missing\\b|^--", "").test(error2.message) ? new CliRuntimeError("VALIDATION", error2.message) : error2,
7722
+ "normalizeDispatcherError"
7723
+ ), commandConfirmationTarget = __name2((resolvedCommand) => {
7687
7724
  const positionalTarget = resolvedCommand.argv.find((value) => value !== "--" && !value.startsWith("-"));
7688
7725
  return positionalTarget !== void 0 && !positionalTarget.startsWith("{") && !positionalTarget.startsWith("[") ? positionalTarget : resolvedCommand.command.path.join(" ");
7689
7726
  }, "commandConfirmationTarget"), PAGING_FLAG_KEYS = ["limit", "cursor", "direction", "sortBy", "sortDir"], rejectCountPagingFlags = __name2((flags, commandName) => {
7690
7727
  for (const key of PAGING_FLAG_KEYS) if (flags[key] !== void 0) throw new Error("".concat(commandName, " does not accept --").concat(key, "; totals use filters only."));
7691
7728
  }, "rejectCountPagingFlags"), rejectBarePagingFlags = __name2((flags) => {
7692
7729
  for (const key of PAGING_FLAG_KEYS) rejectBareFlag(flags, key);
7693
- }, "rejectBarePagingFlags"), parseCursorAndDirection = __name2((flags) => {
7694
- const cursor = getFlag(flags, "cursor");
7695
- if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7696
- const direction = parseProjectDirection(getFlag(flags, "direction"));
7697
- if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7698
- return { cursor, direction };
7699
- }, "parseCursorAndDirection"), parseAscDescSortDir = __name2((flags) => {
7730
+ }, "rejectBarePagingFlags"), parseCursorAndDirection = __name2(
7731
+ (flags) => {
7732
+ const cursor = getFlag(flags, "cursor");
7733
+ if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7734
+ const direction = parseProjectDirection(getFlag(flags, "direction"));
7735
+ if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7736
+ return { cursor, direction };
7737
+ },
7738
+ "parseCursorAndDirection"
7739
+ ), parseAscDescSortDir = __name2((flags) => {
7700
7740
  const sortDir = getFlag(flags, "sortDir");
7701
7741
  if (sortDir !== void 0 && sortDir !== "asc" && sortDir !== "desc") throw new Error('--sortDir must be "asc" or "desc".');
7702
7742
  return sortDir;
7703
7743
  }, "parseAscDescSortDir"), commandWhoami = __name2(async () => {
7704
7744
  await whoAmI();
7705
- }, "commandWhoami"), commandListBudgets = __name2(async ({
7706
- cmd,
7707
- flags
7708
- }) => {
7745
+ }, "commandWhoami"), commandListBudgets = __name2(async ({ cmd, flags }) => {
7709
7746
  const statusStr = getFlag(flags, "status"), statuses = parseCommaSeparatedBudgetStatuses(statusStr !== void 0 ? String(statusStr) : void 0), filters = { projectId: getFlag(flags, "projectId"), name: getFlag(flags, "name"), statuses, createdBy: getFlag(flags, "createdBy"), dateFrom: getFlag(flags, "dateFrom"), dateTo: getFlag(flags, "dateTo"), active: parseBudgetActiveFlag(flags) };
7710
7747
  if (rejectRetiredPageFlags(flags), cmd === "count-budgets") {
7711
7748
  for (const key of ["limit", "cursor", "direction", "sortBy", "sortDir"]) if (flags[key] !== void 0) throw new Error("count-budgets does not accept --".concat(key, "; totals use filters only."));
@@ -7716,10 +7753,11 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7716
7753
  const cursor = getFlag(flags, "cursor");
7717
7754
  if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7718
7755
  const direction = parseProjectDirection(getFlag(flags, "direction"));
7719
- if (direction === "backward" && !cursor) throw new Error(
7720
- "--direction backward requires --cursor <token>."
7721
- );
7722
- await listBudgets({ ...filters, limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sortBy: getFlag(flags, "sortBy"), sortDir: getFlag(flags, "sortDir"), includeDetails: flags.summary === !0 ? !1 : parseOptionalBoolFlag(flags, "includeDetails") ?? !0 });
7756
+ if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7757
+ await listBudgets({ ...filters, limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sortBy: getFlag(flags, "sortBy"), sortDir: getFlag(flags, "sortDir"), includeDetails: flags.summary === !0 ? !1 : parseOptionalBoolFlag(
7758
+ flags,
7759
+ "includeDetails"
7760
+ ) ?? !0 });
7723
7761
  }, "commandListBudgets"), commandGetBudget = __name2(async ({ flags, positional }) => {
7724
7762
  const id = positional[0];
7725
7763
  if (!id) throw new Error("get-budget requires <id>");
@@ -7730,10 +7768,11 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7730
7768
  await uploadBudgetAttachmentFromPath(budgetId, filePath);
7731
7769
  }, "commandUploadBudgetAttachment"), commandMarkBudgetWon = __name2(async ({ flags, positional }) => {
7732
7770
  const [budgetId, filePath] = positional;
7733
- if (!budgetId || !filePath) throw new Error(
7734
- "mark-budget-won requires <budgetId> <filePath>"
7735
- );
7736
- await markBudgetWonWithProof(budgetId, filePath, { projectManagerId: getFlag(flags, "projectManagerId") !== void 0 ? String(getFlag(flags, "projectManagerId")) : void 0, markProjectWon: parseOptionalBoolFlag(flags, "markProjectWon"), projectInvoiceSettings: getFlag(flags, "invoiceSettings") !== void 0 ? parseJsonFlag(String(getFlag(flags, "invoiceSettings")), "--invoiceSettings") : void 0 });
7771
+ if (!budgetId || !filePath) throw new Error("mark-budget-won requires <budgetId> <filePath>");
7772
+ await markBudgetWonWithProof(budgetId, filePath, { projectManagerId: getFlag(flags, "projectManagerId") !== void 0 ? String(getFlag(flags, "projectManagerId")) : void 0, markProjectWon: parseOptionalBoolFlag(flags, "markProjectWon"), projectInvoiceSettings: getFlag(
7773
+ flags,
7774
+ "invoiceSettings"
7775
+ ) !== void 0 ? parseJsonFlag(String(getFlag(flags, "invoiceSettings")), "--invoiceSettings") : void 0 });
7737
7776
  }, "commandMarkBudgetWon"), commandGetBudgetItems = __name2(async ({ flags, positional }) => {
7738
7777
  const id = positional[0];
7739
7778
  if (!id) throw new Error("get-budget-items requires <budgetId>");
@@ -7756,40 +7795,43 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7756
7795
  if (flags.limit === !0 || limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > 50)) throw new CliRuntimeError("USAGE", "--limit must be an integer from 1 to 50.");
7757
7796
  if (flags.cursor === !0 || flags.cursor === "") throw new CliRuntimeError("USAGE", "--cursor requires the nextCursor token from the previous page.");
7758
7797
  await getBudgetVersions(id, { limit, cursor: flags.cursor, all: flags.all === !0 || (parseOptionalBoolFlag(flags, "all") ?? !1) });
7759
- }, "commandGetBudgetVersions"), commandRenameBudgetVersion = __name2(async ({ flags, positional }) => {
7760
- const versionId = positional[0], newName = getFlag(flags, "name");
7761
- if (!versionId || newName === void 0) throw new Error("rename-budget-version requires <versionId> --name <text>");
7762
- await renameBudgetVersion(versionId, String(newName));
7763
- }, "commandRenameBudgetVersion"), commandRestoreBudgetVersion = __name2(async ({ positional }) => {
7798
+ }, "commandGetBudgetVersions"), commandRenameBudgetVersion = __name2(
7799
+ async ({ flags, positional }) => {
7800
+ const versionId = positional[0], newName = getFlag(flags, "name");
7801
+ if (!versionId || newName === void 0) throw new Error("rename-budget-version requires <versionId> --name <text>");
7802
+ await renameBudgetVersion(versionId, String(newName));
7803
+ },
7804
+ "commandRenameBudgetVersion"
7805
+ ), commandRestoreBudgetVersion = __name2(async ({ positional }) => {
7764
7806
  const versionId = positional[0];
7765
7807
  if (!versionId) throw new Error("restore-budget-version requires <versionId>");
7766
7808
  await restoreBudgetVersion(versionId);
7767
7809
  }, "commandRestoreBudgetVersion"), commandUpdateBudgetStatus = __name2(async ({ flags, positional }) => {
7768
7810
  const [id, status] = positional;
7769
7811
  if (!id || !status) throw new Error("update-budget-status requires <id> <status>");
7770
- if (!isBudgetStatusUpdate(
7771
- status
7772
- )) throw new Error("Invalid status. Use one of: ".concat(budgetStatusesForHelp.join(", ")));
7812
+ if (!isBudgetStatusUpdate(status)) throw new Error("Invalid status. Use one of: ".concat(budgetStatusesForHelp.join(", ")));
7773
7813
  await updateBudgetStatus(id, status, { projectManagerId: getFlag(flags, "projectManagerId") !== void 0 ? String(getFlag(flags, "projectManagerId")) : void 0, markProjectWon: parseOptionalBoolFlag(flags, "markProjectWon"), projectStatusOnCommercialRejection: parseCommercialRejectionProjectStatus(flags), projectInvoiceSettings: getFlag(flags, "invoiceSettings") !== void 0 ? parseJsonFlag(String(getFlag(flags, "invoiceSettings")), "--invoiceSettings") : void 0 });
7774
7814
  }, "commandUpdateBudgetStatus"), commandCreateBudgetApproval = __name2(async ({ flags, positional }) => {
7775
7815
  const id = positional[0];
7776
7816
  if (!id) throw new Error("create-budget-approval requires <budgetId>");
7777
7817
  const companyPayloadRaw = getFlag(flags, "companyPayload"), contactPayloadRaw = getFlag(flags, "contactPayload"), eventPayloadRaw = getFlag(flags, "eventPayload");
7778
7818
  await createBudgetApproval(id, { company: companyPayloadRaw !== void 0 ? parseJsonObjectFlag(String(companyPayloadRaw), "--companyPayload") : void 0, contactPerson: contactPayloadRaw !== void 0 ? parseJsonObjectFlag(String(contactPayloadRaw), "--contactPayload") : void 0, eventDetails: eventPayloadRaw !== void 0 ? parseJsonObjectFlag(String(eventPayloadRaw), "--eventPayload") : void 0 });
7779
- }, "commandCreateBudgetApproval"), commandCreateEstimate = __name2(async ({ flags, positional }) => {
7780
- const id = positional[0];
7781
- if (!id) throw new Error("create-estimate requires <budgetId>");
7782
- const companyPayloadRaw = getFlag(flags, "companyPayload"), contactPayloadRaw = getFlag(flags, "contactPayload"), eventPayloadRaw = getFlag(flags, "eventPayload");
7783
- await createEstimate(id, { company: companyPayloadRaw !== void 0 ? parseJsonObjectFlag(String(companyPayloadRaw), "--companyPayload") : void 0, contactPerson: contactPayloadRaw !== void 0 ? parseJsonObjectFlag(String(contactPayloadRaw), "--contactPayload") : void 0, eventDetails: eventPayloadRaw !== void 0 ? parseJsonObjectFlag(String(eventPayloadRaw), "--eventPayload") : void 0 });
7784
- }, "commandCreateEstimate"), commandSendEstimateEmail = __name2(async ({ flags }) => {
7785
- const payloadRaw = getFlag(
7786
- flags,
7787
- "payload"
7788
- );
7819
+ }, "commandCreateBudgetApproval"), commandCreateEstimate = __name2(
7820
+ async ({ flags, positional }) => {
7821
+ const id = positional[0];
7822
+ if (!id) throw new Error("create-estimate requires <budgetId>");
7823
+ const companyPayloadRaw = getFlag(flags, "companyPayload"), contactPayloadRaw = getFlag(flags, "contactPayload"), eventPayloadRaw = getFlag(flags, "eventPayload");
7824
+ await createEstimate(id, { company: companyPayloadRaw !== void 0 ? parseJsonObjectFlag(String(companyPayloadRaw), "--companyPayload") : void 0, contactPerson: contactPayloadRaw !== void 0 ? parseJsonObjectFlag(String(contactPayloadRaw), "--contactPayload") : void 0, eventDetails: eventPayloadRaw !== void 0 ? parseJsonObjectFlag(String(eventPayloadRaw), "--eventPayload") : void 0 });
7825
+ },
7826
+ "commandCreateEstimate"
7827
+ ), commandSendEstimateEmail = __name2(async ({ flags }) => {
7828
+ const payloadRaw = getFlag(flags, "payload");
7789
7829
  if (!payloadRaw) throw new Error("send-estimate-to-contact-person requires --payload '<json>'");
7790
7830
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
7791
7831
  await sendEstimateToContactPersonFromPayload(raw);
7792
- }, "commandSendEstimateEmail"), commandCreateBudget = __name2(async ({ flags }) => {
7832
+ }, "commandSendEstimateEmail"), commandCreateBudget = __name2(async ({
7833
+ flags
7834
+ }) => {
7793
7835
  const payloadRaw = getFlag(flags, "payload");
7794
7836
  if (!payloadRaw) throw new Error("create-budget requires --payload '<json>'");
7795
7837
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
@@ -7803,52 +7845,46 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7803
7845
  const id = positional[0];
7804
7846
  if (!id) throw new Error("delete-budget requires <budgetId>");
7805
7847
  await deleteBudgetById(id);
7806
- }, "commandDeleteBudget"), commandAddBudgetItems = __name2(
7807
- async ({ flags }) => {
7808
- const budgetId = getFlag(flags, "budgetId");
7809
- if (!budgetId) throw new Error("add-budget-items requires --budgetId");
7810
- const items = parseJsonFlag(String(getFlag(flags, "items")), "--items");
7811
- await addBudgetItems({ budgetId: String(budgetId), items });
7812
- },
7813
- "commandAddBudgetItems"
7814
- ), commandUpdateBudgetItem = __name2(async ({ flags }) => {
7848
+ }, "commandDeleteBudget"), commandAddBudgetItems = __name2(async ({ flags }) => {
7849
+ const budgetId = getFlag(flags, "budgetId");
7850
+ if (!budgetId) throw new Error("add-budget-items requires --budgetId");
7851
+ const items = parseJsonFlag(String(getFlag(flags, "items")), "--items");
7852
+ await addBudgetItems({ budgetId: String(budgetId), items });
7853
+ }, "commandAddBudgetItems"), commandUpdateBudgetItem = __name2(async ({ flags }) => {
7815
7854
  const id = getFlag(flags, "id");
7816
7855
  if (!id) throw new Error("update-budget-item requires --id");
7817
7856
  await updateBudgetItem({ id: String(id), description: getFlag(flags, "description"), note: getFlag(flags, "note"), quantity: parseOptionalNumber(getFlag(flags, "quantity"), "--quantity"), markup: parseOptionalNumber(getFlag(flags, "markup"), "--markup"), cost: parseOptionalNumber(getFlag(flags, "cost"), "--cost"), unitPrice: parseOptionalNumber(getFlag(flags, "unitPrice"), "--unitPrice"), isFreeOfCharge: parseOptionalBoolFlag(flags, "isFreeOfCharge"), gstInclusive: parseOptionalBoolFlag(flags, "gstInclusive"), gstOutOfScope: parseOptionalBoolFlag(flags, "gstOutOfScope") });
7818
- }, "commandUpdateBudgetItem"), commandRemoveBudgetItem = __name2(
7819
- async ({ positional }) => {
7820
- const id = positional[0];
7821
- if (!id) throw new Error("remove-budget-item requires <budgetItemId>");
7822
- await removeBudgetItem(id);
7823
- },
7824
- "commandRemoveBudgetItem"
7825
- ), commandReplaceBudgetItem = __name2(async ({ flags }) => {
7826
- const budgetItemId = getFlag(flags, "budgetItemId"), replacementItemId = getFlag(flags, "replacementItemId");
7857
+ }, "commandUpdateBudgetItem"), commandRemoveBudgetItem = __name2(async ({ positional }) => {
7858
+ const id = positional[0];
7859
+ if (!id) throw new Error("remove-budget-item requires <budgetItemId>");
7860
+ await removeBudgetItem(id);
7861
+ }, "commandRemoveBudgetItem"), commandReplaceBudgetItem = __name2(async ({ flags }) => {
7862
+ const budgetItemId = getFlag(
7863
+ flags,
7864
+ "budgetItemId"
7865
+ ), replacementItemId = getFlag(flags, "replacementItemId");
7827
7866
  if (!budgetItemId || !replacementItemId) throw new Error("replace-budget-item requires --budgetItemId and --replacementItemId");
7828
7867
  await replaceBudgetItem({ budgetItemId: String(budgetItemId), replacementItemId: String(replacementItemId) });
7829
7868
  }, "commandReplaceBudgetItem"), commandApproveUnavailableItemException = __name2(async ({ flags }) => {
7830
7869
  const budgetItemId = getFlag(flags, "budgetItemId"), reason = getFlag(flags, "reason");
7831
7870
  if (!budgetItemId || !reason) throw new Error("approve-unavailable-item-exception requires --budgetItemId and --reason");
7832
7871
  await approveUnavailableItemException({ budgetItemId: String(budgetItemId), reason: String(reason) });
7833
- }, "commandApproveUnavailableItemException"), commandReorderBudgetItems = __name2(
7834
- async ({ flags, positional }) => {
7835
- const budgetId = positional[0], itemIdsRaw = getFlag(flags, "itemIds");
7836
- if (!budgetId || itemIdsRaw === void 0) throw new Error("reorder-budget-items requires <budgetId> --itemIds <csv>");
7837
- const itemIds = parseCommaSeparatedIds(String(itemIdsRaw));
7838
- if (!itemIds?.length) throw new Error("reorder-budget-items requires non-empty --itemIds <csv>");
7839
- await reorderBudgetItemsCli({ budgetId, itemIds });
7840
- },
7841
- "commandReorderBudgetItems"
7842
- ), commandUpdateBudgetItemSupplier = __name2(async ({ flags }) => {
7872
+ }, "commandApproveUnavailableItemException"), commandReorderBudgetItems = __name2(async ({ flags, positional }) => {
7873
+ const budgetId = positional[0], itemIdsRaw = getFlag(flags, "itemIds");
7874
+ if (!budgetId || itemIdsRaw === void 0) throw new Error("reorder-budget-items requires <budgetId> --itemIds <csv>");
7875
+ const itemIds = parseCommaSeparatedIds(
7876
+ String(itemIdsRaw)
7877
+ );
7878
+ if (!itemIds?.length) throw new Error("reorder-budget-items requires non-empty --itemIds <csv>");
7879
+ await reorderBudgetItemsCli({ budgetId, itemIds });
7880
+ }, "commandReorderBudgetItems"), commandUpdateBudgetItemSupplier = __name2(async ({ flags }) => {
7843
7881
  const budgetItemId = getFlag(flags, "budgetItemId"), supplierId = getFlag(flags, "supplierId");
7844
7882
  if (!budgetItemId || !supplierId) throw new Error("update-budget-item-supplier requires --budgetItemId and --supplierId");
7845
7883
  await updateBudgetItemSupplierCli({ budgetItemId: String(budgetItemId), supplierId: String(supplierId) });
7846
7884
  }, "commandUpdateBudgetItemSupplier"), commandCreateBudgetCategory = __name2(async ({ flags }) => {
7847
7885
  const name = getFlag(flags, "name");
7848
7886
  if (!name) throw new Error("create-budget-category requires --name");
7849
- await createBudgetCategory(
7850
- String(name)
7851
- );
7887
+ await createBudgetCategory(String(name));
7852
7888
  }, "commandCreateBudgetCategory"), commandUpdateBudgetCategory = __name2(async ({ flags }) => {
7853
7889
  const id = getFlag(flags, "id"), name = getFlag(flags, "name");
7854
7890
  if (!id || !name) throw new Error("update-budget-category requires --id and --name");
@@ -7897,9 +7933,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7897
7933
  await countBills({ ...parseCountBillsFlags(flags), isClaimable: !0 });
7898
7934
  }, "commandCountClaims"), commandCreateBillApproval = __name2(async ({ positional }) => {
7899
7935
  const id = positional[0];
7900
- if (!id) throw new Error(
7901
- "create-bill-approval requires <billId>"
7902
- );
7936
+ if (!id) throw new Error("create-bill-approval requires <billId>");
7903
7937
  await createBillApproval(id);
7904
7938
  }, "commandCreateBillApproval"), commandCreateBill = __name2(async ({ flags }) => {
7905
7939
  const payloadRaw = getFlag(flags, "payload");
@@ -7913,17 +7947,19 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7913
7947
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
7914
7948
  if (flags.quotationIds === !0 || flags.quotationId === !0) throw new Error("--quotationIds requires a CSV value and --quotationId requires an ID value.");
7915
7949
  const quotationIds = parseCommaSeparatedIds(getFlag(flags, "quotationIds")), quotationId = getFlag(flags, "quotationId")?.trim() || void 0;
7916
- if (quotationId && quotationIds && (quotationIds.length !== 1 || quotationIds[0] !== quotationId)) throw new Error("--quotationId conflicts with --quotationIds.");
7950
+ if (quotationId && quotationIds && (quotationIds.length !== 1 || quotationIds[0] !== quotationId))
7951
+ throw new Error("--quotationId conflicts with --quotationIds.");
7917
7952
  if (quotationIds && new Set(quotationIds).size !== quotationIds.length) throw new Error("--quotationIds must not contain duplicates.");
7918
7953
  await validateBillSelectionFromPayload(raw, { ...quotationId ? { quotationId } : {}, ...quotationIds ? { quotationIds } : {} });
7919
7954
  }, "commandValidateBillSelection"), commandLinkBillQuotations = __name2(async ({ flags, positional }) => {
7920
7955
  const billId = positional[0], payloadRaw = getFlag(flags, "payload"), quotationIds = parseCommaSeparatedIds(getFlag(flags, "quotationIds"));
7921
7956
  if (!billId || !payloadRaw && (!quotationIds || quotationIds.length === 0)) throw new Error("link-bill-quotations requires <billId> and either --payload '<json>' or --quotationIds <csv>");
7922
- if (payloadRaw && quotationIds) throw new Error(
7923
- "--payload cannot be combined with --quotationIds."
7924
- );
7957
+ if (payloadRaw && quotationIds) throw new Error("--payload cannot be combined with --quotationIds.");
7925
7958
  if (quotationIds && new Set(quotationIds).size !== quotationIds.length) throw new Error("--quotationIds must not contain duplicates.");
7926
- await linkBillQuotations(billId, payloadRaw ? parseJsonFlag(String(payloadRaw), "--payload") : { quotationIds });
7959
+ await linkBillQuotations(billId, payloadRaw ? parseJsonFlag(
7960
+ String(payloadRaw),
7961
+ "--payload"
7962
+ ) : { quotationIds });
7927
7963
  }, "commandLinkBillQuotations"), commandUpdateBill = __name2(async ({ flags }) => {
7928
7964
  const payloadRaw = getFlag(flags, "payload");
7929
7965
  if (!payloadRaw) throw new Error("update-bill requires --payload '<json>'");
@@ -7936,9 +7972,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7936
7972
  await updateBillPaymentEvidenceFromPayload(raw);
7937
7973
  }, "commandUpdateBillPaymentEvidence"), commandDeleteBill = __name2(async ({ positional }) => {
7938
7974
  const id = positional[0];
7939
- if (!id) throw new Error(
7940
- "delete-bill requires <billId>"
7941
- );
7975
+ if (!id) throw new Error("delete-bill requires <billId>");
7942
7976
  await deleteBillById(id);
7943
7977
  }, "commandDeleteBill"), commandUpdateBillStatus = __name2(async ({ flags, positional }) => {
7944
7978
  const [id, statusRaw] = positional;
@@ -7952,17 +7986,17 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7952
7986
  }, "commandListExternalPaymentAccounts"), commandRefreshExternalPaymentAccounts = __name2(async () => {
7953
7987
  await refreshExternalBillPaymentAccounts();
7954
7988
  }, "commandRefreshExternalPaymentAccounts"), commandRecordExternalBillPayment = __name2(async ({ flags, positional }) => {
7955
- const id = positional[0], paymentReference = getFlag(flags, "paymentReference"), paymentDate = getFlag(flags, "paymentDate"), paymentAccount = getFlag(flags, "paymentAccount"), paymentProofPath = getFlag(flags, "paymentProof");
7989
+ const id = positional[0], paymentReference = getFlag(
7990
+ flags,
7991
+ "paymentReference"
7992
+ ), paymentDate = getFlag(flags, "paymentDate"), paymentAccount = getFlag(flags, "paymentAccount"), paymentProofPath = getFlag(flags, "paymentProof");
7956
7993
  if (!id || !paymentReference || !paymentDate || !paymentAccount) throw new Error("record-external-bill-payment requires <billId> --paymentReference --paymentDate YYYY-MM-DD --paymentAccount <QBO account ID> [--paymentProof receipt.pdf]");
7957
7994
  await recordExternalBillPayment({ id, paymentReference, paymentDate, paymentAccount, paymentProofPath });
7958
7995
  }, "commandRecordExternalBillPayment"), commandPatchBillPayment = __name2(async ({ flags, positional }) => {
7959
7996
  const id = positional[0];
7960
7997
  if (!id) throw new Error("patch-bill-payment requires <billId>");
7961
7998
  const paymentTrackingUrl = (() => {
7962
- const clear = parseOptionalBoolFlag(
7963
- flags,
7964
- "clearPaymentTrackingUrl"
7965
- ), raw = getFlag(flags, "paymentTrackingUrl");
7999
+ const clear = parseOptionalBoolFlag(flags, "clearPaymentTrackingUrl"), raw = getFlag(flags, "paymentTrackingUrl");
7966
8000
  if (clear === !0 && raw !== void 0) throw new Error("Use either --paymentTrackingUrl or --clearPaymentTrackingUrl true, not both");
7967
8001
  if (clear === !0) return null;
7968
8002
  if (raw !== void 0) return String(raw);
@@ -7994,54 +8028,44 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7994
8028
  const page = parseDetailFeedPage("get-bill-approvals", "<billId>", positional, flags, 50);
7995
8029
  await getBillApprovals(page);
7996
8030
  }, "commandGetBillApprovals"), commandGetBillLineItems = __name2(async ({ flags, positional }) => {
7997
- const page = parseDetailFeedPage(
7998
- "get-bill-line-items",
7999
- "<billId>",
8000
- positional,
8001
- flags,
8002
- 100
8003
- );
8031
+ const page = parseDetailFeedPage("get-bill-line-items", "<billId>", positional, flags, 100);
8004
8032
  await getBillLineItems(page);
8005
8033
  }, "commandGetBillLineItems"), commandGetBillPayment = __name2(async ({ positional }) => {
8006
8034
  const id = positional[0];
8007
8035
  if (!id) throw new Error("get-bill-payment requires <billId>");
8008
- await getBillPayment(id);
8036
+ await getBillPayment(
8037
+ id
8038
+ );
8009
8039
  }, "commandGetBillPayment"), commandStageBillAttachment = __name2(async ({ flags, positional }) => {
8010
8040
  const [projectId, ...positionalFilePaths] = positional, fileFlag = getFlag(flags, "file"), filesFlag = getFlag(flags, "files"), filePaths = [...positionalFilePaths, ...fileFlag !== void 0 ? [String(fileFlag)] : [], ...filesFlag !== void 0 ? String(filesFlag).split(",").map((value) => value.trim()).filter(Boolean) : []];
8011
8041
  if (!projectId || filePaths.length === 0) throw new Error("stage-bill-attachment requires <projectId> <filePath...> or --file/--files");
8012
8042
  await stageBillAttachmentsFromPaths(projectId, filePaths);
8013
8043
  }, "commandStageBillAttachment"), commandCleanupStagedBillAttachments = __name2(async ({ flags, positional }) => {
8014
- const projectId = positional[0], keys = parseCommaSeparatedIds(getFlag(
8015
- flags,
8016
- "keys"
8017
- ));
8044
+ const projectId = positional[0], keys = parseCommaSeparatedIds(getFlag(flags, "keys"));
8018
8045
  if (!projectId || !keys) throw new Error("cleanup-staged-bill-attachments requires <projectId> --keys <csv>");
8019
8046
  await cleanupStagedBillAttachments(projectId, keys);
8020
- }, "commandCleanupStagedBillAttachments"), commandUploadBillAttachment = __name2(
8021
- async ({ cmd, flags, positional }) => {
8022
- const [billId, ...positionalFilePaths] = positional, fileFlag = getFlag(flags, "file"), filesFlag = getFlag(flags, "files"), filePaths = [...positionalFilePaths, ...fileFlag !== void 0 ? [String(fileFlag)] : [], ...filesFlag !== void 0 ? String(filesFlag).split(",").map((value) => value.trim()).filter(Boolean) : []];
8023
- if (!billId || filePaths.length === 0) throw new Error("".concat(cmd, " requires <billId> <filePath...> or --file/--files"));
8024
- const attachmentType = cmd === "attach-bill-payment-receipt" ? AttachmentType.BILL_PAYMENT_PROOF : AttachmentType.BILL, [firstFilePath] = filePaths;
8025
- filePaths.length === 1 && firstFilePath !== void 0 ? await uploadBillAttachmentFromPath(billId, firstFilePath, attachmentType) : await uploadBillAttachmentsFromPaths(billId, filePaths, attachmentType);
8026
- },
8027
- "commandUploadBillAttachment"
8028
- ), commandAttachBillDocuments = __name2(
8029
- async ({ flags, positional }) => {
8030
- const billId = positional[0];
8031
- if (!billId) throw new Error("attach-bill-documents requires <billId>");
8032
- const getFlagAlias = __name2((...flagNames) => {
8033
- for (const flagName of flagNames) {
8034
- const value = getFlag(flags, flagName);
8035
- if (value !== void 0) return value;
8036
- }
8037
- }, "getFlagAlias"), parseFilesFlag = __name2((...flagNames) => {
8038
- const raw = getFlagAlias(...flagNames);
8039
- return raw === void 0 ? [] : String(raw).split(",").map((value) => value.trim()).filter(Boolean);
8040
- }, "parseFilesFlag"), invoicePath = getFlagAlias("invoice", "invoice-file"), paymentProofPath = getFlagAlias("paymentProof", "payment-proof", "proof", "receipt"), invoicePaths = [...invoicePath !== void 0 ? [String(invoicePath)] : [], ...parseFilesFlag("invoices", "invoice-files")], paymentProofPaths = [...paymentProofPath !== void 0 ? [String(paymentProofPath)] : [], ...parseFilesFlag("paymentProofs", "payment-proofs", "proofs", "receipts")];
8041
- await uploadBillDocumentsFromPaths({ billId, invoicePaths, paymentProofPaths });
8042
- },
8043
- "commandAttachBillDocuments"
8044
- ), commandGetBillReview = __name2(async ({ positional }) => {
8047
+ }, "commandCleanupStagedBillAttachments"), commandUploadBillAttachment = __name2(async ({ cmd, flags, positional }) => {
8048
+ const [billId, ...positionalFilePaths] = positional, fileFlag = getFlag(flags, "file"), filesFlag = getFlag(flags, "files"), filePaths = [...positionalFilePaths, ...fileFlag !== void 0 ? [String(fileFlag)] : [], ...filesFlag !== void 0 ? String(filesFlag).split(",").map((value) => value.trim()).filter(Boolean) : []];
8049
+ if (!billId || filePaths.length === 0) throw new Error("".concat(cmd, " requires <billId> <filePath...> or --file/--files"));
8050
+ const attachmentType = cmd === "attach-bill-payment-receipt" ? AttachmentType.BILL_PAYMENT_PROOF : AttachmentType.BILL, [firstFilePath] = filePaths;
8051
+ filePaths.length === 1 && firstFilePath !== void 0 ? await uploadBillAttachmentFromPath(billId, firstFilePath, attachmentType) : await uploadBillAttachmentsFromPaths(billId, filePaths, attachmentType);
8052
+ }, "commandUploadBillAttachment"), commandAttachBillDocuments = __name2(async ({ flags, positional }) => {
8053
+ const billId = positional[0];
8054
+ if (!billId) throw new Error("attach-bill-documents requires <billId>");
8055
+ const getFlagAlias = __name2((...flagNames) => {
8056
+ for (const flagName of flagNames) {
8057
+ const value = getFlag(
8058
+ flags,
8059
+ flagName
8060
+ );
8061
+ if (value !== void 0) return value;
8062
+ }
8063
+ }, "getFlagAlias"), parseFilesFlag = __name2((...flagNames) => {
8064
+ const raw = getFlagAlias(...flagNames);
8065
+ return raw === void 0 ? [] : String(raw).split(",").map((value) => value.trim()).filter(Boolean);
8066
+ }, "parseFilesFlag"), invoicePath = getFlagAlias("invoice", "invoice-file"), paymentProofPath = getFlagAlias("paymentProof", "payment-proof", "proof", "receipt"), invoicePaths = [...invoicePath !== void 0 ? [String(invoicePath)] : [], ...parseFilesFlag("invoices", "invoice-files")], paymentProofPaths = [...paymentProofPath !== void 0 ? [String(paymentProofPath)] : [], ...parseFilesFlag("paymentProofs", "payment-proofs", "proofs", "receipts")];
8067
+ await uploadBillDocumentsFromPaths({ billId, invoicePaths, paymentProofPaths });
8068
+ }, "commandAttachBillDocuments"), commandGetBillReview = __name2(async ({ positional }) => {
8045
8069
  const id = positional[0];
8046
8070
  if (!id) throw new Error("bill review requires <billId>");
8047
8071
  await getBillReview(id);
@@ -8058,9 +8082,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8058
8082
  for (const key of ["limit", "cursor", "direction"]) rejectBareFlag(flags, key);
8059
8083
  const cursor = getFlag(flags, "cursor");
8060
8084
  if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
8061
- const direction = parseProjectDirection(
8062
- getFlag(flags, "direction")
8063
- );
8085
+ const direction = parseProjectDirection(getFlag(flags, "direction"));
8064
8086
  if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
8065
8087
  await listQuotations({ ...parseQuotationFilterFlags(flags), limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction });
8066
8088
  }, "commandListQuotations"), commandCountQuotations = __name2(async ({ flags }) => {
@@ -8086,14 +8108,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8086
8108
  const payloadRaw = getFlag(flags, "payload");
8087
8109
  if (!payloadRaw) throw new Error("create-quotation requires --payload '<json>'");
8088
8110
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
8089
- await createQuotationFromPayload(
8090
- raw
8091
- );
8111
+ await createQuotationFromPayload(raw);
8092
8112
  }, "commandCreateQuotation"), commandUpdateQuotation = __name2(async ({ flags }) => {
8093
8113
  const payloadRaw = getFlag(flags, "payload");
8094
8114
  if (!payloadRaw) throw new Error("update-quotation requires --payload '<json>'");
8095
8115
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
8096
- await updateQuotationFromPayload(raw);
8116
+ await updateQuotationFromPayload(
8117
+ raw
8118
+ );
8097
8119
  }, "commandUpdateQuotation"), commandDeleteQuotation = __name2(async ({ positional }) => {
8098
8120
  const id = positional[0];
8099
8121
  if (!id) throw new Error("delete-quotation requires <quotationId>");
@@ -8110,13 +8132,16 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8110
8132
  const id = positional[0], reason = getFlag(flags, "reason");
8111
8133
  if (!id || reason === void 0) throw new Error("reject-quotation requires <quotationId> --reason <text>");
8112
8134
  await rejectQuotation(id, reason);
8113
- }, "commandRejectQuotation"), commandDownloadQuotationPdf = __name2(async ({ positional }) => {
8114
- const id = positional[0];
8115
- if (!id) throw new Error("download-quotation-pdf requires <quotationId> [original|staff|final]");
8116
- const roleRaw = (positional[1] ?? "final").toLowerCase(), fileRole = roleRaw === "original" ? SupplierQuotationFileRole.ORIGINAL : roleRaw === "staff" ? SupplierQuotationFileRole.STAFF_SIGNED : roleRaw === "final" ? SupplierQuotationFileRole.FINAL_SIGNED : null;
8117
- if (!fileRole) throw new Error("download-quotation-pdf role must be original, staff, or final");
8118
- await downloadQuotationPdf(id, fileRole);
8119
- }, "commandDownloadQuotationPdf"), commandCheckCustomerInvoiceReadiness = __name2(async ({ positional }) => {
8135
+ }, "commandRejectQuotation"), commandDownloadQuotationPdf = __name2(
8136
+ async ({ positional }) => {
8137
+ const id = positional[0];
8138
+ if (!id) throw new Error("download-quotation-pdf requires <quotationId> [original|staff|final]");
8139
+ const roleRaw = (positional[1] ?? "final").toLowerCase(), fileRole = roleRaw === "original" ? SupplierQuotationFileRole.ORIGINAL : roleRaw === "staff" ? SupplierQuotationFileRole.STAFF_SIGNED : roleRaw === "final" ? SupplierQuotationFileRole.FINAL_SIGNED : null;
8140
+ if (!fileRole) throw new Error("download-quotation-pdf role must be original, staff, or final");
8141
+ await downloadQuotationPdf(id, fileRole);
8142
+ },
8143
+ "commandDownloadQuotationPdf"
8144
+ ), commandCheckCustomerInvoiceReadiness = __name2(async ({ positional }) => {
8120
8145
  const budgetId = positional[0];
8121
8146
  if (!budgetId) throw new Error("check-customer-invoice-readiness requires <budgetId>");
8122
8147
  await checkCustomerInvoiceReadiness(budgetId);
@@ -8133,12 +8158,13 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8133
8158
  if (!budgetId || positional.length !== 1) throw new Error("list-available-qbo-customer-invoices requires <budgetId>");
8134
8159
  await listAvailableQboCustomerInvoices(budgetId);
8135
8160
  }, "commandListAvailableQboCustomerInvoices"), customerInvoiceFiltersFromFlags = __name2((flags, positionalBudgetId) => {
8136
- const projectId = getFlag(flags, "projectId"), projectIds = parseCommaSeparatedIds(getFlag(flags, "projectIds"));
8161
+ const projectId = getFlag(
8162
+ flags,
8163
+ "projectId"
8164
+ ), projectIds = parseCommaSeparatedIds(getFlag(flags, "projectIds"));
8137
8165
  if (projectId && projectIds) throw new Error("Use either --projectId for project scope or --projectIds for a global filter, not both.");
8138
8166
  const budgetIds = [...positionalBudgetId ? [positionalBudgetId] : [], ...parseCommaSeparatedIds(getFlag(flags, "budgetIds")) ?? []], statusRaw = getFlag(flags, "status");
8139
- return { scope: projectId ? { type: "project", projectId } : { type: "global" }, q: getFlag(flags, "search") ?? "", statuses: parseCommaSeparatedCustomerInvoiceStatuses(statusRaw !== void 0 ? String(statusRaw) : void 0), companyIds: parseCommaSeparatedIds(getFlag(flags, "companyIds")), projectIds, budgetIds: budgetIds.length > 0 ? [...new Set(budgetIds)] : void 0, createdByIds: parseCommaSeparatedIds(
8140
- getFlag(flags, "createdByIds")
8141
- ) };
8167
+ return { scope: projectId ? { type: "project", projectId } : { type: "global" }, q: getFlag(flags, "search") ?? "", statuses: parseCommaSeparatedCustomerInvoiceStatuses(statusRaw !== void 0 ? String(statusRaw) : void 0), companyIds: parseCommaSeparatedIds(getFlag(flags, "companyIds")), projectIds, budgetIds: budgetIds.length > 0 ? [...new Set(budgetIds)] : void 0, createdByIds: parseCommaSeparatedIds(getFlag(flags, "createdByIds")) };
8142
8168
  }, "customerInvoiceFiltersFromFlags"), commandListCustomerInvoices = __name2(async ({ cmd, flags, positional }) => {
8143
8169
  const filters = customerInvoiceFiltersFromFlags(flags, positional[0]);
8144
8170
  if (rejectRetiredPageFlags(flags), cmd === "count-customer-invoices") {
@@ -8152,9 +8178,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8152
8178
  const batchId = positional[0];
8153
8179
  if (!batchId) throw new Error("get-customer-invoice requires <batchId>");
8154
8180
  await getCustomerInvoice(batchId);
8155
- }, "commandGetCustomerInvoice"), commandGetCustomerInvoiceInvoices = __name2(async ({
8156
- positional
8157
- }) => {
8181
+ }, "commandGetCustomerInvoice"), commandGetCustomerInvoiceInvoices = __name2(async ({ positional }) => {
8158
8182
  const batchId = positional[0];
8159
8183
  if (!batchId) throw new Error("get-customer-invoice-invoices requires <batchId>");
8160
8184
  await getCustomerInvoiceInvoices(batchId);
@@ -8180,9 +8204,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8180
8204
  if (!budgetId?.trim() || !qboInvoiceId || positional.length !== 2) throw new Error("".concat(cmd, " requires <budgetId> <qboInvoiceId>"));
8181
8205
  if (!new __cliRegExp("^\\d+$", "").test(qboInvoiceId)) throw new Error("qboInvoiceId must be the numeric QuickBooks transaction ID, not the invoice number");
8182
8206
  const confirmEstimateLineage = flags.confirmEstimateLineage === !0 ? !0 : parseOptionalBoolFlag(flags, "confirmEstimateLineage");
8183
- if (cmd === "preview-qbo-customer-invoice") await previewQboCustomerInvoice(
8184
- { budgetId, qboInvoiceId, confirmEstimateLineage }
8185
- );
8207
+ if (cmd === "preview-qbo-customer-invoice") await previewQboCustomerInvoice({ budgetId, qboInvoiceId, confirmEstimateLineage });
8186
8208
  else {
8187
8209
  const token = getFlag(flags, "token");
8188
8210
  if (!token || !new __cliRegExp("^[a-f0-9]{64}$", "").test(token)) throw new Error("import-qbo-customer-invoice requires --token <64-character preview token> from a reviewed preview-qbo result");
@@ -8214,12 +8236,13 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8214
8236
  await approveCustomerInvoice(batchId);
8215
8237
  }, "commandApproveCustomerInvoice"), commandRejectCustomerInvoice = __name2(async ({ flags, positional }) => {
8216
8238
  const batchId = positional[0], reason = getFlag(flags, "reason");
8217
- if (!batchId || reason === void 0) throw new Error(
8218
- "reject-customer-invoice requires <batchId> --reason <text>"
8219
- );
8239
+ if (!batchId || reason === void 0) throw new Error("reject-customer-invoice requires <batchId> --reason <text>");
8220
8240
  await rejectCustomerInvoice(batchId, String(reason));
8221
8241
  }, "commandRejectCustomerInvoice"), commandSendCustomerInvoiceToContactPerson = __name2(async ({ flags }) => {
8222
- const payloadRaw = getFlag(flags, "payload");
8242
+ const payloadRaw = getFlag(
8243
+ flags,
8244
+ "payload"
8245
+ );
8223
8246
  if (!payloadRaw) throw new Error("send-customer-invoice-to-contact-person requires --payload '<json>'");
8224
8247
  await sendCustomerInvoiceToContactPersonFromPayload(parseJsonFlag(String(payloadRaw), "--payload"));
8225
8248
  }, "commandSendCustomerInvoiceToContactPerson"), commandDownloadCustomerInvoicePdf = __name2(async ({ flags, positional }) => {
@@ -8238,7 +8261,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8238
8261
  await updateCustomerInvoiceQboDrift({ invoiceId, resolution, ...typeof requestId == "string" ? { requestId } : {} });
8239
8262
  }, "commandUpdateCustomerInvoiceQboDrift"), commandMarkCustomerInvoiceSentExternally = __name2(async ({ flags, positional }) => {
8240
8263
  const invoiceId = positional[0], sentAt = getFlag(flags, "sentAt"), recipients = getFlag(flags, "recipients");
8241
- if (!invoiceId || !sentAt || !recipients) throw new Error("mark-customer-invoice-sent-externally requires <invoiceId> --sentAt <ISO datetime> --recipients a@x.com,b@y.com [--note <text>]");
8264
+ if (!invoiceId || !sentAt || !recipients) throw new Error(
8265
+ "mark-customer-invoice-sent-externally requires <invoiceId> --sentAt <ISO datetime> --recipients a@x.com,b@y.com [--note <text>]"
8266
+ );
8242
8267
  await markCustomerInvoiceSentExternally({ invoiceId, sentAt, recipients: recipients.split(",").map((recipient) => recipient.trim()).filter(Boolean), note: getFlag(flags, "note") });
8243
8268
  }, "commandMarkCustomerInvoiceSentExternally"), commandSyncCustomerInvoice = __name2(async ({ positional }) => {
8244
8269
  const invoiceId = positional[0];
@@ -8261,14 +8286,13 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8261
8286
  const id = positional[0];
8262
8287
  if (!id) throw new Error("approve-budget requires <budgetId>");
8263
8288
  await approveBudget(id);
8264
- }, "commandApproveBudget"), commandRejectBudget = __name2(async ({
8265
- flags,
8266
- positional
8267
- }) => {
8289
+ }, "commandApproveBudget"), commandRejectBudget = __name2(async ({ flags, positional }) => {
8268
8290
  const id = positional[0], reason = getFlag(flags, "reason");
8269
8291
  if (!id || reason === void 0) throw new Error("reject-budget requires <budgetId> --reason <text>");
8270
8292
  await rejectBudget(id, reason);
8271
- }, "commandRejectBudget"), commandApproveSupplier = __name2(async ({ positional }) => {
8293
+ }, "commandRejectBudget"), commandApproveSupplier = __name2(async ({
8294
+ positional
8295
+ }) => {
8272
8296
  const id = positional[0];
8273
8297
  if (!id) throw new Error("approve-supplier requires <supplierId>");
8274
8298
  await approveSupplier(id);
@@ -8287,7 +8311,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8287
8311
  }, "commandGetSupplierOverview"), commandGetSupplierUsage = __name2(async ({ positional }) => {
8288
8312
  const id = positional[0];
8289
8313
  if (!id) throw new Error("get-supplier-usage requires <supplierId>");
8290
- await getSupplierUsage(id);
8314
+ await getSupplierUsage(
8315
+ id
8316
+ );
8291
8317
  }, "commandGetSupplierUsage"), commandGetSupplierItems = __name2(async ({ positional }) => {
8292
8318
  const id = positional[0];
8293
8319
  if (!id) throw new Error("get-supplier-items requires <supplierId>");
@@ -8302,10 +8328,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8302
8328
  await getCompany(id);
8303
8329
  }, "commandGetCompany"), commandCreateCompany = __name2(async ({ flags }) => {
8304
8330
  rejectBareFlag(flags, "billingEmails");
8305
- const billingEmailsRaw = getFlag(
8306
- flags,
8307
- "billingEmails"
8308
- ), billingEmails = billingEmailsRaw === void 0 ? void 0 : parseCompanyBillingEmails(parseJsonFlag(billingEmailsRaw, "--billingEmails")), name = getFlag(flags, "name"), website = getFlag(flags, "website");
8331
+ const billingEmailsRaw = getFlag(flags, "billingEmails"), billingEmails = billingEmailsRaw === void 0 ? void 0 : parseCompanyBillingEmails(parseJsonFlag(billingEmailsRaw, "--billingEmails")), name = getFlag(flags, "name"), website = getFlag(flags, "website");
8309
8332
  if (!name || !website) throw new Error("create-company requires --name and --website <url>");
8310
8333
  await createCompany({ name, website, ...billingEmails === void 0 ? {} : { billingEmails }, confirmDistinct: parseOptionalBoolFlag(flags, "confirmDistinct") });
8311
8334
  }, "commandCreateCompany"), commandSearchExistingCompanies = __name2(async ({ flags }) => {
@@ -8319,20 +8342,23 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8319
8342
  if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > 50)) throw new Error("--limit must be an integer from 1 to 50.");
8320
8343
  await searchExistingCompanies({ query, limit, cursor });
8321
8344
  }, "commandSearchExistingCompanies"), commandUseExistingCompany = __name2(async ({ flags }) => {
8322
- const companyId = getFlag(flags, "companyId"), quickbooksId = getFlag(flags, "quickbooksId");
8345
+ const companyId = getFlag(
8346
+ flags,
8347
+ "companyId"
8348
+ ), quickbooksId = getFlag(flags, "quickbooksId");
8323
8349
  if (!companyId && !quickbooksId) throw new Error("Supply --companyId and/or --quickbooksId");
8324
8350
  companyId ? await reuseExistingCompany({ source: "bb", companyId, quickbooksId, confirmDistinct: parseOptionalBoolFlag(flags, "confirmDistinct") }) : quickbooksId && await reuseExistingCompany({ source: "qbo", quickbooksId, name: getFlag(flags, "name"), website: getFlag(flags, "website"), confirmDistinct: parseOptionalBoolFlag(flags, "confirmDistinct") });
8325
8351
  }, "commandUseExistingCompany"), commandUpdateCompany = __name2(async ({ flags }) => {
8326
8352
  const payloadRaw = getFlag(flags, "payload");
8327
8353
  if (!payloadRaw) throw new Error("update-company requires --payload '<json>'");
8328
8354
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
8329
- await updateCompanyFromPayload(
8330
- raw
8331
- );
8355
+ await updateCompanyFromPayload(raw);
8332
8356
  }, "commandUpdateCompany"), commandGetCompanyQuickbooksSyncStatus = __name2(async ({ positional }) => {
8333
8357
  const id = positional[0];
8334
8358
  if (!id) throw new Error("get-company-quickbooks-sync-status requires <companyId>");
8335
- await getCompanyQuickBooksSyncStatus(id);
8359
+ await getCompanyQuickBooksSyncStatus(
8360
+ id
8361
+ );
8336
8362
  }, "commandGetCompanyQuickbooksSyncStatus"), commandDeleteCompany = __name2(async ({ positional }) => {
8337
8363
  const id = positional[0];
8338
8364
  if (!id) throw new Error("delete-company requires <id>");
@@ -8359,36 +8385,33 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8359
8385
  const id = positional[0];
8360
8386
  if (!id) throw new Error("get-project requires <id>");
8361
8387
  await getProject(id);
8362
- }, "commandGetProject"), commandGetProjectHubStatus = __name2(
8388
+ }, "commandGetProject"), commandGetProjectHubStatus = __name2(async ({ positional }) => {
8389
+ const projectId = positional[0];
8390
+ if (!projectId) throw new Error("get-project-hub-status requires <projectId>");
8391
+ await getProjectHubStatus(projectId);
8392
+ }, "commandGetProjectHubStatus"), commandSetupProjectHub = __name2(
8363
8393
  async ({ positional }) => {
8364
8394
  const projectId = positional[0];
8365
- if (!projectId) throw new Error("get-project-hub-status requires <projectId>");
8366
- await getProjectHubStatus(projectId);
8395
+ if (!projectId) throw new Error("setup-project-hub requires <projectId>");
8396
+ await setupProjectHub(projectId);
8367
8397
  },
8368
- "commandGetProjectHubStatus"
8369
- ), commandSetupProjectHub = __name2(async ({ positional }) => {
8370
- const projectId = positional[0];
8371
- if (!projectId) throw new Error("setup-project-hub requires <projectId>");
8372
- await setupProjectHub(projectId);
8373
- }, "commandSetupProjectHub"), commandSyncProjectHubCommercialDocuments = __name2(async ({ positional }) => {
8398
+ "commandSetupProjectHub"
8399
+ ), commandSyncProjectHubCommercialDocuments = __name2(async ({ positional }) => {
8374
8400
  const projectId = positional[0];
8375
8401
  if (!projectId) throw new Error("sync-project-hub-commercial-documents requires <projectId>");
8376
8402
  await syncProjectHubCommercialDocuments(projectId);
8377
- }, "commandSyncProjectHubCommercialDocuments"), commandCreateProject = __name2(
8378
- async ({ flags }) => {
8379
- const name = getFlag(flags, "name"), companyId = getFlag(flags, "companyId"), contactPersonId = getFlag(flags, "contactPersonId"), insideSalesId = getFlag(flags, "insideSalesId"), businessDevelopmentId = getFlag(flags, "businessDevelopmentId"), projectManagerId = getFlag(
8380
- flags,
8381
- "projectManagerId"
8382
- ), venue = getFlag(flags, "venue"), pax = getFlag(flags, "pax"), asanaTaskId = getFlag(flags, "asanaTaskId"), asanaSearch = getFlag(flags, "asanaSearch"), startDate = getFlag(flags, "startDate");
8383
- if (getFlag(flags, "requestQboAccountantNotification") !== void 0) throw new Error("create-project does not allow --requestQboAccountantNotification; CLI project creation always requests the QuickBooks project import like the web app.");
8384
- if (!name || !companyId || !contactPersonId || !insideSalesId || !businessDevelopmentId || !venue || !startDate) throw new Error("create-project requires --name --companyId --contactPersonId --insideSalesId --businessDevelopmentId --venue --startDate (ISO/datetime flags as appropriate); optional --projectManagerId, --asanaTaskId, --asanaSearch, --pax and --endDate");
8385
- await createProject({ name, companyId, contactPersonId, insideSalesId, businessDevelopmentId, projectManagerId, venue, pax, asanaTaskId, asanaSearch, startDate, endDate: getFlag(flags, "endDate"), description: getFlag(flags, "description") });
8386
- },
8387
- "commandCreateProject"
8388
- ), commandUpdateProject = __name2(async ({ flags }) => {
8403
+ }, "commandSyncProjectHubCommercialDocuments"), commandCreateProject = __name2(async ({ flags }) => {
8404
+ const name = getFlag(flags, "name"), companyId = getFlag(flags, "companyId"), contactPersonId = getFlag(flags, "contactPersonId"), insideSalesId = getFlag(flags, "insideSalesId"), businessDevelopmentId = getFlag(flags, "businessDevelopmentId"), projectManagerId = getFlag(flags, "projectManagerId"), venue = getFlag(flags, "venue"), pax = getFlag(flags, "pax"), asanaTaskId = getFlag(flags, "asanaTaskId"), asanaSearch = getFlag(flags, "asanaSearch"), startDate = getFlag(flags, "startDate");
8405
+ if (getFlag(flags, "requestQboAccountantNotification") !== void 0) throw new Error("create-project does not allow --requestQboAccountantNotification; CLI project creation always requests the QuickBooks project import like the web app.");
8406
+ if (!name || !companyId || !contactPersonId || !insideSalesId || !businessDevelopmentId || !venue || !startDate) throw new Error("create-project requires --name --companyId --contactPersonId --insideSalesId --businessDevelopmentId --venue --startDate (ISO/datetime flags as appropriate); optional --projectManagerId, --asanaTaskId, --asanaSearch, --pax and --endDate");
8407
+ await createProject({ name, companyId, contactPersonId, insideSalesId, businessDevelopmentId, projectManagerId, venue, pax, asanaTaskId, asanaSearch, startDate, endDate: getFlag(flags, "endDate"), description: getFlag(flags, "description") });
8408
+ }, "commandCreateProject"), commandUpdateProject = __name2(async ({ flags }) => {
8389
8409
  const payloadRaw = getFlag(flags, "payload");
8390
8410
  if (!payloadRaw) throw new Error("update-project requires --payload '<json>'");
8391
- const raw = parseJsonFlag(String(payloadRaw), "--payload");
8411
+ const raw = parseJsonFlag(
8412
+ String(payloadRaw),
8413
+ "--payload"
8414
+ );
8392
8415
  await updateProjectFromPayload(raw);
8393
8416
  }, "commandUpdateProject"), commandDeleteProject = __name2(async ({ positional }) => {
8394
8417
  const id = positional[0];
@@ -8404,9 +8427,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8404
8427
  await reconcileProject(id);
8405
8428
  }, "commandReconcileProject"), commandCompleteProject = __name2(async ({ positional }) => {
8406
8429
  const id = positional[0];
8407
- if (!id) throw new Error(
8408
- "complete-project requires <id>"
8409
- );
8430
+ if (!id) throw new Error("complete-project requires <id>");
8410
8431
  await completeProject(id);
8411
8432
  }, "commandCompleteProject"), commandImportQboProject = __name2(async ({ flags, positional }) => {
8412
8433
  const projectId = positional[0], projectUrl = getFlag(flags, "url");
@@ -8436,19 +8457,19 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8436
8457
  }, "commandCountSuppliers"), commandListSuppliers = __name2(async ({ flags }) => {
8437
8458
  await listSuppliers(parseListSuppliersFlags(flags));
8438
8459
  }, "commandListSuppliers"), commandCreateSupplier = __name2(async ({ flags }) => {
8439
- const payloadRaw = getFlag(
8440
- flags,
8441
- "payload"
8442
- );
8460
+ const payloadRaw = getFlag(flags, "payload");
8443
8461
  if (!payloadRaw) throw new Error("create-supplier requires --payload '<json>'");
8444
8462
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
8445
8463
  await createSupplierFromPayload(raw);
8446
- }, "commandCreateSupplier"), commandUpdateSupplier = __name2(async ({ flags }) => {
8447
- const payloadRaw = getFlag(flags, "payload");
8448
- if (!payloadRaw) throw new Error("update-supplier requires --payload '<json>'");
8449
- const raw = parseJsonFlag(String(payloadRaw), "--payload");
8450
- await updateSupplierFromPayload(raw);
8451
- }, "commandUpdateSupplier"), commandDeleteSuppliers = __name2(async ({ flags }) => {
8464
+ }, "commandCreateSupplier"), commandUpdateSupplier = __name2(
8465
+ async ({ flags }) => {
8466
+ const payloadRaw = getFlag(flags, "payload");
8467
+ if (!payloadRaw) throw new Error("update-supplier requires --payload '<json>'");
8468
+ const raw = parseJsonFlag(String(payloadRaw), "--payload");
8469
+ await updateSupplierFromPayload(raw);
8470
+ },
8471
+ "commandUpdateSupplier"
8472
+ ), commandDeleteSuppliers = __name2(async ({ flags }) => {
8452
8473
  const idsRaw = getFlag(flags, "ids");
8453
8474
  if (idsRaw === void 0) throw new Error("delete-suppliers requires --ids <csv>");
8454
8475
  const ids = parseCommaSeparatedIds(String(idsRaw));
@@ -8460,7 +8481,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8460
8481
  const ids = parseCommaSeparatedIds(String(idsRaw));
8461
8482
  if (!ids?.length) throw new Error("reactivate-suppliers requires non-empty --ids");
8462
8483
  await reactivateSuppliersByIds(ids);
8463
- }, "commandReactivateSuppliers"), commandCreateCertification = __name2(async ({ flags }) => {
8484
+ }, "commandReactivateSuppliers"), commandCreateCertification = __name2(async ({
8485
+ flags
8486
+ }) => {
8464
8487
  const name = getFlag(flags, "name");
8465
8488
  if (!name) throw new Error("create-certification requires --name");
8466
8489
  await createSupplierCertification(String(name));
@@ -8479,7 +8502,15 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8479
8502
  }, "commandCreateSupplierTag"), supplierAnalyticsFiltersFromFlags = __name2((flags) => {
8480
8503
  rejectRetiredPageFlags(flags);
8481
8504
  const tfRaw = getFlag(flags, "timeFrame");
8482
- for (const key of ["name", "status", "gstRegistered", "createdBy", "startDate", "endDate", "timeFrame"]) rejectBareFlag(flags, key);
8505
+ for (const key of [
8506
+ "name",
8507
+ "status",
8508
+ "gstRegistered",
8509
+ "createdBy",
8510
+ "startDate",
8511
+ "endDate",
8512
+ "timeFrame"
8513
+ ]) rejectBareFlag(flags, key);
8483
8514
  const timeFrame = parseOptionalSupplierAnalyticsTimeFrame(tfRaw !== void 0 ? String(tfRaw) : void 0), startDate = getFlag(flags, "startDate"), endDate = getFlag(flags, "endDate");
8484
8515
  if ((startDate || endDate) && timeFrame !== "CUSTOM") throw new Error("--startDate/--endDate need --timeFrame CUSTOM; other time frames ignore them.");
8485
8516
  const status = getFlag(flags, "status")?.split(",").map((value) => value.trim()).filter(Boolean), badStatus = status?.find((value) => !Object.values(ApprovalStatus2).some((s) => s === value));
@@ -8515,7 +8546,8 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8515
8546
  await getItem(id);
8516
8547
  }, "commandGetItem"), commandGetItemQuickbooksSyncStatus = __name2(async ({ positional }) => {
8517
8548
  const id = positional[0];
8518
- if (!id) throw new Error("get-item-quickbooks-sync-status requires <itemId>");
8549
+ if (!id)
8550
+ throw new Error("get-item-quickbooks-sync-status requires <itemId>");
8519
8551
  await getItemQuickBooksSyncStatus(id);
8520
8552
  }, "commandGetItemQuickbooksSyncStatus"), commandCreateItem = __name2(async ({ flags }) => {
8521
8553
  const payloadRaw = getFlag(flags, "payload");
@@ -8534,7 +8566,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8534
8566
  }, "commandDeleteItem"), commandArchiveItems = __name2(async ({ flags }) => {
8535
8567
  const idsRaw = getFlag(flags, "ids");
8536
8568
  if (!idsRaw) throw new Error("archive-items requires --ids <csv>");
8537
- const ids = parseCommaSeparatedIds(String(idsRaw));
8569
+ const ids = parseCommaSeparatedIds(
8570
+ String(idsRaw)
8571
+ );
8538
8572
  if (!ids?.length) throw new Error("archive-items requires non-empty --ids");
8539
8573
  await archiveItemsByIds(ids);
8540
8574
  }, "commandArchiveItems"), commandListItemCategories = __name2(async ({ cmd, flags }) => {
@@ -8547,13 +8581,12 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8547
8581
  rejectBarePagingFlags(flags);
8548
8582
  const { cursor, direction } = parseCursorAndDirection(flags), sortByRaw = getFlag(flags, "sortBy"), sortBy = ITEM_CATEGORY_SORT_IDS.find((id) => id === sortByRaw);
8549
8583
  if (sortByRaw !== void 0 && !sortBy) throw new Error('Invalid --sortBy "'.concat(sortByRaw, '". Use one of: ').concat(ITEM_CATEGORY_SORT_IDS.join(", "), "."));
8550
- const sortDir = parseAscDescSortDir(
8551
- flags
8552
- );
8584
+ const sortDir = parseAscDescSortDir(flags);
8553
8585
  await listItemCategories({ ...filters, limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sortBy, sortDir });
8554
8586
  }, "commandListItemCategories"), commandCreateItemCategory = __name2(async ({ flags }) => {
8555
8587
  const name = getFlag(flags, "name");
8556
- if (!name) throw new Error("create-item-category requires --name");
8588
+ if (!name)
8589
+ throw new Error("create-item-category requires --name");
8557
8590
  await createItemCategory(String(name));
8558
8591
  }, "commandCreateItemCategory"), commandUpdateItemCategory = __name2(async ({ flags }) => {
8559
8592
  const id = getFlag(flags, "id"), name = getFlag(flags, "name");
@@ -8612,7 +8645,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8612
8645
  }, "commandGetSystemOverview"), commandGetEstimatePerformance = __name2(async ({ flags }) => {
8613
8646
  await getEstimatePerformance(parseDashboardQueryFlags(flags));
8614
8647
  }, "commandGetEstimatePerformance"), commandGetFinancialOverview = __name2(async ({ flags }) => {
8615
- await getFinancialOverview({ userId: getFlag(flags, "userId"), role: parseOptionalFinancialRole(getFlag(flags, "role")), deals: parseOptionalDeals(getFlag(flags, "deals")), timeFrame: parseOptionalTimeFrame(getFlag(flags, "timeFrame")), startDate: getFlag(flags, "startDate"), endDate: getFlag(flags, "endDate") });
8648
+ await getFinancialOverview(
8649
+ { userId: getFlag(flags, "userId"), role: parseOptionalFinancialRole(getFlag(flags, "role")), deals: parseOptionalDeals(getFlag(flags, "deals")), timeFrame: parseOptionalTimeFrame(getFlag(flags, "timeFrame")), startDate: getFlag(flags, "startDate"), endDate: getFlag(flags, "endDate") }
8650
+ );
8616
8651
  }, "commandGetFinancialOverview"), commandGetRecentErrors = __name2(async ({ cmd, flags }) => {
8617
8652
  if (getFlag(flags, "page") !== void 0 || getFlag(flags, "perPage") !== void 0) throw new Error("Error logs now use --cursor and --limit; --page/--perPage are no longer supported.");
8618
8653
  const rawTimeFrame = getFlag(flags, "timeFrame"), timeFrame = Object.values(ChartTimeFrame).find((value) => value === rawTimeFrame);
@@ -8620,7 +8655,10 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8620
8655
  const filters = { severity: parseOptionalErrorSeverity(getFlag(flags, "severity")), status: parseOptionalErrorStatus(getFlag(flags, "status")), timeFrame };
8621
8656
  if (cmd === "count-errors") await countErrors(filters);
8622
8657
  else {
8623
- const direction = getFlag(flags, "direction");
8658
+ const direction = getFlag(
8659
+ flags,
8660
+ "direction"
8661
+ );
8624
8662
  if (direction !== void 0 && direction !== "forward" && direction !== "backward") throw new Error("--direction must be forward or backward.");
8625
8663
  await getRecentErrors({ ...filters, cursor: getFlag(flags, "cursor"), limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit"), direction });
8626
8664
  }
@@ -8632,10 +8670,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8632
8670
  await getErrorMetrics();
8633
8671
  }, "commandGetErrorMetrics"), commandListIntegrationOperations = __name2(async ({ cmd, flags }) => {
8634
8672
  rejectRetiredPageFlags(flags);
8635
- const filters = { destination: parseCommaSeparatedIds(getFlag(flags, "destination")), search: getFlag(
8636
- flags,
8637
- "search"
8638
- ), status: parseCommaSeparatedIntegrationOperationStatuses(getFlag(flags, "status")) };
8673
+ const filters = { destination: parseCommaSeparatedIds(getFlag(flags, "destination")), search: getFlag(flags, "search"), status: parseCommaSeparatedIntegrationOperationStatuses(getFlag(flags, "status")) };
8639
8674
  if (cmd === "count-integration-operations") {
8640
8675
  for (const key of ["limit", "cursor", "direction"]) if (flags[key] !== void 0) throw new Error("count-integration-operations does not accept --".concat(key, "; it takes filter flags only."));
8641
8676
  await countIntegrationOperations(filters);
@@ -8648,27 +8683,31 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8648
8683
  if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
8649
8684
  const limitRaw = getFlag(flags, "limit");
8650
8685
  await listIntegrationOperations({ ...filters, limit: limitRaw === void 0 ? 25 : parseProjectLimit(limitRaw), cursor, direction });
8651
- }, "commandListIntegrationOperations"), commandGetIntegrationOperation = __name2(
8652
- async ({ positional }) => {
8686
+ }, "commandListIntegrationOperations"), commandGetIntegrationOperation = __name2(async ({ positional }) => {
8687
+ const operationId = positional[0];
8688
+ if (!operationId) throw new Error("get-integration-operation requires <operationId>");
8689
+ await getIntegrationOperation(operationId);
8690
+ }, "commandGetIntegrationOperation"), commandRetryIntegrationOperation = __name2(
8691
+ async ({ flags, positional }) => {
8653
8692
  const operationId = positional[0];
8654
- if (!operationId) throw new Error("get-integration-operation requires <operationId>");
8655
- await getIntegrationOperation(operationId);
8693
+ if (!operationId) throw new Error("retry-integration-operation requires <operationId>");
8694
+ const outboundEmailResolution = getFlag(flags, "outboundEmailResolution");
8695
+ if (outboundEmailResolution && outboundEmailResolution !== "ACCEPTED" && outboundEmailResolution !== "NOT_ACCEPTED_RETRY") throw new Error("--outboundEmailResolution must be ACCEPTED or NOT_ACCEPTED_RETRY");
8696
+ await retryIntegrationOperation(operationId, parseOptionalBoolFlag(flags, "confirmExternalStateReconciled") ?? !1, outboundEmailResolution, getFlag(flags, "providerMessageId"));
8656
8697
  },
8657
- "commandGetIntegrationOperation"
8658
- ), commandRetryIntegrationOperation = __name2(async ({ flags, positional }) => {
8659
- const operationId = positional[0];
8660
- if (!operationId) throw new Error("retry-integration-operation requires <operationId>");
8661
- const outboundEmailResolution = getFlag(flags, "outboundEmailResolution");
8662
- if (outboundEmailResolution && outboundEmailResolution !== "ACCEPTED" && outboundEmailResolution !== "NOT_ACCEPTED_RETRY") throw new Error("--outboundEmailResolution must be ACCEPTED or NOT_ACCEPTED_RETRY");
8663
- await retryIntegrationOperation(operationId, parseOptionalBoolFlag(flags, "confirmExternalStateReconciled") ?? !1, outboundEmailResolution, getFlag(flags, "providerMessageId"));
8664
- }, "commandRetryIntegrationOperation"), commandListWebhookEventTypes = __name2(async () => {
8698
+ "commandRetryIntegrationOperation"
8699
+ ), commandMobilePushStatus = __name2(async ({ positional }) => {
8700
+ if (positional.length !== 0) throw new CliRuntimeError("USAGE", "mobile-push status accepts no positional arguments.");
8701
+ await listMobilePushDevices();
8702
+ }, "commandMobilePushStatus"), commandMobilePushUnregister = __name2(async ({ positional }) => {
8703
+ const sessionId = positional[0];
8704
+ if (!sessionId || positional.length !== 1) throw new CliRuntimeError("USAGE", "mobile-push unregister requires one <sessionId>.");
8705
+ await unregisterMobilePushDevice(sessionId);
8706
+ }, "commandMobilePushUnregister"), commandListWebhookEventTypes = __name2(async () => {
8665
8707
  await listWebhookEventTypes();
8666
- }, "commandListWebhookEventTypes"), commandListWebhookEndpoints = __name2(
8667
- async () => {
8668
- await listWebhookEndpoints();
8669
- },
8670
- "commandListWebhookEndpoints"
8671
- ), commandGetWebhookEndpoint = __name2(async ({ positional }) => {
8708
+ }, "commandListWebhookEventTypes"), commandListWebhookEndpoints = __name2(async () => {
8709
+ await listWebhookEndpoints();
8710
+ }, "commandListWebhookEndpoints"), commandGetWebhookEndpoint = __name2(async ({ positional }) => {
8672
8711
  const id = positional[0];
8673
8712
  if (!id) throw new Error("get-webhook-endpoint requires <id>");
8674
8713
  await getWebhookEndpoint(id);
@@ -8676,12 +8715,15 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8676
8715
  const name = getFlag(flags, "name"), url = getFlag(flags, "url"), events = parseCommaSeparatedIds(getFlag(flags, "events"));
8677
8716
  if (!name || !url || !events?.length) throw new Error("create-webhook-endpoint requires --name, --url and --events");
8678
8717
  await createWebhookEndpoint({ name, url, eventPatterns: events, enabled: parseOptionalBoolFlag(flags, "enabled") ?? !0 });
8679
- }, "commandCreateWebhookEndpoint"), commandUpdateWebhookEndpoint = __name2(async ({ flags, positional }) => {
8680
- const id = positional[0];
8681
- if (!id) throw new Error("update-webhook-endpoint requires <id>");
8682
- const events = parseCommaSeparatedIds(getFlag(flags, "events"));
8683
- await updateWebhookEndpoint({ id, name: getFlag(flags, "name"), url: getFlag(flags, "url"), eventPatterns: events?.length ? events : void 0, enabled: parseOptionalBoolFlag(flags, "enabled") });
8684
- }, "commandUpdateWebhookEndpoint"), commandDeleteWebhookEndpoint = __name2(async ({ positional }) => {
8718
+ }, "commandCreateWebhookEndpoint"), commandUpdateWebhookEndpoint = __name2(
8719
+ async ({ flags, positional }) => {
8720
+ const id = positional[0];
8721
+ if (!id) throw new Error("update-webhook-endpoint requires <id>");
8722
+ const events = parseCommaSeparatedIds(getFlag(flags, "events"));
8723
+ await updateWebhookEndpoint({ id, name: getFlag(flags, "name"), url: getFlag(flags, "url"), eventPatterns: events?.length ? events : void 0, enabled: parseOptionalBoolFlag(flags, "enabled") });
8724
+ },
8725
+ "commandUpdateWebhookEndpoint"
8726
+ ), commandDeleteWebhookEndpoint = __name2(async ({ positional }) => {
8685
8727
  const id = positional[0];
8686
8728
  if (!id) throw new Error("delete-webhook-endpoint requires <id>");
8687
8729
  await deleteWebhookEndpoint(id);
@@ -8696,14 +8738,15 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8696
8738
  await sendWebhookTestEvent(id);
8697
8739
  }, "commandSendWebhookTestEvent"), commandListWebhookDeliveries = __name2(async ({ flags }) => {
8698
8740
  const statuses = (getFlag(flags, "status") ?? "").split(",").map((value) => value.trim()).filter(Boolean);
8699
- for (const status of statuses)
8700
- if (status !== "PENDING" && status !== "SUCCEEDED" && status !== "FAILED") throw new Error("--status must be PENDING, SUCCEEDED or FAILED (comma-separated)");
8741
+ for (const status of statuses) if (status !== "PENDING" && status !== "SUCCEEDED" && status !== "FAILED") throw new Error("--status must be PENDING, SUCCEEDED or FAILED (comma-separated)");
8701
8742
  const cursor = getFlag(flags, "cursor"), direction = parseProjectDirection(getFlag(flags, "direction"));
8702
8743
  if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
8703
8744
  await listWebhookDeliveries({ endpointId: getFlag(flags, "endpointId"), ...statuses.length ? { status: statuses } : {}, eventType: getFlag(flags, "eventType"), cursor, direction, limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") });
8704
8745
  }, "commandListWebhookDeliveries"), commandGetWebhookDelivery = __name2(async ({ positional }) => {
8705
8746
  const id = positional[0];
8706
- if (!id) throw new Error("get-webhook-delivery requires <id>");
8747
+ if (!id) throw new Error(
8748
+ "get-webhook-delivery requires <id>"
8749
+ );
8707
8750
  await getWebhookDelivery(id);
8708
8751
  }, "commandGetWebhookDelivery"), commandReplayWebhookDelivery = __name2(async ({ positional }) => {
8709
8752
  const id = positional[0];
@@ -8732,8 +8775,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8732
8775
  }, "parseInboundSourcePaging"), commandListInboundSources = __name2(async ({ cmd, flags }) => {
8733
8776
  const filters = inboundSourceFiltersFromFlags(flags);
8734
8777
  if (cmd === "count-inbound-sources") {
8735
- if (["limit", "cursor", "direction"].some((key) => flags[key] !== void 0))
8736
- throw new Error("Source counts accept filters only, not pagination flags.");
8778
+ if (["limit", "cursor", "direction"].some((key) => flags[key] !== void 0)) throw new Error("Source counts accept filters only, not pagination flags.");
8737
8779
  await countInboundSources(filters);
8738
8780
  } else {
8739
8781
  const { cursor, direction, limit } = parseInboundSourcePaging(flags);
@@ -8745,7 +8787,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8745
8787
  await createInboundSource({ externalSourceId, name });
8746
8788
  }, "commandCreateInboundSource"), commandGetInboundSource = __name2(async ({ positional }) => {
8747
8789
  const sourceId = positional[0];
8748
- if (!sourceId) throw new Error("get-inbound-source requires <sourceId>");
8790
+ if (!sourceId) throw new Error(
8791
+ "get-inbound-source requires <sourceId>"
8792
+ );
8749
8793
  await getInboundSource(sourceId);
8750
8794
  }, "commandGetInboundSource"), commandUpdateInboundSource = __name2(async ({ flags, positional }) => {
8751
8795
  const sourceId = positional[0], name = getFlag(flags, "name");
@@ -8756,11 +8800,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8756
8800
  await listInboundSubmissions({ cursor: getFlag(flags, "cursor"), limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") ?? 25, sourceId: getFlag(flags, "sourceId") });
8757
8801
  }, "commandListInboundSubmissions"), commandCountInboundSubmissions = __name2(async ({ flags }) => {
8758
8802
  await countInboundSubmissions({ sourceId: getFlag(flags, "sourceId") });
8759
- }, "commandCountInboundSubmissions"), commandGetInboundSubmission = __name2(async ({ positional }) => {
8760
- const submissionId = positional[0];
8761
- if (!submissionId) throw new Error("get-inbound-submission requires <submissionId>");
8762
- await getInboundSubmission(submissionId);
8763
- }, "commandGetInboundSubmission"), commandSaveInboundMapping = __name2(async ({ flags, positional }) => {
8803
+ }, "commandCountInboundSubmissions"), commandGetInboundSubmission = __name2(
8804
+ async ({ positional }) => {
8805
+ const submissionId = positional[0];
8806
+ if (!submissionId) throw new Error("get-inbound-submission requires <submissionId>");
8807
+ await getInboundSubmission(submissionId);
8808
+ },
8809
+ "commandGetInboundSubmission"
8810
+ ), commandSaveInboundMapping = __name2(async ({ flags, positional }) => {
8764
8811
  const sourceId = positional[0], payloadRaw = getFlag(flags, "payload");
8765
8812
  if (!sourceId || payloadRaw === void 0) throw new Error("save-inbound-mapping requires <sourceId> --payload <JSON array>");
8766
8813
  const mappings = parseJsonFlag(String(payloadRaw), "--payload");
@@ -8778,12 +8825,12 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8778
8825
  await getApprovedBudgets({ projectId: getFlag(flags, "projectId"), limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit"), minRevenue: parseOptionalNumber(getFlag(flags, "minRevenue"), "--minRevenue"), maxRevenue: parseOptionalNumber(getFlag(flags, "maxRevenue"), "--maxRevenue") });
8779
8826
  }, "commandGetApprovedBudgets"), commandGetBudgetCategoryBenchmarks = __name2(async ({ flags, positional }) => {
8780
8827
  const id = positional[0];
8781
- if (!id) throw new Error("get-budget-category-benchmarks requires <categoryId> [--limit]");
8828
+ if (!id) throw new Error(
8829
+ "get-budget-category-benchmarks requires <categoryId> [--limit]"
8830
+ );
8782
8831
  await getBudgetCategoryBenchmarks({ categoryId: id, limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") });
8783
8832
  }, "commandGetBudgetCategoryBenchmarks"), commandGetItemPricingHistory = __name2(async ({ flags }) => {
8784
- await getItemPricingHistory(
8785
- { itemName: getFlag(flags, "itemName"), categoryId: getFlag(flags, "categoryId"), supplierId: getFlag(flags, "supplierId"), limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") }
8786
- );
8833
+ await getItemPricingHistory({ itemName: getFlag(flags, "itemName"), categoryId: getFlag(flags, "categoryId"), supplierId: getFlag(flags, "supplierId"), limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") });
8787
8834
  }, "commandGetItemPricingHistory"), commandGetSupplierPricingHistory = __name2(async ({ flags, positional }) => {
8788
8835
  const id = positional[0];
8789
8836
  if (!id) throw new Error("get-supplier-pricing-history requires <supplierId> [--itemCategoryId] [--limit]");
@@ -8838,10 +8885,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8838
8885
  ["update-bill-payment-evidence", commandUpdateBillPaymentEvidence],
8839
8886
  ["delete-bill", commandDeleteBill],
8840
8887
  ["update-bill-status", commandUpdateBillStatus],
8841
- [
8842
- "list-external-payment-accounts",
8843
- commandListExternalPaymentAccounts
8844
- ],
8888
+ ["list-external-payment-accounts", commandListExternalPaymentAccounts],
8845
8889
  ["refresh-external-payment-accounts", commandRefreshExternalPaymentAccounts],
8846
8890
  ["record-external-bill-payment", commandRecordExternalBillPayment],
8847
8891
  ["patch-bill-payment", commandPatchBillPayment],
@@ -8936,10 +8980,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8936
8980
  ["sync-project-hub-commercial-documents", commandSyncProjectHubCommercialDocuments],
8937
8981
  ["create-project", commandCreateProject],
8938
8982
  ["update-project", commandUpdateProject],
8939
- [
8940
- "delete-project",
8941
- commandDeleteProject
8942
- ],
8983
+ ["delete-project", commandDeleteProject],
8943
8984
  ["check-project-reconciliation", commandCheckProjectReconciliation],
8944
8985
  ["reconcile-project", commandReconcileProject],
8945
8986
  ["complete-project", commandCompleteProject],
@@ -8993,6 +9034,8 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8993
9034
  ["count-integration-operations", commandListIntegrationOperations],
8994
9035
  ["get-integration-operation", commandGetIntegrationOperation],
8995
9036
  ["retry-integration-operation", commandRetryIntegrationOperation],
9037
+ ["mobile-push-status", commandMobilePushStatus],
9038
+ ["mobile-push-unregister", commandMobilePushUnregister],
8996
9039
  ["list-webhook-event-types", commandListWebhookEventTypes],
8997
9040
  ["list-webhook-endpoints", commandListWebhookEndpoints],
8998
9041
  ["get-webhook-endpoint", commandGetWebhookEndpoint],
@@ -9020,18 +9063,17 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
9020
9063
  ["get-budget-category-benchmarks", commandGetBudgetCategoryBenchmarks],
9021
9064
  ["get-item-pricing-history", commandGetItemPricingHistory],
9022
9065
  ["get-supplier-pricing-history", commandGetSupplierPricingHistory]
9023
- ]), dispatchCliCommand = __name2(
9024
- async (context) => {
9025
- const handler = CLI_COMMAND_HANDLERS.get(context.cmd);
9026
- if (!handler) throw new Error("Unknown command: ".concat(context.cmd, ". Run 'bb help'."));
9027
- await handler(context);
9028
- },
9029
- "dispatchCliCommand"
9030
- ), startCliSession = __name2((context, command) => {
9066
+ ]), dispatchCliCommand = __name2(async (context) => {
9067
+ const handler = CLI_COMMAND_HANDLERS.get(context.cmd);
9068
+ if (!handler) throw new Error("Unknown command: ".concat(context.cmd, ". Run 'bb help'."));
9069
+ await handler(context);
9070
+ }, "dispatchCliCommand"), startCliSession = __name2((context, command) => {
9031
9071
  setActiveCliSession({ runtime: context.runtime, invocation: { command, cliVersion: context.version, apiBaseUrl: BUDGET_BUILDER_API_BASE_URL, quiet: context.quiet, debug: context.debug }, effects: [], permissions: {} });
9032
9072
  }, "startCliSession"), failCliSession = __name2((context, command, error2) => {
9033
9073
  startCliSession(context, command);
9034
- const exitCode = emitCommandError(error2);
9074
+ const exitCode = emitCommandError(
9075
+ error2
9076
+ );
9035
9077
  return clearActiveCliSession(), exitCode;
9036
9078
  }, "failCliSession"), resolveRootArguments = __name2((rawArgv, runtime) => {
9037
9079
  const rootArguments = parseRootArguments(rawArgv), apiBaseUrl = rootArguments.apiBaseUrl ?? runtime.env.BB_API_URL?.trim();
@@ -9043,10 +9085,13 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
9043
9085
  }
9044
9086
  const helpArgv = commandArgv.filter((argument, index) => argument !== "-h" && argument !== "--help" && !argument.startsWith("--help=") && !(commandArgv[index - 1] === "--help" && booleanFlagValues.has(argument))), helpCommand = resolveCommand(helpArgv[0] === "help" ? helpArgv.slice(1) : helpArgv)?.command;
9045
9087
  runtime.stdout.write("".concat(createHumanHelp(helpCommand), "\n"));
9046
- }, "printCliHelp"), runCompletionCommand = __name2((context, commandArgv) => {
9047
- const shell = commandArgv[1];
9048
- return shell === void 0 || !isCompletionShell(shell) ? failCliSession(context, "completion", new CliRuntimeError("USAGE", "completion requires bash, zsh, fish, or powershell.")) : (context.runtime.stdout.write(createCompletionScript(shell)), 0);
9049
- }, "runCompletionCommand"), isVersionRequest = __name2((commandArgv) => commandArgv[0] === "version" || isEnabledFlag(commandArgv, "--version") || commandArgv.includes("-v"), "isVersionRequest"), runVersionCommand = __name2((context) => (startCliSession(context, "version"), emitCommandResult(getVersionData()), clearActiveCliSession(), 0), "runVersionCommand"), createDefaultCredentialStore = __name2((runtime) => createBunCredentialStore({ account: resolveCliCredentialAccount(runtime.env), product: "budget-builder" }), "createDefaultCredentialStore"), authStatusResult = __name2(async (runtime, store) => {
9088
+ }, "printCliHelp"), runCompletionCommand = __name2(
9089
+ (context, commandArgv) => {
9090
+ const shell = commandArgv[1];
9091
+ return shell === void 0 || !isCompletionShell(shell) ? failCliSession(context, "completion", new CliRuntimeError("USAGE", "completion requires bash, zsh, fish, or powershell.")) : (context.runtime.stdout.write(createCompletionScript(shell)), 0);
9092
+ },
9093
+ "runCompletionCommand"
9094
+ ), isVersionRequest = __name2((commandArgv) => commandArgv[0] === "version" || isEnabledFlag(commandArgv, "--version") || commandArgv.includes("-v"), "isVersionRequest"), runVersionCommand = __name2((context) => (startCliSession(context, "version"), emitCommandResult(getVersionData()), clearActiveCliSession(), 0), "runVersionCommand"), createDefaultCredentialStore = __name2((runtime) => createBunCredentialStore({ account: resolveCliCredentialAccount(runtime.env), product: "budget-builder" }), "createDefaultCredentialStore"), authStatusResult = __name2(async (runtime, store) => {
9050
9095
  const apiKeyActive = !!runtime.env.BB_API_KEY?.trim(), credentials = apiKeyActive ? null : await store.get();
9051
9096
  return apiKeyActive ? { authenticated: !0, method: "api-key", storage: "environment" } : credentials && isCliCredentialForIssuer(credentials, BUDGET_BUILDER_API_BASE_URL) ? { authenticated: !0, method: "browser-session", accessTokenExpiresAt: credentials.accessTokenExpiresAt, refreshTokenExpiresAt: credentials.refreshTokenExpiresAt, session: credentials.session, storage: "Bun.secrets" } : { authenticated: !1, method: null, storage: "Bun.secrets" };
9052
9097
  }, "authStatusResult"), runAuthAction = __name2(async (context, authAction, rawArgv, store) => {
@@ -9090,9 +9135,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
9090
9135
  shouldLogCliActions() && logCliAction({ event: "cli.command", phase: "start", command: cmd, positional, flags: sanitizeFlagsForTrace(flags) });
9091
9136
  try {
9092
9137
  if (flags.q === !0) throw new CliRuntimeError("USAGE", "--q needs a search value (--q <text> or --q=<text>). Use -q or --quiet to hide logs.");
9093
- return await configureCliAuthentication(runtime, credentialStore, configureAccessToken), await confirmCanonicalMutation(resolvedCommand, cmd), await dispatchCliCommand(
9094
- { cmd, flags, positional }
9095
- ), shouldLogCliActions() && logCliAction({ event: "cli.command", phase: "ok", command: cmd, durationMs: Date.now() - t0 }), clearActiveCliSession(), 0;
9138
+ return await configureCliAuthentication(runtime, credentialStore, configureAccessToken), await confirmCanonicalMutation(resolvedCommand, cmd), await dispatchCliCommand({ cmd, flags, positional }), shouldLogCliActions() && logCliAction({ event: "cli.command", phase: "ok", command: cmd, durationMs: Date.now() - t0 }), clearActiveCliSession(), 0;
9096
9139
  } catch (err) {
9097
9140
  const message = err instanceof Error ? err.message : String(err);
9098
9141
  shouldLogCliActions() && logCliAction({ event: "cli.command", phase: "error", command: cmd, durationMs: Date.now() - t0, error: message });
@@ -9115,7 +9158,9 @@ async function runCli(argv = process.argv, runtime = createProcessRuntime(), cre
9115
9158
  if (isVersionRequest(commandArgv)) return runVersionCommand(context);
9116
9159
  const authAction = authActionFromArgv(commandArgv);
9117
9160
  if (authAction !== void 0) return await runAuthCommand(context, authAction, commandArgv, rawArgv, credentialStore);
9118
- const resolvedCommand = resolveCommand(commandArgv);
9161
+ const resolvedCommand = resolveCommand(
9162
+ commandArgv
9163
+ );
9119
9164
  return resolvedCommand === void 0 ? failCliSession(context, commandArgv[0] ?? "unknown", new CliRuntimeError("USAGE", "Unknown command: ".concat(commandArgv.join(" "), ". Run 'bb help'."))) : await runResolvedCommand(context, argv, rawArgv, resolvedCommand, credentialStore, configureAccessToken);
9120
9165
  }
9121
9166
  __name(runCli, "runCli"), __name2(runCli, "runCli"), import.meta.main && (assertBunRuntime(), process.exitCode = await runCli());