@agentforge-io/sdk-server 4.90.0 → 4.91.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/errors.d.ts CHANGED
@@ -64,6 +64,34 @@ export declare class AgentForgeCreditError extends AgentForgeError {
64
64
  readonly code: AgentForgeCreditErrorCode;
65
65
  constructor(status: number, code: AgentForgeCreditErrorCode, message: string, body?: string);
66
66
  }
67
+ /**
68
+ * PDK-RENTAL-DEAL R7 — the coded refusals of the partial-payment routes (`cases.recordPayment` / `refundPayment` / `confirmPayment` /
69
+ * `rejectPayment` / `waiveAnticipo` / `extendAnticipo`, `transition`, `createDirectRental`, `sendQuote`). `code` narrows to this union.
70
+ * 400: `invalid_payment_plan` / `invalid_cancel_policy` (the plan), `deposit_due` (a transition while the anticipo is owed; `err.anticipoDueCents`),
71
+ * `exceeds_balance` (`err.balanceCents`), `exceeds_due`, `exceeds_paid` (`err.paidCents`), `reason_required` (a retention that differs from the policy,
72
+ * or a confirmation for less than reported; `err.suggestedRetainedCents`), `note_required`, `total_pending`, `not_accepted`, `case_closed`, `on_account`,
73
+ * `nothing_due`, `no_anticipo`, `not_waiting`, `method_required`, `invalid_*`; 404 `entry_not_found`;
74
+ * 409 `report_pending` (a customer report waits: confirm or reject it first), `already_paid`, `already_waived`, `entry_resolved`,
75
+ * `deposit_expired` (the anticipo expired: the case is being cancelled), `idempotency_conflict` (the key was used for another request).
76
+ * A refusal is final: do not retry it with another key. On a timeout, repeat the call with the SAME `idempotencyKey`.
77
+ */
78
+ export type AgentForgePaymentErrorCode = 'invalid_payment_plan' | 'invalid_cancel_policy' | 'deposit_due' | 'deposit_expired' | 'exceeds_balance' | 'exceeds_due' | 'exceeds_paid' | 'invalid_retention' | 'reason_required' | 'note_required' | 'total_pending' | 'not_accepted' | 'case_closed' | 'on_account' | 'nothing_due' | 'no_anticipo' | 'already_waived' | 'not_waiting' | 'already_paid' | 'report_pending' | 'entry_not_found' | 'entry_resolved' | 'idempotency_conflict' | 'invalid_idempotency_key' | 'invalid_amount' | 'invalid_kind' | 'invalid_source' | 'invalid_account' | 'invalid_method' | 'method_required' | 'invalid_hours' | 'invalid_body' | 'ledger_guard_missing';
79
+ export declare const AGENTFORGE_PAYMENT_ERROR_CODES: readonly AgentForgePaymentErrorCode[];
80
+ export declare class AgentForgePaymentError extends AgentForgeError {
81
+ readonly code: AgentForgePaymentErrorCode;
82
+ /** `deposit_due`: the anticipo the case still waits for (cents). */
83
+ readonly anticipoDueCents?: number;
84
+ /** `exceeds_balance`: what the case still owes (cents). */
85
+ readonly balanceCents?: number;
86
+ /** `exceeds_due`: what is asked now (cents). */
87
+ readonly dueNowCents?: number;
88
+ /** `exceeds_paid`: what is paid (cents). */
89
+ readonly paidCents?: number;
90
+ /** `reason_required` on a refund: what the policy suggests retaining, and the refund that implies (cents). */
91
+ readonly suggestedRetainedCents?: number;
92
+ readonly refundCents?: number;
93
+ constructor(status: number, code: AgentForgePaymentErrorCode, message: string, body?: string);
94
+ }
67
95
  export declare class AgentForgeNetworkError extends Error {
68
96
  readonly cause: Error;
69
97
  constructor(message: string, cause: Error);
package/dist/errors.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentForgeNetworkError = exports.AgentForgeCreditError = exports.AGENTFORGE_CREDIT_ERROR_CODES = exports.AgentForgeBillingError = exports.AGENTFORGE_BILLING_ERROR_CODES = exports.AgentForgeDuplicateContactError = exports.AgentForgeNotFoundError = exports.AgentForgeAuthError = exports.AgentForgeError = void 0;
3
+ exports.AgentForgeNetworkError = exports.AgentForgePaymentError = exports.AGENTFORGE_PAYMENT_ERROR_CODES = exports.AgentForgeCreditError = exports.AGENTFORGE_CREDIT_ERROR_CODES = exports.AgentForgeBillingError = exports.AGENTFORGE_BILLING_ERROR_CODES = exports.AgentForgeDuplicateContactError = exports.AgentForgeNotFoundError = exports.AgentForgeAuthError = exports.AgentForgeError = void 0;
4
4
  class AgentForgeError extends Error {
5
5
  constructor(status, message, body, code) {
6
6
  super(message);
@@ -116,6 +116,35 @@ class AgentForgeCreditError extends AgentForgeError {
116
116
  }
117
117
  }
118
118
  exports.AgentForgeCreditError = AgentForgeCreditError;
119
+ exports.AGENTFORGE_PAYMENT_ERROR_CODES = [
120
+ 'invalid_payment_plan', 'invalid_cancel_policy', 'deposit_due', 'deposit_expired', 'exceeds_balance', 'exceeds_due', 'exceeds_paid',
121
+ 'invalid_retention', 'reason_required', 'note_required', 'total_pending', 'not_accepted', 'case_closed', 'on_account', 'nothing_due',
122
+ 'no_anticipo', 'already_waived', 'not_waiting', 'already_paid', 'report_pending', 'entry_not_found', 'entry_resolved',
123
+ 'idempotency_conflict', 'invalid_idempotency_key', 'invalid_amount', 'invalid_kind', 'invalid_source', 'invalid_account',
124
+ 'invalid_method', 'method_required', 'invalid_hours', 'invalid_body', 'ledger_guard_missing',
125
+ ];
126
+ class AgentForgePaymentError extends AgentForgeError {
127
+ constructor(status, code, message, body) {
128
+ super(status, message, body, code);
129
+ this.name = 'AgentForgePaymentError';
130
+ if (body) {
131
+ try {
132
+ const b = JSON.parse(body);
133
+ const n = (k) => (typeof b[k] === 'number' ? b[k] : undefined);
134
+ this.anticipoDueCents = n('anticipoDueCents');
135
+ this.balanceCents = n('balanceCents');
136
+ this.dueNowCents = n('dueNowCents');
137
+ this.paidCents = n('paidCents');
138
+ this.suggestedRetainedCents = n('suggestedRetainedCents');
139
+ this.refundCents = n('refundCents');
140
+ }
141
+ catch {
142
+ /* no extras */
143
+ }
144
+ }
145
+ }
146
+ }
147
+ exports.AgentForgePaymentError = AgentForgePaymentError;
119
148
  class AgentForgeNetworkError extends Error {
120
149
  constructor(message, cause) {
121
150
  super(message);
package/dist/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  export { AgentForgeClient, INSTALLED_TENANT_HEADER } from './client';
2
2
  export type { AgentForgeClientOptions, RequestOptions } from './client';
3
- export { AgentForgeError, AgentForgeAuthError, AgentForgeNotFoundError, AgentForgeNetworkError, AgentForgeDuplicateContactError, AgentForgeBillingError, AGENTFORGE_BILLING_ERROR_CODES, AgentForgeCreditError, AGENTFORGE_CREDIT_ERROR_CODES, } from './errors';
4
- export type { AgentForgeBillingErrorCode, AgentForgeCreditErrorCode } from './errors';
3
+ export { AgentForgeError, AgentForgeAuthError, AgentForgeNotFoundError, AgentForgeNetworkError, AgentForgeDuplicateContactError, AgentForgeBillingError, AGENTFORGE_BILLING_ERROR_CODES, AgentForgeCreditError, AGENTFORGE_CREDIT_ERROR_CODES, AgentForgePaymentError, AGENTFORGE_PAYMENT_ERROR_CODES, } from './errors';
4
+ export type { AgentForgeBillingErrorCode, AgentForgeCreditErrorCode, AgentForgePaymentErrorCode } from './errors';
5
5
  export { CreditResource, CreditAccountsResource } from './resources/credit';
6
- export type { CreateDirectRentalInput, UpdateCaseRentalInput, CaseRental, RentalPeriodUnit } from './types';
6
+ export type { CreateDirectRentalInput, UpdateCaseRentalInput, CaseRental, RentalPeriodUnit, RentalOptionMode } from './types';
7
+ export type { CancelPolicy, CancelPolicyTier, CancelBy, CancellationOutcome, CaseCancellation, CasePaymentPlanInput, CasePaymentPlan, CasePaymentEntry, CasePaymentEntryKind, CasePaymentEntryStatus, CasePaymentEntrySource, PublicCasePaymentEntry, RecordCasePaymentInput, RefundCasePaymentInput, CasePaymentWriteResult, } from './types';
8
+ export type { CaseQuote, CaseQuoteStatus, CaseQuoteVersion, CaseQuoteVersionStatus, CaseQuoteLine, CaseQuotePrice, CaseQuoteExtra, CaseQuoteAction, CaseQuoteAnswerInput, CaseCustomerRequestKind, CaseReceiptQuote, CaseReceiptQuoteVersion, SendCaseQuoteInput, } from './types';
7
9
  export type { CreditEntryKind, CreditAgingBucket, CreditAccountStatus, CreditEntry, CreditAllocation, CreditDebt, CreditAccount, CreditWriteResult, CreditStatementRow, CreditAccountListRow, CreditAccountsQuery, CreditAccountsPage, CreditStatementQuery, CreditStatement, UpdateCreditAccountInput, CreditPayInput, CreditReversePaymentInput, CreditWriteOffInput, CreditOpeningInput, CreditPayoutInput, } from './resources/credit';
8
10
  export { BillingResource } from './resources/billing';
9
11
  export type { BillingCurrency, BillingEntitlement, BillingEntitlementStatus, BillingInterval, BillingLimits, BillingPlan, BillingInvoice, BillingInvoicePage, BillingInvoicesQuery, BillingPaymentMethod, BillingCheckoutInput, BillingStartTrialInput, AppBillingWebhookEvent, AppBillingWebhookEventName, AppBillingWebhookData, } from './resources/billing';
package/dist/index.js CHANGED
@@ -28,8 +28,8 @@
28
28
  // const payload = af.tools.verifyCallback({ rawBody, signatureHeader, secretPlaintext });
29
29
  // await af.tools.respondToCallback({ resultUrl: payload.resultUrl, tenantId: payload.tenantId, secret, result });
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.CatalogResource = exports.BusinessRolesResource = exports.CasesResource = exports.DeliveryResource = exports.FilesResource = exports.ContactListsResource = exports.ContactTagsResource = exports.ContactAddressesResource = exports.ContactVerificationResource = exports.ContactsResource = exports.PlacesResource = exports.TenantConfigResource = exports.MarketplaceResource = exports.REFERENCE_BULK_MAX_ITEMS = exports.REFERENCE_MATCH_MAX_ITEMS = exports.AgentForgeReferenceLimitError = exports.ReferenceProductsResource = exports.ReferenceResource = exports.TemplateReportsResource = exports.TemplateReviewsResource = exports.TemplatesResource = exports.InstallationsResource = exports.InboxResource = exports.parseGoogleSheetsPickerResult = exports.ConnectorsResource = exports.ChatResource = exports.AppsResource = exports.AnalyticsResource = exports.AgentsResource = exports.WebhookResource = exports.verifyToolCallbackSignature = exports.verifyAppWebhook = exports.signToolCallbackPayload = exports.ToolCallbackSignatureError = exports.TOOL_CALLBACK_HEADERS = exports.APP_WEBHOOK_HEADERS = exports.BillingResource = exports.CreditAccountsResource = exports.CreditResource = exports.AGENTFORGE_CREDIT_ERROR_CODES = exports.AgentForgeCreditError = exports.AGENTFORGE_BILLING_ERROR_CODES = exports.AgentForgeBillingError = exports.AgentForgeDuplicateContactError = exports.AgentForgeNetworkError = exports.AgentForgeNotFoundError = exports.AgentForgeAuthError = exports.AgentForgeError = exports.INSTALLED_TENANT_HEADER = exports.AgentForgeClient = void 0;
32
- exports.ToolsResource = exports.TeamsResource = exports.SecretsResource = exports.ProvisioningResource = exports.CATALOG_IMPORT_MAX_ITEMS = exports.AgentForgeCatalogImportLimitError = exports.CatalogSourcesResource = exports.CatalogUnitsResource = exports.CatalogOptionGroupsResource = exports.CatalogMenuImportResource = exports.CatalogFileImportResource = exports.CatalogImportResource = exports.CatalogPhotosResource = exports.CatalogReviewsResource = exports.CatalogProductLikesResource = exports.CatalogProductReviewsResource = exports.CatalogProductsResource = exports.CatalogCategoriesResource = void 0;
31
+ exports.CasesResource = exports.DeliveryResource = exports.FilesResource = exports.ContactListsResource = exports.ContactTagsResource = exports.ContactAddressesResource = exports.ContactVerificationResource = exports.ContactsResource = exports.PlacesResource = exports.TenantConfigResource = exports.MarketplaceResource = exports.REFERENCE_BULK_MAX_ITEMS = exports.REFERENCE_MATCH_MAX_ITEMS = exports.AgentForgeReferenceLimitError = exports.ReferenceProductsResource = exports.ReferenceResource = exports.TemplateReportsResource = exports.TemplateReviewsResource = exports.TemplatesResource = exports.InstallationsResource = exports.InboxResource = exports.parseGoogleSheetsPickerResult = exports.ConnectorsResource = exports.ChatResource = exports.AppsResource = exports.AnalyticsResource = exports.AgentsResource = exports.WebhookResource = exports.verifyToolCallbackSignature = exports.verifyAppWebhook = exports.signToolCallbackPayload = exports.ToolCallbackSignatureError = exports.TOOL_CALLBACK_HEADERS = exports.APP_WEBHOOK_HEADERS = exports.BillingResource = exports.CreditAccountsResource = exports.CreditResource = exports.AGENTFORGE_PAYMENT_ERROR_CODES = exports.AgentForgePaymentError = exports.AGENTFORGE_CREDIT_ERROR_CODES = exports.AgentForgeCreditError = exports.AGENTFORGE_BILLING_ERROR_CODES = exports.AgentForgeBillingError = exports.AgentForgeDuplicateContactError = exports.AgentForgeNetworkError = exports.AgentForgeNotFoundError = exports.AgentForgeAuthError = exports.AgentForgeError = exports.INSTALLED_TENANT_HEADER = exports.AgentForgeClient = void 0;
32
+ exports.ToolsResource = exports.TeamsResource = exports.SecretsResource = exports.ProvisioningResource = exports.CATALOG_IMPORT_MAX_ITEMS = exports.AgentForgeCatalogImportLimitError = exports.CatalogSourcesResource = exports.CatalogUnitsResource = exports.CatalogOptionGroupsResource = exports.CatalogMenuImportResource = exports.CatalogFileImportResource = exports.CatalogImportResource = exports.CatalogPhotosResource = exports.CatalogReviewsResource = exports.CatalogProductLikesResource = exports.CatalogProductReviewsResource = exports.CatalogProductsResource = exports.CatalogCategoriesResource = exports.CatalogResource = exports.BusinessRolesResource = void 0;
33
33
  var client_1 = require("./client");
34
34
  Object.defineProperty(exports, "AgentForgeClient", { enumerable: true, get: function () { return client_1.AgentForgeClient; } });
35
35
  Object.defineProperty(exports, "INSTALLED_TENANT_HEADER", { enumerable: true, get: function () { return client_1.INSTALLED_TENANT_HEADER; } });
@@ -43,6 +43,8 @@ Object.defineProperty(exports, "AgentForgeBillingError", { enumerable: true, get
43
43
  Object.defineProperty(exports, "AGENTFORGE_BILLING_ERROR_CODES", { enumerable: true, get: function () { return errors_1.AGENTFORGE_BILLING_ERROR_CODES; } });
44
44
  Object.defineProperty(exports, "AgentForgeCreditError", { enumerable: true, get: function () { return errors_1.AgentForgeCreditError; } });
45
45
  Object.defineProperty(exports, "AGENTFORGE_CREDIT_ERROR_CODES", { enumerable: true, get: function () { return errors_1.AGENTFORGE_CREDIT_ERROR_CODES; } });
46
+ Object.defineProperty(exports, "AgentForgePaymentError", { enumerable: true, get: function () { return errors_1.AgentForgePaymentError; } });
47
+ Object.defineProperty(exports, "AGENTFORGE_PAYMENT_ERROR_CODES", { enumerable: true, get: function () { return errors_1.AGENTFORGE_PAYMENT_ERROR_CODES; } });
46
48
  var credit_1 = require("./resources/credit");
47
49
  Object.defineProperty(exports, "CreditResource", { enumerable: true, get: function () { return credit_1.CreditResource; } });
48
50
  Object.defineProperty(exports, "CreditAccountsResource", { enumerable: true, get: function () { return credit_1.CreditAccountsResource; } });
@@ -1,5 +1,5 @@
1
1
  import type { AgentForgeClient } from '../client';
2
- import type { CaseAccount, CaseChangeInput, ConfirmCaseLineInput, CaseClosingReport, CaseProposalAnswer, CaseProposalInput, CaseReportPage, CasePaymentStatus, CaseReceipt, CaseState, CaseView, CreateDirectBookingInput, CreateDirectOrderInput, CreateDirectRentalInput, CreateOpenOrderInput, DirectOrderForm, ListCasesInput, MoveCaseSlotInput, ProductReview, ReceiptReviewables, SaveReceiptReviewInput, SetCaseLinePriceInput, SetOnAccountInput, SetOnAccountResult, UpdateCaseRentalInput } from '../types';
2
+ import type { CancellationOutcome, CasePaymentEntry, CasePaymentWriteResult, RecordCasePaymentInput, RefundCasePaymentInput, CaseAccount, CaseChangeInput, CaseCustomerRequestKind, CaseQuoteAnswerInput, ConfirmCaseLineInput, CaseClosingReport, CaseProposalAnswer, CaseProposalInput, CaseReportPage, CasePaymentStatus, CaseReceipt, CaseState, CaseView, CreateDirectBookingInput, CreateDirectOrderInput, CreateDirectRentalInput, CreateOpenOrderInput, DirectOrderForm, ListCasesInput, MoveCaseSlotInput, ProductReview, ReceiptReviewables, SaveReceiptReviewInput, SendCaseQuoteInput, SetCaseLinePriceInput, SetOnAccountInput, SetOnAccountResult, UpdateCaseRentalInput } from '../types';
3
3
  export declare class CasesResource {
4
4
  private readonly client;
5
5
  constructor(client: AgentForgeClient);
@@ -71,6 +71,56 @@ export declare class CasesResource {
71
71
  * Returns the updated case.
72
72
  */
73
73
  setLinePrice(caseId: string, input: SetCaseLinePriceInput): Promise<CaseView>;
74
+ /**
75
+ * `POST /api/v1/cases/:id/quote` — PDK-RENTAL-DEAL R1: the business sends a rental QUOTE (a case made with `createDirectRental({ quote: true })`)
76
+ * as numbered, immutable version N: a price for every line nobody priced (a catalog line with a `quote` option, a free line the customer typed),
77
+ * optional extra lines (transporte, depósito…), a validity (`validUntil`) and a conditions `note`. The customer gets a proposal
78
+ * (`CaseView.proposal.quote`, `requiresAnswer`) and answers it on the receipt (`receiptAnswerQuote`) or you record it (`answerQuote`).
79
+ * NOTHING is applied until they accept: a rejected, expired or replaced version leaves lines, prices and total as they were. A version still
80
+ * waiting is `superseded` by the next one. Poodleck-style flow: `requested` → `sent` → (`changes_requested` → `sent` …) → `accepted`.
81
+ * 400 `not_a_quote` / `quote_closed` (already accepted) / `prices_missing` (`lines`) / `unknown_line` / `not_priceable` / `price_overflow` /
82
+ * `invalid_valid_until` / invalid body, 409 another proposal is waiting. Returns the updated case (`quote.versions`). The App gets
83
+ * `case.proposal` with `proposal: 'quote_sent'` and `quoteVersion`.
84
+ */
85
+ sendQuote(caseId: string, input: SendCaseQuoteInput): Promise<CaseView>;
86
+ /**
87
+ * `POST /api/v1/cases/:id/quote/answer` — PDK-RENTAL-DEAL R1: the business records the customer's answer to the quote waiting (they said it by
88
+ * phone). Same body and effects as `receiptAnswerQuote`.
89
+ */
90
+ answerQuote(caseId: string, input: CaseQuoteAnswerInput): Promise<CaseView>;
91
+ /**
92
+ * `POST /api/v1/cases/receipts/:token/quote/answer` — PDK-RENTAL-DEAL R1: the customer answers the quote version waiting on their receipt.
93
+ *
94
+ * - `accept` — that version is the agreement: its prices and extras are applied, the receipt is re-issued (same link, revision + 1, total
95
+ * frozen = the version's `totalCents`) and the case becomes `accepted` (the customer is asked how to pay; `receiptChoosePayment` opens).
96
+ * - `reject` — the case ends `rejected` (its units are released like any undone close); `comment` = the reason.
97
+ * - `changes_requested` — `comment` required (≤ 1000): the case stays open waiting for the business's next version.
98
+ *
99
+ * `version` (optional) guards against answering a version that was replaced meanwhile. 400 `no_quote_waiting` / invalid body,
100
+ * 409 `quote_stale` (replaced, or the order changed since) or `quote_expired` (past `validUntil`: the case ends `cancelled`).
101
+ * Returns the receipt as it is now (`quote`). The App gets `case.proposal` with `proposal: 'quote_accepted' | 'quote_rejected' | 'quote_changes_requested'`.
102
+ */
103
+ receiptAnswerQuote(token: string, input: CaseQuoteAnswerInput): Promise<CaseReceipt>;
104
+ /**
105
+ * `POST /api/v1/cases/:id/customer-request` — PDK-RENTAL-DEAL R1b (App sk_ key; 403 otherwise): records ON the case what the customer asked
106
+ * the business for — `asks_cancel` («Pedir cancelación», after your cutoff) or `asks_change` («pedir cambio de fechas») — as the assistant's
107
+ * requests do. It shows as `CaseView.customerRequest` (`kind: 'cancel' | 'change'`, `text`, `at`) until the business moves the case, and the
108
+ * App gets `case.customer_request` (`request`, `by: 'customer'`). `text` ≤ 500 (a default per kind when omitted). Only a case the business
109
+ * already accepted; 400 before that (the customer cancels/changes it directly) and when closed. The platform applies no policy: you enforce yours.
110
+ */
111
+ customerRequest(caseId: string, input: {
112
+ kind: CaseCustomerRequestKind;
113
+ text?: string;
114
+ }): Promise<CaseView>;
115
+ /**
116
+ * `POST /api/v1/cases/:id/cancel-for-customer` — PDK-RENTAL-DEAL R1b (App sk_ key; 403 otherwise): cancels on the customer's behalf when YOUR policy
117
+ * allows it (e.g. before the cutoff), also once the case is `confirmed` — which `receiptCancel` refuses and keeps refusing. The case closes
118
+ * `cancelled` with `by: 'customer'` (history and `case.closed` say so), the note is `reason` (≤ 500) and its units go back like any undone close;
119
+ * a quote still waiting is withdrawn. 400 `in_progress` while it is under way (`en_obra`, `devuelta`, out for delivery) and 400 when already closed.
120
+ */
121
+ cancelForCustomer(caseId: string, input?: {
122
+ reason?: string;
123
+ }): Promise<CaseView>;
74
124
  /**
75
125
  * `POST /api/v1/cases/:id/weigh` — AGF-UNITS U3: what a line sold by value
76
126
  * («$3.000 de queso») really weighed, in the product's unit (`line` = the
@@ -187,6 +237,8 @@ export declare class CasesResource {
187
237
  * PDK-OFF-CATALOG: moving to a confirmed state (`confirmed`, ready, out for delivery, `completed`) is refused with
188
238
  * 400 `code: 'lines_pending'` while a free line is still pending (`offCatalog.pendingCount > 0`): confirm them
189
239
  * first. `cancelled` / `rejected` stay allowed.
240
+ * PDK-RENTAL-DEAL R7: a rental whose required anticipo is not in is refused with 400 `deposit_due` (`AgentForgePaymentError`, `err.anticipoDueCents`):
241
+ * record it (`recordPayment`) or `waiveAnticipo` first.
190
242
  */
191
243
  transition(caseId: string, state: CaseState, opts?: {
192
244
  note?: string;
@@ -250,6 +302,9 @@ export declare class CasesResource {
250
302
  * `confirmation: 'instant'`. 400 for a bad range (end ≤ start, > 366 days, a count below what the range spans) or a
251
303
  * line with `variantId`/`amountCents`; 409 when a product lacks stock. A retried `idempotencyKey` returns the same rental.
252
304
  * R2d: `lines[].periodRateCents` (App sk_ key) prices a line with YOUR rate of one period instead of the catalog; still multiplied here.
305
+ * PDK-RENTAL-DEAL R1: `lines[].optionPricing` (App key) charges an option `per_trip` (once per unit) or leaves it «a cotizar» (`quote`); `quote: true`
306
+ * makes the rental a QUOTE REQUEST (stays `submitted`, `receipt.pricePending`, never instant) and allows `allowOffCatalog` + `offCatalogLines`
307
+ * (free-text extras with a pending price); anything pending without `quote: true` is a 400 `quote_required`. The business then answers with `sendQuote`.
253
308
  */
254
309
  createDirectRental(input: CreateDirectRentalInput): Promise<CaseView>;
255
310
  /**
@@ -333,7 +388,67 @@ export declare class CasesResource {
333
388
  contentType: 'image/jpeg' | 'image/png' | 'image/webp';
334
389
  dataBase64: string;
335
390
  };
391
+ /**
392
+ * PDK-RENTAL-DEAL R7 — on a case paid in parts: how much the customer reports (positive whole cents, at most what is due now; default: all of it).
393
+ * 400 `exceeds_due` / `nothing_due`; 409 `report_pending` (one report at a time) / `deposit_expired` (`AgentForgePaymentError`).
394
+ */
395
+ amountCents?: number;
336
396
  }): Promise<CaseReceipt>;
397
+ /** `GET /api/v1/cases/:id/payments` — the case's payment entries (anticipo, saldo, refunds, customer reports), oldest first, with the owner's data. */
398
+ payments(caseId: string): Promise<{
399
+ entries: CasePaymentEntry[];
400
+ }>;
401
+ /**
402
+ * `POST /api/v1/cases/:id/payments` — record money that came in (cash at the door, a transfer you saw): a confirmed entry. Returns the case
403
+ * (`payment.paidCents`, `balanceCents`, status `partially_paid` | `paid`…), the entry and `replayed`. 400 `not_accepted` / `case_closed` /
404
+ * `on_account` / `total_pending` / `exceeds_balance` (`err.balanceCents`) / `method_required` / `invalid_*`; 409 `already_paid` / `report_pending` /
405
+ * `deposit_expired` / `idempotency_conflict`. Same `idempotencyKey` + same body = replay.
406
+ */
407
+ recordPayment(caseId: string, input: RecordCasePaymentInput): Promise<CasePaymentWriteResult>;
408
+ /**
409
+ * `POST /api/v1/cases/:id/payments/refund` — money given back. On a case cancelled under a policy, retaining anything but the suggestion needs a
410
+ * `reason` (400 `reason_required`, with `err.suggestedRetainedCents` / `err.refundCents`). 400 `exceeds_paid` (`err.paidCents`) / `invalid_retention` /
411
+ * `not_accepted` / `on_account`; 409 `idempotency_conflict`.
412
+ */
413
+ refundPayment(caseId: string, input: RefundCasePaymentInput): Promise<CasePaymentWriteResult>;
414
+ /**
415
+ * `POST /api/v1/cases/:id/payments/:entryId/confirm` — the reported payment arrived. `amountCents` = what the bank shows (at most what was reported;
416
+ * a lower one needs a `note`: 400 `reason_required`). 404 `entry_not_found`; 409 `entry_resolved`; 400 `exceeds_balance`.
417
+ */
418
+ confirmPayment(caseId: string, entryId: string, input?: {
419
+ amountCents?: number;
420
+ note?: string;
421
+ }): Promise<CasePaymentWriteResult>;
422
+ /**
423
+ * `POST /api/v1/cases/:id/payments/:entryId/reject` — the reported payment did not arrive. After the anticipo deadline the customer gets 12 h more (once).
424
+ * 404 `entry_not_found`; 409 `entry_resolved`.
425
+ */
426
+ rejectPayment(caseId: string, entryId: string, input?: {
427
+ note?: string;
428
+ }): Promise<CasePaymentWriteResult>;
429
+ /**
430
+ * `POST /api/v1/cases/:id/payment/waive-anticipo` — «Sin anticipo»: removes the `deposit_due` gate (an instant rental confirms itself). `note` is required
431
+ * (400 `note_required`). 400 `no_anticipo`; 409 `already_waived`.
432
+ */
433
+ waiveAnticipo(caseId: string, input: {
434
+ note: string;
435
+ }): Promise<CaseView>;
436
+ /**
437
+ * `POST /api/v1/cases/:id/payment/extend-anticipo` — «Dar más tiempo»: the anticipo deadline moves to the later of now and the deadline, plus `hours` (whole 1–168).
438
+ * 400 `invalid_hours` / `no_anticipo` / `not_waiting`; 409 `deposit_expired`.
439
+ */
440
+ extendAnticipo(caseId: string, input: {
441
+ hours: number;
442
+ note?: string;
443
+ }): Promise<CaseView>;
444
+ /**
445
+ * `GET /api/v1/cases/:id/cancellation-preview?by=customer|business` — what cancelling now would retain and refund under the frozen policy (no write).
446
+ * `by: 'customer'` (default) applies the policy; `business` cancels without a penalty by default. A case already cancelled answers its frozen figures (`frozen: true`).
447
+ */
448
+ cancellationPreview(caseId: string, by?: 'customer' | 'business'): Promise<CancellationOutcome>;
449
+ /** `GET /api/v1/cases/receipts/:token/cancellation-preview` — the same, from the customer's link (the customer cancels; no `tierIndex`). */
450
+ receiptCancellationPreview(token: string): Promise<CancellationOutcome>;
451
+ private paymentWrite;
337
452
  /**
338
453
  * `GET /api/v1/cases/receipts/:token/image.png` — the receipt as a PNG:
339
454
  * `wide` (1200×630, what a shared link previews) or `tall` (1080×1350, to send or save).
@@ -6,6 +6,26 @@
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.CasesResource = void 0;
8
8
  const credit_1 = require("./credit");
9
+ const errors_1 = require("../errors");
10
+ const PAYMENT_CODES = new Set(errors_1.AGENTFORGE_PAYMENT_ERROR_CODES);
11
+ /** PDK-RENTAL-DEAL R7 — a payment-coded failure becomes the typed `AgentForgePaymentError` (still an `AgentForgeError`); anything else is rethrown as is. */
12
+ function asPaymentError(err) {
13
+ if (err instanceof errors_1.AgentForgeError && err.code && PAYMENT_CODES.has(err.code) && err.status !== 401 && err.status !== 403) {
14
+ let message = err.message;
15
+ if (err.body) {
16
+ try {
17
+ const b = JSON.parse(err.body);
18
+ if (typeof b.message === 'string')
19
+ message = b.message;
20
+ }
21
+ catch {
22
+ /* keep the status message */
23
+ }
24
+ }
25
+ return new errors_1.AgentForgePaymentError(err.status, err.code, message, err.body);
26
+ }
27
+ return err;
28
+ }
9
29
  class CasesResource {
10
30
  constructor(client) {
11
31
  this.client = client;
@@ -116,6 +136,66 @@ class CasesResource {
116
136
  async setLinePrice(caseId, input) {
117
137
  return this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/lines/price`, input);
118
138
  }
139
+ /**
140
+ * `POST /api/v1/cases/:id/quote` — PDK-RENTAL-DEAL R1: the business sends a rental QUOTE (a case made with `createDirectRental({ quote: true })`)
141
+ * as numbered, immutable version N: a price for every line nobody priced (a catalog line with a `quote` option, a free line the customer typed),
142
+ * optional extra lines (transporte, depósito…), a validity (`validUntil`) and a conditions `note`. The customer gets a proposal
143
+ * (`CaseView.proposal.quote`, `requiresAnswer`) and answers it on the receipt (`receiptAnswerQuote`) or you record it (`answerQuote`).
144
+ * NOTHING is applied until they accept: a rejected, expired or replaced version leaves lines, prices and total as they were. A version still
145
+ * waiting is `superseded` by the next one. Poodleck-style flow: `requested` → `sent` → (`changes_requested` → `sent` …) → `accepted`.
146
+ * 400 `not_a_quote` / `quote_closed` (already accepted) / `prices_missing` (`lines`) / `unknown_line` / `not_priceable` / `price_overflow` /
147
+ * `invalid_valid_until` / invalid body, 409 another proposal is waiting. Returns the updated case (`quote.versions`). The App gets
148
+ * `case.proposal` with `proposal: 'quote_sent'` and `quoteVersion`.
149
+ */
150
+ async sendQuote(caseId, input) {
151
+ try {
152
+ return await this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/quote`, input);
153
+ }
154
+ catch (err) {
155
+ throw asPaymentError(err);
156
+ }
157
+ }
158
+ /**
159
+ * `POST /api/v1/cases/:id/quote/answer` — PDK-RENTAL-DEAL R1: the business records the customer's answer to the quote waiting (they said it by
160
+ * phone). Same body and effects as `receiptAnswerQuote`.
161
+ */
162
+ async answerQuote(caseId, input) {
163
+ return this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/quote/answer`, input);
164
+ }
165
+ /**
166
+ * `POST /api/v1/cases/receipts/:token/quote/answer` — PDK-RENTAL-DEAL R1: the customer answers the quote version waiting on their receipt.
167
+ *
168
+ * - `accept` — that version is the agreement: its prices and extras are applied, the receipt is re-issued (same link, revision + 1, total
169
+ * frozen = the version's `totalCents`) and the case becomes `accepted` (the customer is asked how to pay; `receiptChoosePayment` opens).
170
+ * - `reject` — the case ends `rejected` (its units are released like any undone close); `comment` = the reason.
171
+ * - `changes_requested` — `comment` required (≤ 1000): the case stays open waiting for the business's next version.
172
+ *
173
+ * `version` (optional) guards against answering a version that was replaced meanwhile. 400 `no_quote_waiting` / invalid body,
174
+ * 409 `quote_stale` (replaced, or the order changed since) or `quote_expired` (past `validUntil`: the case ends `cancelled`).
175
+ * Returns the receipt as it is now (`quote`). The App gets `case.proposal` with `proposal: 'quote_accepted' | 'quote_rejected' | 'quote_changes_requested'`.
176
+ */
177
+ async receiptAnswerQuote(token, input) {
178
+ return this.client.request('POST', `/api/v1/cases/receipts/${encodeURIComponent(token)}/quote/answer`, input);
179
+ }
180
+ /**
181
+ * `POST /api/v1/cases/:id/customer-request` — PDK-RENTAL-DEAL R1b (App sk_ key; 403 otherwise): records ON the case what the customer asked
182
+ * the business for — `asks_cancel` («Pedir cancelación», after your cutoff) or `asks_change` («pedir cambio de fechas») — as the assistant's
183
+ * requests do. It shows as `CaseView.customerRequest` (`kind: 'cancel' | 'change'`, `text`, `at`) until the business moves the case, and the
184
+ * App gets `case.customer_request` (`request`, `by: 'customer'`). `text` ≤ 500 (a default per kind when omitted). Only a case the business
185
+ * already accepted; 400 before that (the customer cancels/changes it directly) and when closed. The platform applies no policy: you enforce yours.
186
+ */
187
+ async customerRequest(caseId, input) {
188
+ return this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/customer-request`, input);
189
+ }
190
+ /**
191
+ * `POST /api/v1/cases/:id/cancel-for-customer` — PDK-RENTAL-DEAL R1b (App sk_ key; 403 otherwise): cancels on the customer's behalf when YOUR policy
192
+ * allows it (e.g. before the cutoff), also once the case is `confirmed` — which `receiptCancel` refuses and keeps refusing. The case closes
193
+ * `cancelled` with `by: 'customer'` (history and `case.closed` say so), the note is `reason` (≤ 500) and its units go back like any undone close;
194
+ * a quote still waiting is withdrawn. 400 `in_progress` while it is under way (`en_obra`, `devuelta`, out for delivery) and 400 when already closed.
195
+ */
196
+ async cancelForCustomer(caseId, input = {}) {
197
+ return this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/cancel-for-customer`, input);
198
+ }
119
199
  /**
120
200
  * `POST /api/v1/cases/:id/weigh` — AGF-UNITS U3: what a line sold by value
121
201
  * («$3.000 de queso») really weighed, in the product's unit (`line` = the
@@ -252,12 +332,19 @@ class CasesResource {
252
332
  * PDK-OFF-CATALOG: moving to a confirmed state (`confirmed`, ready, out for delivery, `completed`) is refused with
253
333
  * 400 `code: 'lines_pending'` while a free line is still pending (`offCatalog.pendingCount > 0`): confirm them
254
334
  * first. `cancelled` / `rejected` stay allowed.
335
+ * PDK-RENTAL-DEAL R7: a rental whose required anticipo is not in is refused with 400 `deposit_due` (`AgentForgePaymentError`, `err.anticipoDueCents`):
336
+ * record it (`recordPayment`) or `waiveAnticipo` first.
255
337
  */
256
338
  async transition(caseId, state, opts = {}) {
257
- return this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/transition`, {
258
- state,
259
- ...(opts.note ? { note: opts.note } : {}),
260
- });
339
+ try {
340
+ return await this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/transition`, {
341
+ state,
342
+ ...(opts.note ? { note: opts.note } : {}),
343
+ });
344
+ }
345
+ catch (err) {
346
+ throw asPaymentError(err);
347
+ }
261
348
  }
262
349
  /**
263
350
  * `GET /api/v1/cases/receipts/:token` — AGF-CASE-RECEIPT: the receipt behind a
@@ -336,9 +423,17 @@ class CasesResource {
336
423
  * `confirmation: 'instant'`. 400 for a bad range (end ≤ start, > 366 days, a count below what the range spans) or a
337
424
  * line with `variantId`/`amountCents`; 409 when a product lacks stock. A retried `idempotencyKey` returns the same rental.
338
425
  * R2d: `lines[].periodRateCents` (App sk_ key) prices a line with YOUR rate of one period instead of the catalog; still multiplied here.
426
+ * PDK-RENTAL-DEAL R1: `lines[].optionPricing` (App key) charges an option `per_trip` (once per unit) or leaves it «a cotizar» (`quote`); `quote: true`
427
+ * makes the rental a QUOTE REQUEST (stays `submitted`, `receipt.pricePending`, never instant) and allows `allowOffCatalog` + `offCatalogLines`
428
+ * (free-text extras with a pending price); anything pending without `quote: true` is a 400 `quote_required`. The business then answers with `sendQuote`.
339
429
  */
340
430
  async createDirectRental(input) {
341
- return this.client.request('POST', '/api/v1/cases/direct-rental', input);
431
+ try {
432
+ return await this.client.request('POST', '/api/v1/cases/direct-rental', input);
433
+ }
434
+ catch (err) {
435
+ throw asPaymentError(err);
436
+ }
342
437
  }
343
438
  /**
344
439
  * `PATCH /api/v1/cases/:id/rental` — PDK-RENTAL-AVAILABILITY: reschedule or extend a rental you already moved in your
@@ -441,7 +536,94 @@ class CasesResource {
441
536
  * ≤ 700 KB). The payment waits for the business to confirm it.
442
537
  */
443
538
  async receiptReportPayment(token, input) {
444
- return this.client.request('POST', `/api/v1/cases/receipts/${encodeURIComponent(token)}/payment/report`, input);
539
+ try {
540
+ return await this.client.request('POST', `/api/v1/cases/receipts/${encodeURIComponent(token)}/payment/report`, input);
541
+ }
542
+ catch (err) {
543
+ throw asPaymentError(err);
544
+ }
545
+ }
546
+ // ─── PDK-RENTAL-DEAL R7: partial payments (anticipo / saldo / refunds) ────────────────────────────────────────────
547
+ // Append-only payment entries per case. Tenant API key. Money is whole cents. Every write needs an `idempotencyKey` (8–120 of
548
+ // `A-Za-z0-9_.:-`) that the CALLER chooses and keeps; this SDK never retries a request and never invents a key. Refusals throw
549
+ // `AgentForgePaymentError` (`err.code`, `err.status`). Needs the platform change PDK-RENTAL-DEAL R7; an older platform answers 404.
550
+ /** `GET /api/v1/cases/:id/payments` — the case's payment entries (anticipo, saldo, refunds, customer reports), oldest first, with the owner's data. */
551
+ async payments(caseId) {
552
+ return this.client.request('GET', `/api/v1/cases/${encodeURIComponent(caseId)}/payments`);
553
+ }
554
+ /**
555
+ * `POST /api/v1/cases/:id/payments` — record money that came in (cash at the door, a transfer you saw): a confirmed entry. Returns the case
556
+ * (`payment.paidCents`, `balanceCents`, status `partially_paid` | `paid`…), the entry and `replayed`. 400 `not_accepted` / `case_closed` /
557
+ * `on_account` / `total_pending` / `exceeds_balance` (`err.balanceCents`) / `method_required` / `invalid_*`; 409 `already_paid` / `report_pending` /
558
+ * `deposit_expired` / `idempotency_conflict`. Same `idempotencyKey` + same body = replay.
559
+ */
560
+ async recordPayment(caseId, input) {
561
+ return this.paymentWrite(`/api/v1/cases/${encodeURIComponent(caseId)}/payments`, input);
562
+ }
563
+ /**
564
+ * `POST /api/v1/cases/:id/payments/refund` — money given back. On a case cancelled under a policy, retaining anything but the suggestion needs a
565
+ * `reason` (400 `reason_required`, with `err.suggestedRetainedCents` / `err.refundCents`). 400 `exceeds_paid` (`err.paidCents`) / `invalid_retention` /
566
+ * `not_accepted` / `on_account`; 409 `idempotency_conflict`.
567
+ */
568
+ async refundPayment(caseId, input) {
569
+ return this.paymentWrite(`/api/v1/cases/${encodeURIComponent(caseId)}/payments/refund`, input);
570
+ }
571
+ /**
572
+ * `POST /api/v1/cases/:id/payments/:entryId/confirm` — the reported payment arrived. `amountCents` = what the bank shows (at most what was reported;
573
+ * a lower one needs a `note`: 400 `reason_required`). 404 `entry_not_found`; 409 `entry_resolved`; 400 `exceeds_balance`.
574
+ */
575
+ async confirmPayment(caseId, entryId, input = {}) {
576
+ return this.paymentWrite(`/api/v1/cases/${encodeURIComponent(caseId)}/payments/${encodeURIComponent(entryId)}/confirm`, input);
577
+ }
578
+ /**
579
+ * `POST /api/v1/cases/:id/payments/:entryId/reject` — the reported payment did not arrive. After the anticipo deadline the customer gets 12 h more (once).
580
+ * 404 `entry_not_found`; 409 `entry_resolved`.
581
+ */
582
+ async rejectPayment(caseId, entryId, input = {}) {
583
+ return this.paymentWrite(`/api/v1/cases/${encodeURIComponent(caseId)}/payments/${encodeURIComponent(entryId)}/reject`, input);
584
+ }
585
+ /**
586
+ * `POST /api/v1/cases/:id/payment/waive-anticipo` — «Sin anticipo»: removes the `deposit_due` gate (an instant rental confirms itself). `note` is required
587
+ * (400 `note_required`). 400 `no_anticipo`; 409 `already_waived`.
588
+ */
589
+ async waiveAnticipo(caseId, input) {
590
+ try {
591
+ return await this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/payment/waive-anticipo`, input);
592
+ }
593
+ catch (err) {
594
+ throw asPaymentError(err);
595
+ }
596
+ }
597
+ /**
598
+ * `POST /api/v1/cases/:id/payment/extend-anticipo` — «Dar más tiempo»: the anticipo deadline moves to the later of now and the deadline, plus `hours` (whole 1–168).
599
+ * 400 `invalid_hours` / `no_anticipo` / `not_waiting`; 409 `deposit_expired`.
600
+ */
601
+ async extendAnticipo(caseId, input) {
602
+ try {
603
+ return await this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/payment/extend-anticipo`, input);
604
+ }
605
+ catch (err) {
606
+ throw asPaymentError(err);
607
+ }
608
+ }
609
+ /**
610
+ * `GET /api/v1/cases/:id/cancellation-preview?by=customer|business` — what cancelling now would retain and refund under the frozen policy (no write).
611
+ * `by: 'customer'` (default) applies the policy; `business` cancels without a penalty by default. A case already cancelled answers its frozen figures (`frozen: true`).
612
+ */
613
+ async cancellationPreview(caseId, by = 'customer') {
614
+ return this.client.request('GET', `/api/v1/cases/${encodeURIComponent(caseId)}/cancellation-preview?by=${by}`);
615
+ }
616
+ /** `GET /api/v1/cases/receipts/:token/cancellation-preview` — the same, from the customer's link (the customer cancels; no `tierIndex`). */
617
+ async receiptCancellationPreview(token) {
618
+ return this.client.request('GET', `/api/v1/cases/receipts/${encodeURIComponent(token)}/cancellation-preview`);
619
+ }
620
+ async paymentWrite(path, body) {
621
+ try {
622
+ return await this.client.request('POST', path, body);
623
+ }
624
+ catch (err) {
625
+ throw asPaymentError(err);
626
+ }
445
627
  }
446
628
  /**
447
629
  * `GET /api/v1/cases/receipts/:token/image.png` — the receipt as a PNG:
package/dist/types.d.ts CHANGED
@@ -2582,6 +2582,12 @@ export interface CaseView {
2582
2582
  payment: CasePayment | null;
2583
2583
  /** AGF-PDK-DISPATCH-PROPOSAL — the latest proposed changes and their answer (absent on an older platform). */
2584
2584
  proposal?: CaseProposal | null;
2585
+ /**
2586
+ * PDK-RENTAL-DEAL R1 — a rental QUOTE request (`createDirectRental({ quote: true })`): where it is, every version the business sent
2587
+ * (newest last; snapshot, validity, answer, comment) and the agreed one. Null: not a quote (absent on an older platform). The lines still
2588
+ * waiting for a price are `cases.receipt(token).quote.pendingLines` (the receipt's lines carry the keys to price).
2589
+ */
2590
+ quote?: CaseQuote | null;
2585
2591
  /** AGF-AGENDA — who of the business attends it: your member reference (set with `cases.assign`). */
2586
2592
  assigneeRef: string | null;
2587
2593
  /** AGF-AGENDA — the time a booking holds, and how it reads («lunes, 9 de noviembre, 10:00–10:45»). */
@@ -2678,7 +2684,9 @@ export interface CreateOffCatalogLineInput {
2678
2684
  */
2679
2685
  export type CasePaymentStatus = 'unpaid' | 'awaiting_payment' | 'pending_confirmation' | 'paid' | 'rejected' | 'refunded' | 'partially_refunded' | 'reversed' | 'voided'
2680
2686
  /** PDK-STORE-CREDIT — «Fiado»: left on the customer's account (`cases.setOnAccount`). Neither to collect nor payable by chat. Absent on an older platform. */
2681
- | 'on_account';
2687
+ | 'on_account'
2688
+ /** PDK-RENTAL-DEAL R7 — some money came in, not all (an anticipo, a partial saldo). Only a case with payment entries reaches it. Absent on an older platform. */
2689
+ | 'partially_paid';
2682
2690
  /** The account the customer chose, as it was then (a later edit never rewrites a sale). */
2683
2691
  export interface CasePaymentAccount {
2684
2692
  id: string;
@@ -2734,13 +2742,35 @@ export interface CasePayment {
2734
2742
  * abono, never on the order). Absent otherwise and on an older platform; cleared when it goes back on account.
2735
2743
  */
2736
2744
  settledBy?: 'account';
2745
+ /** The plan frozen with the agreement: anticipo %, its amount, the deadline, the cancellation policy. */
2746
+ plan?: CasePaymentPlan;
2747
+ /** The case's money lives in its payment entries (`cases.payments`); the fields below are their projection. */
2748
+ ledger?: true;
2749
+ /** Confirmed money in − confirmed refunds. */
2750
+ paidCents?: number;
2751
+ /** Confirmed money in (refunds not subtracted). */
2752
+ grossPaidCents?: number;
2753
+ /** `max(total − paid, 0)` against the live receipt total (absent while the total is unknown). */
2754
+ balanceCents?: number;
2755
+ /** What the customer pays next: the anticipo still owed while it gates the case, else the balance. */
2756
+ dueNowCents?: number;
2757
+ /** Reported entries still waiting for the business. */
2758
+ pendingCents?: number;
2759
+ /** The anticipo still owed (0 when paid, waived or none). */
2760
+ anticipoDueCents?: number;
2761
+ /** `deposit_due`: a required anticipo is not in, so the case cannot be confirmed / dispatched (400 `deposit_due`). */
2762
+ gate?: 'deposit_due' | null;
2763
+ /** What has to go back: after the retention on a case that closed undone, or what was over-paid on a live one. */
2764
+ refundDueCents?: number;
2765
+ /** The money consequence frozen when the case closed undone (penalty tier, retained, to refund). */
2766
+ cancellation?: CaseCancellation;
2737
2767
  history: Array<{
2738
2768
  status: CasePaymentStatus;
2739
2769
  by: 'assistant' | 'customer' | 'business' | 'system';
2740
2770
  at: string;
2741
2771
  note?: string;
2742
2772
  amountCents?: number;
2743
- settledBy?: 'account';
2773
+ settledBy?: 'account' | 'ledger';
2744
2774
  }>;
2745
2775
  }
2746
2776
  /** The payment as a receipt's public link shows it (no proof image, only that one was sent). */
@@ -2772,6 +2802,37 @@ export interface CaseReceiptPayment {
2772
2802
  refundDue?: boolean;
2773
2803
  /** PDK-SERVICE-CHANGES S3 — what is still owed (+) or given back (−) after an accepted change moved the total; null/absent: nothing. */
2774
2804
  differenceCents?: number | null;
2805
+ /** `expiredAt` (R7-POLISH-2): the anticipo deadline passed with nothing paid and the platform cancelled the case (ISO); null otherwise; absent on an older platform. */
2806
+ plan?: {
2807
+ totalCents: number;
2808
+ anticipoPercent: number;
2809
+ anticipoCents: number;
2810
+ required: boolean;
2811
+ waived: boolean;
2812
+ dueAt: string | null;
2813
+ expiredAt?: string | null;
2814
+ cancelPolicyText: string;
2815
+ };
2816
+ paidCents?: number;
2817
+ balanceCents?: number | null;
2818
+ /** What «Cómo pagar» asks for now: the anticipo while it is owed, then the balance. */
2819
+ dueNowCents?: number | null;
2820
+ /** A reported transfer the business has not confirmed yet («En revisión»). */
2821
+ pendingCents?: number;
2822
+ anticipoDueCents?: number;
2823
+ gate?: 'deposit_due' | null;
2824
+ refundDueCents?: number;
2825
+ /** The money consequence once the case closed undone (null: none). `tier` is the applied `CancelPolicyTier` (or null). */
2826
+ cancellation?: {
2827
+ policyApplied: boolean;
2828
+ by: string;
2829
+ tier: CancelPolicyTier | null;
2830
+ retainedCents: number;
2831
+ refundCents: number;
2832
+ at: string;
2833
+ } | null;
2834
+ /** The customer's payments (no owner data, no proof URL, no actor, no App reference). */
2835
+ entries?: PublicCasePaymentEntry[];
2775
2836
  }
2776
2837
  /** AGF-CASE-RECEIPT — one product line, with the price it had when the receipt was issued. */
2777
2838
  export interface CaseReceiptLine {
@@ -2804,12 +2865,28 @@ export interface CaseReceiptLine {
2804
2865
  weigh?: string;
2805
2866
  /** The business typed its real weight: `qty` is that, not an estimate. */
2806
2867
  weighed?: boolean;
2807
- /** AGF-MENU-OPTIONS M2 — the options chosen; `unitCents` already includes them. */
2868
+ /**
2869
+ * AGF-MENU-OPTIONS M2 — the options chosen; `unitCents` already includes them.
2870
+ * `optionId`: the catalog option's id. `priceMode` (PDK-RENTAL-DEAL R1, rentals): `quote` = «a cotizar» (`deltaCents` is 0, not counted),
2871
+ * `per_trip` = `deltaCents` is charged once per unit, not × the periods.
2872
+ */
2808
2873
  options?: Array<{
2809
2874
  group: string;
2810
2875
  name: string;
2811
2876
  deltaCents: number;
2877
+ optionId?: string;
2878
+ priceMode?: RentalOptionMode;
2812
2879
  }>;
2880
+ /** PDK-RENTAL-DEAL R1 — names of the options that wait for a quote: the line is `priceKind: 'from'` («desde `unitCents`») until the business prices it. */
2881
+ quoteOptions?: string[];
2882
+ /** PDK-RENTAL-DEAL R1 — of `unitCents` (one unit over the whole range), the part charged once per unit (per-trip options): not × `periods.count`. */
2883
+ tripCents?: number;
2884
+ /** PDK-RENTAL-DEAL R1 — a line the business added in a quote (transporte, depósito…), not asked for by the customer (`offCatalog`, already priced). */
2885
+ extra?: true;
2886
+ /** PDK-RENTAL-DEAL R1 — the line of a `per_booking` option (a transport): charged once for the whole case, qty 1, key `booking#<option>`; the business may re-price it in a quote. */
2887
+ perBooking?: true;
2888
+ /** PDK-RENTAL-DEAL R1 — an extra line charged once (a trip), not × the rental's periods. */
2889
+ perTrip?: true;
2813
2890
  /** PDK-BUG-006 — the line is to go (packed for takeaway). Present only when `true`; absent means
2814
2891
  * eaten here, and also on receipts issued before this flag or by an older platform. */
2815
2892
  takeaway?: true;
@@ -3021,7 +3098,10 @@ export interface CaseProposalChange {
3021
3098
  */
3022
3099
  export interface CaseProposal {
3023
3100
  id: string;
3024
- /** `redone`: the customer chose «Rehacer pedido» (the order went back to being edited). */
3101
+ /**
3102
+ * `redone`: the customer chose «Rehacer pedido» (the order went back to being edited). A rental quote's proposal (`quote`) ends `accepted`,
3103
+ * or `withdrawn` for every other end (rejected, changes requested, expired, taken back): which one is `CaseView.quote.versions[n].status`.
3104
+ */
3025
3105
  status: 'pending' | 'accepted' | 'withdrawn' | 'redone';
3026
3106
  sentAt: string;
3027
3107
  answeredAt?: string;
@@ -3037,6 +3117,14 @@ export interface CaseProposal {
3037
3117
  offCatalog?: true;
3038
3118
  /** PDK-SERVICE-CHANGES — a quote of line prices (`cases.setLinePrice`, `answer: 'required'`): the customer must accept or reject (`requiresAnswer` is true, never auto-accepted); each accepted price becomes the line's price and the receipt is re-issued; a rejected one leaves the line as it was. */
3039
3119
  linePrice?: true;
3120
+ /**
3121
+ * PDK-RENTAL-DEAL R1 — a rental QUOTE version waiting for the customer (`cases.sendQuote`). It is NOT answered with `answerProposal` /
3122
+ * `receiptAnswerProposal` (400 `use_quote_answer`) but with `receiptAnswerQuote` / `answerQuote`. `changes` lists the lines priced in it.
3123
+ */
3124
+ quote?: {
3125
+ version: number;
3126
+ validUntil: string;
3127
+ };
3040
3128
  /** PDK-OFF-CATALOG — the customer MUST answer (a line is out or swapped, or its amount is over what they said × 1.2); payment waits for it. */
3041
3129
  requiresAnswer?: boolean;
3042
3130
  /**
@@ -3128,6 +3216,12 @@ export interface CaseReceipt {
3128
3216
  } | null;
3129
3217
  /** AGF-PDK-DISPATCH-PROPOSAL — the business's latest proposed changes and their answer (absent on an older platform). */
3130
3218
  proposal?: CaseProposal | null;
3219
+ /**
3220
+ * PDK-RENTAL-DEAL R1 — a rental QUOTE request: its status, the version in force and the history (sent / accepted / rejected /
3221
+ * changes_requested / superseded / expired, each with validity, total, comments), the lines still «a cotizar» and what the customer may do
3222
+ * now (`actions`). Answer with `cases.receiptAnswerQuote`. Null / absent: not a quote (or an older platform).
3223
+ */
3224
+ quote?: CaseReceiptQuote | null;
3131
3225
  /** PDK-SERVICE-CHANGES S3 — the customer may ask a change now (`cases.receiptRequestChange`); `changeReason` says why not. Absent on an older platform. */
3132
3226
  changeAllowed?: boolean;
3133
3227
  changeReason?: CaseChangeReason;
@@ -3644,7 +3738,14 @@ export interface CaseRental {
3644
3738
  };
3645
3739
  /** The rate of ONE period of ONE unit per product id when your App priced the lines (`periodRateCents`); absent: the catalog price. */
3646
3740
  periodRates?: Record<string, number>;
3741
+ /**
3742
+ * PDK-RENTAL-DEAL R1 — options charged apart from the periods, by the option's id or its lower-cased accent-free name (what you sent in
3743
+ * `lines[].optionPricing`): `quote` = «a cotizar», `per_trip` = charged once per unit, `per_booking` = once for the whole case. Absent: every option is charged per period.
3744
+ */
3745
+ optionModes?: Record<string, RentalOptionMode>;
3647
3746
  }
3747
+ /** PDK-RENTAL-DEAL R1 — how a rental option is charged when it is not «per period and unit». */
3748
+ export type RentalOptionMode = 'quote' | 'per_trip' | 'per_booking';
3648
3749
  /**
3649
3750
  * `POST /api/v1/cases/direct-rental` — an order of items rented over a time range. The body of `CreateDirectOrderInput`
3650
3751
  * (customer, lines, fields, destination, origin, payment, type, idempotencyKey…) plus `rental`. Without the options
@@ -3654,7 +3755,7 @@ export interface CaseRental {
3654
3755
  * price of ONE period (with the chosen `options`) × units × `rental.periods.count`. Never send totals; an App that owns a rate
3655
3756
  * table sends only the rate of one period per line (`lines[].periodRateCents`, R2d).
3656
3757
  */
3657
- export interface CreateDirectRentalInput extends Omit<CreateDirectOrderInput, 'lines' | 'reopens' | 'allowOffCatalog' | 'maxOffCatalogLines' | 'offCatalogLines'> {
3758
+ export interface CreateDirectRentalInput extends Omit<CreateDirectOrderInput, 'lines' | 'reopens'> {
3658
3759
  lines: Array<{
3659
3760
  productId: string;
3660
3761
  /** Units of the item (2 backhoes). */
@@ -3669,7 +3770,33 @@ export interface CreateDirectRentalInput extends Omit<CreateDirectOrderInput, 'l
3669
3770
  * The same product on two lines must use the same rate. Send the SAME unit as `rental.periods.unit`.
3670
3771
  */
3671
3772
  periodRateCents?: number;
3773
+ /**
3774
+ * PDK-RENTAL-DEAL R1 — options of THIS line that are not charged «per period and unit» (only for an App: an sk_ key bound to an App, 403
3775
+ * without it). `option` names an option the line chose (`options[].options`, by id or name); `mode`: `per_trip` = its price delta is charged
3776
+ * ONCE per unit, not × `rental.periods.count`; `per_booking` = ONCE for the whole case (a transport: not × units nor periods; it becomes its own
3777
+ * receipt line, `perBooking: true`, qty 1, even when several lines chose it); `quote` = it has no price: the line shows «desde» (without it) and waits
3778
+ * for the business's quote. A `quote` option makes the booking a quote request: it needs `quote: true` (400 `quote_required` otherwise).
3779
+ * An option the line did not choose, or one named twice with two modes, is a 400.
3780
+ */
3781
+ optionPricing?: Array<{
3782
+ option: string;
3783
+ mode: RentalOptionMode;
3784
+ }>;
3672
3785
  }>;
3786
+ /**
3787
+ * PDK-RENTAL-DEAL R1 — this is a QUOTE REQUEST, not a booking: the case stays `submitted` with `receipt.pricePending` (never instant, nothing
3788
+ * is paid), and the business answers with `cases.sendQuote`. Required when anything is pending a price: a line with a `quote` option, or
3789
+ * `offCatalogLines` (free-text extras the customer asks for: title + qty, with `allowOffCatalog: true`) — 400 `quote_required` otherwise;
3790
+ * `confirmation: 'instant'` with it is a 400 `quote_not_instant`. A rental with nothing pending behaves as before.
3791
+ */
3792
+ quote?: boolean;
3793
+ /**
3794
+ * PDK-RENTAL-DEAL R7 — partial payments: the anticipo (a % of the agreed total, rounded UP to 1 000 COP), its deadline and the cancellation
3795
+ * policy. Frozen on the case when it is agreed (on a quote request, when the customer accepts a version: send the plan with the quote request
3796
+ * as the default, or with `sendQuote` per version). 0 % and no enabled policy = no plan (the legacy single payment). 400 `invalid_payment_plan` /
3797
+ * `invalid_cancel_policy`. With a required anticipo, `confirmation: 'instant'` waits in `accepted` and confirms itself when the anticipo is in.
3798
+ */
3799
+ paymentPlan?: CasePaymentPlanInput;
3673
3800
  rental: {
3674
3801
  /** ISO instants with their offset (Z or ±hh:mm); at most 366 days apart. */
3675
3802
  startsAt: string;
@@ -3686,6 +3813,348 @@ export interface CreateDirectRentalInput extends Omit<CreateDirectOrderInput, 'l
3686
3813
  /** `review` (default): the business accepts it (`submitted`); `instant`: `confirmed` as it is made (your ledger guarantees the units). */
3687
3814
  confirmation?: 'review' | 'instant';
3688
3815
  }
3816
+ /** One tier of a cancellation policy: with a notice of at least `minHoursBefore` hours before the rental starts, retain `percent` % or `fixedCents`. */
3817
+ export interface CancelPolicyTier {
3818
+ /** Whole hours, 0 or more. Tiers are sorted highest first, strictly descending, and the LAST one is 0 (short notice, after the start, no-shows). */
3819
+ minHoursBefore: number;
3820
+ mode: 'percent' | 'fixed';
3821
+ /** `mode: 'percent'`: whole number 0–100 (rounded up to the peso). */
3822
+ percent?: number;
3823
+ /** `mode: 'fixed'`: positive whole cents. */
3824
+ fixedCents?: number;
3825
+ }
3826
+ /** The cancellation policy: 1–4 tiers when `enabled` (none needed when disabled). The retention is capped at what was paid. */
3827
+ export interface CancelPolicy {
3828
+ enabled: boolean;
3829
+ /** What a percent tier is a percent of: the agreed `total` (default) or the `anticipo`. */
3830
+ basis?: 'total' | 'anticipo';
3831
+ tiers: CancelPolicyTier[];
3832
+ }
3833
+ /** What a host App sends with a direct rental / a quote version: `paymentPlan`. */
3834
+ export interface CasePaymentPlanInput {
3835
+ /** Whole number 0–100. 0 with no enabled policy = no plan. */
3836
+ anticipoPercent: number;
3837
+ /** Hours from acceptance to the anticipo deadline, whole 1–168 (default 48). */
3838
+ anticipoDueHours?: number;
3839
+ /** ISO instant: the deadline is never after it (the platform also caps it at the rental start − 1 h). */
3840
+ notLaterThan?: string;
3841
+ cancelPolicy?: CancelPolicy;
3842
+ }
3843
+ /** The plan frozen on the case when the agreement is made (`CaseView.payment.plan`). */
3844
+ export interface CasePaymentPlan {
3845
+ totalCents: number;
3846
+ anticipoPercent: number;
3847
+ anticipoCents: number;
3848
+ /** Gates confirmation / dispatch (true when the anticipo is > 0). */
3849
+ required: boolean;
3850
+ waived?: {
3851
+ at: string;
3852
+ by: string;
3853
+ note: string;
3854
+ };
3855
+ dueHours: number;
3856
+ notLaterThan?: string;
3857
+ /** The anticipo deadline, set when the case is accepted. */
3858
+ dueAt?: string;
3859
+ acceptedAt?: string;
3860
+ /** The deadline was pushed (`cases.extendAnticipo`, or a late report was rejected). */
3861
+ extendedAt?: string;
3862
+ rejectExtended?: true;
3863
+ /** The expiry sweep claimed it: the case is being cancelled and no money is taken any more (409 `deposit_expired`). */
3864
+ expiredAt?: string;
3865
+ overdueNotifiedAt?: string;
3866
+ cancelPolicy?: CancelPolicy;
3867
+ frozenFrom: 'quote' | 'booking';
3868
+ quoteVersion?: number;
3869
+ /** An instant rental held in `accepted` until the anticipo is in: it confirms itself then. */
3870
+ autoConfirm?: true;
3871
+ frozenAt: string;
3872
+ }
3873
+ export type CasePaymentEntryKind = 'anticipo' | 'saldo' | 'other' | 'refund';
3874
+ export type CasePaymentEntryStatus = 'confirmed' | 'pending' | 'rejected';
3875
+ export type CasePaymentEntrySource = 'owner' | 'driver' | 'online' | 'customer';
3876
+ /** One row of a case's append-only payment ledger (`cases.payments`), as the business reads it. */
3877
+ export interface CasePaymentEntry {
3878
+ id: string;
3879
+ /** Position in the ledger, from 1. */
3880
+ seq: number;
3881
+ kind: CasePaymentEntryKind;
3882
+ /** Positive cents (a refund too: `kind: 'refund'` says the direction). */
3883
+ amountCents: number;
3884
+ status: CasePaymentEntryStatus;
3885
+ source: CasePaymentEntrySource;
3886
+ method: string | null;
3887
+ account: CasePaymentAccount | null;
3888
+ reference: string | null;
3889
+ proofUrl: string | null;
3890
+ note: string | null;
3891
+ /** `<caseCode>-P<seq>`: what the customer reads and the PDF prints. */
3892
+ receiptNo: string;
3893
+ actor: string | null;
3894
+ externalRef: Record<string, unknown> | null;
3895
+ /** A refund / reversal points at the entry it undoes. */
3896
+ reversesId: string | null;
3897
+ occurredAt: string;
3898
+ /** When it counted as money (confirmed). Null while pending / when rejected. */
3899
+ countedAt: string | null;
3900
+ resolvedAt: string | null;
3901
+ resolutionNote: string | null;
3902
+ }
3903
+ /** What the customer sees of an entry (`CaseReceipt.payment.entries`). */
3904
+ export interface PublicCasePaymentEntry {
3905
+ kind: CasePaymentEntryKind;
3906
+ amountCents: number;
3907
+ status: CasePaymentEntryStatus;
3908
+ methodName: string | null;
3909
+ receiptNo: string;
3910
+ occurredAt: string;
3911
+ countedAt: string | null;
3912
+ }
3913
+ export type CancelBy = 'customer' | 'business' | 'system';
3914
+ /** The money consequence of cancelling (`cases.cancellationPreview`). */
3915
+ export interface CancellationOutcome {
3916
+ by: CancelBy;
3917
+ /** The policy applies only when the CUSTOMER cancels (the business and the system cancel without a penalty by default). */
3918
+ policyApplied: boolean;
3919
+ /** Hours between the cancel and the rental start (negative after it); null without a start. */
3920
+ noticeHours: number | null;
3921
+ tier: CancelPolicyTier | null;
3922
+ /** Index into `plan.cancelPolicy.tiers` (absent on the customer's public preview). */
3923
+ tierIndex?: number | null;
3924
+ basis: 'total' | 'anticipo' | null;
3925
+ computedPenaltyCents: number;
3926
+ paidCents: number;
3927
+ retainedCents: number;
3928
+ refundCents: number;
3929
+ /** True when the case already closed undone: these are its frozen figures. */
3930
+ frozen: boolean;
3931
+ currency: string | null;
3932
+ }
3933
+ /** `CaseView.payment.cancellation`: the outcome frozen when the case closed undone. */
3934
+ export interface CaseCancellation extends Omit<CancellationOutcome, 'frozen' | 'currency' | 'tierIndex'> {
3935
+ tierIndex: number | null;
3936
+ at: string;
3937
+ /** The retention the team settled on when it differs from the suggestion (recorded with a reason on the refund entry). */
3938
+ agreedRetainedCents?: number;
3939
+ }
3940
+ /** `POST :id/payments` — money that came in. A confirmed entry. */
3941
+ export interface RecordCasePaymentInput {
3942
+ /** Positive whole cents; at most the balance (400 `exceeds_balance`). */
3943
+ amountCents: number;
3944
+ /** Informational: `anticipo` while it is owed, then `saldo`. Never `refund` (use `refundPayment`). */
3945
+ kind?: 'anticipo' | 'saldo' | 'other';
3946
+ /** How the money moved: one of the business's payment accounts… */
3947
+ accountId?: string;
3948
+ /** …or a method key (`efectivo`, `nequi`, `transferencia`…). One of the two is required (400 `method_required`). */
3949
+ method?: string;
3950
+ source?: 'owner' | 'driver';
3951
+ reference?: string;
3952
+ note?: string;
3953
+ /** Who of the business recorded it (≤ 120). */
3954
+ actor?: string;
3955
+ /** Your own reference (e.g. a POS ticket id); object, ≤ 1000 chars. */
3956
+ externalRef?: Record<string, unknown>;
3957
+ /** 8–120 of `A-Za-z0-9_.:-`, chosen and kept by the CALLER: the same key + body replays (`replayed: true`); another body → 409 `idempotency_conflict`. */
3958
+ idempotencyKey: string;
3959
+ }
3960
+ /** `POST :id/payments/refund` — money given back. */
3961
+ export interface RefundCasePaymentInput {
3962
+ /** Positive whole cents, at most what is paid (400 `exceeds_paid`). */
3963
+ amountCents: number;
3964
+ /** What the business keeps of what was paid. On a case cancelled under a policy, anything but the suggestion needs `reason` (400 `reason_required`). */
3965
+ retainedCents?: number;
3966
+ reason?: string;
3967
+ accountId?: string;
3968
+ method?: string;
3969
+ actor?: string;
3970
+ idempotencyKey: string;
3971
+ }
3972
+ /** What every ledger write answers: the case as it is now and the entry written. */
3973
+ export interface CasePaymentWriteResult {
3974
+ case: CaseView;
3975
+ entry: CasePaymentEntry;
3976
+ /** True when the same `idempotencyKey` + body had already been applied. */
3977
+ replayed: boolean;
3978
+ }
3979
+ /** PDK-RENTAL-DEAL R1 — the status of a rental quote. `requested`: the business owes a version (none yet, or the last one was withdrawn). */
3980
+ export type CaseQuoteStatus = 'requested' | 'sent' | 'changes_requested' | 'accepted' | 'rejected' | 'expired' | 'withdrawn';
3981
+ /** PDK-RENTAL-DEAL R1 — `sent`: waiting for the customer; the others are final for that version (`changes_requested`: the business sends the next). */
3982
+ export type CaseQuoteVersionStatus = 'sent' | 'accepted' | 'rejected' | 'changes_requested' | 'superseded' | 'expired' | 'withdrawn';
3983
+ /** PDK-RENTAL-DEAL R1b — what the customer asked the business for, recorded by the App (`cases.customerRequest`). */
3984
+ export type CaseCustomerRequestKind = 'asks_cancel' | 'asks_change';
3985
+ /** PDK-RENTAL-DEAL R1 — one line of a quote as the customer reads it. `unitCents` = one unit as charged (over the whole range for a rented item); `amountCents` = `unitCents` × `qty`. */
3986
+ export interface CaseQuoteLine {
3987
+ /** The receipt line's key. An extra the business added is `quote#n` here and becomes `off#n` on the receipt once accepted (`CaseQuoteVersion.extras[].key`). */
3988
+ key: string;
3989
+ title: string;
3990
+ qty: number;
3991
+ unit?: string;
3992
+ options?: Array<{
3993
+ group: string;
3994
+ name: string;
3995
+ deltaCents: number;
3996
+ priceMode?: RentalOptionMode;
3997
+ }>;
3998
+ periods?: {
3999
+ unit: string;
4000
+ count: number;
4001
+ unitCents: number | null;
4002
+ };
4003
+ unitCents: number;
4004
+ amountCents: number;
4005
+ /** The business priced this line in this version. */
4006
+ quoted?: true;
4007
+ /** A line the business added (transporte, depósito…). `perTrip`: charged once, not × the periods. */
4008
+ extra?: true;
4009
+ perTrip?: true;
4010
+ note?: string;
4011
+ breakdown?: CaseLinePriceBreakdownItem[];
4012
+ }
4013
+ /** PDK-RENTAL-DEAL R1 — a price as the version froze it (`unitCents`: ONE unit over the whole range, what `linePrices` stores). */
4014
+ export interface CaseQuotePrice {
4015
+ line: string;
4016
+ unitCents: number;
4017
+ per: 'range' | 'period';
4018
+ /** What was typed (`unitCents` ÷ periods when `per` is `period`). */
4019
+ inputCents: number;
4020
+ note?: string;
4021
+ breakdown?: CaseLinePriceBreakdownItem[];
4022
+ }
4023
+ /** PDK-RENTAL-DEAL R1 — a line the business added in a version, as frozen (`unitCents`: one unit as charged). `key`: its `off#n` on the receipt, once accepted. */
4024
+ export interface CaseQuoteExtra {
4025
+ key?: string;
4026
+ title: string;
4027
+ qty: number;
4028
+ unitCents: number;
4029
+ inputCents: number;
4030
+ perTrip: boolean;
4031
+ note?: string;
4032
+ }
4033
+ /** PDK-RENTAL-DEAL R1 — one immutable quote version, as the business reads it (`CaseView.quote.versions`). */
4034
+ export interface CaseQuoteVersion {
4035
+ version: number;
4036
+ id: string;
4037
+ status: CaseQuoteVersionStatus;
4038
+ sentAt: string;
4039
+ /** ISO instant: unanswered after it, the quote expires. */
4040
+ validUntil: string;
4041
+ /** The business's conditions note (what is included, cancellation…). */
4042
+ note: string | null;
4043
+ by: CaseLinePriceActor;
4044
+ currency: string | null;
4045
+ /** The whole order as it will be charged if this version is accepted. */
4046
+ lines: CaseQuoteLine[];
4047
+ deliveryCents: number | null;
4048
+ totalCents: number;
4049
+ /** The receipt revision it was made on. */
4050
+ revision: number;
4051
+ /** The inputs, resolved (what accepting applies). */
4052
+ prices: CaseQuotePrice[];
4053
+ extras: CaseQuoteExtra[];
4054
+ answeredAt?: string;
4055
+ answeredBy?: 'customer' | 'business' | 'system';
4056
+ /** The customer's words (`changes_requested`, or a reason when they rejected). */
4057
+ comment?: string;
4058
+ /** PDK-RENTAL-DEAL R7 — the payment plan sent with this version and the anticipo it makes on this version's total (promoted to `payment.plan` when the customer accepts THIS version). */
4059
+ paymentPlan?: CasePaymentPlanInput & {
4060
+ anticipoCents: number;
4061
+ };
4062
+ }
4063
+ /** PDK-RENTAL-DEAL R1 — `CaseView.quote`. */
4064
+ export interface CaseQuote {
4065
+ status: CaseQuoteStatus;
4066
+ requestedAt: string;
4067
+ /** The latest version (waiting for the customer, or how it ended); null before the first. */
4068
+ current: CaseQuoteVersion | null;
4069
+ /** Every version, oldest first. */
4070
+ versions: CaseQuoteVersion[];
4071
+ /** The version the customer accepted: the agreement. */
4072
+ agreedVersion: number | null;
4073
+ }
4074
+ /** PDK-RENTAL-DEAL R1 — a version on the public link: no inputs and no who. */
4075
+ export interface CaseReceiptQuoteVersion {
4076
+ version: number;
4077
+ status: CaseQuoteVersionStatus;
4078
+ sentAt: string;
4079
+ validUntil: string;
4080
+ note: string | null;
4081
+ currency: string | null;
4082
+ lines: CaseQuoteLine[];
4083
+ deliveryCents: number | null;
4084
+ totalCents: number;
4085
+ answeredAt?: string;
4086
+ comment?: string;
4087
+ /** PDK-RENTAL-DEAL R7 — the anticipo this version asks for and the cancellation policy, as the customer reads them before accepting. */
4088
+ payment?: {
4089
+ anticipoPercent: number;
4090
+ anticipoCents: number;
4091
+ anticipoDueHours?: number;
4092
+ cancelPolicyText: string;
4093
+ };
4094
+ }
4095
+ /** PDK-RENTAL-DEAL R1 — what a customer may do on a quote's receipt: `cancel` is the case's own cancel (`receiptCancel`). */
4096
+ export type CaseQuoteAction = 'accept' | 'reject' | 'changes_requested' | 'cancel';
4097
+ /** PDK-RENTAL-DEAL R1 — `CaseReceipt.quote`. */
4098
+ export interface CaseReceiptQuote {
4099
+ status: CaseQuoteStatus;
4100
+ requestedAt: string;
4101
+ /** The version in force (waiting for the customer, else the latest); null before the first. */
4102
+ current: CaseReceiptQuoteVersion | null;
4103
+ /** Every version, oldest first (the current one included). */
4104
+ versions: CaseReceiptQuoteVersion[];
4105
+ agreedVersion: number | null;
4106
+ /** The lines the business has not priced yet («a cotizar»): catalog lines (`quoteOptions`) and the free ones the customer asked for. */
4107
+ pendingLines: Array<{
4108
+ key: string;
4109
+ title: string;
4110
+ qty: number;
4111
+ quoteOptions?: string[];
4112
+ }>;
4113
+ /** What the customer may do now. `accept` / `reject` / `changes_requested` only while a version waits and is valid. */
4114
+ actions: CaseQuoteAction[];
4115
+ }
4116
+ /** PDK-RENTAL-DEAL R1 — what `cases.sendQuote` sends. */
4117
+ export interface SendCaseQuoteInput {
4118
+ /**
4119
+ * The price of every line nobody priced (receipt `key`: a catalog line with a `quote` option, or a pending free line `off#n`); a priced
4120
+ * catalog line may be re-priced too. 400 `prices_missing` (with `lines`) when a pending one has none. `unitCents` is ONE unit over the
4121
+ * WHOLE range (`per: 'range'`, default) or for ONE period (`per: 'period'`, × the rental's periods); 0 = «gratis». `breakdown` adds up to `unitCents`.
4122
+ */
4123
+ prices: Array<{
4124
+ line: string;
4125
+ unitCents: number;
4126
+ per?: 'range' | 'period';
4127
+ note?: string;
4128
+ breakdown?: CaseLinePriceBreakdownItem[];
4129
+ }>;
4130
+ /** Lines the business adds (transporte ida/regreso, depósito, horas extra…), at most 20: `unitCents` × `qty`, × the periods unless `perTrip`. */
4131
+ extras?: Array<{
4132
+ title: string;
4133
+ qty?: number;
4134
+ unitCents: number;
4135
+ perTrip?: boolean;
4136
+ note?: string;
4137
+ }>;
4138
+ /** ISO instant with offset, in the future and at most 90 days ahead. Unanswered after it, the quote expires and the case ends `cancelled` (by `system`). */
4139
+ validUntil: string;
4140
+ /** Conditions (≤ 1000): what is included, cancellation, deposit. */
4141
+ note?: string;
4142
+ /** Who of the business sends it (default `{ id: 'business' }`). */
4143
+ by?: CaseLinePriceActor;
4144
+ /**
4145
+ * PDK-RENTAL-DEAL R7 — the payment plan of THIS version (anticipo %, deadline, cancellation policy); a version sent without one keeps the plan
4146
+ * the quote request came with. It is frozen on the case when the customer accepts this version. 400 `invalid_payment_plan` / `invalid_cancel_policy`.
4147
+ */
4148
+ paymentPlan?: CasePaymentPlanInput;
4149
+ }
4150
+ /** PDK-RENTAL-DEAL R1 — the answer to a quote version: `cases.receiptAnswerQuote` (the customer) / `cases.answerQuote` (the business, by phone). */
4151
+ export interface CaseQuoteAnswerInput {
4152
+ answer: 'accept' | 'reject' | 'changes_requested';
4153
+ /** ≤ 1000. Required with `changes_requested`; with `reject` it is the reason (kept as the case's note, ≤ 500). */
4154
+ comment?: string;
4155
+ /** The version being answered: 409 `quote_stale` when it was replaced meanwhile. */
4156
+ version?: number;
4157
+ }
3689
4158
  /** `PATCH /api/v1/cases/:id/rental` — reschedule or extend: the new range (you already hold it). */
3690
4159
  export interface UpdateCaseRentalInput {
3691
4160
  startsAt: string;
@@ -3717,7 +4186,7 @@ export interface MoveCaseSlotInput {
3717
4186
  }
3718
4187
  import type { AppBillingWebhookEvent } from './resources/billing';
3719
4188
  import type { ContactPropertiesPatch } from './resources/contacts';
3720
- export type AppCaseWebhookEventName = 'case.submitted' | 'case.state_changed' | 'case.closed' | 'case.customer_request' | 'case.payment_changed' | 'case.proposal' | 'case.change';
4189
+ export type AppCaseWebhookEventName = 'case.submitted' | 'case.state_changed' | 'case.closed' | 'case.customer_request' | 'case.payment_changed' | 'case.proposal' | 'case.change' | 'case.deposit_overdue';
3721
4190
  export type AppWebhookEventName = AppCaseWebhookEventName | 'conversation.message' | 'channel.status_changed' | 'billing.plan_changed' | 'billing.trial_ended';
3722
4191
  export interface AppWebhook {
3723
4192
  url: string;
@@ -3786,12 +4255,37 @@ export interface AppCaseWebhookEvent extends AppWebhookEventBase {
3786
4255
  paymentStatus?: CasePaymentStatus;
3787
4256
  previousPaymentStatus?: CasePaymentStatus;
3788
4257
  /** `case.proposal` (AGF-PDK-DISPATCH-PROPOSAL): the business sent or withdrew changes, or they were answered. */
3789
- proposal?: 'sent' | 'accepted' | 'withdrawn' | 'redone';
4258
+ proposal?: 'sent' | 'accepted' | 'withdrawn' | 'redone' | 'quote_sent' | 'quote_accepted' | 'quote_rejected' | 'quote_changes_requested' | 'quote_expired';
4259
+ /**
4260
+ * PDK-RENTAL-DEAL R1 — with `proposal: 'quote_*'` (a `case.proposal` event; no new event name to subscribe to): the quote version it is about.
4261
+ * `quote_sent` (the business sent version N), `quote_accepted` (the case is now `accepted`), `quote_rejected` (the case ended `rejected`),
4262
+ * `quote_changes_requested` (read the version's `comment`; the case stays open), `quote_expired` (the case ended `cancelled` by `system`).
4263
+ */
4264
+ quoteVersion?: number;
3790
4265
  /**
3791
4266
  * `case.change` (PDK-SERVICE-CHANGES S3): a change request was `requested` (by the customer or the App), `accepted` or `rejected`
3792
4267
  * by the business, or `withdrawn` by the customer. `by` is who did this move; the case keeps its state while a change waits.
3793
4268
  */
3794
4269
  change?: 'requested' | 'accepted' | 'rejected' | 'withdrawn';
4270
+ /**
4271
+ * PDK-RENTAL-DEAL R7 — `case.payment_changed` / `case.deposit_overdue` on a case paid in parts: what it has paid, still owes and is asked now,
4272
+ * and the payment entry this move recorded. Absent on every case paid as a whole.
4273
+ */
4274
+ paidCents?: number;
4275
+ balanceCents?: number;
4276
+ dueNowCents?: number;
4277
+ entry?: {
4278
+ id: string;
4279
+ kind: CasePaymentEntryKind;
4280
+ amountCents: number;
4281
+ status: CasePaymentEntryStatus;
4282
+ method: string | null;
4283
+ source: CasePaymentEntrySource;
4284
+ receiptNo: string;
4285
+ };
4286
+ /** `case.deposit_overdue` (once, when money came in but the anticipo is still short after its deadline): the anticipo still owed and its (passed) deadline. No state change: the team decides. */
4287
+ anticipoDueCents?: number;
4288
+ dueAt?: string;
3795
4289
  /** AGF-ORDER-ORIGIN-POS — where the case came from (cases from before carry none). */
3796
4290
  origin?: CaseOrigin;
3797
4291
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentforge-io/sdk-server",
3
- "version": "4.90.0",
3
+ "version": "4.91.0",
4
4
  "description": "Server-side SDK for backend apps integrating with AgentForge platform. Auth via ChatToken, ak_live_ API key or App secret (sk_live_), with App installations across tenants.",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",