diff --git a/CHANGELOG.md b/CHANGELOG.md index 93971bb..18643dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.0.4] - 2026-11-03 + +### Added + +- `coupons().validate()` checks a coupon code against a cart + (`POST /v1/sales/coupons/validate`) without redeeming it. New exported types + `Coupons`, `CouponCartItem`, and `CouponValidateOptions`. + +### Changed + +- **BREAKING:** `treatments().sync()` payment `card` sub-object: `bin` is + replaced by `last_4` (the card's last four digits, optional). + ## [0.0.3] - 2026-09-21 ### Changed diff --git a/README.md b/README.md index 51ab3e1..0c26414 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ per request throws that cache away. ## Resources `sessions`, `intakeSubmissions`, `carts`, `checkoutEvents`, `teleforms`, -`patients`, `opportunities`, `treatments`, `doctorsNetworks`, `channels`, +`patients`, `opportunities`, `treatments`, `coupons`, `doctorsNetworks`, `channels`, `products`, `categories`, `labTests`, `medications`, `shippings`, `verification`, `geo`. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fd0902b..f54624d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -14,7 +14,8 @@ For end-user usage see `docs/INTEGRATION_GUIDE.md`. │ AsterMDClient ← entry point, holds collaborators │ │ • config() │ │ • sessions() intakeSubmissions() teleforms() patients() │ -│ • opportunities() treatments() doctorsNetworks() channels() │ +│ • opportunities() treatments() coupons() doctorsNetworks() │ +│ • channels() │ │ • products() categories() labTests() medications() shippings() │ │ • verification() geo() │ └─────────────────────────────┬────────────────────────────────────────┘ @@ -80,6 +81,7 @@ src/ │ ├── patients.ts /v1/sales/patients/* │ ├── opportunities.ts /v1/sales/opportunities/* │ ├── treatments.ts /v1/sales/treatments/* +│ ├── coupons.ts /v1/sales/coupons/validate │ ├── doctors-networks.ts /v1/sales/doctors-networks/sync (+ client-side validation) │ ├── channels.ts /v1/sales/channels/* │ ├── products.ts /v1/sales/products/* diff --git a/docs/INTEGRATION_GUIDE.md b/docs/INTEGRATION_GUIDE.md index ae6ca00..0a112d8 100644 --- a/docs/INTEGRATION_GUIDE.md +++ b/docs/INTEGRATION_GUIDE.md @@ -35,7 +35,7 @@ The SDK is a thin, typed wrapper around the AsterMD public REST API. your app └── AsterMDClient ├── .sessions() .intakeSubmissions() .carts() .teleforms() - ├── .patients() .opportunities() .treatments() + ├── .patients() .opportunities() .treatments() .coupons() ├── .doctorsNetworks() .channels() └── catalog: .products() / .categories() / .labTests() .medications() / .shippings() @@ -592,7 +592,27 @@ a debug log. `{ session, orderIds, userAgent, utmSource?, payment?, verification? }`. `userAgent` is required - an empty or missing value throws `TypeError`. Use `sync()` to push an order settled in an external CRM into AsterMD after -settlement happens outside the SDK. +settlement happens outside the SDK. In `payment.card`, `type` and `exp` are +required and `last_4` (the card's last four digits) is optional. + +### `coupons()` + +| Method | HTTP | Path | +| ---------------------------------------------------------------- | ---- | ---------------------------- | +| `validate(options: CouponValidateOptions): Promise>` | POST | `/v1/sales/coupons/validate` | + +`CouponValidateOptions` is `{ code, items, patientId?, email?, opportunityId? }`. +`items` is the cart, main item first, 1 to 6 lines; each line is either +`{ plan_id, quantity }` or `{ product_id, variant_id, quantity }` (never both), +with `quantity` an integer from 1 to 999. Never send amounts - AsterMD prices the +cart itself. The optional identifiers name the shopper and are sent only when +provided; when several are given the server uses `patientId`, then `email`, then +`opportunityId`. Call it when the shopper applies a code, before creating the +payment. A check redeems nothing. `data()` holds `coupon_id`, `name`, +`discount_type`, `value`, `tiers`, `default_scope`, `gross_amount_cents`, +`discount_cents`, `amount_cents`, `currency` and the discounted `items`. An +unknown code throws `NotFoundError` (404); any other refusal throws +`ValidationError` (422). ### `doctorsNetworks()` diff --git a/package.json b/package.json index 3908cec..08f4eb5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@astermd-hq/sdk", - "version": "0.0.3", + "version": "0.0.4", "description": "Official Node.js SDK for the AsterMD order-flow API.", "keywords": [ "astermd", diff --git a/src/astermd-client.ts b/src/astermd-client.ts index 557bcf1..f4052a0 100644 --- a/src/astermd-client.ts +++ b/src/astermd-client.ts @@ -13,6 +13,7 @@ import { Carts } from './resource/carts.js'; import { Categories } from './resource/categories.js'; import { Channels } from './resource/channels.js'; import { CheckoutEvents } from './resource/checkout-events.js'; +import { Coupons } from './resource/coupons.js'; import { DoctorsNetworks } from './resource/doctors-networks.js'; import { Geo } from './resource/geo.js'; import { IntakeSubmissions } from './resource/intake-submissions.js'; @@ -72,7 +73,7 @@ export interface AsterMDClientOptions { } /** - * The SDK's entry point: one client, seventeen resources. + * The SDK's entry point: one client, eighteen resources. * * Construct it once at application start and share it. It holds the credentials, * caches the bearer token, and owns the single transport every resource dispatches @@ -123,6 +124,7 @@ export class AsterMDClient { #patients?: Patients; #opportunities?: Opportunities; #treatments?: Treatments; + #coupons?: Coupons; #doctorsNetworks?: DoctorsNetworks; #channels?: Channels; #products?: Products; @@ -261,6 +263,11 @@ export class AsterMDClient { return (this.#treatments ??= new Treatments(this.#transport)); } + /** Coupons - checking a code the shopper typed against their cart. */ + coupons(): Coupons { + return (this.#coupons ??= new Coupons(this.#transport)); + } + /** Doctors' networks - handing a case to the clinicians who review it. */ doctorsNetworks(): DoctorsNetworks { return (this.#doctorsNetworks ??= new DoctorsNetworks(this.#transport)); diff --git a/src/http/transport.ts b/src/http/transport.ts index 1700d57..07b4b8d 100644 --- a/src/http/transport.ts +++ b/src/http/transport.ts @@ -67,7 +67,7 @@ export interface TransportOptions { * building, body serialisation, dispatch through the {@link HttpClient} seam, * envelope decoding, and the mapping from HTTP status to error class. Resources * never see a `Request`, a `Response`, or a line of JSON - that separation is - * what keeps seventeen resource classes trivial and testable. + * what keeps eighteen resource classes trivial and testable. * * The 401-retry protocol is built in. On a 401 the transport calls * `onUnauthorized` once, which in the production wiring refreshes the token, and diff --git a/src/index.ts b/src/index.ts index c7cf1bf..8085265 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,6 +47,7 @@ export { type TreatmentIdVerificationOptions, type TreatmentIdVerificationMethod, } from './resource/treatments.js'; +export { Coupons, type CouponCartItem, type CouponValidateOptions } from './resource/coupons.js'; export { Channels } from './resource/channels.js'; export { DoctorsNetworks } from './resource/doctors-networks.js'; export { Categories } from './resource/categories.js'; diff --git a/src/resource/abstract-resource.ts b/src/resource/abstract-resource.ts index dc4786a..5586179 100644 --- a/src/resource/abstract-resource.ts +++ b/src/resource/abstract-resource.ts @@ -6,7 +6,7 @@ import type { Transport } from '../http/transport.js'; * Resource classes extend this and call `this.transport.send()` to dispatch every * outbound request. A resource never builds a request, touches a header, or * decodes JSON - all of that belongs to `Transport` alone. That is what keeps - * seventeen resource classes small enough to read at a glance and testable + * eighteen resource classes small enough to read at a glance and testable * without a network. */ export abstract class AbstractResource { diff --git a/src/resource/coupons.ts b/src/resource/coupons.ts new file mode 100644 index 0000000..293b3ab --- /dev/null +++ b/src/resource/coupons.ts @@ -0,0 +1,125 @@ +import type { Response as ApiResponse } from '../response.js'; +import type { Transport } from '../http/transport.js'; +import { AbstractResource } from './abstract-resource.js'; + +/** + * One cart line for {@link Coupons.validate}: either a subscription plan, or a + * product with its variant - never both. Never an amount; AsterMD prices the + * line itself. + */ +export type CouponCartItem = + | { + /** The subscription plan the line is sold on. Priced at the plan's first payment. */ + plan_id: string; + /** Units of the line, an integer from 1 to 999. */ + quantity: number; + } + | { + /** The AsterMD product. */ + product_id: string; + /** The product's variant; the product id again for a product without variants. */ + variant_id: string; + /** Units of the line, an integer from 1 to 999. */ + quantity: number; + }; + +/** Options for {@link Coupons.validate}. */ +export interface CouponValidateOptions { + /** The code the shopper typed. Not case sensitive. */ + code: string; + /** The cart, main item first. Between 1 and 6 lines. */ + items: CouponCartItem[]; + /** + * The AsterMD patient id of the shopper, when already a patient. Sent only + * when provided. When several of `patientId`, `email` and `opportunityId` are + * given, the server uses them in that order. + */ + patientId?: string; + /** The shopper's email; used when `patientId` is not sent. Sent only when provided. */ + email?: string; + /** + * The shopper's opportunity id; used when neither `patientId` nor `email` is + * sent. Sent only when provided. + */ + opportunityId?: string; +} + +/** + * Coupons - checking a code the shopper typed against their cart. + * + * Use this resource just before creating the payment: it tells the storefront + * whether a coupon code can be used on the current cart, and what it takes off. + * AsterMD prices the cart itself from its catalogue, so callers send product, + * variant or plan identifiers and quantities - never amounts. + * + * The call applies to a channel whose payment provider is a storefront gateway. + * Nothing is counted against the coupon by a check; redemption is recorded later, + * when the order is synced. + * + * ```ts + * const { discount_cents, amount_cents } = ( + * await client.coupons().validate<{ discount_cents: number; amount_cents: number }>({ + * code: 'WELCOME20', + * items: [{ plan_id: planId, quantity: 1 }], + * email: 'jane.doe@example.com', + * }) + * ).data(); + * ``` + */ +export class Coupons extends AbstractResource { + /** + * @param transport The shared transport. + */ + constructor(transport: Transport) { + super(transport); + } + + /** + * Checks a coupon code against a cart without redeeming it. + * + * Call this when the shopper applies a code at checkout, before the payment is + * created. The server validates the coupon's status, validity window, patient, + * products, budget, scope and redemption limits, and prices the cart. The check + * has no side effects. Inspect `data()` on the response for the coupon terms, + * the price before and after the discount, and the discounted lines. A shopper + * who is not a patient yet only fits a coupon open to anyone. + * + * @param options The code, the cart, and optionally who the shopper is + * (`patientId`, `email` or `opportunityId`). Each optional identifier is sent + * only when provided. + * @returns The coupon check; `data()` holds `coupon_id`, `name`, + * `discount_type`, `value`, `tiers`, `default_scope`, `gross_amount_cents`, + * `discount_cents`, `amount_cents`, `currency` and the discounted `items`. + * @throws {NotFoundError} If no coupon exists with this code. + * @throws {ValidationError} If the coupon cannot be used on this cart, or the + * cart cannot be priced. + * @throws {AuthenticationError} If the credentials are refused. + * @throws {ApiError} On any other non-2xx status. + * @throws {TransportError} If the request never completed. + */ + async validate>(options: CouponValidateOptions): Promise> { + const body: Record = { + code: options.code, + items: options.items, + }; + + if (options.patientId !== undefined) { + body.patient_id = options.patientId; + } + + if (options.email !== undefined) { + body.email = options.email; + } + + if (options.opportunityId !== undefined) { + body.opportunity_id = options.opportunityId; + } + + return await this.transport.send({ + service: 'sales', + method: 'POST', + path: '/coupons/validate', + body, + }); + } +} diff --git a/src/resource/treatments.ts b/src/resource/treatments.ts index 12fceac..768b871 100644 --- a/src/resource/treatments.ts +++ b/src/resource/treatments.ts @@ -16,8 +16,8 @@ export type TreatmentIdVerificationMethod = 'ssn' | 'dob' | 'cross_check' | 'doc export interface TreatmentCardOptions { /** The card network. */ type: TreatmentCardType; - /** The card's bank identification number, when available. */ - bin?: string; + /** The card's last four digits, when available. */ + last_4?: string; /** The card's expiry, in the format your integration agreed with AsterMD. */ exp: string; } diff --git a/test/astermd-client.spec.ts b/test/astermd-client.spec.ts index 3bc64bb..38393e8 100644 --- a/test/astermd-client.spec.ts +++ b/test/astermd-client.spec.ts @@ -59,7 +59,7 @@ describe('AsterMDClient construction', () => { }); describe('AsterMDClient resource accessors', () => { - it('exposes all seventeen resources', () => { + it('exposes all eighteen resources', () => { const { client } = makeClient(); const accessors = [ @@ -71,6 +71,7 @@ describe('AsterMDClient resource accessors', () => { 'patients', 'opportunities', 'treatments', + 'coupons', 'doctorsNetworks', 'channels', 'products', @@ -82,7 +83,7 @@ describe('AsterMDClient resource accessors', () => { 'geo', ] as const; - expect(accessors).toHaveLength(17); + expect(accessors).toHaveLength(18); for (const accessor of accessors) { expect(typeof client[accessor]).toBe('function'); diff --git a/test/index.spec.ts b/test/index.spec.ts index 22a1a11..c34d4b1 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -6,6 +6,7 @@ describe('public surface', () => { const expected = [ 'AsterMDClient', 'Config', + 'Coupons', 'Response', 'AbstractResource', 'Sessions', diff --git a/test/resource/coupons.spec.ts b/test/resource/coupons.spec.ts new file mode 100644 index 0000000..33020ad --- /dev/null +++ b/test/resource/coupons.spec.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest'; +import { NotFoundError, ValidationError } from '../../src/errors/index.js'; +import { Coupons } from '../../src/resource/coupons.js'; +import { makeHarness } from '../support/harness.js'; + +const PLAN_ITEM = { plan_id: '6a01b2c3d4e5f6a7b8c9d0f1', quantity: 1 }; +const PRODUCT_ITEM = { + product_id: '6a01b2c3d4e5f6a7b8c9d0a1', + variant_id: '6a01b2c3d4e5f6a7b8c9d0a2', + quantity: 2, +}; + +const RESULT = { + coupon_id: '6a01b2c3d4e5f6a7b8c9d0f9', + name: 'Welcome 20% off', + discount_type: 'percent', + value: 20, + tiers: [], + default_scope: { from_occurrence_index: 0, occurrence_count: 3 }, + gross_amount_cents: 9900, + discount_cents: 1980, + amount_cents: 7920, + currency: 'usd', + items: [], +}; + +describe('Coupons.validate', () => { + it('posts code and items to coupons/validate', async () => { + const { transport, http } = makeHarness(); + http.enqueueJson(200, { success: true, message: 'ok', data: RESULT }); + + const response = await new Coupons(transport).validate({ + code: 'WELCOME20', + items: [PLAN_ITEM, PRODUCT_ITEM], + }); + + const request = http.lastRequest(); + expect(request.url).toBe('https://api.astermd.com/v1/sales/coupons/validate'); + expect(request.method).toBe('POST'); + expect(request.headers.authorization).toBe('Bearer test-jwt'); + expect(request.headers['content-type']).toBe('application/json'); + expect(JSON.parse(request.body)).toEqual({ code: 'WELCOME20', items: [PLAN_ITEM, PRODUCT_ITEM] }); + expect(response.data()).toEqual(RESULT); + }); + + it('omits patient_id, email and opportunity_id when absent', async () => { + const { transport, http } = makeHarness(); + http.enqueueJson(200, { success: true, message: 'ok', data: RESULT }); + + await new Coupons(transport).validate({ code: 'WELCOME20', items: [PLAN_ITEM] }); + + const body = JSON.parse(http.lastRequest().body) as Record; + expect(Object.keys(body).sort()).toEqual(['code', 'items']); + }); + + it('sends each optional identifier when provided', async () => { + const { transport, http } = makeHarness(); + http.enqueueJson(200, { success: true, message: 'ok', data: RESULT }); + + await new Coupons(transport).validate({ + code: 'WELCOME20', + items: [PLAN_ITEM], + patientId: '6a7f1c2d3e4b5a6978123457', + email: 'jane.doe@example.com', + opportunityId: '6a7f1c2d3e4b5a6978123458', + }); + + expect(JSON.parse(http.lastRequest().body)).toEqual({ + code: 'WELCOME20', + items: [PLAN_ITEM], + patient_id: '6a7f1c2d3e4b5a6978123457', + email: 'jane.doe@example.com', + opportunity_id: '6a7f1c2d3e4b5a6978123458', + }); + }); + + it('sends only the identifier that was provided', async () => { + const { transport, http } = makeHarness(); + http.enqueueJson(200, { success: true, message: 'ok', data: RESULT }); + + await new Coupons(transport).validate({ code: 'X', items: [PLAN_ITEM], email: 'jane.doe@example.com' }); + + expect(JSON.parse(http.lastRequest().body)).toEqual({ + code: 'X', + items: [PLAN_ITEM], + email: 'jane.doe@example.com', + }); + }); + + it('maps 404 for an unknown code to NotFoundError', async () => { + const { transport, http } = makeHarness(); + http.enqueueJson(404, { success: false, message: 'There is no coupon with this code' }); + + const failure = new Coupons(transport).validate({ code: 'NOPE', items: [PLAN_ITEM] }); + + await expect(failure).rejects.toBeInstanceOf(NotFoundError); + await expect(failure).rejects.toThrow('There is no coupon with this code'); + }); + + it('maps 422 for any other coupon refusal to ValidationError', async () => { + const { transport, http } = makeHarness(); + http.enqueueJson(422, { success: false, message: 'The coupon has expired' }); + + const failure = new Coupons(transport).validate({ code: 'OLD', items: [PLAN_ITEM] }); + + await expect(failure).rejects.toBeInstanceOf(ValidationError); + await expect(failure).rejects.toThrow('The coupon has expired'); + }); +}); diff --git a/test/resource/treatments.spec.ts b/test/resource/treatments.spec.ts index 209aa10..62891e7 100644 --- a/test/resource/treatments.spec.ts +++ b/test/resource/treatments.spec.ts @@ -174,7 +174,7 @@ describe('Treatments.sync', () => { preAuth: true, preAuthQa: false, preAuthAmount: 100.99, - card: { type: 'visa', bin: '411111', exp: '12/29' }, + card: { type: 'visa', last_4: '4242', exp: '12/29' }, }, }); @@ -184,7 +184,7 @@ describe('Treatments.sync', () => { pre_auth: true, pre_auth_qa: false, pre_auth_amount: 100.99, - card: { type: 'visa', bin: '411111', exp: '12/29' }, + card: { type: 'visa', last_4: '4242', exp: '12/29' }, }, }); });