@agentforge-io/sdk-server 4.89.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.
@@ -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
@@ -188,6 +268,54 @@ class CasesResource {
188
268
  async receiptRedoProposal(token) {
189
269
  return this.client.request('POST', `/api/v1/cases/receipts/${encodeURIComponent(token)}/proposal/redo`, {});
190
270
  }
271
+ /**
272
+ * `POST /api/v1/cases/receipts/:token/change` — PDK-SERVICE-CHANGES S3: the customer asks to change their request
273
+ * (replaces `receiptReopen` for the new flow). The change is kept APART (`pendingChange`): the case keeps its state, holds,
274
+ * payment and progress until the business answers (`answerChange`); nothing is held or charged before. It is validated like a
275
+ * direct order (products exist and are sellable, options, the booking's/rental's shape) and priced — `pendingChange.previewTotalCents`
276
+ * (line prices, rental rates, delivery) — so you can show the new total. One at a time: a new request replaces the pending one.
277
+ *
278
+ * Read `receipt.changeAllowed` / `changeReason` / `changeKind` / `changeUntil` / `pendingChange` first to render the right form:
279
+ * `items` (the cart: send the FULL new `lines`), `service` (answers + address), `booking` (`slot`), `rental` (`rental`, and `lines`
280
+ * for the units), `mixed`. Rules per kind (409 with `code`): `change_window_closed` — products until confirmed, a quote until the
281
+ * customer accepted a price, a service until it is in progress, a booking/rental until `changeWindowHours` (type setting, default 24)
282
+ * before it starts —; `case_closed`; `case_not_sent`; `change_pending` (a change from the business waits); `not_enough_stock`.
283
+ * 400 on a bad body (`code: 'invalid_change' | 'empty_change' | 'product_not_available' | 'not_a_booking' | 'not_a_rental' …`).
284
+ * You own availability of a booking's time / a rental's range: check it before sending. Returns the receipt.
285
+ */
286
+ async receiptRequestChange(token, input) {
287
+ return this.client.request('POST', `/api/v1/cases/receipts/${encodeURIComponent(token)}/change`, input);
288
+ }
289
+ /**
290
+ * `DELETE /api/v1/cases/receipts/:token/change` — the customer takes their pending change back (or leaves without sending: the
291
+ * case was never touched, so nothing needs undoing). 409 `no_pending_change`, or `change_pending` when the change is the business's.
292
+ */
293
+ async receiptWithdrawChange(token) {
294
+ return this.client.request('DELETE', `/api/v1/cases/receipts/${encodeURIComponent(token)}/change`);
295
+ }
296
+ /**
297
+ * `POST /api/v1/cases/:id/change` — PDK-SERVICE-CHANGES S3: the App asks a change on behalf of the customer (the same body as
298
+ * `receiptRequestChange`). It is kept apart (`pendingChange.by: 'business'`) until `answerChange`; the business is not held to
299
+ * the customer's window (a closed case still answers 409). Returns the case.
300
+ */
301
+ async requestChange(caseId, input) {
302
+ return this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/change`, input);
303
+ }
304
+ /**
305
+ * `POST /api/v1/cases/:id/change/answer` — the business answers the pending change.
306
+ *
307
+ * `accept: true` applies it in one go: the lines' holds are swapped (old released, new taken, discounted too when the business
308
+ * already took the order — a stock failure answers 409 `not_enough_stock` and leaves the case exactly as it was, still pending),
309
+ * the answers/address/time/range are replaced, line prices follow the lines that survive (a removed line's price is unset, its
310
+ * history kept as `outcome: 'removed'`), and the receipt is re-issued (revision + 1). The payment is kept; when the total moved
311
+ * after it was reported or made, `payment.differenceCents` says what is still owed (+) or given back (−) until the business
312
+ * settles it. The case state is NOT reset (no `submitted` again) and its progress stays. A price quote waiting is withdrawn.
313
+ * `accept: false` discards it and tells the customer (`note` goes with it). Emits `case.change` (`accepted` / `rejected`).
314
+ * 409 `no_pending_change`. Returns the case.
315
+ */
316
+ async answerChange(caseId, input) {
317
+ return this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/change/answer`, { accept: input.accept, ...(input.note ? { note: input.note } : {}) });
318
+ }
191
319
  /**
192
320
  * `POST /api/v1/cases/receipts/:token/cancel` — «Cancelar pedido»: the customer cancels from
193
321
  * the receipt while the order is a draft (sent, accepted, being prepared or redone, changes
@@ -204,12 +332,19 @@ class CasesResource {
204
332
  * PDK-OFF-CATALOG: moving to a confirmed state (`confirmed`, ready, out for delivery, `completed`) is refused with
205
333
  * 400 `code: 'lines_pending'` while a free line is still pending (`offCatalog.pendingCount > 0`): confirm them
206
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.
207
337
  */
208
338
  async transition(caseId, state, opts = {}) {
209
- return this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/transition`, {
210
- state,
211
- ...(opts.note ? { note: opts.note } : {}),
212
- });
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
+ }
213
348
  }
214
349
  /**
215
350
  * `GET /api/v1/cases/receipts/:token` — AGF-CASE-RECEIPT: the receipt behind a
@@ -288,9 +423,17 @@ class CasesResource {
288
423
  * `confirmation: 'instant'`. 400 for a bad range (end ≤ start, > 366 days, a count below what the range spans) or a
289
424
  * line with `variantId`/`amountCents`; 409 when a product lacks stock. A retried `idempotencyKey` returns the same rental.
290
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`.
291
429
  */
292
430
  async createDirectRental(input) {
293
- 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
+ }
294
437
  }
295
438
  /**
296
439
  * `PATCH /api/v1/cases/:id/rental` — PDK-RENTAL-AVAILABILITY: reschedule or extend a rental you already moved in your
@@ -393,7 +536,94 @@ class CasesResource {
393
536
  * ≤ 700 KB). The payment waits for the business to confirm it.
394
537
  */
395
538
  async receiptReportPayment(token, input) {
396
- 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
+ }
397
627
  }
398
628
  /**
399
629
  * `GET /api/v1/cases/receipts/:token/image.png` — the receipt as a PNG: