@agentforge-io/sdk-server 4.90.0 → 4.92.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,15 +1,17 @@
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';
10
12
  export { APP_WEBHOOK_HEADERS, TOOL_CALLBACK_HEADERS, ToolCallbackSignatureError, signToolCallbackPayload, verifyAppWebhook, verifyToolCallbackSignature, } from './webhooks';
11
13
  export { WebhookResource, type SetAppWebhookInput } from './resources/webhook';
12
- export type { AppWebhook, AppWebhookEvent, AppWebhookEventName, AppCaseWebhookEvent, AppCaseWebhookEventName, AppConversationMessageWebhookEvent, AppChannelStatusWebhookEvent, AgentMe, AgentSummary, AppUserConnectorStatus, ApprovalCopyBundle, ChannelContext, ChatStreamChunk, ChatStreamEvent, ChatTokenRecord, ConnectorDefaultsResult, ConnectorDefaultsSource, ConnectorResourceItem, ConnectorStatus, ConnectorToolInfo, ConversationHistory, ConversationStatus, CreateAgentInput, CreateClickupTaskInput, CreateClickupTaskResult, ExternalToolSummary, IssueChatTokenInput, ListAgentsResult, ListConnectorResourcesResult, McpServerConfig, MessageRecord, MessageRole, PublicAppBranding, PublicProfileBlock, PublicProfileTemplate, PublicTeamLanding, CreateTeamInput, UpdateTeamInput, TeamSummary, TeamDetail, TeamTheme, ThemedColor, TeamBusinessHours, TeamWeekday, TeamProfileBlock, ProfileBlockPlacement, ProfileBlockPosition, CatalogBlockPreview, ServiceCta, ServiceCtaAction, CatalogServicesBlockConfig, AppInstallation, TemplateConfigField, TemplateSummary, TemplateDetail, TemplateInstallStats, TemplatePublisher, TemplateAuthor, AppTemplatePolicy, TemplateCategoryRef, MarketplaceCategory, MarketplaceCategoryGroup, MarketplaceLocale, TemplateInstallResult, CheckSystemTemplateResult, SetSystemAppProfileResult, SystemAppProfileView, TemplatePublishIssue, UpsertSystemTemplateInput, UpsertSystemTemplateResult, TemplateReview, TemplateRatingSummary, TemplateReviewsPage, BusinessReview, BusinessReviewsPage, ProductRatingSummary, ProductReview, ProductReviewOwner, ProductReviewsPage, ProductReviewsOwnerPage, ListProductReviewsInput, ListProductReviewsForOwnerInput, HideProductReviewInput, ProductLikeResult, ReceiptReviewable, ReceiptReviewables, SaveReceiptReviewInput, ListTemplateReviewsInput, SaveTemplateReviewInput, TemplateReportKind, CreateTemplateReportInput, TenantConfigEntry, Place, PlaceSuggestion, SearchPlacesInput, AutocompletePlacesInput, PlacesScope, CaseField, CaseBusinessState, CaseType, CaseState, CaseStateType, CasePayment, CasePaymentAccount, CasePaymentStatus, CaseReceiptPayment, CaseDestination, CaseView, CaseContactLink, CaseStateStep, CreateDirectOrderInput, CreateOpenOrderInput, CaseOffCatalogLine, CaseOffCatalogView, ConfirmCaseLineInput, SetCaseLinePriceInput, CaseLinePrices, CaseChangeInput, CaseChangeKind, CaseChangeLine, CaseChangeReason, CasePendingChange, CaseLinePriceEntry, CaseLinePriceHistoryEntry, CaseLinePriceSet, CaseLinePriceActor, CaseLinePriceBreakdownItem, CreateOffCatalogLineInput, OpenOrderFreeLine, OpenOrderLineMark, OpenOrderPayment, CreateDirectBookingInput, MoveCaseSlotInput, CaseSlot, CatalogAttendedAt, CatalogBookingRule, CaseOrigin, CaseOriginChannel, DirectOrderForm, DirectPaymentOption, CaseClosingMethod, CaseClosingOrder, CaseClosingReport, CaseClosingReceivables, CaseAccount, SetOnAccountInput, SetOnAccountResult, CaseReportPage, CaseReceipt, CaseReceiptLine, CaseProposal, CaseProposalAnswer, CaseProposalChange, CaseProposalInput, ListCasesInput, AddressValue, DeliveryLocalPricing, DeliverySettings, PaymentMethodKind, PaymentSettings, PaymentSettingsInput, PaymentAccount, PaymentCountry, PaymentFieldDef, PaymentMethodDef, StructuredConfigInput, StructuredConfigEntry, DeliveryQuoteStatus, DeliveryQuoteInput, DeliveryPricePreview, DeliveryPricingPreview, DeliveryPricingPreviewInput, DeliveryRoute, DeliveryRouteInput, DeliveryQuote, AppSelf, AppOwner, AppSelfConnector, AppSelfConnectors, AppSelfConnectorTools, AppSelfConnectorToolsResponse, RegisterToolInput, RegisterToolsInput, BusinessRoleEntry, Catalog, CatalogCheckoutCta, CatalogCategory, CatalogProduct, CatalogProductPhoto, CatalogProductKind, CatalogProductStatus, CatalogPriceKind, CatalogAvailability, CatalogLockableField, CatalogProductPage, UpsertCatalogInput, CreateCatalogCategoryInput, ListCatalogCategoriesInput, UpdateCatalogCategoryInput, CreateCatalogProductInput, UpdateCatalogProductInput, ListCatalogProductsInput, CatalogPhotoUploadTarget, SignCatalogPhotoUploadInput, AttachCatalogPhotoInput, AttachCatalogCategoryImageInput, CatalogImportItem, CatalogImportPreview, CatalogImportApplyResult, CatalogFileMapping, CatalogFilePlan, CatalogFilePreview, CatalogFileApplyResult, CatalogFileInput, CatalogFilePreviewInput, CatalogMenuItem, CatalogMenuRead, CatalogMenuReadInput, CatalogMenuAttachInput, CatalogMenuChatFile, CatalogMenuKeepInSyncInput, CatalogMenuKeepInSyncResult, CatalogOption, CatalogOptionGroup, SaveCatalogOptionGroupInput, CatalogOptionChoice, CatalogOptionChange, CatalogOptionChangesPlan, CatalogUnit, SaveCatalogUnitInput, CatalogSaleRule, CatalogFileApplyInput, CatalogFileErrorCode, CatalogImportSourceStatus, CatalogImportColumnMapping, CatalogImportRunResult, CatalogImportSource, CreateCatalogImportSourceInput, UpdateCatalogImportSourceInput, PreviewCatalogImportSourceInput, CatalogImportSourcePreview, CatalogSheetTab, CatalogTemplateSheet, CreateCatalogTemplateSheetInput, ReferenceMatchItemInput, ReferenceMatchDecisionKind, ReferenceMatchCandidate, ReferenceMatchDecision, ReferenceMatchInput, ReferenceMatchResult, ReferenceProductInput, ReferenceProductsBulkInput, ReferenceProductsBulkResult, ReferenceProduct, ListReferenceProductsInput, ReferenceProductPage, GoogleCalendarAccount, GoogleCalendarEventInput, GoogleCalendarUpsertResult, GoogleCalendarBusyInput, GoogleCalendarBusyResult, GoogleSheetsPickerInput, GoogleSheetsPickerSession, GoogleSheetsPickerErrorCode, GoogleSheetsPickerResult, RegisterToolsResult, ToolCallbackPayload, ToolCallRecord, ToolPermission, ToolPermissionMode, TokenUsage, TenantSecretEntry, UpdateAgentInput, InboxThreadMode, InboxMessageDirection, InboxMessageSource, InboxMessageType, InboxThreadCustomerProfileView, InboxThreadView, InboxMessageView, SupportKpiTotals, SupportKpiResponse, AgentAttentionLogRow, } from './types';
14
+ export type { AppWebhook, AppWebhookEvent, AppWebhookEventName, AppCaseWebhookEvent, AppCaseWebhookEventName, AppConversationMessageWebhookEvent, AppChannelStatusWebhookEvent, AgentMe, AgentSummary, AppUserConnectorStatus, ApprovalCopyBundle, ChannelContext, ChatStreamChunk, ChatStreamEvent, ChatTokenRecord, ConnectorDefaultsResult, ConnectorDefaultsSource, ConnectorResourceItem, ConnectorStatus, ConnectorToolInfo, ConversationHistory, ConversationStatus, CreateAgentInput, CreateClickupTaskInput, CreateClickupTaskResult, ExternalToolSummary, IssueChatTokenInput, ListAgentsResult, ListConnectorResourcesResult, McpServerConfig, MessageRecord, MessageRole, PublicAppBranding, PublicProfileBlock, PublicProfileTemplate, PublicTeamLanding, CreateTeamInput, UpdateTeamInput, TeamSummary, TeamDetail, TeamTheme, ThemedColor, TeamBusinessHours, TeamWeekday, TeamProfileBlock, ProfileBlockPlacement, ProfileBlockPosition, CatalogBlockPreview, ServiceCta, ServiceCtaAction, CatalogServicesBlockConfig, AppInstallation, TemplateConfigField, TemplateSummary, TemplateDetail, TemplateInstallStats, TemplatePublisher, TemplateAuthor, AppTemplatePolicy, TemplateCategoryRef, MarketplaceCategory, MarketplaceCategoryGroup, MarketplaceLocale, TemplateInstallResult, CheckSystemTemplateResult, SetSystemAppProfileResult, SystemAppProfileView, TemplatePublishIssue, UpsertSystemTemplateInput, UpsertSystemTemplateResult, TemplateReview, TemplateRatingSummary, TemplateReviewsPage, BusinessReview, BusinessReviewsPage, ProductRatingSummary, ProductReview, ProductReviewOwner, ProductReviewsPage, ProductReviewsOwnerPage, ListProductReviewsInput, ListProductReviewsForOwnerInput, HideProductReviewInput, ProductLikeResult, ReceiptReviewable, ReceiptReviewables, SaveReceiptReviewInput, ListTemplateReviewsInput, SaveTemplateReviewInput, TemplateReportKind, CreateTemplateReportInput, TenantConfigEntry, Place, PlaceSuggestion, SearchPlacesInput, AutocompletePlacesInput, PlacesScope, CaseField, CaseBusinessState, CaseType, CaseState, CaseStateType, CasePayment, CasePaymentAccount, CasePaymentStatus, CaseReceiptPayment, CaseDestination, CaseView, CaseContactLink, CaseStateStep, CreateDirectOrderInput, CreateOpenOrderInput, CaseOffCatalogLine, CaseOffCatalogView, ConfirmCaseLineInput, SetCaseLinePriceInput, CaseLinePrices, CaseChangeInput, CaseChangeKind, CaseChangeLine, CaseChangeReason, CasePendingChange, CaseLinePriceEntry, CaseLinePriceHistoryEntry, CaseLinePriceSet, CaseLinePriceActor, CaseLinePriceBreakdownItem, CreateOffCatalogLineInput, OpenOrderFreeLine, OpenOrderLineMark, OpenOrderPayment, CreateDirectBookingInput, MoveCaseSlotInput, CaseSlot, CatalogAttendedAt, CatalogBookingRule, CaseOrigin, CaseOriginChannel, DirectOrderForm, DirectPaymentOption, CaseClosingMethod, CaseClosingOrder, CaseClosingReport, CaseClosingReceivables, CaseAccount, SetOnAccountInput, SetOnAccountResult, CaseReportPage, CaseReceipt, CaseReceiptLine, CaseProposal, CaseProposalAnswer, CaseProposalChange, CaseProposalInput, ListCasesInput, AddressValue, DeliveryLocalPricing, DeliverySettings, PaymentMethodKind, PaymentSettings, PaymentSettingsInput, PaymentAccount, PaymentCountry, PaymentFieldDef, PaymentMethodDef, StructuredConfigInput, StructuredConfigEntry, DeliveryQuoteStatus, DeliveryQuoteInput, DeliveryPricePreview, DeliveryPricingPreview, DeliveryPricingPreviewInput, DeliveryRoute, DeliveryRouteInput, DeliveryQuote, AppSelf, AppOwner, AppSelfConnector, AppSelfConnectors, AppSelfConnectorTools, AppSelfConnectorToolsResponse, RegisterToolInput, RegisterToolsInput, BusinessRoleEntry, Catalog, CatalogCheckoutCta, CatalogCategory, CatalogProduct, CatalogProductPhoto, CatalogProductKind, CatalogProductStatus, CatalogPriceKind, CatalogAvailability, CatalogLockableField, CatalogProductPage, UpsertCatalogInput, CreateCatalogCategoryInput, ListCatalogCategoriesInput, UpdateCatalogCategoryInput, CreateCatalogProductInput, UpdateCatalogProductInput, ListCatalogProductsInput, CatalogPhotoUploadTarget, SignCatalogPhotoUploadInput, CatalogPhotoStudioMode, CatalogPhotoStudioAngle, CatalogPhotoStudioStatus, CatalogPhotoStudioRequest, CatalogPhotoStudioQuote, CreateCatalogPhotoStudioJobInput, CatalogPhotoStudioJob, CatalogPhotoStudioCreated, CatalogPhotoStudioAttachResult, CatalogPhotoStudioSkill, CatalogPhotoStudioOutput, CatalogPhotoStudioPalette, CatalogPhotoStudioSkillInfo, CatalogPhotoStudioSkills, AttachCatalogPhotoInput, AttachCatalogCategoryImageInput, CatalogImportItem, CatalogImportPreview, CatalogImportApplyResult, CatalogFileMapping, CatalogFilePlan, CatalogFilePreview, CatalogFileApplyResult, CatalogFileInput, CatalogFilePreviewInput, CatalogMenuItem, CatalogMenuRead, CatalogMenuReadInput, CatalogMenuAttachInput, CatalogMenuChatFile, CatalogMenuKeepInSyncInput, CatalogMenuKeepInSyncResult, CatalogOption, CatalogOptionGroup, SaveCatalogOptionGroupInput, CatalogOptionChoice, CatalogOptionChange, CatalogOptionChangesPlan, CatalogUnit, SaveCatalogUnitInput, CatalogSaleRule, CatalogFileApplyInput, CatalogFileErrorCode, CatalogImportSourceStatus, CatalogImportColumnMapping, CatalogImportRunResult, CatalogImportSource, CreateCatalogImportSourceInput, UpdateCatalogImportSourceInput, PreviewCatalogImportSourceInput, CatalogImportSourcePreview, CatalogSheetTab, CatalogTemplateSheet, CreateCatalogTemplateSheetInput, ReferenceMatchItemInput, ReferenceMatchDecisionKind, ReferenceMatchCandidate, ReferenceMatchDecision, ReferenceMatchInput, ReferenceMatchResult, ReferenceProductInput, ReferenceProductsBulkInput, ReferenceProductsBulkResult, ReferenceProduct, ListReferenceProductsInput, ReferenceProductPage, GoogleCalendarAccount, GoogleCalendarEventInput, GoogleCalendarUpsertResult, GoogleCalendarBusyInput, GoogleCalendarBusyResult, GoogleSheetsPickerInput, GoogleSheetsPickerSession, GoogleSheetsPickerErrorCode, GoogleSheetsPickerResult, RegisterToolsResult, ToolCallbackPayload, ToolCallRecord, ToolPermission, ToolPermissionMode, TokenUsage, TenantSecretEntry, UpdateAgentInput, InboxThreadMode, InboxMessageDirection, InboxMessageSource, InboxMessageType, InboxThreadCustomerProfileView, InboxThreadView, InboxMessageView, SupportKpiTotals, SupportKpiResponse, AgentAttentionLogRow, } from './types';
13
15
  export { AgentsResource } from './resources/agents';
