prezense 1.3.0 → 1.4.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.
package/loyalty.js CHANGED
@@ -15,25 +15,19 @@ export class Loyalty {
15
15
 
16
16
  // The store's program rules and tiers — no customer, so no sign-in needed.
17
17
  async getProgram({ data }) {
18
- const query = `query {
19
- getLoyaltyProgram {
20
- ${data.trim()}
21
- }
22
- }`;
23
- return this.client.sendRequest({ query }, 'getLoyaltyProgram');
18
+ return this.client.sendRequest(operation('query', 'getLoyaltyProgram', {}, data), 'getLoyaltyProgram');
24
19
  }
25
20
 
26
- // A signed-in customer's own points history, newest first.
27
- async getHistory({ email, fingerprint, limit = 20, offset = 0, data }) {
28
- const query = `
29
- query GetCustomerLoyaltyHistory($email: String!, $fingerprint: String!, $limit: Int!, $offset: Int!) {
30
- getCustomerLoyaltyHistory(email: $email, fingerprint: $fingerprint, limit: $limit, offset: $offset) {
31
- ${data.trim()}
32
- }
33
- }
34
- `;
35
- const variables = { email, fingerprint, limit, offset };
36
- return this.client.sendRequest({ query, variables }, 'getCustomerLoyaltyHistory');
21
+ // A signed-in customer's own points history, newest first. limit
22
+ // defaults to 20 and offset to 0; numbers or numeric strings both work.
23
+ async getHistory({ email, fingerprint, limit, offset, data }) {
24
+ const args = {
25
+ email: ['String!', text(email)],
26
+ fingerprint: ['String!', text(fingerprint)],
27
+ limit: ['Int!', number(limit ?? 20)],
28
+ offset: ['Int!', number(offset ?? 0)],
29
+ };
30
+ return this.client.sendRequest(operation('query', 'getCustomerLoyaltyHistory', args, data), 'getCustomerLoyaltyHistory');
37
31
  }
38
32
 
39
33
  async getAvailableRewards({ email, fingerprint, cartID, data }) {
package/orders.js CHANGED
@@ -8,13 +8,21 @@ export class Orders {
8
8
  this.client = client;
9
9
  }
10
10
 
11
- async create({ cartID, stripePaymentIntentID, data }) {
11
+ async create({ cartID, stripePaymentIntentID, paymentAmount, paymentCurrency, data }) {
12
12
  // The Stripe PaymentIntent that paid for this cart. Optional for backwards
13
13
  // compatibility, but always pass it: without it the order has no link to the
14
14
  // payment and can never be refunded through Prezense.
15
+ //
16
+ // paymentAmount / paymentCurrency: what the payment charged, as Stripe
17
+ // reports it on the PaymentIntent (`amount` in minor units, `currency`).
18
+ // Optional. When given, the order is refused unless they match the cart's
19
+ // charge (cart.prepareCheckoutPayment), and the currency is recorded as
20
+ // the one the shopper paid in.
15
21
  const args = {
16
22
  cartID: ['String!', text(cartID)],
17
23
  stripePaymentIntentID: ['String', text(stripePaymentIntentID || undefined)],
24
+ paymentAmount: ['Int', paymentAmount == null ? undefined : Math.round(Number(paymentAmount))],
25
+ paymentCurrency: ['String', paymentCurrency ? text(paymentCurrency).toUpperCase() : undefined],
18
26
  };
19
27
  return this.client.sendRequest(operation('mutation', 'createOrder', args, data), 'createOrder');
20
28
  }
@@ -28,23 +36,27 @@ export class Orders {
28
36
  * variables, never spliced into the query text.
29
37
  */
30
38
  async getOrder({ email, purchase_id, data }) {
31
- const query = `query RetrieveOrder($email: String!, $purchaseId: String!) {
32
- retrieveOrder(email: $email, purchaseId: $purchaseId) {
33
- ${data.trim()}
34
- }
35
- }`;
36
-
37
- return this.client.sendRequest({ query, variables: { email, purchaseId: purchase_id } }, 'retrieveOrder');
39
+ const args = {
40
+ email: ['String!', text(email)],
41
+ purchaseId: ['String!', text(purchase_id)],
42
+ };
43
+ return this.client.sendRequest(operation('query', 'retrieveOrder', args, data), 'retrieveOrder');
38
44
  }
39
45
 
40
46
  async getAllOrders({ email, data }) {
41
- const query = `query RetrieveAllOrders($email: String!) {
42
- retrieveAllOrders(email: $email) {
43
- ${data.trim()}
44
- }
45
- }`;
47
+ const args = { email: ['String!', text(email)] };
48
+ return this.client.sendRequest(operation('query', 'retrieveAllOrders', args, data), 'retrieveAllOrders');
49
+ }
46
50
 
47
- return this.client.sendRequest({ query, variables: { email } }, 'retrieveAllOrders');
51
+ /**
52
+ * The store's exchange settings (whether exchanges are on, the
53
+ * acceptance window, how many suggestions are offered, …). Readable with
54
+ * storefront keys. Fields: enabled, autoApproveReturnOnAccept,
55
+ * underPaymentMode, requireReturnReceipt, acceptanceWindowHours,
56
+ * maxSuggestions.
57
+ */
58
+ async exchangeSettings({ data }) {
59
+ return this.client.sendRequest(operation('query', 'getExchangeSettings', {}, data), 'getExchangeSettings');
48
60
  }
49
61
 
50
62
  async getReturns({ customer_email, data, limit, offset }) {
@@ -71,13 +83,8 @@ export class Orders {
71
83
  * @param {string} args.data GraphQL selection set
72
84
  */
73
85
  async getReturn({ return_id, data }) {
74
- const query = `query GetReturn($returnID: String!) {
75
- getReturn(returnID: $returnID) {
76
- ${data.trim()}
77
- }
78
- }`;
79
-
80
- return this.client.sendRequest({ query, variables: { returnID: return_id } }, 'getReturn');
86
+ const args = { returnID: ['String!', text(return_id)] };
87
+ return this.client.sendRequest(operation('query', 'getReturn', args, data), 'getReturn');
81
88
  }
82
89
 
83
90
  async createReturn({ order_id, customer_email, products_to_return, reason_for_return, data }) {
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "prezense",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "bin": {
7
7
  "prezense": "./cli.js"
8
8
  },
9
+ "scripts": {
10
+ "test": "node --test test/offline.test.js test/checkout-payment.test.js test/post-purchase-charge.test.js"
11
+ },
9
12
  "engines": {
10
13
  "node": ">=18"
11
14
  },
package/post_purchase.js CHANGED
@@ -1,8 +1,20 @@
1
- import { operation, text, number } from './graphql.js';
1
+ import { operation, text, number, invalidInput } from './graphql.js';
2
2
 
3
3
  // Every value goes in as a GraphQL variable (graphql.js), never spliced into
4
4
  // the query text.
5
5
 
6
+ function validItems(items) {
7
+ return Array.isArray(items) && items.length > 0 && !items.some((item) => item == null || typeof item !== 'object');
8
+ }
9
+
10
+ function invalidItems() {
11
+ return invalidInput('items must be a non-empty list of { variantID, quantity }');
12
+ }
13
+
14
+ function appendItemsInput(items) {
15
+ return items.map(i => ({ variantID: text(i.variantID), quantity: number(i.quantity) }));
16
+ }
17
+
6
18
  export class PostPurchase {
7
19
  constructor(client) {
8
20
  this.client = client;
@@ -17,12 +29,43 @@ export class PostPurchase {
17
29
  return this.client.sendRequest(operation('query', 'getPostPurchaseRecommendations', args, data), 'getPostPurchaseRecommendations');
18
30
  }
19
31
 
20
- async appendItems({ orderID, items, paymentReference, taxAmount, data }) {
32
+ /**
33
+ * What adding `items` to an order charges the shopper. Call it right
34
+ * before creating the Stripe payment for the upsell, then charge
35
+ * `amountMinor` in `currency.toLowerCase()` and pass both to
36
+ * `appendItems` as paymentAmount / paymentCurrency.
37
+ *
38
+ * An order paid in another currency is charged in that same currency at
39
+ * the order's own rate; any other order is charged its base total.
40
+ * `taxAmount` is the tax on the added items, in the store's base currency.
41
+ *
42
+ * Fields: currency, amount, amountMinor, baseCurrency, baseAmount,
43
+ * exchangeRate, converted. All of them when `data` is left out.
44
+ */
45
+ async quoteCharge({ orderID, items, taxAmount, data } = {}) {
46
+ if (!validItems(items)) return invalidItems();
47
+ const args = {
48
+ orderID: ['String!', text(orderID)],
49
+ items: ['[AppendOrderItemInput!]!', appendItemsInput(items)],
50
+ taxAmount: ['Float', Number(taxAmount) || 0],
51
+ };
52
+ const selection = data ?? 'currency amount amountMinor baseCurrency baseAmount exchangeRate converted';
53
+ return this.client.sendRequest(operation('query', 'quotePostPurchaseCharge', args, selection), 'quotePostPurchaseCharge');
54
+ }
55
+
56
+ // paymentAmount / paymentCurrency: what the payment charged, as Stripe
57
+ // reports it on the PaymentIntent (`amount` in minor units, `currency`).
58
+ // Optional. When given, the append is refused unless they match
59
+ // quoteCharge.
60
+ async appendItems({ orderID, items, paymentReference, taxAmount, paymentAmount, paymentCurrency, data }) {
61
+ if (!validItems(items)) return invalidItems();
21
62
  const args = {
22
63
  orderID: ['String!', text(orderID)],
23
- items: ['[AppendOrderItemInput!]!', items.map(i => ({ variantID: text(i.variantID), quantity: number(i.quantity) }))],
64
+ items: ['[AppendOrderItemInput!]!', appendItemsInput(items)],
24
65
  paymentReference: ['String!', text(paymentReference)],
25
66
  taxAmount: ['Float!', Number(taxAmount) || 0],
67
+ paymentAmount: ['Int', paymentAmount == null ? undefined : Math.round(Number(paymentAmount))],
68
+ paymentCurrency: ['String', paymentCurrency ? text(paymentCurrency).toUpperCase() : undefined],
26
69
  };
27
70
  return this.client.sendRequest(operation('mutation', 'appendItemsToOrder', args, data), 'appendItemsToOrder');
28
71
  }
package/prezanse.js CHANGED
@@ -21,6 +21,46 @@ import { Alerts } from './alerts.js';
21
21
  import { Collections } from './collections.js';
22
22
  import { Pages } from './pages.js';
23
23
  import { GiftCards } from './gift_cards.js';
24
+ import { sdkError } from './graphql.js';
25
+
26
+ const MODULES = [
27
+ 'products', 'cart', 'locations', 'promotions', 'media', 'reviews', 'accounts',
28
+ 'orders', 'analytics', 'shipping', 'personalization', 'postPurchase', 'trending',
29
+ 'search', 'bundles', 'currency', 'loyalty', 'fraud', 'alerts', 'collections',
30
+ 'pages', 'giftCards',
31
+ ];
32
+
33
+ const warned = new Set();
34
+
35
+ /** Warn once per process that an endpoint variable is missing in production. */
36
+ function warnOnce(variable, fallback) {
37
+ if (warned.has(variable)) return;
38
+ warned.add(variable);
39
+ console.warn(`[prezense] ${variable} is not set, so the SDK is using ${fallback}. Set ${variable} in this environment.`);
40
+ }
41
+
42
+ /**
43
+ * Wrap each async method of a module so it never throws: a call with no
44
+ * arguments is treated as a call with `{}` (so it gets the method's own
45
+ * error, e.g. MISSING_DATA), and anything thrown resolves to
46
+ * { error, response: null }.
47
+ */
48
+ function guard(module) {
49
+ const prototype = Object.getPrototypeOf(module);
50
+ for (const name of Object.getOwnPropertyNames(prototype)) {
51
+ if (name === 'constructor') continue;
52
+ const method = prototype[name];
53
+ if (typeof method !== 'function' || method.constructor.name !== 'AsyncFunction') continue;
54
+ module[name] = async (...args) => {
55
+ if (args[0] == null) args[0] = {};
56
+ try {
57
+ return await method.apply(module, args);
58
+ } catch (error) {
59
+ return { error, response: null };
60
+ }
61
+ };
62
+ }
63
+ }
24
64
 
25
65
  export class Prezense {
26
66
  constructor(apiKey, platformKey, options = {}) {
@@ -52,6 +92,15 @@ export class Prezense {
52
92
  : null;
53
93
  this.baseUrl = options.baseUrl || process.env.PREZENSE_API_URL || 'http://localhost:4000/';
54
94
  this.trackingUrl = options.trackingUrl || process.env.PREZENSE_TRACKING_URL || 'http://localhost:4001';
95
+ // In production a missing endpoint means every call goes to localhost
96
+ // and fails. Say so once per process, naming the variable to set.
97
+ if (process.env.NODE_ENV === 'production') {
98
+ if (!options.baseUrl && !process.env.PREZENSE_API_URL) warnOnce('PREZENSE_API_URL', this.baseUrl);
99
+ if (!options.trackingUrl && !process.env.PREZENSE_TRACKING_URL) warnOnce('PREZENSE_TRACKING_URL', this.trackingUrl);
100
+ }
101
+ // The HTTP client. node-fetch by default; `options.fetch` swaps it
102
+ // (tests pass a stub).
103
+ this.fetch = typeof options.fetch === 'function' ? options.fetch : fetch;
55
104
 
56
105
  // Instantiate each category class
57
106
  this.products = new Products(this);
@@ -76,6 +125,10 @@ export class Prezense {
76
125
  this.collections = new Collections(this);
77
126
  this.pages = new Pages(this);
78
127
  this.giftCards = new GiftCards(this);
128
+
129
+ // Every method resolves { error, response } and never throws, even
130
+ // when called with no arguments or with input it can't use.
131
+ for (const name of MODULES) guard(this[name]);
79
132
  }
80
133
 
81
134
  /** The shopper's IP and User-Agent, forwarded so Prezense sees the shopper, not this server. */
@@ -89,7 +142,17 @@ export class Prezense {
89
142
  }
90
143
 
91
144
  // Method to send a request directly to the GraphQL server
145
+ //
146
+ // Resolves { error, response }:
147
+ // - an operation that couldn't be built (operation() in graphql.js,
148
+ // e.g. MISSING_DATA): that error, without calling the API;
149
+ // - GraphQL errors: the first one as { message, code, details }, where
150
+ // details is the error's `extensions` minus `code` (null if none).
151
+ // Any partial data sent alongside errors is not returned;
152
+ // - a reply that isn't JSON: code INVALID_RESPONSE with the HTTP status;
153
+ // - network failures: the underlying error, as before.
92
154
  async sendRequest(query, dataField) {
155
+ if (query && query.error) return { error: query.error, response: null };
93
156
  try {
94
157
 
95
158
  const headers = {
@@ -103,35 +166,61 @@ export class Prezense {
103
166
  }
104
167
  Object.assign(headers, this.#shopperHeaders());
105
168
 
106
- const response = await fetch(this.baseUrl, {
169
+ const response = await this.fetch(this.baseUrl, {
107
170
  method: 'POST',
108
171
  headers,
109
172
  body: JSON.stringify(query),
110
173
  });
111
174
 
112
- const result = await response.json();
175
+ const body = await response.text();
176
+ let result;
177
+ try {
178
+ result = JSON.parse(body);
179
+ } catch {
180
+ return {
181
+ error: sdkError(
182
+ `The Prezense API sent a reply that isn't JSON (HTTP ${response.status}).`,
183
+ 'INVALID_RESPONSE',
184
+ { status: response.status },
185
+ ),
186
+ response: null,
187
+ };
188
+ }
113
189
 
114
190
  // Check for errors in the response
115
- if (result.errors) {
191
+ if (Array.isArray(result?.errors) && result.errors.length > 0) {
116
192
  // Keep the machine-readable code (e.g. FRAUD_RISK_TOO_HIGH) so
117
- // callers can branch on it instead of matching message text.
118
- const first = result.errors[0];
119
- const error = new Error(first.message);
120
- error.code = first.code ?? first.extensions?.code ?? null;
193
+ // callers can branch on it instead of matching message text,
194
+ // and the rest of the extensions (e.g. productIDsNotInStore)
195
+ // as `details`.
196
+ const first = result.errors[0] ?? {};
197
+ const { code: extensionCode, ...rest } = first.extensions ?? {};
198
+ const details = Object.keys(rest).length > 0 ? rest : null;
199
+ const error = sdkError(
200
+ first.message ?? 'The Prezense API returned an error.',
201
+ first.code ?? extensionCode ?? null,
202
+ { details },
203
+ );
121
204
  return { error, response: null };
122
205
  }
123
206
 
124
207
  // If no errors, return the data
125
- return { error: null, response: result.data[dataField] };
208
+ return { error: null, response: result?.data?.[dataField] ?? null };
126
209
  } catch (error) {
127
210
  return { error, response: null };
128
211
  }
129
212
  }
130
213
 
214
+ // Resolves { error, response }. The reply is read as text, then parsed as
215
+ // JSON when it is JSON (otherwise `response` is the text, or null when
216
+ // empty). A non-2xx reply resolves to
217
+ // { error: { message, code, status }, response: null }, with the server's
218
+ // own `error`/`message` and `code` when it sent them, else
219
+ // code TRACKING_ERROR. Network failures resolve to the underlying error.
131
220
  async trackEvent(endpoint, body) {
132
221
  try {
133
222
 
134
- const response = await fetch(`${this.trackingUrl}/track/${endpoint}`, {
223
+ const response = await this.fetch(`${this.trackingUrl}/track/${endpoint}`, {
135
224
  method: 'POST',
136
225
  headers: {
137
226
  'Content-Type': 'application/json',
@@ -142,10 +231,27 @@ export class Prezense {
142
231
  body: JSON.stringify(body),
143
232
  });
144
233
 
145
- const result = await response.json();
234
+ const raw = await response.text();
235
+ let result = raw === '' ? null : raw;
236
+ try {
237
+ if (raw !== '') result = JSON.parse(raw);
238
+ } catch {
239
+ // Not JSON: keep the text.
240
+ }
241
+
242
+ if (!response.ok) {
243
+ const server = result && typeof result === 'object' ? result : {};
244
+ const serverMessage = typeof server.error === 'string' ? server.error : server.message;
245
+ const error = sdkError(
246
+ serverMessage || `The tracking request failed (HTTP ${response.status}).`,
247
+ server.code || 'TRACKING_ERROR',
248
+ { status: response.status },
249
+ );
250
+ return { error, response: null };
251
+ }
146
252
 
147
253
  return { error: null, response: result };
148
-
254
+
149
255
  } catch (error) {
150
256
  return { error, response: null };
151
257
  }
package/products.js CHANGED
@@ -97,11 +97,12 @@ export class Products {
97
97
 
98
98
  async purchaseBundles({ productId, data, limit, minConfidence }) {
99
99
  // Values go in as GraphQL variables, never spliced into the query text.
100
- const query = `query ($productId: String!, $limit: Int, $minConfidence: Float) {
101
- getProductPurchaseBundles(productId: $productId, limit: $limit, minConfidence: $minConfidence) { ${data.trim()} }
102
- }`;
103
- const variables = { productId, limit, minConfidence };
104
- return this.client.sendRequest({ query, variables }, 'getProductPurchaseBundles');
100
+ const args = {
101
+ productId: ['String!', text(productId)],
102
+ limit: ['Int', number(limit)],
103
+ minConfidence: ['Float', number(minConfidence)],
104
+ };
105
+ return this.client.sendRequest(operation('query', 'getProductPurchaseBundles', args, data), 'getProductPurchaseBundles');
105
106
  }
106
107
 
107
108
  }
package/reviews.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { operation, text, number, textList } from './graphql.js';
2
+
1
3
  export class Reviews {
2
4
  constructor(client) {
3
5
  this.client = client;
@@ -5,49 +7,45 @@ export class Reviews {
5
7
 
6
8
  // Every value goes in as a GraphQL variable, never spliced into the query
7
9
  // text, so reviews with newlines, quotes or backslashes are sent intact.
10
+ // IDs may be numbers or strings; ratings, limits and offsets may be
11
+ // numbers or numeric strings.
8
12
 
9
- async addReview({ productID, rating, review, customerEmail }) {
10
- const query = `mutation ($productID: String!, $rating: Int!, $review: String!, $customerEmail: String!) {
11
- addProductReview(productID: $productID, rating: $rating, review: $review, customerEmail: $customerEmail)
12
- }`;
13
- const variables = { productID, rating, review, customerEmail };
14
- return this.client.sendRequest({ query, variables }, 'addProductReview');
13
+ // reviewerName (up to 100 characters) and title (up to 150) are optional:
14
+ // left out, they aren't sent and the review has no name or headline.
15
+ async addReview({ productID, rating, review, customerEmail, reviewerName, title }) {
16
+ // addProductReview returns a String, so no field selection.
17
+ const args = {
18
+ productID: ['String!', text(productID)],
19
+ rating: ['Int!', number(rating)],
20
+ review: ['String!', text(review)],
21
+ customerEmail: ['String!', text(customerEmail)],
22
+ reviewerName: ['String', text(reviewerName)],
23
+ title: ['String', text(title)],
24
+ };
25
+ return this.client.sendRequest(operation('mutation', 'addProductReview', args), 'addProductReview');
15
26
  }
16
27
 
17
28
  async getAllReviewsOfProduct({ productID, data, limit, offset }) {
18
- const query = `query ($productID: String!, $limit: Int, $offset: Int) {
19
- getAllReviewsOfProduct(productID: $productID, limit: $limit, offset: $offset) {
20
- ${data.trim()}
21
- }
22
- }`;
23
- const variables = { productID, limit, offset };
24
- return this.client.sendRequest({ query, variables }, 'getAllReviewsOfProduct');
29
+ const args = {
30
+ productID: ['String!', text(productID)],
31
+ limit: ['Int', number(limit)],
32
+ offset: ['Int', number(offset)],
33
+ };
34
+ return this.client.sendRequest(operation('query', 'getAllReviewsOfProduct', args, data), 'getAllReviewsOfProduct');
25
35
  }
26
36
 
27
37
  async getReviewByID({ reviewID, data }) {
28
- const query = `query ($reviewID: String!) {
29
- getReviewByID(reviewID: $reviewID) {
30
- ${data.trim()}
31
- }
32
- }`;
33
- return this.client.sendRequest({ query, variables: { reviewID } }, 'getReviewByID');
38
+ const args = { reviewID: ['String!', text(reviewID)] };
39
+ return this.client.sendRequest(operation('query', 'getReviewByID', args, data), 'getReviewByID');
34
40
  }
35
41
 
36
42
  async getReviewsByID({ reviewIDs, data }) {
37
- const query = `query ($reviewIDs: [String!]!) {
38
- getListOfReviewsByIDs(reviewIDs: $reviewIDs) {
39
- ${data.trim()}
40
- }
41
- }`;
42
- return this.client.sendRequest({ query, variables: { reviewIDs } }, 'getListOfReviewsByIDs');
43
+ const args = { reviewIDs: ['[String!]!', textList(reviewIDs)] };
44
+ return this.client.sendRequest(operation('query', 'getListOfReviewsByIDs', args, data), 'getListOfReviewsByIDs');
43
45
  }
44
46
 
45
47
  async getProductRatingSummary({ productID, data }) {
46
- const query = `query ($productID: String!) {
47
- getProductRatingSummary(productID: $productID) {
48
- ${data.trim()}
49
- }
50
- }`;
51
- return this.client.sendRequest({ query, variables: { productID } }, 'getProductRatingSummary');
48
+ const args = { productID: ['String!', text(productID)] };
49
+ return this.client.sendRequest(operation('query', 'getProductRatingSummary', args, data), 'getProductRatingSummary');
52
50
  }
53
51
  }
package/shipping.js CHANGED
@@ -8,6 +8,16 @@ export class Shipping {
8
8
  this.client = client;
9
9
  }
10
10
 
11
+ /**
12
+ * The carriers the merchant has connected, each as
13
+ * { carrierName, displayName, serviceCodes }. Pass a carrierName and
14
+ * serviceCodes from here to `rates`. An empty list means none are
15
+ * connected.
16
+ */
17
+ async carriers({ data }) {
18
+ return this.client.sendRequest(operation('query', 'getShippingCarriers', {}, data), 'getShippingCarriers');
19
+ }
20
+
11
21
  async rates({ cartID, carrierName, serviceCodes, data }) {
12
22
  const args = {
13
23
  cartID: ['String!', text(cartID)],
@@ -0,0 +1,44 @@
1
+ // Charging in the shopper's currency: cart.prepareCheckoutPayment and the
2
+ // new orders.create arguments. Offline, like offline.test.js.
3
+ import { test } from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import { Prezense } from '../index.js';
6
+
7
+ function client(body = { data: {} }) {
8
+ const calls = [];
9
+ const fetch = async (url, init) => {
10
+ calls.push(JSON.parse(init.body));
11
+ const text = JSON.stringify(body);
12
+ return { ok: true, status: 200, text: async () => text, json: async () => JSON.parse(text) };
13
+ };
14
+ const sdk = new Prezense('key', 'platform', { baseUrl: 'http://api.test/', trackingUrl: 'http://track.test', fetch });
15
+ return { sdk, calls };
16
+ }
17
+
18
+ test('prepareCheckoutPayment asks for every field by default and returns the charge', async () => {
19
+ const charge = { currency: 'CAD', amount: 74.68, amountMinor: 7468, baseCurrency: 'USD', baseAmount: 50.5, exchangeRate: 1.4274, converted: true };
20
+ const { sdk, calls } = client({ data: { prepareCheckoutPayment: charge } });
21
+ const result = await sdk.cart.prepareCheckoutPayment({ cartID: 'c1' });
22
+ assert.deepEqual(result.response, charge);
23
+ assert.match(calls[0].query, /mutation \(\$cartID: String!\)/);
24
+ assert.match(calls[0].query, /prepareCheckoutPayment\(cartID: \$cartID\) \{ currency amount amountMinor baseCurrency baseAmount exchangeRate converted \}/);
25
+ assert.deepEqual(calls[0].variables, { cartID: 'c1' });
26
+ });
27
+
28
+ test('prepareCheckoutPayment without a cart ID makes no request', async () => {
29
+ const { sdk, calls } = client();
30
+ const result = await sdk.cart.prepareCheckoutPayment({});
31
+ assert.equal(result.error.code, 'MISSING_CART_ID');
32
+ assert.equal(calls.length, 0);
33
+ });
34
+
35
+ test('orders.create sends what the payment charged, and leaves it out when not given', async () => {
36
+ const { sdk, calls } = client({ data: { createOrder: { success: true } } });
37
+ await sdk.orders.create({ cartID: 'c1', stripePaymentIntentID: 'pi_1', paymentAmount: 7468, paymentCurrency: 'cad', data: 'success' });
38
+ assert.match(calls[0].query, /\$paymentAmount: Int, \$paymentCurrency: String/);
39
+ assert.deepEqual(calls[0].variables, { cartID: 'c1', stripePaymentIntentID: 'pi_1', paymentAmount: 7468, paymentCurrency: 'CAD' });
40
+
41
+ await sdk.orders.create({ cartID: 'c1', stripePaymentIntentID: 'pi_1', data: 'success' });
42
+ assert.doesNotMatch(calls[1].query, /payment(Amount|Currency)/);
43
+ assert.deepEqual(calls[1].variables, { cartID: 'c1', stripePaymentIntentID: 'pi_1' });
44
+ });