Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added ledger resources to the seller and admin SDKs

Damian Legawiec3294ca24bfa8
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 3645847bca..44800d0701 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -313,6 +313,7 @@ import type {
OptionType,
Order,
OrderCancellationReason,
+ OrderGroup,
OrderRoutingRule,
PackageType,
Payment,
@@ -335,6 +336,7 @@ import type {
ReturnReason,
Role,
Seller,
+ SellerBalance,
SellerPayout,
SellerRequirement,
SellerRequirementSubmission,
@@ -3038,6 +3040,13 @@ export class AdminClient {
reject: (id: string, params?: SellerRejectParams, options?: RequestOptions): Promise<Seller> =>
this.request<Seller>('PATCH', `/sellers/${id}/reject`, { ...options, body: params }),
+
+ /**
+ * Where this seller stands, one row per currency: earned, paid, still
+ * owed, and earnings the payout provider has not yet confirmed.
+ */
+ balances: (id: string, options?: RequestOptions): Promise<{ data: SellerBalance[] }> =>
+ this.request<{ data: SellerBalance[] }>('GET', `/sellers/${id}/balances`, options),
}
// ============================================
@@ -3170,6 +3179,32 @@ export class AdminClient {
}),
}
+ /**
+ * `Spree::OrderGroup` — the checkout a split basket produced, and the
+ * payments made against it. An order placed in one has no payments of its
+ * own: its share of each of these is in its `payment_splits`.
+ */
+ readonly orderGroups = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<OrderGroup>> =>
+ this.request<PaginatedResponse<OrderGroup>>('GET', '/order_groups', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (
+ id: string,
+ params?: { expand?: string[]; fields?: string[] },
+ options?: RequestOptions,
+ ): Promise<OrderGroup> =>
+ this.request<OrderGroup>('GET', `/order_groups/${id}`, {
+ ...options,
+ params: getParams(params),
+ }),
+ }
+
// ============================================
// Seller fund ledger
// ============================================
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 68140ad938..67ee2e43c5 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -82,11 +82,13 @@ export type { default as OptionType } from './generated/OptionType'
export type { default as OptionValue } from './generated/OptionValue'
export type { default as Order } from './generated/Order'
export type { default as OrderCancellationReason } from './generated/OrderCancellationReason'
+export type { default as OrderGroup } from './generated/OrderGroup'
export type { default as OrderRoutingRule } from './generated/OrderRoutingRule'
export type { default as PackageType } from './generated/PackageType'
export type { default as Payment } from './generated/Payment'
export type { default as PaymentMethod } from './generated/PaymentMethod'
export type { default as PaymentSource } from './generated/PaymentSource'
+export type { default as PaymentSplit } from './generated/PaymentSplit'
export type { default as Permission } from './generated/Permission'
export type { default as Policy } from './generated/Policy'
export type { default as Price } from './generated/Price'
@@ -107,6 +109,7 @@ export type { default as ReturnLineItem } from './generated/ReturnLineItem'
export type { default as ReturnReason } from './generated/ReturnReason'
export type { default as Role } from './generated/Role'
export type { default as Seller } from './generated/Seller'
+export type { default as SellerBalance } from './generated/SellerBalance'
export type { default as SellerPayout } from './generated/SellerPayout'
export type { default as SellerRequirement } from './generated/SellerRequirement'
export type { default as SellerRequirementStatus } from './generated/SellerRequirementStatus'
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 8d19de122e..05356bbf6b 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -2,6 +2,7 @@ import type { ListParams, PaginatedResponse, RequestFn, RequestOptions } from '@
import { transformListParams } from '@spree/sdk-core'
import type {
AuthTokens,
+ Balance,
Claim,
Delivery,
DeliveryMethod,
@@ -15,6 +16,7 @@ import type {
Invitation,
Order,
PackageType,
+ Payout,
Policy,
Product,
ProductType,
@@ -28,6 +30,7 @@ import type {
StockLocation,
TaxIdentifier,
TeamMember,
+ Transfer,
} from './types'
/**
@@ -386,8 +389,16 @@ export class SellerClient {
params: params ? transformListParams(params) : undefined,
}),
- get: (id: string, options?: RequestOptions): Promise<Order> =>
- this.request<Order>('GET', `/orders/${id}`, options),
+ /**
+ * @param params `expand: ['payment_splits']` adds this order's share of
+ * the payment the buyer made for the whole basket. A basket placed with
+ * one seller only does not split and has no shares.
+ */
+ get: (id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Order> =>
+ this.request<Order>('GET', `/orders/${id}`, {
+ ...options,
+ params: params?.expand?.length ? { expand: params.expand.join(',') } : undefined,
+ }),
/**
* Withdraws from an order this seller cannot fulfil.
@@ -1158,6 +1169,56 @@ export class SellerClient {
this.request<void>('DELETE', `/package_types/${id}`, options),
}
+ /**
+ * Where this seller stands with the marketplace, one row per currency:
+ * earned, paid, still owed, and earnings the payout provider has not yet
+ * confirmed. Computed from the ledger, so the rows carry no id.
+ */
+ readonly balances = {
+ list: (options?: RequestOptions): Promise<{ data: Balance[] }> =>
+ this.request<{ data: Balance[] }>('GET', '/balances', options),
+ }
+
+ /**
+ * What this seller has earned, order by order — the sale less the
+ * marketplace's commission, credited when the goods went out.
+ *
+ * Read-only: a refund writes a negative reversal row rather than editing
+ * the earning. Filter with `q[order_id_eq]` or `q[payout_id_eq]`.
+ */
+ readonly transfers = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Transfer>> =>
+ this.request<PaginatedResponse<Transfer>>('GET', '/transfers', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, options?: RequestOptions): Promise<Transfer> =>
+ this.request<Transfer>('GET', `/transfers/${id}`, options),
+ }
+
+ /**
+ * Settlements to this seller, each batching the earnings that accumulated
+ * since the last one. Created by the marketplace's sweep and confirmed by
+ * the payout provider or the operator, so read-only here.
+ */
+ readonly payouts = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Payout>> =>
+ this.request<PaginatedResponse<Payout>>('GET', '/payouts', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, options?: RequestOptions): Promise<Payout> =>
+ this.request<Payout>('GET', `/payouts/${id}`, options),
+ }
+
/**
* This seller's own policy documents — their returns policy, shipping
* policy, whatever the marketplace asks them to publish.
diff --git a/packages/seller-sdk/src/types/generated/Balance.ts b/packages/seller-sdk/src/types/generated/Balance.ts
new file mode 100644
index 0000000000..e81942e9a8
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Balance.ts
@@ -0,0 +1,17 @@
+// Typelizer digest 599d7c1a5853edef15f4d9f0ed9cf177
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type Balance = {
+ currency: string;
+ earned: string;
+ display_earned: string;
+ paid: string;
+ display_paid: string;
+ balance: string;
+ display_balance: string;
+ pending: string;
+ display_pending: string;
+}
+
+export default Balance;
diff --git a/packages/seller-sdk/src/types/generated/Order.ts b/packages/seller-sdk/src/types/generated/Order.ts
index 72187eb428..8d1049652b 100644
--- a/packages/seller-sdk/src/types/generated/Order.ts
+++ b/packages/seller-sdk/src/types/generated/Order.ts
@@ -1,7 +1,7 @@
-// Typelizer digest 7f8142a53aa435a471b0c4ed4c729af5
+// Typelizer digest b43335372a936c1921a5621b1e97bfd0
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
-import type {OrderLineItem, Fulfillment, Address} from '@/types'
+import type {OrderLineItem, PaymentSplit, Fulfillment, Address} from '@/types'
type Order = {
id: string;
@@ -47,6 +47,7 @@ type Order = {
cancel_reason_name: string | null;
cancel_note: string | null;
items: Array<OrderLineItem>;
+ payment_splits?: Array<PaymentSplit>;
fulfillments: Array<Fulfillment>;
shipping_address: Address;
billing_address: Address;
diff --git a/packages/seller-sdk/src/types/generated/PaymentSplit.ts b/packages/seller-sdk/src/types/generated/PaymentSplit.ts
new file mode 100644
index 0000000000..29d187cf13
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/PaymentSplit.ts
@@ -0,0 +1,23 @@
+// Typelizer digest 5f70a78445db39e84c1e0df1f6076faa
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type PaymentSplit = {
+ id: string;
+ currency: string;
+ created_at: string;
+ authorized_amount: string;
+ display_authorized_amount: string;
+ captured_amount: string;
+ display_captured_amount: string;
+ refunded_amount: string;
+ display_refunded_amount: string;
+ claimed_amount: string;
+ display_claimed_amount: string;
+ net_captured_amount: string;
+ display_net_captured_amount: string;
+ refundable_amount: string;
+ display_refundable_amount: string;
+}
+
+export default PaymentSplit;
diff --git a/packages/seller-sdk/src/types/generated/Payout.ts b/packages/seller-sdk/src/types/generated/Payout.ts
new file mode 100644
index 0000000000..dcda83c3f0
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Payout.ts
@@ -0,0 +1,20 @@
+// Typelizer digest f11021a481e967fe025171c379ea6bab
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type Payout = {
+ id: string;
+ status: string;
+ currency: string;
+ provider: string;
+ reference: string | null;
+ period_start: string | null;
+ period_end: string | null;
+ created_at: string;
+ updated_at: string;
+ amount: string;
+ display_amount: string;
+ transfers_count: number;
+}
+
+export default Payout;
diff --git a/packages/seller-sdk/src/types/generated/Transfer.ts b/packages/seller-sdk/src/types/generated/Transfer.ts
new file mode 100644
index 0000000000..ef19ba153b
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Transfer.ts
@@ -0,0 +1,22 @@
+// Typelizer digest 13a899486fe193e935361492c1d7a3ef
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type Transfer = {
+ id: string;
+ kind: string;
+ status: string;
+ currency: string;
+ provider: string;
+ reference: string | null;
+ created_at: string;
+ updated_at: string;
+ amount: string;
+ display_amount: string;
+ order_id: string | null;
+ payout_id: string | null;
+ reversed_from_id: string | null;
+ order_number: string | null;
+}
+
+export default Transfer;
diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.ts
index 0503349f57..93b9b27e76 100644
--- a/packages/seller-sdk/src/types/generated/index.ts
+++ b/packages/seller-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest a6c988fabc8d57ee3db309097f7ad477
+// Typelizer digest d0331637341450312e6cc6cbb1c33b08
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { ClaimStatus, ExchangeStatus, FulfillmentStatus, ImportRowStatus, ImportStatus, InvitationStatus, ProductStatus, ProductSubmissionStatus, ReturnStatus, SellerRequirementSubmissionStatus, SellerStatus, ShippingLabelStatus, StockLocationKind } from './Enums'
@@ -9,6 +9,7 @@ export type { default as OptionType } from './OptionType'
export type { default as OptionValue } from './OptionValue'
export type { default as PriceHistory } from './PriceHistory'
export type { default as Price } from './Price'
+export type { default as Balance } from './Balance'
export type { default as ClaimLineItem } from './ClaimLineItem'
export type { default as Claim } from './Claim'
export type { default as DeliveryMethodRule } from './DeliveryMethodRule'
@@ -30,6 +31,8 @@ export type { default as Media } from './Media'
export type { default as OrderLineItem } from './OrderLineItem'
export type { default as Order } from './Order'
export type { default as PackageType } from './PackageType'
+export type { default as PaymentSplit } from './PaymentSplit'
+export type { default as Payout } from './Payout'
export type { default as Policy } from './Policy'
export type { default as Product } from './Product'
export type { default as ProductSubmission } from './ProductSubmission'
@@ -46,5 +49,6 @@ export type { default as StockLevel } from './StockLevel'
export type { default as StockLocation } from './StockLocation'
export type { default as TaxIdentifier } from './TaxIdentifier'
export type { default as TeamMember } from './TeamMember'
+export type { default as Transfer } from './Transfer'
export type { default as Variant } from './Variant'
export type { default as Seller } from './Seller'
diff --git a/packages/seller-sdk/tests/ledger.test.ts b/packages/seller-sdk/tests/ledger.test.ts
new file mode 100644
index 0000000000..93191f66cc
--- /dev/null
+++ b/packages/seller-sdk/tests/ledger.test.ts
@@ -0,0 +1,85 @@
+import { HttpResponse, http } from 'msw'
+import { describe, expect, it } from 'vitest'
+import { createSellerClient } from '../src'
+import { server } from './mocks/server'
+
+const API = 'http://api.test/api/v3/seller'
+
+function client() {
+ return createSellerClient({ baseUrl: 'http://api.test', token: 'jwt' })
+}
+
+describe('the seller ledger', () => {
+ it('reads the balances as a plain list, with no paging params', async () => {
+ let search = ''
+ server.use(
+ http.get(`${API}/balances`, ({ request }) => {
+ search = new URL(request.url).search
+ return HttpResponse.json({ data: [{ currency: 'USD', balance: '25.0' }] })
+ }),
+ )
+
+ const res = await client().balances.list()
+
+ expect(res.data[0]?.currency).toBe('USD')
+ expect(search).toBe('')
+ })
+
+ // The panel filters a seller's earnings to one order and to one settlement;
+ // both go through Ransack, so they must arrive as `q[...]` rather than as
+ // bare params the controller would ignore.
+ it('sends a transfer filter as a Ransack predicate', async () => {
+ let search = ''
+ server.use(
+ http.get(`${API}/transfers`, ({ request }) => {
+ search = decodeURIComponent(new URL(request.url).search)
+ return HttpResponse.json({ data: [], meta: { page: 1, limit: 25, count: 0, pages: 0 } })
+ }),
+ )
+
+ await client().transfers.list({ order_id_eq: 'or_1', limit: 10 })
+
+ expect(search).toContain('q[order_id_eq]=or_1')
+ expect(search).toContain('limit=10')
+ })
+
+ it('reads one payout', async () => {
+ server.use(
+ http.get(`${API}/payouts/vpo_1`, () =>
+ HttpResponse.json({ id: 'vpo_1', status: 'completed' }),
+ ),
+ )
+
+ expect((await client().payouts.get('vpo_1')).status).toBe('completed')
+ })
+
+ // The order page asks for the shares of the basket's payment; without the
+ // expand the server sends none and the card renders empty.
+ it("asks for an order's payment shares as one comma-separated expand", async () => {
+ let search = ''
+ server.use(
+ http.get(`${API}/orders/or_1`, ({ request }) => {
+ search = decodeURIComponent(new URL(request.url).search)
+ return HttpResponse.json({ id: 'or_1' })
+ }),
+ )
+
+ await client().orders.get('or_1', { expand: ['payment_splits'] })
+
+ expect(search).toBe('?expand=payment_splits')
+ })
+
+ it('asks for nothing extra when no expand is given', async () => {
+ let search = 'unset'
+ server.use(
+ http.get(`${API}/orders/or_1`, ({ request }) => {
+ search = new URL(request.url).search
+ return HttpResponse.json({ id: 'or_1' })
+ }),
+ )
+
+ await client().orders.get('or_1')
+
+ expect(search).toBe('')
+ })
+})