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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,20 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [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.

### Changed

- `treatments()->sync()` payment `card` sub-object: `bin` is replaced by
`last_4` (the card's last four digits).

## [0.0.3] - 2026-09-21

### Added
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ manager — never commit it.

## Resources

`sessions`, `intakeSubmissions`, `carts`, `checkoutEvents`, `teleforms`,
`sessions`, `intakeSubmissions`, `carts`, `coupons`, `checkoutEvents`, `teleforms`,
`patients`, `opportunities`, `treatments`, `doctorsNetworks`, `channels`,
`products`, `categories`, `labTests`, `medications`, `shippings`,
`verification`, `geo`.
Expand Down
1 change: 1 addition & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ src/
│ ├── Sessions.php /v1/sales/sessions/*
│ ├── IntakeSubmissions.php /v1/sales/intake-submissions/*
│ ├── Carts.php /v1/sales/carts/*
│ ├── Coupons.php /v1/sales/coupons/*
│ ├── CheckoutEvents.php /v1/sales/checkout-events/*
│ ├── Teleforms.php /v1/sales/teleforms/*
│ ├── Patients.php /v1/sales/patients/*
Expand Down
12 changes: 10 additions & 2 deletions docs/INTEGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ The SDK is a thin, typed wrapper around the AsterMD public REST API.
```
your app
└── AsterMDClient
├── ->sessions() ->intakeSubmissions() ->carts() ->teleforms()
├── ->patients() ->opportunities() ->treatments()
├── ->sessions() ->intakeSubmissions() ->carts() ->coupons()
├── ->patients() ->opportunities() ->treatments() ->teleforms()
├── ->doctorsNetworks() ->channels()
└── catalog: ->products() / ->categories() / ->labTests()
->medications() / ->shippings()
Expand Down Expand Up @@ -495,6 +495,14 @@ Uploaded bytes are **PHI**. The SDK never writes them to a debug log, even with

`items` is a list of items. Each item: `product_id` (string), `name` (string), `qty` (int) — all required. The journey event and `channel_id` are derived server-side, so the SDK does not send them.

### `coupons()`

| Method | HTTP | Path |
| ---------------------------------------------------------------------------------------------------------------------------- | ---- | -------------------------- |
| `validate(string $code, array $items, ?string $patientId = null, ?string $email = null, ?string $opportunityId = null): Response` | POST | `/v1/sales/coupons/validate` |

Checks a coupon code against a cart before the payment is created; nothing is redeemed. `items` is the cart (1–6 lines): each line is a `plan_id`, or a `product_id` with `variant_id`, plus a `quantity` — never an amount. Name the shopper with one of `patientId`, `email` or `opportunityId`. `data()` carries the coupon terms, `gross_amount_cents`, `discount_cents`, `amount_cents`, `currency` and the discounted `items`. An unknown code throws `NotFoundException`; any other refusal throws `ValidationException`.

### `teleforms()`

| Method | HTTP | Path | Notes |
Expand Down
14 changes: 14 additions & 0 deletions src/AsterMDClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,20 @@ public function checkoutEvents(): \AsterMD\Sdk\Resource\CheckoutEvents
return new \AsterMD\Sdk\Resource\CheckoutEvents($this->transport);
}

/**
* Returns the Coupons resource for checking a coupon code against a cart.
*
* Use it at checkout, before the payment is created, to learn whether the
* shopper's code applies to the cart and what it takes off. A check never
* redeems the coupon.
*
* @return \AsterMD\Sdk\Resource\Coupons
*/
public function coupons(): \AsterMD\Sdk\Resource\Coupons
{
return new \AsterMD\Sdk\Resource\Coupons($this->transport);
}

/**
* Returns the Teleforms resource for reading questionnaire and intake form definitions.
*
Expand Down
79 changes: 79 additions & 0 deletions src/Resource/Coupons.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

namespace AsterMD\Sdk\Resource;

use AsterMD\Sdk\Response;

/**
* Coupon checks for a storefront cart on the `sales` service.
*
* Use this resource just before creating the payment: it tells the storefront
* whether a coupon code the shopper typed can be used on the current cart, and
* what it takes off. AsterMD prices the cart itself from its catalogue — callers
* send product, variant or plan identifiers and quantities, never amounts.
*
* The call is authenticated with the channel's API user credential and only
* 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.
*
* @phpstan-type CouponCartItem array{plan_id?: string, product_id?: string, variant_id?: string, quantity: int}
*/
final class Coupons extends AbstractResource
{
/**
* 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.
* Name the shopper with one of `$patientId`, `$email` or `$opportunityId`
* (when several are sent the server uses them in that order); a shopper who is
* not a patient yet only fits a coupon open to anyone. The check has no
* side effects. Inspect `$response->data()` for the coupon terms, the price
* before and after the discount, and the discounted lines.
*
* @param string $code the code the shopper typed (not case sensitive)
* @param list<CouponCartItem> $items the cart, main item first, 1 to 6 lines. Each line is either a
* `plan_id` or a `product_id` with `variant_id` (never both), plus
* a `quantity` from 1 to 999
* @param string|null $patientId the AsterMD patient id of the shopper, when already a patient;
* sent only when provided
* @param string|null $email the shopper's email, used when `$patientId` is not sent;
* sent only when provided
* @param string|null $opportunityId the shopper's opportunity id, used when neither `$patientId` nor
* `$email` is sent; sent only when provided
*
* @return Response the coupon check envelope; `data()` contains `coupon_id`, `name`, `discount_type`, `value`,
* `tiers`, `default_scope`, `gross_amount_cents`, `discount_cents`, `amount_cents`,
* `currency` and the discounted `items`
*
* @throws \AsterMD\Sdk\Exception\NotFoundException if no coupon exists with this code
* @throws \AsterMD\Sdk\Exception\ValidationException if the coupon cannot be used on this cart or the cart cannot be priced
* @throws \AsterMD\Sdk\Exception\ApiException on any other non-2xx response from the server
* @throws \AsterMD\Sdk\Exception\TransportException on a network-level failure
*/
public function validate(
string $code,
array $items,
?string $patientId = null,
?string $email = null,
?string $opportunityId = null,
): Response {
$body = ['code' => $code, 'items' => $items];

if ($patientId !== null) {
$body['patient_id'] = $patientId;
}
if ($email !== null) {
$body['email'] = $email;
}
if ($opportunityId !== null) {
$body['opportunity_id'] = $opportunityId;
}

return $this->transport->send('sales', 'POST', '/coupons/validate', body: $body);
}
}
3 changes: 2 additions & 1 deletion src/Resource/Treatments.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ public function list(array $query = []): Response
*
* `$payment`, when supplied, carries the settled payment method for the order.
* `card`, when present, additionally requires `type` (one of `amex`, `visa`,
* `mastercard`, `discover`, `diners_club`, `jcb`) and `exp`, with `bin` optional.
* `mastercard`, `discover`, `diners_club`, `jcb`) and `exp`, with `last_4` (the card's
* last four digits) optional.
*
* `$verification`, when supplied, records identity/contact verification already
* performed by the caller. `id`, when present, additionally requires `verified`
Expand Down
92 changes: 92 additions & 0 deletions tests/Unit/Resource/CouponsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

declare(strict_types=1);

namespace AsterMD\Sdk\Tests\Unit\Resource;

use AsterMD\Sdk\Exception\NotFoundException;
use AsterMD\Sdk\Exception\ValidationException;
use AsterMD\Sdk\Http\Transport;
use AsterMD\Sdk\Http\UrlBuilder;
use AsterMD\Sdk\Resource\Coupons;
use AsterMD\Sdk\Tests\Support\MockHttpClient;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\TestCase;

final class CouponsTest extends TestCase
{
private const OK = '{"success":true,"message":"ok","data":{"discount_cents":1980},"meta":{}}';

private MockHttpClient $http;
private Coupons $resource;

protected function setUp(): void
{
$factory = new Psr17Factory();
$this->http = new MockHttpClient();
$this->resource = new Coupons(new Transport(
httpClient: $this->http,
requestFactory: $factory,
streamFactory: $factory,
urlBuilder: new UrlBuilder('api.astermd.com'),
tokenProvider: static fn (): string => 'jwt',
onUnauthorized: static fn (): bool => false,
));
}

public function testValidateSendsCodeAndItemsOnly(): void
{
$this->http->enqueue(200, self::OK);

$response = $this->resource->validate('WELCOME20', [
['plan_id' => 'plan1', 'quantity' => 1],
['product_id' => 'p1', 'variant_id' => 'v1', 'quantity' => 2],
]);

$req = $this->http->lastRequest();
self::assertSame('POST', $req->getMethod());
self::assertSame('https://api.astermd.com/v1/sales/coupons/validate', (string) $req->getUri());
self::assertSame('Bearer jwt', $req->getHeaderLine('Authorization'));
self::assertSame('application/json', $req->getHeaderLine('Content-Type'));
self::assertJsonStringEqualsJsonString(
'{"code":"WELCOME20","items":[{"plan_id":"plan1","quantity":1},{"product_id":"p1","variant_id":"v1","quantity":2}]}',
(string) $req->getBody(),
);
self::assertSame(['discount_cents' => 1980], $response->data());
}

public function testValidateForwardsShopperIdentifiersWhenProvided(): void
{
$this->http->enqueue(200, self::OK);

$this->resource->validate(
'WELCOME20',
[['plan_id' => 'plan1', 'quantity' => 1]],
patientId: 'pat1',
email: 'jane.doe@example.com',
opportunityId: 'opp1',
);

self::assertJsonStringEqualsJsonString(
'{"code":"WELCOME20","items":[{"plan_id":"plan1","quantity":1}],'
. '"patient_id":"pat1","email":"jane.doe@example.com","opportunity_id":"opp1"}',
(string) $this->http->lastRequest()->getBody(),
);
}

public function testValidateMapsUnknownCodeToNotFound(): void
{
$this->http->enqueue(404, '{"success":false,"message":"There is no coupon with this code"}');

$this->expectException(NotFoundException::class);
$this->resource->validate('NOPE', [['plan_id' => 'plan1', 'quantity' => 1]]);
}

public function testValidateMapsCouponRefusalToValidationException(): void
{
$this->http->enqueue(422, '{"success":false,"message":"The coupon has expired"}');

$this->expectException(ValidationException::class);
$this->resource->validate('OLD', [['plan_id' => 'plan1', 'quantity' => 1]]);
}
}
3 changes: 2 additions & 1 deletion tests/Unit/Resource/TreatmentsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,14 @@ public function testSyncIncludesPaymentWhenProvided(): void
'card' => [
'type' => 'visa',
'exp' => '12/29',
'last_4' => '4242',
],
];
$this->resource->sync('17de25ac-ba67-4f6e-8067-d752e800ae47', ['28618'], $ua, payment: $payment);

self::assertJsonStringEqualsJsonString(
'{"session_id":"17de25ac-ba67-4f6e-8067-d752e800ae47","order_ids":["28618"],"payment":'
. '{"type":"credit_card","pre_auth":false,"card":{"type":"visa","exp":"12/29"}}}',
. '{"type":"credit_card","pre_auth":false,"card":{"type":"visa","exp":"12/29","last_4":"4242"}}}',
(string) $this->http->lastRequest()->getBody(),
);
}
Expand Down
Loading