feat: Move shipping option + profile test and more (#7609)

This commit is contained in:
Oli Juhl
2024-06-05 08:36:41 +02:00
committed by GitHub
parent e44fe78b96
commit dc087bf310
16 changed files with 627 additions and 1110 deletions
@@ -12,5 +12,7 @@ export * from "./delete-shipping-option-rules"
export * from "./delete-shipping-options"
export * from "./set-shipping-options-prices"
export * from "./update-fulfillment"
export * from "./update-shipping-profiles"
export * from "./upsert-shipping-options"
export * from "./validate-shipment"
@@ -0,0 +1,50 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import {
FilterableShippingProfileProps,
IFulfillmentModuleService,
UpdateShippingProfileDTO,
} from "@medusajs/types"
import { getSelectsAndRelationsFromObjectArray } from "@medusajs/utils"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
type StepInput = {
update: UpdateShippingProfileDTO
selector: FilterableShippingProfileProps
}
export const updateShippingProfilesStepId = "update-shipping-profiles"
export const updateShippingProfilesStep = createStep(
updateShippingProfilesStepId,
async (input: StepInput, { container }) => {
const service = container.resolve<IFulfillmentModuleService>(
ModuleRegistrationName.FULFILLMENT
)
const { selects, relations } = getSelectsAndRelationsFromObjectArray([
input.update,
])
const prevData = await service.listShippingProfiles(input.selector, {
select: selects,
relations,
})
const profiles = await service.updateShippingProfiles(
input.selector,
input.update
)
return new StepResponse(profiles, prevData)
},
async (prevData, { container }) => {
if (!prevData?.length) {
return
}
const service = container.resolve<IFulfillmentModuleService>(
ModuleRegistrationName.FULFILLMENT
)
await service.upsertShippingProfiles(prevData)
}
)
@@ -12,3 +12,5 @@ export * from "./delete-shipping-options"
export * from "./update-fulfillment"
export * from "./update-service-zones"
export * from "./update-shipping-options"
export * from "./update-shipping-profiles"
@@ -0,0 +1,16 @@
import { FulfillmentWorkflow } from "@medusajs/types"
import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk"
import { updateShippingProfilesStep } from "../steps/update-shipping-profiles"
export const updateShippingProfilesWorkflowId =
"update-shipping-profiles-workflow"
export const updateShippingProfilesWorkflow = createWorkflow(
updateShippingProfilesWorkflowId,
(
input: WorkflowData<FulfillmentWorkflow.UpdateShippingProfilesWorkflowInput>
): WorkflowData<FulfillmentWorkflow.CreateShippingProfilesWorkflowOutput> => {
const shippingProfiles = updateShippingProfilesStep(input)
return shippingProfiles
}
)
@@ -15,11 +15,32 @@ export interface CreateShippingProfileDTO {
/**
* Holds custom data in key-value pairs.
*/
metadata?: Record<string, unknown>
metadata?: Record<string, unknown> | null
}
/**
* The attributes to update in the shipping profile.
*/
export interface UpdateShippingProfileDTO
extends Partial<CreateShippingProfileDTO> {}
export interface UpdateShippingProfileDTO {
/**
* The name of the shipping profile.
*/
name?: string
/**
* The type of the shipping profile.
*/
type?: string
/**
* Holds custom data in key-value pairs.
*/
metadata?: Record<string, unknown> | null
}
/**
* The attributes to update in the shipping profile.
*/
export interface UpsertShippingProfileDTO extends UpdateShippingProfileDTO {
id?: string
}
+53 -4
View File
@@ -40,7 +40,7 @@ import {
UpsertShippingOptionDTO,
} from "./mutations"
import { CreateFulfillmentDTO } from "./mutations/fulfillment"
import { CreateShippingProfileDTO } from "./mutations/shipping-profile"
import { CreateShippingProfileDTO, UpsertShippingProfileDTO } from "./mutations/shipping-profile"
/**
* The main service interface for the Fulfillment Module.
@@ -1649,7 +1649,8 @@ export interface IFulfillmentModuleService extends IModuleService {
/**
* This method updates existing shipping profiles.
*
* @param {CreateShippingProfileDTO[]} data - The shipping profiles to be created.
* @param {UpdateShippingProfileDTO} data - The shipping profiles update data.
* @param {FilterableShippingProfileProps} selector - The selector of shipping profiles to update
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ShippingProfileDTO[]>} The updated shipping profiles.
*
@@ -1667,14 +1668,16 @@ export interface IFulfillmentModuleService extends IModuleService {
* ])
*/
updateShippingProfiles(
data: UpdateShippingProfileDTO[],
selector: FilterableShippingProfileProps,
data: UpdateShippingProfileDTO,
sharedContext?: Context
): Promise<ShippingProfileDTO[]>
/**
* This method updates an existing shipping profiles.
*
* @param {CreateShippingProfileDTO} data - The shipping profile to be created.
* @param {string} id - The shipping profile to be updated.
* @param {UpdateShippingProfileDTO} data - The shipping profile to be created.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ShippingProfileDTO>} The updated shipping profiles.
*
@@ -1686,6 +1689,7 @@ export interface IFulfillmentModuleService extends IModuleService {
* })
*/
updateShippingProfiles(
id: string,
data: UpdateShippingProfileDTO,
sharedContext?: Context
): Promise<ShippingProfileDTO>
@@ -1719,6 +1723,51 @@ export interface IFulfillmentModuleService extends IModuleService {
*/
deleteShippingProfiles(id: string, sharedContext?: Context): Promise<void>
/**
* This method updates existing shipping profiles, or creates new ones if they don't exist.
*
* @param {UpdateShippingProfileDTO[]} data - The attributes to update or create for each profile.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ProductTagDTO[]>} The updated and created profiles.
*
* @example
* const productTags = await productModuleService.upsertShippingProfiles([
* {
* id: "id_1234",
* metadata: {
* test: true,
* },
* },
* {
* name: "Digital",
* },
* ])
*/
upsertShippingProfiles(
data: UpsertShippingProfileDTO[],
sharedContext?: Context
): Promise<ShippingProfileDTO[]>
/**
* This method updates an existing shipping profile, or creates a new one if it doesn't exist.
*
* @param {UpdateShippingProfileDTO} data - The attributes to update or create for the profile.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ProductTagDTO>} The updated or created profile.
*
* @example
* const productTag = await productModuleService.upsertShippingProfiles({
* id: "id_1234",
* metadata: {
* test: true,
* },
* })
*/
upsertShippingProfiles(
data: UpsertShippingProfileDTO,
sharedContext?: Context
): Promise<ShippingProfileDTO>
/**
* This method soft deletes shipping profiles by their IDs.
*
@@ -1,16 +1,22 @@
import {
deleteShippingProfileWorkflow,
updateShippingProfilesWorkflow,
} from "@medusajs/core-flows"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import {
AdminShippingProfileDeleteResponse,
AdminShippingProfileResponse,
IFulfillmentModuleService,
} from "@medusajs/types"
import { deleteShippingProfileWorkflow } from "@medusajs/core-flows"
import {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "../../../../types/routing"
import { AdminGetShippingProfileParamsType } from "../validators"
import { refetchShippingProfile } from "../helpers"
import {
AdminGetShippingProfileParamsType,
AdminUpdateShippingProfileType,
} from "../validators"
export const GET = async (
req: AuthenticatedMedusaRequest<AdminGetShippingProfileParamsType>,
@@ -48,3 +54,24 @@ export const DELETE = async (
deleted: true,
})
}
export const POST = async (
req: AuthenticatedMedusaRequest<AdminUpdateShippingProfileType>,
res: MedusaResponse<AdminShippingProfileResponse>
) => {
const { id } = req.params
await updateShippingProfilesWorkflow(req.scope).run({
input: { selector: { id }, update: req.body },
})
const shippingProfile = await refetchShippingProfile(
req.params.id,
req.scope,
req.remoteQueryConfig.fields
)
res.status(200).json({
shipping_profile: shippingProfile,
})
}
@@ -9,6 +9,7 @@ import {
AdminCreateShippingProfile,
AdminGetShippingProfileParams,
AdminGetShippingProfilesParams,
AdminUpdateShippingProfile,
} from "./validators"
export const adminShippingProfilesMiddlewares: MiddlewareRoute[] = [
@@ -33,6 +34,17 @@ export const adminShippingProfilesMiddlewares: MiddlewareRoute[] = [
),
],
},
{
method: ["POST"],
matcher: "/admin/shipping-profiles/:id",
middlewares: [
validateAndTransformBody(AdminUpdateShippingProfile),
validateAndTransformQuery(
AdminGetShippingProfileParams,
retrieveTransformQueryConfig
),
],
},
{
method: ["GET"],
matcher: "/admin/shipping-profiles/:id",
@@ -39,3 +39,14 @@ export const AdminCreateShippingProfile = z
metadata: z.record(z.string(), z.unknown()).optional(),
})
.strict()
export type AdminUpdateShippingProfileType = z.infer<
typeof AdminUpdateShippingProfile
>
export const AdminUpdateShippingProfile = z
.object({
name: z.string().optional(),
type: z.string().optional(),
metadata: z.record(z.string(), z.unknown()).optional().nullable(),
})
.strict()
@@ -14,18 +14,18 @@ import {
UpdateServiceZoneDTO,
} from "@medusajs/types"
import {
arrayDifference,
deepEqualObj,
EmitEvents,
getSetDifference,
InjectManager,
InjectTransactionManager,
isDefined,
isPresent,
isString,
MedusaContext,
MedusaError,
ModulesSdkUtils,
arrayDifference,
deepEqualObj,
getSetDifference,
isDefined,
isPresent,
isString,
promiseAll,
} from "@medusajs/utils"
import {
@@ -49,8 +49,8 @@ import {
} from "@utils"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
import { UpdateShippingOptionsInput } from "../types/service"
import FulfillmentProviderService from "./fulfillment-provider"
import { buildCreatedShippingOptionEvents } from "../utils/events"
import FulfillmentProviderService from "./fulfillment-provider"
const generateMethodForModels = [
ServiceZone,
@@ -1541,25 +1541,106 @@ export default class FulfillmentModuleService<
}
updateShippingProfiles(
data: FulfillmentTypes.UpdateShippingProfileDTO[],
selector: FulfillmentTypes.FilterableShippingProfileProps,
data: FulfillmentTypes.UpdateShippingProfileDTO,
sharedContext?: Context
): Promise<FulfillmentTypes.ShippingProfileDTO[]>
updateShippingProfiles(
id: string,
data: FulfillmentTypes.UpdateShippingProfileDTO,
sharedContext?: Context
): Promise<FulfillmentTypes.ShippingProfileDTO>
@InjectTransactionManager("baseRepository_")
async updateShippingProfiles(
data:
| FulfillmentTypes.UpdateShippingProfileDTO
| FulfillmentTypes.UpdateShippingProfileDTO[],
idOrSelector: string | FulfillmentTypes.FilterableShippingProfileProps,
data: FulfillmentTypes.UpdateShippingProfileDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<
FulfillmentTypes.ShippingProfileDTO | FulfillmentTypes.ShippingProfileDTO[]
> {
// TODO: should we implement that or can we get rid of the profiles concept entirely and link to the so instead?
return []
let normalizedInput: ({
id: string
} & FulfillmentTypes.UpdateShippingProfileDTO)[] = []
if (isString(idOrSelector)) {
await this.shippingProfileService_.retrieve(
idOrSelector,
{},
sharedContext
)
normalizedInput = [{ id: idOrSelector, ...data }]
} else {
const profiles = await this.shippingProfileService_.list(
idOrSelector,
{},
sharedContext
)
normalizedInput = profiles.map((profile) => ({
id: profile.id,
...data,
}))
}
const profiles = await this.shippingProfileService_.update(
normalizedInput,
sharedContext
)
const updatedProfiles = await this.baseRepository_.serialize<
FulfillmentTypes.ShippingProfileDTO[]
>(profiles)
return isString(idOrSelector) ? updatedProfiles[0] : updatedProfiles
}
async upsertShippingProfiles(
data: FulfillmentTypes.UpsertShippingProfileDTO[],
sharedContext?: Context
): Promise<FulfillmentTypes.ShippingProfileDTO[]>
async upsertShippingProfiles(
data: FulfillmentTypes.UpsertShippingProfileDTO,
sharedContext?: Context
): Promise<FulfillmentTypes.ShippingProfileDTO>
@InjectTransactionManager("baseRepository_")
async upsertShippingProfiles(
data:
| FulfillmentTypes.UpsertShippingProfileDTO[]
| FulfillmentTypes.UpsertShippingProfileDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<
FulfillmentTypes.ShippingProfileDTO[] | FulfillmentTypes.ShippingProfileDTO
> {
const input = Array.isArray(data) ? data : [data]
const forUpdate = input.filter((prof) => !!prof.id)
const forCreate = input.filter(
(prof): prof is FulfillmentTypes.CreateShippingProfileDTO => !prof.id
)
let created: ShippingProfile[] = []
let updated: ShippingProfile[] = []
if (forCreate.length) {
created = await this.shippingProfileService_.create(
forCreate,
sharedContext
)
}
if (forUpdate.length) {
updated = await this.shippingProfileService_.update(
forUpdate,
sharedContext
)
}
const result = [...created, ...updated]
const allProfiles = await this.baseRepository_.serialize<
| FulfillmentTypes.ShippingProfileDTO[]
| FulfillmentTypes.ShippingProfileDTO
>(result)
return Array.isArray(data) ? allProfiles : allProfiles[0]
}
updateGeoZones(