@go-labs-sg/bb 3.22.1 → 3.24.0

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
@@ -5597,15 +5597,20 @@ var createProcessRuntime = __name2(() => ({ stdout: { write: __name2((value) =>
5597
5597
  }
5598
5598
  }, "confirmCurrentCommand");
5599
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, NOTIFICATION_PAGE_LIMIT = 50, getAllNotifications = __name2(async () => {
5601
- const user = await api2.user.getCurrentUser.query(), notifications = [];
5602
- let cursor;
5603
- do {
5604
- const page = await api2.budget.getNotificationPage.query({ cacheUserId: user.id, cursor, limit: NOTIFICATION_PAGE_LIMIT });
5605
- notifications.push(...page.notifications), cursor = page.nextCursor;
5606
- } while (cursor);
5607
- return notifications;
5608
- }, "getAllNotifications"), createApprovalEmailDeliveryReport = __name2((delivery) => {
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;
5609
+ },
5610
+ "getAllPendingApprovals"
5611
+ ), getPendingApproval = __name2(async (approvalId) => {
5612
+ out(await api2.budget.getPendingApproval.query({ approvalId }));
5613
+ }, "getPendingApproval"), createApprovalEmailDeliveryReport = __name2((delivery) => {
5609
5614
  if (!delivery) return { queued: !1, sent: !1, count: 0, queuedCount: 0, sentCount: 0, skippedCount: 0, error: "No approval email delivery was queued" };
5610
5615
  const { queuedCount, sentCount, skippedCount, message, operationIds } = delivery;
5611
5616
  return { queued: queuedCount > 0, sent: !1, count: queuedCount, queuedCount, sentCount, skippedCount, operationIds, message };
@@ -5657,7 +5662,9 @@ var out = __name2((data) => {
5657
5662
  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";
5658
5663
  return "".concat(sectionText, "; ").concat(dateText, "; ").concat(candidate.gid);
5659
5664
  }, "formatAsanaCandidateMetadata"), promptForAsanaLeadCandidate = __name2(async (candidates) => {
5660
- 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.");
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
+ );
5661
5668
  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.");
5662
5669
  console.error("Select the Asana lead task to link to this project:"), candidates.forEach((candidate, index) => {
5663
5670
  console.error("".concat(index + 1, ". ").concat(candidate.name, " (").concat(formatAsanaCandidateMetadata(candidate), ")"));
@@ -5683,13 +5690,7 @@ var out = __name2((data) => {
5683
5690
  }, "combineDateAndTime"), formatOptionalProjectPaxInput = __name2((pax) => typeof pax != "number" || !Number.isFinite(pax) || pax <= 0 ? "" : String(pax), "formatOptionalProjectPaxInput"), contentTypeHeaderForFileName = __name2((fileName) => {
5684
5691
  const ct = contentType(fileName);
5685
5692
  return typeof ct == "string" ? ct : "application/octet-stream";
5686
- }, "contentTypeHeaderForFileName"), supportedAttachmentContentTypes = [
5687
- "application/pdf",
5688
- "image/gif",
5689
- "image/jpeg",
5690
- "image/png",
5691
- "image/webp"
5692
- ], attachmentContentTypeForFileName = __name2((fileName) => {
5693
+ }, "contentTypeHeaderForFileName"), supportedAttachmentContentTypes = ["application/pdf", "image/gif", "image/jpeg", "image/png", "image/webp"], attachmentContentTypeForFileName = __name2((fileName) => {
5693
5694
  const resolvedContentType = contentTypeHeaderForFileName(fileName), supportedContentType = supportedAttachmentContentTypes.find((contentTypeValue) => contentTypeValue === resolvedContentType);
5694
5695
  if (supportedContentType) return supportedContentType;
5695
5696
  throw new Error("Unsupported attachment type: ".concat(fileName));
@@ -5698,29 +5699,28 @@ var out = __name2((data) => {
5698
5699
  if (resolvedContentType === "image/webp") throw new Error("Unsupported QuickBooks bill attachment type: ".concat(fileName, ". Use PDF, GIF, JPEG, or PNG."));
5699
5700
  return resolvedContentType;
5700
5701
  }, "billAttachmentContentTypeForFileName"), PAYMENT_PROOF_MAX_SIZE = 20 * 1024 * 1024, QUOTATION_ATTACHMENT_MAX_SIZE = 20 * 1024 * 1024, quotationAttachmentContentTypeForFileName = __name2((fileName) => {
5701
- const resolvedContentType = contentTypeHeaderForFileName(fileName);
5702
+ const resolvedContentType = contentTypeHeaderForFileName(
5703
+ fileName
5704
+ );
5702
5705
  if (resolvedContentType === "application/pdf" || resolvedContentType === "image/jpeg" || resolvedContentType === "image/png") return resolvedContentType;
5703
5706
  throw new Error("Unsupported quotation attachment type: ".concat(fileName, ". Use PDF, JPEG, or PNG."));
5704
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 }) => {
5705
5708
  const effects = details ?? "may change workflow state or send notifications";
5706
5709
  return ["Budget Builder workflow preview", "Action: ".concat(action), "Target: ".concat(entity), "Effects: ".concat(effects)].join("\n");
5707
- }, "buildSensitiveWorkflowPreview"), assertSensitiveWorkflowConfirmed = __name2(
5708
- async (input) => {
5709
- if (getActiveCliSession()?.invocation.legacy !== !0) {
5710
- await confirmCurrentCommand({ action: input.action, target: input.entity, details: input.details, effects: input.effects });
5711
- return;
5712
- }
5713
- const expected = "CONFIRM", preview = buildSensitiveWorkflowPreview(input);
5714
- if (!process.stdin.isTTY || !process.stderr.isTTY) throw new Error("".concat(preview, '\nThis is a sensitive workflow change. Run it in an interactive terminal only after the user explicitly confirms this exact action, then type "').concat(expected, '" to continue.'));
5715
- const rl = createInterface2({ input: process.stdin, output: process.stderr });
5716
- try {
5717
- if ((await rl.question("".concat(preview, '\nConfirm the user explicitly approved this exact action, then type "').concat(expected, '" to continue: '))).trim() !== expected) throw new Error("Aborted.");
5718
- } finally {
5719
- rl.close();
5720
- }
5721
- },
5722
- "assertSensitiveWorkflowConfirmed"
5723
- ), assertLockedBudgetChangeConfirmed = __name2(async ({ budget, action }) => {
5710
+ }, "buildSensitiveWorkflowPreview"), assertSensitiveWorkflowConfirmed = __name2(async (input) => {
5711
+ if (getActiveCliSession()?.invocation.legacy !== !0) {
5712
+ await confirmCurrentCommand({ action: input.action, target: input.entity, details: input.details, effects: input.effects });
5713
+ return;
5714
+ }
5715
+ const expected = "CONFIRM", preview = buildSensitiveWorkflowPreview(input);
5716
+ if (!process.stdin.isTTY || !process.stderr.isTTY) throw new Error("".concat(preview, '\nThis is a sensitive workflow change. Run it in an interactive terminal only after the user explicitly confirms this exact action, then type "').concat(expected, '" to continue.'));
5717
+ const rl = createInterface2({ input: process.stdin, output: process.stderr });
5718
+ try {
5719
+ if ((await rl.question("".concat(preview, '\nConfirm the user explicitly approved this exact action, then type "').concat(expected, '" to continue: '))).trim() !== expected) throw new Error("Aborted.");
5720
+ } finally {
5721
+ rl.close();
5722
+ }
5723
+ }, "assertSensitiveWorkflowConfirmed"), assertLockedBudgetChangeConfirmed = __name2(async ({ budget, action }) => {
5724
5724
  if (!LOCKED_BUDGET_STATUSES_REQUIRING_CONFIRMATION.has(budget.status)) return;
5725
5725
  const statusLabel = lockedBudgetStatusLabel(budget.status);
5726
5726
  if (getActiveCliSession()?.invocation.legacy !== !0) {
@@ -5745,7 +5745,9 @@ 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({ action: "Update project and reject existing estimates", entity: "project ".concat(input.id), details: error2.message }), api2.project.updateProject.mutate({ ...input, confirmEstimateInvalidation: !0 });
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 });
5749
5751
  }
5750
5752
  }, "updateProjectWithEstimateInvalidationConfirmation"), listBudgets = __name2(async (input) => {
5751
5753
  out(await api2.budget.getAllBudgets.query(input));
@@ -5758,7 +5760,9 @@ async function getBudget(id, opts) {
5758
5760
  }
5759
5761
  __name(getBudget, "getBudget"), __name2(getBudget, "getBudget");
5760
5762
  async function updateBudgetStatus(budgetId, status, opts) {
5761
- await assertSensitiveWorkflowConfirmed({ action: "Update budget status", entity: "budget ".concat(budgetId), details: "to ".concat(status) }), await confirmLockedBudgetChangeByBudgetId(budgetId, "Update budget status");
5763
+ await assertSensitiveWorkflowConfirmed({ action: "Update budget status", entity: "budget ".concat(budgetId), details: "to ".concat(
5764
+ status
5765
+ ) }), await confirmLockedBudgetChangeByBudgetId(budgetId, "Update budget status");
5762
5766
  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 } });
5763
5767
  out({ ...result, invoiceSetup: result.newStatus === BudgetStatus2.ESTIMATE_ACCEPTED && result.hasQuickbooksEstimate ? invoiceSplitSetupNextAction(budgetId) : null });
5764
5768
  }
@@ -5772,19 +5776,20 @@ var assertBudgetActionReadiness = __name2(async ({ budgetId, requireQuickbooksPr
5772
5776
  if (requireQuickbooksProject && !budget.project.quickbooksProjectId) throw new Error("Cannot create estimate: project is not linked to QuickBooks yet.");
5773
5777
  }, "assertBudgetActionReadiness"), runBudgetPreflight = __name2(async (budgetId, preflight) => {
5774
5778
  if (preflight && (preflight.company && await api2.company.updateCompany.mutate(preflight.company), preflight.contactPerson && await api2.contactPerson.updateContactPerson.mutate(preflight.contactPerson), preflight.eventDetails)) {
5775
- const budget = await api2.budget.getBudget.query(
5776
- { id: budgetId }
5777
- ), project = await api2.project.getProjectById.query({ id: budget.projectId }), day = new Date(preflight.eventDetails.date), start = new Date(preflight.eventDetails.startTime), end = new Date(preflight.eventDetails.endTime), payload = { id: project.id, name: project.name, description: project.description ?? void 0, dateRange: { from: combineDateAndTime(day, start), to: combineDateAndTime(day, end) }, companyId: project.companyId, contactPersonId: project.contactPersonId, asanaTaskId: project.asanaTaskId ?? "", insideSalesId: project.insideSalesId ?? "", businessDevelopmentId: project.businessDevelopmentId ?? "", venue: project.venue ?? "", pax: formatOptionalProjectPaxInput(project.pax) };
5779
+ const budget = await api2.budget.getBudget.query({ id: budgetId }), project = await api2.project.getProjectById.query({ id: budget.projectId }), day = new Date(preflight.eventDetails.date), start = new Date(preflight.eventDetails.startTime), end = new Date(preflight.eventDetails.endTime), payload = { id: project.id, name: project.name, description: project.description ?? void 0, dateRange: { from: combineDateAndTime(day, start), to: combineDateAndTime(day, end) }, companyId: project.companyId, contactPersonId: project.contactPersonId, asanaTaskId: project.asanaTaskId ?? "", insideSalesId: project.insideSalesId ?? "", businessDevelopmentId: project.businessDevelopmentId ?? "", venue: project.venue ?? "", pax: formatOptionalProjectPaxInput(project.pax) };
5778
5780
  await updateProjectWithEstimateInvalidationConfirmation(payload);
5779
5781
  }
5780
5782
  }, "runBudgetPreflight"), listBills = __name2(async (input) => {
5781
5783
  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 }));
5782
- }, "listBills"), countBills = __name2(async (input) => {
5783
- 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 }));
5784
- }, "countBills");
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
+ );
5785
5790
  async function approveBill(billId, overBudgetOverrideReason) {
5786
5791
  await assertSensitiveWorkflowConfirmed({ action: "Approve bill", entity: "bill ".concat(billId), details: "and send requester reply email" });
5787
- const approval = (await getAllNotifications()).filter((n) => isPendingRequest(n) && n.type === BILL && (n.billId === billId || n.bill?.id === billId))[0];
5792
+ const approval = (await getAllPendingApprovals()).filter((n) => isPendingRequest(n) && n.type === BILL && (n.billId === billId || n.bill?.id === billId))[0];
5788
5793
  if (!approval) throw new Error("No pending bill approval found for this bill.");
5789
5794
  const result = await api2.bill.updateApproval.mutate({ billApprovalId: approval.id, status: ApprovalStatus2.APPROVED, overBudgetOverrideReason });
5790
5795
  if (result.processing) {
@@ -5796,20 +5801,18 @@ async function approveBill(billId, overBudgetOverrideReason) {
5796
5801
  const delivery = result.emailDelivery;
5797
5802
  email2 = createApprovalEmailDeliveryReport(delivery);
5798
5803
  } catch (error2) {
5799
- email2 = createApprovalEmailDeliveryFailure(error2 instanceof Error ? error2.message : String(
5800
- error2
5801
- ));
5804
+ email2 = createApprovalEmailDeliveryFailure(error2 instanceof Error ? error2.message : String(error2));
5802
5805
  }
5803
5806
  out({ ...result, email: email2 });
5804
5807
  }
5805
5808
  __name(approveBill, "approveBill"), __name2(approveBill, "approveBill");
5806
5809
  var approvalIdentity = __name2((n) => n.type === BUDGET && n.budget ? { id: n.budgetId ?? n.id, name: n.budget.name } : n.type === BILL && n.bill ? { id: n.bill.id, name: "Bill ".concat(n.bill.invoiceNumber ?? n.bill.id.slice(0, 8)) } : n.type === SUPPLIER && n.supplier ? { id: n.supplier.id, name: n.supplier.name } : n.type === QUOTATION && n.supplierQuotation ? { id: n.supplierQuotation.id, name: "Quotation ".concat(n.supplierQuotation.supplier.name) } : n.type === CUSTOMER_INVOICE && n.customerInvoiceBatch ? { id: n.customerInvoiceBatch.id, name: "Customer invoice ".concat(n.customerInvoiceBatch.project.name) } : { id: n.id, name: "Unknown" }, "approvalIdentity"), approvalRequestedAt = __name2((createdAt) => typeof createdAt == "string" ? createdAt : createdAt instanceof Date ? createdAt.toISOString() : String(createdAt), "approvalRequestedAt");
5807
5810
  async function listApprovals(opts) {
5808
- const pending = (await getAllNotifications()).filter(isPendingRequest), typeFilter = opts.type === void 0 || opts.type === "ALL" ? (_n) => !0 : (n) => n.type === opts.type, items = pending.filter(typeFilter).filter((n) => n.type !== BUDGET || !n.budget?.quickbooksEstimateId).map((n) => {
5811
+ const page = await api2.budget.getPendingApprovals.query({ ...opts, type: opts.type === "ALL" ? void 0 : opts.type }), items = page.items.filter(isPendingRequest).map((n) => {
5809
5812
  const { id, name } = approvalIdentity(n);
5810
5813
  return { approvalId: n.id, type: n.type, id, name, requestedBy: n.requester?.name ?? n.requester?.email ?? "Unknown", requestedAt: approvalRequestedAt(n.createdAt) };
5811
5814
  });
5812
- out({ items });
5815
+ out({ items, pageInfo: page.pageInfo });
5813
5816
  }
5814
5817
  __name(listApprovals, "listApprovals"), __name2(listApprovals, "listApprovals");
5815
5818
  var listSuppliers = __name2(async (opts) => {
@@ -5824,7 +5827,9 @@ async function createBillApproval(billId) {
5824
5827
  if (approvalIds.length === 0) email2 = createApprovalEmailDeliveryFailure("No approval ids returned");
5825
5828
  else try {
5826
5829
  const delivery = result.emailDelivery;
5827
- email2 = createApprovalEmailDeliveryReport(delivery);
5830
+ email2 = createApprovalEmailDeliveryReport(
5831
+ delivery
5832
+ );
5828
5833
  } catch (error2) {
5829
5834
  email2 = createApprovalEmailDeliveryFailure(error2 instanceof Error ? error2.message : String(error2));
5830
5835
  }
@@ -5838,12 +5843,14 @@ var validateBillStatusUpdateOptions = __name2((opts) => {
5838
5843
  }, "validateBillStatusUpdateOptions"), deleteStagedPaymentProof = __name2(async (projectId, key) => {
5839
5844
  await api2.attachment.deleteStagedBillAttachments.mutate({ projectId, keys: [key] });
5840
5845
  }, "deleteStagedPaymentProof"), rethrowAfterStagedPaymentProofCleanup = __name2(async (error2, cleanup) => {
5841
- if (cleanup)
5842
- try {
5843
- await cleanup();
5844
- } catch (cleanupError) {
5845
- throw new AggregateError([error2, cleanupError], "Bill status update failed and its staged payment proof could not be cleaned up.");
5846
- }
5846
+ if (cleanup) try {
5847
+ await cleanup();
5848
+ } 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
+ );
5853
+ }
5847
5854
  throw error2;
5848
5855
  }, "rethrowAfterStagedPaymentProofCleanup"), stageBillPaymentProof = __name2(async (projectId, filePath) => {
5849
5856
  const buffer = await readFile2(filePath), fileName = basename(filePath), size = buffer.byteLength, contentType2 = billAttachmentContentTypeForFileName(fileName);
@@ -5868,15 +5875,7 @@ async function updateBillStatus(opts) {
5868
5875
  validateBillStatusUpdateOptions(opts), await assertSensitiveWorkflowConfirmed({ action: "Update bill status", entity: "bill ".concat(opts.id), details: "to ".concat(opts.status) });
5869
5876
  const bill = opts.paymentProofPath ? await api2.bill.getPayment.query({ id: opts.id }) : null, paymentProof = bill && opts.paymentProofPath ? await stageBillPaymentProof(bill.projectId, opts.paymentProofPath) : void 0;
5870
5877
  try {
5871
- const result = await api2.bill.updateStatus.mutate({
5872
- id: opts.id,
5873
- status: opts.status,
5874
- rejectionReason: opts.rejectionReason,
5875
- paymentTrackingUrl: opts.paymentTrackingUrl,
5876
- paymentReference: opts.paymentReference,
5877
- paymentProofAttachments: paymentProof ? [paymentProof] : void 0,
5878
- overBudgetOverrideReason: opts.overBudgetOverrideReason
5879
- });
5878
+ const result = await api2.bill.updateStatus.mutate({ id: opts.id, status: opts.status, rejectionReason: opts.rejectionReason, paymentTrackingUrl: opts.paymentTrackingUrl, paymentReference: opts.paymentReference, paymentProofAttachments: paymentProof ? [paymentProof] : void 0, overBudgetOverrideReason: opts.overBudgetOverrideReason });
5880
5879
  out(result);
5881
5880
  } catch (error2) {
5882
5881
  await rethrowAfterStagedPaymentProofCleanup(error2, bill && paymentProof ? async () => {
@@ -5890,10 +5889,7 @@ var listExternalBillPaymentAccounts = __name2(async () => {
5890
5889
  }, "listExternalBillPaymentAccounts"), refreshExternalBillPaymentAccounts = __name2(async () => {
5891
5890
  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());
5892
5891
  }, "refreshExternalBillPaymentAccounts"), recordExternalBillPayment = __name2(async (opts) => {
5893
- if (!opts.paymentReference.trim() || !opts.paymentAccount.trim() || !new __cliRegExp(
5894
- "^\\d{4}-\\d{2}-\\d{2}$",
5895
- ""
5896
- ).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>.");
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>.");
5897
5893
  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.") });
5898
5894
  const bill = await api2.bill.getPayment.query({ id: opts.id }), proof = !bill.externalPayment && opts.paymentProofPath ? await stageBillPaymentProof(bill.projectId, opts.paymentProofPath) : void 0;
5899
5895
  try {
@@ -5934,9 +5930,7 @@ var getBillAttachments = __name2(async (input) => {
5934
5930
  async function stageBillAttachmentsFromPaths(projectId, filePaths) {
5935
5931
  const attachments = [];
5936
5932
  for (const filePath of filePaths) {
5937
- const buffer = await readFile2(filePath), fileName = basename(filePath), size = buffer.byteLength, contentType2 = billAttachmentContentTypeForFileName(
5938
- fileName
5939
- ), { uploadUrl, key } = await api2.attachment.requestStagedBillAttachmentUpload.mutate({ projectId, fileName, size, contentType: contentType2 }), response = await fetch(uploadUrl, { method: "PUT", body: buffer, headers: { "Content-Type": contentType2 } });
5933
+ const buffer = await readFile2(filePath), fileName = basename(filePath), size = buffer.byteLength, contentType2 = billAttachmentContentTypeForFileName(fileName), { uploadUrl, key } = await api2.attachment.requestStagedBillAttachmentUpload.mutate({ projectId, fileName, size, contentType: contentType2 }), response = await fetch(uploadUrl, { method: "PUT", body: buffer, headers: { "Content-Type": contentType2 } });
5940
5934
  if (!response.ok) throw new Error("S3 upload failed: HTTP ".concat(response.status, " ").concat((await response.text()).slice(0, 500)));
5941
5935
  attachments.push({ id: randomUUID2(), key, name: fileName, size });
5942
5936
  }
@@ -5960,12 +5954,15 @@ var uploadSingleBillAttachmentFromPath = __name2(async (billId, filePath, type =
5960
5954
  async function uploadBillAttachmentsFromPaths(billId, filePaths, type = AttachmentType.BILL) {
5961
5955
  if (filePaths.length === 0) throw new Error("At least one bill attachment file path is required");
5962
5956
  const results = [];
5963
- for (const filePath of filePaths) results.push(await uploadSingleBillAttachmentFromPath(
5957
+ for (const filePath of filePaths) results.push(await uploadSingleBillAttachmentFromPath(billId, filePath, type));
5958
+ out({
5959
+ success: !0,
5964
5960
  billId,
5965
- filePath,
5966
- type
5967
- ));
5968
- out({ success: !0, billId, type, count: results.length, attachments: results.map((result) => result.attachment), results });
5961
+ type,
5962
+ count: results.length,
5963
+ attachments: results.map((result) => result.attachment),
5964
+ results
5965
+ });
5969
5966
  }
5970
5967
  __name(uploadBillAttachmentsFromPaths, "uploadBillAttachmentsFromPaths"), __name2(uploadBillAttachmentsFromPaths, "uploadBillAttachmentsFromPaths");
5971
5968
  async function uploadBillDocumentsFromPaths({ billId, invoicePaths = [], paymentProofPaths = [] }) {
@@ -5974,12 +5971,12 @@ async function uploadBillDocumentsFromPaths({ billId, invoicePaths = [], payment
5974
5971
  for (const filePath of invoicePaths) invoiceResults.push(await uploadSingleBillAttachmentFromPath(billId, filePath, AttachmentType.BILL));
5975
5972
  const paymentProofResults = [];
5976
5973
  for (const filePath of paymentProofPaths) paymentProofResults.push(await uploadSingleBillAttachmentFromPath(billId, filePath, AttachmentType.BILL_PAYMENT_PROOF));
5977
- out({ success: !0, billId, count: invoiceResults.length + paymentProofResults.length, invoiceAttachments: invoiceResults.map((result) => result.attachment), paymentProofAttachments: paymentProofResults.map((result) => result.attachment), results: [
5978
- ...invoiceResults,
5979
- ...paymentProofResults
5980
- ] });
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] });
5981
5975
  }
5982
- __name(uploadBillDocumentsFromPaths, "uploadBillDocumentsFromPaths"), __name2(uploadBillDocumentsFromPaths, "uploadBillDocumentsFromPaths");
5976
+ __name(uploadBillDocumentsFromPaths, "uploadBillDocumentsFromPaths"), __name2(
5977
+ uploadBillDocumentsFromPaths,
5978
+ "uploadBillDocumentsFromPaths"
5979
+ );
5983
5980
  async function uploadQuotationAttachmentFromPath(projectId, filePath) {
5984
5981
  const buf = await readFile2(filePath), fileName = basename(filePath);
5985
5982
  if (buf.byteLength > QUOTATION_ATTACHMENT_MAX_SIZE) throw new Error("Quotation attachment must be 20MB or smaller.");
@@ -5996,23 +5993,25 @@ async function uploadBudgetAttachmentFromPath(budgetId, filePath) {
5996
5993
  await confirmLockedBudgetChangeByBudgetId(budgetId, "Upload budget attachment");
5997
5994
  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 } });
5998
5995
  if (!res.ok) throw new Error("S3 upload failed: HTTP ".concat(res.status, " ").concat((await res.text()).slice(0, 500)));
5999
- const confirmed = await api2.attachment.confirmBudgetAttachment.mutate(
6000
- { budgetId, key, name: fileName, size }
6001
- );
5996
+ const confirmed = await api2.attachment.confirmBudgetAttachment.mutate({ budgetId, key, name: fileName, size });
6002
5997
  out(confirmed);
6003
5998
  }
6004
- __name(uploadBudgetAttachmentFromPath, "uploadBudgetAttachmentFromPath"), __name2(uploadBudgetAttachmentFromPath, "uploadBudgetAttachmentFromPath");
5999
+ __name(uploadBudgetAttachmentFromPath, "uploadBudgetAttachmentFromPath"), __name2(
6000
+ uploadBudgetAttachmentFromPath,
6001
+ "uploadBudgetAttachmentFromPath"
6002
+ );
6005
6003
  async function uploadBudgetWinProofFromPath(budgetId, filePath, opts) {
6006
6004
  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");
6007
6005
  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 } });
6008
6006
  if (!res.ok) throw new Error("S3 upload failed: HTTP ".concat(res.status, " ").concat((await res.text()).slice(0, 500)));
6009
- await api2.attachment.confirmBudgetWinProofAttachment.mutate({
6010
- budgetId,
6011
- key,
6012
- name: fileName,
6013
- size
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 }
6014
6014
  });
6015
- 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 } });
6016
6015
  out({ ...result, invoiceSetup: result.hasQuickbooksEstimate ? invoiceSplitSetupNextAction(budgetId) : null });
6017
6016
  }
6018
6017
  __name(uploadBudgetWinProofFromPath, "uploadBudgetWinProofFromPath"), __name2(uploadBudgetWinProofFromPath, "uploadBudgetWinProofFromPath");
@@ -6026,7 +6025,10 @@ async function getBillDetails(id) {
6026
6025
  }
6027
6026
  __name(getBillDetails, "getBillDetails"), __name2(getBillDetails, "getBillDetails");
6028
6027
  async function getBudgetItemsOnly(budgetId, opts) {
6029
- const includeInactive = opts?.includeInactive ?? !1, [items, totals] = await Promise.all([api2.budget.getBudgetItems.query({ budgetId, includeInactive }), api2.budget.getBudgetItemTotals.query({ budgetId, includeInactive })]);
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
+ })]);
6030
6032
  out({ ...items, totals });
6031
6033
  }
6032
6034
  __name(getBudgetItemsOnly, "getBudgetItemsOnly"), __name2(getBudgetItemsOnly, "getBudgetItemsOnly");
@@ -6043,10 +6045,7 @@ async function updateBudgetItem(input) {
6043
6045
  }
6044
6046
  __name(updateBudgetItem, "updateBudgetItem"), __name2(updateBudgetItem, "updateBudgetItem");
6045
6047
  async function removeBudgetItem(budgetItemId) {
6046
- await confirmLockedBudgetChangeByBudgetItemId(
6047
- budgetItemId,
6048
- "Remove budget item"
6049
- );
6048
+ await confirmLockedBudgetChangeByBudgetItemId(budgetItemId, "Remove budget item");
6050
6049
  const result = await api2.budgetItem.removeBudgetItem.mutate({ budgetItemId });
6051
6050
  out(result);
6052
6051
  }
@@ -6077,7 +6076,9 @@ async function createBudgetApproval(budgetId, preflight) {
6077
6076
  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" });
6078
6077
  const result = await api2.budget.createBudgetApproval.mutate({ budgetId }), approvalIds = (result.results ?? []).map((item) => ({ id: item.id }));
6079
6078
  let email2;
6080
- if (approvalIds.length === 0) email2 = createApprovalEmailDeliveryFailure("No approval ids returned");
6079
+ if (approvalIds.length === 0) email2 = createApprovalEmailDeliveryFailure(
6080
+ "No approval ids returned"
6081
+ );
6081
6082
  else try {
6082
6083
  const delivery = result.emailDelivery;
6083
6084
  email2 = createApprovalEmailDeliveryReport(delivery);
@@ -6110,14 +6111,14 @@ async function createBudgetFromPayload(raw) {
6110
6111
  try {
6111
6112
  result = await api2.budget.createBudget.mutate(input);
6112
6113
  } catch (error2) {
6113
- throw budgetCreateUncertainError(
6114
- error2,
6115
- input
6116
- ) || error2;
6114
+ throw budgetCreateUncertainError(error2, input) || error2;
6117
6115
  }
6118
6116
  out(result);
6119
6117
  }
6120
- __name(createBudgetFromPayload, "createBudgetFromPayload"), __name2(createBudgetFromPayload, "createBudgetFromPayload");
6118
+ __name(createBudgetFromPayload, "createBudgetFromPayload"), __name2(
6119
+ createBudgetFromPayload,
6120
+ "createBudgetFromPayload"
6121
+ );
6121
6122
  async function updateBudgetFromPayload(raw) {
6122
6123
  const input = parseUpdateBudgetPayload(raw);
6123
6124
  await confirmLockedBudgetChangeByBudgetId(input.id, "Update budget");
@@ -6187,7 +6188,9 @@ var deleteBudgetDiscount = __name2(async (budgetId) => {
6187
6188
  const result = await api2.budget.deleteBudgetDiscount.mutate({ budgetId });
6188
6189
  out(result);
6189
6190
  }, "deleteBudgetDiscount"), deleteBudgetCommission = __name2(async (budgetId) => {
6190
- await assertSensitiveWorkflowConfirmed({ action: "Remove budget commission", entity: "budget ".concat(budgetId), details: "and return the budget to DRAFT" });
6191
+ await assertSensitiveWorkflowConfirmed(
6192
+ { action: "Remove budget commission", entity: "budget ".concat(budgetId), details: "and return the budget to DRAFT" }
6193
+ );
6191
6194
  const result = await api2.budget.deleteBudgetCommission.mutate({ budgetId });
6192
6195
  out(result);
6193
6196
  }, "deleteBudgetCommission"), setBudgetItemsNotUtilized = __name2(async (budgetItemIds, notUtilized) => {
@@ -6277,10 +6280,7 @@ async function getQuotationDetails(id) {
6277
6280
  const result = await api2.quotation.getById.query({ id });
6278
6281
  out(result);
6279
6282
  }
6280
- __name(getQuotationDetails, "getQuotationDetails"), __name2(
6281
- getQuotationDetails,
6282
- "getQuotationDetails"
6283
- );
6283
+ __name(getQuotationDetails, "getQuotationDetails"), __name2(getQuotationDetails, "getQuotationDetails");
6284
6284
  var getQuotationLineItems = __name2(async (input) => {
6285
6285
  out(await api2.quotation.getLineItems.query(input));
6286
6286
  }, "getQuotationLineItems");
@@ -6301,10 +6301,7 @@ async function submitQuotation(id, overBudgetOverrideReason) {
6301
6301
  const result = await api2.quotation.submitForApproval.mutate({ id, overBudgetOverrideReason });
6302
6302
  out(result);
6303
6303
  }
6304
- __name(submitQuotation, "submitQuotation"), __name2(
6305
- submitQuotation,
6306
- "submitQuotation"
6307
- );
6304
+ __name(submitQuotation, "submitQuotation"), __name2(submitQuotation, "submitQuotation");
6308
6305
  async function downloadQuotationPdf(id, fileRole) {
6309
6306
  const result = await api2.quotation.getSignedDownloadUrl.query({ id, fileRole });
6310
6307
  out(result);
@@ -6339,18 +6336,23 @@ var checkCustomerInvoiceReadiness = __name2(async (budgetId) => {
6339
6336
  out(await api2.customerInvoice.getHistory.query(input));
6340
6337
  }, "getCustomerInvoiceHistory"), getCustomerInvoicePayments = __name2(async (invoiceId) => {
6341
6338
  out(await api2.customerInvoice.getPayments.query({ invoiceId }));
6342
- }, "getCustomerInvoicePayments"), getCustomerInvoiceEmailContext = __name2(async (batchId) => {
6343
- const result = await api2.customerInvoice.getInvoiceEmailContext.query({ batchId });
6344
- out(result);
6345
- }, "getCustomerInvoiceEmailContext"), previewQboCustomerInvoice = __name2(async (input) => {
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) => {
6346
6346
  const result = await api2.customerInvoice.previewExistingInvoice.mutate(input);
6347
6347
  out(result);
6348
6348
  }, "previewQboCustomerInvoice"), importQboCustomerInvoice = __name2(async (input) => {
6349
- 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" });
6349
+ 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
6350
  const result = await api2.customerInvoice.linkExistingInvoice.mutate(input);
6351
6351
  out(result);
6352
6352
  }, "importQboCustomerInvoice"), createCustomerInvoice = __name2(async (raw) => {
6353
- const input = parseCreateCustomerInvoicePayload(raw), readiness = await api2.customerInvoice.getInvoiceReadiness.query({ budgetId: input.budgetId, includePreview: !0 });
6353
+ const input = parseCreateCustomerInvoicePayload(
6354
+ raw
6355
+ ), readiness = await api2.customerInvoice.getInvoiceReadiness.query({ budgetId: input.budgetId, includePreview: !0 });
6354
6356
  if (!readiness.ready) throw new CliRuntimeError("VALIDATION", readiness.issues.join("; ") || "Invoice is not ready for creation.");
6355
6357
  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.") });
6356
6358
  const result = await api2.customerInvoice.createInvoiceBatch.mutate(input);
@@ -6505,7 +6507,7 @@ async function updateCompanyFromPayload(raw) {
6505
6507
  __name(updateCompanyFromPayload, "updateCompanyFromPayload"), __name2(updateCompanyFromPayload, "updateCompanyFromPayload");
6506
6508
  async function approveBudget(budgetId) {
6507
6509
  await assertSensitiveWorkflowConfirmed({ action: "Approve budget", entity: "budget ".concat(budgetId), details: "and send requester reply email" });
6508
- const approval = (await getAllNotifications()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.BUDGET && (n.budgetId === budgetId || n.budget?.id === budgetId))[0];
6510
+ 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];
6509
6511
  if (!approval) throw new Error("No pending budget approval found for this budget and approver.");
6510
6512
  const result = await api2.budget.updateBudgetApproval.mutate({ budgetApprovalId: approval.id, status: ExtendedApprovalStatus.APPROVED });
6511
6513
  let email2;
@@ -6523,7 +6525,7 @@ async function rejectBudget(budgetId, reason) {
6523
6525
  reason,
6524
6526
  '" and send requester reply email'
6525
6527
  ) });
6526
- const approval = (await getAllNotifications()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.BUDGET && (n.budgetId === budgetId || n.budget?.id === budgetId))[0];
6528
+ 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];
6527
6529
  if (!approval) throw new Error("No pending budget approval found for this budget and approver.");
6528
6530
  const result = await api2.budget.updateBudgetApproval.mutate({ budgetApprovalId: approval.id, status: ExtendedApprovalStatus.REJECTED, rejectionReason: reason });
6529
6531
  let email2;
@@ -6565,7 +6567,7 @@ async function approveSupplier(supplierId) {
6565
6567
  entity: "supplier ".concat(supplierId),
6566
6568
  details: "and send requester reply email"
6567
6569
  });
6568
- const approval = (await getAllNotifications()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.SUPPLIER && (n.supplierId === supplierId || n.supplier?.id === supplierId))[0];
6570
+ 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];
6569
6571
  if (!approval) throw new Error("No pending supplier approval found.");
6570
6572
  const result = await api2.supplier.updateSupplierApproval.mutate({ supplierApprovalId: approval.id, status: ExtendedApprovalStatus.APPROVED });
6571
6573
  let email2;
@@ -6580,7 +6582,7 @@ async function approveSupplier(supplierId) {
6580
6582
  __name(approveSupplier, "approveSupplier"), __name2(approveSupplier, "approveSupplier");
6581
6583
  async function rejectSupplier(supplierId, reason) {
6582
6584
  await assertSensitiveWorkflowConfirmed({ action: "Reject supplier", entity: "supplier ".concat(supplierId), details: 'with reason "'.concat(reason, '" and send requester reply email') });
6583
- const approval = (await getAllNotifications()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.SUPPLIER && (n.supplierId === supplierId || n.supplier?.id === supplierId))[0];
6585
+ 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];
6584
6586
  if (!approval) throw new Error("No pending supplier approval found.");
6585
6587
  const result = await api2.supplier.updateSupplierApproval.mutate({ supplierApprovalId: approval.id, status: ExtendedApprovalStatus.REJECTED, rejectionReason: reason });
6586
6588
  let email2;
@@ -6595,7 +6597,7 @@ async function rejectSupplier(supplierId, reason) {
6595
6597
  __name(rejectSupplier, "rejectSupplier"), __name2(rejectSupplier, "rejectSupplier");
6596
6598
  async function rejectBill(billId, reason) {
6597
6599
  await assertSensitiveWorkflowConfirmed({ action: "Reject bill", entity: "bill ".concat(billId), details: 'with reason "'.concat(reason, '" and send requester reply email') });
6598
- const approval = (await getAllNotifications()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.BILL && (n.billId === billId || n.bill?.id === billId))[0];
6600
+ const approval = (await getAllPendingApprovals()).filter((n) => n.notificationType === "request" && n.status === ExtendedApprovalStatus.PENDING_APPROVAL && n.type === ExtendedApprovalType.BILL && (n.billId === billId || n.bill?.id === billId))[0];
6599
6601
  if (!approval) throw new Error("No pending bill approval found.");
6600
6602
  const result = await api2.bill.updateApproval.mutate({ billApprovalId: approval.id, status: ExtendedApprovalStatus.REJECTED, rejectionReason: reason });
6601
6603
  if (result.processing) {
@@ -6614,7 +6616,7 @@ async function rejectBill(billId, reason) {
6614
6616
  __name(rejectBill, "rejectBill"), __name2(rejectBill, "rejectBill");
6615
6617
  async function approveQuotation(quotationId, overBudgetOverrideReason) {
6616
6618
  await assertSensitiveWorkflowConfirmed({ action: "Approve quotation", entity: "quotation ".concat(quotationId) });
6617
- const approval = (await getAllNotifications()).filter((n) => isPendingRequest(n) && n.type === QUOTATION && (n.supplierQuotationId === quotationId || n.supplierQuotation?.id === quotationId))[0];
6619
+ const approval = (await getAllPendingApprovals()).filter((n) => isPendingRequest(n) && n.type === QUOTATION && (n.supplierQuotationId === quotationId || n.supplierQuotation?.id === quotationId))[0];
6618
6620
  if (!approval) throw new Error("No pending quotation approval found.");
6619
6621
  const result = await api2.quotation.approve.mutate({ quotationApprovalId: approval.id, overBudgetOverrideReason });
6620
6622
  out(result);
@@ -6622,7 +6624,7 @@ async function approveQuotation(quotationId, overBudgetOverrideReason) {
6622
6624
  __name(approveQuotation, "approveQuotation"), __name2(approveQuotation, "approveQuotation");
6623
6625
  async function rejectQuotation(quotationId, reason) {
6624
6626
  await assertSensitiveWorkflowConfirmed({ action: "Reject quotation", entity: "quotation ".concat(quotationId), details: 'with reason "'.concat(reason, '"') });
6625
- const approval = (await getAllNotifications()).filter((n) => isPendingRequest(n) && n.type === QUOTATION && (n.supplierQuotationId === quotationId || n.supplierQuotation?.id === quotationId))[0];
6627
+ const approval = (await getAllPendingApprovals()).filter((n) => isPendingRequest(n) && n.type === QUOTATION && (n.supplierQuotationId === quotationId || n.supplierQuotation?.id === quotationId))[0];
6626
6628
  if (!approval) throw new Error("No pending quotation approval found.");
6627
6629
  const result = await api2.quotation.reject.mutate({ quotationApprovalId: approval.id, rejectionReason: reason });
6628
6630
  out(result);
@@ -6630,7 +6632,9 @@ async function rejectQuotation(quotationId, reason) {
6630
6632
  __name(rejectQuotation, "rejectQuotation"), __name2(rejectQuotation, "rejectQuotation");
6631
6633
  var listCompanies = __name2(async (input) => {
6632
6634
  const result = await api2.company.getCompanies.query(input);
6633
- out(result);
6635
+ out(
6636
+ result
6637
+ );
6634
6638
  }, "listCompanies"), countCompanies = __name2(async (input) => {
6635
6639
  const result = await api2.company.getCompanyCounts.query(input);
6636
6640
  out(result);
@@ -6655,9 +6659,12 @@ var searchExistingCompanies = __name2(async (input) => {
6655
6659
  }, "listProjects"), countProjects = __name2(async (input) => {
6656
6660
  const result = await api2.project.getProjectCounts.query(input);
6657
6661
  out(result);
6658
- }, "countProjects"), listProjectHubs = __name2(async (input) => {
6659
- out(await api2.project.getAllProjectHubs.query(input));
6660
- }, "listProjectHubs"), countProjectHubs = __name2(async (input) => {
6662
+ }, "countProjects"), listProjectHubs = __name2(
6663
+ async (input) => {
6664
+ out(await api2.project.getAllProjectHubs.query(input));
6665
+ },
6666
+ "listProjectHubs"
6667
+ ), countProjectHubs = __name2(async (input) => {
6661
6668
  out(await api2.project.getProjectHubCounts.query(input));
6662
6669
  }, "countProjectHubs");
6663
6670
  async function getProject(id) {
@@ -6672,17 +6679,16 @@ var getProjectHubStatus = __name2(async (projectId) => {
6672
6679
  await assertSensitiveWorkflowConfirmed({ action: "Set up Project Hub", entity: "project ".concat(projectId), details: "queue Asana, Drive, and client Hub provisioning" });
6673
6680
  const result = await api2.project.setupProjectHub.mutate({ projectId });
6674
6681
  out(result);
6675
- }, "setupProjectHub"), syncProjectHubCommercialDocuments = __name2(
6676
- async (projectId) => {
6677
- await assertSensitiveWorkflowConfirmed({ action: "Sync Project Hub commercial documents", entity: "project ".concat(projectId), details: "queue a full Budget Builder to Google Drive and Asana reconciliation" });
6678
- const result = await api2.project.syncProjectHubCommercialDocuments.mutate({ projectId });
6679
- out(result);
6680
- },
6681
- "syncProjectHubCommercialDocuments"
6682
- );
6682
+ }, "setupProjectHub"), syncProjectHubCommercialDocuments = __name2(async (projectId) => {
6683
+ await assertSensitiveWorkflowConfirmed({ action: "Sync Project Hub commercial documents", entity: "project ".concat(projectId), details: "queue a full Budget Builder to Google Drive and Asana reconciliation" });
6684
+ const result = await api2.project.syncProjectHubCommercialDocuments.mutate({ projectId });
6685
+ out(result);
6686
+ }, "syncProjectHubCommercialDocuments");
6683
6687
  async function createProject(opts) {
6684
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 } });
6685
- out(result);
6689
+ out(
6690
+ result
6691
+ );
6686
6692
  }
6687
6693
  __name(createProject, "createProject"), __name2(createProject, "createProject");
6688
6694
  async function updateProjectStatus(id, status, opts) {
@@ -6698,9 +6704,12 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6698
6704
  await assertSensitiveWorkflowConfirmed({ action: "Reconcile project", entity: "project ".concat(projectId), details: "rerun all reconciliation checks and mark it RECONCILED" });
6699
6705
  const result = await api2.project.reconcile.mutate({ projectId });
6700
6706
  out(result);
6701
- }, "reconcileProject"), completeProject = __name2(async (projectId) => {
6702
- await updateProjectStatus(projectId, ProjectStatus2.COMPLETED);
6703
- }, "completeProject"), importQuickBooksProjectId = __name2(async (projectId, projectUrl) => {
6707
+ }, "reconcileProject"), completeProject = __name2(
6708
+ async (projectId) => {
6709
+ await updateProjectStatus(projectId, ProjectStatus2.COMPLETED);
6710
+ },
6711
+ "completeProject"
6712
+ ), importQuickBooksProjectId = __name2(async (projectId, projectUrl) => {
6704
6713
  const result = await api2.project.importQboProjectId.mutate({ projectId, projectUrl });
6705
6714
  out(result);
6706
6715
  }, "importQuickBooksProjectId"), listWebhookEventTypes = __name2(async () => {
@@ -6715,7 +6724,9 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6715
6724
  }, "createWebhookEndpoint"), updateWebhookEndpoint = __name2(async (input) => {
6716
6725
  out(await api2.webhook.updateEndpoint.mutate(input));
6717
6726
  }, "updateWebhookEndpoint"), deleteWebhookEndpoint = __name2(async (id) => {
6718
- await assertSensitiveWorkflowConfirmed({ action: "Delete webhook endpoint and its delivery history", entity: "webhook endpoint ".concat(id) }), out(await api2.webhook.deleteEndpoint.mutate({ 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 }));
6719
6730
  }, "deleteWebhookEndpoint"), rotateWebhookSecret = __name2(async (input) => {
6720
6731
  await assertSensitiveWorkflowConfirmed({ action: "Rotate webhook signing secret", entity: "webhook endpoint ".concat(input.id), details: "previous secrets keep signing for ".concat(input.previousSecretTtlHours ?? 24, "h") });
6721
6732
  const result = await api2.webhook.rotateSecret.mutate(input);
@@ -6726,9 +6737,12 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6726
6737
  out(await api2.webhook.listDeliveries.query(input));
6727
6738
  }, "listWebhookDeliveries"), getWebhookDelivery = __name2(async (deliveryId) => {
6728
6739
  out(await api2.webhook.getDelivery.query({ deliveryId }));
6729
- }, "getWebhookDelivery"), replayWebhookDelivery = __name2(async (deliveryId) => {
6730
- out(await api2.webhook.replayDelivery.mutate({ deliveryId }));
6731
- }, "replayWebhookDelivery"), listIntegrationOperations = __name2(async (input) => {
6740
+ }, "getWebhookDelivery"), replayWebhookDelivery = __name2(
6741
+ async (deliveryId) => {
6742
+ out(await api2.webhook.replayDelivery.mutate({ deliveryId }));
6743
+ },
6744
+ "replayWebhookDelivery"
6745
+ ), listIntegrationOperations = __name2(async (input) => {
6732
6746
  const result = await api2.integration.listOperations.query(input);
6733
6747
  out(result);
6734
6748
  }, "listIntegrationOperations"), getIntegrationOperation = __name2(async (operationId) => {
@@ -6744,10 +6758,13 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6744
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" });
6745
6759
  const result = await api2.integration.reconcileResourceOperation.mutate({ operationId });
6746
6760
  out(result);
6747
- }, "reconcileResourceOperation"), listInboundSources = __name2(async (input) => {
6748
- const result = await api2.inbound.listSources.query(input);
6749
- out(result);
6750
- }, "listInboundSources"), countInboundSources = __name2(async (input) => {
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) => {
6751
6768
  const result = await api2.inbound.countSources.query(input);
6752
6769
  out(result);
6753
6770
  }, "countInboundSources"), createInboundSource = __name2(async (input) => {
@@ -6765,9 +6782,7 @@ var checkProjectReconciliation = __name2(async (projectId) => {
6765
6782
  }, "listInboundSubmissions"), countInboundSubmissions = __name2(async (input) => {
6766
6783
  out(await api2.inbound.countSubmissions.query(input));
6767
6784
  }, "countInboundSubmissions"), getInboundSubmission = __name2(async (submissionId) => {
6768
- const result = await api2.inbound.getSubmission.query(
6769
- { submissionId }
6770
- );
6785
+ const result = await api2.inbound.getSubmission.query({ submissionId });
6771
6786
  out(result);
6772
6787
  }, "getInboundSubmission"), saveInboundMappingVersion = __name2(async (sourceId, mappings) => {
6773
6788
  const source = await api2.inbound.getSource.query({ sourceId }), result = await api2.inbound.saveMappingVersion.mutate({ expectedActiveMappingVersion: source.activeMappingVersion, mappings, sourceId });
@@ -6786,12 +6801,9 @@ async function listContacts(companyId) {
6786
6801
  __name(listContacts, "listContacts"), __name2(listContacts, "listContacts");
6787
6802
  var listItems = __name2(async (input) => {
6788
6803
  out(await api2.item.getItems.query(input));
6789
- }, "listItems"), countItems = __name2(
6790
- async (input) => {
6791
- out(await api2.item.getItemCounts.query(input));
6792
- },
6793
- "countItems"
6794
- );
6804
+ }, "listItems"), countItems = __name2(async (input) => {
6805
+ out(await api2.item.getItemCounts.query(input));
6806
+ }, "countItems");
6795
6807
  async function getItem(id) {
6796
6808
  const item = await api2.item.getItem.query({ id });
6797
6809
  out(item);
@@ -6895,9 +6907,7 @@ async function getApprovedBudgets(opts) {
6895
6907
  const maxR = opts.maxRevenue;
6896
6908
  filtered = filtered.filter((i) => i.revenue <= maxR);
6897
6909
  }
6898
- out(
6899
- { budgets: filtered, count: filtered.length, totalCount }
6900
- );
6910
+ out({ budgets: filtered, count: filtered.length, totalCount });
6901
6911
  }
6902
6912
  __name(getApprovedBudgets, "getApprovedBudgets"), __name2(getApprovedBudgets, "getApprovedBudgets");
6903
6913
  async function getBudgetCategoryBenchmarks(opts) {
@@ -6915,6 +6925,14 @@ async function getSupplierPricingHistory(opts) {
6915
6925
  out(result);
6916
6926
  }
6917
6927
  __name(getSupplierPricingHistory, "getSupplierPricingHistory"), __name2(getSupplierPricingHistory, "getSupplierPricingHistory");
6928
+ async function getBillReview(billId) {
6929
+ out(await api2.ai.getBillReview.query({ billId }));
6930
+ }
6931
+ __name(getBillReview, "getBillReview"), __name2(getBillReview, "getBillReview");
6932
+ async function requestBillReview(billId, requestId) {
6933
+ out(await api2.ai.requestBillReview.mutate({ billId, requestId }));
6934
+ }
6935
+ __name(requestBillReview, "requestBillReview"), __name2(requestBillReview, "requestBillReview");
6918
6936
  function parseLongFlag(arg, next, flags) {
6919
6937
  const eq = arg.indexOf("=");
6920
6938
  if (eq > 0) return flags[arg.slice(2, eq)] = arg.slice(eq + 1), !1;
@@ -6961,7 +6979,10 @@ __name(parseJsonObjectFlag, "parseJsonObjectFlag"), __name2(parseJsonObjectFlag,
6961
6979
  function parseOptionalNumber(raw, label) {
6962
6980
  if (raw === void 0 || raw === "") return;
6963
6981
  const n = typeof raw == "number" ? raw : Number.parseFloat(String(raw).trim());
6964
- if (!Number.isFinite(n)) throw new CliRuntimeError("VALIDATION", "".concat(label, " must be a number."));
6982
+ if (!Number.isFinite(n)) throw new CliRuntimeError("VALIDATION", "".concat(
6983
+ label,
6984
+ " must be a number."
6985
+ ));
6965
6986
  return n;
6966
6987
  }
6967
6988
  __name(parseOptionalNumber, "parseOptionalNumber"), __name2(parseOptionalNumber, "parseOptionalNumber");
@@ -6979,71 +7000,70 @@ g, customerMemo: string}; isCustomPercentage: boolean", example: '{"budgetId":"<
6979
7000
  mitted", example: '[{"canonicalField":"CONTACT_FIRST_NAME","typeformFieldId":"<typeform-field-id>"}]' }, "save-inbound-automation-config": { required: "positional <sourceId>; asanaCustomFields: object; asanaDefaultAssigneeId: string|null; asanaDefaultAssigneeName: string|null; asanaFollowerIds: string[]; asanaProjectId: string; asanaSectionId: string; asanaWonSectionId: string; asanaLostSectionId: string; googleCalendarId: string; googleCalendarTimeZone: string; goshBriefBaseUrl: URL", optional: "asanaDiscussionSectionId, asanaFirstContactSectionId, asanaFirstProposalSentSectionId, asanaProposalWipSectionId: string|null; googlePitchCalendarId: string|null (PITCH project events; must differ from googleCalendarId; null keeps them in googleCalendarId); asanaCustomFields.*: mapped IDs", example: '{"asanaCustomFields":{},"asanaDefaultAssigneeId":null,"asanaDefaultAssigneeName":null,"asanaFollowerIds":[],"asanaProjectId":"<asana-project-id>","asanaSectionId":"<asana-section-id>","asanaWonSec\
6980
7001
  tionId":"<asana-won-id>","asanaLostSectionId":"<asana-lost-id>","googleCalendarId":"team@example.com","googleCalendarTimeZone":"Asia/Singapore","goshBriefBaseUrl":"https://example.com/brief"}' } }, formatPayloadHelp = __name2((command) => {
6981
7002
  const help = payloadHelp[command];
6982
- return help ? ["Payload fields (--payload JSON)", " Required: ".concat(help.required), " Optional: ".concat(help.optional), " Example: bb ".concat(command).concat(
6983
- command === "link-bill-quotations" ? " <billId>" : command.startsWith("save-inbound-") ? " <sourceId>" : "",
6984
- " --payload '"
6985
- ).concat(help.example, "'"), ""] : [];
7003
+ 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, "'"), ""] : [];
6986
7004
  }, "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\
6987
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\
6988
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\
6989
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", "\
6990
- remove-budget-item", "restore-budget-version", "update-project-status"]), explicitEffects = { "resubmit-customer-invoice": [
6991
- "state-change",
6992
- "external-write",
6993
- "financial-write",
6994
- "email"
6995
- ], "rotate-webhook-secret": ["state-change"], "replay-webhook-delivery": ["state-change", "external-write"] }, effectsFor = __name2((legacyTarget) => {
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) => {
6996
7009
  const explicit = explicitEffects[legacyTarget];
6997
7010
  if (explicit) return explicit;
6998
7011
  const effects = /* @__PURE__ */ new Set();
6999
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];
7000
7013
  }, "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."], [
7001
7014
  "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\
7002
- 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>."], ["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-i\
7003
- tems", "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 }; 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\
7004
- , 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-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 }; follo\
7005
- w 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 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 c\
7006
- ursor 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-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 AL\
7007
- L|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 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|des\
7008
- c] [--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|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] [--su\
7009
- pplierId] [--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>] 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 ba\
7010
- ckward 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 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, pag\
7011
- eInfo }; 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. 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\
7012
- 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 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, oper\
7013
- ationId) 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>."], ["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 addres\
7014
- s, 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>. 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.\
7015
- 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 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-opera\
7016
- tions", "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", "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; extra\
7017
- ctedAmount 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. --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 w\
7018
- ith 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-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\
7019
- 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 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 (refr\
7020
- eshing 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 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\
7021
- 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 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 th\
7022
- e 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 { 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\
7023
- -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 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 \
7024
- 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 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 budg\
7025
- et 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, 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 pric\
7026
- ed 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. 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 pr\
7027
- ovider 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 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 (s\
7028
- tatus 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 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(
7029
- (legacyTarget) => {
7015
+ 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
+ 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) => {
7030
7046
  const summary = SUMMARIES.get(legacyTarget);
7031
7047
  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), ".");
7032
- }, "summaryFor"), aliasesFor = __name2((legacyTarget, aliases) => [...new Set([legacyTarget, ...aliases].flatMap((alias) => [alias, alias.replaceAll("-", "_")]))], "aliasesFor"), legacyCommand = __name2((legacyTarget, path2, aliases = [], commandOptions = []) => ({
7033
- path: path2,
7034
- legacyAliases: aliasesFor(legacyTarget, aliases),
7035
- summary: summaryFor(legacyTarget),
7036
- options: [...globalCommandOptions, ...commandOptions],
7037
- effects: effectsFor(legacyTarget),
7038
- legacyTarget
7039
- }), "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 = [
7040
- authCommand("login", "Authorize this device through Budget Builder in your browser."),
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
+ ),
7041
7056
  authCommand("status", "Show the active CLI authentication method and session status."),
7042
7057
  authCommand("logout", "Revoke the interactive CLI session and remove its local credential."),
7043
7058
  legacyCommand("whoami", ["auth", "whoami"]),
7044
7059
  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." }]),
7045
7060
  legacyCommand("count-budgets", ["budget", "count"], [], [{ name: "--active <true|false|all>", description: "Omit for active budgets only; false or all requires Admin access." }]),
7046
- legacyCommand("get-budget", ["budget", "get"], [], [{ name: "--includeInactive", description: "Include inactive historical budgets; Admin only." }]),
7061
+ legacyCommand(
7062
+ "get-budget",
7063
+ ["budget", "get"],
7064
+ [],
7065
+ [{ name: "--includeInactive", description: "Include inactive historical budgets; Admin only." }]
7066
+ ),
7047
7067
  legacyCommand("upload-budget-attachment", ["budget", "attachment", "upload"]),
7048
7068
  legacyCommand("mark-budget-won", ["budget", "won", "mark"]),
7049
7069
  legacyCommand("get-budget-items", ["budget", "item", "list"], [], [{ name: "--includeInactive", description: "Include inactive historical budgets; Admin only." }]),
@@ -7072,17 +7092,17 @@ tatus codes, errors, durations). Argument: <deliveryId>."], ["list-webhook-event
7072
7092
  legacyCommand("update-budget-commission", ["budget", "commission", "update"]),
7073
7093
  legacyCommand("update-budget-discount", ["budget", "discount", "update"]),
7074
7094
  legacyCommand("delete-budget-commission", ["budget", "commission", "delete"]),
7075
- legacyCommand("delete-budget-discount", ["budget", "discount", "delete"]),
7095
+ legacyCommand(
7096
+ "delete-budget-discount",
7097
+ ["budget", "discount", "delete"]
7098
+ ),
7076
7099
  legacyCommand("mark-budget-items-not-utilized", ["budget", "item", "mark-not-utilized"]),
7077
7100
  legacyCommand("restore-budget-item", ["budget", "item", "restore"]),
7078
7101
  legacyCommand("create-placeholder-bill", ["budget", "item", "placeholder-bill", "create"]),
7079
7102
  legacyCommand("list-bills", ["bill", "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." }]),
7080
7103
  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." }]),
7081
7104
  legacyCommand("count-bills", ["bill", "count"]),
7082
- legacyCommand(
7083
- "count-claims",
7084
- ["claim", "count"]
7085
- ),
7105
+ legacyCommand("count-claims", ["claim", "count"]),
7086
7106
  legacyCommand("create-bill-approval", ["bill", "approval", "create"]),
7087
7107
  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." }]),
7088
7108
  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." }]),
@@ -7103,22 +7123,29 @@ tatus codes, errors, durations). Argument: <deliveryId>."], ["list-webhook-event
7103
7123
  legacyCommand("attach-bill-payment-receipt", ["bill", "payment-receipt", "attach"]),
7104
7124
  legacyCommand("attach-bill-documents", ["bill", "document", "attach"]),
7105
7125
  legacyCommand("get-bill-details", ["bill", "get"]),
7126
+ legacyCommand("get-bill-review", ["bill", "review"]),
7127
+ legacyCommand("request-bill-review", ["bill", "request-review"]),
7106
7128
  legacyCommand("get-bill-line-items", ["bill", "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." }]),
7107
7129
  legacyCommand("get-bill-approvals", ["bill", "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." }]),
7108
7130
  legacyCommand("get-bill-payment", ["bill", "payment", "get"]),
7109
7131
  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." }]),
7110
7132
  legacyCommand("count-quotations", ["quotation", "count"]),
7111
7133
  legacyCommand("get-quotation", ["quotation", "get"]),
7112
- 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." }]),
7113
- legacyCommand("upload-quotation-attachment", ["quotation", "attachment", "upload"]),
7114
7134
  legacyCommand(
7115
- "cleanup-staged-quotation-attachments",
7116
- ["quotation", "attachment", "staged", "cleanup"]
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." }]
7117
7139
  ),
7140
+ legacyCommand("upload-quotation-attachment", ["quotation", "attachment", "upload"]),
7141
+ legacyCommand("cleanup-staged-quotation-attachments", ["quotation", "attachment", "staged", "cleanup"]),
7118
7142
  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 }]),
7119
7143
  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 }]),
