1 import {
2 CalculatedShippingOptionPrice,
3 CalculateShippingOptionPriceDTO,
4 CreateFulfillmentResult,
5 CreateShippingOptionDTO,
6 FulfillmentDTO,
7 FulfillmentItemDTO,
8 FulfillmentOption,
9 FulfillmentOrderDTO,
10 IFulfillmentProvider,
11 ValidateFulfillmentDataContext,
12 } from "@medusajs/types"
13
14 /**
15 * ### constructor
16 *
17 * The constructor allows you to access resources from the [module's container](https://docs.medusajs.com/learn/fundamentals/modules/container)
18 * using the first parameter, and the module's options using the second parameter.
19 *
20 * :::note
21 *
22 * A module's options are passed when you register it in the Medusa application.
23 *
24 * :::
25 *
26 * If you're creating a client or establishing a connection with a third-party service, do it in the constructor.
27 *
28 * #### Example
29 *
30 * ```ts title="src/modules/my-fulfillment/service.ts"
31 * import { AbstractFulfillmentProviderService } from "@medusajs/framework/utils"
32 * import { Logger } from "@medusajs/framework/types"
33 *
34 * type InjectedDependencies = {
35 * logger: Logger
36 * }
37 *
38 * type Options = {
39 * apiKey: string
40 * }
41 *
42 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
43 * // other properties...
44 * protected logger_: Logger
45 * protected options_: Options
46 * // assuming you're initializing a client
47 * protected client
48 *
49 * constructor(
50 * { logger }: InjectedDependencies,
51 * options: Options
52 * ) {
53 * super()
54 *
55 * this.logger_ = logger
56 * this.options_ = options
57 *
58 * // TODO initialize your client
59 * }
60 * }
61 *
62 * export default MyFulfillmentProviderService
63 * ```
64 */
65 export class AbstractFulfillmentProviderService
66 implements IFulfillmentProvider
67 {
68 /**
69 * Each fulfillment provider has a unique identifier defined in its class. The provider's ID
70 * will be stored as `fp_{identifier}_{id}`, where `{id}` is the provider's `id`
71 * property in the `medusa-config.ts`.
72 *
73 * @example
74 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
75 * static identifier = "my-fulfillment"
76 *
77 * // ...
78 * }
79 */
80 static identifier: string
81
82 /**
83 * @ignore
84 */
85 static _isFulfillmentService = true
86
87 /**
88 * @ignore
89 */
90 static isFulfillmentService(obj) {
91 return obj?.constructor?._isFulfillmentService
92 }
93
94 /**
95 * @ignore
96 */
97 getIdentifier() {
98 return (this.constructor as any).identifier
99 }
100
101 /**
102 * This method retrieves a list of fulfillment options that this provider supports. Admin users will then choose from these options when
103 * they're creating a shipping option. The chosen fulfillment option's object is then stored within the created shipping option's `data` property.
104 * The `data` property is useful to store data relevant for the third-party provider to later process the fulfillment.
105 *
106 * This method is useful if your third-party provider allows you to retrieve support options, carriers, or services from an API. You can then
107 * retrieve those and return then in the method, allowing the admin user to choose from the services provided by the third-party provider.
108 *
109 * @returns The list of fulfillment options. Each object in the array should have an `id` property unique to an item, and a `name` property
110 * that's used to display the option in the admin.
111 *
112 * @example
113 * // other imports...
114 * import { FulfillmentOption } from "@medusajs/framework/types"
115 *
116 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
117 * // ...
118 * async getFulfillmentOptions(): Promise<FulfillmentOption[]> {
119 * // assuming you have a client
120 * const services = await this.client.getServices()
121 *
122 * return services.map((service) => ({
123 * id: service.service_id,
124 * name: service.name,
125 * service_code: service.code,
126 * // can add other relevant data for the provider to later process the shipping option.
127 * }))
128 * }
129 * }
130 */
131 async getFulfillmentOptions(): Promise<FulfillmentOption[]> {
132 throw Error("getFulfillmentOptions must be overridden by the child class")
133 }
134
135 /**
136 * This method validates the `data` property of a shipping method and returns it. The returned data
137 * is stored in the shipping method's `data` property.
138 *
139 * Your fulfillment provider can use the `data` property to store additional information useful for
140 * handling the fulfillment later. For example, you may store an ID from the third-party fulfillment
141 * system.
142 *
143 * @param optionData - The `data` property of the shipping option.
144 * @param data - The `data` property of the shipping method.
145 * @param context - Context details, such as context of the cart or customer.
146 * @returns the data to store in the `data` property of the shipping method.
147 *
148 * @example
149 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
150 * // ...
151 * async validateFulfillmentData(
152 * optionData: any,
153 * data: any,
154 * context: any
155 * ): Promise<any> {
156 * // assuming your client retrieves an ID from the
157 * // third-party service
158 * const externalId = await this.client.getId()
159 *
160 * return {
161 * ...data,
162 * externalId
163 * }
164 * }
165 * }
166 */
167 async validateFulfillmentData(
168 optionData: Record<string, unknown>,
169 data: Record<string, unknown>,
170 context: ValidateFulfillmentDataContext
171 ): Promise<any> {
172 throw Error("validateFulfillmentData must be overridden by the child class")
173 }
174
175 /**
176 * This method validates the `data` property of a shipping option when it's created.
177 *
178 * The `data` property can hold useful information that's later added to the `data` attribute
179 * of shipping methods created from this option.
180 *
181 * @param data - The data to validate.
182 * @return Whether the data is valid.
183 *
184 * @example
185 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
186 * // ...
187 * async validateOption(data: any): Promise<boolean> {
188 * return data.external_id !== undefined
189 * }
190 * }
191 */
192 async validateOption(data: Record<string, unknown>): Promise<boolean> {
193 throw Error("validateOption must be overridden by the child class")
194 }
195
196 /**
197 * This method validates whether a shippin option's price can be calculated during checkout. It's executed when the admin user creates a shipping
198 * option of type `calculated`. If this method returns `false`, an error is thrown as the shipping option's price can't be calculated.
199 *
200 * You can perform the checking using the third-party provider if applicable. The `data` parameter will hold the shipping option's `data` property, which
201 * includes the data of a fulfillment option returned by {@link getFulfillmentOptions}.
202 *
203 * @param data - The `data` property of the shipping option.
204 * @returns Whether the price can be calculated for the shipping option.
205 *
206 * @example
207 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
208 * // ...
209 * async canCalculate(data: CreateShippingOptionDTO): Promise<boolean> {
210 * // assuming you have a client
211 * return await this.client.hasRates(data.id)
212 * }
213 * }
214 */
215 async canCalculate(data: CreateShippingOptionDTO): Promise<boolean> {
216 throw Error("canCalculate must be overridden by the child class")
217 }
218
219 /**
220 * This method calculates the price of a shipping method whose shipping option has the
221 * `price_type` set to `calculated`.
222 *
223 * In this method, you can send a request to your third-party provider to retrieve the prices. The first
224 * parameters holds the `data` property of the shipping method's shipping option, which has fulfillment
225 * object data returned by {@link getFulfillmentOptions}.
226 *
227 * The second parameter holds the `data` property of the shipping method, which has data returned by {@link validateFulfillmentData}.
228 * It can also hold custom data passed from the frontend during checkout.
229 *
230 * So, using both of these data, assuming you're storing in them data related to the third-party service,
231 * you can retrieve the calculated price of the shipping method.
232 *
233 * ### When is this method invoked?
234 *
235 * This method is invoked in Medusa whenever the calculated shipping option's price needs to be resolved
236 * against a cart:
237 *
238 * - When retrieving a cart's shipping options with their prices, such as when the customer views their shipping options during checkout.
239 * - When the shipping method is added to the cart.
240 * - Every time the cart is refreshed. A cart is refreshed after most cart changes, such as adding a line item or updating the cart's details, so this method may be invoked frequently for a cart that has a calculated shipping method.
241 *
242 * The price isn't re-calculated when the cart is completed and converted to an order; the order uses the last price that was stored on the shipping method.
243 *
244 * If this method throws an error, or returns a result without a `calculated_amount`, the shipping
245 * option's price can't be resolved. This blocks the operation that triggered the calculation,
246 * such as adding the shipping method to the cart or the cart refresh triggered by other cart
247 * changes, which can prevent the customer from completing checkout. So, ensure to handle errors
248 * gracefully, such as by falling back to a default price, if you don't want a failure in the
249 * third-party service to block checkout.
250 *
251 * @param optionData - The `data` property of a shipping option.
252 * @param data - The shipping method's `data` property with custom data passed from the frontend.
253 * @param context - The context details, such as the cart details. If the workflow that triggered
254 * the calculation consumed the `setCalculatedShippingPricingContext` hook, its returned properties
255 * are merged into this object as well, with the framework-provided properties always taking
256 * precedence if there's a naming conflict.
257 * @returns The calculated price's details.
258 *
259 * @example
260 * import { CalculateShippingOptionPriceDTO } from "@medusajs/framework/types"
261 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
262 * // ...
263 * async calculatePrice(
264 * optionData: CalculateShippingOptionPriceDTO["optionData"],
265 * data: CalculateShippingOptionPriceDTO["data"],
266 * context: CalculateShippingOptionPriceDTO["context"]
267 * ): Promise<CalculatedShippingOptionPrice> {
268 * // assuming the client can calculate the price using
269 * // the third-party service
270 * const price = await this.client.calculate(data, context)
271 * return {
272 * calculated_amount: price,
273 * // Update this boolean value based on your logic
274 * is_calculated_price_tax_inclusive: true,
275 * }
276 * }
277 * }
278 */
279 async calculatePrice(
280 optionData: CalculateShippingOptionPriceDTO["optionData"],
281 data: CalculateShippingOptionPriceDTO["data"],
282 context: CalculateShippingOptionPriceDTO["context"]
283 ): Promise<CalculatedShippingOptionPrice> {
284 throw Error("calculatePrice must be overridden by the child class")
285 }
286
287 /**
288 * This method is used when a fulfillment is created. If the method returns in the object a
289 * `data` property, it's stored in the fulfillment's `data` property.
290 *
291 * The `data` property is useful when handling the fulfillment later,
292 * as you can access information useful for your integration, such as the ID in the
293 * third-party provider.
294 *
295 * You can also use this method to perform an action with the third-party fulfillment service
296 * since a fulfillment is created, such as purchase a label.
297 *
298 * @param data - The `data` property of the shipping method this fulfillment is created for.
299 * @param items - The items in the fulfillment.
300 * @param order - The order this fulfillment is created for.
301 * @param fulfillment - The fulfillment's details.
302 * @param additionalData - Custom key-value pairs forwarded from the workflow that
303 * created the fulfillment (for example, the `additional_data` of the Create Order
304 * Fulfillment API route). It isn't persisted on the fulfillment.
305 * @returns An object whose `data` property is stored in the fulfillment's `data` property.
306 *
307 * @example
308 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
309 * // ...
310 * async createFulfillment(
311 * data: Record<string, unknown>,
312 * items: Partial<Omit<FulfillmentItemDTO, "fulfillment">>[],
313 * order: Partial<FulfillmentOrderDTO> | undefined,
314 * fulfillment: Partial<Omit<FulfillmentDTO, "provider_id" | "data" | "items">>,
315 * additionalData?: Record<string, unknown>
316 * ): Promise<CreateFulfillmentResult> {
317 * // assuming the client creates a fulfillment
318 * // in the third-party service
319 * const externalData = await this.client.create(
320 * fulfillment,
321 * items
322 * )
323 *
324 * return {
325 * data: {
326 * ...(fulfillment.data as object || {}),
327 * ...externalData
328 * }
329 * }
330 * }
331 * }
332 */
333 async createFulfillment(
334 data: Record<string, unknown>,
335 items: Partial<Omit<FulfillmentItemDTO, "fulfillment">>[],
336 order: Partial<FulfillmentOrderDTO> | undefined,
337 fulfillment: Partial<
338 Omit<FulfillmentDTO, "provider_id" | "data" | "items">
339 >,
340 additionalData?: Record<string, unknown>
341 ): Promise<CreateFulfillmentResult> {
342 throw Error("createFulfillment must be overridden by the child class")
343 }
344
345 /**
346 * This method is used when a fulfillment is canceled. Use it to perform operations
347 * with the third-party fulfillment service.
348 *
349 * @param data - The fulfillment's `data` property.
350 *
351 * @example
352 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
353 * // ...
354 * async cancelFulfillment(data: Record<string, unknown>): Promise<any> {
355 * // assuming the client cancels a fulfillment
356 * // in the third-party service
357 * const { external_id } = data as {
358 * external_id: string
359 * }
360 * await this.client.cancel(external_id)
361 * }
362 * }
363 */
364 async cancelFulfillment(data: Record<string, unknown>): Promise<any> {
365 throw Error("cancelFulfillment must be overridden by the child class")
366 }
367
368 /**
369 * This method retrieves the documents of a fulfillment.
370 *
371 * @param data - The `data` property of the fulfillment.
372 * @returns The fulfillment's documents.
373 *
374 * @example
375 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
376 * // ...
377 * async getFulfillmentDocuments(data: any): Promise<never[]> {
378 * // assuming the client retrieves documents
379 * // from a third-party service
380 * return await this.client.documents(data)
381 * }
382 * }
383 */
384 async getFulfillmentDocuments(data: Record<string, unknown>) {
385 return []
386 }
387
388 /**
389 * This method is used when a fulfillment is created for a return. If the method returns in the object a
390 * `data` property, it's stored in the fulfillment's `data` property.
391 *
392 * The `data` property is useful when handling the fulfillment later,
393 * as you can access information useful for your integration. For example, you
394 * can store an ID for the fulfillment in the third-party service.
395 *
396 * Use this method to perform actions necessary in the third-party fulfillment service, such as
397 * purchasing a label for the return fulfillment.
398 *
399 * @param fulfillment - The fulfillment's details.
400 * @returns An object containing `data` which is stored in the fulfillment's `data` property and `labels` array which is used to create FulfillmentLabels.
401 *
402 * @example
403 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
404 * // ...
405 * async createReturnFulfillment(fulfillment: Record<string, unknown>): Promise<CreateFulfillmentResult> {
406 * // assuming the client creates a fulfillment for a return
407 * // in the third-party service
408 * const externalData = await this.client.createReturn(
409 * fulfillment
410 * )
411 *
412 * return {
413 * data: {
414 * ...(fulfillment.data as object || {}),
415 * ...externalData
416 * }
417 * }
418 * }
419 * }
420 */
421 async createReturnFulfillment(
422 fulfillment: Record<string, unknown>
423 ): Promise<CreateFulfillmentResult> {
424 throw Error("createReturn must be overridden by the child class")
425 }
426
427 /**
428 * This method retrieves documents for a return's fulfillment.
429 *
430 * @param data - The `data` property of the fulfillment.
431 * @returns The fulfillment's documents.
432 *
433 * @example
434 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
435 * // ...
436 * async getReturnDocuments(data: any): Promise<never[]> {
437 * // assuming the client retrieves documents
438 * // from a third-party service
439 * return await this.client.documents(data)
440 * }
441 * }
442 */
443 async getReturnDocuments(data: Record<string, unknown>) {
444 return []
445 }
446
447 /**
448 * This method retrieves the documents for a shipment.
449 *
450 * @param data - The `data` property of the shipmnet.
451 * @returns The shipment's documents.
452 *
453 * @example
454 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
455 * // ...
456 * async getShipmentDocuments(data: any): Promise<never[]> {
457 * // assuming the client retrieves documents
458 * // from a third-party service
459 * return await this.client.documents(data)
460 * }
461 * }
462 *
463 */
464 async getShipmentDocuments(data: Record<string, unknown>) {
465 return []
466 }
467
468 /**
469 * This method retrieves the documents of a fulfillment of a certain type.
470 *
471 * @param fulfillmentData - The `data` property of the fulfillment.
472 * @param documentType - The document's type. For example, `invoice`.
473 * @returns The fulfillment's documents.
474 *
475 * @example
476 * class MyFulfillmentProviderService extends AbstractFulfillmentProviderService {
477 * // ...
478 * async retrieveDocuments(
479 * fulfillmentData: any,
480 * documentType: any
481 * ): Promise<void> {
482 * // assuming the client retrieves documents
483 * // from a third-party service
484 * return await this.client.documents(
485 * fulfillmentData,
486 * documentType
487 * )
488 * }
489 * }
490 */
491 async retrieveDocuments(
492 fulfillmentData: Record<string, unknown>,
493 documentType: string
494 ) {
495 throw Error("retrieveDocuments must be overridden by the child class")
496 }
497 }