@reactionary/medusa 0.9.27 → 0.9.28

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.
@@ -207,10 +207,12 @@ class MedusaCartCapability extends CartCapability {
207
207
  * @param currency
208
208
  * @returns
209
209
  */
210
- createCartPayload(payload) {
210
+ async createCartPayload(payload) {
211
+ const newRegionId = (await this.medusaApi.getActiveRegion()).id;
211
212
  return {
212
213
  currency_code: (this.context.languageContext.currencyCode || "EUR").toLowerCase(),
213
214
  locale: this.context.languageContext.locale,
215
+ region_id: newRegionId,
214
216
  metadata: {
215
217
  name: payload.name
216
218
  }
@@ -245,7 +247,7 @@ class MedusaCartCapability extends CartCapability {
245
247
  try {
246
248
  const client = await this.getClient();
247
249
  const response = await client.store.cart.create(
248
- this.createCartPayload(payload),
250
+ await this.createCartPayload(payload),
249
251
  {
250
252
  fields: this.includedFields
251
253
  }
@@ -58,7 +58,7 @@ class MedusaCheckoutCapability extends CheckoutCapability {
58
58
  *
59
59
  * example: this.includedFields = [includedFields, '+discounts.*'].join(',');
60
60
  */
61
- includedFields = ["+items.*"].join(",");
61
+ includedFields = ["+items.*", "+order.id", "+order.display_id", "+order.custom_display_id"].join(",");
62
62
  initiateCheckoutForCartPayload(payload) {
63
63
  return {
64
64
  billing_address: payload.billingAddress ? this.mapAddressToStoreAddress(payload.billingAddress) : void 0,
@@ -242,41 +242,39 @@ class MedusaCheckoutCapability extends CheckoutCapability {
242
242
  }
243
243
  }
244
244
  async finalizeCheckout(payload) {
245
- const checkout = await this.getById({ identifier: payload.checkout });
245
+ let checkout = await this.getById({ identifier: payload.checkout });
246
246
  if (!checkout.success || !checkout.value.readyForFinalization) {
247
247
  throw new CheckoutNotReadyForFinalizationError(payload.checkout);
248
248
  }
249
- const client = await this.medusaApi.getClient();
250
- const medusaId = payload.checkout;
251
- const response = await client.store.cart.complete(medusaId.key);
252
- if (response.type === "order") {
253
- const updatedCart = await client.store.cart.update(medusaId.key, {
254
- metadata: {
255
- order_id: response.order.id,
256
- order_display_id: response.order?.display_id ? response.order.display_id + "" : ""
257
- }
258
- });
259
- const refreshedCheckout = await this.getById({
260
- identifier: payload.checkout
261
- });
262
- const sessionData = this.medusaApi.getSessionData();
263
- const cartCollectionKey = "_me";
264
- if (sessionData.allOwnedCarts?.[cartCollectionKey]) {
265
- const updatedCollection = sessionData.allOwnedCarts[cartCollectionKey].filter((x) => x.key !== updatedCart.cart.id);
266
- this.medusaApi.setSessionData({
267
- allOwnedCarts: {
268
- ...sessionData.allOwnedCarts,
269
- [cartCollectionKey]: updatedCollection
270
- },
271
- activeCartId: updatedCollection.length > 0 ? updatedCollection[0] : void 0
249
+ if (!checkout.value.resultingOrder) {
250
+ const client = await this.medusaApi.getClient();
251
+ const medusaId = payload.checkout;
252
+ const response = await client.store.cart.complete(medusaId.key);
253
+ if (response.type === "order") {
254
+ checkout = await this.getById({
255
+ identifier: payload.checkout
272
256
  });
257
+ if (!checkout.success) {
258
+ throw new Error(`Unable to reload checkout ${payload.checkout.key} after completion`);
259
+ }
260
+ } else {
261
+ throw new Error(`Failed to finalize checkout ${payload.checkout.key}. Expected order, got ${response.type}`);
273
262
  }
274
- if (!refreshedCheckout.success) {
275
- throw new Error(`Unable to reload checkout ${payload.checkout.key} after completion`);
276
- }
277
- return success(refreshedCheckout.value);
278
263
  }
279
- throw new Error("Something failed during order creation");
264
+ const originatingCartRef = checkout.value.originalCartReference;
265
+ const sessionData = this.medusaApi.getSessionData();
266
+ const cartCollectionKey = "_me";
267
+ if (sessionData.allOwnedCarts?.[cartCollectionKey]) {
268
+ const updatedCollection = sessionData.allOwnedCarts[cartCollectionKey].filter((x) => x.key !== originatingCartRef?.key);
269
+ this.medusaApi.setSessionData({
270
+ allOwnedCarts: {
271
+ ...sessionData.allOwnedCarts,
272
+ [cartCollectionKey]: updatedCollection
273
+ },
274
+ activeCartId: updatedCollection.length > 0 ? updatedCollection[0] : void 0
275
+ });
276
+ }
277
+ return success(checkout.value);
280
278
  }
281
279
  /**
282
280
  * Extension point to map an Address to a Store Address
@@ -1,3 +1,5 @@
1
+ import {
2
+ } from "@medusajs/types";
1
3
  import {
2
4
  AddressIdentifierSchema,
3
5
  MonetaryAmountSchema,
@@ -86,6 +88,9 @@ class MedusaCheckoutFactory {
86
88
  return false;
87
89
  return true;
88
90
  }
91
+ isCart(data) {
92
+ return data.payment_collection !== void 0;
93
+ }
89
94
  parseCheckout(context, data) {
90
95
  const identifier = {
91
96
  key: data.id
@@ -132,33 +137,11 @@ class MedusaCheckoutFactory {
132
137
  };
133
138
  });
134
139
  const paymentInstructions = new Array();
135
- for (const remotePayment of data.payment_collection?.payment_sessions || []) {
136
- if (remotePayment.status === "canceled" || remotePayment.status === "error") {
137
- console.warn(
138
- `Skipping payment session ${remotePayment.id} with status ${remotePayment.status}`
139
- );
140
- continue;
140
+ if (data.payment_collection) {
141
+ const paymentInstruction = this.parsePaymentInstruction(context, data.payment_collection, data);
142
+ if (paymentInstruction) {
143
+ paymentInstructions.push(paymentInstruction);
141
144
  }
142
- const paymentMethodIdentifier = {
143
- method: remotePayment.provider_id,
144
- name: remotePayment.provider_id,
145
- paymentProcessor: remotePayment.provider_id
146
- };
147
- paymentInstructions.push({
148
- identifier: {
149
- key: remotePayment.id
150
- },
151
- amount: {
152
- value: remotePayment.amount,
153
- currency: remotePayment.currency_code?.toUpperCase()
154
- },
155
- paymentMethod: paymentMethodIdentifier,
156
- protocolData: remotePayment.data ? Object.entries(remotePayment.data).map(([key, value]) => ({
157
- key,
158
- value: String(value)
159
- })) : [],
160
- status: "pending"
161
- });
162
145
  }
163
146
  const originalCartReference = {
164
147
  key: data.id,
@@ -169,10 +152,16 @@ class MedusaCheckoutFactory {
169
152
  phone: data.metadata?.["sms_notification"] ?? void 0
170
153
  };
171
154
  let resultingOrder = void 0;
172
- if (data.metadata?.["order_id"]) {
155
+ let displayId = void 0;
156
+ if (data["order"]?.custom_display_id) {
157
+ displayId = Number(data["order"].custom_display_id + "" || "0");
158
+ } else if (data["order"]?.display_id) {
159
+ displayId = Number(data["order"].display_id + "" || "0");
160
+ }
161
+ if (data["order"]?.id) {
173
162
  resultingOrder = {
174
- key: data.metadata?.["order_id"] + "" || "",
175
- display_id: Number(data.metadata?.["order_display_id"] + "" || "0")
163
+ key: data["order"].id || "",
164
+ display_id: displayId
176
165
  };
177
166
  }
178
167
  const readyForFinalization = this.isReadyForFinalization(
@@ -212,6 +201,61 @@ class MedusaCheckoutFactory {
212
201
  };
213
202
  return this.shippingMethodSchema.parse(sm);
214
203
  }
204
+ parsePaymentInstruction(_context, remotePayment, checkout) {
205
+ const mainSession = (remotePayment.payment_sessions || []).find(
206
+ (session) => session.status !== "canceled" && session.status !== "error"
207
+ );
208
+ if (!mainSession) {
209
+ console.log(`Skipping collection ${remotePayment.id} because it has no valid payment sessions`);
210
+ return void 0;
211
+ }
212
+ const paymentMethodIdentifier = {
213
+ method: mainSession.provider_id,
214
+ name: mainSession.provider_id,
215
+ paymentProcessor: mainSession.provider_id
216
+ };
217
+ let status = "pending";
218
+ switch (remotePayment.status) {
219
+ case "not_paid":
220
+ status = "pending";
221
+ break;
222
+ case "awaiting":
223
+ status = "pending";
224
+ break;
225
+ case "authorized":
226
+ status = "authorized";
227
+ break;
228
+ case "partially_authorized":
229
+ status = "pending";
230
+ break;
231
+ case "canceled":
232
+ status = "canceled";
233
+ break;
234
+ case "failed":
235
+ status = "canceled";
236
+ break;
237
+ case "completed":
238
+ status = "capture";
239
+ break;
240
+ }
241
+ const paymentData = mainSession.data || {};
242
+ const pi = {
243
+ identifier: {
244
+ key: remotePayment.id
245
+ },
246
+ amount: {
247
+ value: remotePayment.amount,
248
+ currency: remotePayment.currency_code?.toUpperCase()
249
+ },
250
+ paymentMethod: paymentMethodIdentifier,
251
+ protocolData: paymentData ? Object.entries(paymentData).map(([key, value]) => ({
252
+ key,
253
+ value: String(value)
254
+ })) : [],
255
+ status
256
+ };
257
+ return pi;
258
+ }
215
259
  parsePaymentMethod(_context, data) {
216
260
  const pm = {
217
261
  identifier: {
@@ -35,7 +35,7 @@ class MedusaOrderFactory {
35
35
  }
36
36
  const paymentInstructions = data.payment_collections?.map((pc) => {
37
37
  return this.parsePaymentInstruction(context, pc, data);
38
- }) || [];
38
+ }).filter((x) => !!x) || [];
39
39
  const result = {
40
40
  identifier,
41
41
  userId,
@@ -85,10 +85,17 @@ class MedusaOrderFactory {
85
85
  return item;
86
86
  }
87
87
  parsePaymentInstruction(_context, remotePayment, order) {
88
+ const mainSession = (remotePayment.payment_sessions || []).find(
89
+ (session) => session.status !== "canceled" && session.status !== "error"
90
+ );
91
+ if (!mainSession) {
92
+ console.log(`Skipping collection ${remotePayment.id} because it has no valid payment sessions`);
93
+ return void 0;
94
+ }
88
95
  const paymentMethodIdentifier = {
89
- method: remotePayment.payment_providers?.[0]?.id || "unknown",
90
- name: remotePayment.payment_providers?.[0]?.id || "unknown",
91
- paymentProcessor: remotePayment.payment_providers?.[0]?.id || "unknown"
96
+ method: mainSession.provider_id,
97
+ name: mainSession.provider_id,
98
+ paymentProcessor: mainSession.provider_id
92
99
  };
93
100
  let status = "pending";
94
101
  switch (remotePayment.status) {
@@ -114,7 +121,7 @@ class MedusaOrderFactory {
114
121
  status = "capture";
115
122
  break;
116
123
  }
117
- const paymentData = remotePayment.payments?.[0].data || {};
124
+ const paymentData = mainSession.data || {};
118
125
  const pi = {
119
126
  identifier: {
120
127
  key: remotePayment.id
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@reactionary/medusa",
3
- "version": "0.9.27",
3
+ "version": "0.9.28",
4
4
  "type": "module",
5
5
  "main": "./index.js",
6
6
  "types": "./src/index.d.ts",
7
7
  "dependencies": {
8
8
  "@medusajs/js-sdk": "^2.13.3",
9
- "@reactionary/core": "0.9.27",
9
+ "@reactionary/core": "0.9.28",
10
10
  "debug": "^4.4.3",
11
11
  "@medusajs/types": "^2.13.3",
12
12
  "zod": "4.1.9"
@@ -34,7 +34,7 @@ export declare class MedusaCartCapability<TFactory extends CartFactory = MedusaC
34
34
  * @param currency
35
35
  * @returns
36
36
  */
37
- protected createCartPayload(payload: CartMutationCreateCart): StoreCreateCart;
37
+ protected createCartPayload(payload: CartMutationCreateCart): Promise<StoreCreateCart>;
38
38
  protected addCartToOwnedList(cartIdentifier: MedusaCartIdentifier, companyId?: CompanyIdentifier): void;
39
39
  protected removeCartFromOwnedList(cartIdentifier: MedusaCartIdentifier, company?: CompanyIdentifier): void;
40
40
  createCart(payload: CartMutationCreateCart): Promise<Result<CartFactoryCartOutput<TFactory>>>;
@@ -1,5 +1,6 @@
1
- import type { StoreCart, StoreCartAddress, StoreCartLineItem, StoreCartShippingOptionWithServiceZone, StorePaymentProvider } from '@medusajs/types';
2
- import { type Address, type AnyCheckoutSchema, type AnyPaymentMethodSchema, type AnyShippingMethodSchema, type CheckoutFactory, type CheckoutItem, type CheckoutSchema, type CostBreakDown, type Currency, type ItemCostBreakdown, type PaymentInstruction, type PaymentMethodSchema, type RequestContext, type ShippingInstruction, type ShippingMethodSchema } from '@reactionary/core';
1
+ import type { StorePaymentCollection } from '@medusajs/types';
2
+ import { type StoreCart, type StoreCartAddress, type StoreCartLineItem, type StoreCartShippingOptionWithServiceZone, type StorePaymentProvider } from '@medusajs/types';
3
+ import { type Address, type AnyCheckoutSchema, type AnyPaymentMethodSchema, type AnyShippingMethodSchema, type CheckoutFactory, type CheckoutItem, type CheckoutSchema, type CostBreakDown, type Currency, type ItemCostBreakdown, type PaymentInstruction, type PaymentMethodIdentifier, type PaymentMethodSchema, type RequestContext, type ShippingInstruction, type ShippingMethodSchema } from '@reactionary/core';
3
4
  import type * as z from 'zod';
4
5
  export declare class MedusaCheckoutFactory<TCheckoutSchema extends AnyCheckoutSchema = typeof CheckoutSchema, TShippingMethodSchema extends AnyShippingMethodSchema = typeof ShippingMethodSchema, TPaymentMethodSchema extends AnyPaymentMethodSchema = typeof PaymentMethodSchema> implements CheckoutFactory<TCheckoutSchema, TShippingMethodSchema, TPaymentMethodSchema> {
5
6
  readonly checkoutSchema: TCheckoutSchema;
@@ -33,7 +34,23 @@ export declare class MedusaCheckoutFactory<TCheckoutSchema extends AnyCheckoutSc
33
34
  */
34
35
  protected parseAddress(_context: RequestContext, storeAddress: StoreCartAddress): Address;
35
36
  protected isReadyForFinalization(price: CostBreakDown, paymentInstructions: PaymentInstruction[], billingAddress?: Address, shippingAddress?: Address, shippingInstruction?: ShippingInstruction): boolean;
37
+ protected isCart(data: StoreCart): data is StoreCart;
36
38
  parseCheckout(context: RequestContext, data: StoreCart): z.output<TCheckoutSchema>;
37
39
  parseShippingMethod(_context: RequestContext, data: StoreCartShippingOptionWithServiceZone): z.output<TShippingMethodSchema>;
40
+ protected parsePaymentInstruction(_context: RequestContext, remotePayment: StorePaymentCollection, checkout: StoreCart): {
41
+ identifier: {
42
+ key: string;
43
+ };
44
+ amount: {
45
+ value: number;
46
+ currency: Currency;
47
+ };
48
+ paymentMethod: PaymentMethodIdentifier;
49
+ protocolData: {
50
+ key: string;
51
+ value: string;
52
+ }[];
53
+ status: "pending" | "authorized" | "canceled" | "capture";
54
+ } | undefined;
38
55
  parsePaymentMethod(_context: RequestContext, data: StorePaymentProvider): z.output<TPaymentMethodSchema>;
39
56
  }
@@ -39,5 +39,5 @@ export declare class MedusaOrderFactory<TOrderSchema extends AnyOrderSchema = ty
39
39
  value: string;
40
40
  }[];
41
41
  status: "pending" | "authorized" | "canceled" | "capture";
42
- };
42
+ } | undefined;
43
43
  }