Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
4 changes: 3 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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() │
└─────────────────────────────┬────────────────────────────────────────┘
Expand Down Expand Up @@ -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/*
Expand Down
24 changes: 22 additions & 2 deletions docs/INTEGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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<Response<T>>` | 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()`

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
9 changes: 8 additions & 1 deletion src/astermd-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -123,6 +124,7 @@ export class AsterMDClient {
#patients?: Patients;
#opportunities?: Opportunities;
#treatments?: Treatments;
#coupons?: Coupons;
#doctorsNetworks?: DoctorsNetworks;
#channels?: Channels;
#products?: Products;
Expand Down Expand Up @@ -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));
Expand Down
2 changes: 1 addition & 1 deletion src/http/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
2 changes: 1 addition & 1 deletion src/resource/abstract-resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
125 changes: 125 additions & 0 deletions src/resource/coupons.ts
Original file line number Diff line number Diff line change
@@ -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<T = Record<string, unknown>>(options: CouponValidateOptions): Promise<ApiResponse<T>> {
const body: Record<string, unknown> = {
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<T>({
service: 'sales',
method: 'POST',
path: '/coupons/validate',
body,
});
}
}
4 changes: 2 additions & 2 deletions src/resource/treatments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
5 changes: 3 additions & 2 deletions test/astermd-client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -71,6 +71,7 @@ describe('AsterMDClient resource accessors', () => {
'patients',
'opportunities',
'treatments',
'coupons',
'doctorsNetworks',
'channels',
'products',
Expand All @@ -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');
Expand Down
1 change: 1 addition & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ describe('public surface', () => {
const expected = [
'AsterMDClient',
'Config',
'Coupons',
'Response',
'AbstractResource',
'Sessions',
Expand Down
Loading
Loading