14
16
  export { AnalyticsResource } from './resources/analytics';
15
17
  export type { GetSupportKpisInput, GetAgentAttentionLogInput, } from './resources/analytics';
@@ -35,7 +37,7 @@ export type { AppFileKind, SignAppFileInput, AppFileUploadTarget } from './resou
35
37
  export { DeliveryResource } from './resources/delivery';
36
38
  export { CasesResource } from './resources/cases';
37
39
  export { BusinessRolesResource } from './resources/business-roles';
38
- export { CatalogResource, CatalogCategoriesResource, CatalogProductsResource, CatalogProductReviewsResource, CatalogProductLikesResource, CatalogReviewsResource, CatalogPhotosResource, CatalogImportResource, CatalogFileImportResource, CatalogMenuImportResource, CatalogOptionGroupsResource, CatalogUnitsResource, CatalogSourcesResource, AgentForgeCatalogImportLimitError, CATALOG_IMPORT_MAX_ITEMS, } from './resources/catalog';
40
+ export { CatalogResource, CatalogCategoriesResource, CatalogProductsResource, CatalogProductReviewsResource, CatalogProductLikesResource, CatalogReviewsResource, CatalogPhotosResource, CatalogPhotoStudioResource, CatalogImportResource, CatalogFileImportResource, CatalogMenuImportResource, CatalogOptionGroupsResource, CatalogUnitsResource, CatalogSourcesResource, AgentForgeCatalogImportLimitError, CATALOG_IMPORT_MAX_ITEMS, } from './resources/catalog';
39
41
  export type { ListThreadsOptions, ListNewestMessagesOptions, NewestMessagesPage, SendMessageInput, InboxOperatorAttachment, InboxAttachmentKind, AssignThreadInput, UnassignThreadInput, SetThreadModeInput, CloseThreadInput, } from './resources/inbox';