7120
7144
  legacyCommand("delete-quotation", ["quotation", "delete"]),
7121
- legacyCommand("submit-quotation", ["quotation", "submit"]),
7145
+ legacyCommand(
7146
+ "submit-quotation",
7147
+ ["quotation", "submit"]
7148
+ ),
7122
7149
  legacyCommand("approve-quotation", ["quotation", "approve"]),
7123
7150
  legacyCommand("reject-quotation", ["quotation", "reject"]),
7124
7151
  legacyCommand("download-quotation-pdf", ["quotation", "pdf", "download"]),
@@ -7132,7 +7159,10 @@ tatus codes, errors, durations). Argument: <deliveryId>."], ["list-webhook-event
7132
7159
  legacyCommand("get-customer-invoice-invoices", ["customer-invoice", "invoice", "list"]),
7133
7160
  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." }]),
7134
7161
  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." }]),
7135
- 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." }]),
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
+ ]),
7136
7166
  legacyCommand("get-customer-invoice-payments", ["customer-invoice", "payments", "list"]),
7137
7167
  legacyCommand("get-customer-invoice-email-context", ["customer-invoice", "email-context", "get"]),
7138
7168
  legacyCommand("preview-qbo-customer-invoice", ["customer-invoice", "preview-qbo"]),
@@ -7148,13 +7178,14 @@ tatus codes, errors, durations). Argument: <deliveryId>."], ["list-webhook-event
7148
7178
  legacyCommand("download-customer-invoice-pdf", ["customer-invoice", "pdf", "download"]),
7149
7179
  legacyCommand("sync-customer-invoice", ["customer-invoice", "sync"]),
7150
7180
  legacyCommand("update-customer-invoice-details", ["customer-invoice", "details", "update"]),
7151
- legacyCommand(
7152
- "update-customer-invoice-qbo-drift",
7153
- ["customer-invoice", "qbo-drift", "resolve"]
7154
- ),
7181
+ legacyCommand("update-customer-invoice-qbo-drift", ["customer-invoice", "qbo-drift", "resolve"]),
7155
7182
  legacyCommand("mark-customer-invoice-sent-externally", ["customer-invoice", "mark-sent-externally"]),
7156
- legacyCommand("list-approvals", ["approval", "list"], ["get-pending-approvals"]),
7157
- legacyCommand("approve-bill", ["bill", "approve"]),
7183
+ 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
+ legacyCommand("get-pending-approval", ["approval", "get"]),
7185
+ legacyCommand("approve-bill", [
7186
+ "bill",
7187
+ "approve"
7188
+ ]),
7158
7189
  legacyCommand("reject-bill", ["bill", "reject"]),
7159
7190
  legacyCommand("approve-budget", ["budget", "approve"]),
7160
7191
  legacyCommand("reject-budget", ["budget", "reject"]),
@@ -7196,10 +7227,7 @@ sor; pass nextCursor forward or previousCursor backward unchanged." }, { name: "
7196
7227
  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\
7197
7228
  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." }]),
7198
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." }]),
7199
- legacyCommand(
7200
- "create-supplier",
7201
- ["supplier", "create"]
7202
- ),
7230
+ legacyCommand("create-supplier", ["supplier", "create"]),
7203
7231
  legacyCommand("update-supplier", ["supplier", "update"]),
7204
7232
  legacyCommand("delete-suppliers", ["supplier", "delete"]),
7205
7233
  legacyCommand("reactivate-suppliers", ["supplier", "reactivate"]),
@@ -7219,7 +7247,10 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7219
7247
  legacyCommand("delete-item", ["item", "delete"]),
7220
7248
  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." }]),
7221
7249
  legacyCommand("count-item-categories", ["item", "category", "count"]),
7222
- legacyCommand("create-item-category", ["item", "category", "create"]),
7250
+ legacyCommand(
7251
+ "create-item-category",
7252
+ ["item", "category", "create"]
7253
+ ),
7223
7254
  legacyCommand("update-item-category", ["item", "category", "update"]),
7224
7255
  legacyCommand("delete-item-categories", ["item", "category", "delete"]),
7225
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." }]),
@@ -7234,18 +7265,10 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7234
7265
  legacyCommand("get-system-overview", ["dashboard", "system-overview", "get"]),
7235
7266
  legacyCommand("get-estimate-performance", ["dashboard", "estimate-performance", "get"]),
7236
7267
  legacyCommand("get-financial-overview", ["dashboard", "financial-overview", "get"]),
7237
- legacyCommand("get-recent-errors", [
7238
- "error",
7239
- "recent",
7240
- "list"
7241
- ], [], [{ name: "--cursor <token>", description: "Pass a returned pageInfo boundary unchanged, with the same filters." }, { name: "--direction <direction>", description: "forward (default) uses nextCursor; backward uses previousCursor." }, { name: "--limit <number>", description: "1\u2013100 rows (default 10). Returns items and pageInfo, without a total." }, { name: "--severity <severity>", description: "Error severity or ALL." }, { name: "--status <status>", description: "Error status or ALL." }, { name: "--timeFrame <period>", description: "all_time (default), last_30_days, last_3_months, last_6_months or last_1_year." }]),
7268
+ legacyCommand("get-recent-errors", ["error", "recent", "list"], [], [{ name: "--cursor <token>", description: "Pass a returned pageInfo boundary unchanged, with the same filters." }, { name: "--direction <direction>", description: "forward (default) uses nextCursor; backward uses previousCursor." }, { name: "--limit <number>", description: "1\u2013100 rows (default 10). Returns items and pageInfo, without a total." }, { name: "--severity <severity>", description: "Error severity or ALL." }, { name: "--status <status>", description: "Error status or ALL." }, { name: "--timeFrame <period>", description: "all_time (default), last_30_days, last_3_months, last_6_months or last_1_year." }]),
7242
7269
  legacyCommand("count-errors", ["error", "recent", "count"], [], [{ name: "--severity <severity>", description: "Error severity or ALL." }, { name: "--status <status>", description: "Error status or ALL." }, { name: "--timeFrame <period>", description: "Same filters as error recent list; returns independent totalCount." }]),
7243
7270
  legacyCommand("get-error", ["error", "get"]),
7244
- legacyCommand("get-error-metrics", [
7245
- "error",
7246
- "metrics",
7247
- "get"
7248
- ]),
7271
+ legacyCommand("get-error-metrics", ["error", "metrics", "get"]),
7249
7272
  legacyCommand("list-integration-operations", ["integration", "operation", "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." }]),
7250
7273
  legacyCommand("count-integration-operations", ["integration", "operation", "count"]),
7251
7274
  legacyCommand("get-integration-operation", ["integration", "operation", "get"]),
@@ -7258,7 +7281,10 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7258
7281
  legacyCommand("update-webhook-endpoint", ["webhook", "endpoint", "update"]),
7259
7282
  legacyCommand("delete-webhook-endpoint", ["webhook", "endpoint", "delete"]),
7260
7283
  legacyCommand("rotate-webhook-secret", ["webhook", "secret", "rotate"]),
7261
- legacyCommand("send-webhook-test-event", ["webhook", "endpoint", "test"]),
7284
+ legacyCommand(
7285
+ "send-webhook-test-event",
7286
+ ["webhook", "endpoint", "test"]
7287
+ ),
7262
7288
  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)." }]),
7263
7289
  legacyCommand("get-webhook-delivery", ["webhook", "delivery", "get"]),
7264
7290
  legacyCommand("replay-webhook-delivery", ["webhook", "delivery", "replay"]),
@@ -7267,7 +7293,12 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7267
7293
  legacyCommand("create-inbound-source", ["inbound", "source", "create"]),
7268
7294
  legacyCommand("get-inbound-source", ["inbound", "source", "get"]),
7269
7295
  legacyCommand("update-inbound-source", ["inbound", "source", "update"]),
7270
- 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." }]),
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
+ ),
7271
7302
  legacyCommand("count-inbound-submissions", ["inbound", "submission", "count"], [], [{ name: "--sourceId <id>", description: "Optional source filter. Returns an independently calculated exact totalCount, not a list snapshot." }]),
7272
7303
  legacyCommand("get-inbound-submission", ["inbound", "submission", "get"]),
7273
7304
  legacyCommand("save-inbound-mapping", ["inbound", "mapping", "save"]),
@@ -7293,22 +7324,20 @@ At." }, { name: "--sortDir <asc|desc>", description: "Descending createdAt by de
7293
7324
  }
7294
7325
  }
7295
7326
  }, "assertRegistry");
7296
- assertRegistry(registry2);
7327
+ assertRegistry(
7328
+ registry2
7329
+ );
7297
7330
  var commandRegistry = registry2, resolveCommand = __name2((argv) => {
7298
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));
7299
7332
  if (canonical) return { command: canonical, argv: argv.slice(canonical.path.length), invokedAs: argv.slice(0, canonical.path.length), isLegacyAlias: !1 };
7300
7333
  const rawAlias = argv[0];
7301
7334
  if (!rawAlias) return;
7302
7335
  const normalizedAlias = normalizeToken(rawAlias), legacy = commandRegistry.find((command) => command.legacyAliases.some((alias) => normalizeToken(alias) === normalizedAlias));
7303
- if (legacy) return { command: legacy, argv: argv.slice(1), invokedAs: [
7304
- rawAlias
7305
- ], isLegacyAlias: !0 };
7336
+ if (legacy) return { command: legacy, argv: argv.slice(1), invokedAs: [rawAlias], isLegacyAlias: !0 };
7306
7337
  }, "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) => {
7307
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");
7308
7339
  const lines = commandRegistry.map((command2) => {
7309
- const canonical = "bb ".concat(command2.path.join(" ")), aliases = command2.legacyAliases.filter((alias) => alias.includes("-")).map((alias) => "bb ".concat(
7310
- alias
7311
- )).join(", ");
7340
+ const canonical = "bb ".concat(command2.path.join(" ")), aliases = command2.legacyAliases.filter((alias) => alias.includes("-")).map((alias) => "bb ".concat(alias)).join(", ");
7312
7341
  return " ".concat(canonical, "\n ").concat(command2.summary).concat(aliases ? " Legacy: ".concat(aliases, ".") : "");
7313
7342
  });
7314
7343
  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");
@@ -7339,10 +7368,7 @@ function parsePositiveIntFlag(value, flagName) {
7339
7368
  return parsed;
7340
7369
  }
7341
7370
  __name(parsePositiveIntFlag, "parsePositiveIntFlag"), __name2(parsePositiveIntFlag, "parsePositiveIntFlag");
7342
- var COMPANY_SORT_FIELDS = ["name", "createdAt"], COMPANY_SORT_DIRECTIONS = [
7343
- "asc",
7344
- "desc"
7345
- ], COMPANY_PAGE_FLAGS = ["page", "perPage", "pageSize", "page-size", "per-page", "page_size", "per_page"], rejectBareFlag = __name2((flags, key) => {
7371
+ var COMPANY_SORT_FIELDS = ["name", "createdAt"], COMPANY_SORT_DIRECTIONS = ["asc", "desc"], COMPANY_PAGE_FLAGS = ["page", "perPage", "pageSize", "page-size", "per-page", "page_size", "per_page"], rejectBareFlag = __name2((flags, key) => {
7346
7372
  if (flags[key] === !0) throw new Error("--".concat(key, " requires a value."));
7347
7373
  }, "rejectBareFlag"), rejectCompanyPageFlags = __name2((flags, command) => {
7348
7374
  for (const key of COMPANY_PAGE_FLAGS) if (flags[key] !== void 0) throw new Error("--".concat(key, " is not supported by company ").concat(command, "; use --limit and --cursor for list or company count for totals."));
@@ -7351,14 +7377,11 @@ var COMPANY_SORT_FIELDS = ["name", "createdAt"], COMPANY_SORT_DIRECTIONS = [
7351
7377
  const parsed = Number(String(value));
7352
7378
  if (!Number.isInteger(parsed) || parsed < 1 || parsed > 100) throw new Error("--limit must be an integer from 1 to 100.");
7353
7379
  return parsed;
7354
- }, "parseCompanyLimit"), parseCompanySortBy = __name2(
7355
- (value) => {
7356
- if (value === void 0) return "createdAt";
7357
- if (!COMPANY_SORT_FIELDS.includes(value)) throw new Error('Invalid --sortBy "'.concat(value, '". Use one of: ').concat(COMPANY_SORT_FIELDS.join(", "), "."));
7358
- return value;
7359
- },
7360
- "parseCompanySortBy"
7361
- ), parseCompanySortDir = __name2((value) => {
7380
+ }, "parseCompanyLimit"), parseCompanySortBy = __name2((value) => {
7381
+ if (value === void 0) return "createdAt";
7382
+ if (!COMPANY_SORT_FIELDS.includes(value)) throw new Error('Invalid --sortBy "'.concat(value, '". Use one of: ').concat(COMPANY_SORT_FIELDS.join(", "), "."));
7383
+ return value;
7384
+ }, "parseCompanySortBy"), parseCompanySortDir = __name2((value) => {
7362
7385
  if (value === void 0) return "desc";
7363
7386
  if (!COMPANY_SORT_DIRECTIONS.includes(value)) throw new Error('Invalid --sortDir "'.concat(value, '". Use one of: ').concat(COMPANY_SORT_DIRECTIONS.join(", "), "."));
7364
7387
  return value;
@@ -7372,22 +7395,29 @@ var COMPANY_SORT_FIELDS = ["name", "createdAt"], COMPANY_SORT_DIRECTIONS = [
7372
7395
  const cursor = getFlag(flags, "cursor"), direction = parseCompanyDirection(getFlag(flags, "direction"));
7373
7396
  if (direction === "backward" && cursor === void 0) throw new Error("--direction backward requires --cursor <token>.");
7374
7397
  if (cursor === "") throw new Error("--cursor requires a non-empty token.");
7375
- return { name: getFlag(
7376
- flags,
7377
- "name"
7378
- ), 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")) };
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
+ };
7379
7409
  }, "parseCompanyListFlags"), parseCompanyCountFlags = __name2((flags) => {
7380
7410
  rejectCompanyPageFlags(flags, "count");
7381
7411
  for (const key of ["name", "createdBy", "createdByIds", "active", "limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7382
7412
  if (flags.limit !== void 0 || flags.cursor !== void 0 || flags.direction !== void 0) throw new Error("company count does not accept list pagination flags.");
7383
7413
  if (flags.sortBy !== void 0 || flags.sortDir !== void 0) throw new Error("company count does not accept list sorting flags.");
7384
- return { name: getFlag(flags, "name"), createdBy: getFlag(flags, "createdBy"), createdByIds: parseCommaSeparatedIds(getFlag(flags, "createdByIds")), active: parseOptionalBoolFlag(
7385
- flags,
7386
- "active"
7387
- ) };
7388
- }, "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) => {
7389
- 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."));
7390
- }, "rejectProjectPageFlags"), parseProjectLimit = __name2((value) => {
7414
+ 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) => {
7391
7421
  if (value === void 0) return 20;
7392
7422
  const parsed = Number(String(value));
7393
7423
  if (!Number.isInteger(parsed) || parsed < 1 || parsed > 100) throw new Error("--limit must be an integer from 1 to 100.");
@@ -7411,10 +7441,7 @@ var COMPANY_SORT_FIELDS = ["name", "createdAt"], COMPANY_SORT_DIRECTIONS = [
7411
7441
  return value;
7412
7442
  }, "parseProjectDirection"), parseProjectListFlags = __name2((flags) => {
7413
7443
  rejectProjectPageFlags(flags, "list");
7414
- for (const key of ["companyId", "name", "status", "statuses", "active", "wonFrom", "wonTo", "wonWithinDays", "limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(
7415
- flags,
7416
- key
7417
- );
7444
+ for (const key of ["companyId", "name", "status", "statuses", "active", "wonFrom", "wonTo", "wonWithinDays", "limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7418
7445
  const cursor = getFlag(flags, "cursor"), direction = parseProjectDirection(getFlag(flags, "direction"));
7419
7446
  if (direction === "backward" && cursor === void 0) throw new Error("--direction backward requires --cursor <token>.");
7420
7447
  if (cursor === "") throw new Error("--cursor requires a non-empty token.");
@@ -7456,7 +7483,9 @@ __name(parseCustomerInvoiceSortBy, "parseCustomerInvoiceSortBy"), __name2(parseC
7456
7483
  function parseCommercialRejectionProjectStatus(flags) {
7457
7484
  const raw = flags.projectStatusOnCommercialRejection;
7458
7485
  if (raw === void 0) return;
7459
- if (raw === !0) throw new Error("--projectStatusOnCommercialRejection requires PITCH or LOST.");
7486
+ if (raw === !0) throw new Error(
7487
+ "--projectStatusOnCommercialRejection requires PITCH or LOST."
7488
+ );
7460
7489
  const status = String(raw).toUpperCase();
7461
7490
  if (status === ProjectStatus2.PITCH || status === ProjectStatus2.LOST) return status;
7462
7491
  throw new Error("--projectStatusOnCommercialRejection must be PITCH or LOST.");
@@ -7470,7 +7499,10 @@ var rejectRetiredPageFlags = __name2((flags) => {
7470
7499
  rejectRetiredPageFlags(flags);
7471
7500
  for (const key of ["limit", "cursor"]) rejectBareFlag(flags, key);
7472
7501
  if (flags.direction !== void 0) throw new Error("".concat(command, " pages forward only; follow pageInfo.nextCursor with --cursor."));
7473
- const cursor = getFlag(flags, "cursor");
7502
+ const cursor = getFlag(
7503
+ flags,
7504
+ "cursor"
7505
+ );
7474
7506
  if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7475
7507
  const limitFlag = getFlag(flags, "limit"), limit = limitFlag === void 0 ? void 0 : Number(limitFlag);
7476
7508
  if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > maxLimit)) throw new Error("--limit must be an integer from 1 to ".concat(maxLimit, "."));
@@ -7478,17 +7510,18 @@ var rejectRetiredPageFlags = __name2((flags) => {
7478
7510
  }, "parseDetailFeedPage"), parseBillFilterFlags = __name2((flags) => {
7479
7511
  const statusRaw = getFlag(flags, "status"), createdByIdsRaw = getFlag(flags, "createdByIds"), searchRaw = getFlag(flags, "search");
7480
7512
  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) };
7481
- }, "parseBillFilterFlags"), parseQuotationFilterFlags = __name2((flags) => {
7482
- const createdByRaw = getFlag(flags, "createdBy") ?? getFlag(flags, "requesterIds"), searchRaw = getFlag(flags, "search");
7483
- 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 };
7484
- }, "parseQuotationFilterFlags");
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
+ );
7485
7520
  function parseListBillsFlags(flags) {
7486
7521
  rejectRetiredPageFlags(flags);
7487
7522
  for (const key of ["limit", "cursor", "direction", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7488
7523
  const sortByRaw = getFlag(flags, "sortBy"), sortDirRaw = getFlag(flags, "sortDir"), cursor = getFlag(flags, "cursor");
7489
- if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error(
7490
- "--cursor must be a non-empty opaque token of at most 8192 characters."
7491
- );
7524
+ if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7492
7525
  const direction = parseProjectDirection(getFlag(flags, "direction"));
7493
7526
  if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7494
7527
  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 };
@@ -7512,12 +7545,12 @@ var parseSupplierFilters = __name2((flags) => {
7512
7545
  for (const key of ["name", "createdBy", "gstRegistered", "status", "supplierTags", "active"]) rejectBareFlag(flags, key);
7513
7546
  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 };
7514
7547
  }, "parseSupplierFilters"), rejectSupplierPageFlags = __name2((flags) => {
7515
- for (const key of PROJECT_PAGE_FLAGS) if (flags[key] !== void 0) throw new Error(
7516
- "--".concat(key, " is retired for suppliers; use --limit/--cursor or supplier count for totals.")
7517
- );
7548
+ 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."));
7518
7549
  }, "rejectSupplierPageFlags"), parseSupplierListSortEntries = __name2((sortRaw) => {
7519
7550
  const parsed = parseJsonFlag(sortRaw, "--sort");
7520
- if (!Array.isArray(parsed) || parsed.length > 8) throw new Error("--sort must be a JSON array of at most eight {id, desc} entries.");
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.");
7521
7554
  return parsed.map((item) => {
7522
7555
  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}.");
7523
7556
  const id = parseOptionalSupplierSortBy(item.id);
@@ -7528,25 +7561,24 @@ var parseSupplierFilters = __name2((flags) => {
7528
7561
  const sortRaw = getFlag(flags, "sort");
7529
7562
  if (sortRaw !== void 0) {
7530
7563
  if (flags.sortBy !== void 0 || flags.sortDir !== void 0) throw new Error("Use --sort or --sortBy/--sortDir, not both.");
7531
- return parseSupplierListSortEntries(
7532
- sortRaw
7533
- );
7564
+ return parseSupplierListSortEntries(sortRaw);
7534
7565
  }
7535
7566
  const sortBy = parseOptionalSupplierSortBy(getFlag(flags, "sortBy")), sortDir = parseOptionalBillListSortDir(getFlag(flags, "sortDir"));
7536
7567
  return [{ id: sortBy ?? "createdAt", desc: (sortDir ?? "desc") === "desc" }];
7537
- }, "parseSupplierListSort"), parseListSuppliersFlags = __name2((flags) => {
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) => {
7538
7581
  rejectSupplierPageFlags(flags);
7539
- for (const key of ["limit", "cursor", "direction", "sort", "sortBy", "sortDir"]) rejectBareFlag(flags, key);
7540
- const limit = getFlag(flags, "limit") === void 0 ? 10 : parseProjectLimit(getFlag(flags, "limit")), cursor = getFlag(flags, "cursor");
7541
- if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7542
- const direction = parseProjectDirection(getFlag(flags, "direction"));
7543
- if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7544
- const sort = parseSupplierListSort(flags);
7545
- return { ...parseSupplierFilters(flags), limit, cursor, direction, sort };
7546
- }, "parseListSuppliersFlags"), parseCountSuppliersFlags = __name2((flags) => {
7547
- rejectSupplierPageFlags(
7548
- flags
7549
- );
7550
7582
  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."));
7551
7583
  return parseSupplierFilters(flags);
7552
7584
  }, "parseCountSuppliersFlags");
@@ -7567,32 +7599,35 @@ on backward, keeping the same filters and sort. --page/--pageSize/--perPage are
7567
7599
  ations. Document-only quotations (documentOnly: true, $0) are never valid bill sources; create-bill, update-bill, validate-bill-selection and link-bill-quotations reject them, and a line covered only by one still counts as unquoted.\n Amounts for create/update (including drafts) exclude GST: amount = portion billed; extractedAmount = full invoice subtotal; lineAmounts[].amount and quotationAllocations[].amount also exclude GST. The CLI does not strip GST from input.\n Example: invoice subtotal 1800 + GST 162 = total 1962 -> amount: 1800, extractedAmount: 1800, allocations totaling 1800. BB calculates applicable GST separately. Re-read and verify both amount fields after writing.\n create-bill-approval <billId> (also queues approval request emails)\n create-bill --payload '<json>' [--draft-only] [--quotation-exempt] (bill.create; supplier bills use payload.quotationAllocations for split sources or quotationIds for disjoint coverage; explicit allocations require lin\
7568
7600
  eAmounts; claims reject quotation sources; an Admin's unpaid bill queues its QuickBooks bill: quickBooksSyncQueued, operationId)\n validate-bill-selection --payload '<json>' [--quotationIds <csv> | --quotationId <id>] Validate an approved supplier and approved quotation coverage for each supplier-bill line. --quotationId is legacy single-quotation syntax.\n link-bill-quotations <billId> (--payload '<json>' | --quotationIds <csv>) Admin-only source-link repair; payload.quotationAllocations supports same-line splits.\n stage-bill-attachment <projectId> <filePath...> [--file <path>] [--files <csv>] Upload files before create-bill; returns attachment JSON for attachments/paymentProofAttachments\n cleanup-staged-bill-attachments <projectId> --keys <csv> Queue cleanup of unattached staged uploads; returns operation IDs.\n update-bill --payload '<json>' (bill.update; must include id)\n update-bill-payment-evidence --payload '<json>' Replace paymentReference/pay\
7569
7601
  mentProofAttachments for an already-paid bill.\n delete-bill <billId>\n update-bill-status <id> <status> [--rejectionReason] [--paymentTrackingUrl] [--paymentReference] [--paymentProof <receipt.pdf>] [--overBudgetOverrideReason <text>]\n status (").concat(billStatusesForUpdateHelp.join(", "), ') \u2014 not PENDING_APPROVAL; use create-bill-approval\n PAID requires --paymentReference and a payment-proof PDF. Use --paymentProof to stage and submit the PDF atomically, or omit it only when BB already has a BILL_PAYMENT_PROOF attachment.\n Moving a bill or claim to PAID runs the server\'s paid-bill notification workflow.\n patch-bill-payment <billId> [--paymentTrackingUrl] [--paymentReference] [--quickbooksBillId] [--paymentDate <ISO>]\n Clear a field: --clearPaymentTrackingUrl true | --clearPaymentReference true | --clearQuickbooksBillId true | --clearPaymentDate true\n patch-bill-invoice-number <billId> <invoiceNumber>\n get-bill-attachments <billId> [--limit 1-50] [--cursor <token>]\
7570
- \n Newest first. Returns { items, pageInfo }; follow nextCursor.\n upload-bill-attachment <billId> <filePath...> [--file <path>] [--files <csv>] Attach invoice/supporting files as BILL attachments to any bill status, including PAID bills\n attach-bill-payment-receipt <billId> <filePath...> [--file <path>] [--files <csv>] Attach Wise/payment-proof PDFs as BILL_PAYMENT_PROOF attachments\n attach-bill-documents <billId> [--invoice <path>] [--invoices <csv>] [--paymentProof|--payment-proof|--proof <path>] [--paymentProofs|--payment-proofs|--proofs <csv>] Attach invoice and/or payment proof files with separate BB attachment types\n get-bill-details <billId> Bill summary as shown in the web app (status, amounts, people, payment, line totals)\n get-bill-line-items <billId> [--limit 1-100] [--cursor <token>] Line items with budget-item/quotation detail; { items, pageInfo }\n get-bill-approvals <billId> [--limit 1-50] [--cursor <token>] Approval requests with approver/requester/re\
7571
- sponder; { items, pageInfo }\n get-bill-payment <billId> Payment status, reference, date, tracking URL, QuickBooks link and external payment\n\nQuotations\n list-quotations [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Newest first; returns { items, pageInfo }; rows carry 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.\n count-quotations [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--includeMetrics true|false] totalCount, status facets (ignore --status) and optional amount metrics\n get-quotation <quotationId> Quotation as shown in the web app (status, documentOnly, amounts, people, line totals, files, approvals; pdfProcessing is PROC\
7572
- ESSING or FAILED until queued PDF conversion/signing links the PDF; gstMismatch warns when GST differs from the expected GST)\n get-quotation-line-items <quotationId> [--limit 1-100] [--cursor <token>] Line items with budget-item detail; { items, pageInfo }\n upload-quotation-attachment <projectId> <filePath> Upload one PDF, JPEG, or PNG up to 20MB; returns attachment JSON for a quotation payload.\n cleanup-staged-quotation-attachments <projectId> --keys <csv> Queue cleanup of unattached quotation uploads; returns operation IDs.\n create-quotation --payload \'<json>\' (quotation.createDraft; requires amountWithoutGst, gstAmount, and lineAmounts [{budgetItemId, amount}] for multiple budgetItemIds; amounts before GST must sum to amountWithoutGst; result gstMismatch warns when gstAmount is not 0 or the expected GST)\n Document-only ($0 supplier document, e.g. a contract or proposal with no price): set documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and zero line\
7573
- Amounts (lineAmounts may be omitted). It goes through submit/sign/approve like any quotation and shows documentOnly: true in list/get output, but it is never a valid bill quotation source (create-bill, update-bill, validate-bill-selection and link-bill-quotations are rejected by the API) and does not count as quotation coverage: a budget line covered only by it still counts as unquoted. Without documentOnly (default false), amountWithoutGst must be positive.\n Example: --payload \'{"projectId":"<id>","budgetId":"<id>","supplierId":"<id>","budgetItemIds":["<id>"],"amountWithoutGst":0,"gstAmount":0,"documentOnly":true,"attachments":[<uploaded attachment>]}\'\n update-quotation --payload \'<json>\' Update a DRAFT or REJECTED quotation; same allocation payload plus id; use lineAmounts [{budgetItemId, amount}] for every selected item. Result gstMismatch warns when gstAmount is not 0 or the expected GST. Update is a full replace: send documentOnly: true again when updating a documen\
7574
- t-only quotation, or it is treated as a priced quotation and needs a positive amountWithoutGst.\n delete-quotation <quotationId>\n submit-quotation <quotationId> [--overBudgetOverrideReason <text>] (signed PDF is made by a queued job: pdfProcessing; gstMismatch warns when GST is not 0 or the expected GST)\n approve-quotation <quotationId> [--overBudgetOverrideReason <text>] (assigned pending request/current Admin; concurrent revision or allocation changes conflict; final signed PDF is queued: pdfProcessing)\n reject-quotation <quotationId> --reason <text>\n download-quotation-pdf <quotationId> [original|staff|final] (refused with "still processing" until the queued PDF step links it)\n\nCustomer invoices\n check-customer-invoice-readiness <budgetId> Readiness plus the full remaining-balance amount preview and live QuickBooks validation.\n list-eligible-customer-invoice-budgets <projectId> Accepted budgets that are ready and still have invoice coverage remaining, including \
7575
- estimate total, invoiced/remaining percentages, and available amount.\n preview-customer-invoice-amount <budgetId> <percentage-of-estimate> Preview amount before GST, GST, and total for a percentage of the original estimate. The percentage cannot exceed the budget\'s remaining coverage.\n list-available-qbo-customer-invoices <budgetId> List unlinked QuickBooks invoices available for this accepted or closed estimate before previewing and importing one.\n list-customer-invoices [budgetId] [--projectId <id>] [--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]\n Returns { items, pageInfo }; follow nextCursor/previousCursor with the same filters and sort. --page/--perPage are rejected.\n No scope flag lists invoices globally. --projectId uses the project scope. A positional budgetI\
7576
- d is a backward-compatible shortcut for --budgetIds.\n count-customer-invoices [budgetId] [same filter flags as list-customer-invoices] totalCount, lifecycle status facets (ignore --status) and amount metrics; no paging or sort flags\n get-customer-invoice <batchId> Batch as shown in the web app: status, totals, people, approvals and invoice summaries\n get-customer-invoice-invoices <batchId> Invoices with QuickBooks identity, dates, sync state, bill email (from QuickBooks) and held QuickBooks changes (qboDetailsDrift)\n get-customer-invoice-lines <invoiceId> [--limit 1-100] [--cursor <token>] One invoice\'s lines; { items, pageInfo }\n get-customer-invoice-approvals <batchId> [--limit 1-50] [--cursor <token>] Approval requests with approver/requester/responder; { items, pageInfo }\n get-customer-invoice-history <batchId> [--limit 1-100] [--cursor <token>] Status history; { items, pageInfo }\n get-customer-invoice-payments <invoiceId> P\
7577
- ayments QuickBooks applied to one invoice (date, reference, amount applied, attachment names). Live QuickBooks read.\n get-customer-invoice-email-context <batchId> Contact, required CC, budget, and project context for composing an invoice email.\n preview-qbo-customer-invoice <budgetId> <qboInvoiceId> Preview an invoice selected from list-available-qbo-customer-invoices; works on accepted/closed estimates.\n import-qbo-customer-invoice <budgetId> <qboInvoiceId> --token <previewToken> Confirm the reviewed BB-only link; requires --allow-state-change --allow-financial-write in automation.\n create-customer-invoice --payload \'<json>\' Create one invoice from an eligible budget. Include budgetId, a recommended UUID requestId, invoiceDate, details {billingAddress, customerMemo}, and exactly one split {label, percentage, dueDate}. Percentage is of the original estimate and cannot exceed the remaining coverage. Never sends.\n discard-customer-invoice <batchId> Discard a r\
7578
- eserved CREATING batch with no created QBO invoices.\n delete-customer-invoice <batchId> Delete QBO invoices and the local batch.\n void-customer-invoice <batchId> Void the invoice batch in QuickBooks.\n resubmit-customer-invoice <batchId> Original requester only. Queues one replacement after confirmed expiry voiding; retries return the same replacement. Never sends to the customer.\n approve-customer-invoice <batchId> Admin approval; rejects voided invoices, notifies the creator, and closes the estimate at cumulative 100% coverage.\n reject-customer-invoice <batchId> --reason <text> Admin rejection; voids QBO invoices and notifies the creator.\n send-customer-invoice-to-contact-person --payload \'<json>\' Queues same composer workflow as web; requires invoiceId, to, cc, replyTo, subject, HTML content, and HTML signature.\n download-customer-invoice-pdf <invoiceId> [--output <path>]\n mark-customer-invoice-sent-externally <invoiceId> --sentA\
7579
- t <ISO datetime> --recipients a@x.com,b@y.com [--note <text>] Admin only. Record an APPROVED invoice as SENT because it was emailed outside Budget Builder; sends no email.\n sync-customer-invoice <invoiceId> Refresh local status and balance from QuickBooks; paid invoices become PAID, reversals restore delivery/approval, and QBO voids can reopen an estimate. QuickBooks edits to bill-to address, memo, bill email or total are not applied: they are flagged as qboDetailsDrift and admins are emailed.\n update-customer-invoice-details <invoiceId> --billingAddress <text> --customerMemo <text> [--requestId <uuid>]\n Save bill-to address and memo in BB and queue the QuickBooks update (external write). Bill email is managed in QuickBooks.\n update-customer-invoice-qbo-drift <invoiceId> --resolution ACCEPT_QBO|KEEP_BB [--requestId <uuid>]\n Admin: resolve flagged QuickBooks changes. ACCEPT_QBO\
7580
- copies them into BB only; KEEP_BB queues BB\'s address and memo to QuickBooks.\n\nApprovals\n list-approvals | get-pending-approvals [--type budget|supplier|bill|quotation|customer_invoice|all]\n approve-bill <billId> [--overBudgetOverrideReason <text>] (also sends requester reply email)\n reject-bill <billId> --reason <text> (also sends requester reply email)\n approve-budget <budgetId> (also sends requester reply email)\n reject-budget <budgetId> --reason <text> (also sends requester reply email)\n approve-supplier <supplierId> (approve a pending request, or Admin/Lead re-approve a rejected supplier; QuickBooks vendor sync is queued)\n reject-supplier <supplierId> --reason <text> (also sends requester reply email)\n\nCompanies & projects\n list-companies [--name] [--createdBy] [--createdByIds CSV] [--active true|false] [--sortBy name|createdAt] [--sortDir asc|desc] [--limit 1-100] [--cursor] [--direction forward|backward]\n Returns { items, pageInfo }; p\
7581
- ass nextCursor with direction forward or previousCursor with direction backward. Omit --cursor to restart.\n count-companies [--name] [--createdBy] [--createdByIds CSV] [--active true|false]\n Returns independent { totalCount, counts: { active: { true, false } } }; no pagination or sorting flags.\n get-company <id>\n search-existing-companies --query <name> [--limit 1-50] [--cursor <token>] (BB + QuickBooks, read-only; follow pageInfo.nextCursor)\n use-existing-company --companyId <bbId> and/or --quickbooksId <qboId> [--name <qboName>] [--website <url>] [--confirmDistinct true]\n Supply both IDs to explicitly connect existing records with different names.\n Reuses both records, creating only the missing counterpart. A QBO-only import needs --name (from search-existing-companies);\n website is needed only for a QBO import without one. The QuickBooks link is queued (quickBooksSyncQueued, operationId).\n create-company --name --website <url> [--confirm\
7582
- Distinct true] [--billingEmails \'<json-array>\'] (QuickBooks customer queued)\n Exact existing companies are reused. Similar names require explicit separate-entity confirmation.\n update-company --payload \'<json>\' (optional billingEmails: omit to preserve, [] to clear; returns queued QBO operation ID, not completion)\n get-company-quickbooks-sync-status <companyId> (saved status only; no provider call or polling)\n delete-company <id>\n list-projects [--companyId] [--name] [--status|--statuses CSV] [--active true|false] [--wonFrom ISO] [--wonTo ISO] [--wonWithinDays N] [--limit 1-100] [--cursor] [--direction forward|backward] [--sortBy name|createdAt|status|companyName|wonAt] [--sortDir asc|desc]\n Returns { items, pageInfo }; pass nextCursor with direction forward or previousCursor with direction backward. Legacy --page/--perPage are rejected.\n --sortBy wonAt orders by when the project was marked WON (unwon projects last). Each project includes wonAt,\
7583
- wonBy { id, name } and wonAtEstimated (true for backfilled dates).\n count-projects [--companyId] [--name] [--status|--statuses CSV] [--active true|false] [--wonFrom ISO] [--wonTo ISO] [--wonWithinDays N]\n Returns independent { totalCount, counts: { status, active: { true, false } } }; no pagination or sorting flags.\n list-project-hubs [--q] [--status CSV] [--sortBy startDate|name|companyName|status] [--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-project-hubs [--q] [--status CSV] totalCount plus status facet\n List active projects that have a Project Hub integration.\n get-project <id>\n Budget overview totalRevenue includes Estimate Accepted and Estimate Closed budgets only.\n create-project --name --companyId --contactPersonId --insideSalesId --businessDevelo\
7584
- pmentId --venue --startDate <ISO> [--projectManagerId <userId>] [--asanaTaskId] [--asanaSearch <text>] [--pax] [--endDate <ISO>] [--description]\n update-project --payload \'<json>\' (project.updateProject; warns before estimate-affecting changes reject linked estimates; a companyId change (with a contactPersonId from that company) does not itself reject estimates or touch invoices, but date/pax/venue changes in the same save still do; optional projectManagerId and requestQboAccountantNotification)\n delete-project <id>\n check-project-reconciliation <id> Run the same live reconciliation review as the web app without changing status.\n reconcile-project <id> Rerun all checks transactionally and mark an eligible WON project RECONCILED.\n complete-project <id> Rerun reconciliation validation, mark a RECONCILED project COMPLETED, and queue QBO placeholder cleanup.\n import-qbo-project <projectId> --url <quickBooksProjectUrl>\n update-project-status \
7585
- <id> <status> [--projectManagerId <userId>] [--projectManagerEmail <email>]\n PITCH \u2192 WON requires an accepted/closed estimate. To win a pitch, accept its estimate with mark-budget-won <budgetId> <signed-quote.pdf>, which moves the project to WON.\n Required when moving PITCH \u2192 WON: supply --projectManagerId or --projectManagerEmail.\n The project manager must be an active @getout.sg user; list eligible users with list-users --projectTeamOnly true.\n status: ').concat(projectStatusesForHelp.join(", "), "\n\nContacts\n list-contacts <companyId>\n create-contact-person --payload '<json>' (contactPerson.createContactPerson; title MR|MRS|MS|DR)\n update-contact-person --payload '<json>' (contactPerson.updateContactPerson; must include id)\n\nSuppliers & items\n list-suppliers [--name] [--limit 1-100] [--cursor <token>] [--direction forward|backward] [--sortBy createdAt|updatedAt|name|email|phone|gstRegistered|status|active] [--sortDir asc|desc | --\
7586
- sort JSON] [--createdBy <csv>] [--gstRegistered true|false] [--status CSV] [--supplierTags <csv>] [--active true|false]\n count-suppliers [--name] [--createdBy <csv>] [--gstRegistered true|false] [--status CSV] [--supplierTags <csv>] [--active true|false] (independent totals/facets; no pagination/sort flags)\n Defaults: --active true, --limit 10, --sortBy createdAt, --sortDir desc (same as the web list); pass --active false for archived suppliers.\n create-supplier --payload '<json>' (supplier.createSupplier; archived-name recreation is Admin-only; auto-requests approval + emails when status is PENDING_APPROVAL; Lead/Admin creates queue the QuickBooks vendor: quickBooksSyncQueued, operationId)\n update-supplier --payload '<json>' (authenticated; normal-user edits require server-enforced approval; Lead/Admin edits of a linked supplier queue the QuickBooks sync)\n delete-suppliers --ids <csv> (supplier.deleteSuppliers; admin; archives/deact\
7587
- ivates supplier items)\n reactivate-suppliers --ids <csv> (supplier.reactivateSuppliers; admin; queues QuickBooks vendor reactivation, then the suppliers and their items become active: queuedSuppliers, operations)\n create-certification --name (supplier.createCertification)\n create-payment-method --name (supplier.createPaymentMethod)\n create-supplier-role --name (supplier.createSupplierRole)\n create-supplier-tag --name (supplier.createSupplierTag)\n create-item --payload '<json>' (item.createItem; saves the item and queues its QuickBooks create: quickBooksSyncQueued, operationId)\n update-item --payload '<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.delete\
7588
- Item; 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>] [--sortBy 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 [--na\
7589
- me] [--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 provider 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. --pa\
7590
- ge/--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 <token>]\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 [\
7591
- --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 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-overv\
7592
- iew [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-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-\
7593
- 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 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-en\
7594
- dpoint <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] [--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: eve\
7595
- ry 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();
7602
+ \n Newest first. Returns { items, pageInfo }; follow nextCursor.\n upload-bill-attachment <billId> <filePath...> [--file <path>] [--files <csv>] Attach invoice/supporting files as BILL attachments to any bill status, including PAID bills\n attach-bill-payment-receipt <billId> <filePath...> [--file <path>] [--files <csv>] Attach Wise/payment-proof PDFs as BILL_PAYMENT_PROOF attachments\n attach-bill-documents <billId> [--invoice <path>] [--invoices <csv>] [--paymentProof|--payment-proof|--proof <path>] [--paymentProofs|--payment-proofs|--proofs <csv>] Attach invoice and/or payment proof files with separate BB attachment types\n get-bill-review <billId> Read advisory AI review and evidence (passive)\n request-bill-review <billId> [--requestId <id>] Queue AI review; never approves or pays\n get-bill-details <billId> Bill summary as shown in the web app (status, amounts, people, payment, line totals)\n get-bill-line-items <billId> [--limit 1-100] [--cursor <token>] Line item\
7603
+ s with budget-item/quotation detail; { items, pageInfo }\n get-bill-approvals <billId> [--limit 1-50] [--cursor <token>] Approval requests with approver/requester/responder; { items, pageInfo }\n get-bill-payment <billId> Payment status, reference, date, tracking URL, QuickBooks link and external payment\n\nQuotations\n list-quotations [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--limit 1-100] [--cursor <token>] [--direction forward|backward]\n Newest first; returns { items, pageInfo }; rows carry 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.\n count-quotations [--projectId] [--budgetId] [--supplierId] [--status CSV] [--createdBy CSV] [--search] [--includeMetrics true|false] totalCount, status facets (ignore --status) and optional amount\
7604
+ metrics\n get-quotation <quotationId> Quotation as shown in the web app (status, documentOnly, amounts, people, line totals, files, approvals; pdfProcessing is PROCESSING or FAILED until queued PDF conversion/signing links the PDF; gstMismatch warns when GST differs from the expected GST)\n get-quotation-line-items <quotationId> [--limit 1-100] [--cursor <token>] Line items with budget-item detail; { items, pageInfo }\n upload-quotation-attachment <projectId> <filePath> Upload one PDF, JPEG, or PNG up to 20MB; returns attachment JSON for a quotation payload.\n cleanup-staged-quotation-attachments <projectId> --keys <csv> Queue cleanup of unattached quotation uploads; returns operation IDs.\n create-quotation --payload \'<json>\' (quotation.createDraft; requires amountWithoutGst, gstAmount, and lineAmounts [{budgetItemId, amount}] for multiple budgetItemIds; amounts before GST must sum to amountWithoutGst; result gstMismatch warns when gstAmount is not 0 or the expecte\
7605
+ d GST)\n Document-only ($0 supplier document, e.g. a contract or proposal with no price): set documentOnly: true with amountWithoutGst: 0, gstAmount: 0 and zero lineAmounts (lineAmounts may be omitted). It goes through submit/sign/approve like any quotation and shows documentOnly: true in list/get output, but it is never a valid bill quotation source (create-bill, update-bill, validate-bill-selection and link-bill-quotations are rejected by the API) and does not count as quotation coverage: a budget line covered only by it still counts as unquoted. Without documentOnly (default false), amountWithoutGst must be positive.\n Example: --payload \'{"projectId":"<id>","budgetId":"<id>","supplierId":"<id>","budgetItemIds":["<id>"],"amountWithoutGst":0,"gstAmount":0,"documentOnly":true,"attachments":[<uploaded attachment>]}\'\n update-quotation --payload \'<json>\' Update a DRAFT or REJECTED quotation; same allocation payload plus id; use lineAmounts [{budgetItemId, amount}] for eve\
7606
+ ry selected item. Result gstMismatch warns when gstAmount is not 0 or the expected GST. Update is a full replace: send documentOnly: true again when updating a document-only quotation, or it is treated as a priced quotation and needs a positive amountWithoutGst.\n delete-quotation <quotationId>\n submit-quotation <quotationId> [--overBudgetOverrideReason <text>] (signed PDF is made by a queued job: pdfProcessing; gstMismatch warns when GST is not 0 or the expected GST)\n approve-quotation <quotationId> [--overBudgetOverrideReason <text>] (assigned pending request/current Admin; concurrent revision or allocation changes conflict; final signed PDF is queued: pdfProcessing)\n reject-quotation <quotationId> --reason <text>\n download-quotation-pdf <quotationId> [original|staff|final] (refused with "still processing" until the queued PDF step links it)\n\nCustomer invoices\n check-customer-invoice-readiness <budgetId> Readiness plus the full remaining-balance amount preview and l\
7607
+ ive QuickBooks validation.\n list-eligible-customer-invoice-budgets <projectId> Accepted budgets that are ready and still have invoice coverage remaining, including estimate total, invoiced/remaining percentages, and available amount.\n preview-customer-invoice-amount <budgetId> <percentage-of-estimate> Preview amount before GST, GST, and total for a percentage of the original estimate. The percentage cannot exceed the budget\'s remaining coverage.\n list-available-qbo-customer-invoices <budgetId> List unlinked QuickBooks invoices available for this accepted or closed estimate before previewing and importing one.\n list-customer-invoices [budgetId] [--projectId <id>] [--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]\n Returns { items, pageInfo }; follow nextCursor/previousCu\
7608
+ rsor with the same filters and sort. --page/--perPage are rejected.\n No scope flag lists invoices globally. --projectId uses the project scope. A positional budgetId is a backward-compatible shortcut for --budgetIds.\n count-customer-invoices [budgetId] [same filter flags as list-customer-invoices] totalCount, lifecycle status facets (ignore --status) and amount metrics; no paging or sort flags\n get-customer-invoice <batchId> Batch as shown in the web app: status, totals, people, approvals and invoice summaries\n get-customer-invoice-invoices <batchId> Invoices with QuickBooks identity, dates, sync state, bill email (from QuickBooks) and held QuickBooks changes (qboDetailsDrift)\n get-customer-invoice-lines <invoiceId> [--limit 1-100] [--cursor <token>] One invoice\'s lines; { items, pageInfo }\n get-customer-invoice-approvals <batchId> [--limit 1-50] [--cursor <token>] Approval requests with approver/requester/responder; { items, pageInfo }\n \
7609
+ get-customer-invoice-history <batchId> [--limit 1-100] [--cursor <token>] Status history; { items, pageInfo }\n get-customer-invoice-payments <invoiceId> Payments QuickBooks applied to one invoice (date, reference, amount applied, attachment names). Live QuickBooks read.\n get-customer-invoice-email-context <batchId> Contact, required CC, budget, and project context for composing an invoice email.\n preview-qbo-customer-invoice <budgetId> <qboInvoiceId> Preview an invoice selected from list-available-qbo-customer-invoices; works on accepted/closed estimates.\n import-qbo-customer-invoice <budgetId> <qboInvoiceId> --token <previewToken> Confirm the reviewed BB-only link; requires --allow-state-change --allow-financial-write in automation.\n create-customer-invoice --payload \'<json>\' Create one invoice from an eligible budget. Include budgetId, a recommended UUID requestId, invoiceDate, details {billingAddress, customerMemo}, and exactly one split {label, percent\
7610
+ age, dueDate}. Percentage is of the original estimate and cannot exceed the remaining coverage. Never sends.\n discard-customer-invoice <batchId> Discard a reserved CREATING batch with no created QBO invoices.\n delete-customer-invoice <batchId> Delete QBO invoices and the local batch.\n void-customer-invoice <batchId> Void the invoice batch in QuickBooks.\n resubmit-customer-invoice <batchId> Original requester only. Queues one replacement after confirmed expiry voiding; retries return the same replacement. Never sends to the customer.\n approve-customer-invoice <batchId> Admin approval; rejects voided invoices, notifies the creator, and closes the estimate at cumulative 100% coverage.\n reject-customer-invoice <batchId> --reason <text> Admin rejection; voids QBO invoices and notifies the creator.\n send-customer-invoice-to-contact-person --payload \'<json>\' Queues same composer workflow as web; requires invoiceId, to, cc, replyT\
7611
+ o, subject, HTML content, and HTML signature.\n download-customer-invoice-pdf <invoiceId> [--output <path>]\n mark-customer-invoice-sent-externally <invoiceId> --sentAt <ISO datetime> --recipients a@x.com,b@y.com [--note <text>] Admin only. Record an APPROVED invoice as SENT because it was emailed outside Budget Builder; sends no email.\n sync-customer-invoice <invoiceId> Refresh local status and balance from QuickBooks; paid invoices become PAID, reversals restore delivery/approval, and QBO voids can reopen an estimate. QuickBooks edits to bill-to address, memo, bill email or total are not applied: they are flagged as qboDetailsDrift and admins are emailed.\n update-customer-invoice-details <invoiceId> --billingAddress <text> --customerMemo <text> [--requestId <uuid>]\n Save bill-to address and memo in BB and queue the QuickBooks update (external write). Bill email is managed in QuickBooks.\n update-customer-invoice-qbo-drift\
7612
+ <invoiceId> --resolution ACCEPT_QBO|KEEP_BB [--requestId <uuid>]\n Admin: resolve flagged QuickBooks changes. ACCEPT_QBO copies them into BB only; KEEP_BB queues BB\'s address and memo to QuickBooks.\n\nApprovals\n list-approvals | get-pending-approvals [--type budget|supplier|bill|quotation|customer_invoice|all] [--limit 1-100] [--cursor token] [--direction forward|backward]\n get-pending-approval <approvalId> Read one request still pending your approval.\n approve-bill <billId> [--overBudgetOverrideReason <text>] (also sends requester reply email)\n reject-bill <billId> --reason <text> (also sends requester reply email)\n approve-budget <budgetId> (also sends requester reply email)\n reject-budget <budgetId> --reason <text> (also sends requester reply email)\n approve-supplier <supplierId> (approve a pending request, or Admin/Lead re-approve a rejected supplier; QuickBooks vendor sync is queued)\n reject-supplier <supp\
7613
+ lierId> --reason <text> (also sends requester reply email)\n\nCompanies & projects\n list-companies [--name] [--createdBy] [--createdByIds CSV] [--active true|false] [--sortBy name|createdAt] [--sortDir asc|desc] [--limit 1-100] [--cursor] [--direction forward|backward]\n Returns { items, pageInfo }; pass nextCursor with direction forward or previousCursor with direction backward. Omit --cursor to restart.\n count-companies [--name] [--createdBy] [--createdByIds CSV] [--active true|false]\n Returns independent { totalCount, counts: { active: { true, false } } }; no pagination or sorting flags.\n get-company <id>\n search-existing-companies --query <name> [--limit 1-50] [--cursor <token>] (BB + QuickBooks, read-only; follow pageInfo.nextCursor)\n use-existing-company --companyId <bbId> and/or --quickbooksId <qboId> [--name <qboName>] [--website <url>] [--confirmDistinct true]\n Supply both IDs to explicitly connect existing records with different names.\n\
7614
+ Reuses both records, creating only the missing counterpart. A QBO-only import needs --name (from search-existing-companies);\n website is needed only for a QBO import without one. The QuickBooks link is queued (quickBooksSyncQueued, operationId).\n create-company --name --website <url> [--confirmDistinct true] [--billingEmails \'<json-array>\'] (QuickBooks customer queued)\n Exact existing companies are reused. Similar names require explicit separate-entity confirmation.\n update-company --payload \'<json>\' (optional billingEmails: omit to preserve, [] to clear; returns queued QBO operation ID, not completion)\n get-company-quickbooks-sync-status <companyId> (saved status only; no provider call or polling)\n delete-company <id>\n list-projects [--companyId] [--name] [--status|--statuses CSV] [--active true|false] [--wonFrom ISO] [--wonTo ISO] [--wonWithinDays N] [--limit 1-100] [--cursor] [--direction forward|backward] [--sortBy name|created\
7615
+ At|status|companyName|wonAt] [--sortDir asc|desc]\n Returns { items, pageInfo }; pass nextCursor with direction forward or previousCursor with direction backward. Legacy --page/--perPage are rejected.\n --sortBy wonAt orders by when the project was marked WON (unwon projects last). Each project includes wonAt, wonBy { id, name } and wonAtEstimated (true for backfilled dates).\n count-projects [--companyId] [--name] [--status|--statuses CSV] [--active true|false] [--wonFrom ISO] [--wonTo ISO] [--wonWithinDays N]\n Returns independent { totalCount, counts: { status, active: { true, false } } }; no pagination or sorting flags.\n list-project-hubs [--q] [--status CSV] [--sortBy startDate|name|companyName|status] [--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-project-hubs [--q] [--s\
7616
+ tatus CSV] totalCount plus status facet\n List active projects that have a Project Hub integration.\n get-project <id>\n Budget overview totalRevenue includes Estimate Accepted and Estimate Closed budgets only.\n create-project --name --companyId --contactPersonId --insideSalesId --businessDevelopmentId --venue --startDate <ISO> [--projectManagerId <userId>] [--asanaTaskId] [--asanaSearch <text>] [--pax] [--endDate <ISO>] [--description]\n update-project --payload \'<json>\' (project.updateProject; warns before estimate-affecting changes reject linked estimates; a companyId change (with a contactPersonId from that company) does not itself reject estimates or touch invoices, but date/pax/venue changes in the same save still do; optional projectManagerId and requestQboAccountantNotification)\n delete-project <id>\n check-project-reconciliation <id> Run the same live reconciliation review as the web app without changing status.\n reconcile-project <id> \
7617
+ Rerun all checks transactionally and mark an eligible WON project RECONCILED.\n complete-project <id> Rerun reconciliation validation, mark a RECONCILED project COMPLETED, and queue QBO placeholder cleanup.\n import-qbo-project <projectId> --url <quickBooksProjectUrl>\n update-project-status <id> <status> [--projectManagerId <userId>] [--projectManagerEmail <email>]\n PITCH \u2192 WON requires an accepted/closed estimate. To win a pitch, accept its estimate with mark-budget-won <budgetId> <signed-quote.pdf>, which moves the project to WON.\n Required when moving PITCH \u2192 WON: supply --projectManagerId or --projectManagerEmail.\n The project manager must be an active @getout.sg user; list eligible users with list-users --projectTeamOnly true.\n status: ').concat(projectStatusesForHelp.join(", "), "\n\nContacts\n list-contacts <companyId>\n create-contact-person --payload '<json>' (contactPerson.createContactPerson; title MR|MRS|MS|DR)\n updat\
7618
+ e-contact-person --payload '<json>' (contactPerson.updateContactPerson; must include id)\n\nSuppliers & items\n list-suppliers [--name] [--limit 1-100] [--cursor <token>] [--direction forward|backward] [--sortBy createdAt|updatedAt|name|email|phone|gstRegistered|status|active] [--sortDir asc|desc | --sort JSON] [--createdBy <csv>] [--gstRegistered true|false] [--status CSV] [--supplierTags <csv>] [--active true|false]\n count-suppliers [--name] [--createdBy <csv>] [--gstRegistered true|false] [--status CSV] [--supplierTags <csv>] [--active true|false] (independent totals/facets; no pagination/sort flags)\n Defaults: --active true, --limit 10, --sortBy createdAt, --sortDir desc (same as the web list); pass --active false for archived suppliers.\n create-supplier --payload '<json>' (supplier.createSupplier; archived-name recreation is Admin-only; auto-requests approval + emails when status is PENDING_APPROVAL; Lead/Admin creates queue the QuickBoo\
7619
+ ks vendor: quickBooksSyncQueued, operationId)\n update-supplier --payload '<json>' (authenticated; normal-user edits require server-enforced approval; Lead/Admin edits of a linked supplier queue the QuickBooks sync)\n delete-suppliers --ids <csv> (supplier.deleteSuppliers; admin; archives/deactivates supplier items)\n reactivate-suppliers --ids <csv> (supplier.reactivateSuppliers; admin; queues QuickBooks vendor reactivation, then the suppliers and their items become active: queuedSuppliers, operations)\n create-certification --name (supplier.createCertification)\n create-payment-method --name (supplier.createPaymentMethod)\n create-supplier-role --name (supplier.createSupplierRole)\n create-supplier-tag --name (supplier.createSupplierTag)\n create-item --payload '<json>' (item.createItem; saves the item and queues its QuickBooks create: quickBooksSyncQueued, operationId)\n update-item --payload '<\
7620
+ 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
+ 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
+ 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();
7596
7631
  runtime.stdout.write("".concat(help, "\n"));
7597
7632
  }
7598
7633
  __name(printLegacyHelp, "printLegacyHelp"), __name2(printLegacyHelp, "printLegacyHelp");
@@ -7643,16 +7678,16 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7643
7678
  return { apiBaseUrl, commandArgv };
7644
7679
  }, "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) => {
7645
7680
  const legacyTarget = resolvedCommand.command.legacyTarget;
7646
- if (legacyTarget === void 0) throw new CliRuntimeError("INTERNAL", "Command ".concat(resolvedCommand.command.path.join(" "), " has no dispatcher target."));
7681
+ if (legacyTarget === void 0) throw new CliRuntimeError(
7682
+ "INTERNAL",
7683
+ "Command ".concat(resolvedCommand.command.path.join(" "), " has no dispatcher target.")
7684
+ );
7647
7685
  return [argv[0] ?? "node", argv[1] ?? "bb", legacyTarget, ...resolvedCommand.argv.filter((value) => !isRuntimeOnlyArgument(value))];
7648
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) => {
7649
7687
  const positionalTarget = resolvedCommand.argv.find((value) => value !== "--" && !value.startsWith("-"));
7650
7688
  return positionalTarget !== void 0 && !positionalTarget.startsWith("{") && !positionalTarget.startsWith("[") ? positionalTarget : resolvedCommand.command.path.join(" ");
7651
7689
  }, "commandConfirmationTarget"), PAGING_FLAG_KEYS = ["limit", "cursor", "direction", "sortBy", "sortDir"], rejectCountPagingFlags = __name2((flags, commandName) => {
7652
- for (const key of PAGING_FLAG_KEYS) if (flags[key] !== void 0) throw new Error("".concat(
7653
- commandName,
7654
- " does not accept --"
7655
- ).concat(key, "; totals use filters only."));
7690
+ 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."));
7656
7691
  }, "rejectCountPagingFlags"), rejectBarePagingFlags = __name2((flags) => {
7657
7692
  for (const key of PAGING_FLAG_KEYS) rejectBareFlag(flags, key);
7658
7693
  }, "rejectBarePagingFlags"), parseCursorAndDirection = __name2((flags) => {
@@ -7667,11 +7702,11 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7667
7702
  return sortDir;
7668
7703
  }, "parseAscDescSortDir"), commandWhoami = __name2(async () => {
7669
7704
  await whoAmI();
7670
- }, "commandWhoami"), commandListBudgets = __name2(async ({ cmd, flags }) => {
7671
- const statusStr = getFlag(
7672
- flags,
7673
- "status"
7674
- ), 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) };
7705
+ }, "commandWhoami"), commandListBudgets = __name2(async ({
7706
+ cmd,
7707
+ flags
7708
+ }) => {
7709
+ 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) };
7675
7710
  if (rejectRetiredPageFlags(flags), cmd === "count-budgets") {
7676
7711
  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."));
7677
7712
  await countBudgets(filters);
@@ -7681,7 +7716,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7681
7716
  const cursor = getFlag(flags, "cursor");
7682
7717
  if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
7683
7718
  const direction = parseProjectDirection(getFlag(flags, "direction"));
7684
- if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
7719
+ if (direction === "backward" && !cursor) throw new Error(
7720
+ "--direction backward requires --cursor <token>."
7721
+ );
7685
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 });
7686
7723
  }, "commandListBudgets"), commandGetBudget = __name2(async ({ flags, positional }) => {
7687
7724
  const id = positional[0];
@@ -7693,7 +7730,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7693
7730
  await uploadBudgetAttachmentFromPath(budgetId, filePath);
7694
7731
  }, "commandUploadBudgetAttachment"), commandMarkBudgetWon = __name2(async ({ flags, positional }) => {
7695
7732
  const [budgetId, filePath] = positional;
7696
- if (!budgetId || !filePath) throw new Error("mark-budget-won requires <budgetId> <filePath>");
7733
+ if (!budgetId || !filePath) throw new Error(
7734
+ "mark-budget-won requires <budgetId> <filePath>"
7735
+ );
7697
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 });
7698
7737
  }, "commandMarkBudgetWon"), commandGetBudgetItems = __name2(async ({ flags, positional }) => {
7699
7738
  const id = positional[0];
@@ -7715,8 +7754,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7715
7754
  if (!id) throw new Error("get-budget-versions requires <budgetId>");
7716
7755
  const limit = flags.limit === void 0 ? void 0 : Number(flags.limit);
7717
7756
  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.");
7718
- if (flags.cursor === !0 || flags.cursor === "")
7719
- throw new CliRuntimeError("USAGE", "--cursor requires the nextCursor token from the previous page.");
7757
+ if (flags.cursor === !0 || flags.cursor === "") throw new CliRuntimeError("USAGE", "--cursor requires the nextCursor token from the previous page.");
7720
7758
  await getBudgetVersions(id, { limit, cursor: flags.cursor, all: flags.all === !0 || (parseOptionalBoolFlag(flags, "all") ?? !1) });
7721
7759
  }, "commandGetBudgetVersions"), commandRenameBudgetVersion = __name2(async ({ flags, positional }) => {
7722
7760
  const versionId = positional[0], newName = getFlag(flags, "name");
@@ -7729,9 +7767,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7729
7767
  }, "commandRestoreBudgetVersion"), commandUpdateBudgetStatus = __name2(async ({ flags, positional }) => {
7730
7768
  const [id, status] = positional;
7731
7769
  if (!id || !status) throw new Error("update-budget-status requires <id> <status>");
7732
- if (!isBudgetStatusUpdate(status)) throw new Error(
7733
- "Invalid status. Use one of: ".concat(budgetStatusesForHelp.join(", "))
7734
- );
7770
+ if (!isBudgetStatusUpdate(
7771
+ status
7772
+ )) throw new Error("Invalid status. Use one of: ".concat(budgetStatusesForHelp.join(", ")));
7735
7773
  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 });
7736
7774
  }, "commandUpdateBudgetStatus"), commandCreateBudgetApproval = __name2(async ({ flags, positional }) => {
7737
7775
  const id = positional[0];
@@ -7744,9 +7782,11 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7744
7782
  const companyPayloadRaw = getFlag(flags, "companyPayload"), contactPayloadRaw = getFlag(flags, "contactPayload"), eventPayloadRaw = getFlag(flags, "eventPayload");
7745
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 });
7746
7784
  }, "commandCreateEstimate"), commandSendEstimateEmail = __name2(async ({ flags }) => {
7747
- const payloadRaw = getFlag(flags, "payload");
7748
- if (!payloadRaw)
7749
- throw new Error("send-estimate-to-contact-person requires --payload '<json>'");
7785
+ const payloadRaw = getFlag(
7786
+ flags,
7787
+ "payload"
7788
+ );
7789
+ if (!payloadRaw) throw new Error("send-estimate-to-contact-person requires --payload '<json>'");
7750
7790
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
7751
7791
  await sendEstimateToContactPersonFromPayload(raw);
7752
7792
  }, "commandSendEstimateEmail"), commandCreateBudget = __name2(async ({ flags }) => {
@@ -7763,23 +7803,26 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7763
7803
  const id = positional[0];
7764
7804
  if (!id) throw new Error("delete-budget requires <budgetId>");
7765
7805
  await deleteBudgetById(id);
7766
- }, "commandDeleteBudget"), commandAddBudgetItems = __name2(async ({ flags }) => {
7767
- const budgetId = getFlag(
7768
- flags,
7769
- "budgetId"
7770
- );
7771
- if (!budgetId) throw new Error("add-budget-items requires --budgetId");
7772
- const items = parseJsonFlag(String(getFlag(flags, "items")), "--items");
7773
- await addBudgetItems({ budgetId: String(budgetId), items });
7774
- }, "commandAddBudgetItems"), commandUpdateBudgetItem = __name2(async ({ flags }) => {
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 }) => {
7775
7815
  const id = getFlag(flags, "id");
7776
7816
  if (!id) throw new Error("update-budget-item requires --id");
7777
7817
  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") });
7778
- }, "commandUpdateBudgetItem"), commandRemoveBudgetItem = __name2(async ({ positional }) => {
7779
- const id = positional[0];
7780
- if (!id) throw new Error("remove-budget-item requires <budgetItemId>");
7781
- await removeBudgetItem(id);
7782
- }, "commandRemoveBudgetItem"), commandReplaceBudgetItem = __name2(async ({ flags }) => {
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 }) => {
7783
7826
  const budgetItemId = getFlag(flags, "budgetItemId"), replacementItemId = getFlag(flags, "replacementItemId");
7784
7827
  if (!budgetItemId || !replacementItemId) throw new Error("replace-budget-item requires --budgetItemId and --replacementItemId");
7785
7828
  await replaceBudgetItem({ budgetItemId: String(budgetItemId), replacementItemId: String(replacementItemId) });
@@ -7787,25 +7830,25 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7787
7830
  const budgetItemId = getFlag(flags, "budgetItemId"), reason = getFlag(flags, "reason");
7788
7831
  if (!budgetItemId || !reason) throw new Error("approve-unavailable-item-exception requires --budgetItemId and --reason");
7789
7832
  await approveUnavailableItemException({ budgetItemId: String(budgetItemId), reason: String(reason) });
7790
- }, "commandApproveUnavailableItemException"), commandReorderBudgetItems = __name2(async ({
7791
- flags,
7792
- positional
7793
- }) => {
7794
- const budgetId = positional[0], itemIdsRaw = getFlag(flags, "itemIds");
7795
- if (!budgetId || itemIdsRaw === void 0) throw new Error("reorder-budget-items requires <budgetId> --itemIds <csv>");
7796
- const itemIds = parseCommaSeparatedIds(String(itemIdsRaw));
7797
- if (!itemIds?.length) throw new Error("reorder-budget-items requires non-empty --itemIds <csv>");
7798
- await reorderBudgetItemsCli({ budgetId, itemIds });
7799
- }, "commandReorderBudgetItems"), commandUpdateBudgetItemSupplier = __name2(async ({ flags }) => {
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 }) => {
7800
7843
  const budgetItemId = getFlag(flags, "budgetItemId"), supplierId = getFlag(flags, "supplierId");
7801
7844
  if (!budgetItemId || !supplierId) throw new Error("update-budget-item-supplier requires --budgetItemId and --supplierId");
7802
7845
  await updateBudgetItemSupplierCli({ budgetItemId: String(budgetItemId), supplierId: String(supplierId) });
7803
7846
  }, "commandUpdateBudgetItemSupplier"), commandCreateBudgetCategory = __name2(async ({ flags }) => {
7804
7847
  const name = getFlag(flags, "name");
7805
7848
  if (!name) throw new Error("create-budget-category requires --name");
7806
- await createBudgetCategory(String(
7807
- name
7808
- ));
7849
+ await createBudgetCategory(
7850
+ String(name)
7851
+ );
7809
7852
  }, "commandCreateBudgetCategory"), commandUpdateBudgetCategory = __name2(async ({ flags }) => {
7810
7853
  const id = getFlag(flags, "id"), name = getFlag(flags, "name");
7811
7854
  if (!id || !name) throw new Error("update-budget-category requires --id and --name");
@@ -7998,7 +8041,15 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
7998
8041
  await uploadBillDocumentsFromPaths({ billId, invoicePaths, paymentProofPaths });
7999
8042
  },
8000
8043
  "commandAttachBillDocuments"
8001
- ), commandGetBillDetails = __name2(async ({ positional }) => {
8044
+ ), commandGetBillReview = __name2(async ({ positional }) => {
8045
+ const id = positional[0];
8046
+ if (!id) throw new Error("bill review requires <billId>");
8047
+ await getBillReview(id);
8048
+ }, "commandGetBillReview"), commandRequestBillReview = __name2(async ({ positional, flags }) => {
8049
+ const id = positional[0];
8050
+ if (!id) throw new Error("bill request-review requires <billId>");
8051
+ rejectBareFlag(flags, "requestId"), await requestBillReview(id, getFlag(flags, "requestId"));
8052
+ }, "commandRequestBillReview"), commandGetBillDetails = __name2(async ({ positional }) => {
8002
8053
  const id = positional[0];
8003
8054
  if (!id) throw new Error("get-bill-details requires <billId>");
8004
8055
  await getBillDetails(id);
@@ -8007,14 +8058,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8007
8058
  for (const key of ["limit", "cursor", "direction"]) rejectBareFlag(flags, key);
8008
8059
  const cursor = getFlag(flags, "cursor");
8009
8060
  if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
8010
- const direction = parseProjectDirection(getFlag(flags, "direction"));
8061
+ const direction = parseProjectDirection(
8062
+ getFlag(flags, "direction")
8063
+ );
8011
8064
  if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
8012
8065
  await listQuotations({ ...parseQuotationFilterFlags(flags), limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction });
8013
8066
  }, "commandListQuotations"), commandCountQuotations = __name2(async ({ flags }) => {
8014
8067
  rejectRetiredPageFlags(flags);
8015
- for (const key of ["limit", "cursor", "direction"]) if (flags[key] !== void 0) throw new Error(
8016
- "count-quotations does not accept --".concat(key, "; totals use filters only.")
8017
- );
8068
+ for (const key of ["limit", "cursor", "direction"]) if (flags[key] !== void 0) throw new Error("count-quotations does not accept --".concat(key, "; totals use filters only."));
8018
8069
  await countQuotations({ ...parseQuotationFilterFlags(flags), includeMetrics: parseOptionalBoolFlag(flags, "includeMetrics") ?? !1 });
8019
8070
  }, "commandCountQuotations"), commandGetQuotation = __name2(async ({ positional }) => {
8020
8071
  const id = positional[0];
@@ -8027,10 +8078,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8027
8078
  const [projectId, filePath] = positional;
8028
8079
  if (!projectId || !filePath) throw new Error("upload-quotation-attachment requires <projectId> <filePath>");
8029
8080
  await uploadQuotationAttachmentFromPath(projectId, filePath);
8030
- }, "commandUploadQuotationAttachment"), commandCleanupStagedQuotationAttachments = __name2(async ({
8031
- flags,
8032
- positional
8033
- }) => {
8081
+ }, "commandUploadQuotationAttachment"), commandCleanupStagedQuotationAttachments = __name2(async ({ flags, positional }) => {
8034
8082
  const projectId = positional[0], keys = parseCommaSeparatedIds(getFlag(flags, "keys"));
8035
8083
  if (!projectId || !keys) throw new Error("cleanup-staged-quotation-attachments requires <projectId> --keys <csv>");
8036
8084
  await cleanupStagedQuotationAttachments(projectId, keys);
@@ -8038,7 +8086,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8038
8086
  const payloadRaw = getFlag(flags, "payload");
8039
8087
  if (!payloadRaw) throw new Error("create-quotation requires --payload '<json>'");
8040
8088
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
8041
- await createQuotationFromPayload(raw);
8089
+ await createQuotationFromPayload(
8090
+ raw
8091
+ );
8042
8092
  }, "commandCreateQuotation"), commandUpdateQuotation = __name2(async ({ flags }) => {
8043
8093
  const payloadRaw = getFlag(flags, "payload");
8044
8094
  if (!payloadRaw) throw new Error("update-quotation requires --payload '<json>'");
@@ -8074,14 +8124,11 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8074
8124
  const projectId = positional[0];
8075
8125
  if (!projectId) throw new Error("list-eligible-customer-invoice-budgets requires <projectId>");
8076
8126
  await listEligibleCustomerInvoiceBudgets(projectId);
8077
- }, "commandListEligibleCustomerInvoiceBudgets"), commandPreviewCustomerInvoiceAmount = __name2(
8078
- async ({ positional }) => {
8079
- const [budgetId, rawPercentage] = positional, percentage = Number(rawPercentage);
8080
- if (!budgetId || !rawPercentage || positional.length !== 2 || !Number.isFinite(percentage) || percentage <= 0 || percentage > 100 || Math.round(percentage * 100) !== percentage * 100) throw new Error("preview-customer-invoice-amount requires <budgetId> <percentage-of-estimate> between 0.01 and 100");
8081
- await previewCustomerInvoiceAmount(budgetId, percentage);
8082
- },
8083
- "commandPreviewCustomerInvoiceAmount"
8084
- ), commandListAvailableQboCustomerInvoices = __name2(async ({ positional }) => {
8127
+ }, "commandListEligibleCustomerInvoiceBudgets"), commandPreviewCustomerInvoiceAmount = __name2(async ({ positional }) => {
8128
+ const [budgetId, rawPercentage] = positional, percentage = Number(rawPercentage);
8129
+ if (!budgetId || !rawPercentage || positional.length !== 2 || !Number.isFinite(percentage) || percentage <= 0 || percentage > 100 || Math.round(percentage * 100) !== percentage * 100) throw new Error("preview-customer-invoice-amount requires <budgetId> <percentage-of-estimate> between 0.01 and 100");
8130
+ await previewCustomerInvoiceAmount(budgetId, percentage);
8131
+ }, "commandPreviewCustomerInvoiceAmount"), commandListAvailableQboCustomerInvoices = __name2(async ({ positional }) => {
8085
8132
  const budgetId = positional[0];
8086
8133
  if (!budgetId || positional.length !== 1) throw new Error("list-available-qbo-customer-invoices requires <budgetId>");
8087
8134
  await listAvailableQboCustomerInvoices(budgetId);
@@ -8089,7 +8136,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8089
8136
  const projectId = getFlag(flags, "projectId"), projectIds = parseCommaSeparatedIds(getFlag(flags, "projectIds"));
8090
8137
  if (projectId && projectIds) throw new Error("Use either --projectId for project scope or --projectIds for a global filter, not both.");
8091
8138
  const budgetIds = [...positionalBudgetId ? [positionalBudgetId] : [], ...parseCommaSeparatedIds(getFlag(flags, "budgetIds")) ?? []], statusRaw = getFlag(flags, "status");
8092
- 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")) };
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
+ ) };
8093
8142
  }, "customerInvoiceFiltersFromFlags"), commandListCustomerInvoices = __name2(async ({ cmd, flags, positional }) => {
8094
8143
  const filters = customerInvoiceFiltersFromFlags(flags, positional[0]);
8095
8144
  if (rejectRetiredPageFlags(flags), cmd === "count-customer-invoices") {
@@ -8097,16 +8146,15 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8097
8146
  return;
8098
8147
  }
8099
8148
  rejectBarePagingFlags(flags);
8100
- const {
8101
- cursor,
8102
- direction
8103
- } = parseCursorAndDirection(flags), sortDir = parseOptionalBillListSortDir(getFlag(flags, "sortDir"));
8149
+ const { cursor, direction } = parseCursorAndDirection(flags), sortDir = parseOptionalBillListSortDir(getFlag(flags, "sortDir"));
8104
8150
  await listCustomerInvoices({ ...filters, limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sortBy: parseCustomerInvoiceSortBy(getFlag(flags, "sortBy")), sortDir: sortDir ?? "desc" });
8105
8151
  }, "commandListCustomerInvoices"), commandGetCustomerInvoice = __name2(async ({ positional }) => {
8106
8152
  const batchId = positional[0];
8107
8153
  if (!batchId) throw new Error("get-customer-invoice requires <batchId>");
8108
8154
  await getCustomerInvoice(batchId);
8109
- }, "commandGetCustomerInvoice"), commandGetCustomerInvoiceInvoices = __name2(async ({ positional }) => {
8155
+ }, "commandGetCustomerInvoice"), commandGetCustomerInvoiceInvoices = __name2(async ({
8156
+ positional
8157
+ }) => {
8110
8158
  const batchId = positional[0];
8111
8159
  if (!batchId) throw new Error("get-customer-invoice-invoices requires <batchId>");
8112
8160
  await getCustomerInvoiceInvoices(batchId);
@@ -8131,11 +8179,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8131
8179
  const [budgetId, qboInvoiceId] = positional;
8132
8180
  if (!budgetId?.trim() || !qboInvoiceId || positional.length !== 2) throw new Error("".concat(cmd, " requires <budgetId> <qboInvoiceId>"));
8133
8181
  if (!new __cliRegExp("^\\d+$", "").test(qboInvoiceId)) throw new Error("qboInvoiceId must be the numeric QuickBooks transaction ID, not the invoice number");
8134
- if (cmd === "preview-qbo-customer-invoice") await previewQboCustomerInvoice({ budgetId, qboInvoiceId });
8182
+ const confirmEstimateLineage = flags.confirmEstimateLineage === !0 ? !0 : parseOptionalBoolFlag(flags, "confirmEstimateLineage");
8183
+ if (cmd === "preview-qbo-customer-invoice") await previewQboCustomerInvoice(
8184
+ { budgetId, qboInvoiceId, confirmEstimateLineage }
8185
+ );
8135
8186
  else {
8136
8187
  const token = getFlag(flags, "token");
8137
8188
  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");
8138
- await importQboCustomerInvoice({ budgetId, qboInvoiceId, token });
8189
+ await importQboCustomerInvoice({ budgetId, qboInvoiceId, token, confirmEstimateLineage });
8139
8190
  }
8140
8191
  }, "commandPreviewQboCustomerInvoice"), commandCreateCustomerInvoice = __name2(async ({ flags }) => {
8141
8192
  const payloadRaw = getFlag(flags, "payload");
@@ -8163,33 +8214,29 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8163
8214
  await approveCustomerInvoice(batchId);
8164
8215
  }, "commandApproveCustomerInvoice"), commandRejectCustomerInvoice = __name2(async ({ flags, positional }) => {
8165
8216
  const batchId = positional[0], reason = getFlag(flags, "reason");
8166
- if (!batchId || reason === void 0) throw new Error("reject-customer-invoice requires <batchId> --reason <text>");
8217
+ if (!batchId || reason === void 0) throw new Error(
8218
+ "reject-customer-invoice requires <batchId> --reason <text>"
8219
+ );
8167
8220
  await rejectCustomerInvoice(batchId, String(reason));
8168
8221
  }, "commandRejectCustomerInvoice"), commandSendCustomerInvoiceToContactPerson = __name2(async ({ flags }) => {
8169
8222
  const payloadRaw = getFlag(flags, "payload");
8170
8223
  if (!payloadRaw) throw new Error("send-customer-invoice-to-contact-person requires --payload '<json>'");
8171
8224
  await sendCustomerInvoiceToContactPersonFromPayload(parseJsonFlag(String(payloadRaw), "--payload"));
8172
- }, "commandSendCustomerInvoiceToContactPerson"), commandDownloadCustomerInvoicePdf = __name2(
8173
- async ({ flags, positional }) => {
8174
- const invoiceId = positional[0];
8175
- if (!invoiceId) throw new Error("download-customer-invoice-pdf requires <invoiceId> [--output <path>]");
8176
- await downloadCustomerInvoicePdf(invoiceId, getFlag(flags, "output"));
8177
- },
8178
- "commandDownloadCustomerInvoicePdf"
8179
- ), commandUpdateCustomerInvoiceDetails = __name2(async ({ flags, positional }) => {
8225
+ }, "commandSendCustomerInvoiceToContactPerson"), commandDownloadCustomerInvoicePdf = __name2(async ({ flags, positional }) => {
8226
+ const invoiceId = positional[0];
8227
+ if (!invoiceId) throw new Error("download-customer-invoice-pdf requires <invoiceId> [--output <path>]");
8228
+ await downloadCustomerInvoicePdf(invoiceId, getFlag(flags, "output"));
8229
+ }, "commandDownloadCustomerInvoicePdf"), commandUpdateCustomerInvoiceDetails = __name2(async ({ flags, positional }) => {
8180
8230
  const invoiceId = positional[0], billingAddress = getFlag(flags, "billingAddress"), customerMemo = getFlag(flags, "customerMemo");
8181
8231
  if (!invoiceId || typeof billingAddress != "string" || typeof customerMemo != "string") throw new Error("update-customer-invoice-details requires <invoiceId> --billingAddress <text> --customerMemo <text> (send both; use \\n for address lines). The bill email is managed in QuickBooks.");
8182
8232
  const requestId = getFlag(flags, "requestId");
8183
8233
  await updateCustomerInvoiceDetails({ billingAddress: billingAddress.replaceAll("\\n", "\n"), customerMemo, invoiceId, ...typeof requestId == "string" ? { requestId } : {} });
8184
- }, "commandUpdateCustomerInvoiceDetails"), commandUpdateCustomerInvoiceQboDrift = __name2(
8185
- async ({ flags, positional }) => {
8186
- const invoiceId = positional[0], resolution = getFlag(flags, "resolution");
8187
- if (!invoiceId || resolution !== "ACCEPT_QBO" && resolution !== "KEEP_BB") throw new Error("update-customer-invoice-qbo-drift requires <invoiceId> --resolution ACCEPT_QBO|KEEP_BB");
8188
- const requestId = getFlag(flags, "requestId");
8189
- await updateCustomerInvoiceQboDrift({ invoiceId, resolution, ...typeof requestId == "string" ? { requestId } : {} });
8190
- },
8191
- "commandUpdateCustomerInvoiceQboDrift"
8192
- ), commandMarkCustomerInvoiceSentExternally = __name2(async ({ flags, positional }) => {
8234
+ }, "commandUpdateCustomerInvoiceDetails"), commandUpdateCustomerInvoiceQboDrift = __name2(async ({ flags, positional }) => {
8235
+ const invoiceId = positional[0], resolution = getFlag(flags, "resolution");
8236
+ if (!invoiceId || resolution !== "ACCEPT_QBO" && resolution !== "KEEP_BB") throw new Error("update-customer-invoice-qbo-drift requires <invoiceId> --resolution ACCEPT_QBO|KEEP_BB");
8237
+ const requestId = getFlag(flags, "requestId");
8238
+ await updateCustomerInvoiceQboDrift({ invoiceId, resolution, ...typeof requestId == "string" ? { requestId } : {} });
8239
+ }, "commandUpdateCustomerInvoiceQboDrift"), commandMarkCustomerInvoiceSentExternally = __name2(async ({ flags, positional }) => {
8193
8240
  const invoiceId = positional[0], sentAt = getFlag(flags, "sentAt"), recipients = getFlag(flags, "recipients");
8194
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>]");
8195
8242
  await markCustomerInvoiceSentExternally({ invoiceId, sentAt, recipients: recipients.split(",").map((recipient) => recipient.trim()).filter(Boolean), note: getFlag(flags, "note") });
@@ -8198,8 +8245,10 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8198
8245
  if (!invoiceId) throw new Error("sync-customer-invoice requires <invoiceId>");
8199
8246
  await syncCustomerInvoice(invoiceId);
8200
8247
  }, "commandSyncCustomerInvoice"), commandListApprovals = __name2(async ({ flags }) => {
8201
- const typeRaw = getFlag(flags, "type");
8202
- await listApprovals({ type: parseApprovalTypeFlag(typeRaw !== void 0 ? String(typeRaw) : void 0) });
8248
+ rejectBarePagingFlags(flags);
8249
+ for (const key of ["page", "perPage"]) if (flags[key] !== void 0) throw new Error("approval list does not accept --".concat(key, "; use --limit and --cursor."));
8250
+ const { cursor, direction } = parseCursorAndDirection(flags), typeRaw = getFlag(flags, "type");
8251
+ await listApprovals({ limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, type: parseApprovalTypeFlag(typeRaw !== void 0 ? String(typeRaw) : void 0) });
8203
8252
  }, "commandListApprovals"), commandApproveBill = __name2(async ({ flags, positional }) => {
8204
8253
  const id = positional[0];
8205
8254
  if (!id) throw new Error("approve-bill requires <billId>");
@@ -8210,10 +8259,12 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8210
8259
  await rejectBill(id, reason);
8211
8260
  }, "commandRejectBill"), commandApproveBudget = __name2(async ({ positional }) => {
8212
8261
  const id = positional[0];
8213
- if (!id)
8214
- throw new Error("approve-budget requires <budgetId>");
8262
+ if (!id) throw new Error("approve-budget requires <budgetId>");
8215
8263
  await approveBudget(id);
8216
- }, "commandApproveBudget"), commandRejectBudget = __name2(async ({ flags, positional }) => {
8264
+ }, "commandApproveBudget"), commandRejectBudget = __name2(async ({
8265
+ flags,
8266
+ positional
8267
+ }) => {
8217
8268
  const id = positional[0], reason = getFlag(flags, "reason");
8218
8269
  if (!id || reason === void 0) throw new Error("reject-budget requires <budgetId> --reason <text>");
8219
8270
  await rejectBudget(id, reason);
@@ -8248,12 +8299,13 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8248
8299
  }, "commandCountCompanies"), commandGetCompany = __name2(async ({ positional }) => {
8249
8300
  const id = positional[0];
8250
8301
  if (!id) throw new Error("get-company requires <id>");
8251
- await getCompany(
8252
- id
8253
- );
8302
+ await getCompany(id);
8254
8303
  }, "commandGetCompany"), commandCreateCompany = __name2(async ({ flags }) => {
8255
8304
  rejectBareFlag(flags, "billingEmails");
8256
- const billingEmailsRaw = getFlag(flags, "billingEmails"), billingEmails = billingEmailsRaw === void 0 ? void 0 : parseCompanyBillingEmails(parseJsonFlag(billingEmailsRaw, "--billingEmails")), name = getFlag(flags, "name"), website = getFlag(flags, "website");
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");
8257
8309
  if (!name || !website) throw new Error("create-company requires --name and --website <url>");
8258
8310
  await createCompany({ name, website, ...billingEmails === void 0 ? {} : { billingEmails }, confirmDistinct: parseOptionalBoolFlag(flags, "confirmDistinct") });
8259
8311
  }, "commandCreateCompany"), commandSearchExistingCompanies = __name2(async ({ flags }) => {
@@ -8274,7 +8326,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8274
8326
  const payloadRaw = getFlag(flags, "payload");
8275
8327
  if (!payloadRaw) throw new Error("update-company requires --payload '<json>'");
8276
8328
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
8277
- await updateCompanyFromPayload(raw);
8329
+ await updateCompanyFromPayload(
8330
+ raw
8331
+ );
8278
8332
  }, "commandUpdateCompany"), commandGetCompanyQuickbooksSyncStatus = __name2(async ({ positional }) => {
8279
8333
  const id = positional[0];
8280
8334
  if (!id) throw new Error("get-company-quickbooks-sync-status requires <companyId>");
@@ -8289,9 +8343,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8289
8343
  await countProjects(parseProjectCountFlags(flags));
8290
8344
  }, "commandCountProjects"), commandListProjectHubs = __name2(async ({ cmd, flags }) => {
8291
8345
  rejectRetiredPageFlags(flags);
8292
- const filters = { q: getFlag(flags, "q"), statuses: parseCommaSeparatedProjectStatuses(
8293
- getFlag(flags, "status")
8294
- ) };
8346
+ const filters = { q: getFlag(flags, "q"), statuses: parseCommaSeparatedProjectStatuses(getFlag(flags, "status")) };
8295
8347
  if (cmd === "count-project-hubs") {
8296
8348
  for (const key of ["limit", "cursor", "direction", "sortBy", "sortDir"]) if (flags[key] !== void 0) throw new Error("count-project-hubs does not accept --".concat(key, "; totals use filters only."));
8297
8349
  await countProjectHubs(filters);
@@ -8307,11 +8359,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8307
8359
  const id = positional[0];
8308
8360
  if (!id) throw new Error("get-project requires <id>");
8309
8361
  await getProject(id);
8310
- }, "commandGetProject"), commandGetProjectHubStatus = __name2(async ({ positional }) => {
8311
- const projectId = positional[0];
8312
- if (!projectId) throw new Error("get-project-hub-status requires <projectId>");
8313
- await getProjectHubStatus(projectId);
8314
- }, "commandGetProjectHubStatus"), commandSetupProjectHub = __name2(async ({ positional }) => {
8362
+ }, "commandGetProject"), commandGetProjectHubStatus = __name2(
8363
+ async ({ positional }) => {
8364
+ const projectId = positional[0];
8365
+ if (!projectId) throw new Error("get-project-hub-status requires <projectId>");
8366
+ await getProjectHubStatus(projectId);
8367
+ },
8368
+ "commandGetProjectHubStatus"
8369
+ ), commandSetupProjectHub = __name2(async ({ positional }) => {
8315
8370
  const projectId = positional[0];
8316
8371
  if (!projectId) throw new Error("setup-project-hub requires <projectId>");
8317
8372
  await setupProjectHub(projectId);
@@ -8319,26 +8374,18 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8319
8374
  const projectId = positional[0];
8320
8375
  if (!projectId) throw new Error("sync-project-hub-commercial-documents requires <projectId>");
8321
8376
  await syncProjectHubCommercialDocuments(projectId);
8322
- }, "commandSyncProjectHubCommercialDocuments"), commandCreateProject = __name2(async ({ flags }) => {
8323
- 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");
8324
- 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.");
8325
- 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");
8326
- await createProject({
8327
- name,
8328
- companyId,
8329
- contactPersonId,
8330
- insideSalesId,
8331
- businessDevelopmentId,
8332
- projectManagerId,
8333
- venue,
8334
- pax,
8335
- asanaTaskId,
8336
- asanaSearch,
8337
- startDate,
8338
- endDate: getFlag(flags, "endDate"),
8339
- description: getFlag(flags, "description")
8340
- });
8341
- }, "commandCreateProject"), commandUpdateProject = __name2(async ({ flags }) => {
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 }) => {
8342
8389
  const payloadRaw = getFlag(flags, "payload");
8343
8390
  if (!payloadRaw) throw new Error("update-project requires --payload '<json>'");
8344
8391
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
@@ -8354,26 +8401,23 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8354
8401
  }, "commandCheckProjectReconciliation"), commandReconcileProject = __name2(async ({ positional }) => {
8355
8402
  const id = positional[0];
8356
8403
  if (!id) throw new Error("reconcile-project requires <id>");
8357
- await reconcileProject(
8358
- id
8359
- );
8404
+ await reconcileProject(id);
8360
8405
  }, "commandReconcileProject"), commandCompleteProject = __name2(async ({ positional }) => {
8361
8406
  const id = positional[0];
8362
- if (!id) throw new Error("complete-project requires <id>");
8407
+ if (!id) throw new Error(
8408
+ "complete-project requires <id>"
8409
+ );
8363
8410
  await completeProject(id);
8364
8411
  }, "commandCompleteProject"), commandImportQboProject = __name2(async ({ flags, positional }) => {
8365
8412
  const projectId = positional[0], projectUrl = getFlag(flags, "url");
8366
8413
  if (!projectId || projectUrl === void 0) throw new Error("import-qbo-project requires <projectId> --url <quickBooksProjectUrl>");
8367
8414
  await importQuickBooksProjectId(projectId, String(projectUrl));
8368
- }, "commandImportQboProject"), commandUpdateProjectStatus = __name2(
8369
- async ({ flags, positional }) => {
8370
- const [id, statusRaw] = positional;
8371
- if (!id || !statusRaw) throw new Error("update-project-status requires <id> <status>");
8372
- const pmIdFlag = getFlag(flags, "projectManagerId"), pmEmailFlag = getFlag(flags, "projectManagerEmail");
8373
- await updateProjectStatus(id, parseProjectStatusForUpdate(statusRaw), { ...pmIdFlag && { projectManagerId: String(pmIdFlag) }, ...pmEmailFlag && { projectManagerEmail: String(pmEmailFlag) } });
8374
- },
8375
- "commandUpdateProjectStatus"
8376
- ), commandListContacts = __name2(async ({ positional }) => {
8415
+ }, "commandImportQboProject"), commandUpdateProjectStatus = __name2(async ({ flags, positional }) => {
8416
+ const [id, statusRaw] = positional;
8417
+ if (!id || !statusRaw) throw new Error("update-project-status requires <id> <status>");
8418
+ const pmIdFlag = getFlag(flags, "projectManagerId"), pmEmailFlag = getFlag(flags, "projectManagerEmail");
8419
+ await updateProjectStatus(id, parseProjectStatusForUpdate(statusRaw), { ...pmIdFlag && { projectManagerId: String(pmIdFlag) }, ...pmEmailFlag && { projectManagerEmail: String(pmEmailFlag) } });
8420
+ }, "commandUpdateProjectStatus"), commandListContacts = __name2(async ({ positional }) => {
8377
8421
  const id = positional[0];
8378
8422
  if (!id) throw new Error("list-contacts requires <companyId>");
8379
8423
  await listContacts(id);
@@ -8390,11 +8434,12 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8390
8434
  }, "commandUpdateContactPerson"), commandCountSuppliers = __name2(async ({ flags }) => {
8391
8435
  await countSuppliers(parseCountSuppliersFlags(flags));
8392
8436
  }, "commandCountSuppliers"), commandListSuppliers = __name2(async ({ flags }) => {
8393
- await listSuppliers(
8394
- parseListSuppliersFlags(flags)
8395
- );
8437
+ await listSuppliers(parseListSuppliersFlags(flags));
8396
8438
  }, "commandListSuppliers"), commandCreateSupplier = __name2(async ({ flags }) => {
8397
- const payloadRaw = getFlag(flags, "payload");
8439
+ const payloadRaw = getFlag(
8440
+ flags,
8441
+ "payload"
8442
+ );
8398
8443
  if (!payloadRaw) throw new Error("create-supplier requires --payload '<json>'");
8399
8444
  const raw = parseJsonFlag(String(payloadRaw), "--payload");
8400
8445
  await createSupplierFromPayload(raw);
@@ -8409,16 +8454,13 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8409
8454
  const ids = parseCommaSeparatedIds(String(idsRaw));
8410
8455
  if (!ids?.length) throw new Error("delete-suppliers requires non-empty --ids");
8411
8456
  await deleteSuppliersByIds(ids);
8412
- }, "commandDeleteSuppliers"), commandReactivateSuppliers = __name2(
8413
- async ({ flags }) => {
8414
- const idsRaw = getFlag(flags, "ids");
8415
- if (idsRaw === void 0) throw new Error("reactivate-suppliers requires --ids <csv>");
8416
- const ids = parseCommaSeparatedIds(String(idsRaw));
8417
- if (!ids?.length) throw new Error("reactivate-suppliers requires non-empty --ids");
8418
- await reactivateSuppliersByIds(ids);
8419
- },
8420
- "commandReactivateSuppliers"
8421
- ), commandCreateCertification = __name2(async ({ flags }) => {
8457
+ }, "commandDeleteSuppliers"), commandReactivateSuppliers = __name2(async ({ flags }) => {
8458
+ const idsRaw = getFlag(flags, "ids");
8459
+ if (idsRaw === void 0) throw new Error("reactivate-suppliers requires --ids <csv>");
8460
+ const ids = parseCommaSeparatedIds(String(idsRaw));
8461
+ if (!ids?.length) throw new Error("reactivate-suppliers requires non-empty --ids");
8462
+ await reactivateSuppliersByIds(ids);
8463
+ }, "commandReactivateSuppliers"), commandCreateCertification = __name2(async ({ flags }) => {
8422
8464
  const name = getFlag(flags, "name");
8423
8465
  if (!name) throw new Error("create-certification requires --name");
8424
8466
  await createSupplierCertification(String(name));
@@ -8441,10 +8483,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8441
8483
  const timeFrame = parseOptionalSupplierAnalyticsTimeFrame(tfRaw !== void 0 ? String(tfRaw) : void 0), startDate = getFlag(flags, "startDate"), endDate = getFlag(flags, "endDate");
8442
8484
  if ((startDate || endDate) && timeFrame !== "CUSTOM") throw new Error("--startDate/--endDate need --timeFrame CUSTOM; other time frames ignore them.");
8443
8485
  const status = getFlag(flags, "status")?.split(",").map((value) => value.trim()).filter(Boolean), badStatus = status?.find((value) => !Object.values(ApprovalStatus2).some((s) => s === value));
8444
- if (badStatus) throw new Error("Invalid --status ".concat(
8445
- badStatus,
8446
- ". Use a comma list of: "
8447
- ).concat(Object.values(ApprovalStatus2).join(", "), "."));
8486
+ if (badStatus) throw new Error("Invalid --status ".concat(badStatus, ". Use a comma list of: ").concat(Object.values(ApprovalStatus2).join(", "), "."));
8448
8487
  const gstRaw = getFlag(flags, "gstRegistered");
8449
8488
  if (gstRaw !== void 0 && gstRaw !== "true" && gstRaw !== "false") throw new Error("--gstRegistered must be true or false.");
8450
8489
  return { name: getFlag(flags, "name"), timeFrame, status: status?.length ? status : void 0, gstRegistered: gstRaw === void 0 ? void 0 : gstRaw === "true", createdBy: getFlag(flags, "createdBy"), startDate, endDate };
@@ -8456,10 +8495,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8456
8495
  }
8457
8496
  rejectBarePagingFlags(flags);
8458
8497
  const { cursor, direction } = parseCursorAndDirection(flags), sortBy = getFlag(flags, "sortBy");
8459
- if (sortBy !== void 0 && !SUPPLIER_ANALYTICS_SORT_IDS.some((id) => id === sortBy)) throw new Error("--sortBy must be one of: ".concat(
8460
- SUPPLIER_ANALYTICS_SORT_IDS.join(", "),
8461
- "."
8462
- ));
8498
+ if (sortBy !== void 0 && !SUPPLIER_ANALYTICS_SORT_IDS.some((id) => id === sortBy)) throw new Error("--sortBy must be one of: ".concat(SUPPLIER_ANALYTICS_SORT_IDS.join(", "), "."));
8463
8499
  await getSupplierAnalytics({ ...filters, limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sortBy: SUPPLIER_ANALYTICS_SORT_IDS.find((id) => id === sortBy), sortDir: parseOptionalBillListSortDir(getFlag(flags, "sortDir")) });
8464
8500
  }, "commandGetSupplierAnalytics"), commandListItems = __name2(async ({ cmd, flags }) => {
8465
8501
  rejectRetiredPageFlags(flags);
@@ -8472,9 +8508,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8472
8508
  const { cursor, direction } = parseCursorAndDirection(flags), sortBy = getFlag(flags, "sortBy"), sortId = INVENTORY_SORT_IDS.find((id) => id === sortBy);
8473
8509
  if (sortBy !== void 0 && !sortId) throw new Error('Invalid --sortBy "'.concat(sortBy, '". Use one of: ').concat(INVENTORY_SORT_IDS.join(", "), "."));
8474
8510
  const sortDir = parseAscDescSortDir(flags);
8475
- await listItems(
8476
- { ...filters, limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sort: sortId ? [{ id: sortId, desc: sortDir !== "asc" }] : void 0 }
8477
- );
8511
+ await listItems({ ...filters, limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sort: sortId ? [{ id: sortId, desc: sortDir !== "asc" }] : void 0 });
8478
8512
  }, "commandListItems"), commandGetItem = __name2(async ({ positional }) => {
8479
8513
  const id = positional[0];
8480
8514
  if (!id) throw new Error("get-item requires <id>");
@@ -8491,9 +8525,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8491
8525
  }, "commandCreateItem"), commandUpdateItem = __name2(async ({ flags }) => {
8492
8526
  const payloadRaw = getFlag(flags, "payload");
8493
8527
  if (!payloadRaw) throw new Error("update-item requires --payload '<json>'");
8494
- const raw = parseJsonFlag(String(
8495
- payloadRaw
8496
- ), "--payload");
8528
+ const raw = parseJsonFlag(String(payloadRaw), "--payload");
8497
8529
  await updateItemFromPayload(raw);
8498
8530
  }, "commandUpdateItem"), commandDeleteItem = __name2(async ({ positional }) => {
8499
8531
  const id = positional[0];
@@ -8515,7 +8547,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8515
8547
  rejectBarePagingFlags(flags);
8516
8548
  const { cursor, direction } = parseCursorAndDirection(flags), sortByRaw = getFlag(flags, "sortBy"), sortBy = ITEM_CATEGORY_SORT_IDS.find((id) => id === sortByRaw);
8517
8549
  if (sortByRaw !== void 0 && !sortBy) throw new Error('Invalid --sortBy "'.concat(sortByRaw, '". Use one of: ').concat(ITEM_CATEGORY_SORT_IDS.join(", "), "."));
8518
- const sortDir = parseAscDescSortDir(flags);
8550
+ const sortDir = parseAscDescSortDir(
8551
+ flags
8552
+ );
8519
8553
  await listItemCategories({ ...filters, limit: parseProjectLimit(getFlag(flags, "limit")), cursor, direction, sortBy, sortDir });
8520
8554
  }, "commandListItemCategories"), commandCreateItemCategory = __name2(async ({ flags }) => {
8521
8555
  const name = getFlag(flags, "name");
@@ -8528,9 +8562,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8528
8562
  }, "commandUpdateItemCategory"), commandDeleteItemCategories = __name2(async ({ flags }) => {
8529
8563
  const idsRaw = getFlag(flags, "ids");
8530
8564
  if (idsRaw === void 0) throw new Error("delete-item-categories requires --ids <csv>");
8531
- const ids = parseCommaSeparatedIds(
8532
- String(idsRaw)
8533
- );
8565
+ const ids = parseCommaSeparatedIds(String(idsRaw));
8534
8566
  if (!ids?.length) throw new Error("delete-item-categories requires non-empty --ids");
8535
8567
  await deleteItemCategoriesByIds(ids);
8536
8568
  }, "commandDeleteItemCategories"), commandListUsers = __name2(async ({ cmd, flags }) => {
@@ -8547,9 +8579,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8547
8579
  if (flags.direction !== void 0) throw new Error("list-users pages forward only; follow pageInfo.nextCursor with --cursor.");
8548
8580
  const cursor = getFlag(flags, "cursor");
8549
8581
  if (cursor === "" || (cursor?.length ?? 0) > 8192) throw new Error("--cursor must be a non-empty opaque token of at most 8192 characters.");
8550
- await listUsers({ q, projectTeamOnly, limit: parseProjectLimit(
8551
- getFlag(flags, "limit")
8552
- ), cursor });
8582
+ await listUsers({ q, projectTeamOnly, limit: parseProjectLimit(getFlag(flags, "limit")), cursor });
8553
8583
  }, "commandListUsers"), commandCreateUser = __name2(async ({ flags }) => {
8554
8584
  const email2 = getFlag(flags, "email");
8555
8585
  if (!email2) throw new Error("create-user requires --email <email> [--name <name>] [--role ".concat(userRolesForHelp.join("|"), "]"));
@@ -8600,12 +8630,12 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8600
8630
  await getError(id);
8601
8631
  }, "commandGetError"), commandGetErrorMetrics = __name2(async () => {
8602
8632
  await getErrorMetrics();
8603
- }, "commandGetErrorMetrics"), commandListIntegrationOperations = __name2(async ({
8604
- cmd,
8605
- flags
8606
- }) => {
8633
+ }, "commandGetErrorMetrics"), commandListIntegrationOperations = __name2(async ({ cmd, flags }) => {
8607
8634
  rejectRetiredPageFlags(flags);
8608
- const filters = { destination: parseCommaSeparatedIds(getFlag(flags, "destination")), search: getFlag(flags, "search"), status: parseCommaSeparatedIntegrationOperationStatuses(getFlag(flags, "status")) };
8635
+ const filters = { destination: parseCommaSeparatedIds(getFlag(flags, "destination")), search: getFlag(
8636
+ flags,
8637
+ "search"
8638
+ ), status: parseCommaSeparatedIntegrationOperationStatuses(getFlag(flags, "status")) };
8609
8639
  if (cmd === "count-integration-operations") {
8610
8640
  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."));
8611
8641
  await countIntegrationOperations(filters);
@@ -8618,11 +8648,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8618
8648
  if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
8619
8649
  const limitRaw = getFlag(flags, "limit");
8620
8650
  await listIntegrationOperations({ ...filters, limit: limitRaw === void 0 ? 25 : parseProjectLimit(limitRaw), cursor, direction });
8621
- }, "commandListIntegrationOperations"), commandGetIntegrationOperation = __name2(async ({ positional }) => {
8622
- const operationId = positional[0];
8623
- if (!operationId) throw new Error("get-integration-operation requires <operationId>");
8624
- await getIntegrationOperation(operationId);
8625
- }, "commandGetIntegrationOperation"), commandRetryIntegrationOperation = __name2(async ({ flags, positional }) => {
8651
+ }, "commandListIntegrationOperations"), commandGetIntegrationOperation = __name2(
8652
+ async ({ positional }) => {
8653
+ const operationId = positional[0];
8654
+ if (!operationId) throw new Error("get-integration-operation requires <operationId>");
8655
+ await getIntegrationOperation(operationId);
8656
+ },
8657
+ "commandGetIntegrationOperation"
8658
+ ), commandRetryIntegrationOperation = __name2(async ({ flags, positional }) => {
8626
8659
  const operationId = positional[0];
8627
8660
  if (!operationId) throw new Error("retry-integration-operation requires <operationId>");
8628
8661
  const outboundEmailResolution = getFlag(flags, "outboundEmailResolution");
@@ -8630,9 +8663,12 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8630
8663
  await retryIntegrationOperation(operationId, parseOptionalBoolFlag(flags, "confirmExternalStateReconciled") ?? !1, outboundEmailResolution, getFlag(flags, "providerMessageId"));
8631
8664
  }, "commandRetryIntegrationOperation"), commandListWebhookEventTypes = __name2(async () => {
8632
8665
  await listWebhookEventTypes();
8633
- }, "commandListWebhookEventTypes"), commandListWebhookEndpoints = __name2(async () => {
8634
- await listWebhookEndpoints();
8635
- }, "commandListWebhookEndpoints"), commandGetWebhookEndpoint = __name2(async ({ positional }) => {
8666
+ }, "commandListWebhookEventTypes"), commandListWebhookEndpoints = __name2(
8667
+ async () => {
8668
+ await listWebhookEndpoints();
8669
+ },
8670
+ "commandListWebhookEndpoints"
8671
+ ), commandGetWebhookEndpoint = __name2(async ({ positional }) => {
8636
8672
  const id = positional[0];
8637
8673
  if (!id) throw new Error("get-webhook-endpoint requires <id>");
8638
8674
  await getWebhookEndpoint(id);
@@ -8643,9 +8679,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8643
8679
  }, "commandCreateWebhookEndpoint"), commandUpdateWebhookEndpoint = __name2(async ({ flags, positional }) => {
8644
8680
  const id = positional[0];
8645
8681
  if (!id) throw new Error("update-webhook-endpoint requires <id>");
8646
- const events = parseCommaSeparatedIds(
8647
- getFlag(flags, "events")
8648
- );
8682
+ const events = parseCommaSeparatedIds(getFlag(flags, "events"));
8649
8683
  await updateWebhookEndpoint({ id, name: getFlag(flags, "name"), url: getFlag(flags, "url"), eventPatterns: events?.length ? events : void 0, enabled: parseOptionalBoolFlag(flags, "enabled") });
8650
8684
  }, "commandUpdateWebhookEndpoint"), commandDeleteWebhookEndpoint = __name2(async ({ positional }) => {
8651
8685
  const id = positional[0];
@@ -8660,16 +8694,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8660
8694
  const id = positional[0];
8661
8695
  if (!id) throw new Error("send-webhook-test-event requires <id>");
8662
8696
  await sendWebhookTestEvent(id);
8663
- }, "commandSendWebhookTestEvent"), commandListWebhookDeliveries = __name2(
8664
- async ({ flags }) => {
8665
- const statuses = (getFlag(flags, "status") ?? "").split(",").map((value) => value.trim()).filter(Boolean);
8666
- for (const status of statuses) if (status !== "PENDING" && status !== "SUCCEEDED" && status !== "FAILED") throw new Error("--status must be PENDING, SUCCEEDED or FAILED (comma-separated)");
8667
- const cursor = getFlag(flags, "cursor"), direction = parseProjectDirection(getFlag(flags, "direction"));
8668
- if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
8669
- await listWebhookDeliveries({ endpointId: getFlag(flags, "endpointId"), ...statuses.length ? { status: statuses } : {}, eventType: getFlag(flags, "eventType"), cursor, direction, limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") });
8670
- },
8671
- "commandListWebhookDeliveries"
8672
- ), commandGetWebhookDelivery = __name2(async ({ positional }) => {
8697
+ }, "commandSendWebhookTestEvent"), commandListWebhookDeliveries = __name2(async ({ flags }) => {
8698
+ 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)");
8701
+ const cursor = getFlag(flags, "cursor"), direction = parseProjectDirection(getFlag(flags, "direction"));
8702
+ if (direction === "backward" && !cursor) throw new Error("--direction backward requires --cursor <token>.");
8703
+ await listWebhookDeliveries({ endpointId: getFlag(flags, "endpointId"), ...statuses.length ? { status: statuses } : {}, eventType: getFlag(flags, "eventType"), cursor, direction, limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") });
8704
+ }, "commandListWebhookDeliveries"), commandGetWebhookDelivery = __name2(async ({ positional }) => {
8673
8705
  const id = positional[0];
8674
8706
  if (!id) throw new Error("get-webhook-delivery requires <id>");
8675
8707
  await getWebhookDelivery(id);
@@ -8698,11 +8730,10 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8698
8730
  if (rawLimit === !0 || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("--limit must be an integer between 1 and 100.");
8699
8731
  return { cursor, direction, limit };
8700
8732
  }, "parseInboundSourcePaging"), commandListInboundSources = __name2(async ({ cmd, flags }) => {
8701
- const filters = inboundSourceFiltersFromFlags(
8702
- flags
8703
- );
8733
+ const filters = inboundSourceFiltersFromFlags(flags);
8704
8734
  if (cmd === "count-inbound-sources") {
8705
- if (["limit", "cursor", "direction"].some((key) => flags[key] !== void 0)) throw new Error("Source counts accept filters only, not pagination flags.");
8735
+ if (["limit", "cursor", "direction"].some((key) => flags[key] !== void 0))
8736
+ throw new Error("Source counts accept filters only, not pagination flags.");
8706
8737
  await countInboundSources(filters);
8707
8738
  } else {
8708
8739
  const { cursor, direction, limit } = parseInboundSourcePaging(flags);
@@ -8745,15 +8776,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8745
8776
  await updateInboundProcessing({ processingEnabled: enabled, processingMode: String(mode), sourceId });
8746
8777
  }, "commandUpdateInboundProcessing"), commandGetApprovedBudgets = __name2(async ({ flags }) => {
8747
8778
  await getApprovedBudgets({ projectId: getFlag(flags, "projectId"), limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit"), minRevenue: parseOptionalNumber(getFlag(flags, "minRevenue"), "--minRevenue"), maxRevenue: parseOptionalNumber(getFlag(flags, "maxRevenue"), "--maxRevenue") });
8748
- }, "commandGetApprovedBudgets"), commandGetBudgetCategoryBenchmarks = __name2(
8749
- async ({ flags, positional }) => {
8750
- const id = positional[0];
8751
- if (!id) throw new Error("get-budget-category-benchmarks requires <categoryId> [--limit]");
8752
- await getBudgetCategoryBenchmarks({ categoryId: id, limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") });
8753
- },
8754
- "commandGetBudgetCategoryBenchmarks"
8755
- ), commandGetItemPricingHistory = __name2(async ({ flags }) => {
8756
- await getItemPricingHistory({ itemName: getFlag(flags, "itemName"), categoryId: getFlag(flags, "categoryId"), supplierId: getFlag(flags, "supplierId"), limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") });
8779
+ }, "commandGetApprovedBudgets"), commandGetBudgetCategoryBenchmarks = __name2(async ({ flags, positional }) => {
8780
+ const id = positional[0];
8781
+ if (!id) throw new Error("get-budget-category-benchmarks requires <categoryId> [--limit]");
8782
+ await getBudgetCategoryBenchmarks({ categoryId: id, limit: parsePositiveIntFlag(getFlag(flags, "limit"), "--limit") });
8783
+ }, "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
+ );
8757
8787
  }, "commandGetItemPricingHistory"), commandGetSupplierPricingHistory = __name2(async ({ flags, positional }) => {
8758
8788
  const id = positional[0];
8759
8789
  if (!id) throw new Error("get-supplier-pricing-history requires <supplierId> [--itemCategoryId] [--limit]");
@@ -8765,10 +8795,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8765
8795
  ["get-budget", commandGetBudget],
8766
8796
  ["upload-budget-attachment", commandUploadBudgetAttachment],
8767
8797
  ["mark-budget-won", commandMarkBudgetWon],
8768
- [
8769
- "get-budget-items",
8770
- commandGetBudgetItems
8771
- ],
8798
+ ["get-budget-items", commandGetBudgetItems],
8772
8799
  ["get-budget-details", commandGetBudgetDetails],
8773
8800
  ["get-budget-categories", commandGetBudgetCategories],
8774
8801
  ["get-budget-versions", commandGetBudgetVersions],
@@ -8811,7 +8838,10 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8811
8838
  ["update-bill-payment-evidence", commandUpdateBillPaymentEvidence],
8812
8839
  ["delete-bill", commandDeleteBill],
8813
8840
  ["update-bill-status", commandUpdateBillStatus],
8814
- ["list-external-payment-accounts", commandListExternalPaymentAccounts],
8841
+ [
8842
+ "list-external-payment-accounts",
8843
+ commandListExternalPaymentAccounts
8844
+ ],
8815
8845
  ["refresh-external-payment-accounts", commandRefreshExternalPaymentAccounts],
8816
8846
  ["record-external-bill-payment", commandRecordExternalBillPayment],
8817
8847
  ["patch-bill-payment", commandPatchBillPayment],
@@ -8827,6 +8857,8 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8827
8857
  ["attach-bill-payment-receipt", commandUploadBillAttachment],
8828
8858
  ["attach-bill-documents", commandAttachBillDocuments],
8829
8859
  ["get-bill-details", commandGetBillDetails],
8860
+ ["get-bill-review", commandGetBillReview],
8861
+ ["request-bill-review", commandRequestBillReview],
8830
8862
  ["list-quotations", commandListQuotations],
8831
8863
  ["count-quotations", commandCountQuotations],
8832
8864
  ["get-quotation", commandGetQuotation],
@@ -8845,10 +8877,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8845
8877
  ["preview-customer-invoice-amount", commandPreviewCustomerInvoiceAmount],
8846
8878
  ["list-available-qbo-customer-invoices", commandListAvailableQboCustomerInvoices],
8847
8879
  ["list-customer-invoices", commandListCustomerInvoices],
8848
- [
8849
- "count-customer-invoices",
8850
- commandListCustomerInvoices
8851
- ],
8880
+ ["count-customer-invoices", commandListCustomerInvoices],
8852
8881
  ["get-customer-invoice", commandGetCustomerInvoice],
8853
8882
  ["get-customer-invoice-invoices", commandGetCustomerInvoiceInvoices],
8854
8883
  ["get-customer-invoice-lines", commandGetCustomerInvoiceLines],
@@ -8871,6 +8900,11 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8871
8900
  ["update-customer-invoice-qbo-drift", commandUpdateCustomerInvoiceQboDrift],
8872
8901
  ["mark-customer-invoice-sent-externally", commandMarkCustomerInvoiceSentExternally],
8873
8902
  ["sync-customer-invoice", commandSyncCustomerInvoice],
8903
+ ["get-pending-approval", async ({ positional }) => {
8904
+ const id = positional[0];
8905
+ if (!id) throw new Error("approval get requires <approvalId>");
8906
+ await getPendingApproval(id);
8907
+ }],
8874
8908
  ["list-approvals", commandListApprovals],
8875
8909
  ["get-pending-approvals", commandListApprovals],
8876
8910
  ["approve-bill", commandApproveBill],
@@ -8902,13 +8936,13 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8902
8936
  ["sync-project-hub-commercial-documents", commandSyncProjectHubCommercialDocuments],
8903
8937
  ["create-project", commandCreateProject],
8904
8938
  ["update-project", commandUpdateProject],
8905
- ["delete-project", commandDeleteProject],
8906
- ["check-project-reconciliation", commandCheckProjectReconciliation],
8907
- ["reconcile-project", commandReconcileProject],
8908
8939
  [
8909
- "complete-project",
8910
- commandCompleteProject
8940
+ "delete-project",
8941
+ commandDeleteProject
8911
8942
  ],
8943
+ ["check-project-reconciliation", commandCheckProjectReconciliation],
8944
+ ["reconcile-project", commandReconcileProject],
8945
+ ["complete-project", commandCompleteProject],
8912
8946
  ["import-qbo-project", commandImportQboProject],
8913
8947
  ["update-project-status", commandUpdateProjectStatus],
8914
8948
  ["list-contacts", commandListContacts],
@@ -8986,11 +9020,14 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8986
9020
  ["get-budget-category-benchmarks", commandGetBudgetCategoryBenchmarks],
8987
9021
  ["get-item-pricing-history", commandGetItemPricingHistory],
8988
9022
  ["get-supplier-pricing-history", commandGetSupplierPricingHistory]
8989
- ]), dispatchCliCommand = __name2(async (context) => {
8990
- const handler = CLI_COMMAND_HANDLERS.get(context.cmd);
8991
- if (!handler) throw new Error("Unknown command: ".concat(context.cmd, ". Run 'bb help'."));
8992
- await handler(context);
8993
- }, "dispatchCliCommand"), startCliSession = __name2((context, command) => {
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) => {
8994
9031
  setActiveCliSession({ runtime: context.runtime, invocation: { command, cliVersion: context.version, apiBaseUrl: BUDGET_BUILDER_API_BASE_URL, quiet: context.quiet, debug: context.debug }, effects: [], permissions: {} });
8995
9032
  }, "startCliSession"), failCliSession = __name2((context, command, error2) => {
8996
9033
  startCliSession(context, command);
@@ -8999,40 +9036,29 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
8999
9036
  }, "failCliSession"), resolveRootArguments = __name2((rawArgv, runtime) => {
9000
9037
  const rootArguments = parseRootArguments(rawArgv), apiBaseUrl = rootArguments.apiBaseUrl ?? runtime.env.BB_API_URL?.trim();
9001
9038
  return configureBudgetBuilderApiBaseUrl(apiBaseUrl || DEFAULT_BUDGET_BUILDER_API_BASE_URL), rootArguments;
9002
- }, "resolveRootArguments"), isHelpRequest = __name2((commandArgv) => commandArgv.length === 0 || commandArgv[0] === "help" || isEnabledFlag(commandArgv, "--help") || commandArgv.includes("-h"), "isHelpRequest"), printCliHelp = __name2(
9003
- (commandArgv, runtime) => {
9004
- if (commandArgv.includes("--legacy")) {
9005
- printLegacyHelp(runtime);
9006
- return;
9007
- }
9008
- 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;
9009
- runtime.stdout.write("".concat(createHumanHelp(helpCommand), "\n"));
9010
- },
9011
- "printCliHelp"
9012
- ), runCompletionCommand = __name2((context, commandArgv) => {
9039
+ }, "resolveRootArguments"), isHelpRequest = __name2((commandArgv) => commandArgv.length === 0 || commandArgv[0] === "help" || isEnabledFlag(commandArgv, "--help") || commandArgv.includes("-h"), "isHelpRequest"), printCliHelp = __name2((commandArgv, runtime) => {
9040
+ if (commandArgv.includes("--legacy")) {
9041
+ printLegacyHelp(runtime);
9042
+ return;
9043
+ }
9044
+ 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
+ runtime.stdout.write("".concat(createHumanHelp(helpCommand), "\n"));
9046
+ }, "printCliHelp"), runCompletionCommand = __name2((context, commandArgv) => {
9013
9047
  const shell = commandArgv[1];
9014
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);
9015
- }, "runCompletionCommand"), isVersionRequest = __name2((commandArgv) => commandArgv[0] === "version" || isEnabledFlag(commandArgv, "--version") || commandArgv.includes("-v"), "isVersionRequest"), runVersionCommand = __name2((context) => (startCliSession(
9016
- context,
9017
- "version"
9018
- ), emitCommandResult(getVersionData()), clearActiveCliSession(), 0), "runVersionCommand"), createDefaultCredentialStore = __name2((runtime) => createBunCredentialStore({ account: resolveCliCredentialAccount(runtime.env), product: "budget-builder" }), "createDefaultCredentialStore"), authStatusResult = __name2(async (runtime, store) => {
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) => {
9019
9050
  const apiKeyActive = !!runtime.env.BB_API_KEY?.trim(), credentials = apiKeyActive ? null : await store.get();
9020
9051
  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" };
9021
9052
  }, "authStatusResult"), runAuthAction = __name2(async (context, authAction, rawArgv, store) => {
9022
9053
  const { runtime } = context;
9023
9054
  if (authAction === "login") {
9024
- const credentials = await loginWithBrowser(
9025
- { apiBaseUrl: BUDGET_BUILDER_API_BASE_URL, clientVersion: context.version, onVerification: __name2(({ browserOpened, userCode, verificationUriComplete }) => runtime.stderr.write("".concat(browserOpened ? "Opened" : "Open", " ").concat(verificationUriComplete, "\nCode: ").concat(userCode, "\nWaiting for approval\u2026\n")), "onVerification"), ...isEnabledFlag(rawArgv, "--no-browser") ? { openBrowser: __name2(async () => !1, "openBrowser") } : {}, store }
9026
- );
9055
+ const credentials = await loginWithBrowser({ apiBaseUrl: BUDGET_BUILDER_API_BASE_URL, clientVersion: context.version, onVerification: __name2(({ browserOpened, userCode, verificationUriComplete }) => runtime.stderr.write("".concat(browserOpened ? "Opened" : "Open", " ").concat(verificationUriComplete, "\nCode: ").concat(userCode, "\nWaiting for approval\u2026\n")), "onVerification"), ...isEnabledFlag(rawArgv, "--no-browser") ? { openBrowser: __name2(async () => !1, "openBrowser") } : {}, store });
9027
9056
  emitCommandResult({ authenticated: !0, method: "browser-session", session: credentials.session, storage: "Bun.secrets" });
9028
9057
  } else emitCommandResult(authAction === "status" ? await authStatusResult(runtime, store) : { loggedOut: !0, ...await logoutCliSession({ apiBaseUrl: BUDGET_BUILDER_API_BASE_URL, store }), apiKeyActive: !!runtime.env.BB_API_KEY?.trim() });
9029
9058
  }, "runAuthAction"), runAuthCommand = __name2(async (context, authAction, commandArgv, rawArgv, credentialStore) => {
9030
9059
  startCliSession(context, "auth ".concat(authAction));
9031
9060
  try {
9032
- if (commandArgv.length !== 2) throw new CliRuntimeError("USAGE", "auth ".concat(
9033
- authAction,
9034
- " accepts no positional arguments."
9035
- ));
9061
+ if (commandArgv.length !== 2) throw new CliRuntimeError("USAGE", "auth ".concat(authAction, " accepts no positional arguments."));
9036
9062
  const store = credentialStore ?? createDefaultCredentialStore(context.runtime);
9037
9063
  return await runAuthAction(context, authAction, rawArgv, store), 0;
9038
9064
  } catch (error2) {
@@ -9054,9 +9080,7 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
9054
9080
  } catch (error2) {
9055
9081
  throw getCliStorageError(error2) ? error2 : new CliRuntimeError("AUTHENTICATION", error2 instanceof Error ? error2.message : "Not authenticated. Run bb auth login first.");
9056
9082
  }
9057
- configureAccessToken(
9058
- accessToken
9059
- );
9083
+ configureAccessToken(accessToken);
9060
9084
  }, "configureCliAuthentication"), CONFIRMATION_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["create-bill", "import-qbo-customer-invoice", "approve-supplier"]), confirmCanonicalMutation = __name2(async (resolvedCommand, cmd) => {
9061
9085
  resolvedCommand.isLegacyAlias || CONFIRMATION_EXEMPT_COMMANDS.has(cmd) || resolvedCommand.command.effects.length === 0 || await confirmCurrentCommand({ action: resolvedCommand.command.path.join(" "), target: commandConfirmationTarget(resolvedCommand), details: "Canonical v2 mutation. Supply every effect-specific --allow-* flag for non-interactive execution." });
9062
9086
  }, "confirmCanonicalMutation"), runResolvedCommand = __name2(async (context, argv, rawArgv, resolvedCommand, credentialStore, configureAccessToken) => {
@@ -9066,7 +9090,9 @@ var booleanFlagValues = /* @__PURE__ */ new Set(["true", "false", "1", "0"]), is
9066
9090
  shouldLogCliActions() && logCliAction({ event: "cli.command", phase: "start", command: cmd, positional, flags: sanitizeFlagsForTrace(flags) });
9067
9091
  try {
9068
9092
  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.");
9069
- 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;
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;
9070
9096
  } catch (err) {
9071
9097
  const message = err instanceof Error ? err.message : String(err);
9072
9098
  shouldLogCliActions() && logCliAction({ event: "cli.command", phase: "error", command: cmd, durationMs: Date.now() - t0, error: message });