feat(medusa, types, utils, workflow): Migrate medusa workflow to the workflow package (#4682)

This commit is contained in:
Adrien de Peretti authored and GitHub committed 2023-08-05 16:03:45 +02:00
1 parent 433914ae01
commit dc46927bc6
68 files changed
+1224 -1064

No files matched your search

@@ -3,46 +3,284 @@ import {
TransactionStepsDefinition,
WorkflowManager,
} from "@medusajs/orchestration"
import {
createProducts as createProductsHandler,
removeProducts,
} from "../handlers"
import { exportWorkflow, pipe } from "../helper"
import { ProductTypes } from "@medusajs/types"
import { ProductTypes, WorkflowTypes } from "@medusajs/types"
import {
InventoryHandlers,
MiddlewaresHandlers,
ProductHandlers,
} from "../handlers"
import { aggregateData } from "../helper/aggregate"
enum Actions {
export enum Actions {
prepare = "prepare",
createProducts = "createProducts",
attachToSalesChannel = "attachToSalesChannel",
attachShippingProfile = "attachShippingProfile",
createPrices = "createPrices",
createInventoryItems = "createInventoryItems",
attachInventoryItems = "attachInventoryItems",
result = "result",
}
const workflowSteps: TransactionStepsDefinition = {
export const workflowSteps: TransactionStepsDefinition = {
next: {
action: Actions.createProducts,
action: Actions.prepare,
noCompensation: true,
next: {
action: Actions.createProducts,
next: [
{
action: Actions.attachShippingProfile,
saveResponse: false,
},
{
action: Actions.attachToSalesChannel,
saveResponse: false,
},
{
action: Actions.createPrices,
next: {
action: Actions.createInventoryItems,
next: {
action: Actions.attachInventoryItems,
next: {
action: Actions.result,
noCompensation: true,
},
},
},
},
],
},
},
}
const handlers = new Map([
[
Actions.prepare,
{
invoke: pipe(
{
inputAlias: InputAlias.ProductsInputData,
invoke: {
from: InputAlias.ProductsInputData,
},
},
aggregateData(),
MiddlewaresHandlers.createProductsPrepareData
),
},
],
[
Actions.createProducts,
{
invoke: pipe(
{
inputAlias: InputAlias.Products,
invoke: {
from: InputAlias.Products,
alias: InputAlias.Products,
from: Actions.prepare,
},
},
createProductsHandler
aggregateData(),
ProductHandlers.createProducts
),
compensate: pipe(
{
invoke: {
from: Actions.createProducts,
alias: InputAlias.Products,
alias: ProductHandlers.removeProducts.aliases.products,
},
},
removeProducts
aggregateData(),
ProductHandlers.removeProducts
),
},
],
[
Actions.attachShippingProfile,
{
invoke: pipe(
{
invoke: [
{
from: Actions.prepare,
},
{
from: Actions.createProducts,
alias:
ProductHandlers.attachShippingProfileToProducts.aliases
.products,
},
],
},
aggregateData(),
ProductHandlers.attachShippingProfileToProducts
),
compensate: pipe(
{
invoke: [
{
from: Actions.prepare,
},
{
from: Actions.createProducts,
alias:
ProductHandlers.detachShippingProfileFromProducts.aliases
.products,
},
],
},
aggregateData(),
ProductHandlers.detachShippingProfileFromProducts
),
},
],
[
Actions.attachToSalesChannel,
{
invoke: pipe(
{
invoke: [
{
from: Actions.prepare,
},
{
from: Actions.createProducts,
alias:
ProductHandlers.attachSalesChannelToProducts.aliases.products,
},
],
},
aggregateData(),
ProductHandlers.attachSalesChannelToProducts
),
compensate: pipe(
{
invoke: [
{
from: Actions.prepare,
},
{
from: Actions.createProducts,
alias:
ProductHandlers.detachSalesChannelFromProducts.aliases.products,
},
],
},
aggregateData(),
ProductHandlers.detachSalesChannelFromProducts
),
},
],
[
Actions.createInventoryItems,
{
invoke: pipe(
{
invoke: {
from: Actions.createProducts,
alias: InventoryHandlers.createInventoryItems.aliases.products,
},
},
aggregateData(),
InventoryHandlers.createInventoryItems
),
compensate: pipe(
{
invoke: {
from: Actions.createInventoryItems,
alias:
InventoryHandlers.removeInventoryItems.aliases.inventoryItems,
},
},
aggregateData(),
InventoryHandlers.removeInventoryItems
),
},
],
[
Actions.attachInventoryItems,
{
invoke: pipe(
{
invoke: {
from: Actions.createInventoryItems,
alias:
InventoryHandlers.attachInventoryItems.aliases.inventoryItems,
},
},
aggregateData(),
InventoryHandlers.attachInventoryItems
),
compensate: pipe(
{
invoke: {
from: Actions.createInventoryItems,
alias:
InventoryHandlers.detachInventoryItems.aliases.inventoryItems,
},
},
aggregateData(),
InventoryHandlers.detachInventoryItems
),
},
],
[
Actions.createPrices,
{
invoke: pipe(
{
invoke: [
{
from: Actions.prepare,
},
{
from: Actions.createProducts,
alias:
ProductHandlers.updateProductsVariantsPrices.aliases.products,
},
],
},
aggregateData(),
ProductHandlers.updateProductsVariantsPrices
),
compensate: pipe(
{
invoke: [
{
from: Actions.prepare,
},
{
from: Actions.createProducts,
alias:
ProductHandlers.updateProductsVariantsPrices.aliases.products,
},
],
},
aggregateData(),
MiddlewaresHandlers.createProductsPrepareCreatePricesCompensation,
ProductHandlers.updateProductsVariantsPrices
),
},
],
[
Actions.result,
{
invoke: pipe(
{
invoke: [
{
from: Actions.prepare,
},
{
from: Actions.createProducts,
alias: ProductHandlers.listProducts.aliases.products,
},
],
},
aggregateData(),
ProductHandlers.listProducts
),
},
],
@@ -51,6 +289,6 @@ const handlers = new Map([
WorkflowManager.register(Workflows.CreateProducts, workflowSteps, handlers)
export const createProducts = exportWorkflow<
ProductTypes.CreateProductDTO[],
WorkflowTypes.ProductWorkflow.CreateProductsWorkflowInputDTO,
ProductTypes.ProductDTO[]
>(Workflows.CreateProducts, Actions.createProducts)
>(Workflows.CreateProducts, Actions.result)
+1
View File
@@ -4,6 +4,7 @@ export enum Workflows {
export enum InputAlias {
Products = "products",
ProductsInputData = "productsInputData",
RemovedProducts = "removedProducts",
InventoryItems = "inventoryItems",
@@ -1,31 +0,0 @@
import { InventoryItemDTO, ProductTypes } from "@medusajs/types"
import { InputAlias } from "../definitions"
import { WorkflowArguments } from "../helper"
import { ProductVariantInventoryItem } from "@medusajs/medusa/src"
export async function attachInventoryItems({
container,
data,
}: WorkflowArguments & {
data: {
variant: ProductTypes.ProductVariantDTO
[InputAlias.InventoryItems]: InventoryItemDTO
}[]
}): Promise<ProductVariantInventoryItem[]> {
const manager = container.resolve("manager")
const productVariantInventoryService = container
.resolve("productVariantInventoryService")
.withTransaction(manager)
return await Promise.all(
data
.filter((d) => d)
.map(async ({ variant, [InputAlias.InventoryItems]: inventoryItem }) => {
return await productVariantInventoryService.attachInventoryItem(
variant.id,
inventoryItem.id
)
})
)
}
@@ -1,15 +0,0 @@
import { InputAlias } from "../definitions"
import { ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../helper"
export async function createProducts({
container,
context,
data,
}: WorkflowArguments & {
data: { [InputAlias.Products]: ProductTypes.CreateProductDTO[] }
}): Promise<ProductTypes.ProductDTO[]> {
const productModuleService = container.resolve("productModuleService")
return await productModuleService.create(data[InputAlias.Products], context)
}
+3 -5
View File
@@ -1,5 +1,3 @@
export * from "./remove-products"
export * from "./create-products"
export * from "./create-inventory-items"
export * from "./remove-inventory-items"
export * from "./attach-inventory-items"
export * as ProductHandlers from "./product"
export * as InventoryHandlers from "./inventory"
export * as MiddlewaresHandlers from "./middlewares"
@@ -0,0 +1,36 @@
import { InventoryItemDTO, ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
export async function attachInventoryItems({
container,
context,
data,
}: WorkflowArguments<{
inventoryItems: {
variant: ProductTypes.ProductVariantDTO
inventoryItem: InventoryItemDTO
}[]
}>) {
const { manager } = context
const productVariantInventoryService = container
.resolve("productVariantInventoryService")
.withTransaction(manager)
if (!data?.inventoryItems.length) {
return
}
const inventoryData = data.inventoryItems.map(
({ variant, inventoryItem }) => ({
variantId: variant.id,
inventoryItemId: inventoryItem.id,
})
)
return await productVariantInventoryService.attachInventoryItem(inventoryData)
}
attachInventoryItems.aliases = {
inventoryItems: "inventoryItems",
}
@@ -3,25 +3,32 @@ import {
InventoryItemDTO,
ProductTypes,
} from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
import { InputAlias } from "../definitions"
import { WorkflowArguments } from "../helper"
type Result = {
variant: ProductTypes.ProductVariantDTO
inventoryItem: InventoryItemDTO
}[]
export async function createInventoryItems({
container,
context,
data,
}: WorkflowArguments & {
data: {
[InputAlias.Products]: ProductTypes.ProductDTO[]
}
}): Promise<{ variant: any; inventoryItem: InventoryItemDTO }[]> {
const manager = container.resolve("manager")
}: WorkflowArguments<{
products: ProductTypes.ProductDTO[]
}>): Promise<Result | void> {
const inventoryService: IInventoryService =
container.resolve("inventoryService")
const context = { transactionManager: manager }
const products = data[InputAlias.Products]
const variants = products.reduce(
if (!inventoryService) {
const logger = container.resolve("logger")
logger.warn(
`Inventory service not found. You should install the @medusajs/inventory package to use inventory. The 'createInventoryItems' will be skipped.`
)
return void 0
}
const variants = data.products.reduce(
(
acc: ProductTypes.ProductVariantDTO[],
product: ProductTypes.ProductDTO
@@ -31,7 +38,7 @@ export async function createInventoryItems({
[]
)
return await Promise.all(
const result = await Promise.all(
variants.map(async (variant) => {
if (!variant.manage_inventory) {
return
@@ -49,10 +56,19 @@ export async function createInventoryItems({
height: variant.height!,
width: variant.width!,
},
context
{
transactionManager: (context.transactionManager ??
context.manager) as any,
}
)
return { variant, inventoryItem }
})
)
return result.filter(Boolean) as Result
}
createInventoryItems.aliases = {
products: "products",
}
@@ -0,0 +1,36 @@
import { InventoryItemDTO, ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
export async function detachInventoryItems({
container,
context,
data,
}: WorkflowArguments<{
inventoryItems: {
variant: ProductTypes.ProductVariantDTO
inventoryItem: InventoryItemDTO
}[]
}>): Promise<void> {
const { manager } = context
const productVariantInventoryService = container
.resolve("productVariantInventoryService")
.withTransaction(manager)
if (!data?.inventoryItems.length) {
return
}
await Promise.all(
data.inventoryItems.map(async ({ variant, inventoryItem }) => {
return await productVariantInventoryService.detachInventoryItem(
inventoryItem.id,
variant.id
)
})
)
}
detachInventoryItems.aliases = {
inventoryItems: "inventoryItems",
}
@@ -0,0 +1,4 @@
export * from "./detach-inventory-items"
export * from "./attach-inventory-items"
export * from "./create-inventory-items"
export * from "./remove-inventory-items"
@@ -0,0 +1,30 @@
import { InventoryItemDTO } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
export async function removeInventoryItems({
container,
context,
data,
}: WorkflowArguments<{
inventoryItems: { inventoryItem: InventoryItemDTO }[]
}>) {
const { manager } = context
const inventoryService = container.resolve("inventoryService")
if (!inventoryService) {
const logger = container.resolve("logger")
logger.warn(
`Inventory service not found. You should install the @medusajs/inventory package to use inventory. The 'removeInventoryItems' will be skipped.`
)
return
}
return await inventoryService!.deleteInventoryItem(
data.inventoryItems.map(({ inventoryItem }) => inventoryItem.id),
{ transactionManager: manager }
)
}
removeInventoryItems.aliases = {
inventoryItems: "inventoryItems",
}
@@ -0,0 +1,50 @@
import { ProductTypes, WorkflowTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
type ProductHandle = string
type VariantIndexAndPrices = {
index: number
prices: WorkflowTypes.ProductWorkflow.CreateProductVariantPricesInputDTO[]
}
export async function createProductsPrepareCreatePricesCompensation({
data,
}: WorkflowArguments<{
productsHandleVariantsIndexPricesMap: Map<
ProductHandle,
VariantIndexAndPrices[]
>
products: ProductTypes.ProductDTO[]
}>) {
const productsHandleVariantsIndexPricesMap =
data.productsHandleVariantsIndexPricesMap
const products = data.products
const updatedProductsHandleVariantsIndexPricesMap = new Map()
productsHandleVariantsIndexPricesMap.forEach((items, productHandle) => {
const existingItems =
updatedProductsHandleVariantsIndexPricesMap.get(productHandle) ?? []
items.forEach(({ index }) => {
existingItems.push({
index,
prices: [],
})
})
updatedProductsHandleVariantsIndexPricesMap.set(productHandle, items)
})
return {
alias: "",
value: {
productsHandleVariantsIndexPricesMap:
updatedProductsHandleVariantsIndexPricesMap,
products,
},
}
}
createProductsPrepareCreatePricesCompensation.aliases = {
payload: "payload",
}
@@ -1,8 +1,154 @@
import { InputAlias } from "../../definitions"
import { ProductTypes, SalesChannelTypes, WorkflowTypes } from "@medusajs/types"
import {
FeatureFlagUtils,
kebabCase,
ShippingProfileUtils,
} from "@medusajs/utils"
import { WorkflowArguments } from "../../helper"
type ShippingProfileId = string
type SalesChannelId = string
type ProductHandle = string
type VariantIndexAndPrices = {
index: number
prices: {
region_id?: string
currency_code?: string
amount: number
min_quantity?: number
max_quantity?: number
}[]
}
export type CreateProductsPreparedData = {
products: ProductTypes.CreateProductDTO[]
productsHandleShippingProfileIdMap: Map<ProductHandle, ShippingProfileId>
productsHandleSalesChannelsMap: Map<ProductHandle, SalesChannelId[]>
productsHandleVariantsIndexPricesMap: Map<
ProductHandle,
VariantIndexAndPrices[]
>
config?: WorkflowTypes.CommonWorkflow.WorkflowInputConfig
}
export async function createProductsPrepareData({
container,
context,
data,
}: WorkflowArguments<WorkflowTypes.ProductWorkflow.CreateProductsWorkflowInputDTO>): Promise<CreateProductsPreparedData> {
const { manager } = context
let products = data.products
const shippingProfileService = container
.resolve("shippingProfileService")
.withTransaction(manager)
const featureFlagRouter = container.resolve("featureFlagRouter")
const salesChannelService = container
.resolve("salesChannelService")
.withTransaction(manager)
const salesChannelFeatureFlagKey =
FeatureFlagUtils.SalesChannelFeatureFlag.key
const shippingProfileServiceTx =
shippingProfileService.withTransaction(manager)
const shippingProfiles = await shippingProfileServiceTx.list({
type: [
ShippingProfileUtils.ShippingProfileType.DEFAULT,
ShippingProfileUtils.ShippingProfileType.GIFT_CARD,
],
})
const defaultShippingProfile = shippingProfiles.find(
(sp) => sp.type === ShippingProfileUtils.ShippingProfileType.DEFAULT
)
const gitCardShippingProfile = shippingProfiles.find(
(sp) => sp.type === ShippingProfileUtils.ShippingProfileType.GIFT_CARD
)
let defaultSalesChannel: SalesChannelTypes.SalesChannelDTO | undefined
if (featureFlagRouter.isFeatureEnabled(salesChannelFeatureFlagKey)) {
defaultSalesChannel = await salesChannelService
.withTransaction(manager)
.retrieveDefault()
}
const productsHandleShippingProfileIdMap = new Map<
ProductHandle,
ShippingProfileId
>()
const productsHandleSalesChannelsMap = new Map<
ProductHandle,
SalesChannelId[]
>()
const productsHandleVariantsIndexPricesMap = new Map<
ProductHandle,
VariantIndexAndPrices[]
>()
for (const product of products) {
product.handle ??= kebabCase(product.title)
if (product.is_giftcard) {
productsHandleShippingProfileIdMap.set(
product.handle!,
gitCardShippingProfile!.id
)
} else {
productsHandleShippingProfileIdMap.set(
product.handle!,
defaultShippingProfile!.id
)
}
if (
featureFlagRouter.isFeatureEnabled(salesChannelFeatureFlagKey) &&
!product.sales_channels?.length
) {
productsHandleSalesChannelsMap.set(product.handle!, [
defaultSalesChannel!.id,
])
} else {
productsHandleSalesChannelsMap.set(
product.handle!,
product.sales_channels!.map((s) => s.id)
)
}
if (product.variants) {
const hasPrices = product.variants.some((variant) => {
return (variant.prices?.length ?? 0) > 0
})
if (hasPrices) {
const items =
productsHandleVariantsIndexPricesMap.get(product.handle!) ?? []
product.variants.forEach((variant, index) => {
items.push({
index,
prices: variant.prices!,
})
})
productsHandleVariantsIndexPricesMap.set(product.handle!, items)
}
}
}
products = products.map((productData) => {
delete productData.sales_channels
return productData
})
export function createProductsPrepareData({ data }) {
return {
alias: InputAlias.Products as string,
value: [{}],
products: products as ProductTypes.CreateProductDTO[],
productsHandleShippingProfileIdMap,
productsHandleSalesChannelsMap,
productsHandleVariantsIndexPricesMap,
config: data.config,
}
}
createProductsPrepareData.aliases = {
payload: "payload",
}
@@ -0,0 +1,2 @@
export * from "./create-products-prepare-create-prices-compensation"
export * from "./create-products-prepare-data"
@@ -0,0 +1,48 @@
import { ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
type ProductHandle = string
type SalesChannelId = string
export async function attachSalesChannelToProducts({
container,
context,
data,
}: WorkflowArguments<{
productsHandleSalesChannelsMap: Map<ProductHandle, SalesChannelId[]>
products: ProductTypes.ProductDTO[]
}>): Promise<void> {
const { manager } = context
const productsHandleSalesChannelsMap = data.productsHandleSalesChannelsMap
const products = data.products
const salesChannelService = container.resolve("salesChannelService")
const salesChannelServiceTx = salesChannelService.withTransaction(manager)
const salesChannelIdProductIdsMap = new Map<ProductHandle, SalesChannelId[]>()
products.forEach((product) => {
const salesChannelIds = productsHandleSalesChannelsMap.get(product.handle!)
if (salesChannelIds) {
salesChannelIds.forEach((salesChannelId) => {
const productIds = salesChannelIdProductIdsMap.get(salesChannelId) || []
productIds.push(product.id)
salesChannelIdProductIdsMap.set(salesChannelId, productIds)
})
}
})
await Promise.all(
Array.from(salesChannelIdProductIdsMap.entries()).map(
async ([salesChannelId, productIds]) => {
return await salesChannelServiceTx.addProducts(
salesChannelId,
productIds
)
}
)
)
}
attachSalesChannelToProducts.aliases = {
products: "products",
}
@@ -0,0 +1,46 @@
import { ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
type ProductHandle = string
type ShippingProfileId = string
export async function attachShippingProfileToProducts({
container,
context,
data,
}: WorkflowArguments<{
productsHandleShippingProfileIdMap: Map<ProductHandle, ShippingProfileId>
products: ProductTypes.ProductDTO[]
}>): Promise<void> {
const { manager } = context
const productsHandleShippingProfileIdMap =
data.productsHandleShippingProfileIdMap
const products = data.products
const shippingProfileService = container.resolve("shippingProfileService")
const shippingProfileServiceTx =
shippingProfileService.withTransaction(manager)
const profileIdProductIdsMap = new Map<ShippingProfileId, ProductHandle[]>()
products.forEach((product) => {
const profileId = productsHandleShippingProfileIdMap.get(product.handle!)
if (profileId) {
const productIds = profileIdProductIdsMap.get(profileId) || []
productIds.push(product.id)
profileIdProductIdsMap.set(profileId, productIds)
}
})
await Promise.all(
Array.from(profileIdProductIdsMap.entries()).map(
async ([profileId, productIds]) => {
return await shippingProfileServiceTx.addProducts(profileId, productIds)
}
)
)
}
attachShippingProfileToProducts.aliases = {
products: "products",
}
@@ -0,0 +1,21 @@
import { ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
export async function createProducts({
container,
data,
}: WorkflowArguments<{
products: ProductTypes.CreateProductDTO[]
}>): Promise<ProductTypes.ProductDTO[]> {
const data_ = data.products
const productModuleService: ProductTypes.IProductModuleService =
container.resolve(ModulesDefinition[Modules.PRODUCT].registrationName)
return await productModuleService.create(data_)
}
createProducts.aliases = {
payload: "payload",
}
@@ -0,0 +1,48 @@
import { ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
type ProductHandle = string
type SalesChannelId = string
export async function detachSalesChannelFromProducts({
container,
context,
data,
}: WorkflowArguments<{
productsHandleSalesChannelsMap: Map<ProductHandle, SalesChannelId[]>
products: ProductTypes.ProductDTO[]
}>): Promise<void> {
const { manager } = context
const productsHandleSalesChannelsMap = data.productsHandleSalesChannelsMap
const products = data.products
const salesChannelService = container.resolve("salesChannelService")
const salesChannelServiceTx = salesChannelService.withTransaction(manager)
const salesChannelIdProductIdsMap = new Map<ProductHandle, SalesChannelId[]>()
products.forEach((product) => {
const salesChannelIds = productsHandleSalesChannelsMap.get(product.handle!)
if (salesChannelIds) {
salesChannelIds.forEach((salesChannelId) => {
const productIds = salesChannelIdProductIdsMap.get(salesChannelId) || []
productIds.push(product.id)
salesChannelIdProductIdsMap.set(salesChannelId, productIds)
})
}
})
await Promise.all(
Array.from(salesChannelIdProductIdsMap.entries()).map(
async ([salesChannelId, productIds]) => {
return await salesChannelServiceTx.removeProducts(
salesChannelId,
productIds
)
}
)
)
}
detachSalesChannelFromProducts.aliases = {
products: "products",
}
@@ -0,0 +1,48 @@
import { ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
type ProductHandle = string
type ShippingProfileId = string
export async function detachShippingProfileFromProducts({
container,
context,
data,
}: WorkflowArguments<{
productsHandleShippingProfileIdMap: Map<ProductHandle, ShippingProfileId>
products: ProductTypes.ProductDTO[]
}>): Promise<void> {
const { manager } = context
const productsHandleShippingProfileIdMap =
data.productsHandleShippingProfileIdMap
const products = data.products
const shippingProfileService = container.resolve("shippingProfileService")
const shippingProfileServiceTx =
shippingProfileService.withTransaction(manager)
const profileIdProductIdsMap = new Map<ShippingProfileId, ProductHandle[]>()
products.forEach((product) => {
const profileId = productsHandleShippingProfileIdMap.get(product.handle!)
if (profileId) {
const productIds = profileIdProductIdsMap.get(profileId) || []
productIds.push(product.id)
profileIdProductIdsMap.set(profileId, productIds)
}
})
await Promise.all(
Array.from(profileIdProductIdsMap.entries()).map(
async ([profileId, productIds]) => {
return await shippingProfileServiceTx.removeProducts(
profileId,
productIds
)
}
)
)
}
detachShippingProfileFromProducts.aliases = {
products: "products",
}
@@ -0,0 +1,8 @@
export * from "./create-products"
export * from "./detach-sales-channel-from-products"
export * from "./attach-sales-channel-to-products"
export * from "./detach-shipping-profile-from-products"
export * from "./remove-products"
export * from "./attach-shipping-profile-to-products"
export * from "./list-products"
export * from "./update-products-variants-prices"
@@ -0,0 +1,44 @@
import { ProductTypes, WorkflowTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
export async function listProducts({
container,
context,
data,
}: WorkflowArguments<{
products: ProductTypes.ProductDTO[]
config?: WorkflowTypes.CommonWorkflow.WorkflowInputConfig
}>): Promise<ProductTypes.ProductDTO[]> {
const { manager } = context
const products = data.products
const listConfig = data.config?.listConfig ?? {}
const productService = container.resolve("productService")
const pricingService = container.resolve("pricingService")
const config = {}
let shouldUseConfig = false
if (listConfig.select) {
shouldUseConfig = !!listConfig.select.length
Object.assign(config, { select: listConfig.select })
}
if (listConfig.relations) {
shouldUseConfig = shouldUseConfig || !!listConfig.relations.length
Object.assign(config, { relations: listConfig.relations })
}
const rawProduct = await productService
.withTransaction(manager as any)
.retrieve(products[0].id, shouldUseConfig ? config : undefined)
return await pricingService
.withTransaction(manager as any)
.setProductPrices([rawProduct])
}
listProducts.aliases = {
products: "products",
}
@@ -0,0 +1,21 @@
import { ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../../helper"
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
export async function removeProducts({
container,
data,
}: WorkflowArguments<{ products: ProductTypes.ProductDTO[] }>): Promise<void> {
if (!data.products.length) {
return
}
const productModuleService: ProductTypes.IProductModuleService =
container.resolve(ModulesDefinition[Modules.PRODUCT].registrationName)
await productModuleService.softDelete(data.products.map((p) => p.id))
}
removeProducts.aliases = {
products: "products",
}
@@ -0,0 +1,60 @@
import { ProductTypes, WorkflowTypes } from "@medusajs/types"
import { MedusaError } from "@medusajs/utils"
import { WorkflowArguments } from "../../helper"
type ProductHandle = string
type VariantIndexAndPrices = {
index: number
prices: WorkflowTypes.ProductWorkflow.CreateProductVariantPricesInputDTO[]
}
export async function updateProductsVariantsPrices({
container,
context,
data,
}: WorkflowArguments<{
productsHandleVariantsIndexPricesMap: Map<
ProductHandle,
VariantIndexAndPrices[]
>
products: ProductTypes.ProductDTO[]
}>) {
const { manager } = context
const products = data.products
const productsHandleVariantsIndexPricesMap =
data.productsHandleVariantsIndexPricesMap
const productVariantService = container.resolve("productVariantService")
const productVariantServiceTx = productVariantService.withTransaction(manager)
const variantIdsPricesData: any[] = []
const productsMap = new Map<string, ProductTypes.ProductDTO>(
products.map((p) => [p.handle!, p])
)
for (const mapData of productsHandleVariantsIndexPricesMap.entries()) {
const [handle, variantData] = mapData
const product = productsMap.get(handle)
if (!product) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Product with handle ${handle} not found`
)
}
variantData.forEach((item, index) => {
const variant = product.variants[index]
variantIdsPricesData.push({
variantId: variant.id,
prices: item.prices,
})
})
}
await productVariantServiceTx.updateVariantPrices(variantIdsPricesData)
}
updateProductsVariantsPrices.aliases = {
products: "products",
}
@@ -1,26 +0,0 @@
import { InventoryItemDTO } from "@medusajs/types"
import { InputAlias } from "../definitions"
import { WorkflowArguments } from "../helper"
export async function removeInventoryItems({
container,
data,
}: WorkflowArguments & {
data: {
[InputAlias.InventoryItems]: InventoryItemDTO
}[]
}) {
const manager = container.resolve("manager")
const inventoryService = container.resolve("inventoryService")
const context = { transactionManager: manager }
return await Promise.all(
data.map(async ({ [InputAlias.InventoryItems]: inventoryItem }) => {
return await inventoryService!.deleteInventoryItem(
inventoryItem.id,
context
)
})
)
}
@@ -1,17 +0,0 @@
import { InputAlias } from "../definitions"
import { ProductTypes } from "@medusajs/types"
import { WorkflowArguments } from "../helper"
export async function removeProducts({
container,
data,
}: WorkflowArguments & {
data: {
[InputAlias.Products]: ProductTypes.ProductDTO[]
}
}) {
const productModuleService = container.resolve("productModuleService")
return await productModuleService.softDelete(
data[InputAlias.Products].map((p) => p.id)
)
}
@@ -0,0 +1,55 @@
import { aggregateData } from "../aggregate"
import { WorkflowStepMiddlewareReturn } from "../pipe"
describe("aggregate", function () {
it("should aggregate a new object from the source into a specify target", async function () {
const source = {
stringProp: "stringProp",
anArray: ["anArray"],
input: {
test: "test",
},
another: {
anotherTest: "anotherTest",
},
}
const { value: result } = (await aggregateData(
["input", "another", "stringProp", "anArray"],
"payload"
)({ data: source } as any)) as unknown as WorkflowStepMiddlewareReturn
expect(result).toEqual({
payload: {
...source.input,
...source.another,
anArray: source.anArray,
stringProp: source.stringProp,
},
})
})
it("should aggregate a new object from the entire source into the resul object", async function () {
const source = {
stringProp: "stringProp",
anArray: ["anArray"],
input: {
test: "test",
},
another: {
anotherTest: "anotherTest",
},
}
const { value: result } = (await aggregateData()({
data: source,
} as any)) as unknown as WorkflowStepMiddlewareReturn
expect(result).toEqual({
...source.input,
...source.another,
anArray: source.anArray,
stringProp: source.stringProp,
})
})
})
@@ -0,0 +1,49 @@
import { PipelineHandler, WorkflowArguments } from "./pipe"
import { isObject } from "@medusajs/utils"
/**
* Pipe utils that aggregates data from an object into a new object.
* The new object will have a target key with the aggregated data from the keys.
* @param keys
* @param target
*/
export function aggregateData<
T extends Record<string, unknown> = Record<string, unknown>,
TKeys extends keyof T = keyof T,
Target extends "payload" | string = string
>(keys: TKeys[] = [], target?: Target): PipelineHandler {
return async function ({ data }: WorkflowArguments<T>) {
const workingKeys = (keys.length ? keys : Object.keys(data)) as TKeys[]
const value = workingKeys.reduce((acc, key) => {
let targetAcc = { ...(target ? acc[target as string] : acc) }
targetAcc ??= {}
if (Array.isArray(data[key as string])) {
targetAcc[key as string] = data[key as string]
} else if (isObject(data[key as string])) {
targetAcc = {
...targetAcc,
...(data[key as string] as object),
}
} else {
targetAcc[key as string] = data[key as string]
}
if (target) {
acc[target as string] = {
...acc[target as string],
...targetAcc,
}
} else {
acc = targetAcc
}
return acc
}, {})
return {
alias: target,
value,
}
}
}
+32 -18
View File
@@ -6,14 +6,14 @@ import {
import { InputAlias } from "../definitions"
type WorkflowStepMiddlewareReturn = {
alias: string
export type WorkflowStepMiddlewareReturn = {
alias?: string
value: any
}
type WorkflowStepMiddlewareInput = {
export type WorkflowStepMiddlewareInput = {
from: string
alias: string
alias?: string
}
interface PipelineInput {
@@ -32,11 +32,13 @@ export type WorkflowArguments<T = any> = {
export type PipelineHandler<T extends any = undefined> = (
args: WorkflowArguments
) => T extends undefined
? Promise<WorkflowStepMiddlewareReturn | WorkflowStepMiddlewareReturn[]>
: T
) => Promise<
T extends undefined
? WorkflowStepMiddlewareReturn | WorkflowStepMiddlewareReturn[]
: T
>
export function pipe<T = undefined>(
export function pipe<T>(
input: PipelineInput,
...functions: [...PipelineHandler[], PipelineHandler<T>]
): WorkflowStepHandler {
@@ -48,7 +50,7 @@ export function pipe<T = undefined>(
metadata,
context,
}) => {
const data = {}
let data = {}
const original = {
invoke: invoke ?? {},
@@ -60,7 +62,7 @@ export function pipe<T = undefined>(
}
for (const key in input) {
if (!input[key]) {
if (!input[key] || key === "inputAlias") {
continue
}
@@ -69,13 +71,16 @@ export function pipe<T = undefined>(
}
for (const action of input[key]) {
if (action?.alias) {
if (action.alias) {
data[action.alias] = original[key][action.from]
} else {
data[action.from] = original[key][action.from]
}
}
}
return functions.reduce(async (_, fn) => {
let finalResult
for (const fn of functions) {
let result = await fn({
container,
payload,
@@ -90,13 +95,22 @@ export function pipe<T = undefined>(
data[action.alias] = action.value
}
}
} else if ((result as WorkflowStepMiddlewareReturn)?.alias) {
data[(result as WorkflowStepMiddlewareReturn).alias] = (
result as WorkflowStepMiddlewareReturn
).value
} else if (
result &&
"alias" in (result as WorkflowStepMiddlewareReturn)
) {
if ((result as WorkflowStepMiddlewareReturn).alias) {
data[(result as WorkflowStepMiddlewareReturn).alias!] = (
result as WorkflowStepMiddlewareReturn
).value
} else {
data = (result as WorkflowStepMiddlewareReturn).value
}
}
return result
}, {})
finalResult = result
}
return finalResult
}
}