40
42
  export { ProvisioningResource } from './resources/provisioning';
41
43
  export type { ProvisionedTenant, ProvisionedApp, ProvisionedTeam, } from './resources/provisioning';
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.CatalogPhotoStudioResource = 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; } });
@@ -110,6 +112,7 @@ Object.defineProperty(exports, "CatalogProductReviewsResource", { enumerable: tr
110
112
  Object.defineProperty(exports, "CatalogProductLikesResource", { enumerable: true, get: function () { return catalog_1.CatalogProductLikesResource; } });
111
113
  Object.defineProperty(exports, "CatalogReviewsResource", { enumerable: true, get: function () { return catalog_1.CatalogReviewsResource; } });
112
114
  Object.defineProperty(exports, "CatalogPhotosResource", { enumerable: true, get: function () { return catalog_1.CatalogPhotosResource; } });
115
+ Object.defineProperty(exports, "CatalogPhotoStudioResource", { enumerable: true, get: function () { return catalog_1.CatalogPhotoStudioResource; } });
113
116
  Object.defineProperty(exports, "CatalogImportResource", { enumerable: true, get: function () { return catalog_1.CatalogImportResource; } });
114
117
  Object.defineProperty(exports, "CatalogFileImportResource", { enumerable: true, get: function () { return catalog_1.CatalogFileImportResource; } });
115
118
  Object.defineProperty(exports, "CatalogMenuImportResource", { enumerable: true, get: function () { return catalog_1.CatalogMenuImportResource; } });
@@ -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: