diff --git a/.github/actions/setup-server/action.yml b/.github/actions/setup-server/action.yml index 56b890a6fe..155fa294bd 100644 --- a/.github/actions/setup-server/action.yml +++ b/.github/actions/setup-server/action.yml @@ -5,7 +5,7 @@ inputs: node-version: description: "Node version" required: false - default: "16.10.0" + default: "20.0.0" cache-extension: description: "Extension for fetching cached dependencies" required: true diff --git a/integration-tests/helpers/create-admin-user.ts b/integration-tests/helpers/create-admin-user.ts index 46fb0fe528..eb551c278d 100644 --- a/integration-tests/helpers/create-admin-user.ts +++ b/integration-tests/helpers/create-admin-user.ts @@ -20,18 +20,22 @@ export const createAdminUser = async ( const authModule: IAuthModuleService = appContainer.resolve( ModuleRegistrationName.AUTH ) - const user = await userModule.create({ + const user = await userModule.createUsers({ first_name: "Admin", last_name: "User", email: "admin@medusa.js", }) - const authIdentity = await authModule.create({ - provider: "emailpass", - entity_id: "admin@medusa.js", - provider_metadata: { - password: "somepassword", - }, + const authIdentity = await authModule.createAuthIdentities({ + provider_identities: [ + { + provider: "emailpass", + entity_id: "admin@medusa.js", + provider_metadata: { + password: "somepassword", + }, + }, + ], app_metadata: { user_id: user.id, }, diff --git a/integration-tests/helpers/seed-storefront-defaults.ts b/integration-tests/helpers/seed-storefront-defaults.ts index 9186ed1a0c..6945ae80d8 100644 --- a/integration-tests/helpers/seed-storefront-defaults.ts +++ b/integration-tests/helpers/seed-storefront-defaults.ts @@ -20,14 +20,14 @@ export const seedStorefrontDefaults = async ( // Creates the stores & default sales channel await createDefaultsWorkflow(container).run() - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "Default Region", currency_code: defaultCurrency, }) - let [store] = await storeModule.list({}) + let [store] = await storeModule.listStores({}) - store = await storeModule.update(store.id, { + store = await storeModule.updateStores(store.id, { default_region_id: region.id, supported_currency_codes: [region.currency_code], default_currency_code: region.currency_code, diff --git a/integration-tests/http/__tests__/fulfillment/admin/fulfillment-sets.spec.ts b/integration-tests/http/__tests__/fulfillment/admin/fulfillment-sets.spec.ts index 75d556af1f..70cee78d5d 100644 --- a/integration-tests/http/__tests__/fulfillment/admin/fulfillment-sets.spec.ts +++ b/integration-tests/http/__tests__/fulfillment/admin/fulfillment-sets.spec.ts @@ -31,7 +31,7 @@ medusaIntegrationTestRunner({ const fulfillmentModule: IFulfillmentModuleService = getContainer().resolve(ModuleRegistrationName.FULFILLMENT) - fulfillmentSet1 = await fulfillmentModule.create({ + fulfillmentSet1 = await fulfillmentModule.createFulfillmentSets({ name: "Test fulfillment set", type: "pickup", }) diff --git a/integration-tests/http/__tests__/product/store/product.spec.ts b/integration-tests/http/__tests__/product/store/product.spec.ts index c2fbf0bcfb..303fc4ca54 100644 --- a/integration-tests/http/__tests__/product/store/product.spec.ts +++ b/integration-tests/http/__tests__/product/store/product.spec.ts @@ -91,10 +91,10 @@ medusaIntegrationTestRunner({ const defaultId = (await api.get("/admin/stores", adminHeaders)).data .stores?.[0]?.id if (defaultId) { - storeModule.delete(defaultId) + storeModule.deleteStores(defaultId) } - store = await storeModule.create({ + store = await storeModule.createStores({ name: "New store", supported_currency_codes: ["usd", "dkk"], default_currency_code: "usd", @@ -532,13 +532,13 @@ medusaIntegrationTestRunner({ ) const service = appContainer.resolve(ModuleRegistrationName.STORE) - const [store] = await service.list() + const [store] = await service.listStores() if (store) { - await service.delete(store.id) + await service.deleteStores(store.id) } - await service.create({ + await service.createStores({ supported_currency_codes: ["usd", "dkk"], default_currency_code: "usd", default_sales_channel_id: defaultSalesChannel.id, @@ -969,13 +969,13 @@ medusaIntegrationTestRunner({ ) const service = appContainer.resolve(ModuleRegistrationName.STORE) - const [store] = await service.list() + const [store] = await service.listStores() if (store) { - await service.delete(store.id) + await service.deleteStores(store.id) } - await service.create({ + await service.createStores({ supported_currency_codes: ["usd", "dkk"], default_currency_code: "usd", default_sales_channel_id: defaultSalesChannel.id, diff --git a/integration-tests/http/__tests__/stock-location/admin/stock-location.spec.ts b/integration-tests/http/__tests__/stock-location/admin/stock-location.spec.ts index 7be10f0788..cc18583a92 100644 --- a/integration-tests/http/__tests__/stock-location/admin/stock-location.spec.ts +++ b/integration-tests/http/__tests__/stock-location/admin/stock-location.spec.ts @@ -301,7 +301,7 @@ medusaIntegrationTestRunner({ const fulfillmentModule = getContainer().resolve( ModuleRegistrationName.FULFILLMENT ) - const sets = await fulfillmentModule.list() + const sets = await fulfillmentModule.listFulfillmentSets() expect(sets).toHaveLength(0) }) diff --git a/integration-tests/http/__tests__/store/admin/store.spec.ts b/integration-tests/http/__tests__/store/admin/store.spec.ts index b1e4529e7f..d75185695f 100644 --- a/integration-tests/http/__tests__/store/admin/store.spec.ts +++ b/integration-tests/http/__tests__/store/admin/store.spec.ts @@ -25,10 +25,10 @@ medusaIntegrationTestRunner({ const defaultId = (await api.get("/admin/stores", adminHeaders)).data .stores?.[0]?.id if (defaultId) { - storeModule.delete(defaultId) + await storeModule.deleteStores(defaultId) } - store = await storeModule.create({ + store = await storeModule.createStores({ name: "New store", supported_currency_codes: ["usd", "dkk"], default_currency_code: "usd", diff --git a/integration-tests/modules/__tests__/auth/admin/email-password-provider.spec.ts b/integration-tests/modules/__tests__/auth/admin/email-password-provider.spec.ts index 8298a49478..babe32fa89 100644 --- a/integration-tests/modules/__tests__/auth/admin/email-password-provider.spec.ts +++ b/integration-tests/modules/__tests__/auth/admin/email-password-provider.spec.ts @@ -1,5 +1,5 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import { IAuthModuleService, ICustomerModuleService } from "@medusajs/types" +import { IAuthModuleService } from "@medusajs/types" import Scrypt from "scrypt-kdf" import { medusaIntegrationTestRunner } from "medusa-test-utils" import { @@ -16,13 +16,8 @@ medusaIntegrationTestRunner({ testSuite: ({ dbConnection, getContainer, api }) => { describe("POST /auth/emailpass", () => { let appContainer - let customerModuleService: ICustomerModuleService - beforeAll(async () => { appContainer = getContainer() - customerModuleService = appContainer.resolve( - ModuleRegistrationName.CUSTOMER - ) }) beforeEach(async () => { @@ -40,7 +35,7 @@ medusaIntegrationTestRunner({ ModuleRegistrationName.AUTH ) - await authService.create({ + await authService.createAuthIdentities({ provider_identities: [ { provider: "emailpass", @@ -75,7 +70,7 @@ medusaIntegrationTestRunner({ ModuleRegistrationName.AUTH ) - await authService.create({ + await authService.createAuthIdentities({ provider_identities: [ { provider: "emailpass", diff --git a/integration-tests/modules/__tests__/cart/store/add-promotions-to-cart.spec.ts b/integration-tests/modules/__tests__/cart/store/add-promotions-to-cart.spec.ts index a38e36b7ee..596e79e188 100644 --- a/integration-tests/modules/__tests__/cart/store/add-promotions-to-cart.spec.ts +++ b/integration-tests/modules/__tests__/cart/store/add-promotions-to-cart.spec.ts @@ -40,48 +40,50 @@ medusaIntegrationTestRunner({ describe("POST /store/carts/:id/promotions", () => { it("should add line item adjustments to a cart based on promotions", async () => { - const appliedPromotion = await promotionModuleService.create({ - code: "PROMOTION_APPLIED", - type: PromotionType.STANDARD, - application_method: { - type: "fixed", - target_type: "items", - allocation: "each", - value: "300", - apply_to_quantity: 1, - currency_code: "usd", - max_quantity: 1, - target_rules: [ - { - attribute: "product_id", - operator: "eq", - values: "prod_tshirt", - }, - ], - }, - }) + const appliedPromotion = + await promotionModuleService.createPromotions({ + code: "PROMOTION_APPLIED", + type: PromotionType.STANDARD, + application_method: { + type: "fixed", + target_type: "items", + allocation: "each", + value: "300", + apply_to_quantity: 1, + currency_code: "usd", + max_quantity: 1, + target_rules: [ + { + attribute: "product_id", + operator: "eq", + values: "prod_tshirt", + }, + ], + }, + }) - const createdPromotion = await promotionModuleService.create({ - code: "PROMOTION_TEST", - type: PromotionType.STANDARD, - application_method: { - type: "fixed", - target_type: "items", - allocation: "across", - value: "1000", - apply_to_quantity: 1, - currency_code: "usd", - target_rules: [ - { - attribute: "product_id", - operator: "eq", - values: "prod_mat", - }, - ], - }, - }) + const createdPromotion = + await promotionModuleService.createPromotions({ + code: "PROMOTION_TEST", + type: PromotionType.STANDARD, + application_method: { + type: "fixed", + target_type: "items", + allocation: "across", + value: "1000", + apply_to_quantity: 1, + currency_code: "usd", + target_rules: [ + { + attribute: "product_id", + operator: "eq", + values: "prod_mat", + }, + ], + }, + }) - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "usd", items: [ // Adjustment to add @@ -152,41 +154,42 @@ medusaIntegrationTestRunner({ }) it("should add shipping method adjustments to a cart based on promotions", async () => { - const [appliedPromotion] = await promotionModuleService.create([ - { - code: "PROMOTION_APPLIED", - type: PromotionType.STANDARD, - rules: [ - { - attribute: "customer_id", - operator: "in", - values: ["cus_test"], - }, - { - attribute: "currency_code", - operator: "in", - values: ["eur"], - }, - ], - application_method: { - type: "fixed", - target_type: "shipping_methods", - allocation: "each", - value: "100", - max_quantity: 1, - currency_code: "usd", - target_rules: [ + const [appliedPromotion] = + await promotionModuleService.createPromotions([ + { + code: "PROMOTION_APPLIED", + type: PromotionType.STANDARD, + rules: [ { - attribute: "name", + attribute: "customer_id", operator: "in", - values: ["express"], + values: ["cus_test"], + }, + { + attribute: "currency_code", + operator: "in", + values: ["eur"], }, ], + application_method: { + type: "fixed", + target_type: "shipping_methods", + allocation: "each", + value: "100", + max_quantity: 1, + currency_code: "usd", + target_rules: [ + { + attribute: "name", + operator: "in", + values: ["express"], + }, + ], + }, }, - }, - ]) + ]) - const [newPromotion] = await promotionModuleService.create([ + const [newPromotion] = await promotionModuleService.createPromotions([ { code: "PROMOTION_NEW", type: PromotionType.STANDARD, @@ -220,7 +223,7 @@ medusaIntegrationTestRunner({ }, ]) - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "eur", customer_id: "cus_test", items: [ diff --git a/integration-tests/modules/__tests__/cart/store/cart.workflows.spec.ts b/integration-tests/modules/__tests__/cart/store/cart.workflows.spec.ts index 6e01f48116..7fe2072619 100644 --- a/integration-tests/modules/__tests__/cart/store/cart.workflows.spec.ts +++ b/integration-tests/modules/__tests__/cart/store/cart.workflows.spec.ts @@ -18,13 +18,13 @@ import { ICartModuleService, ICustomerModuleService, IFulfillmentModuleService, - IInventoryServiceNext, + IInventoryService, IPaymentModuleService, IPricingModuleService, IProductModuleService, IRegionModuleService, ISalesChannelModuleService, - IStockLocationServiceNext, + IStockLocationService, } from "@medusajs/types" import { ContainerRegistrationKeys, RuleOperator } from "@medusajs/utils" import { medusaIntegrationTestRunner } from "medusa-test-utils" @@ -50,10 +50,9 @@ medusaIntegrationTestRunner({ let productModule: IProductModuleService let pricingModule: IPricingModuleService let paymentModule: IPaymentModuleService - let inventoryModule: IInventoryServiceNext - let stockLocationModule: IStockLocationServiceNext + let stockLocationModule: IStockLocationService + let inventoryModule: IInventoryService let fulfillmentModule: IFulfillmentModuleService - let locationModule: IStockLocationServiceNext let remoteLink, remoteQuery let defaultRegion @@ -78,9 +77,6 @@ medusaIntegrationTestRunner({ fulfillmentModule = appContainer.resolve( ModuleRegistrationName.FULFILLMENT ) - locationModule = appContainer.resolve( - ModuleRegistrationName.STOCK_LOCATION - ) remoteLink = appContainer.resolve(ContainerRegistrationKeys.REMOTE_LINK) remoteQuery = appContainer.resolve( ContainerRegistrationKeys.REMOTE_QUERY @@ -97,20 +93,20 @@ medusaIntegrationTestRunner({ describe("CreateCartWorkflow", () => { it("should create a cart", async () => { - const region = await regionModuleService.create({ + const region = await regionModuleService.createRegions({ name: "US", currency_code: "usd", }) - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await stockLocationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Warehouse", }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -121,7 +117,7 @@ medusaIntegrationTestRunner({ }, ]) - const inventoryItem = await inventoryModule.create({ + const inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -134,7 +130,7 @@ medusaIntegrationTestRunner({ }, ]) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, @@ -185,7 +181,7 @@ medusaIntegrationTestRunner({ }, }) - const cart = await cartModuleService.retrieve(result.id, { + const cart = await cartModuleService.retrieveCart(result.id, { relations: ["items"], }) @@ -207,20 +203,20 @@ medusaIntegrationTestRunner({ }) it("should revert if the cart creation fails", async () => { - const region = await regionModuleService.create({ + const region = await regionModuleService.createRegions({ name: "US", currency_code: "usd", }) - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await stockLocationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Warehouse", }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -231,7 +227,7 @@ medusaIntegrationTestRunner({ }, ]) - const inventoryItem = await inventoryModule.create({ + const inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -244,7 +240,7 @@ medusaIntegrationTestRunner({ }, ]) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, @@ -314,7 +310,7 @@ medusaIntegrationTestRunner({ }) it("should throw when no regions exist", async () => { - await regionModuleService.delete(defaultRegion.id) + await regionModuleService.deleteRegions(defaultRegion.id) const { errors } = await createCartWorkflow(appContainer).run({ input: { @@ -332,15 +328,15 @@ medusaIntegrationTestRunner({ }) it("should throw if variants are out of stock", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await stockLocationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Warehouse", }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -379,12 +375,12 @@ medusaIntegrationTestRunner({ adminHeaders ) - const region = await regionModuleService.create({ + const region = await regionModuleService.createRegions({ name: "US", currency_code: "usd", }) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, @@ -448,7 +444,7 @@ medusaIntegrationTestRunner({ }) it("should throw if sales channel is disabled", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", is_disabled: true, }) @@ -500,7 +496,7 @@ medusaIntegrationTestRunner({ }, ]) - const customers = await customerModule.list({ + const customers = await customerModule.listCustomers({ email: "tony@stark-industries.com", }) @@ -517,7 +513,7 @@ medusaIntegrationTestRunner({ }, }) - const customer = await customerModule.create({ + const customer = await customerModule.createCustomers({ email: "tony@stark-industries.com", }) @@ -539,7 +535,7 @@ medusaIntegrationTestRunner({ }, ]) - const customers = await customerModule.list({ + const customers = await customerModule.listCustomers({ email: "tony@stark-industries.com", }) @@ -550,20 +546,20 @@ medusaIntegrationTestRunner({ describe("AddToCartWorkflow", () => { it("should add item to cart", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await stockLocationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Warehouse", }) - let cart = await cartModuleService.create({ + let cart = await cartModuleService.createCarts({ currency_code: "usd", sales_channel_id: salesChannel.id, }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -574,7 +570,7 @@ medusaIntegrationTestRunner({ }, ]) - const inventoryItem = await inventoryModule.create({ + const inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -587,7 +583,7 @@ medusaIntegrationTestRunner({ }, ]) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, @@ -623,7 +619,7 @@ medusaIntegrationTestRunner({ }, ]) - cart = await cartModuleService.retrieve(cart.id, { + cart = await cartModuleService.retrieveCart(cart.id, { select: ["id", "region_id", "currency_code", "sales_channel_id"], }) @@ -639,7 +635,7 @@ medusaIntegrationTestRunner({ }, }) - cart = await cartModuleService.retrieve(cart.id, { + cart = await cartModuleService.retrieveCart(cart.id, { relations: ["items"], }) @@ -659,20 +655,20 @@ medusaIntegrationTestRunner({ }) it("should throw if no price sets for variant exist", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await stockLocationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Warehouse", }) - let cart = await cartModuleService.create({ + let cart = await cartModuleService.createCarts({ currency_code: "usd", sales_channel_id: salesChannel.id, }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -683,7 +679,7 @@ medusaIntegrationTestRunner({ }, ]) - const inventoryItem = await inventoryModule.create({ + const inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -742,7 +738,7 @@ medusaIntegrationTestRunner({ }) it("should throw if variant does not exist", async () => { - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "usd", }) @@ -774,15 +770,15 @@ medusaIntegrationTestRunner({ describe("updateLineItemInCartWorkflow", () => { it("should update item in cart", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await stockLocationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Warehouse", }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -793,7 +789,7 @@ medusaIntegrationTestRunner({ }, ]) - const inventoryItem = await inventoryModule.create({ + const inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -806,7 +802,7 @@ medusaIntegrationTestRunner({ }, ]) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, @@ -842,7 +838,7 @@ medusaIntegrationTestRunner({ }, ]) - let cart = await cartModuleService.create({ + let cart = await cartModuleService.createCarts({ currency_code: "usd", sales_channel_id: salesChannel.id, items: [ @@ -855,7 +851,7 @@ medusaIntegrationTestRunner({ ], }) - cart = await cartModuleService.retrieve(cart.id, { + cart = await cartModuleService.retrieveCart(cart.id, { select: ["id", "region_id", "currency_code"], relations: ["items", "items.variant_id", "items.metadata"], }) @@ -901,15 +897,15 @@ medusaIntegrationTestRunner({ }, }) - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await stockLocationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Warehouse", }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -920,7 +916,7 @@ medusaIntegrationTestRunner({ }, ]) - const inventoryItem = await inventoryModule.create({ + const inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -933,7 +929,7 @@ medusaIntegrationTestRunner({ }, ]) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, @@ -969,7 +965,7 @@ medusaIntegrationTestRunner({ }, ]) - let cart = await cartModuleService.create({ + let cart = await cartModuleService.createCarts({ currency_code: "usd", items: [ { @@ -981,7 +977,7 @@ medusaIntegrationTestRunner({ ], }) - cart = await cartModuleService.retrieve(cart.id, { + cart = await cartModuleService.retrieveCart(cart.id, { select: ["id", "region_id", "currency_code"], relations: ["items", "items.variant_id", "items.metadata"], }) @@ -1031,7 +1027,7 @@ medusaIntegrationTestRunner({ describe("deleteLineItems", () => { it("should delete items in cart", async () => { - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "usd", items: [ { @@ -1072,7 +1068,7 @@ medusaIntegrationTestRunner({ }, }) - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "usd", items: [ { @@ -1115,7 +1111,7 @@ medusaIntegrationTestRunner({ describe("createPaymentCollectionForCart", () => { it("should create a payment collection and link it to cart", async () => { - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "dkk", region_id: defaultRegion.id, items: [ @@ -1181,12 +1177,12 @@ medusaIntegrationTestRunner({ } ) - const region = await regionModuleService.create({ + const region = await regionModuleService.createRegions({ name: "US", currency_code: "usd", }) - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "usd", region_id: region.id, items: [ @@ -1253,7 +1249,7 @@ medusaIntegrationTestRunner({ describe("refreshPaymentCollectionForCart", () => { it("should refresh a payment collection for a cart", async () => { - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "dkk", region_id: defaultRegion.id, items: [ @@ -1320,12 +1316,12 @@ medusaIntegrationTestRunner({ describe("compensation", () => { it("should revert payment collection amount and create a new payment session", async () => { - const region = await regionModuleService.create({ + const region = await regionModuleService.createRegions({ name: "US", currency_code: "usd", }) - const testCart = await cartModuleService.create({ + const testCart = await cartModuleService.createCarts({ currency_code: "usd", region_id: region.id, items: [ @@ -1431,7 +1427,7 @@ medusaIntegrationTestRunner({ let priceSet beforeEach(async () => { - cart = await cartModuleService.create({ + cart = await cartModuleService.createCarts({ currency_code: "usd", shipping_address: { country_code: "us", @@ -1444,7 +1440,7 @@ medusaIntegrationTestRunner({ type: "default", }) - fulfillmentSet = await fulfillmentModule.create({ + fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ @@ -1455,7 +1451,7 @@ medusaIntegrationTestRunner({ ], }) - priceSet = await pricingModule.create({ + priceSet = await pricingModule.createPriceSets({ prices: [{ amount: 3000, currency_code: "usd" }], }) }) @@ -1500,7 +1496,7 @@ medusaIntegrationTestRunner({ }, }) - cart = await cartModuleService.retrieve(cart.id, { + cart = await cartModuleService.retrieveCart(cart.id, { relations: ["shipping_methods"], }) @@ -1592,15 +1588,15 @@ medusaIntegrationTestRunner({ describe("listShippingOptionsForCartWorkflow", () => { it("should list shipping options for cart", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await locationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Europe", }) - let cart = await cartModuleService.create({ + let cart = await cartModuleService.createCarts({ currency_code: "usd", sales_channel_id: salesChannel.id, shipping_address: { @@ -1616,7 +1612,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await fulfillmentModule.create({ + const fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ @@ -1645,7 +1641,7 @@ medusaIntegrationTestRunner({ }, }) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, @@ -1681,7 +1677,7 @@ medusaIntegrationTestRunner({ }, ]) - cart = await cartModuleService.retrieve(cart.id, { + cart = await cartModuleService.retrieveCart(cart.id, { select: ["id"], relations: ["shipping_address"], }) @@ -1711,15 +1707,15 @@ medusaIntegrationTestRunner({ }) it("should list no shipping options for cart, if sales channel is not associated with location", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await locationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Europe", }) - let cart = await cartModuleService.create({ + let cart = await cartModuleService.createCarts({ currency_code: "usd", sales_channel_id: salesChannel.id, shipping_address: { @@ -1735,7 +1731,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await fulfillmentModule.create({ + const fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ @@ -1764,7 +1760,7 @@ medusaIntegrationTestRunner({ }, }) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, @@ -1792,7 +1788,7 @@ medusaIntegrationTestRunner({ }, ]) - cart = await cartModuleService.retrieve(cart.id, { + cart = await cartModuleService.retrieveCart(cart.id, { select: ["id"], relations: ["shipping_address"], }) @@ -1816,15 +1812,15 @@ medusaIntegrationTestRunner({ }) it("should throw when shipping options are missing prices", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await locationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Europe", }) - let cart = await cartModuleService.create({ + let cart = await cartModuleService.createCarts({ currency_code: "usd", sales_channel_id: salesChannel.id, shipping_address: { @@ -1840,7 +1836,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await fulfillmentModule.create({ + const fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ @@ -1888,7 +1884,7 @@ medusaIntegrationTestRunner({ }, ]) - cart = await cartModuleService.retrieve(cart.id, { + cart = await cartModuleService.retrieveCart(cart.id, { select: ["id"], relations: ["shipping_address"], }) diff --git a/integration-tests/modules/__tests__/cart/store/carts.spec.ts b/integration-tests/modules/__tests__/cart/store/carts.spec.ts index ed02aeea46..3255933687 100644 --- a/integration-tests/modules/__tests__/cart/store/carts.spec.ts +++ b/integration-tests/modules/__tests__/cart/store/carts.spec.ts @@ -98,16 +98,16 @@ medusaIntegrationTestRunner({ describe("POST /store/carts", () => { it("should create a cart", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Webshop", }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -123,7 +123,7 @@ medusaIntegrationTestRunner({ }, ]) - const [priceSet, priceSetTwo] = await pricingModule.create([ + const [priceSet, priceSetTwo] = await pricingModule.createPriceSets([ { prices: [ { @@ -209,7 +209,7 @@ medusaIntegrationTestRunner({ it("should create cart with customer from email and tax lines", async () => { await setupTaxStructure(taxModule) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product default tax", variants: [ @@ -218,11 +218,11 @@ medusaIntegrationTestRunner({ }, ]) - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Webshop", }) - const [priceSet] = await pricingModule.create([ + const [priceSet] = await pricingModule.createPriceSets([ { prices: [{ amount: 3000, currency_code: "usd" }] }, ]) @@ -281,7 +281,7 @@ medusaIntegrationTestRunner({ }) it("should create cart with any region", async () => { - await regionModule.create({ + await regionModule.createRegions({ name: "US", currency_code: "usd", }) @@ -305,11 +305,11 @@ medusaIntegrationTestRunner({ }) it("should create cart with default store sales channel", async () => { - const sc = await scModule.create({ + const sc = await scModule.createSalesChannels({ name: "Webshop", }) - await storeService.update(store.id, { + await storeService.updateStores(store.id, { default_sales_channel_id: sc.id, }) @@ -330,7 +330,7 @@ medusaIntegrationTestRunner({ }) it("should create cart with region currency code", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) @@ -381,15 +381,15 @@ medusaIntegrationTestRunner({ }) it("throws if publishable key is not associated with sales channel", async () => { - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Retail Store", }) - const salesChannel2 = await scModule.create({ + const salesChannel2 = await scModule.createSalesChannels({ name: "Webshop", }) - const pubKey = await apiKeyModule.create({ + const pubKey = await apiKeyModule.createApiKeys({ title: "Test key", type: "publishable", created_by: "test", @@ -426,15 +426,15 @@ medusaIntegrationTestRunner({ }) it("throws if publishable key has multiple associated sales channels", async () => { - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Retail Store", }) - const salesChannel2 = await scModule.create({ + const salesChannel2 = await scModule.createSalesChannels({ name: "Webshop", }) - const pubKey = await apiKeyModule.create({ + const pubKey = await apiKeyModule.createApiKeys({ title: "Test key", type: "publishable", created_by: "test", @@ -469,11 +469,11 @@ medusaIntegrationTestRunner({ }) it("should create cart with sales channel if pub key does not have any scopes defined", async () => { - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Retail Store", }) - const pubKey = await apiKeyModule.create({ + const pubKey = await apiKeyModule.createApiKeys({ title: "Test key", type: "publishable", created_by: "test", @@ -498,11 +498,11 @@ medusaIntegrationTestRunner({ }) it("should create cart with sales channel associated with pub key", async () => { - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Retail Store", }) - const pubKey = await apiKeyModule.create({ + const pubKey = await apiKeyModule.createApiKeys({ title: "Test key", type: "publishable", created_by: "test", @@ -545,7 +545,7 @@ medusaIntegrationTestRunner({ it("should update a cart with promo codes with a replace action", async () => { await setupTaxStructure(taxModule) - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) @@ -558,7 +558,7 @@ medusaIntegrationTestRunner({ }, ] - const appliedPromotion = await promotionModule.create({ + const appliedPromotion = await promotionModule.createPromotions({ code: "PROMOTION_APPLIED", type: PromotionType.STANDARD, application_method: { @@ -573,7 +573,7 @@ medusaIntegrationTestRunner({ }, }) - const createdPromotion = await promotionModule.create({ + const createdPromotion = await promotionModule.createPromotions({ code: "PROMOTION_TEST", type: PromotionType.STANDARD, application_method: { @@ -587,7 +587,7 @@ medusaIntegrationTestRunner({ }, }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", email: "tony@stark.com", region_id: region.id, @@ -686,13 +686,13 @@ medusaIntegrationTestRunner({ it("should not generate tax lines if region is not present or automatic taxes is false", async () => { await setupTaxStructure(taxModule) - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", automatic_taxes: false, }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", email: "tony@stark.com", shipping_address: { @@ -732,7 +732,7 @@ medusaIntegrationTestRunner({ }) ) - await cartModule.update(cart.id, { + await cartModule.updateCarts(cart.id, { region_id: region.id, }) @@ -758,16 +758,16 @@ medusaIntegrationTestRunner({ it("should update a cart's region, sales channel, customer data and tax lines", async () => { await setupTaxStructure(taxModule) - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "us", currency_code: "usd", }) - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Webshop", }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "eur", email: "tony@stark.com", shipping_address: { @@ -795,7 +795,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await fulfillmentModule.create({ + const fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ @@ -967,12 +967,12 @@ medusaIntegrationTestRunner({ it("should remove invalid shipping methods", async () => { await setupTaxStructure(taxModule) - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ region_id: region.id, currency_code: "eur", email: "tony@stark.com", @@ -992,7 +992,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await fulfillmentModule.create({ + const fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ @@ -1101,12 +1101,12 @@ medusaIntegrationTestRunner({ describe("POST /store/carts/:id", () => { it("should create and update a cart", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Webshop", }) @@ -1151,16 +1151,16 @@ medusaIntegrationTestRunner({ describe("GET /store/carts", () => { it("should get cart", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Webshop", }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", items: [ { @@ -1250,22 +1250,22 @@ medusaIntegrationTestRunner({ beforeEach(async () => { await setupTaxStructure(taxModule) - region = await regionModule.create({ + region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) }) it("should add item to cart", async () => { - const customer = await customerModule.create({ + const customer = await customerModule.createCustomers({ email: "tony@stark-industries.com", }) - const salesChannel = await scModule.create({ + const salesChannel = await scModule.createSalesChannels({ name: "Webshop", }) - const [productWithSpecialTax] = await productModule.create([ + const [productWithSpecialTax] = await productModule.createProducts([ { // This product ID is setup in the tax structure fixture (setupTaxStructure) id: "product_id_1", @@ -1274,7 +1274,7 @@ medusaIntegrationTestRunner({ } as any, ]) - const [productWithDefaultTax] = await productModule.create([ + const [productWithDefaultTax] = await productModule.createProducts([ { title: "Test product default tax", variants: [ @@ -1283,7 +1283,7 @@ medusaIntegrationTestRunner({ }, ]) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", customer_id: customer.id, sales_channel_id: salesChannel.id, @@ -1308,7 +1308,7 @@ medusaIntegrationTestRunner({ ], }) - const appliedPromotion = await promotionModule.create({ + const appliedPromotion = await promotionModule.createPromotions({ code: "PROMOTION_APPLIED", type: PromotionType.STANDARD, application_method: { @@ -1337,14 +1337,15 @@ medusaIntegrationTestRunner({ }, ]) - const [priceSet, priceSetDefaultTax] = await pricingModule.create([ - { - prices: [{ amount: 3000, currency_code: "usd" }], - }, - { - prices: [{ amount: 2000, currency_code: "usd" }], - }, - ]) + const [priceSet, priceSetDefaultTax] = + await pricingModule.createPriceSets([ + { + prices: [{ amount: 3000, currency_code: "usd" }], + }, + { + prices: [{ amount: 2000, currency_code: "usd" }], + }, + ]) await remoteLink.create([ { @@ -1520,12 +1521,12 @@ medusaIntegrationTestRunner({ describe("POST /store/payment-collections", () => { it("should create a payment collection for the cart", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", region_id: region.id, }) @@ -1547,12 +1548,12 @@ medusaIntegrationTestRunner({ }) it("should return an existing payment collection for the cart", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", region_id: region.id, }) @@ -1580,17 +1581,17 @@ medusaIntegrationTestRunner({ }) it("should create a new payment collection for a new cart", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", }) - const firstCart = await cartModule.create({ + const firstCart = await cartModule.createCarts({ currency_code: "usd", region_id: region.id, }) - const secondCart = await cartModule.create({ + const secondCart = await cartModule.createCarts({ currency_code: "usd", region_id: region.id, }) @@ -1622,13 +1623,13 @@ medusaIntegrationTestRunner({ it("should update a carts tax lines when region.automatic_taxes is false", async () => { await setupTaxStructure(taxModule) - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", automatic_taxes: false, }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", region_id: region.id, shipping_address: { @@ -1679,13 +1680,13 @@ medusaIntegrationTestRunner({ it("should throw error when shipping is not present", async () => { await setupTaxStructure(taxModule) - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "US", currency_code: "usd", automatic_taxes: false, }) - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", region_id: region.id, items: [ @@ -1713,7 +1714,7 @@ medusaIntegrationTestRunner({ describe("POST /store/carts/:id/shipping-methods", () => { it("should add a shipping methods to a cart", async () => { - const cart = await cartModule.create({ + const cart = await cartModule.createCarts({ currency_code: "usd", shipping_address: { country_code: "us" }, items: [], @@ -1725,7 +1726,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await fulfillmentModule.create({ + const fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ @@ -1736,7 +1737,7 @@ medusaIntegrationTestRunner({ ], }) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [{ amount: 3000, currency_code: "usd" }], }) @@ -1809,7 +1810,7 @@ medusaIntegrationTestRunner({ beforeEach(async () => { await setupTaxStructure(taxModule) - region = await regionService.create({ + region = await regionService.createRegions({ name: "Test region", countries: ["US"], currency_code: "usd", @@ -1861,7 +1862,7 @@ medusaIntegrationTestRunner({ type: "default", }) - fulfillmentSet = await fulfillmentModule.create({ + fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ diff --git a/integration-tests/modules/__tests__/cart/store/remove-promotions-from-cart.spec.ts b/integration-tests/modules/__tests__/cart/store/remove-promotions-from-cart.spec.ts index 498aa65776..3a5805d377 100644 --- a/integration-tests/modules/__tests__/cart/store/remove-promotions-from-cart.spec.ts +++ b/integration-tests/modules/__tests__/cart/store/remove-promotions-from-cart.spec.ts @@ -40,49 +40,51 @@ medusaIntegrationTestRunner({ describe("DELETE /store/carts/:id/promotions", () => { it("should remove line item adjustments from a cart based on promotions", async () => { - const appliedPromotion = await promotionModuleService.create({ - code: "PROMOTION_APPLIED", - type: PromotionType.STANDARD, - application_method: { - type: "fixed", - target_type: "items", - allocation: "each", - value: "300", - apply_to_quantity: 1, - currency_code: "usd", - max_quantity: 1, - target_rules: [ - { - attribute: "product_id", - operator: "eq", - values: "prod_tshirt", - }, - ], - }, - }) + const appliedPromotion = + await promotionModuleService.createPromotions({ + code: "PROMOTION_APPLIED", + type: PromotionType.STANDARD, + application_method: { + type: "fixed", + target_type: "items", + allocation: "each", + value: "300", + apply_to_quantity: 1, + currency_code: "usd", + max_quantity: 1, + target_rules: [ + { + attribute: "product_id", + operator: "eq", + values: "prod_tshirt", + }, + ], + }, + }) - const appliedPromotionToRemove = await promotionModuleService.create({ - code: "PROMOTION_APPLIED_TO_REMOVE", - type: PromotionType.STANDARD, - application_method: { - type: "fixed", - target_type: "items", - allocation: "each", - value: "300", - apply_to_quantity: 1, - currency_code: "usd", - max_quantity: 1, - target_rules: [ - { - attribute: "product_id", - operator: "eq", - values: "prod_tshirt", - }, - ], - }, - }) + const appliedPromotionToRemove = + await promotionModuleService.createPromotions({ + code: "PROMOTION_APPLIED_TO_REMOVE", + type: PromotionType.STANDARD, + application_method: { + type: "fixed", + target_type: "items", + allocation: "each", + value: "300", + apply_to_quantity: 1, + currency_code: "usd", + max_quantity: 1, + target_rules: [ + { + attribute: "product_id", + operator: "eq", + values: "prod_tshirt", + }, + ], + }, + }) - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "usd", items: [ { @@ -170,71 +172,73 @@ medusaIntegrationTestRunner({ }) it("should add shipping method adjustments to a cart based on promotions", async () => { - const appliedPromotion = await promotionModuleService.create({ - code: "PROMOTION_APPLIED", - type: PromotionType.STANDARD, - rules: [ - { - attribute: "customer_id", - operator: "in", - values: ["cus_test"], - }, - { - attribute: "currency_code", - operator: "in", - values: ["eur"], - }, - ], - application_method: { - type: "fixed", - target_type: "shipping_methods", - allocation: "each", - value: "100", - max_quantity: 1, - currency_code: "usd", - target_rules: [ + const appliedPromotion = + await promotionModuleService.createPromotions({ + code: "PROMOTION_APPLIED", + type: PromotionType.STANDARD, + rules: [ { - attribute: "name", + attribute: "customer_id", operator: "in", - values: ["express"], + values: ["cus_test"], + }, + { + attribute: "currency_code", + operator: "in", + values: ["eur"], }, ], - }, - }) + application_method: { + type: "fixed", + target_type: "shipping_methods", + allocation: "each", + value: "100", + max_quantity: 1, + currency_code: "usd", + target_rules: [ + { + attribute: "name", + operator: "in", + values: ["express"], + }, + ], + }, + }) - const appliedPromotionToRemove = await promotionModuleService.create({ - code: "PROMOTION_APPLIED_TO_REMOVE", - type: PromotionType.STANDARD, - rules: [ - { - attribute: "customer_id", - operator: "in", - values: ["cus_test"], - }, - { - attribute: "currency_code", - operator: "in", - values: ["eur"], - }, - ], - application_method: { - type: "fixed", - target_type: "shipping_methods", - allocation: "each", - value: "100", - max_quantity: 1, - currency_code: "usd", - target_rules: [ + const appliedPromotionToRemove = + await promotionModuleService.createPromotions({ + code: "PROMOTION_APPLIED_TO_REMOVE", + type: PromotionType.STANDARD, + rules: [ { - attribute: "name", + attribute: "customer_id", operator: "in", - values: ["express"], + values: ["cus_test"], + }, + { + attribute: "currency_code", + operator: "in", + values: ["eur"], }, ], - }, - }) + application_method: { + type: "fixed", + target_type: "shipping_methods", + allocation: "each", + value: "100", + max_quantity: 1, + currency_code: "usd", + target_rules: [ + { + attribute: "name", + operator: "in", + values: ["express"], + }, + ], + }, + }) - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ currency_code: "eur", customer_id: "cus_test", items: [ diff --git a/integration-tests/modules/__tests__/customer-group/admin/batch-add-customers.ts b/integration-tests/modules/__tests__/customer-group/admin/batch-add-customers.ts index ffb79dfed4..ea14b4f9e7 100644 --- a/integration-tests/modules/__tests__/customer-group/admin/batch-add-customers.ts +++ b/integration-tests/modules/__tests__/customer-group/admin/batch-add-customers.ts @@ -29,10 +29,10 @@ medusaIntegrationTestRunner({ }) it("should batch add customers to a group", async () => { - const group = await customerModuleService.createCustomerGroup({ + const group = await customerModuleService.createCustomerGroups({ name: "VIP", }) - const customers = await customerModuleService.create([ + const customers = await customerModuleService.createCustomers([ { first_name: "Test", last_name: "Test", diff --git a/integration-tests/modules/__tests__/customer-group/admin/batch-remove-customers.ts b/integration-tests/modules/__tests__/customer-group/admin/batch-remove-customers.ts index d6ed7200f7..c452013fd3 100644 --- a/integration-tests/modules/__tests__/customer-group/admin/batch-remove-customers.ts +++ b/integration-tests/modules/__tests__/customer-group/admin/batch-remove-customers.ts @@ -29,10 +29,10 @@ medusaIntegrationTestRunner({ }) it("should batch delete customers from a group", async () => { - const group = await customerModuleService.createCustomerGroup({ + const group = await customerModuleService.createCustomerGroups({ name: "VIP", }) - const customers = await customerModuleService.create([ + const customers = await customerModuleService.createCustomers([ { first_name: "Test", last_name: "Test", diff --git a/integration-tests/modules/__tests__/customer-group/admin/create-customer-group.ts b/integration-tests/modules/__tests__/customer-group/admin/create-customer-group.ts index bfc4b9ef7d..d4cba8e88a 100644 --- a/integration-tests/modules/__tests__/customer-group/admin/create-customer-group.ts +++ b/integration-tests/modules/__tests__/customer-group/admin/create-customer-group.ts @@ -1,5 +1,3 @@ -import { ICustomerModuleService } from "@medusajs/types" -import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { createAdminUser } from "../../../../helpers/create-admin-user" import { medusaIntegrationTestRunner } from "medusa-test-utils" @@ -15,13 +13,9 @@ medusaIntegrationTestRunner({ testSuite: ({ dbConnection, getContainer, api }) => { describe("POST /admin/customer-groups", () => { let appContainer - let customerModuleService: ICustomerModuleService beforeAll(async () => { appContainer = getContainer() - customerModuleService = appContainer.resolve( - ModuleRegistrationName.CUSTOMER - ) }) beforeEach(async () => { diff --git a/integration-tests/modules/__tests__/customer-group/admin/delete-customer-group.ts b/integration-tests/modules/__tests__/customer-group/admin/delete-customer-group.ts index 8c9d618076..16a8c2942f 100644 --- a/integration-tests/modules/__tests__/customer-group/admin/delete-customer-group.ts +++ b/integration-tests/modules/__tests__/customer-group/admin/delete-customer-group.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should delete a group", async () => { - const group = await customerModuleService.createCustomerGroup({ + const group = await customerModuleService.createCustomerGroups({ name: "VIP", }) diff --git a/integration-tests/modules/__tests__/customer-group/admin/list-customer-group-customers.ts b/integration-tests/modules/__tests__/customer-group/admin/list-customer-group-customers.ts index 62913b9c27..269fb9024a 100644 --- a/integration-tests/modules/__tests__/customer-group/admin/list-customer-group-customers.ts +++ b/integration-tests/modules/__tests__/customer-group/admin/list-customer-group-customers.ts @@ -29,11 +29,11 @@ medusaIntegrationTestRunner({ }) it("should get all customer groups and its count", async () => { - const group = await customerModuleService.createCustomerGroup({ + const group = await customerModuleService.createCustomerGroups({ name: "Test", }) - const customers = await customerModuleService.create([ + const customers = await customerModuleService.createCustomers([ { first_name: "Test", last_name: "Test", diff --git a/integration-tests/modules/__tests__/customer-group/admin/list-customer-groups.spec.ts b/integration-tests/modules/__tests__/customer-group/admin/list-customer-groups.spec.ts index 2ce766900a..bdbdd61298 100644 --- a/integration-tests/modules/__tests__/customer-group/admin/list-customer-groups.spec.ts +++ b/integration-tests/modules/__tests__/customer-group/admin/list-customer-groups.spec.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should get all customer groups and its count", async () => { - await customerModuleService.createCustomerGroup({ + await customerModuleService.createCustomerGroups({ name: "Test", }) @@ -46,7 +46,7 @@ medusaIntegrationTestRunner({ }) it("should support searching of customer groups", async () => { - await customerModuleService.createCustomerGroup([ + await customerModuleService.createCustomerGroups([ { name: "First group", }, diff --git a/integration-tests/modules/__tests__/customer-group/admin/retrieve-customer-group.ts b/integration-tests/modules/__tests__/customer-group/admin/retrieve-customer-group.ts index 24f854159e..22ebfc42f0 100644 --- a/integration-tests/modules/__tests__/customer-group/admin/retrieve-customer-group.ts +++ b/integration-tests/modules/__tests__/customer-group/admin/retrieve-customer-group.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should retrieve customer group", async () => { - const group = await customerModuleService.createCustomerGroup({ + const group = await customerModuleService.createCustomerGroups({ name: "Test", }) diff --git a/integration-tests/modules/__tests__/customer-group/admin/update-customer-group.ts b/integration-tests/modules/__tests__/customer-group/admin/update-customer-group.ts index 9970789aba..c35773bd01 100644 --- a/integration-tests/modules/__tests__/customer-group/admin/update-customer-group.ts +++ b/integration-tests/modules/__tests__/customer-group/admin/update-customer-group.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should update a customer group", async () => { - const customer = await customerModuleService.createCustomerGroup({ + const customer = await customerModuleService.createCustomerGroups({ name: "VIP", }) diff --git a/integration-tests/modules/__tests__/customer/admin/create-customer-addresses.ts b/integration-tests/modules/__tests__/customer/admin/create-customer-addresses.ts index 591ab3647a..0644d5eff4 100644 --- a/integration-tests/modules/__tests__/customer/admin/create-customer-addresses.ts +++ b/integration-tests/modules/__tests__/customer/admin/create-customer-addresses.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should create a customer address", async () => { // Create a customer - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", }) @@ -56,16 +56,16 @@ medusaIntegrationTestRunner({ ]) ) - const customerWithAddresses = await customerModuleService.retrieve( - customer.id, - { relations: ["addresses"] } - ) + const customerWithAddresses = + await customerModuleService.retrieveCustomer(customer.id, { + relations: ["addresses"], + }) expect(customerWithAddresses.addresses?.length).toEqual(1) }) it("sets new shipping address as default and unsets the old one", async () => { - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", addresses: [ @@ -100,7 +100,7 @@ medusaIntegrationTestRunner({ }) it("sets new billing address as default and unsets the old one", async () => { - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", addresses: [ diff --git a/integration-tests/modules/__tests__/customer/admin/create-customer.ts b/integration-tests/modules/__tests__/customer/admin/create-customer.ts index d2d6e8f1bd..706b0569b6 100644 --- a/integration-tests/modules/__tests__/customer/admin/create-customer.ts +++ b/integration-tests/modules/__tests__/customer/admin/create-customer.ts @@ -1,5 +1,3 @@ -import { ICustomerModuleService } from "@medusajs/types" -import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { createAdminUser } from "../../../../helpers/create-admin-user" import { medusaIntegrationTestRunner } from "medusa-test-utils" @@ -15,13 +13,8 @@ medusaIntegrationTestRunner({ testSuite: ({ dbConnection, getContainer, api }) => { describe("POST /admin/customers", () => { let appContainer - let customerModuleService: ICustomerModuleService - beforeAll(async () => { appContainer = getContainer() - customerModuleService = appContainer.resolve( - ModuleRegistrationName.CUSTOMER - ) }) beforeEach(async () => { diff --git a/integration-tests/modules/__tests__/customer/admin/delete-customer-address.spec.ts b/integration-tests/modules/__tests__/customer/admin/delete-customer-address.spec.ts index 25612aaf40..c40716fb52 100644 --- a/integration-tests/modules/__tests__/customer/admin/delete-customer-address.spec.ts +++ b/integration-tests/modules/__tests__/customer/admin/delete-customer-address.spec.ts @@ -29,12 +29,12 @@ medusaIntegrationTestRunner({ }) it("should update a customer address", async () => { - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", }) - const address = await customerModuleService.addAddresses({ + const address = await customerModuleService.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -48,7 +48,7 @@ medusaIntegrationTestRunner({ expect(response.status).toEqual(200) - const updatedCustomer = await customerModuleService.retrieve( + const updatedCustomer = await customerModuleService.retrieveCustomer( customer.id, { relations: ["addresses"], diff --git a/integration-tests/modules/__tests__/customer/admin/delete-customer.ts b/integration-tests/modules/__tests__/customer/admin/delete-customer.ts index 1c2ae9e03c..643b50edf1 100644 --- a/integration-tests/modules/__tests__/customer/admin/delete-customer.ts +++ b/integration-tests/modules/__tests__/customer/admin/delete-customer.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should delete a customer", async () => { - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", }) @@ -41,7 +41,7 @@ medusaIntegrationTestRunner({ expect(response.status).toEqual(200) - const deletedCustomer = await customerModuleService.retrieve( + const deletedCustomer = await customerModuleService.retrieveCustomer( customer.id, { withDeleted: true, diff --git a/integration-tests/modules/__tests__/customer/admin/list-customer-addresses.ts b/integration-tests/modules/__tests__/customer/admin/list-customer-addresses.ts index 2e7be1b0c0..7e3156fad0 100644 --- a/integration-tests/modules/__tests__/customer/admin/list-customer-addresses.ts +++ b/integration-tests/modules/__tests__/customer/admin/list-customer-addresses.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should get all customer addresses and its count", async () => { - const [customer] = await customerModuleService.create([ + const [customer] = await customerModuleService.createCustomers([ { first_name: "Test", last_name: "Test", @@ -94,7 +94,7 @@ medusaIntegrationTestRunner({ }) it("should support searching through the addresses", async () => { - const [customer] = await customerModuleService.create([ + const [customer] = await customerModuleService.createCustomers([ { first_name: "Test", last_name: "Test", diff --git a/integration-tests/modules/__tests__/customer/admin/list-customers.spec.ts b/integration-tests/modules/__tests__/customer/admin/list-customers.spec.ts index bc1a49705d..43759e658a 100644 --- a/integration-tests/modules/__tests__/customer/admin/list-customers.spec.ts +++ b/integration-tests/modules/__tests__/customer/admin/list-customers.spec.ts @@ -32,7 +32,7 @@ medusaIntegrationTestRunner({ }) it("should get all customers and its count", async () => { - await customerModuleService.create([ + await customerModuleService.createCustomers([ { first_name: "Test", last_name: "Test", @@ -55,11 +55,11 @@ medusaIntegrationTestRunner({ }) it("should get all customers in specific customer group and its count", async () => { - const vipGroup = await customerModuleService.createCustomerGroup({ + const vipGroup = await customerModuleService.createCustomerGroups({ name: "VIP", }) - const [john] = await customerModuleService.create([ + const [john] = await customerModuleService.createCustomers([ { first_name: "John", last_name: "Doe", @@ -94,7 +94,7 @@ medusaIntegrationTestRunner({ }) it("should filter customers by last name", async () => { - await customerModuleService.create([ + await customerModuleService.createCustomers([ { first_name: "Jane", last_name: "Doe", @@ -143,7 +143,7 @@ medusaIntegrationTestRunner({ }) it("should support searching of customers", async () => { - await customerModuleService.create([ + await customerModuleService.createCustomers([ { first_name: "Jane", last_name: "Doe", diff --git a/integration-tests/modules/__tests__/customer/admin/update-customer-address.spec.ts b/integration-tests/modules/__tests__/customer/admin/update-customer-address.spec.ts index db47eac959..b6baa7f0ec 100644 --- a/integration-tests/modules/__tests__/customer/admin/update-customer-address.spec.ts +++ b/integration-tests/modules/__tests__/customer/admin/update-customer-address.spec.ts @@ -29,12 +29,12 @@ medusaIntegrationTestRunner({ }) it("should update a customer address", async () => { - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", }) - const address = await customerModuleService.addAddresses({ + const address = await customerModuleService.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -62,11 +62,11 @@ medusaIntegrationTestRunner({ }) it("updates a new address to be default and unsets old one", async () => { - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", }) - const [, address] = await customerModuleService.addAddresses([ + const [, address] = await customerModuleService.createAddresses([ { customer_id: customer.id, first_name: "John", @@ -104,11 +104,11 @@ medusaIntegrationTestRunner({ // do the same as above but for billing address it("updates a new address to be default and unsets old one", async () => { - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", }) - const [, address] = await customerModuleService.addAddresses([ + const [, address] = await customerModuleService.createAddresses([ { customer_id: customer.id, first_name: "John", diff --git a/integration-tests/modules/__tests__/customer/admin/update-customer.ts b/integration-tests/modules/__tests__/customer/admin/update-customer.ts index c6ffb858f6..663afccbe6 100644 --- a/integration-tests/modules/__tests__/customer/admin/update-customer.ts +++ b/integration-tests/modules/__tests__/customer/admin/update-customer.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should update a customer", async () => { - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", }) diff --git a/integration-tests/modules/__tests__/customer/store/create-customer-addresses.ts b/integration-tests/modules/__tests__/customer/store/create-customer-addresses.ts index 6b467be733..bd93d0abfc 100644 --- a/integration-tests/modules/__tests__/customer/store/create-customer-addresses.ts +++ b/integration-tests/modules/__tests__/customer/store/create-customer-addresses.ts @@ -47,10 +47,10 @@ medusaIntegrationTestRunner({ }) ) - const customerWithAddresses = await customerModuleService.retrieve( - customer.id, - { relations: ["addresses"] } - ) + const customerWithAddresses = + await customerModuleService.retrieveCustomer(customer.id, { + relations: ["addresses"], + }) expect(customerWithAddresses.addresses?.length).toEqual(1) }) diff --git a/integration-tests/modules/__tests__/customer/store/create-customer.spec.ts b/integration-tests/modules/__tests__/customer/store/create-customer.spec.ts index 4b713080fa..035dcd51da 100644 --- a/integration-tests/modules/__tests__/customer/store/create-customer.spec.ts +++ b/integration-tests/modules/__tests__/customer/store/create-customer.spec.ts @@ -35,9 +35,13 @@ medusaIntegrationTestRunner({ const { http } = appContainer.resolve( ContainerRegistrationKeys.CONFIG_MODULE ).projectConfig - const authIdentity = await authService.create({ - entity_id: "store_user", - provider: "emailpass", + const authIdentity = await authService.createAuthIdentities({ + provider_identities: [ + { + entity_id: "store_user", + provider: "emailpass", + }, + ], }) const token = jwt.sign(authIdentity, http.jwtSecret) diff --git a/integration-tests/modules/__tests__/customer/store/delete-customer-address.spec.ts b/integration-tests/modules/__tests__/customer/store/delete-customer-address.spec.ts index 411d6bb3f4..22236d5eb1 100644 --- a/integration-tests/modules/__tests__/customer/store/delete-customer-address.spec.ts +++ b/integration-tests/modules/__tests__/customer/store/delete-customer-address.spec.ts @@ -26,7 +26,7 @@ medusaIntegrationTestRunner({ appContainer ) - const address = await customerModuleService.addAddresses({ + const address = await customerModuleService.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -40,7 +40,7 @@ medusaIntegrationTestRunner({ expect(response.status).toEqual(200) - const updatedCustomer = await customerModuleService.retrieve( + const updatedCustomer = await customerModuleService.retrieveCustomer( customer.id, { relations: ["addresses"], @@ -53,11 +53,11 @@ medusaIntegrationTestRunner({ it("should fail to delete another customer's address", async () => { const { jwt } = await createAuthenticatedCustomer(appContainer) - const otherCustomer = await customerModuleService.create({ + const otherCustomer = await customerModuleService.createCustomers({ first_name: "Jane", last_name: "Doe", }) - const address = await customerModuleService.addAddresses({ + const address = await customerModuleService.createAddresses({ customer_id: otherCustomer.id, first_name: "John", last_name: "Doe", diff --git a/integration-tests/modules/__tests__/customer/store/get-me.spec.ts b/integration-tests/modules/__tests__/customer/store/get-me.spec.ts index 9e305215c2..d654165c98 100644 --- a/integration-tests/modules/__tests__/customer/store/get-me.spec.ts +++ b/integration-tests/modules/__tests__/customer/store/get-me.spec.ts @@ -1,5 +1,3 @@ -import { ICustomerModuleService } from "@medusajs/types" -import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { createAuthenticatedCustomer } from "../../../helpers/create-authenticated-customer" import { medusaIntegrationTestRunner } from "medusa-test-utils" @@ -12,13 +10,8 @@ medusaIntegrationTestRunner({ testSuite: ({ dbConnection, getContainer, api }) => { describe("GET /store/customers", () => { let appContainer - let customerModuleService: ICustomerModuleService - beforeAll(async () => { appContainer = getContainer() - customerModuleService = appContainer.resolve( - ModuleRegistrationName.CUSTOMER - ) }) it("should retrieve auth user's customer", async () => { diff --git a/integration-tests/modules/__tests__/customer/store/list-customer-addresses.ts b/integration-tests/modules/__tests__/customer/store/list-customer-addresses.ts index 0848416083..c9e58cc929 100644 --- a/integration-tests/modules/__tests__/customer/store/list-customer-addresses.ts +++ b/integration-tests/modules/__tests__/customer/store/list-customer-addresses.ts @@ -26,7 +26,7 @@ medusaIntegrationTestRunner({ appContainer ) - await customerModuleService.addAddresses([ + await customerModuleService.createAddresses([ { first_name: "Test", last_name: "Test", @@ -47,7 +47,7 @@ medusaIntegrationTestRunner({ }, ]) - await customerModuleService.create({ + await customerModuleService.createCustomers({ first_name: "Test Test", last_name: "Test Test", addresses: [ diff --git a/integration-tests/modules/__tests__/customer/store/update-customer-address.spec.ts b/integration-tests/modules/__tests__/customer/store/update-customer-address.spec.ts index 91a70f9b65..cff7b87c62 100644 --- a/integration-tests/modules/__tests__/customer/store/update-customer-address.spec.ts +++ b/integration-tests/modules/__tests__/customer/store/update-customer-address.spec.ts @@ -26,7 +26,7 @@ medusaIntegrationTestRunner({ appContainer ) - const address = await customerModuleService.addAddresses({ + const address = await customerModuleService.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -54,12 +54,12 @@ medusaIntegrationTestRunner({ it("should fail to update another customer's address", async () => { const { jwt } = await createAuthenticatedCustomer(appContainer) - const otherCustomer = await customerModuleService.create({ + const otherCustomer = await customerModuleService.createCustomers({ first_name: "Jane", last_name: "Doe", }) - const address = await customerModuleService.addAddresses({ + const address = await customerModuleService.createAddresses({ customer_id: otherCustomer.id, first_name: "John", last_name: "Doe", diff --git a/integration-tests/modules/__tests__/fixtures/fulfillment/index.ts b/integration-tests/modules/__tests__/fixtures/fulfillment/index.ts index 0c2607413e..6d92aa5a8d 100644 --- a/integration-tests/modules/__tests__/fixtures/fulfillment/index.ts +++ b/integration-tests/modules/__tests__/fixtures/fulfillment/index.ts @@ -109,7 +109,7 @@ export async function setupFullDataFulfillmentStructure( name: "test_" + randomString, type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test_" + randomString, type: "test-type", }) diff --git a/integration-tests/modules/__tests__/fixtures/tax/index.ts b/integration-tests/modules/__tests__/fixtures/tax/index.ts index 68d7bbd320..9d60686e68 100644 --- a/integration-tests/modules/__tests__/fixtures/tax/index.ts +++ b/integration-tests/modules/__tests__/fixtures/tax/index.ts @@ -105,7 +105,7 @@ export const setupTaxStructure = async (service: ITaxModuleService) => { ]) const [calProd, calType, deType, canProd, canType, qcType] = - await service.create([ + await service.createTaxRates([ { tax_region_id: cal.id, name: "CA Reduced Rate for Products", diff --git a/integration-tests/modules/__tests__/fulfillment/fulfillment.workflows.spec.ts b/integration-tests/modules/__tests__/fulfillment/fulfillment.workflows.spec.ts index 9fc790d1bb..4ecc843223 100644 --- a/integration-tests/modules/__tests__/fulfillment/fulfillment.workflows.spec.ts +++ b/integration-tests/modules/__tests__/fulfillment/fulfillment.workflows.spec.ts @@ -48,7 +48,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -111,7 +111,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -190,7 +190,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) diff --git a/integration-tests/modules/__tests__/fulfillment/index.spec.ts b/integration-tests/modules/__tests__/fulfillment/index.spec.ts index fddf8a31a6..b70182465f 100644 --- a/integration-tests/modules/__tests__/fulfillment/index.spec.ts +++ b/integration-tests/modules/__tests__/fulfillment/index.spec.ts @@ -40,7 +40,7 @@ medusaIntegrationTestRunner({ it("should allow to create a full data structure after the backward compatible migration have run on top of the medusa v1 database", async () => { await setupFullDataFulfillmentStructure(service, { providerId }) - const fulfillmentSets = await service.list( + const fulfillmentSets = await service.listFulfillmentSets( {}, { relations: [ @@ -119,7 +119,7 @@ medusaIntegrationTestRunner({ type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) diff --git a/integration-tests/modules/__tests__/link-modules/cart-links.spec.ts b/integration-tests/modules/__tests__/link-modules/cart-links.spec.ts index 0035c3a180..b32b1ba694 100644 --- a/integration-tests/modules/__tests__/link-modules/cart-links.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/cart-links.spec.ts @@ -41,20 +41,20 @@ medusaIntegrationTestRunner({ }) it("should query carts, sales channels, customers, regions with remote query", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "Region", currency_code: "usd", }) - const customer = await customerModule.create({ + const customer = await customerModule.createCustomers({ email: "tony@stark.com", }) - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ email: "tony@stark.com", currency_code: "usd", region_id: region.id, diff --git a/integration-tests/modules/__tests__/link-modules/cart-region.spec.ts b/integration-tests/modules/__tests__/link-modules/cart-region.spec.ts index aca1502f71..c3e0d82460 100644 --- a/integration-tests/modules/__tests__/link-modules/cart-region.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/cart-region.spec.ts @@ -23,12 +23,12 @@ medusaIntegrationTestRunner({ }) it("should query carts and regions with remote query", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "Region", currency_code: "usd", }) - const cart = await cartModuleService.create({ + const cart = await cartModuleService.createCarts({ email: "tony@stark.com", currency_code: "usd", region_id: region.id, diff --git a/integration-tests/modules/__tests__/link-modules/fulfillment-set-location.spec.ts b/integration-tests/modules/__tests__/link-modules/fulfillment-set-location.spec.ts index a378f972f6..07569f7aea 100644 --- a/integration-tests/modules/__tests__/link-modules/fulfillment-set-location.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/fulfillment-set-location.spec.ts @@ -1,8 +1,7 @@ import { ModuleRegistrationName, Modules } from "@medusajs/modules-sdk" import { IFulfillmentModuleService, - ISalesChannelModuleService, - IStockLocationServiceNext, + IStockLocationService, } from "@medusajs/types" import { ContainerRegistrationKeys, @@ -20,8 +19,7 @@ medusaIntegrationTestRunner({ describe("FulfillmentSet and Location", () => { let appContainer let fulfillmentModule: IFulfillmentModuleService - let locationModule: IStockLocationServiceNext - let scService: ISalesChannelModuleService + let locationModule: IStockLocationService let remoteQuery let remoteLink @@ -33,7 +31,6 @@ medusaIntegrationTestRunner({ locationModule = appContainer.resolve( ModuleRegistrationName.STOCK_LOCATION ) - scService = appContainer.resolve(ModuleRegistrationName.SALES_CHANNEL) remoteQuery = appContainer.resolve( ContainerRegistrationKeys.REMOTE_QUERY ) @@ -41,12 +38,12 @@ medusaIntegrationTestRunner({ }) it("should query fulfillment set and location link with remote query", async () => { - const fulfillmentSet = await fulfillmentModule.create({ + const fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test fulfillment set", type: "delivery", }) - const euWarehouse = await locationModule.create({ + const euWarehouse = await locationModule.createStockLocations({ name: "EU Warehouse", }) diff --git a/integration-tests/modules/__tests__/link-modules/product-variant-price-set.spec.ts b/integration-tests/modules/__tests__/link-modules/product-variant-price-set.spec.ts index 155fb9f735..327931d24a 100644 --- a/integration-tests/modules/__tests__/link-modules/product-variant-price-set.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/product-variant-price-set.spec.ts @@ -31,7 +31,7 @@ medusaIntegrationTestRunner({ }) it("should query product variants and price set link with remote query", async () => { - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -52,7 +52,7 @@ medusaIntegrationTestRunner({ }, ]) - const [priceSet1, priceSet2] = await pricingModule.create([ + const [priceSet1, priceSet2] = await pricingModule.createPriceSets([ { rules: [{ rule_attribute: "customer_group_id" }], prices: [ diff --git a/integration-tests/modules/__tests__/link-modules/publishable-key-sales-channel.spec.ts b/integration-tests/modules/__tests__/link-modules/publishable-key-sales-channel.spec.ts index 60330d50b8..1552d57c64 100644 --- a/integration-tests/modules/__tests__/link-modules/publishable-key-sales-channel.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/publishable-key-sales-channel.spec.ts @@ -31,11 +31,11 @@ medusaIntegrationTestRunner({ }) it("should query api key and sales channels link with remote query", async () => { - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const apiKeys = await apiKeyModule.create([ + const apiKeys = await apiKeyModule.createApiKeys([ { title: "Api key", type: "publishable", diff --git a/integration-tests/modules/__tests__/link-modules/region-payment-provider.spec.ts b/integration-tests/modules/__tests__/link-modules/region-payment-provider.spec.ts index 03b7940d20..6ded4d5f6a 100644 --- a/integration-tests/modules/__tests__/link-modules/region-payment-provider.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/region-payment-provider.spec.ts @@ -1,7 +1,7 @@ import { ModuleRegistrationName, Modules } from "@medusajs/modules-sdk" -import { IPaymentModuleService, IRegionModuleService } from "@medusajs/types" +import { IRegionModuleService } from "@medusajs/types" import { medusaIntegrationTestRunner } from "medusa-test-utils" -import {ContainerRegistrationKeys} from "@medusajs/utils"; +import { ContainerRegistrationKeys } from "@medusajs/utils" jest.setTimeout(50000) @@ -13,20 +13,20 @@ medusaIntegrationTestRunner({ describe("Region and Payment Providers", () => { let appContainer let regionModule: IRegionModuleService - let paymentModule: IPaymentModuleService let remoteQuery let remoteLink beforeAll(async () => { appContainer = getContainer() regionModule = appContainer.resolve(ModuleRegistrationName.REGION) - paymentModule = appContainer.resolve(ModuleRegistrationName.PAYMENT) - remoteQuery = appContainer.resolve(ContainerRegistrationKeys.REMOTE_QUERY) + remoteQuery = appContainer.resolve( + ContainerRegistrationKeys.REMOTE_QUERY + ) remoteLink = appContainer.resolve(ContainerRegistrationKeys.REMOTE_LINK) }) it("should query region and payment provider link with remote query", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "North America", currency_code: "usd", }) @@ -87,7 +87,7 @@ medusaIntegrationTestRunner({ }), expect.objectContaining({ id: "pp_system_default_2", - regions: [] + regions: [], }), ]) ) diff --git a/integration-tests/modules/__tests__/link-modules/sales-channel-location.spec.ts b/integration-tests/modules/__tests__/link-modules/sales-channel-location.spec.ts index 6d8cce012e..4d6f16b71b 100644 --- a/integration-tests/modules/__tests__/link-modules/sales-channel-location.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/sales-channel-location.spec.ts @@ -30,23 +30,23 @@ medusaIntegrationTestRunner({ }) it("should query carts, sales channels, customers, regions with remote query", async () => { - const scWebshop = await scService.create({ + const scWebshop = await scService.createSalesChannels({ name: "Webshop", }) - const scCphStore = await scService.create({ + const scCphStore = await scService.createSalesChannels({ name: "CPH store", }) - const scNycStore = await scService.create({ + const scNycStore = await scService.createSalesChannels({ name: "NYC store", }) - const euWarehouse = await locationService.create({ + const euWarehouse = await locationService.createStockLocations({ name: "EU Warehouse", }) - const usWarehouse = await locationService.create({ + const usWarehouse = await locationService.createStockLocations({ name: "US Warehouse", }) diff --git a/integration-tests/modules/__tests__/link-modules/shipping-option-price-set.spec.ts b/integration-tests/modules/__tests__/link-modules/shipping-option-price-set.spec.ts index 83b739083a..a08aab4876 100644 --- a/integration-tests/modules/__tests__/link-modules/shipping-option-price-set.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/shipping-option-price-set.spec.ts @@ -37,7 +37,7 @@ medusaIntegrationTestRunner({ name: "Test", type: "default", }) - const fulfillmentSet = await fulfillmentModule.create({ + const fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", }) @@ -65,7 +65,7 @@ medusaIntegrationTestRunner({ }, }) - const priceSet = await pricingModule.create({ + const priceSet = await pricingModule.createPriceSets({ prices: [ { amount: 3000, diff --git a/integration-tests/modules/__tests__/link-modules/store-currency.spec.ts b/integration-tests/modules/__tests__/link-modules/store-currency.spec.ts index 984485be62..290e3ecb49 100644 --- a/integration-tests/modules/__tests__/link-modules/store-currency.spec.ts +++ b/integration-tests/modules/__tests__/link-modules/store-currency.spec.ts @@ -25,7 +25,7 @@ medusaIntegrationTestRunner({ }) it("should query store and default currency with remote query", async () => { - const store = await storeModuleService.create({ + const store = await storeModuleService.createStores({ name: "Store", default_currency_code: "usd", supported_currency_codes: ["usd"], diff --git a/integration-tests/modules/__tests__/modules/load-standalone.ts b/integration-tests/modules/__tests__/modules/load-standalone.ts index b55dcfdfd2..dfaf8525bc 100644 --- a/integration-tests/modules/__tests__/modules/load-standalone.ts +++ b/integration-tests/modules/__tests__/modules/load-standalone.ts @@ -28,7 +28,7 @@ medusaIntegrationTestRunner({ Modules.PRODUCT ] as unknown as IProductModuleService - const productList = await product.list() + const productList = await product.listProducts() expect(productList).toEqual(expect.arrayContaining([])) }) diff --git a/integration-tests/modules/__tests__/modules/remote-query.spec.ts b/integration-tests/modules/__tests__/modules/remote-query.spec.ts index 3773acb432..b870d43b4d 100644 --- a/integration-tests/modules/__tests__/modules/remote-query.spec.ts +++ b/integration-tests/modules/__tests__/modules/remote-query.spec.ts @@ -1,5 +1,5 @@ import { ModuleRegistrationName, Modules } from "@medusajs/modules-sdk" -import { IPaymentModuleService, IRegionModuleService } from "@medusajs/types" +import { IRegionModuleService } from "@medusajs/types" import { ContainerRegistrationKeys } from "@medusajs/utils" import { medusaIntegrationTestRunner } from "medusa-test-utils" import { createAdminUser } from "../../..//helpers/create-admin-user" @@ -15,14 +15,12 @@ medusaIntegrationTestRunner({ describe("Remote Query", () => { let appContainer let regionModule: IRegionModuleService - let paymentModule: IPaymentModuleService let remoteQuery let remoteLink beforeAll(async () => { appContainer = getContainer() regionModule = appContainer.resolve(ModuleRegistrationName.REGION) - paymentModule = appContainer.resolve(ModuleRegistrationName.PAYMENT) remoteQuery = appContainer.resolve( ContainerRegistrationKeys.REMOTE_QUERY ) @@ -34,7 +32,7 @@ medusaIntegrationTestRunner({ }) it("should fail to retrieve a single non-existing id", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "Test Region", currency_code: "usd", countries: ["us"], @@ -75,19 +73,19 @@ medusaIntegrationTestRunner({ }) it("should fail if a expected relation is not found", async () => { - const region = await regionModule.create({ + const region = await regionModule.createRegions({ name: "Test Region", currency_code: "usd", countries: ["us"], }) - const regionWithPayment = await regionModule.create({ + const regionWithPayment = await regionModule.createRegions({ name: "Test W/ Payment", currency_code: "brl", countries: ["br"], }) - const regionNoLink = await regionModule.create({ + const regionNoLink = await regionModule.createRegions({ name: "No link", currency_code: "eur", countries: ["dk"], diff --git a/integration-tests/modules/__tests__/notification/admin/notification.spec.ts b/integration-tests/modules/__tests__/notification/admin/notification.spec.ts index c36cfff5d0..d25d4ec8a1 100644 --- a/integration-tests/modules/__tests__/notification/admin/notification.spec.ts +++ b/integration-tests/modules/__tests__/notification/admin/notification.spec.ts @@ -40,8 +40,8 @@ medusaIntegrationTestRunner({ resource_type: "order", } as CreateNotificationDTO - const result = await service.create(notification) - const fromDB = await service.retrieve(result.id) + const result = await service.createNotifications(notification) + const fromDB = await service.retrieveNotification(result.id) expect(result).toEqual( expect.objectContaining({ @@ -94,7 +94,9 @@ medusaIntegrationTestRunner({ channel: "sms", } as CreateNotificationDTO - const error = await service.create(notification).catch((e) => e) + const error = await service + .createNotifications(notification) + .catch((e) => e) expect(error.message).toEqual( "Could not find a notification provider for channel: sms" ) @@ -113,9 +115,11 @@ medusaIntegrationTestRunner({ template: "product-created", } as CreateNotificationDTO - await service.create([notification1, notification2]) + await service.createNotifications([notification1, notification2]) - const notifications = await service.list({ channel: "log" }) + const notifications = await service.listNotifications({ + channel: "log", + }) expect(notifications).toHaveLength(1) expect(notifications[0]).toEqual( expect.objectContaining({ @@ -139,9 +143,12 @@ medusaIntegrationTestRunner({ template: "product-created", } as CreateNotificationDTO - const [first] = await service.create([notification1, notification2]) + const [first] = await service.createNotifications([ + notification1, + notification2, + ]) - const notification = await service.retrieve(first.id) + const notification = await service.retrieveNotification(first.id) expect(notification).toEqual( expect.objectContaining({ to: "test@medusajs.com", @@ -176,7 +183,7 @@ medusaIntegrationTestRunner({ }) await subscriberExecution - const notifications = await service.list() + const notifications = await service.listNotifications() expect(logSpy).toHaveBeenLastCalledWith( `Attempting to send a notification to: 'test@medusajs.com' on the channel: 'email' with template: 'order-created-template' and data: '{\"order_id\":\"1234\"}'` diff --git a/integration-tests/modules/__tests__/order/draft-order.spec.ts b/integration-tests/modules/__tests__/order/draft-order.spec.ts index e984b6355a..c0120ab3f9 100644 --- a/integration-tests/modules/__tests__/order/draft-order.spec.ts +++ b/integration-tests/modules/__tests__/order/draft-order.spec.ts @@ -1,10 +1,8 @@ import { ModuleRegistrationName, Modules } from "@medusajs/modules-sdk" import { ICartModuleService, - ICustomerModuleService, IFulfillmentModuleService, IInventoryServiceNext, - IPaymentModuleService, IPricingModuleService, IProductModuleService, IRegionModuleService, @@ -31,14 +29,11 @@ medusaIntegrationTestRunner({ let cartModuleService: ICartModuleService let regionModuleService: IRegionModuleService let scModuleService: ISalesChannelModuleService - let customerModule: ICustomerModuleService let productModule: IProductModuleService let pricingModule: IPricingModuleService - let paymentModule: IPaymentModuleService let inventoryModule: IInventoryServiceNext let stockLocationModule: IStockLocationServiceNext let fulfillmentModule: IFulfillmentModuleService - let locationModule: IStockLocationServiceNext let taxModule: ITaxModuleService let remoteLink, remoteQuery @@ -49,10 +44,8 @@ medusaIntegrationTestRunner({ scModuleService = appContainer.resolve( ModuleRegistrationName.SALES_CHANNEL ) - customerModule = appContainer.resolve(ModuleRegistrationName.CUSTOMER) productModule = appContainer.resolve(ModuleRegistrationName.PRODUCT) pricingModule = appContainer.resolve(ModuleRegistrationName.PRICING) - paymentModule = appContainer.resolve(ModuleRegistrationName.PAYMENT) inventoryModule = appContainer.resolve(ModuleRegistrationName.INVENTORY) stockLocationModule = appContainer.resolve( ModuleRegistrationName.STOCK_LOCATION @@ -60,9 +53,6 @@ medusaIntegrationTestRunner({ fulfillmentModule = appContainer.resolve( ModuleRegistrationName.FULFILLMENT ) - locationModule = appContainer.resolve( - ModuleRegistrationName.STOCK_LOCATION - ) taxModule = appContainer.resolve(ModuleRegistrationName.TAX) remoteLink = appContainer.resolve(ContainerRegistrationKeys.REMOTE_LINK) remoteQuery = appContainer.resolve(ContainerRegistrationKeys.REMOTE_QUERY) @@ -74,20 +64,20 @@ medusaIntegrationTestRunner({ describe("Draft Orders - Admin", () => { it("should create a draft order", async () => { - const region = await regionModuleService.create({ + const region = await regionModuleService.createRegions({ name: "US", currency_code: "usd", }) - const salesChannel = await scModuleService.create({ + const salesChannel = await scModuleService.createSalesChannels({ name: "Webshop", }) - const location = await stockLocationModule.create({ + const location = await stockLocationModule.createStockLocations({ name: "Warehouse", }) - const [product, product_2] = await productModule.create([ + const [product, product_2] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -107,7 +97,7 @@ medusaIntegrationTestRunner({ }, ]) - const inventoryItem = await inventoryModule.create({ + const inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -120,7 +110,7 @@ medusaIntegrationTestRunner({ }, ]) - const [priceSet, priceSet_2] = await pricingModule.create([ + const [priceSet, priceSet_2] = await pricingModule.createPriceSets([ { prices: [ { diff --git a/integration-tests/modules/__tests__/order/order.spec.ts b/integration-tests/modules/__tests__/order/order.spec.ts index 0e1f2d4999..275134e08c 100644 --- a/integration-tests/modules/__tests__/order/order.spec.ts +++ b/integration-tests/modules/__tests__/order/order.spec.ts @@ -1,7 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ICartModuleService, - ICustomerModuleService, IFulfillmentModuleService, IInventoryServiceNext, IOrderModuleService, @@ -9,9 +8,7 @@ import { IPricingModuleService, IProductModuleService, IRegionModuleService, - ISalesChannelModuleService, IStockLocationServiceNext, - ITaxModuleService, } from "@medusajs/types" import { ContainerRegistrationKeys } from "@medusajs/utils" import { medusaIntegrationTestRunner } from "medusa-test-utils" @@ -30,16 +27,12 @@ medusaIntegrationTestRunner({ let appContainer let cartModuleService: ICartModuleService let regionModuleService: IRegionModuleService - let scModuleService: ISalesChannelModuleService - let customerModule: ICustomerModuleService let productModule: IProductModuleService - let pricingModule: IPricingModuleService let paymentModule: IPaymentModuleService + let pricingModule: IPricingModuleService let inventoryModule: IInventoryServiceNext let stockLocationModule: IStockLocationServiceNext let fulfillmentModule: IFulfillmentModuleService - let locationModule: IStockLocationServiceNext - let taxModule: ITaxModuleService let orderModule: IOrderModuleService let remoteLink, remoteQuery @@ -47,24 +40,12 @@ medusaIntegrationTestRunner({ appContainer = getContainer() cartModuleService = appContainer.resolve(ModuleRegistrationName.CART) regionModuleService = appContainer.resolve(ModuleRegistrationName.REGION) - scModuleService = appContainer.resolve( - ModuleRegistrationName.SALES_CHANNEL - ) - customerModule = appContainer.resolve(ModuleRegistrationName.CUSTOMER) productModule = appContainer.resolve(ModuleRegistrationName.PRODUCT) - pricingModule = appContainer.resolve(ModuleRegistrationName.PRICING) paymentModule = appContainer.resolve(ModuleRegistrationName.PAYMENT) inventoryModule = appContainer.resolve(ModuleRegistrationName.INVENTORY) - stockLocationModule = appContainer.resolve( - ModuleRegistrationName.STOCK_LOCATION - ) fulfillmentModule = appContainer.resolve( ModuleRegistrationName.FULFILLMENT ) - locationModule = appContainer.resolve( - ModuleRegistrationName.STOCK_LOCATION - ) - taxModule = appContainer.resolve(ModuleRegistrationName.TAX) remoteLink = appContainer.resolve(ContainerRegistrationKeys.REMOTE_LINK) remoteQuery = appContainer.resolve(ContainerRegistrationKeys.REMOTE_QUERY) orderModule = appContainer.resolve(ModuleRegistrationName.ORDER) @@ -76,7 +57,7 @@ medusaIntegrationTestRunner({ describe("Orders - Admin", () => { it("should get an order", async () => { - const created = await orderModule.create({ + const created = await orderModule.createOrders({ region_id: "test_region_idclear", email: "foo@bar.com", items: [ diff --git a/integration-tests/modules/__tests__/order/workflows/cancel-order.spec.ts b/integration-tests/modules/__tests__/order/workflows/cancel-order.spec.ts index 974e2225d0..55b2f0d7d2 100644 --- a/integration-tests/modules/__tests__/order/workflows/cancel-order.spec.ts +++ b/integration-tests/modules/__tests__/order/workflows/cancel-order.spec.ts @@ -9,7 +9,7 @@ import { FulfillmentWorkflow, IOrderModuleService, IRegionModuleService, - IStockLocationServiceNext, + IStockLocationService, OrderWorkflow, ProductDTO, RegionDTO, @@ -35,7 +35,7 @@ async function prepareDataFixtures({ container }) { const salesChannelService = container.resolve( ModuleRegistrationName.SALES_CHANNEL ) - const stockLocationModule: IStockLocationServiceNext = container.resolve( + const stockLocationModule: IStockLocationService = container.resolve( ModuleRegistrationName.STOCK_LOCATION ) const productModule = container.resolve(ModuleRegistrationName.PRODUCT) @@ -46,7 +46,7 @@ async function prepareDataFixtures({ container }) { type: "default", }) - const fulfillmentSet = await fulfillmentService.create({ + const fulfillmentSet = await fulfillmentService.createFulfillmentSets({ name: "Test fulfillment set", type: "manual_test", }) @@ -66,7 +66,7 @@ async function prepareDataFixtures({ container }) { ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", @@ -74,22 +74,23 @@ async function prepareDataFixtures({ container }) { }, ]) - const salesChannel = await salesChannelService.create({ + const salesChannel = await salesChannelService.createSalesChannels({ name: "Webshop", }) - const location: StockLocationDTO = await stockLocationModule.create({ - name: "Warehouse", - address: { - address_1: "Test", - city: "Test", - country_code: "US", - postal_code: "12345", - phone: "12345", - }, - }) + const location: StockLocationDTO = + await stockLocationModule.createStockLocations({ + name: "Warehouse", + address: { + address_1: "Test", + city: "Test", + country_code: "US", + postal_code: "12345", + phone: "12345", + }, + }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -101,7 +102,7 @@ async function prepareDataFixtures({ container }) { }, ]) - inventoryItem = await inventoryModule.create({ + inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -210,7 +211,7 @@ async function createOrderFixture({ container, product, location }) { const orderService: IOrderModuleService = container.resolve( ModuleRegistrationName.ORDER ) - let order = await orderService.create({ + let order = await orderService.createOrders({ region_id: "test_region_idclear", email: "foo@bar.com", items: [ @@ -292,7 +293,7 @@ async function createOrderFixture({ container, product, location }) { }, ]) - order = await orderService.retrieve(order.id, { + order = await orderService.retrieveOrder(order.id, { relations: ["items"], }) diff --git a/integration-tests/modules/__tests__/order/workflows/create-fulfillment.spec.ts b/integration-tests/modules/__tests__/order/workflows/create-fulfillment.spec.ts index 39c869008c..600d1bda35 100644 --- a/integration-tests/modules/__tests__/order/workflows/create-fulfillment.spec.ts +++ b/integration-tests/modules/__tests__/order/workflows/create-fulfillment.spec.ts @@ -8,7 +8,7 @@ import { FulfillmentWorkflow, IOrderModuleService, IRegionModuleService, - IStockLocationServiceNext, + IStockLocationService, OrderWorkflow, ProductDTO, RegionDTO, @@ -34,7 +34,7 @@ async function prepareDataFixtures({ container }) { const salesChannelService = container.resolve( ModuleRegistrationName.SALES_CHANNEL ) - const stockLocationModule: IStockLocationServiceNext = container.resolve( + const stockLocationModule: IStockLocationService = container.resolve( ModuleRegistrationName.STOCK_LOCATION ) const productModule = container.resolve(ModuleRegistrationName.PRODUCT) @@ -45,7 +45,7 @@ async function prepareDataFixtures({ container }) { type: "default", }) - const fulfillmentSet = await fulfillmentService.create({ + const fulfillmentSet = await fulfillmentService.createFulfillmentSets({ name: "Test fulfillment set", type: "manual_test", }) @@ -65,7 +65,7 @@ async function prepareDataFixtures({ container }) { ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", @@ -73,22 +73,23 @@ async function prepareDataFixtures({ container }) { }, ]) - const salesChannel = await salesChannelService.create({ + const salesChannel = await salesChannelService.createSalesChannels({ name: "Webshop", }) - const location: StockLocationDTO = await stockLocationModule.create({ - name: "Warehouse", - address: { - address_1: "Test", - city: "Test", - country_code: "US", - postal_code: "12345", - phone: "12345", - }, - }) + const location: StockLocationDTO = + await stockLocationModule.createStockLocations({ + name: "Warehouse", + address: { + address_1: "Test", + city: "Test", + country_code: "US", + postal_code: "12345", + phone: "12345", + }, + }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -105,7 +106,7 @@ async function prepareDataFixtures({ container }) { }, ]) - inventoryItem = await inventoryModule.create({ + inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -214,7 +215,7 @@ async function createOrderFixture({ container, product, location }) { const orderService: IOrderModuleService = container.resolve( ModuleRegistrationName.ORDER ) - let order = await orderService.create({ + let order = await orderService.createOrders({ region_id: "test_region_idclear", email: "foo@bar.com", items: [ @@ -305,7 +306,7 @@ async function createOrderFixture({ container, product, location }) { }, ]) - order = await orderService.retrieve(order.id, { + order = await orderService.retrieveOrder(order.id, { relations: ["items"], }) diff --git a/integration-tests/modules/__tests__/order/workflows/create-return.spec.ts b/integration-tests/modules/__tests__/order/workflows/create-return.spec.ts index 3c4901ccaa..45bf0ca3e2 100644 --- a/integration-tests/modules/__tests__/order/workflows/create-return.spec.ts +++ b/integration-tests/modules/__tests__/order/workflows/create-return.spec.ts @@ -12,7 +12,7 @@ import { FulfillmentWorkflow, IOrderModuleService, IRegionModuleService, - IStockLocationServiceNext, + IStockLocationService, OrderWorkflow, ProductDTO, RegionDTO, @@ -21,8 +21,8 @@ import { } from "@medusajs/types" import { ContainerRegistrationKeys, - RuleOperator, remoteQueryObjectFromString, + RuleOperator, } from "@medusajs/utils" import { medusaIntegrationTestRunner } from "medusa-test-utils/dist" @@ -38,7 +38,7 @@ async function prepareDataFixtures({ container }) { const salesChannelService = container.resolve( ModuleRegistrationName.SALES_CHANNEL ) - const stockLocationModule: IStockLocationServiceNext = container.resolve( + const stockLocationModule: IStockLocationService = container.resolve( ModuleRegistrationName.STOCK_LOCATION ) const productModule = container.resolve(ModuleRegistrationName.PRODUCT) @@ -49,7 +49,7 @@ async function prepareDataFixtures({ container }) { type: "default", }) - const fulfillmentSet = await fulfillmentService.create({ + const fulfillmentSet = await fulfillmentService.createFulfillmentSets({ name: "Test fulfillment set", type: "manual_test", }) @@ -69,7 +69,7 @@ async function prepareDataFixtures({ container }) { ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", @@ -77,22 +77,23 @@ async function prepareDataFixtures({ container }) { }, ]) - const salesChannel = await salesChannelService.create({ + const salesChannel = await salesChannelService.createSalesChannels({ name: "Webshop", }) - const location: StockLocationDTO = await stockLocationModule.create({ - name: "Warehouse", - address: { - address_1: "Test", - city: "Test", - country_code: "US", - postal_code: "12345", - phone: "12345", - }, - }) + const location: StockLocationDTO = + await stockLocationModule.createStockLocations({ + name: "Warehouse", + address: { + address_1: "Test", + city: "Test", + country_code: "US", + postal_code: "12345", + phone: "12345", + }, + }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -104,7 +105,7 @@ async function prepareDataFixtures({ container }) { }, ]) - const inventoryItem = await inventoryModule.create({ + const inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -221,7 +222,7 @@ async function createOrderFixture({ container, product }) { const orderService: IOrderModuleService = container.resolve( ModuleRegistrationName.ORDER ) - let order = await orderService.create({ + let order = await orderService.createOrders({ region_id: "test_region_idclear", email: "foo@bar.com", items: [ @@ -331,7 +332,7 @@ async function createOrderFixture({ container, product }) { await orderService.applyPendingOrderActions(order.id) - order = await orderService.retrieve(order.id, { + order = await orderService.retrieveOrder(order.id, { relations: ["items"], }) diff --git a/integration-tests/modules/__tests__/order/workflows/create-shipment.spec.ts b/integration-tests/modules/__tests__/order/workflows/create-shipment.spec.ts index 87e99fb282..eb6651f878 100644 --- a/integration-tests/modules/__tests__/order/workflows/create-shipment.spec.ts +++ b/integration-tests/modules/__tests__/order/workflows/create-shipment.spec.ts @@ -8,7 +8,7 @@ import { FulfillmentWorkflow, IOrderModuleService, IRegionModuleService, - IStockLocationServiceNext, + IStockLocationService, OrderWorkflow, ProductDTO, RegionDTO, @@ -17,8 +17,8 @@ import { } from "@medusajs/types" import { ContainerRegistrationKeys, - RuleOperator, remoteQueryObjectFromString, + RuleOperator, } from "@medusajs/utils" import { medusaIntegrationTestRunner } from "medusa-test-utils/dist" @@ -35,7 +35,7 @@ async function prepareDataFixtures({ container }) { const salesChannelService = container.resolve( ModuleRegistrationName.SALES_CHANNEL ) - const stockLocationModule: IStockLocationServiceNext = container.resolve( + const stockLocationModule: IStockLocationService = container.resolve( ModuleRegistrationName.STOCK_LOCATION ) const productModule = container.resolve(ModuleRegistrationName.PRODUCT) @@ -46,7 +46,7 @@ async function prepareDataFixtures({ container }) { type: "default", }) - const fulfillmentSet = await fulfillmentService.create({ + const fulfillmentSet = await fulfillmentService.createFulfillmentSets({ name: "Test fulfillment set", type: "manual_test", }) @@ -66,7 +66,7 @@ async function prepareDataFixtures({ container }) { ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", @@ -74,22 +74,23 @@ async function prepareDataFixtures({ container }) { }, ]) - const salesChannel = await salesChannelService.create({ + const salesChannel = await salesChannelService.createSalesChannels({ name: "Webshop", }) - const location: StockLocationDTO = await stockLocationModule.create({ - name: "Warehouse", - address: { - address_1: "Test", - city: "Test", - country_code: "US", - postal_code: "12345", - phone: "12345", - }, - }) + const location: StockLocationDTO = + await stockLocationModule.createStockLocations({ + name: "Warehouse", + address: { + address_1: "Test", + city: "Test", + country_code: "US", + postal_code: "12345", + phone: "12345", + }, + }) - const [product] = await productModule.create([ + const [product] = await productModule.createProducts([ { title: "Test product", variants: [ @@ -101,7 +102,7 @@ async function prepareDataFixtures({ container }) { }, ]) - inventoryItem = await inventoryModule.create({ + inventoryItem = await inventoryModule.createInventoryItems({ sku: "inv-1234", }) @@ -217,7 +218,7 @@ async function createOrderFixture({ container, product, location }) { const orderService: IOrderModuleService = container.resolve( ModuleRegistrationName.ORDER ) - let order = await orderService.create({ + let order = await orderService.createOrders({ region_id: "test_region_idclear", email: "foo@bar.com", items: [ @@ -299,7 +300,7 @@ async function createOrderFixture({ container, product, location }) { }, ]) - order = await orderService.retrieve(order.id, { + order = await orderService.retrieveOrder(order.id, { relations: ["items"], }) diff --git a/integration-tests/modules/__tests__/payment/payment-session.workflows.spec.ts b/integration-tests/modules/__tests__/payment/payment-session.workflows.spec.ts index 07953c7bae..12e5f4fc7b 100644 --- a/integration-tests/modules/__tests__/payment/payment-session.workflows.spec.ts +++ b/integration-tests/modules/__tests__/payment/payment-session.workflows.spec.ts @@ -31,7 +31,7 @@ medusaIntegrationTestRunner({ let paymentCollection beforeEach(async () => { - region = await regionModule.create({ + region = await regionModule.createRegions({ currency_code: "usd", name: "US", }) @@ -130,7 +130,7 @@ medusaIntegrationTestRunner({ }, }) - const region = await regionModule.create({ + const region = await regionModule.createRegions({ currency_code: "usd", name: "US", }) diff --git a/integration-tests/modules/__tests__/payment/payments.spec.ts b/integration-tests/modules/__tests__/payment/payments.spec.ts index 42758a41c3..c92248ca3a 100644 --- a/integration-tests/modules/__tests__/payment/payments.spec.ts +++ b/integration-tests/modules/__tests__/payment/payments.spec.ts @@ -32,7 +32,7 @@ medusaIntegrationTestRunner({ // TODO: Test should move to `integration-tests/api` it("should list payment providers", async () => { - const region = await regionService.create({ + const region = await regionService.createRegions({ name: "Test Region", currency_code: "usd", }) diff --git a/integration-tests/modules/__tests__/price-lists/admin/price-lists.spec.ts b/integration-tests/modules/__tests__/price-lists/admin/price-lists.spec.ts index ebb920084e..362a04a36a 100644 --- a/integration-tests/modules/__tests__/price-lists/admin/price-lists.spec.ts +++ b/integration-tests/modules/__tests__/price-lists/admin/price-lists.spec.ts @@ -43,11 +43,14 @@ medusaIntegrationTestRunner({ beforeEach(async () => { await createAdminUser(dbConnection, adminHeaders, appContainer) - customerGroup = await customerModule.createCustomerGroup({ + customerGroup = await customerModule.createCustomerGroups({ name: "VIP", }) - region = await regionModule.create({ name: "US", currency_code: "USD" }) - ;[product] = await productModule.create([ + region = await regionModule.createRegions({ + name: "US", + currency_code: "USD", + }) + ;[product] = await productModule.createProducts([ { title: "test product", variants: [ diff --git a/integration-tests/modules/__tests__/price-lists/store/get-product.ts b/integration-tests/modules/__tests__/price-lists/store/get-product.ts index b0112570bf..7a8a83a9c2 100644 --- a/integration-tests/modules/__tests__/price-lists/store/get-product.ts +++ b/integration-tests/modules/__tests__/price-lists/store/get-product.ts @@ -1,4 +1,3 @@ -import { IPricingModuleService } from "@medusajs/types" import { PriceListStatus, PriceListType } from "@medusajs/utils" import { medusaIntegrationTestRunner } from "medusa-test-utils" import { @@ -31,11 +30,9 @@ medusaIntegrationTestRunner({ let product let variant let priceSetId - let pricingModuleService: IPricingModuleService beforeAll(async () => { appContainer = getContainer() - pricingModuleService = appContainer.resolve("pricingModuleService") }) beforeEach(async () => { diff --git a/integration-tests/modules/__tests__/pricing/get-product.ts b/integration-tests/modules/__tests__/pricing/get-product.ts index db66c274b6..3fffcb4d91 100644 --- a/integration-tests/modules/__tests__/pricing/get-product.ts +++ b/integration-tests/modules/__tests__/pricing/get-product.ts @@ -82,7 +82,7 @@ medusaIntegrationTestRunner({ { name: "region_id", rule_attribute: "region_id" }, ]) - priceSet = await pricingModuleService.create({ + priceSet = await pricingModuleService.createPriceSets({ rules: [{ rule_attribute: "region_id" }], prices: [ { diff --git a/integration-tests/modules/__tests__/product/admin/products.spec.ts b/integration-tests/modules/__tests__/product/admin/products.spec.ts index 5ac231244b..a1980ba96a 100644 --- a/integration-tests/modules/__tests__/product/admin/products.spec.ts +++ b/integration-tests/modules/__tests__/product/admin/products.spec.ts @@ -22,14 +22,14 @@ async function createProductsWithVariants( ): Promise<[ProductDTO, ProductVariantDTO[]]> { const { variants: variantsData, ...productData } = productsData - const [product] = await productModule.create([productData]) + const [product] = await productModule.createProducts([productData]) const variantsDataWithProductId = variantsData?.map((variantData) => { return { ...variantData, product_id: product.id } }) const variants = variantsDataWithProductId - ? await productModule.createVariants(variantsDataWithProductId) + ? await productModule.createProductVariants(variantsDataWithProductId) : [] return [product, variants] diff --git a/integration-tests/modules/__tests__/product/workflows/batch-products.spec.ts b/integration-tests/modules/__tests__/product/workflows/batch-products.spec.ts index 8914f946a6..62111d4806 100644 --- a/integration-tests/modules/__tests__/product/workflows/batch-products.spec.ts +++ b/integration-tests/modules/__tests__/product/workflows/batch-products.spec.ts @@ -35,8 +35,8 @@ medusaIntegrationTestRunner({ }, }) - const product1 = await service.create({ title: "test1" }) - const product2 = await service.create({ title: "test2" }) + const product1 = await service.createProducts({ title: "test1" }) + const product2 = await service.createProducts({ title: "test2" }) const { errors } = await workflow.run({ input: { @@ -57,7 +57,7 @@ medusaIntegrationTestRunner({ }, ]) - const products = await service.list() + const products = await service.listProducts() expect(products).toHaveLength(2) expect(products).toEqual([ @@ -135,7 +135,7 @@ medusaIntegrationTestRunner({ }, ]) - const product = await service.retrieve(product1.id, { + const product = await service.retrieveProduct(product1.id, { relations: ["variants"], }) diff --git a/integration-tests/modules/__tests__/promotion/admin/create-promotion.spec.ts b/integration-tests/modules/__tests__/promotion/admin/create-promotion.spec.ts index 0b49a893b4..162e98e35c 100644 --- a/integration-tests/modules/__tests__/promotion/admin/create-promotion.spec.ts +++ b/integration-tests/modules/__tests__/promotion/admin/create-promotion.spec.ts @@ -16,13 +16,8 @@ medusaIntegrationTestRunner({ testSuite: ({ dbConnection, getContainer, api }) => { describe("POST /admin/promotions", () => { let appContainer - let promotionModuleService: IPromotionModuleService - beforeAll(async () => { appContainer = getContainer() - promotionModuleService = appContainer.resolve( - ModuleRegistrationName.PROMOTION - ) }) beforeEach(async () => { diff --git a/integration-tests/modules/__tests__/promotion/admin/delete-promotion.spec.ts b/integration-tests/modules/__tests__/promotion/admin/delete-promotion.spec.ts index d9a1c16534..c67691983a 100644 --- a/integration-tests/modules/__tests__/promotion/admin/delete-promotion.spec.ts +++ b/integration-tests/modules/__tests__/promotion/admin/delete-promotion.spec.ts @@ -29,7 +29,7 @@ medusaIntegrationTestRunner({ }) it("should delete promotion successfully", async () => { - const createdPromotion = await promotionModuleService.create({ + const createdPromotion = await promotionModuleService.createPromotions({ code: "TEST", type: "standard", application_method: { @@ -47,7 +47,7 @@ medusaIntegrationTestRunner({ expect(deleteRes.status).toEqual(200) - const promotions = await promotionModuleService.list({ + const promotions = await promotionModuleService.listPromotions({ id: [createdPromotion.id], }) diff --git a/integration-tests/modules/__tests__/promotion/admin/list-promotions.spec.ts b/integration-tests/modules/__tests__/promotion/admin/list-promotions.spec.ts index f75867b8d9..eb0e75fd8f 100644 --- a/integration-tests/modules/__tests__/promotion/admin/list-promotions.spec.ts +++ b/integration-tests/modules/__tests__/promotion/admin/list-promotions.spec.ts @@ -30,7 +30,7 @@ medusaIntegrationTestRunner({ }) it("should get all promotions and its count", async () => { - await promotionModuleService.create([ + await promotionModuleService.createPromotions([ { code: "TEST", type: PromotionType.STANDARD, @@ -69,7 +69,7 @@ medusaIntegrationTestRunner({ }) it("should support search of promotions", async () => { - await promotionModuleService.create([ + await promotionModuleService.createPromotions([ { code: "first", type: PromotionType.STANDARD, @@ -103,7 +103,7 @@ medusaIntegrationTestRunner({ }) it("should get all promotions and its count filtered", async () => { - await promotionModuleService.create([ + await promotionModuleService.createPromotions([ { code: "TEST", type: PromotionType.STANDARD, diff --git a/integration-tests/modules/__tests__/promotion/admin/promotion-rules.spec.ts b/integration-tests/modules/__tests__/promotion/admin/promotion-rules.spec.ts index 35e8518a35..6d382059ad 100644 --- a/integration-tests/modules/__tests__/promotion/admin/promotion-rules.spec.ts +++ b/integration-tests/modules/__tests__/promotion/admin/promotion-rules.spec.ts @@ -47,7 +47,7 @@ medusaIntegrationTestRunner({ beforeEach(async () => { await createAdminUser(dbConnection, adminHeaders, appContainer) - standardPromotion = await promotionModule.create({ + standardPromotion = await promotionModule.createPromotions({ code: "TEST_ACROSS", type: PromotionType.STANDARD, application_method: { @@ -322,7 +322,7 @@ medusaIntegrationTestRunner({ }) it("should add buy rules to a buyget promotion successfully", async () => { - const buyGetPromotion = await promotionModule.create({ + const buyGetPromotion = await promotionModule.createPromotions({ code: "TEST_BUYGET", type: PromotionType.BUYGET, application_method: { @@ -414,7 +414,7 @@ medusaIntegrationTestRunner({ deleted: true, }) - const promotion = await promotionModule.retrieve( + const promotion = await promotionModule.retrievePromotion( standardPromotion.id, { relations: ["rules"] } ) @@ -455,7 +455,7 @@ medusaIntegrationTestRunner({ deleted: true, }) - const promotion = await promotionModule.retrieve( + const promotion = await promotionModule.retrievePromotion( standardPromotion.id, { relations: ["application_method.target_rules"] } ) @@ -482,7 +482,7 @@ medusaIntegrationTestRunner({ }) it("should remove buy rules from a promotion successfully", async () => { - const buyGetPromotion = await promotionModule.create({ + const buyGetPromotion = await promotionModule.createPromotions({ code: "TEST_BUYGET", type: PromotionType.BUYGET, application_method: { @@ -513,9 +513,12 @@ medusaIntegrationTestRunner({ deleted: true, }) - const promotion = await promotionModule.retrieve(buyGetPromotion.id, { - relations: ["application_method.buy_rules"], - }) + const promotion = await promotionModule.retrievePromotion( + buyGetPromotion.id, + { + relations: ["application_method.buy_rules"], + } + ) expect(promotion.application_method!.buy_rules!.length).toEqual(0) }) @@ -731,7 +734,7 @@ medusaIntegrationTestRunner({ }) it("should return all values based on rule types", async () => { - const [region1, region2] = await regionService.create([ + const [region1, region2] = await regionService.createRegions([ { name: "North America", currency_code: "usd" }, { name: "Europe", currency_code: "eur" }, ]) @@ -770,7 +773,7 @@ medusaIntegrationTestRunner({ ]) ) - const group = await customerService.createCustomerGroup({ + const group = await customerService.createCustomerGroups({ name: "VIP", }) @@ -787,7 +790,7 @@ medusaIntegrationTestRunner({ }, ]) - const salesChannel = await salesChannelService.create({ + const salesChannel = await salesChannelService.createSalesChannels({ name: "Instagram", }) @@ -826,7 +829,7 @@ medusaIntegrationTestRunner({ ]) ) - const [product1, product2] = await productService.create([ + const [product1, product2] = await productService.createProducts([ { title: "test product 1" }, { title: "test product 2" }, ]) @@ -845,7 +848,7 @@ medusaIntegrationTestRunner({ ]) ) - const category = await productService.createCategory({ + const category = await productService.createProductCategories({ name: "test category 1", parent_category_id: null, }) @@ -860,7 +863,7 @@ medusaIntegrationTestRunner({ { label: "test category 1", value: category.id }, ]) - const collection = await productService.createCollections({ + const collection = await productService.createProductCollections({ title: "test collection 1", }) @@ -874,7 +877,7 @@ medusaIntegrationTestRunner({ { label: "test collection 1", value: collection.id }, ]) - const type = await productService.createTypes({ + const type = await productService.createProductTypes({ value: "test type", }) @@ -888,7 +891,7 @@ medusaIntegrationTestRunner({ { label: "test type", value: type.id }, ]) - const [tag1, tag2] = await productService.createTags([ + const [tag1, tag2] = await productService.createProductTags([ { value: "test tag 1" }, { value: "test tag 2" }, ]) diff --git a/integration-tests/modules/__tests__/promotion/admin/retrieve-promotion.spec.ts b/integration-tests/modules/__tests__/promotion/admin/retrieve-promotion.spec.ts index fef50a8bd1..a21728b187 100644 --- a/integration-tests/modules/__tests__/promotion/admin/retrieve-promotion.spec.ts +++ b/integration-tests/modules/__tests__/promotion/admin/retrieve-promotion.spec.ts @@ -41,7 +41,7 @@ medusaIntegrationTestRunner({ }) it("should get the requested promotion by id or codde", async () => { - const createdPromotion = await promotionModuleService.create({ + const createdPromotion = await promotionModuleService.createPromotions({ code: "TEST", type: PromotionType.STANDARD, application_method: { @@ -78,7 +78,7 @@ medusaIntegrationTestRunner({ }) it("should get the requested promotion with filtered fields and relations", async () => { - const createdPromotion = await promotionModuleService.create({ + const createdPromotion = await promotionModuleService.createPromotions({ code: "TEST", type: PromotionType.STANDARD, application_method: { diff --git a/integration-tests/modules/__tests__/promotion/admin/update-promotion.spec.ts b/integration-tests/modules/__tests__/promotion/admin/update-promotion.spec.ts index cf739e5956..862df69fe7 100644 --- a/integration-tests/modules/__tests__/promotion/admin/update-promotion.spec.ts +++ b/integration-tests/modules/__tests__/promotion/admin/update-promotion.spec.ts @@ -45,7 +45,7 @@ medusaIntegrationTestRunner({ }) it("should throw an error when both campaign and campaign_id params are passed", async () => { - const createdPromotion = await promotionModuleService.create({ + const createdPromotion = await promotionModuleService.createPromotions({ code: "TEST", type: PromotionType.STANDARD, is_automatic: true, @@ -79,7 +79,7 @@ medusaIntegrationTestRunner({ }) it("should update a promotion successfully", async () => { - const createdPromotion = await promotionModuleService.create({ + const createdPromotion = await promotionModuleService.createPromotions({ code: "TEST", type: PromotionType.STANDARD, is_automatic: true, @@ -117,7 +117,7 @@ medusaIntegrationTestRunner({ }) it("should update a buyget promotion successfully", async () => { - const createdPromotion = await promotionModuleService.create({ + const createdPromotion = await promotionModuleService.createPromotions({ code: "PROMOTION_TEST", type: PromotionType.BUYGET, application_method: { diff --git a/integration-tests/modules/__tests__/regions/admin/regions.spec.ts b/integration-tests/modules/__tests__/regions/admin/regions.spec.ts index 6fa145a72f..c60515317f 100644 --- a/integration-tests/modules/__tests__/regions/admin/regions.spec.ts +++ b/integration-tests/modules/__tests__/regions/admin/regions.spec.ts @@ -87,9 +87,12 @@ medusaIntegrationTestRunner({ deleted: true, }) - const deletedRegion = await service.retrieve(updated.data.region.id, { - withDeleted: true, - }) + const deletedRegion = await service.retrieveRegion( + updated.data.region.id, + { + withDeleted: true, + } + ) // @ts-ignore expect(deletedRegion.deleted_at).toBeTruthy() @@ -294,7 +297,7 @@ medusaIntegrationTestRunner({ }) it("should throw on unknown properties in update", async () => { - const created = await service.create({ + const created = await service.createRegions({ name: "Test Region", currency_code: "usd", }) @@ -318,7 +321,7 @@ medusaIntegrationTestRunner({ }) it("should get all regions and count", async () => { - await service.create([ + await service.createRegions([ { name: "Test", currency_code: "usd", @@ -344,7 +347,7 @@ medusaIntegrationTestRunner({ }) it("should support searching of regions", async () => { - await service.create([ + await service.createRegions([ { name: "APAC", currency_code: "usd", @@ -369,7 +372,7 @@ medusaIntegrationTestRunner({ }) it("should get a region", async () => { - const [region] = await service.create([ + const [region] = await service.createRegions([ { name: "Test", currency_code: "usd", diff --git a/integration-tests/modules/__tests__/shipping-options/store/shipping-options.spec.ts b/integration-tests/modules/__tests__/shipping-options/store/shipping-options.spec.ts index aef2300f64..d16c89548d 100644 --- a/integration-tests/modules/__tests__/shipping-options/store/shipping-options.spec.ts +++ b/integration-tests/modules/__tests__/shipping-options/store/shipping-options.spec.ts @@ -43,7 +43,7 @@ medusaIntegrationTestRunner({ ContainerRegistrationKeys.REMOTE_LINK ) - region = await regionService.create({ + region = await regionService.createRegions({ name: "Test region", countries: ["US"], currency_code: "usd", @@ -103,7 +103,7 @@ medusaIntegrationTestRunner({ type: "default", }) - fulfillmentSet = await fulfillmentModule.create({ + fulfillmentSet = await fulfillmentModule.createFulfillmentSets({ name: "Test", type: "test-type", service_zones: [ @@ -184,7 +184,9 @@ medusaIntegrationTestRunner({ describe("GET /admin/shipping-options?cart_id=", () => { it("should get all shipping options for a cart successfully", async () => { - const resp = await api.get(`/store/shipping-options?cart_id=${cart.id}`) + const resp = await api.get( + `/store/shipping-options?cart_id=${cart.id}` + ) const shippingOptions = resp.data.shipping_options expect(shippingOptions).toHaveLength(1) diff --git a/integration-tests/modules/__tests__/shipping-options/workflows/batch-shipping-options-rules.ts b/integration-tests/modules/__tests__/shipping-options/workflows/batch-shipping-options-rules.ts index a743d7bf3e..48e2ae8d60 100644 --- a/integration-tests/modules/__tests__/shipping-options/workflows/batch-shipping-options-rules.ts +++ b/integration-tests/modules/__tests__/shipping-options/workflows/batch-shipping-options-rules.ts @@ -1,4 +1,4 @@ -import { ModuleRegistrationName } from "@medusajs/modules-sdk" +import {ModuleRegistrationName} from "@medusajs/modules-sdk" import { BatchWorkflowInput, CreateShippingOptionRuleDTO, @@ -10,7 +10,7 @@ import { ShippingProfileDTO, UpdateShippingOptionRuleDTO, } from "@medusajs/types" -import { medusaIntegrationTestRunner } from "medusa-test-utils/dist" +import {medusaIntegrationTestRunner} from "medusa-test-utils/dist" import { batchShippingOptionRulesWorkflow, createShippingOptionsWorkflow, @@ -35,7 +35,7 @@ async function createShippingOptionFixture({ ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", @@ -136,7 +136,7 @@ medusaIntegrationTestRunner({ type: "default", }) - fulfillmentSet = await service.create({ + fulfillmentSet = await service.createFulfillmentSets({ name: "Test fulfillment set", type: "manual_test", }) diff --git a/integration-tests/modules/__tests__/shipping-options/workflows/create-shipping-options.ts b/integration-tests/modules/__tests__/shipping-options/workflows/create-shipping-options.ts index d38d1a78b3..1cc96b2113 100644 --- a/integration-tests/modules/__tests__/shipping-options/workflows/create-shipping-options.ts +++ b/integration-tests/modules/__tests__/shipping-options/workflows/create-shipping-options.ts @@ -42,7 +42,7 @@ medusaIntegrationTestRunner({ type: "default", }) - fulfillmentSet = await service.create({ + fulfillmentSet = await service.createFulfillmentSets({ name: "Test fulfillment set", type: "manual_test", }) @@ -64,7 +64,7 @@ medusaIntegrationTestRunner({ ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", @@ -180,7 +180,7 @@ medusaIntegrationTestRunner({ ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", diff --git a/integration-tests/modules/__tests__/shipping-options/workflows/delete-shipping-options.ts b/integration-tests/modules/__tests__/shipping-options/workflows/delete-shipping-options.ts index c9f6a35384..4577c95f4c 100644 --- a/integration-tests/modules/__tests__/shipping-options/workflows/delete-shipping-options.ts +++ b/integration-tests/modules/__tests__/shipping-options/workflows/delete-shipping-options.ts @@ -45,7 +45,7 @@ medusaIntegrationTestRunner({ type: "default", }) - fulfillmentSet = await service.create({ + fulfillmentSet = await service.createFulfillmentSets({ name: "Test fulfillment set", type: "manual_test", }) @@ -67,7 +67,7 @@ medusaIntegrationTestRunner({ ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", @@ -150,7 +150,7 @@ medusaIntegrationTestRunner({ ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", diff --git a/integration-tests/modules/__tests__/shipping-options/workflows/update-shipping-options.ts b/integration-tests/modules/__tests__/shipping-options/workflows/update-shipping-options.ts index 0aad3b7212..a6aa63bd14 100644 --- a/integration-tests/modules/__tests__/shipping-options/workflows/update-shipping-options.ts +++ b/integration-tests/modules/__tests__/shipping-options/workflows/update-shipping-options.ts @@ -46,7 +46,7 @@ medusaIntegrationTestRunner({ type: "default", }) - fulfillmentSet = await service.create({ + fulfillmentSet = await service.createFulfillmentSets({ name: "Test fulfillment set", type: "manual_test", }) @@ -68,7 +68,7 @@ medusaIntegrationTestRunner({ ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", @@ -233,7 +233,7 @@ medusaIntegrationTestRunner({ ModuleRegistrationName.REGION ) as IRegionModuleService - const [region] = await regionService.create([ + const [region] = await regionService.createRegions([ { name: "Test region", currency_code: "eur", diff --git a/integration-tests/modules/__tests__/store/admin/store.spec.ts b/integration-tests/modules/__tests__/store/admin/store.spec.ts index 3de41cf9a2..cb276625bb 100644 --- a/integration-tests/modules/__tests__/store/admin/store.spec.ts +++ b/integration-tests/modules/__tests__/store/admin/store.spec.ts @@ -27,7 +27,7 @@ medusaIntegrationTestRunner({ }) it("should correctly implement the entire lifecycle of a store", async () => { - const createdStore = await service.create({ + const createdStore = await service.createStores({ name: "Test store", supported_currency_codes: ["usd"], }) @@ -56,8 +56,11 @@ medusaIntegrationTestRunner({ }) ) - await service.delete(createdStore.id) - const listedStores = await api.get(`/admin/stores?id=${createdStore.id}`, adminHeaders) + await service.deleteStores(createdStore.id) + const listedStores = await api.get( + `/admin/stores?id=${createdStore.id}`, + adminHeaders + ) expect(listedStores.data.stores).toHaveLength(0) }) }) diff --git a/integration-tests/modules/__tests__/tax/admin/tax.spec.ts b/integration-tests/modules/__tests__/tax/admin/tax.spec.ts index 11c81b39da..868656e93a 100644 --- a/integration-tests/modules/__tests__/tax/admin/tax.spec.ts +++ b/integration-tests/modules/__tests__/tax/admin/tax.spec.ts @@ -31,7 +31,7 @@ medusaIntegrationTestRunner({ const region = await service.createTaxRegions({ country_code: "us", }) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, code: "test", rate: 2.5, @@ -69,14 +69,14 @@ medusaIntegrationTestRunner({ country_code: "us", }) - await service.create({ + await service.createTaxRates({ tax_region_id: region.id, code: "low", rate: 2.5, name: "low rate", }) - await service.create({ + await service.createTaxRates({ tax_region_id: region.id, code: "high", rate: 5, @@ -384,7 +384,7 @@ medusaIntegrationTestRunner({ deleted: true, }) - const rates = await service.list( + const rates = await service.listTaxRates( { id: rateRes.data.tax_rate.id }, { withDeleted: true } ) @@ -397,7 +397,7 @@ medusaIntegrationTestRunner({ country_code: "us", }) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, code: "test", rate: 2.5, diff --git a/integration-tests/modules/__tests__/tax/workflow/tax.spec.ts b/integration-tests/modules/__tests__/tax/workflow/tax.spec.ts index 7d906b4524..32aadc4d21 100644 --- a/integration-tests/modules/__tests__/tax/workflow/tax.spec.ts +++ b/integration-tests/modules/__tests__/tax/workflow/tax.spec.ts @@ -36,7 +36,7 @@ medusaIntegrationTestRunner({ country_code: "us", }) - const [rateOne, rateTwo] = await service.create([ + const [rateOne, rateTwo] = await service.createTaxRates([ { tax_region_id: taxRegion.id, rate: 10, @@ -123,7 +123,7 @@ medusaIntegrationTestRunner({ country_code: "us", }) - const [rateOne, rateTwo] = await service.create([ + const [rateOne, rateTwo] = await service.createTaxRates([ { tax_region_id: taxRegion.id, rate: 10, diff --git a/integration-tests/modules/__tests__/users/delete-user.spec.ts b/integration-tests/modules/__tests__/users/delete-user.spec.ts index ca270094d3..7de05c9563 100644 --- a/integration-tests/modules/__tests__/users/delete-user.spec.ts +++ b/integration-tests/modules/__tests__/users/delete-user.spec.ts @@ -27,7 +27,7 @@ medusaIntegrationTestRunner({ }) it("should delete a single user", async () => { - const user = await userModuleService.create({ + const user = await userModuleService.createUsers({ email: "member@test.com", }) diff --git a/integration-tests/modules/__tests__/users/list-users.spec.ts b/integration-tests/modules/__tests__/users/list-users.spec.ts index 85f9cc3c5e..8a2e5ee779 100644 --- a/integration-tests/modules/__tests__/users/list-users.spec.ts +++ b/integration-tests/modules/__tests__/users/list-users.spec.ts @@ -27,7 +27,7 @@ medusaIntegrationTestRunner({ }) it("should list users", async () => { - await userModuleService.create([ + await userModuleService.createUsers([ { email: "member@test.com", }, diff --git a/integration-tests/modules/__tests__/users/retrieve-user.spec.ts b/integration-tests/modules/__tests__/users/retrieve-user.spec.ts index 4139a09fe6..bbd1f2f3a3 100644 --- a/integration-tests/modules/__tests__/users/retrieve-user.spec.ts +++ b/integration-tests/modules/__tests__/users/retrieve-user.spec.ts @@ -27,7 +27,7 @@ medusaIntegrationTestRunner({ }) it("should retrieve a single user", async () => { - const user = await userModuleService.create({ + const user = await userModuleService.createUsers({ email: "member@test.com", }) diff --git a/integration-tests/modules/__tests__/users/update-user.spec.ts b/integration-tests/modules/__tests__/users/update-user.spec.ts index 3ae251ca78..275d98ef66 100644 --- a/integration-tests/modules/__tests__/users/update-user.spec.ts +++ b/integration-tests/modules/__tests__/users/update-user.spec.ts @@ -27,7 +27,7 @@ medusaIntegrationTestRunner({ }) it("should update a single user", async () => { - const user = await userModuleService.create({ + const user = await userModuleService.createUsers({ email: "member@test.com", }) diff --git a/integration-tests/modules/helpers/create-authenticated-customer.ts b/integration-tests/modules/helpers/create-authenticated-customer.ts index 6ec67fee44..d092ad9ed7 100644 --- a/integration-tests/modules/helpers/create-authenticated-customer.ts +++ b/integration-tests/modules/helpers/create-authenticated-customer.ts @@ -13,16 +13,20 @@ export const createAuthenticatedCustomer = async ( ModuleRegistrationName.CUSTOMER ) - const customer = await customerModuleService.create({ + const customer = await customerModuleService.createCustomers({ first_name: "John", last_name: "Doe", email: "john@me.com", ...customerData, }) - const authIdentity = await authService.create({ - entity_id: "store_user", - provider: "emailpass", + const authIdentity = await authService.createAuthIdentities({ + provider_identities: [ + { + entity_id: "store_user", + provider: "emailpass", + }, + ], app_metadata: { customer_id: customer.id, }, diff --git a/integration-tests/modules/helpers/create-default-rule-types.ts b/integration-tests/modules/helpers/create-default-rule-types.ts index 6db9fb25ef..7ef8284090 100644 --- a/integration-tests/modules/helpers/create-default-rule-types.ts +++ b/integration-tests/modules/helpers/create-default-rule-types.ts @@ -5,7 +5,7 @@ export const createDefaultRuleTypes = async (container) => { "pricingModuleService" ) - return pricingModuleService.createRuleTypes([ + return await pricingModuleService.createRuleTypes([ { name: "region_id", rule_attribute: "region_id", diff --git a/integration-tests/modules/helpers/create-variant-price-set.ts b/integration-tests/modules/helpers/create-variant-price-set.ts index 813aa9d412..9eb13f6ec2 100644 --- a/integration-tests/modules/helpers/create-variant-price-set.ts +++ b/integration-tests/modules/helpers/create-variant-price-set.ts @@ -30,7 +30,7 @@ export const createVariantPriceSet = async ({ "pricingModuleService" ) - const priceSet = await pricingModuleService.create({ + const priceSet = await pricingModuleService.createPriceSets({ rules, prices, }) @@ -40,7 +40,7 @@ export const createVariantPriceSet = async ({ [Modules.PRICING]: { price_set_id: priceSet.id }, }) - return await pricingModuleService.retrieve(priceSet.id, { + return await pricingModuleService.retrievePriceSet(priceSet.id, { relations: ["prices"], }) } diff --git a/packages/admin-next/dashboard/src/hooks/api/reservations.tsx b/packages/admin-next/dashboard/src/hooks/api/reservations.tsx index 7e118cad5e..3941c86a9e 100644 --- a/packages/admin-next/dashboard/src/hooks/api/reservations.tsx +++ b/packages/admin-next/dashboard/src/hooks/api/reservations.tsx @@ -15,7 +15,7 @@ import { ReservationItemRes, } from "../../types/api-responses" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { client } from "../../lib/client" import { queryClient } from "../../lib/query-client" import { queryKeysFactory } from "../../lib/query-key-factory" @@ -68,7 +68,7 @@ export const useUpdateReservationItem = ( options?: UseMutationOptions ) => { return useMutation({ - mutationFn: (payload: InventoryNext.UpdateReservationItemInput) => + mutationFn: (payload: InventoryTypes.UpdateReservationItemInput) => client.reservations.update(id, payload), onSuccess: (data, variables, context) => { queryClient.invalidateQueries({ diff --git a/packages/admin-next/dashboard/src/lib/client/reservations.ts b/packages/admin-next/dashboard/src/lib/client/reservations.ts index 68ac62e426..0a3597fa97 100644 --- a/packages/admin-next/dashboard/src/lib/client/reservations.ts +++ b/packages/admin-next/dashboard/src/lib/client/reservations.ts @@ -5,7 +5,7 @@ import { } from "../../types/api-responses" import { deleteRequest, getRequest, postRequest } from "./common" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" async function retrieveReservation(id: string, query?: Record) { return getRequest(`/admin/reservations/${id}`, query) @@ -16,14 +16,14 @@ async function listReservations(query?: Record) { } async function createReservation( - payload: InventoryNext.CreateReservationItemInput + payload: InventoryTypes.CreateReservationItemInput ) { return postRequest(`/admin/reservations`, payload) } async function updateReservation( id: string, - payload: InventoryNext.UpdateReservationItemInput + payload: InventoryTypes.UpdateReservationItemInput ) { return postRequest(`/admin/reservations/${id}`, payload) } diff --git a/packages/admin-next/dashboard/src/lib/client/workflow-executions.ts b/packages/admin-next/dashboard/src/lib/client/workflow-executions.ts index 30e14ad895..9797cba123 100644 --- a/packages/admin-next/dashboard/src/lib/client/workflow-executions.ts +++ b/packages/admin-next/dashboard/src/lib/client/workflow-executions.ts @@ -14,7 +14,7 @@ async function retrieveWorkflowExecution( ) } -async function listWorkflowExecutions(query?: Record) { +async function listWorkflowExecutionss(query?: Record) { return getRequest( `/admin/workflows-executions`, query @@ -23,5 +23,5 @@ async function listWorkflowExecutions(query?: Record) { export const workflowExecutions = { retrieve: retrieveWorkflowExecution, - list: listWorkflowExecutions, + list: listWorkflowExecutionss, } diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/adjust-inventory/adjust-inventory-drawer.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/adjust-inventory/adjust-inventory-drawer.tsx index 6e6509212a..d66385af8a 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/adjust-inventory/adjust-inventory-drawer.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/adjust-inventory/adjust-inventory-drawer.tsx @@ -1,6 +1,6 @@ import { AdjustInventoryForm } from "./components/adjust-inventory-form" import { Heading } from "@medusajs/ui" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { RouteDrawer } from "../../../../../components/route-modal" import { useInventoryItem } from "../../../../../hooks/api/inventory" import { useParams } from "react-router-dom" @@ -19,7 +19,7 @@ export const AdjustInventoryDrawer = () => { } = useInventoryItem(id!) const inventoryLevel = inventoryItem?.location_levels!.find( - (level: InventoryNext.InventoryLevelDTO) => + (level: InventoryTypes.InventoryLevelDTO) => level.location_id === location_id ) diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/edit-inventory-item-attributes/components/edit-item-attributes-form.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/edit-inventory-item-attributes/components/edit-item-attributes-form.tsx index 9e2324d15a..f75f5b4528 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/edit-inventory-item-attributes/components/edit-item-attributes-form.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/edit-inventory-item-attributes/components/edit-item-attributes-form.tsx @@ -7,7 +7,7 @@ import { } from "../../../../../../components/route-modal" import { zodResolver } from "@hookform/resolvers/zod" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { useForm } from "react-hook-form" import { useTranslation } from "react-i18next" import { z } from "zod" @@ -16,7 +16,7 @@ import { CountrySelect } from "../../../../../../components/inputs/country-selec import { useUpdateInventoryItem } from "../../../../../../hooks/api/inventory" type EditInventoryItemAttributeFormProps = { - item: InventoryNext.InventoryItemDTO + item: InventoryTypes.InventoryItemDTO } const EditInventoryItemAttributesSchema = z.object({ @@ -29,7 +29,7 @@ const EditInventoryItemAttributesSchema = z.object({ origin_country: z.string().optional(), }) -const getDefaultValues = (item: InventoryNext.InventoryItemDTO) => { +const getDefaultValues = (item: InventoryTypes.InventoryItemDTO) => { return { height: item.height ?? undefined, width: item.width ?? undefined, diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/edit-inventory-item/components/edit-item-form.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/edit-inventory-item/components/edit-item-form.tsx index c86649eba4..2de7b4492a 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/edit-inventory-item/components/edit-item-form.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/edit-inventory-item/components/edit-item-form.tsx @@ -7,7 +7,7 @@ import { } from "../../../../../../components/route-modal" import { Form } from "../../../../../../components/common/form" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { useForm } from "react-hook-form" import { useTranslation } from "react-i18next" import { useUpdateInventoryItem } from "../../../../../../hooks/api/inventory" @@ -15,7 +15,7 @@ import { z } from "zod" import { zodResolver } from "@hookform/resolvers/zod" type EditInventoryItemFormProps = { - item: InventoryNext.InventoryItemDTO + item: InventoryTypes.InventoryItemDTO } const EditInventoryItemSchema = z.object({ @@ -23,7 +23,7 @@ const EditInventoryItemSchema = z.object({ sku: z.string().min(1), }) -const getDefaultValues = (item: InventoryNext.InventoryItemDTO) => { +const getDefaultValues = (item: InventoryTypes.InventoryItemDTO) => { return { title: item.title ?? undefined, sku: item.sku ?? undefined, diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/inventory-item-attributes/attributes-section.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/inventory-item-attributes/attributes-section.tsx index 5a47844f4c..6292d568f7 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/inventory-item-attributes/attributes-section.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/inventory-item-attributes/attributes-section.tsx @@ -1,14 +1,14 @@ import { Container, Heading } from "@medusajs/ui" import { ActionMenu } from "../../../../../components/common/action-menu" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { PencilSquare } from "@medusajs/icons" import { SectionRow } from "../../../../../components/common/section" import { getFormattedCountry } from "../../../../../lib/addresses" import { useTranslation } from "react-i18next" type InventoryItemAttributeSectionProps = { - inventoryItem: InventoryNext.InventoryItemDTO + inventoryItem: InventoryTypes.InventoryItemDTO } export const InventoryItemAttributeSection = ({ diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/location-levels-table/location-actions.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/location-levels-table/location-actions.tsx index a2dc301949..9c5d6ae8a4 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/location-levels-table/location-actions.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/location-levels-table/location-actions.tsx @@ -1,7 +1,7 @@ import { PencilSquare, Trash } from "@medusajs/icons" import { ActionMenu } from "../../../../../components/common/action-menu" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { useDeleteInventoryItemLevel } from "../../../../../hooks/api/inventory" import { usePrompt } from "@medusajs/ui" import { useTranslation } from "react-i18next" @@ -9,7 +9,7 @@ import { useTranslation } from "react-i18next" export const LocationActions = ({ level, }: { - level: InventoryNext.InventoryLevelDTO + level: InventoryTypes.InventoryLevelDTO }) => { const { t } = useTranslation() const prompt = usePrompt() diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/location-levels-table/use-location-list-table-columns.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/location-levels-table/use-location-list-table-columns.tsx index f0034901f8..2efc96f134 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/location-levels-table/use-location-list-table-columns.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/location-levels-table/use-location-list-table-columns.tsx @@ -1,4 +1,4 @@ -import { InventoryNext, StockLocationDTO } from "@medusajs/types" +import { InventoryTypes, StockLocationDTO } from "@medusajs/types" import { LocationActions } from "./location-actions" import { PlaceholderCell } from "../../../../../components/table/table-cells/common/placeholder-cell" @@ -9,7 +9,7 @@ import { useTranslation } from "react-i18next" /** * Adds missing properties to the InventoryLevelDTO type. */ -interface ExtendedLocationLevel extends InventoryNext.InventoryLevelDTO { +interface ExtendedLocationLevel extends InventoryTypes.InventoryLevelDTO { stock_locations: StockLocationDTO[] reserved_quantity: number stocked_quantity: number diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/reservation-actions.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/reservation-actions.tsx index 8051a4b94f..762eb6e6d8 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/reservation-actions.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/reservation-actions.tsx @@ -2,14 +2,14 @@ import { PencilSquare, Trash } from "@medusajs/icons" import { toast, usePrompt } from "@medusajs/ui" import { ActionMenu } from "../../../../../components/common/action-menu" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { useDeleteReservationItem } from "../../../../../hooks/api/reservations" import { useTranslation } from "react-i18next" export const ReservationActions = ({ reservation, }: { - reservation: InventoryNext.ReservationItemDTO + reservation: InventoryTypes.ReservationItemDTO }) => { const { t } = useTranslation() const prompt = usePrompt() diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/reservation-list-table.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/reservation-list-table.tsx index 3d64f87523..c87e440af5 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/reservation-list-table.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/reservation-list-table.tsx @@ -1,5 +1,5 @@ import { DataTable } from "../../../../../components/table/data-table" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { useDataTable } from "../../../../../hooks/use-data-table" import { useReservationItems } from "../../../../../hooks/api/reservations" import { useReservationTableColumn } from "./use-reservation-list-table-columns" @@ -10,7 +10,7 @@ const PAGE_SIZE = 20 export const ReservationItemTable = ({ inventoryItem, }: { - inventoryItem: InventoryNext.InventoryItemDTO + inventoryItem: InventoryTypes.InventoryItemDTO }) => { const { searchParams, raw } = useReservationsTableQuery({ pageSize: PAGE_SIZE, @@ -29,7 +29,7 @@ export const ReservationItemTable = ({ columns, count, enablePagination: true, - getRowId: (row: InventoryNext.ReservationItemDTO) => row.id, + getRowId: (row: InventoryTypes.ReservationItemDTO) => row.id, pageSize: PAGE_SIZE, }) diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/use-reservation-list-table-columns.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/use-reservation-list-table-columns.tsx index 38106fb939..d9fd4de014 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/use-reservation-list-table-columns.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-detail/components/reservations-table/use-reservation-list-table-columns.tsx @@ -1,4 +1,4 @@ -import { InventoryNext, StockLocationDTO } from "@medusajs/types" +import { InventoryTypes, StockLocationDTO } from "@medusajs/types" import { PlaceholderCell } from "../../../../../components/table/table-cells/common/placeholder-cell" import { ReservationActions } from "./reservation-actions" @@ -9,7 +9,7 @@ import { useTranslation } from "react-i18next" /** * Adds missing properties to the InventoryItemDTO type. */ -interface ExtendedReservationItem extends InventoryNext.ReservationItemDTO { +interface ExtendedReservationItem extends InventoryTypes.ReservationItemDTO { line_item: { order_id: string } location: StockLocationDTO } diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-list/components/inventory-list-table.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-list/components/inventory-list-table.tsx index 450bdc4c25..ad64b83f1a 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-list/components/inventory-list-table.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-list/components/inventory-list-table.tsx @@ -1,5 +1,5 @@ import { Button, Container, Heading } from "@medusajs/ui" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { DataTable } from "../../../../components/table/data-table" import { useDataTable } from "../../../../hooks/use-data-table" @@ -33,7 +33,7 @@ export const InventoryListTable = () => { const columns = useInventoryTableColumns() const { table } = useDataTable({ - data: (inventory_items ?? []) as InventoryNext.InventoryItemDTO[], + data: (inventory_items ?? []) as InventoryTypes.InventoryItemDTO[], columns, count, enablePagination: true, diff --git a/packages/admin-next/dashboard/src/routes/inventory/inventory-list/components/use-inventory-table-columns.tsx b/packages/admin-next/dashboard/src/routes/inventory/inventory-list/components/use-inventory-table-columns.tsx index fe94defdf4..85b81f3882 100644 --- a/packages/admin-next/dashboard/src/routes/inventory/inventory-list/components/use-inventory-table-columns.tsx +++ b/packages/admin-next/dashboard/src/routes/inventory/inventory-list/components/use-inventory-table-columns.tsx @@ -1,4 +1,4 @@ -import { InventoryNext, ProductVariantDTO } from "@medusajs/types" +import { InventoryTypes, ProductVariantDTO } from "@medusajs/types" import { InventoryActions } from "./inventory-actions" import { PlaceholderCell } from "../../../../components/table/table-cells/common/placeholder-cell" @@ -9,7 +9,7 @@ import { useTranslation } from "react-i18next" /** * Adds missing properties to the InventoryItemDTO type. */ -interface ExtendedInventoryItem extends InventoryNext.InventoryItemDTO { +interface ExtendedInventoryItem extends InventoryTypes.InventoryItemDTO { variants?: ProductVariantDTO[] | null stocked_quantity?: number reserved_quantity?: number diff --git a/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/edit-reservation/components/edit-reservation-form.tsx b/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/edit-reservation/components/edit-reservation-form.tsx index 3dcdbbc2e4..a71be9bf15 100644 --- a/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/edit-reservation/components/edit-reservation-form.tsx +++ b/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/edit-reservation/components/edit-reservation-form.tsx @@ -1,7 +1,7 @@ import * as zod from "zod" import { Button, Input, Select, Text, Textarea, toast } from "@medusajs/ui" -import { InventoryNext, StockLocationDTO } from "@medusajs/types" +import { InventoryTypes, StockLocationDTO } from "@medusajs/types" import { RouteDrawer, useRouteModal, @@ -16,7 +16,7 @@ import { z } from "zod" import { zodResolver } from "@hookform/resolvers/zod" type EditReservationFormProps = { - reservation: InventoryNext.ReservationItemDTO + reservation: InventoryTypes.ReservationItemDTO locations: StockLocationDTO[] item: InventoryItemRes["inventory_item"] } @@ -46,7 +46,7 @@ const AttributeGridRow = ({ ) } -const getDefaultValues = (reservation: InventoryNext.ReservationItemDTO) => { +const getDefaultValues = (reservation: InventoryTypes.ReservationItemDTO) => { return { quantity: reservation.quantity, location_id: reservation.location_id, @@ -85,7 +85,8 @@ export const EditReservationForm = ({ const locationId = form.watch("location_id") const level = item.location_levels!.find( - (level: InventoryNext.InventoryLevelDTO) => level.location_id === locationId + (level: InventoryTypes.InventoryLevelDTO) => + level.location_id === locationId ) return ( diff --git a/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/edit-reservation/edit-reservation-modal.tsx b/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/edit-reservation/edit-reservation-modal.tsx index a070187b5c..e3feb44e17 100644 --- a/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/edit-reservation/edit-reservation-modal.tsx +++ b/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/edit-reservation/edit-reservation-modal.tsx @@ -1,6 +1,6 @@ import { EditReservationForm } from "./components/edit-reservation-form" import { Heading } from "@medusajs/ui" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { RouteDrawer } from "../../../../../components/route-modal" import { useInventoryItem } from "../../../../../hooks/api/inventory" import { useParams } from "react-router-dom" @@ -23,7 +23,7 @@ export const ReservationEdit = () => { const { stock_locations } = useStockLocations( { id: inventoryItem?.location_levels?.map( - (l: InventoryNext.InventoryLevelDTO) => l.location_id + (l: InventoryTypes.InventoryLevelDTO) => l.location_id ), }, { diff --git a/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/reservation-general-section/reservation-general-section.tsx b/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/reservation-general-section/reservation-general-section.tsx index 065590eef0..4e76b7a1ee 100644 --- a/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/reservation-general-section/reservation-general-section.tsx +++ b/packages/admin-next/dashboard/src/routes/reservations/reservation-detail/components/reservation-general-section/reservation-general-section.tsx @@ -2,7 +2,7 @@ import { AdminReservationResponse, StockLocationDTO } from "@medusajs/types" import { Container, Heading } from "@medusajs/ui" import { ActionMenu } from "../../../../../components/common/action-menu" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { PencilSquare } from "@medusajs/icons" import { SectionRow } from "../../../../../components/common/section" import { useInventoryItem } from "../../../../../hooks/api/inventory" @@ -34,7 +34,7 @@ export const ReservationGeneralSection = ({ } const locationLevel = inventoryItem.location_levels!.find( - (l: InventoryNext.InventoryLevelDTO) => + (l: InventoryTypes.InventoryLevelDTO) => l.location_id === reservation.location_id ) diff --git a/packages/admin-next/dashboard/src/routes/reservations/reservation-list/create-reservation/components/create-reservation-form/create-reservation-form.tsx b/packages/admin-next/dashboard/src/routes/reservations/reservation-list/create-reservation/components/create-reservation-form/create-reservation-form.tsx index f7ff05149f..5ae336e0a9 100644 --- a/packages/admin-next/dashboard/src/routes/reservations/reservation-list/create-reservation/components/create-reservation-form/create-reservation-form.tsx +++ b/packages/admin-next/dashboard/src/routes/reservations/reservation-list/create-reservation/components/create-reservation-form/create-reservation-form.tsx @@ -7,7 +7,7 @@ import { } from "../../../../../../components/route-modal" import { zodResolver } from "@hookform/resolvers/zod" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import React from "react" import { useForm } from "react-hook-form" import { useTranslation } from "react-i18next" @@ -81,7 +81,7 @@ export const CreateReservationForm = () => { { id: selectedInventoryItem?.location_levels?.map( - (level: InventoryNext.InventoryLevelDTO) => level.location_id + (level: InventoryTypes.InventoryLevelDTO) => level.location_id ) ?? [], }, { diff --git a/packages/admin-next/dashboard/src/types/api-payloads.ts b/packages/admin-next/dashboard/src/types/api-payloads.ts index ca3fa694c1..0a1554bd73 100644 --- a/packages/admin-next/dashboard/src/types/api-payloads.ts +++ b/packages/admin-next/dashboard/src/types/api-payloads.ts @@ -15,7 +15,7 @@ import { CreateShippingOptionDTO, CreateShippingProfileDTO, CreateStockLocationInput, - InventoryNext, + InventoryTypes, UpdateApiKeyDTO, UpdateCampaignDTO, UpdatePriceListDTO, @@ -112,7 +112,7 @@ export type UpdateCampaignReq = UpdateCampaignDTO // Reservations export type UpdateReservationReq = Omit< - InventoryNext.UpdateReservationItemInput, + InventoryTypes.UpdateReservationItemInput, "id" > -export type CreateReservationReq = InventoryNext.CreateReservationItemInput +export type CreateReservationReq = InventoryTypes.CreateReservationItemInput diff --git a/packages/admin-next/dashboard/src/types/api-responses.ts b/packages/admin-next/dashboard/src/types/api-responses.ts index a1dcf828ab..09bb540a30 100644 --- a/packages/admin-next/dashboard/src/types/api-responses.ts +++ b/packages/admin-next/dashboard/src/types/api-responses.ts @@ -8,7 +8,7 @@ import { CustomerGroupDTO, FulfillmentDTO, FulfillmentProviderDTO, - InventoryNext, + InventoryTypes, InviteDTO, OrderDTO, PaymentProviderDTO, @@ -70,9 +70,9 @@ export type FulfillmentListRes = { fulfillments: FulfillmentDTO[] } & ListRes export type FulfillmentDeleteRes = DeleteRes // Reservations -export type ReservationRes = { reservation: InventoryNext.ReservationItemDTO } +export type ReservationRes = { reservation: InventoryTypes.ReservationItemDTO } export type ReservationListRes = { - reservations: InventoryNext.ReservationItemDTO[] + reservations: InventoryTypes.ReservationItemDTO[] } & ListRes export type ReservationDeleteRes = DeleteRes @@ -152,11 +152,11 @@ export type TaxRateDeleteRes = DeleteRes export type ReservationItemDeleteRes = DeleteRes export type ReservationItemListRes = { - reservations: InventoryNext.ReservationItemDTO[] + reservations: InventoryTypes.ReservationItemDTO[] } & ListRes export type ReservationItemRes = { - reservation: InventoryNext.ReservationItemDTO + reservation: InventoryTypes.ReservationItemDTO } // Price Lists export type PriceListRes = { price_list: PriceListDTO } diff --git a/packages/core/core-flows/src/api-key/steps/create-api-keys.ts b/packages/core/core-flows/src/api-key/steps/create-api-keys.ts index ddf3aa57bd..93b2dd5b24 100644 --- a/packages/core/core-flows/src/api-key/steps/create-api-keys.ts +++ b/packages/core/core-flows/src/api-key/steps/create-api-keys.ts @@ -13,7 +13,7 @@ export const createApiKeysStep = createStep( const service = container.resolve( ModuleRegistrationName.API_KEY ) - const created = await service.create(data.api_keys) + const created = await service.createApiKeys(data.api_keys) return new StepResponse( created, created.map((apiKey) => apiKey.id) @@ -28,6 +28,6 @@ export const createApiKeysStep = createStep( ModuleRegistrationName.API_KEY ) - await service.delete(createdIds) + await service.deleteApiKeys(createdIds) } ) diff --git a/packages/core/core-flows/src/api-key/steps/delete-api-keys.ts b/packages/core/core-flows/src/api-key/steps/delete-api-keys.ts index d24f38ea89..7d438b800a 100644 --- a/packages/core/core-flows/src/api-key/steps/delete-api-keys.ts +++ b/packages/core/core-flows/src/api-key/steps/delete-api-keys.ts @@ -10,7 +10,7 @@ export const deleteApiKeysStep = createStep( ModuleRegistrationName.API_KEY ) - await service.delete(ids) + await service.deleteApiKeys(ids) return new StepResponse(void 0) }, async () => {} diff --git a/packages/core/core-flows/src/api-key/steps/update-api-keys.ts b/packages/core/core-flows/src/api-key/steps/update-api-keys.ts index 6b5f7227ba..9e505a0a0e 100644 --- a/packages/core/core-flows/src/api-key/steps/update-api-keys.ts +++ b/packages/core/core-flows/src/api-key/steps/update-api-keys.ts @@ -24,12 +24,12 @@ export const updateApiKeysStep = createStep( data.update, ]) - const prevData = await service.list(data.selector, { + const prevData = await service.listApiKeys(data.selector, { select: selects, relations, }) - const apiKeys = await service.update(data.selector, data.update) + const apiKeys = await service.updateApiKeys(data.selector, data.update) return new StepResponse(apiKeys, prevData) }, async (prevData, { container }) => { @@ -41,7 +41,7 @@ export const updateApiKeysStep = createStep( ModuleRegistrationName.API_KEY ) - await service.upsert( + await service.upsertApiKeys( prevData.map((r) => ({ id: r.id, title: r.title, diff --git a/packages/core/core-flows/src/api-key/steps/validate-sales-channel-exists.ts b/packages/core/core-flows/src/api-key/steps/validate-sales-channel-exists.ts index 2f9388cb06..4a0dbf78f2 100644 --- a/packages/core/core-flows/src/api-key/steps/validate-sales-channel-exists.ts +++ b/packages/core/core-flows/src/api-key/steps/validate-sales-channel-exists.ts @@ -16,7 +16,7 @@ export const validateSalesChannelsExistStep = createStep( ModuleRegistrationName.SALES_CHANNEL ) - const salesChannels = await salesChannelModuleService.list( + const salesChannels = await salesChannelModuleService.listSalesChannels( { id: data.sales_channel_ids }, { select: ["id"] } ) diff --git a/packages/core/core-flows/src/auth/steps/set-auth-app-metadata.ts b/packages/core/core-flows/src/auth/steps/set-auth-app-metadata.ts index 5d396434a1..97f68cea3d 100644 --- a/packages/core/core-flows/src/auth/steps/set-auth-app-metadata.ts +++ b/packages/core/core-flows/src/auth/steps/set-auth-app-metadata.ts @@ -19,7 +19,7 @@ export const setAuthAppMetadataStep = createStep( ) const key = `${data.actorType}_id` - const authIdentity = await service.retrieve(data.authIdentityId) + const authIdentity = await service.retrieveAuthIdentity(data.authIdentityId) const appMetadata = authIdentity.app_metadata || {} if (isDefined(appMetadata[key])) { @@ -28,7 +28,7 @@ export const setAuthAppMetadataStep = createStep( appMetadata[key] = data.value - await service.update({ + await service.updateAuthIdentites({ id: authIdentity.id, app_metadata: appMetadata, }) @@ -49,14 +49,14 @@ export const setAuthAppMetadataStep = createStep( ModuleRegistrationName.AUTH ) - const authIdentity = await service.retrieve(id) + const authIdentity = await service.retrieveAuthIdentity(id) const appMetadata = authIdentity.app_metadata || {} if (isDefined(appMetadata[key])) { delete appMetadata[key] } - await service.update({ + await service.updateAuthIdentites({ id: authIdentity.id, app_metadata: appMetadata, }) diff --git a/packages/core/core-flows/src/customer-group/steps/create-customer-groups.ts b/packages/core/core-flows/src/customer-group/steps/create-customer-groups.ts index 26a8af5732..6af7db371b 100644 --- a/packages/core/core-flows/src/customer-group/steps/create-customer-groups.ts +++ b/packages/core/core-flows/src/customer-group/steps/create-customer-groups.ts @@ -10,7 +10,7 @@ export const createCustomerGroupsStep = createStep( ModuleRegistrationName.CUSTOMER ) - const createdCustomerGroups = await service.createCustomerGroup(data) + const createdCustomerGroups = await service.createCustomerGroups(data) return new StepResponse( createdCustomerGroups, @@ -28,6 +28,6 @@ export const createCustomerGroupsStep = createStep( ModuleRegistrationName.CUSTOMER ) - await service.delete(createdCustomerGroupIds) + await service.deleteCustomers(createdCustomerGroupIds) } ) diff --git a/packages/core/core-flows/src/customer/steps/create-addresses.ts b/packages/core/core-flows/src/customer/steps/create-addresses.ts index a14686069d..4210f81106 100644 --- a/packages/core/core-flows/src/customer/steps/create-addresses.ts +++ b/packages/core/core-flows/src/customer/steps/create-addresses.ts @@ -13,7 +13,7 @@ export const createCustomerAddressesStep = createStep( ModuleRegistrationName.CUSTOMER ) - const addresses = await service.addAddresses(data) + const addresses = await service.createAddresses(data) return new StepResponse( addresses, diff --git a/packages/core/core-flows/src/customer/steps/create-customers.ts b/packages/core/core-flows/src/customer/steps/create-customers.ts index 3310e1e873..67de8a458d 100644 --- a/packages/core/core-flows/src/customer/steps/create-customers.ts +++ b/packages/core/core-flows/src/customer/steps/create-customers.ts @@ -10,7 +10,7 @@ export const createCustomersStep = createStep( ModuleRegistrationName.CUSTOMER ) - const createdCustomers = await service.create(data) + const createdCustomers = await service.createCustomers(data) return new StepResponse( createdCustomers, @@ -26,6 +26,6 @@ export const createCustomersStep = createStep( ModuleRegistrationName.CUSTOMER ) - await service.delete(createdCustomerIds) + await service.deleteCustomers(createdCustomerIds) } ) diff --git a/packages/core/core-flows/src/customer/steps/delete-addresses.ts b/packages/core/core-flows/src/customer/steps/delete-addresses.ts index 8f3654b978..9d8d05ccb9 100644 --- a/packages/core/core-flows/src/customer/steps/delete-addresses.ts +++ b/packages/core/core-flows/src/customer/steps/delete-addresses.ts @@ -27,6 +27,6 @@ export const deleteCustomerAddressesStep = createStep( ModuleRegistrationName.CUSTOMER ) - await service.addAddresses(prevAddresses) + await service.createAddresses(prevAddresses) } ) diff --git a/packages/core/core-flows/src/customer/steps/delete-customers.ts b/packages/core/core-flows/src/customer/steps/delete-customers.ts index d16bf306bb..98071f4757 100644 --- a/packages/core/core-flows/src/customer/steps/delete-customers.ts +++ b/packages/core/core-flows/src/customer/steps/delete-customers.ts @@ -12,7 +12,7 @@ export const deleteCustomersStep = createStep( ModuleRegistrationName.CUSTOMER ) - await service.softDelete(ids) + await service.softDeleteCustomers(ids) return new StepResponse(void 0, ids) }, @@ -25,6 +25,6 @@ export const deleteCustomersStep = createStep( ModuleRegistrationName.CUSTOMER ) - await service.restore(prevCustomerIds) + await service.restoreCustomers(prevCustomerIds) } ) diff --git a/packages/core/core-flows/src/customer/steps/update-customers.ts b/packages/core/core-flows/src/customer/steps/update-customers.ts index c0e7c90f3b..d884c7b06a 100644 --- a/packages/core/core-flows/src/customer/steps/update-customers.ts +++ b/packages/core/core-flows/src/customer/steps/update-customers.ts @@ -26,12 +26,12 @@ export const updateCustomersStep = createStep( const { selects, relations } = getSelectsAndRelationsFromObjectArray([ data.update, ]) - const prevCustomers = await service.list(data.selector, { + const prevCustomers = await service.listCustomers(data.selector, { select: selects, relations, }) - const customers = await service.update(data.selector, data.update) + const customers = await service.updateCustomers(data.selector, data.update) return new StepResponse(customers, prevCustomers) }, @@ -46,7 +46,7 @@ export const updateCustomersStep = createStep( await promiseAll( prevCustomers.map((c) => - service.update(c.id, { + service.updateCustomers(c.id, { first_name: c.first_name, last_name: c.last_name, email: c.email, diff --git a/packages/core/core-flows/src/defaults/steps/create-default-store.ts b/packages/core/core-flows/src/defaults/steps/create-default-store.ts index c18f3fdb8f..0cbde958ad 100644 --- a/packages/core/core-flows/src/defaults/steps/create-default-store.ts +++ b/packages/core/core-flows/src/defaults/steps/create-default-store.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { CreateStoreDTO, IStoreModuleService, StoreDTO } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" import { createStoresWorkflow } from "../../store" type CreateDefaultStoreStepInput = { @@ -14,7 +14,7 @@ export const createDefaultStoreStep = createStep( const storeService = container.resolve(ModuleRegistrationName.STORE) let shouldDelete = false - let [store] = await storeService.list({}, { take: 1 }) + let [store] = await storeService.listStores({}, { take: 1 }) /** * @todo @@ -55,6 +55,6 @@ export const createDefaultStoreStep = createStep( ModuleRegistrationName.STORE ) - await service.delete(data.storeId) + await service.deleteStores(data.storeId) } ) diff --git a/packages/core/core-flows/src/definition/cart/steps/confirm-inventory.ts b/packages/core/core-flows/src/definition/cart/steps/confirm-inventory.ts index ed5ed756c6..03a58713e5 100644 --- a/packages/core/core-flows/src/definition/cart/steps/confirm-inventory.ts +++ b/packages/core/core-flows/src/definition/cart/steps/confirm-inventory.ts @@ -1,5 +1,5 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import { IInventoryServiceNext } from "@medusajs/types" +import { IInventoryService } from "@medusajs/types" import { MedusaError, promiseAll } from "@medusajs/utils" import { createStep, StepResponse } from "@medusajs/workflows-sdk" @@ -17,7 +17,7 @@ export const confirmInventoryStepId = "confirm-inventory-step" export const confirmInventoryStep = createStep( confirmInventoryStepId, async (data: StepInput, { container }) => { - const inventoryService = container.resolve( + const inventoryService = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/definition/cart/steps/create-carts.ts b/packages/core/core-flows/src/definition/cart/steps/create-carts.ts index 6f06cfe913..4d3200ee97 100644 --- a/packages/core/core-flows/src/definition/cart/steps/create-carts.ts +++ b/packages/core/core-flows/src/definition/cart/steps/create-carts.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { CreateCartDTO, ICartModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" export const createCartsStepId = "create-carts" export const createCartsStep = createStep( @@ -10,7 +10,7 @@ export const createCartsStep = createStep( ModuleRegistrationName.CART ) - const createdCarts = await service.create(data) + const createdCarts = await service.createCarts(data) return new StepResponse( createdCarts, @@ -26,6 +26,6 @@ export const createCartsStep = createStep( ModuleRegistrationName.CART ) - await service.delete(createdCartsIds) + await service.deleteCarts(createdCartsIds) } ) diff --git a/packages/core/core-flows/src/definition/cart/steps/find-one-or-any-region.ts b/packages/core/core-flows/src/definition/cart/steps/find-one-or-any-region.ts index ee428dd2e6..7775aed35f 100644 --- a/packages/core/core-flows/src/definition/cart/steps/find-one-or-any-region.ts +++ b/packages/core/core-flows/src/definition/cart/steps/find-one-or-any-region.ts @@ -17,20 +17,20 @@ export const findOneOrAnyRegionStep = createStep( if (data.regionId) { try { - const region = await service.retrieve(data.regionId) + const region = await service.retrieveRegion(data.regionId) return new StepResponse(region) } catch (error) { return new StepResponse(null) } } - const [store] = await storeModule.list() + const [store] = await storeModule.listStores() if (!store) { throw new MedusaError(MedusaError.Types.NOT_FOUND, "Store not found") } - const [region] = await service.list({ + const [region] = await service.listRegions({ id: store.default_region_id, }) diff --git a/packages/core/core-flows/src/definition/cart/steps/find-or-create-customer.ts b/packages/core/core-flows/src/definition/cart/steps/find-or-create-customer.ts index 40db236869..882655b53a 100644 --- a/packages/core/core-flows/src/definition/cart/steps/find-or-create-customer.ts +++ b/packages/core/core-flows/src/definition/cart/steps/find-or-create-customer.ts @@ -46,7 +46,7 @@ export const findOrCreateCustomerStep = createStep( let customerWasCreated = false if (data.customerId) { - const customer = await service.retrieve(data.customerId) + const customer = await service.retrieveCustomer(data.customerId) customerData.customer = customer customerData.email = customer.email @@ -58,13 +58,13 @@ export const findOrCreateCustomerStep = createStep( if (data.email) { const validatedEmail = validateEmail(data.email) - let [customer] = await service.list({ + let [customer] = await service.listCustomers({ email: validatedEmail, has_account: false, }) if (!customer) { - customer = await service.create({ email: validatedEmail }) + customer = await service.createCustomers({ email: validatedEmail }) customerWasCreated = true } @@ -88,6 +88,6 @@ export const findOrCreateCustomerStep = createStep( ModuleRegistrationName.CUSTOMER ) - await service.delete(customer.id) + await service.deleteCustomers(customer.id) } ) diff --git a/packages/core/core-flows/src/definition/cart/steps/find-sales-channel.ts b/packages/core/core-flows/src/definition/cart/steps/find-sales-channel.ts index 77ce007cc4..b3a4a830a7 100644 --- a/packages/core/core-flows/src/definition/cart/steps/find-sales-channel.ts +++ b/packages/core/core-flows/src/definition/cart/steps/find-sales-channel.ts @@ -25,15 +25,17 @@ export const findSalesChannelStep = createStep( let salesChannel: SalesChannelDTO | undefined if (data.salesChannelId) { - salesChannel = await salesChannelService.retrieve(data.salesChannelId) + salesChannel = await salesChannelService.retrieveSalesChannel( + data.salesChannelId + ) } else if (!isDefined(data.salesChannelId)) { - const [store] = await storeModule.list( + const [store] = await storeModule.listStores( {}, { select: ["default_sales_channel_id"] } ) if (store?.default_sales_channel_id) { - salesChannel = await salesChannelService.retrieve( + salesChannel = await salesChannelService.retrieveSalesChannel( store.default_sales_channel_id ) } diff --git a/packages/core/core-flows/src/definition/cart/steps/get-promotion-codes-to-apply.ts b/packages/core/core-flows/src/definition/cart/steps/get-promotion-codes-to-apply.ts index 8c28a086cf..350808e4c2 100644 --- a/packages/core/core-flows/src/definition/cart/steps/get-promotion-codes-to-apply.ts +++ b/packages/core/core-flows/src/definition/cart/steps/get-promotion-codes-to-apply.ts @@ -38,7 +38,7 @@ export const getPromotionCodesToApply = createStep( const promotionCodesToApply: Set = new Set( ( - await promotionService.list( + await promotionService.listPromotions( { code: adjustmentCodes }, { select: ["code"], take: null } ) diff --git a/packages/core/core-flows/src/definition/cart/steps/get-variants.ts b/packages/core/core-flows/src/definition/cart/steps/get-variants.ts index 7da18741c4..63571b5761 100644 --- a/packages/core/core-flows/src/definition/cart/steps/get-variants.ts +++ b/packages/core/core-flows/src/definition/cart/steps/get-variants.ts @@ -20,7 +20,7 @@ export const getVariantsStep = createStep( ModuleRegistrationName.PRODUCT ) - const variants = await productModuleService.listVariants( + const variants = await productModuleService.listProductVariants( data.filter, data.config ) diff --git a/packages/core/core-flows/src/definition/cart/steps/prepare-adjustments-from-promotion-actions.ts b/packages/core/core-flows/src/definition/cart/steps/prepare-adjustments-from-promotion-actions.ts index 6511ba1dd9..5536d68ddb 100644 --- a/packages/core/core-flows/src/definition/cart/steps/prepare-adjustments-from-promotion-actions.ts +++ b/packages/core/core-flows/src/definition/cart/steps/prepare-adjustments-from-promotion-actions.ts @@ -25,7 +25,7 @@ export const prepareAdjustmentsFromPromotionActionsStep = createStep( ) const { actions = [] } = data - const promotions = await promotionModuleService.list( + const promotions = await promotionModuleService.listPromotions( { code: actions.map((a) => a.code) }, { select: ["id", "code"] } ) diff --git a/packages/core/core-flows/src/definition/cart/steps/reserve-inventory.ts b/packages/core/core-flows/src/definition/cart/steps/reserve-inventory.ts index 32f0216e2e..91f797d463 100644 --- a/packages/core/core-flows/src/definition/cart/steps/reserve-inventory.ts +++ b/packages/core/core-flows/src/definition/cart/steps/reserve-inventory.ts @@ -1,5 +1,5 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import { IInventoryServiceNext } from "@medusajs/types" +import { IInventoryService } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" interface StepInput { @@ -17,7 +17,7 @@ export const reserveInventoryStepId = "reserve-inventory-step" export const reserveInventoryStep = createStep( reserveInventoryStepId, async (data: StepInput, { container }) => { - const inventoryService = container.resolve( + const inventoryService = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -40,7 +40,7 @@ export const reserveInventoryStep = createStep( return } - const inventoryService = container.resolve( + const inventoryService = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/definition/cart/steps/retrieve-cart.ts b/packages/core/core-flows/src/definition/cart/steps/retrieve-cart.ts index d266f07a13..e7de7477ba 100644 --- a/packages/core/core-flows/src/definition/cart/steps/retrieve-cart.ts +++ b/packages/core/core-flows/src/definition/cart/steps/retrieve-cart.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { CartDTO, FindConfig, ICartModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" interface StepInput { id: string @@ -15,7 +15,7 @@ export const retrieveCartStep = createStep( ModuleRegistrationName.CART ) - const cart = await cartModuleService.retrieve(data.id, data.config) + const cart = await cartModuleService.retrieveCart(data.id, data.config) // TODO: remove this when cart handles totals calculation cart.items = cart.items?.map((item) => { diff --git a/packages/core/core-flows/src/definition/cart/steps/update-cart-promotions.ts b/packages/core/core-flows/src/definition/cart/steps/update-cart-promotions.ts index a5d94854ab..9e21e5b407 100644 --- a/packages/core/core-flows/src/definition/cart/steps/update-cart-promotions.ts +++ b/packages/core/core-flows/src/definition/cart/steps/update-cart-promotions.ts @@ -38,7 +38,7 @@ export const updateCartPromotionsStep = createStep( existingCartPromotionLinks.map((link) => [link.promotion_id, link]) ) - const promotions = await promotionService.list( + const promotions = await promotionService.listPromotions( { code: promo_codes }, { select: ["id"] } ) diff --git a/packages/core/core-flows/src/definition/cart/steps/update-carts.ts b/packages/core/core-flows/src/definition/cart/steps/update-carts.ts index 7b9438bce6..37c55dfdd7 100644 --- a/packages/core/core-flows/src/definition/cart/steps/update-carts.ts +++ b/packages/core/core-flows/src/definition/cart/steps/update-carts.ts @@ -5,7 +5,7 @@ import { UpdateCartWorkflowInputDTO, } from "@medusajs/types" import { getSelectsAndRelationsFromObjectArray } from "@medusajs/utils" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" export const updateCartsStepId = "update-carts" export const updateCartsStep = createStep( @@ -16,12 +16,12 @@ export const updateCartsStep = createStep( ) const { selects, relations } = getSelectsAndRelationsFromObjectArray(data) - const cartsBeforeUpdate = await cartModule.list( + const cartsBeforeUpdate = await cartModule.listCarts( { id: data.map((d) => d.id) }, { select: selects, relations } ) - const updatedCart = await cartModule.update(data) + const updatedCart = await cartModule.updateCarts(data) return new StepResponse(updatedCart, cartsBeforeUpdate) }, @@ -48,6 +48,6 @@ export const updateCartsStep = createStep( }) } - return await cartModule.update(dataToUpdate) + return await cartModule.updateCarts(dataToUpdate) } ) diff --git a/packages/core/core-flows/src/file/steps/delete-files.ts b/packages/core/core-flows/src/file/steps/delete-files.ts index 682370e462..f4af33e893 100644 --- a/packages/core/core-flows/src/file/steps/delete-files.ts +++ b/packages/core/core-flows/src/file/steps/delete-files.ts @@ -10,7 +10,7 @@ export const deleteFilesStep = createStep( ModuleRegistrationName.FILE ) - await service.delete(ids) + await service.deleteFiles(ids) return new StepResponse(void 0) }, async () => {} diff --git a/packages/core/core-flows/src/file/steps/upload-files.ts b/packages/core/core-flows/src/file/steps/upload-files.ts index 671c5e9074..d722154828 100644 --- a/packages/core/core-flows/src/file/steps/upload-files.ts +++ b/packages/core/core-flows/src/file/steps/upload-files.ts @@ -17,7 +17,7 @@ export const uploadFilesStep = createStep( const service = container.resolve( ModuleRegistrationName.FILE ) - const created = await service.create(data.files) + const created = await service.createFiles(data.files) return new StepResponse( created, created.map((file) => file.id) @@ -32,6 +32,6 @@ export const uploadFilesStep = createStep( ModuleRegistrationName.FILE ) - await service.delete(createdIds) + await service.deleteFiles(createdIds) } ) diff --git a/packages/core/core-flows/src/fulfillment/steps/add-shipping-options-prices.ts b/packages/core/core-flows/src/fulfillment/steps/add-shipping-options-prices.ts index 0bb3ba95bb..f2f7f6034c 100644 --- a/packages/core/core-flows/src/fulfillment/steps/add-shipping-options-prices.ts +++ b/packages/core/core-flows/src/fulfillment/steps/add-shipping-options-prices.ts @@ -74,7 +74,7 @@ export const createShippingOptionsPriceSetsStep = createStep( const regionService = container.resolve( ModuleRegistrationName.REGION ) - const regions = await regionService.list( + const regions = await regionService.listRegions( { id: [...new Set(regionIds)], }, @@ -96,7 +96,7 @@ export const createShippingOptionsPriceSetsStep = createStep( ModuleRegistrationName.PRICING ) - const priceSets = await pricingService.create(priceSetsData) + const priceSets = await pricingService.createPriceSets(priceSetsData) const shippingOptionPriceSetLinData = data.map((input, index) => { return { @@ -119,6 +119,6 @@ export const createShippingOptionsPriceSetsStep = createStep( ModuleRegistrationName.PRICING ) - await pricingService.delete(priceSetIds) + await pricingService.deletePriceSets(priceSetIds) } ) diff --git a/packages/core/core-flows/src/fulfillment/steps/create-fulfillment-set.ts b/packages/core/core-flows/src/fulfillment/steps/create-fulfillment-set.ts index 0bd01fc063..a25bb72a96 100644 --- a/packages/core/core-flows/src/fulfillment/steps/create-fulfillment-set.ts +++ b/packages/core/core-flows/src/fulfillment/steps/create-fulfillment-set.ts @@ -3,7 +3,7 @@ import { CreateFulfillmentSetDTO, IFulfillmentModuleService, } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" export const createFulfillmentSetsId = "create-fulfillment-sets" export const createFulfillmentSets = createStep( @@ -13,7 +13,7 @@ export const createFulfillmentSets = createStep( ModuleRegistrationName.FULFILLMENT ) - const createSets = await service.create(data) + const createSets = await service.createFulfillmentSets(data) return new StepResponse( createSets, @@ -29,6 +29,6 @@ export const createFulfillmentSets = createStep( ModuleRegistrationName.FULFILLMENT ) - await service.delete(createSetIds) + await service.deleteFulfillmentSets(createSetIds) } ) diff --git a/packages/core/core-flows/src/fulfillment/steps/delete-fulfillment-sets.ts b/packages/core/core-flows/src/fulfillment/steps/delete-fulfillment-sets.ts index 32e35731e8..656f82547e 100644 --- a/packages/core/core-flows/src/fulfillment/steps/delete-fulfillment-sets.ts +++ b/packages/core/core-flows/src/fulfillment/steps/delete-fulfillment-sets.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { IFulfillmentModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" export const deleteFulfillmentSetsStepId = "delete-fulfillment-sets" export const deleteFulfillmentSetsStep = createStep( @@ -10,7 +10,7 @@ export const deleteFulfillmentSetsStep = createStep( ModuleRegistrationName.FULFILLMENT ) - await service.softDelete(ids) + await service.softDeleteFulfillmentSets(ids) return new StepResponse(void 0, ids) }, @@ -23,6 +23,6 @@ export const deleteFulfillmentSetsStep = createStep( ModuleRegistrationName.FULFILLMENT ) - await service.restore(prevIds) + await service.restoreFulfillmentSets(prevIds) } ) diff --git a/packages/core/core-flows/src/fulfillment/steps/set-shipping-options-prices.ts b/packages/core/core-flows/src/fulfillment/steps/set-shipping-options-prices.ts index 8374c5993f..2d310ccd94 100644 --- a/packages/core/core-flows/src/fulfillment/steps/set-shipping-options-prices.ts +++ b/packages/core/core-flows/src/fulfillment/steps/set-shipping-options-prices.ts @@ -108,7 +108,7 @@ export const setShippingOptionsPricesStep = createStep( const regionService = container.resolve( ModuleRegistrationName.REGION ) - const regions = await regionService.list( + const regions = await regionService.listRegions( { id: [...new Set(regionIds)], }, @@ -166,7 +166,7 @@ export const setShippingOptionsPricesStep = createStep( continue } - await pricingService.update(shippingOptionData.price_set_id, { + await pricingService.updatePriceSets(shippingOptionData.price_set_id, { prices: shippingOptionData.prices, }) } @@ -187,7 +187,7 @@ export const setShippingOptionsPricesStep = createStep( if (!isDefined(prices)) { continue } - await pricingService.update(data_.price_set_id, { prices }) + await pricingService.updatePriceSets(data_.price_set_id, { prices }) } } ) diff --git a/packages/core/core-flows/src/inventory/steps/adjust-inventory-levels.ts b/packages/core/core-flows/src/inventory/steps/adjust-inventory-levels.ts index c4f02f16f0..56db099975 100644 --- a/packages/core/core-flows/src/inventory/steps/adjust-inventory-levels.ts +++ b/packages/core/core-flows/src/inventory/steps/adjust-inventory-levels.ts @@ -1,4 +1,4 @@ -import { IInventoryServiceNext, InventoryNext } from "@medusajs/types" +import { IInventoryService, InventoryTypes } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk" @@ -7,14 +7,14 @@ export const adjustInventoryLevelsStepId = "adjust-inventory-levels-step" export const adjustInventoryLevelsStep = createStep( adjustInventoryLevelsStepId, async ( - input: InventoryNext.BulkAdjustInventoryLevelInput[], + input: InventoryTypes.BulkAdjustInventoryLevelInput[], { container } ) => { - const inventoryService: IInventoryServiceNext = container.resolve( + const inventoryService: IInventoryService = container.resolve( ModuleRegistrationName.INVENTORY ) - const adjustedLevels: InventoryNext.InventoryLevelDTO[] = + const adjustedLevels: InventoryTypes.InventoryLevelDTO[] = await inventoryService.adjustInventory( input.map((item) => { return { diff --git a/packages/core/core-flows/src/inventory/steps/create-inventory-items.ts b/packages/core/core-flows/src/inventory/steps/create-inventory-items.ts index ec0203c523..fa733314be 100644 --- a/packages/core/core-flows/src/inventory/steps/create-inventory-items.ts +++ b/packages/core/core-flows/src/inventory/steps/create-inventory-items.ts @@ -1,18 +1,18 @@ import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import { IInventoryServiceNext, InventoryNext } from "@medusajs/types" +import { IInventoryService, InventoryTypes } from "@medusajs/types" export const createInventoryItemsStepId = "create-inventory-items" export const createInventoryItemsStep = createStep( createInventoryItemsStepId, - async (data: InventoryNext.CreateInventoryItemInput[], { container }) => { - const inventoryService: IInventoryServiceNext = container.resolve( + async (data: InventoryTypes.CreateInventoryItemInput[], { container }) => { + const inventoryService: IInventoryService = container.resolve( ModuleRegistrationName.INVENTORY ) - const createdItems: InventoryNext.InventoryItemDTO[] = - await inventoryService.create(data) + const createdItems: InventoryTypes.InventoryItemDTO[] = + await inventoryService.createInventoryItems(data) return new StepResponse( createdItems, @@ -26,6 +26,6 @@ export const createInventoryItemsStep = createStep( const inventoryService = container.resolve(ModuleRegistrationName.INVENTORY) - await inventoryService!.delete(data) + await inventoryService.deleteInventoryItems(data) } ) diff --git a/packages/core/core-flows/src/inventory/steps/create-inventory-levels.ts b/packages/core/core-flows/src/inventory/steps/create-inventory-levels.ts index 7bfa4f5b43..79f5625822 100644 --- a/packages/core/core-flows/src/inventory/steps/create-inventory-levels.ts +++ b/packages/core/core-flows/src/inventory/steps/create-inventory-levels.ts @@ -1,4 +1,4 @@ -import { IInventoryServiceNext, InventoryNext } from "@medusajs/types" +import { IInventoryService, InventoryTypes } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk" @@ -6,8 +6,8 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" export const createInventoryLevelsStepId = "create-inventory-levels" export const createInventoryLevelsStep = createStep( createInventoryLevelsStepId, - async (data: InventoryNext.CreateInventoryLevelInput[], { container }) => { - const service = container.resolve( + async (data: InventoryTypes.CreateInventoryLevelInput[], { container }) => { + const service = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -22,7 +22,7 @@ export const createInventoryLevelsStep = createStep( return } - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/inventory/steps/delete-inventory-items.ts b/packages/core/core-flows/src/inventory/steps/delete-inventory-items.ts index fff3b689db..8ab0d52121 100644 --- a/packages/core/core-flows/src/inventory/steps/delete-inventory-items.ts +++ b/packages/core/core-flows/src/inventory/steps/delete-inventory-items.ts @@ -8,7 +8,7 @@ export const deleteInventoryItemStep = createStep( async (ids: string[], { container }) => { const inventoryService = container.resolve(ModuleRegistrationName.INVENTORY) - await inventoryService.softDelete(ids) + await inventoryService.softDeleteInventoryItems(ids) return new StepResponse(void 0, ids) }, @@ -19,6 +19,6 @@ export const deleteInventoryItemStep = createStep( const inventoryService = container.resolve(ModuleRegistrationName.INVENTORY) - await inventoryService.restore(prevInventoryItemIds) + await inventoryService.restoreInventoryItems(prevInventoryItemIds) } ) diff --git a/packages/core/core-flows/src/inventory/steps/delete-inventory-levels.ts b/packages/core/core-flows/src/inventory/steps/delete-inventory-levels.ts index e0f0d7752f..ce79f514fd 100644 --- a/packages/core/core-flows/src/inventory/steps/delete-inventory-levels.ts +++ b/packages/core/core-flows/src/inventory/steps/delete-inventory-levels.ts @@ -1,4 +1,4 @@ -import { ICustomerModuleService, IInventoryServiceNext } from "@medusajs/types" +import { ICustomerModuleService, IInventoryService } from "@medusajs/types" import { StepResponse, WorkflowData, createStep } from "@medusajs/workflows-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk" @@ -7,7 +7,7 @@ export const deleteInventoryLevelsStepId = "delete-inventory-levels-step" export const deleteInventoryLevelsStep = createStep( deleteInventoryLevelsStepId, async (ids: string[], { container }) => { - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -20,7 +20,7 @@ export const deleteInventoryLevelsStep = createStep( return } - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/inventory/steps/delete-levels-by-item-and-location.ts b/packages/core/core-flows/src/inventory/steps/delete-levels-by-item-and-location.ts index 52ec38c270..685d863f40 100644 --- a/packages/core/core-flows/src/inventory/steps/delete-levels-by-item-and-location.ts +++ b/packages/core/core-flows/src/inventory/steps/delete-levels-by-item-and-location.ts @@ -5,7 +5,7 @@ import { } from "@medusajs/modules-sdk" import { StepResponse, createStep } from "@medusajs/workflows-sdk" -import { IInventoryServiceNext } from "@medusajs/types" +import { IInventoryService } from "@medusajs/types" import { MedusaError } from "@medusajs/utils" export const deleteInventoryLevelsFromItemAndLocationsStepId = @@ -20,7 +20,7 @@ export const deleteInventoryLevelsFromItemAndLocationsStep = createStep( return new StepResponse(void 0, []) } - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -48,7 +48,7 @@ export const deleteInventoryLevelsFromItemAndLocationsStep = createStep( return } - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/inventory/steps/update-inventory-items.ts b/packages/core/core-flows/src/inventory/steps/update-inventory-items.ts index b201bf1fdc..580407393f 100644 --- a/packages/core/core-flows/src/inventory/steps/update-inventory-items.ts +++ b/packages/core/core-flows/src/inventory/steps/update-inventory-items.ts @@ -1,4 +1,4 @@ -import { IInventoryServiceNext, InventoryNext } from "@medusajs/types" +import { IInventoryService, InventoryTypes } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { convertItemResponseToUpdateRequest, @@ -10,18 +10,20 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" export const updateInventoryItemsStepId = "update-inventory-items-step" export const updateInventoryItemsStep = createStep( updateInventoryItemsStepId, - async (input: InventoryNext.UpdateInventoryItemInput[], { container }) => { - const inventoryService = container.resolve( + async (input: InventoryTypes.UpdateInventoryItemInput[], { container }) => { + const inventoryService = container.resolve( ModuleRegistrationName.INVENTORY ) const { selects, relations } = getSelectsAndRelationsFromObjectArray(input) - const dataBeforeUpdate = await inventoryService.list( + const dataBeforeUpdate = await inventoryService.listInventoryItems( { id: input.map(({ id }) => id) }, {} ) - const updatedInventoryItems = await inventoryService.update(input) + const updatedInventoryItems = await inventoryService.updateInventoryItems( + input + ) return new StepResponse(updatedInventoryItems, { dataBeforeUpdate, @@ -36,11 +38,11 @@ export const updateInventoryItemsStep = createStep( const { dataBeforeUpdate, selects, relations } = revertInput - const inventoryService = container.resolve( + const inventoryService = container.resolve( ModuleRegistrationName.INVENTORY ) - await inventoryService.update( + await inventoryService.updateInventoryItems( dataBeforeUpdate.map((data) => convertItemResponseToUpdateRequest(data, selects, relations) ) diff --git a/packages/core/core-flows/src/inventory/steps/update-inventory-levels.ts b/packages/core/core-flows/src/inventory/steps/update-inventory-levels.ts index f5e61236e1..8fc65ce411 100644 --- a/packages/core/core-flows/src/inventory/steps/update-inventory-levels.ts +++ b/packages/core/core-flows/src/inventory/steps/update-inventory-levels.ts @@ -1,4 +1,4 @@ -import { IInventoryServiceNext, InventoryNext } from "@medusajs/types" +import { IInventoryService, InventoryTypes } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { convertItemResponseToUpdateRequest, @@ -11,10 +11,10 @@ export const updateInventoryLevelsStepId = "update-inventory-levels-step" export const updateInventoryLevelsStep = createStep( updateInventoryLevelsStepId, async ( - input: InventoryNext.BulkUpdateInventoryLevelInput[], + input: InventoryTypes.BulkUpdateInventoryLevelInput[], { container } ) => { - const inventoryService: IInventoryServiceNext = container.resolve( + const inventoryService: IInventoryService = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -30,7 +30,7 @@ export const updateInventoryLevelsStep = createStep( {} ) - const updatedLevels: InventoryNext.InventoryLevelDTO[] = + const updatedLevels: InventoryTypes.InventoryLevelDTO[] = await inventoryService.updateInventoryLevels(input) return new StepResponse(updatedLevels, { @@ -51,7 +51,7 @@ export const updateInventoryLevelsStep = createStep( await inventoryService.updateInventoryLevels( dataBeforeUpdate.map((data) => convertItemResponseToUpdateRequest(data, selects, relations) - ) as InventoryNext.BulkUpdateInventoryLevelInput[] + ) as InventoryTypes.BulkUpdateInventoryLevelInput[] ) } ) diff --git a/packages/core/core-flows/src/inventory/steps/validate-inventory-locations.ts b/packages/core/core-flows/src/inventory/steps/validate-inventory-locations.ts index ee30ccdfea..2a920cabd2 100644 --- a/packages/core/core-flows/src/inventory/steps/validate-inventory-locations.ts +++ b/packages/core/core-flows/src/inventory/steps/validate-inventory-locations.ts @@ -5,13 +5,13 @@ import { remoteQueryObjectFromString, } from "@medusajs/utils" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { createStep } from "@medusajs/workflows-sdk" export const validateInventoryLocationsStepId = "validate-inventory-levels-step" export const validateInventoryLocationsStep = createStep( validateInventoryLocationsStepId, - async (data: InventoryNext.CreateInventoryLevelInput[], { container }) => { + async (data: InventoryTypes.CreateInventoryLevelInput[], { container }) => { const remoteQuery = container.resolve( ContainerRegistrationKeys.REMOTE_QUERY ) diff --git a/packages/core/core-flows/src/inventory/workflows/bulk-create-delete-levels.ts b/packages/core/core-flows/src/inventory/workflows/bulk-create-delete-levels.ts index 8c9b25817d..8a7f0fb2ee 100644 --- a/packages/core/core-flows/src/inventory/workflows/bulk-create-delete-levels.ts +++ b/packages/core/core-flows/src/inventory/workflows/bulk-create-delete-levels.ts @@ -1,4 +1,4 @@ -import { InventoryLevelDTO, InventoryNext } from "@medusajs/types" +import { InventoryLevelDTO, InventoryTypes } from "@medusajs/types" import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk" import { createInventoryLevelsStep, @@ -6,7 +6,7 @@ import { } from "../steps" interface WorkflowInput { - creates: InventoryNext.CreateInventoryLevelInput[] + creates: InventoryTypes.CreateInventoryLevelInput[] deletes: { inventory_item_id: string; location_id: string }[] } diff --git a/packages/core/core-flows/src/inventory/workflows/create-inventory-items.ts b/packages/core/core-flows/src/inventory/workflows/create-inventory-items.ts index b889083946..3bd4f1b641 100644 --- a/packages/core/core-flows/src/inventory/workflows/create-inventory-items.ts +++ b/packages/core/core-flows/src/inventory/workflows/create-inventory-items.ts @@ -5,22 +5,22 @@ import { } from "@medusajs/workflows-sdk" import { createInventoryItemsStep } from "../steps" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { createInventoryLevelsWorkflow } from "./create-inventory-levels" type LocationLevelWithoutInventory = Omit< - InventoryNext.CreateInventoryLevelInput, + InventoryTypes.CreateInventoryLevelInput, "inventory_item_id" > interface WorkflowInput { - items: (InventoryNext.CreateInventoryItemInput & { + items: (InventoryTypes.CreateInventoryItemInput & { location_levels?: LocationLevelWithoutInventory[] })[] } const buildLocationLevelMapAndItemData = (data: WorkflowInput) => { data.items = data.items ?? [] - const inventoryItems: InventoryNext.CreateInventoryItemInput[] = [] + const inventoryItems: InventoryTypes.CreateInventoryItemInput[] = [] // Keep an index to location levels mapping to inject the created inventory item // id into the location levels workflow input const locationLevelMap: Record = {} @@ -39,9 +39,9 @@ const buildLocationLevelMapAndItemData = (data: WorkflowInput) => { const buildInventoryLevelsInput = (data: { locationLevelMap: Record - items: InventoryNext.InventoryItemDTO[] + items: InventoryTypes.InventoryItemDTO[] }) => { - const inventoryLevels: InventoryNext.CreateInventoryLevelInput[] = [] + const inventoryLevels: InventoryTypes.CreateInventoryLevelInput[] = [] let index = 0 // The order of the input is critical to accurately create location levels for diff --git a/packages/core/core-flows/src/inventory/workflows/create-inventory-levels.ts b/packages/core/core-flows/src/inventory/workflows/create-inventory-levels.ts index 7ec709edca..724db0151e 100644 --- a/packages/core/core-flows/src/inventory/workflows/create-inventory-levels.ts +++ b/packages/core/core-flows/src/inventory/workflows/create-inventory-levels.ts @@ -1,4 +1,4 @@ -import { InventoryLevelDTO, InventoryNext } from "@medusajs/types" +import { InventoryLevelDTO, InventoryTypes } from "@medusajs/types" import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk" import { createInventoryLevelsStep, @@ -6,7 +6,7 @@ import { } from "../steps" interface WorkflowInput { - inventory_levels: InventoryNext.CreateInventoryLevelInput[] + inventory_levels: InventoryTypes.CreateInventoryLevelInput[] } export const createInventoryLevelsWorkflowId = "create-inventory-levels-workflow" diff --git a/packages/core/core-flows/src/inventory/workflows/update-inventory-items.ts b/packages/core/core-flows/src/inventory/workflows/update-inventory-items.ts index c976d1897a..cbe235c42b 100644 --- a/packages/core/core-flows/src/inventory/workflows/update-inventory-items.ts +++ b/packages/core/core-flows/src/inventory/workflows/update-inventory-items.ts @@ -1,17 +1,17 @@ import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk" -import { InventoryNext } from "@medusajs/types" +import { InventoryTypes } from "@medusajs/types" import { updateInventoryItemsStep } from "../steps" interface WorkflowInput { - updates: InventoryNext.UpdateInventoryItemInput[] + updates: InventoryTypes.UpdateInventoryItemInput[] } export const updateInventoryItemsWorkflowId = "update-inventory-items-workflow" export const updateInventoryItemsWorkflow = createWorkflow( updateInventoryItemsWorkflowId, ( input: WorkflowData - ): WorkflowData => { + ): WorkflowData => { return updateInventoryItemsStep(input.updates) } ) diff --git a/packages/core/core-flows/src/inventory/workflows/update-inventory-levels.ts b/packages/core/core-flows/src/inventory/workflows/update-inventory-levels.ts index d4c7580b6e..6f2799d03c 100644 --- a/packages/core/core-flows/src/inventory/workflows/update-inventory-levels.ts +++ b/packages/core/core-flows/src/inventory/workflows/update-inventory-levels.ts @@ -1,10 +1,10 @@ -import { InventoryLevelDTO, InventoryNext } from "@medusajs/types" +import { InventoryLevelDTO, InventoryTypes } from "@medusajs/types" import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk" import { updateInventoryLevelsStep } from "../steps/update-inventory-levels" interface WorkflowInput { - updates: InventoryNext.BulkUpdateInventoryLevelInput[] + updates: InventoryTypes.BulkUpdateInventoryLevelInput[] } export const updateInventoryLevelsWorkflowId = "update-inventory-levels-workflow" diff --git a/packages/core/core-flows/src/order/steps/archive-orders.ts b/packages/core/core-flows/src/order/steps/archive-orders.ts index 42d2f7aba0..10355e0fd6 100644 --- a/packages/core/core-flows/src/order/steps/archive-orders.ts +++ b/packages/core/core-flows/src/order/steps/archive-orders.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { IOrderModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" type ArchiveOrdersStepInput = { orderIds: string[] @@ -34,6 +34,6 @@ export const archiveOrdersStep = createStep( ModuleRegistrationName.ORDER ) - await service.update(archived) + await service.updateOrders(archived) } ) diff --git a/packages/core/core-flows/src/order/steps/cancel-orders.ts b/packages/core/core-flows/src/order/steps/cancel-orders.ts index 703cbb45d6..0bbc6c3c07 100644 --- a/packages/core/core-flows/src/order/steps/cancel-orders.ts +++ b/packages/core/core-flows/src/order/steps/cancel-orders.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { IOrderModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" type CompleteOrdersStepInput = { orderIds: string[] @@ -14,7 +14,7 @@ export const cancelOrdersStep = createStep( ModuleRegistrationName.ORDER ) - const orders = await service.list( + const orders = await service.listOrders( { id: data.orderIds, }, @@ -45,6 +45,6 @@ export const cancelOrdersStep = createStep( ModuleRegistrationName.ORDER ) - await service.update(canceled) + await service.updateOrders(canceled) } ) diff --git a/packages/core/core-flows/src/order/steps/complete-orders.ts b/packages/core/core-flows/src/order/steps/complete-orders.ts index 25431880a5..b1ce009ca8 100644 --- a/packages/core/core-flows/src/order/steps/complete-orders.ts +++ b/packages/core/core-flows/src/order/steps/complete-orders.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { IOrderModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" type CompleteOrdersStepInput = { orderIds: string[] @@ -14,7 +14,7 @@ export const completeOrdersStep = createStep( ModuleRegistrationName.ORDER ) - const orders = await service.list( + const orders = await service.listOrders( { id: data.orderIds, }, @@ -44,6 +44,6 @@ export const completeOrdersStep = createStep( ModuleRegistrationName.ORDER ) - await service.update(completed) + await service.updateOrders(completed) } ) diff --git a/packages/core/core-flows/src/order/steps/create-orders.ts b/packages/core/core-flows/src/order/steps/create-orders.ts index 40f1ff7f6c..b8eede7b8f 100644 --- a/packages/core/core-flows/src/order/steps/create-orders.ts +++ b/packages/core/core-flows/src/order/steps/create-orders.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { CreateOrderDTO, IOrderModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" type CreateOrdersStepInput = CreateOrderDTO[] @@ -12,7 +12,7 @@ export const createOrdersStep = createStep( ModuleRegistrationName.ORDER ) - const created = await service.create(data) + const created = await service.createOrders(data) return new StepResponse( created, created.map((store) => store.id) @@ -27,6 +27,6 @@ export const createOrdersStep = createStep( ModuleRegistrationName.ORDER ) - await service.delete(createdIds) + await service.deleteOrders(createdIds) } ) diff --git a/packages/core/core-flows/src/pricing/steps/create-price-sets.ts b/packages/core/core-flows/src/pricing/steps/create-price-sets.ts index dc8ddf1c9e..fdbe85880d 100644 --- a/packages/core/core-flows/src/pricing/steps/create-price-sets.ts +++ b/packages/core/core-flows/src/pricing/steps/create-price-sets.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { CreatePriceSetDTO, IPricingModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" export const createPriceSetsStepId = "create-price-sets" export const createPriceSetsStep = createStep( @@ -10,7 +10,7 @@ export const createPriceSetsStep = createStep( ModuleRegistrationName.PRICING ) - const priceSets = await pricingModule.create(data) + const priceSets = await pricingModule.createPriceSets(data) return new StepResponse( priceSets, @@ -26,6 +26,6 @@ export const createPriceSetsStep = createStep( ModuleRegistrationName.PRICING ) - await pricingModule.delete(priceSets) + await pricingModule.deletePriceSets(priceSets) } ) diff --git a/packages/core/core-flows/src/pricing/steps/create-pricing-rule-types.ts b/packages/core/core-flows/src/pricing/steps/create-pricing-rule-types.ts index c14f7cbf2f..d31969363c 100644 --- a/packages/core/core-flows/src/pricing/steps/create-pricing-rule-types.ts +++ b/packages/core/core-flows/src/pricing/steps/create-pricing-rule-types.ts @@ -42,6 +42,6 @@ export const createPricingRuleTypesStep = createStep( ModuleRegistrationName.PRICING ) - await pricingModule.delete(ruleTypeIds) + await pricingModule.deleteRuleTypes(ruleTypeIds) } ) diff --git a/packages/core/core-flows/src/pricing/steps/update-price-sets.ts b/packages/core/core-flows/src/pricing/steps/update-price-sets.ts index 3520f4643b..9344ac00af 100644 --- a/packages/core/core-flows/src/pricing/steps/update-price-sets.ts +++ b/packages/core/core-flows/src/pricing/steps/update-price-sets.ts @@ -1,10 +1,10 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { IPricingModuleService, PricingTypes } from "@medusajs/types" import { - MedusaError, getSelectsAndRelationsFromObjectArray, + MedusaError, } from "@medusajs/utils" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" type UpdatePriceSetsStepInput = | { @@ -31,11 +31,11 @@ export const updatePriceSetsStep = createStep( ) } - const prevData = await pricingModule.list({ + const prevData = await pricingModule.listPriceSets({ id: data.price_sets.map((p) => p.id) as string[], }) - const priceSets = await pricingModule.upsert(data.price_sets) + const priceSets = await pricingModule.upsertPriceSets(data.price_sets) return new StepResponse(priceSets, prevData) } @@ -47,12 +47,12 @@ export const updatePriceSetsStep = createStep( data.update, ]) - const dataBeforeUpdate = await pricingModule.list(data.selector, { + const dataBeforeUpdate = await pricingModule.listPriceSets(data.selector, { select: selects, relations, }) - const updatedPriceSets = await pricingModule.update( + const updatedPriceSets = await pricingModule.updatePriceSets( data.selector, data.update ) @@ -68,6 +68,8 @@ export const updatePriceSetsStep = createStep( return } - await pricingModule.upsert(revertInput as PricingTypes.UpsertPriceSetDTO[]) + await pricingModule.upsertPriceSets( + revertInput as PricingTypes.UpsertPriceSetDTO[] + ) } ) diff --git a/packages/core/core-flows/src/product-category/steps/create-product-categories.ts b/packages/core/core-flows/src/product-category/steps/create-product-categories.ts index c0fc7e355d..c9f76cfa2b 100644 --- a/packages/core/core-flows/src/product-category/steps/create-product-categories.ts +++ b/packages/core/core-flows/src/product-category/steps/create-product-categories.ts @@ -17,7 +17,9 @@ export const createProductCategoriesStep = createStep( ModuleRegistrationName.PRODUCT ) - const created = await service.createCategories(data.product_categories) + const created = await service.createProductCategories( + data.product_categories + ) return new StepResponse( created, @@ -33,6 +35,6 @@ export const createProductCategoriesStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.deleteCategories(createdIds) + await service.deleteProductCategories(createdIds) } ) diff --git a/packages/core/core-flows/src/product-category/steps/delete-product-categories.ts b/packages/core/core-flows/src/product-category/steps/delete-product-categories.ts index 0c774b4a8b..cdd44f5874 100644 --- a/packages/core/core-flows/src/product-category/steps/delete-product-categories.ts +++ b/packages/core/core-flows/src/product-category/steps/delete-product-categories.ts @@ -10,7 +10,7 @@ export const deleteProductCategoriesStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.softDeleteCategories(ids) + await service.softDeleteProductCategories(ids) return new StepResponse(void 0, ids) }, async (prevIds, { container }) => { @@ -22,6 +22,6 @@ export const deleteProductCategoriesStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.restoreCategories(prevIds) + await service.restoreProductCategories(prevIds) } ) diff --git a/packages/core/core-flows/src/product-category/steps/update-product-categories.ts b/packages/core/core-flows/src/product-category/steps/update-product-categories.ts index 01c41f49fb..5da7006b5a 100644 --- a/packages/core/core-flows/src/product-category/steps/update-product-categories.ts +++ b/packages/core/core-flows/src/product-category/steps/update-product-categories.ts @@ -24,12 +24,12 @@ export const updateProductCategoriesStep = createStep( data.update, ]) - const prevData = await service.listCategories(data.selector, { + const prevData = await service.listProductCategories(data.selector, { select: selects, relations, }) - const productCategories = await service.updateCategories( + const productCategories = await service.updateProductCategories( data.selector, data.update ) @@ -44,6 +44,6 @@ export const updateProductCategoriesStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.upsertCategories(prevData) + await service.upsertProductCategories(prevData) } ) diff --git a/packages/core/core-flows/src/product/steps/batch-link-products-collection.ts b/packages/core/core-flows/src/product/steps/batch-link-products-collection.ts index c6e13059ce..381df32934 100644 --- a/packages/core/core-flows/src/product/steps/batch-link-products-collection.ts +++ b/packages/core/core-flows/src/product/steps/batch-link-products-collection.ts @@ -16,7 +16,7 @@ export const batchLinkProductsToCollectionStep = createStep( return new StepResponse(void 0, null) } - const dbCollection = await service.retrieveCollection(data.id, { + const dbCollection = await service.retrieveProductCollection(data.id, { take: null, select: ["id", "products.id"], relations: ["products"], @@ -29,7 +29,7 @@ export const batchLinkProductsToCollectionStep = createStep( ...(data.add ?? []), ] - await service.updateCollections(data.id, { + await service.updateProductCollections(data.id, { product_ids: newProductIds, }) @@ -47,7 +47,7 @@ export const batchLinkProductsToCollectionStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.updateCollections(prevData.id, { + await service.updateProductCollections(prevData.id, { product_ids: prevData.productIds, }) } diff --git a/packages/core/core-flows/src/product/steps/batch-link-products-in-category.ts b/packages/core/core-flows/src/product/steps/batch-link-products-in-category.ts index dea22577cc..b7e813a28f 100644 --- a/packages/core/core-flows/src/product/steps/batch-link-products-in-category.ts +++ b/packages/core/core-flows/src/product/steps/batch-link-products-in-category.ts @@ -19,7 +19,7 @@ export const batchLinkProductsToCategoryStep = createStep( } const toRemoveSet = new Set(data.remove?.map((id) => id)) - const dbProducts = await service.list( + const dbProducts = await service.listProducts( { id: [...(data.add ?? []), ...(data.remove ?? [])] }, { take: null, @@ -43,7 +43,7 @@ export const batchLinkProductsToCategoryStep = createStep( } }) - await service.upsert(productsWithUpdatedCategories) + await service.upsertProducts(productsWithUpdatedCategories) return new StepResponse(void 0, { id: data.id, @@ -61,7 +61,7 @@ export const batchLinkProductsToCategoryStep = createStep( ModuleRegistrationName.PRODUCT ) - const dbProducts = await service.list( + const dbProducts = await service.listProducts( { id: prevData.productIds }, { take: null, @@ -86,6 +86,6 @@ export const batchLinkProductsToCategoryStep = createStep( } }) - await service.upsert(productsWithRevertedCategories) + await service.upsertProducts(productsWithRevertedCategories) } ) diff --git a/packages/core/core-flows/src/product/steps/create-collections.ts b/packages/core/core-flows/src/product/steps/create-collections.ts index 88ce611fd4..ae6af82a59 100644 --- a/packages/core/core-flows/src/product/steps/create-collections.ts +++ b/packages/core/core-flows/src/product/steps/create-collections.ts @@ -10,7 +10,7 @@ export const createCollectionsStep = createStep( ModuleRegistrationName.PRODUCT ) - const created = await service.createCollections(data) + const created = await service.createProductCollections(data) return new StepResponse( created, created.map((collection) => collection.id) @@ -25,6 +25,6 @@ export const createCollectionsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.deleteCollections(createdIds) + await service.deleteProductCollections(createdIds) } ) diff --git a/packages/core/core-flows/src/product/steps/create-product-options.ts b/packages/core/core-flows/src/product/steps/create-product-options.ts index 24c2cf0ee4..a5f90af194 100644 --- a/packages/core/core-flows/src/product/steps/create-product-options.ts +++ b/packages/core/core-flows/src/product/steps/create-product-options.ts @@ -10,7 +10,7 @@ export const createProductOptionsStep = createStep( ModuleRegistrationName.PRODUCT ) - const created = await service.createOptions(data) + const created = await service.createProductOptions(data) return new StepResponse( created, created.map((productOption) => productOption.id) @@ -25,6 +25,6 @@ export const createProductOptionsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.deleteOptions(createdIds) + await service.deleteProductOptions(createdIds) } ) diff --git a/packages/core/core-flows/src/product/steps/create-product-tags.ts b/packages/core/core-flows/src/product/steps/create-product-tags.ts index 46e60f5fbb..c436ef9020 100644 --- a/packages/core/core-flows/src/product/steps/create-product-tags.ts +++ b/packages/core/core-flows/src/product/steps/create-product-tags.ts @@ -10,7 +10,7 @@ export const createProductTagsStep = createStep( ModuleRegistrationName.PRODUCT ) - const created = await service.createTags(data) + const created = await service.createProductTags(data) return new StepResponse( created, created.map((productTag) => productTag.id) @@ -25,6 +25,6 @@ export const createProductTagsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.deleteTags(createdIds) + await service.deleteProductTags(createdIds) } ) diff --git a/packages/core/core-flows/src/product/steps/create-product-types.ts b/packages/core/core-flows/src/product/steps/create-product-types.ts index 52d61fb236..a0196266d0 100644 --- a/packages/core/core-flows/src/product/steps/create-product-types.ts +++ b/packages/core/core-flows/src/product/steps/create-product-types.ts @@ -10,7 +10,7 @@ export const createProductTypesStep = createStep( ModuleRegistrationName.PRODUCT ) - const created = await service.createTypes(data) + const created = await service.createProductTypes(data) return new StepResponse( created, created.map((productType) => productType.id) @@ -25,6 +25,6 @@ export const createProductTypesStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.deleteTypes(createdIds) + await service.deleteProductTypes(createdIds) } ) diff --git a/packages/core/core-flows/src/product/steps/create-product-variants.ts b/packages/core/core-flows/src/product/steps/create-product-variants.ts index 3167e0c6fb..90bb358965 100644 --- a/packages/core/core-flows/src/product/steps/create-product-variants.ts +++ b/packages/core/core-flows/src/product/steps/create-product-variants.ts @@ -9,7 +9,7 @@ export const createProductVariantsStep = createStep( const service = container.resolve( ModuleRegistrationName.PRODUCT ) - const created = await service.createVariants(data) + const created = await service.createProductVariants(data) return new StepResponse( created, created.map((productVariant) => productVariant.id) @@ -24,6 +24,6 @@ export const createProductVariantsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.deleteVariants(createdIds) + await service.deleteProductVariants(createdIds) } ) diff --git a/packages/core/core-flows/src/product/steps/create-products.ts b/packages/core/core-flows/src/product/steps/create-products.ts index cb11828800..9226d6a73f 100644 --- a/packages/core/core-flows/src/product/steps/create-products.ts +++ b/packages/core/core-flows/src/product/steps/create-products.ts @@ -10,7 +10,7 @@ export const createProductsStep = createStep( ModuleRegistrationName.PRODUCT ) - const created = await service.create(data) + const created = await service.createProducts(data) return new StepResponse( created, created.map((product) => product.id) @@ -25,6 +25,6 @@ export const createProductsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.delete(createdIds) + await service.deleteProducts(createdIds) } ) diff --git a/packages/core/core-flows/src/product/steps/delete-collections.ts b/packages/core/core-flows/src/product/steps/delete-collections.ts index 1a77496e5c..2dbb723519 100644 --- a/packages/core/core-flows/src/product/steps/delete-collections.ts +++ b/packages/core/core-flows/src/product/steps/delete-collections.ts @@ -10,7 +10,7 @@ export const deleteCollectionsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.softDeleteCollections(ids) + await service.softDeleteProductCollections(ids) return new StepResponse(void 0, ids) }, async (prevIds, { container }) => { @@ -22,6 +22,6 @@ export const deleteCollectionsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.restoreCollections(prevIds) + await service.restoreProductCollections(prevIds) } ) diff --git a/packages/core/core-flows/src/product/steps/delete-product-options.ts b/packages/core/core-flows/src/product/steps/delete-product-options.ts index 74b881f48f..afe33f506b 100644 --- a/packages/core/core-flows/src/product/steps/delete-product-options.ts +++ b/packages/core/core-flows/src/product/steps/delete-product-options.ts @@ -10,7 +10,7 @@ export const deleteProductOptionsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.softDeleteOptions(ids) + await service.softDeleteProductOptions(ids) return new StepResponse(void 0, ids) }, async (prevIds, { container }) => { @@ -22,6 +22,6 @@ export const deleteProductOptionsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.restoreOptions(prevIds) + await service.restoreProductOptions(prevIds) } ) diff --git a/packages/core/core-flows/src/product/steps/delete-product-tags.ts b/packages/core/core-flows/src/product/steps/delete-product-tags.ts index 44565c40ee..08385b6df0 100644 --- a/packages/core/core-flows/src/product/steps/delete-product-tags.ts +++ b/packages/core/core-flows/src/product/steps/delete-product-tags.ts @@ -10,7 +10,7 @@ export const deleteProductTagsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.softDeleteTags(ids) + await service.softDeleteProductTags(ids) return new StepResponse(void 0, ids) }, async (prevIds, { container }) => { @@ -22,6 +22,6 @@ export const deleteProductTagsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.restoreTags(prevIds) + await service.restoreProductTags(prevIds) } ) diff --git a/packages/core/core-flows/src/product/steps/delete-product-types.ts b/packages/core/core-flows/src/product/steps/delete-product-types.ts index d2d9cd8a01..c1645f963a 100644 --- a/packages/core/core-flows/src/product/steps/delete-product-types.ts +++ b/packages/core/core-flows/src/product/steps/delete-product-types.ts @@ -10,7 +10,7 @@ export const deleteProductTypesStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.softDeleteTypes(ids) + await service.softDeleteProductTypes(ids) return new StepResponse(void 0, ids) }, async (prevIds, { container }) => { @@ -22,6 +22,6 @@ export const deleteProductTypesStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.restoreTypes(prevIds) + await service.restoreProductTypes(prevIds) } ) diff --git a/packages/core/core-flows/src/product/steps/delete-product-variants.ts b/packages/core/core-flows/src/product/steps/delete-product-variants.ts index 5b0cfd1a1c..29aa181da6 100644 --- a/packages/core/core-flows/src/product/steps/delete-product-variants.ts +++ b/packages/core/core-flows/src/product/steps/delete-product-variants.ts @@ -10,7 +10,7 @@ export const deleteProductVariantsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.softDeleteVariants(ids) + await service.softDeleteProductVariants(ids) return new StepResponse(void 0, ids) }, async (prevIds, { container }) => { @@ -22,6 +22,6 @@ export const deleteProductVariantsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.restoreVariants(prevIds) + await service.restoreProductVariants(prevIds) } ) diff --git a/packages/core/core-flows/src/product/steps/delete-products.ts b/packages/core/core-flows/src/product/steps/delete-products.ts index 24559bdbe9..1fc3cc3020 100644 --- a/packages/core/core-flows/src/product/steps/delete-products.ts +++ b/packages/core/core-flows/src/product/steps/delete-products.ts @@ -10,7 +10,7 @@ export const deleteProductsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.softDelete(ids) + await service.softDeleteProducts(ids) return new StepResponse(void 0, ids) }, async (prevIds, { container }) => { @@ -22,6 +22,6 @@ export const deleteProductsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.restore(prevIds) + await service.restoreProducts(prevIds) } ) diff --git a/packages/core/core-flows/src/product/steps/get-products.ts b/packages/core/core-flows/src/product/steps/get-products.ts index 34b6e2bd1c..b5c494799e 100644 --- a/packages/core/core-flows/src/product/steps/get-products.ts +++ b/packages/core/core-flows/src/product/steps/get-products.ts @@ -18,7 +18,7 @@ export const getProductsStep = createStep( return new StepResponse([], []) } - const products = await service.list( + const products = await service.listProducts( { id: data.ids }, { relations: ["variants"], take: null } ) diff --git a/packages/core/core-flows/src/product/steps/update-collections.ts b/packages/core/core-flows/src/product/steps/update-collections.ts index f7776036b6..13c447d822 100644 --- a/packages/core/core-flows/src/product/steps/update-collections.ts +++ b/packages/core/core-flows/src/product/steps/update-collections.ts @@ -20,12 +20,12 @@ export const updateCollectionsStep = createStep( data.update, ]) - const prevData = await service.listCollections(data.selector, { + const prevData = await service.listProductCollections(data.selector, { select: selects, relations, }) - const collections = await service.updateCollections( + const collections = await service.updateProductCollections( data.selector, data.update ) @@ -40,7 +40,7 @@ export const updateCollectionsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.upsertCollections( + await service.upsertProductCollections( prevData.map((r) => ({ ...(r as unknown as ProductTypes.UpdateProductCollectionDTO), })) diff --git a/packages/core/core-flows/src/product/steps/update-product-options.ts b/packages/core/core-flows/src/product/steps/update-product-options.ts index 573d49ed11..b7ea512351 100644 --- a/packages/core/core-flows/src/product/steps/update-product-options.ts +++ b/packages/core/core-flows/src/product/steps/update-product-options.ts @@ -20,12 +20,12 @@ export const updateProductOptionsStep = createStep( data.update, ]) - const prevData = await service.listOptions(data.selector, { + const prevData = await service.listProductOptions(data.selector, { select: selects, relations, }) - const productOptions = await service.updateOptions( + const productOptions = await service.updateProductOptions( data.selector, data.update ) @@ -40,7 +40,7 @@ export const updateProductOptionsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.upsertOptions( + await service.upsertProductOptions( prevData.map((o) => ({ ...o, values: o.values?.map((v) => v.value), diff --git a/packages/core/core-flows/src/product/steps/update-product-tags.ts b/packages/core/core-flows/src/product/steps/update-product-tags.ts index b4bef994da..c5286d876e 100644 --- a/packages/core/core-flows/src/product/steps/update-product-tags.ts +++ b/packages/core/core-flows/src/product/steps/update-product-tags.ts @@ -20,12 +20,15 @@ export const updateProductTagsStep = createStep( data.update, ]) - const prevData = await service.listTags(data.selector, { + const prevData = await service.listProductTags(data.selector, { select: selects, relations, }) - const productTags = await service.updateTags(data.selector, data.update) + const productTags = await service.updateProductTags( + data.selector, + data.update + ) return new StepResponse(productTags, prevData) }, async (prevData, { container }) => { @@ -37,6 +40,6 @@ export const updateProductTagsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.upsertTags(prevData) + await service.upsertProductTags(prevData) } ) diff --git a/packages/core/core-flows/src/product/steps/update-product-types.ts b/packages/core/core-flows/src/product/steps/update-product-types.ts index 61d1a8ca31..e01f5be8d0 100644 --- a/packages/core/core-flows/src/product/steps/update-product-types.ts +++ b/packages/core/core-flows/src/product/steps/update-product-types.ts @@ -20,12 +20,15 @@ export const updateProductTypesStep = createStep( data.update, ]) - const prevData = await service.listTypes(data.selector, { + const prevData = await service.listProductTypes(data.selector, { select: selects, relations, }) - const productTypes = await service.updateTypes(data.selector, data.update) + const productTypes = await service.updateProductTypes( + data.selector, + data.update + ) return new StepResponse(productTypes, prevData) }, async (prevData, { container }) => { @@ -37,6 +40,6 @@ export const updateProductTypesStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.upsertTypes(prevData) + await service.upsertProductTypes(prevData) } ) diff --git a/packages/core/core-flows/src/product/steps/update-product-variants.ts b/packages/core/core-flows/src/product/steps/update-product-variants.ts index 8bb19570ca..2f21d3677c 100644 --- a/packages/core/core-flows/src/product/steps/update-product-variants.ts +++ b/packages/core/core-flows/src/product/steps/update-product-variants.ts @@ -31,11 +31,11 @@ export const updateProductVariantsStep = createStep( ) } - const prevData = await service.listVariants({ + const prevData = await service.listProductVariants({ id: data.product_variants.map((p) => p.id) as string[], }) - const productVariants = await service.upsertVariants( + const productVariants = await service.upsertProductVariants( data.product_variants ) return new StepResponse(productVariants, prevData) @@ -45,12 +45,12 @@ export const updateProductVariantsStep = createStep( data.update, ]) - const prevData = await service.listVariants(data.selector, { + const prevData = await service.listProductVariants(data.selector, { select: selects, relations, }) - const productVariants = await service.updateVariants( + const productVariants = await service.updateProductVariants( data.selector, data.update ) @@ -65,6 +65,6 @@ export const updateProductVariantsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.upsertVariants(prevData) + await service.upsertProductVariants(prevData) } ) diff --git a/packages/core/core-flows/src/product/steps/update-products.ts b/packages/core/core-flows/src/product/steps/update-products.ts index 35e95a97f3..41d1368c21 100644 --- a/packages/core/core-flows/src/product/steps/update-products.ts +++ b/packages/core/core-flows/src/product/steps/update-products.ts @@ -35,11 +35,11 @@ export const updateProductsStep = createStep( return new StepResponse([], []) } - const prevData = await service.list({ + const prevData = await service.listProducts({ id: data.products.map((p) => p.id) as string[], }) - const products = await service.upsert(data.products) + const products = await service.upsertProducts(data.products) return new StepResponse(products, prevData) } @@ -47,12 +47,12 @@ export const updateProductsStep = createStep( data.update, ]) - const prevData = await service.list(data.selector, { + const prevData = await service.listProducts(data.selector, { select: selects, relations, }) - const products = await service.update(data.selector, data.update) + const products = await service.updateProducts(data.selector, data.update) return new StepResponse(products, prevData) }, async (prevData, { container }) => { @@ -64,7 +64,7 @@ export const updateProductsStep = createStep( ModuleRegistrationName.PRODUCT ) - await service.upsert( + await service.upsertProducts( prevData.map((r) => ({ ...(r as unknown as ProductTypes.UpdateProductDTO), })) diff --git a/packages/core/core-flows/src/product/workflows/create-product-variants.ts b/packages/core/core-flows/src/product/workflows/create-product-variants.ts index f55b74028b..528f2b1769 100644 --- a/packages/core/core-flows/src/product/workflows/create-product-variants.ts +++ b/packages/core/core-flows/src/product/workflows/create-product-variants.ts @@ -1,5 +1,5 @@ import { LinkDefinition, Modules } from "@medusajs/modules-sdk" -import { InventoryNext, PricingTypes, ProductTypes } from "@medusajs/types" +import { InventoryTypes, PricingTypes, ProductTypes } from "@medusajs/types" import { WorkflowData, createWorkflow, @@ -40,7 +40,7 @@ const buildLink = ( const buildLinksToCreate = (data: { createdVariants: ProductTypes.ProductVariantDTO[] - inventoryIndexMap: Record + inventoryIndexMap: Record input: WorkflowInput }) => { let index = 0 @@ -83,7 +83,7 @@ const buildVariantItemCreateMap = (data: { input: WorkflowInput }) => { let index = 0 - const map: Record = {} + const map: Record = {} for (const variant of data.createdVariants || []) { const variantInput = data.input.product_variants[index] @@ -156,7 +156,7 @@ export const createProductVariantsWorkflow = createWorkflow( const inventoryIndexMap = transform( { createdInventoryItems, variantItemCreateMap }, (data) => { - const map: Record = {} + const map: Record = {} let inventoryIndex = 0 for (const variantIndex of Object.keys(data.variantItemCreateMap)) { diff --git a/packages/core/core-flows/src/promotion/steps/create-campaigns.ts b/packages/core/core-flows/src/promotion/steps/create-campaigns.ts index 4a9aec2d4b..b85238d795 100644 --- a/packages/core/core-flows/src/promotion/steps/create-campaigns.ts +++ b/packages/core/core-flows/src/promotion/steps/create-campaigns.ts @@ -26,6 +26,6 @@ export const createCampaignsStep = createStep( ModuleRegistrationName.PROMOTION ) - await promotionModule.delete(createdCampaignIds) + await promotionModule.deleteCampaigns(createdCampaignIds) } ) diff --git a/packages/core/core-flows/src/promotion/steps/create-promotions.ts b/packages/core/core-flows/src/promotion/steps/create-promotions.ts index 8a735b74b9..1f85d93fc0 100644 --- a/packages/core/core-flows/src/promotion/steps/create-promotions.ts +++ b/packages/core/core-flows/src/promotion/steps/create-promotions.ts @@ -10,7 +10,7 @@ export const createPromotionsStep = createStep( ModuleRegistrationName.PROMOTION ) - const createdPromotions = await promotionModule.create(data) + const createdPromotions = await promotionModule.createPromotions(data) return new StepResponse( createdPromotions, @@ -26,6 +26,6 @@ export const createPromotionsStep = createStep( ModuleRegistrationName.PROMOTION ) - await promotionModule.delete(createdPromotionIds) + await promotionModule.deletePromotions(createdPromotionIds) } ) diff --git a/packages/core/core-flows/src/promotion/steps/delete-promotions.ts b/packages/core/core-flows/src/promotion/steps/delete-promotions.ts index ddcb66aa69..af6dd4f0d5 100644 --- a/packages/core/core-flows/src/promotion/steps/delete-promotions.ts +++ b/packages/core/core-flows/src/promotion/steps/delete-promotions.ts @@ -10,7 +10,7 @@ export const deletePromotionsStep = createStep( ModuleRegistrationName.PROMOTION ) - await promotionModule.softDelete(ids) + await promotionModule.softDeletePromotions(ids) return new StepResponse(void 0, ids) }, @@ -23,6 +23,6 @@ export const deletePromotionsStep = createStep( ModuleRegistrationName.PROMOTION ) - await promotionModule.restore(idsToRestore) + await promotionModule.restorePromotions(idsToRestore) } ) diff --git a/packages/core/core-flows/src/promotion/steps/remove-rules-from-promotions.ts b/packages/core/core-flows/src/promotion/steps/remove-rules-from-promotions.ts index f7be51109f..00369d3fb4 100644 --- a/packages/core/core-flows/src/promotion/steps/remove-rules-from-promotions.ts +++ b/packages/core/core-flows/src/promotion/steps/remove-rules-from-promotions.ts @@ -18,7 +18,7 @@ export const removeRulesFromPromotionsStep = createStep( ModuleRegistrationName.PROMOTION ) - const promotion = await promotionModule.retrieve(data.id, { + const promotion = await promotionModule.retrievePromotion(data.id, { relations: [ "rules.values", "application_method.target_rules.values", diff --git a/packages/core/core-flows/src/promotion/steps/update-promotions.ts b/packages/core/core-flows/src/promotion/steps/update-promotions.ts index 1ffe3125a1..4f679f910c 100644 --- a/packages/core/core-flows/src/promotion/steps/update-promotions.ts +++ b/packages/core/core-flows/src/promotion/steps/update-promotions.ts @@ -15,12 +15,12 @@ export const updatePromotionsStep = createStep( ) const { selects, relations } = getSelectsAndRelationsFromObjectArray(data) - const dataBeforeUpdate = await promotionModule.list( + const dataBeforeUpdate = await promotionModule.listPromotions( { id: data.map((d) => d.id) }, { relations, select: selects } ) - const updatedPromotions = await promotionModule.update(data) + const updatedPromotions = await promotionModule.updatePromotions(data) return new StepResponse(updatedPromotions, { dataBeforeUpdate, @@ -39,7 +39,7 @@ export const updatePromotionsStep = createStep( ModuleRegistrationName.PROMOTION ) - await promotionModule.update( + await promotionModule.updatePromotions( dataBeforeUpdate.map((data) => convertItemResponseToUpdateRequest(data, selects, relations) ) diff --git a/packages/core/core-flows/src/region/steps/create-regions.ts b/packages/core/core-flows/src/region/steps/create-regions.ts index d9fcfba354..a755ea386c 100644 --- a/packages/core/core-flows/src/region/steps/create-regions.ts +++ b/packages/core/core-flows/src/region/steps/create-regions.ts @@ -10,7 +10,7 @@ export const createRegionsStep = createStep( ModuleRegistrationName.REGION ) - const created = await service.create(data) + const created = await service.createRegions(data) return new StepResponse( created, @@ -26,6 +26,6 @@ export const createRegionsStep = createStep( ModuleRegistrationName.REGION ) - await service.delete(createdIds) + await service.deleteRegions(createdIds) } ) diff --git a/packages/core/core-flows/src/region/steps/delete-regions.ts b/packages/core/core-flows/src/region/steps/delete-regions.ts index d7b11490d1..ae14864600 100644 --- a/packages/core/core-flows/src/region/steps/delete-regions.ts +++ b/packages/core/core-flows/src/region/steps/delete-regions.ts @@ -10,7 +10,7 @@ export const deleteRegionsStep = createStep( ModuleRegistrationName.REGION ) - await service.softDelete(ids) + await service.softDeleteRegions(ids) return new StepResponse(void 0, ids) }, @@ -23,6 +23,6 @@ export const deleteRegionsStep = createStep( ModuleRegistrationName.REGION ) - await service.restore(prevIds) + await service.restoreRegions(prevIds) } ) diff --git a/packages/core/core-flows/src/region/steps/update-regions.ts b/packages/core/core-flows/src/region/steps/update-regions.ts index 759aa0210b..3613cd73ac 100644 --- a/packages/core/core-flows/src/region/steps/update-regions.ts +++ b/packages/core/core-flows/src/region/steps/update-regions.ts @@ -24,7 +24,7 @@ export const updateRegionsStep = createStep( data.update, ]) - const prevData = await service.list(data.selector, { + const prevData = await service.listRegions(data.selector, { select: selects, relations, }) @@ -33,7 +33,7 @@ export const updateRegionsStep = createStep( return new StepResponse(prevData, []) } - const regions = await service.update(data.selector, data.update) + const regions = await service.updateRegions(data.selector, data.update) return new StepResponse(regions, prevData) }, @@ -46,7 +46,7 @@ export const updateRegionsStep = createStep( ModuleRegistrationName.REGION ) - await service.upsert( + await service.upsertRegions( prevData.map((r) => ({ id: r.id, name: r.name, diff --git a/packages/core/core-flows/src/reservation/steps/create-reservations.ts b/packages/core/core-flows/src/reservation/steps/create-reservations.ts index fcd103cc9d..2770f1a144 100644 --- a/packages/core/core-flows/src/reservation/steps/create-reservations.ts +++ b/packages/core/core-flows/src/reservation/steps/create-reservations.ts @@ -1,4 +1,4 @@ -import { IInventoryServiceNext, InventoryNext } from "@medusajs/types" +import { IInventoryService, InventoryTypes } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk" @@ -6,8 +6,8 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" export const createReservationsStepId = "create-reservations-step" export const createReservationsStep = createStep( createReservationsStepId, - async (data: InventoryNext.CreateReservationItemInput[], { container }) => { - const service = container.resolve( + async (data: InventoryTypes.CreateReservationItemInput[], { container }) => { + const service = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -23,7 +23,7 @@ export const createReservationsStep = createStep( return } - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/reservation/steps/delete-reservations-by-line-items.ts b/packages/core/core-flows/src/reservation/steps/delete-reservations-by-line-items.ts index eba051712b..2737a731ce 100644 --- a/packages/core/core-flows/src/reservation/steps/delete-reservations-by-line-items.ts +++ b/packages/core/core-flows/src/reservation/steps/delete-reservations-by-line-items.ts @@ -1,14 +1,14 @@ import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import { IInventoryServiceNext } from "@medusajs/types" +import { IInventoryService } from "@medusajs/types" export const deleteReservationsByLineItemsStepId = "delete-reservations-by-line-items" export const deleteReservationsByLineItemsStep = createStep( deleteReservationsByLineItemsStepId, async (ids: string[], { container }) => { - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -21,7 +21,7 @@ export const deleteReservationsByLineItemsStep = createStep( return } - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/reservation/steps/delete-reservations.ts b/packages/core/core-flows/src/reservation/steps/delete-reservations.ts index c25a4f8f37..374b877ae5 100644 --- a/packages/core/core-flows/src/reservation/steps/delete-reservations.ts +++ b/packages/core/core-flows/src/reservation/steps/delete-reservations.ts @@ -1,13 +1,13 @@ import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import { IInventoryServiceNext } from "@medusajs/types" +import { IInventoryService } from "@medusajs/types" export const deleteReservationsStepId = "delete-reservations" export const deleteReservationsStep = createStep( deleteReservationsStepId, async (ids: string[], { container }) => { - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -20,7 +20,7 @@ export const deleteReservationsStep = createStep( return } - const service = container.resolve( + const service = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/reservation/steps/update-reservations.ts b/packages/core/core-flows/src/reservation/steps/update-reservations.ts index 467c51395a..80cc1584e7 100644 --- a/packages/core/core-flows/src/reservation/steps/update-reservations.ts +++ b/packages/core/core-flows/src/reservation/steps/update-reservations.ts @@ -1,8 +1,4 @@ -import { - IInventoryServiceNext, - InventoryNext, - UpdateRuleTypeDTO, -} from "@medusajs/types" +import { IInventoryService, InventoryTypes } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" import { convertItemResponseToUpdateRequest, @@ -14,8 +10,8 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" export const updateReservationsStepId = "update-reservations-step" export const updateReservationsStep = createStep( updateReservationsStepId, - async (data: InventoryNext.UpdateReservationItemInput[], { container }) => { - const inventoryModuleService = container.resolve( + async (data: InventoryTypes.UpdateReservationItemInput[], { container }) => { + const inventoryModuleService = container.resolve( ModuleRegistrationName.INVENTORY ) @@ -41,7 +37,7 @@ export const updateReservationsStep = createStep( const { dataBeforeUpdate = [], selects, relations } = revertInput - const inventoryModuleService = container.resolve( + const inventoryModuleService = container.resolve( ModuleRegistrationName.INVENTORY ) diff --git a/packages/core/core-flows/src/sales-channel/steps/create-default-sales-channel.ts b/packages/core/core-flows/src/sales-channel/steps/create-default-sales-channel.ts index d28b210fad..b3b911e0ac 100644 --- a/packages/core/core-flows/src/sales-channel/steps/create-default-sales-channel.ts +++ b/packages/core/core-flows/src/sales-channel/steps/create-default-sales-channel.ts @@ -18,10 +18,13 @@ export const createDefaultSalesChannelStep = createStep( ) let shouldDelete = false - let [salesChannel] = await salesChannelService.list({}, { take: 1 }) + let [salesChannel] = await salesChannelService.listSalesChannels( + {}, + { take: 1 } + ) if (!salesChannel) { - salesChannel = await salesChannelService.create(input.data) + salesChannel = await salesChannelService.createSalesChannels(input.data) shouldDelete = true } @@ -37,6 +40,6 @@ export const createDefaultSalesChannelStep = createStep( ModuleRegistrationName.SALES_CHANNEL ) - await service.delete(data.id) + await service.deleteSalesChannels(data.id) } ) diff --git a/packages/core/core-flows/src/sales-channel/steps/create-sales-channels.ts b/packages/core/core-flows/src/sales-channel/steps/create-sales-channels.ts index 64499fd39b..0f856d33fc 100644 --- a/packages/core/core-flows/src/sales-channel/steps/create-sales-channels.ts +++ b/packages/core/core-flows/src/sales-channel/steps/create-sales-channels.ts @@ -17,7 +17,9 @@ export const createSalesChannelsStep = createStep( ModuleRegistrationName.SALES_CHANNEL ) - const salesChannels = await salesChannelService.create(input.data) + const salesChannels = await salesChannelService.createSalesChannels( + input.data + ) return new StepResponse( salesChannels, @@ -33,6 +35,6 @@ export const createSalesChannelsStep = createStep( ModuleRegistrationName.SALES_CHANNEL ) - await service.delete(createdIds) + await service.deleteSalesChannels(createdIds) } ) diff --git a/packages/core/core-flows/src/sales-channel/steps/delete-sales-channels.ts b/packages/core/core-flows/src/sales-channel/steps/delete-sales-channels.ts index bf56e3676e..08915cc187 100644 --- a/packages/core/core-flows/src/sales-channel/steps/delete-sales-channels.ts +++ b/packages/core/core-flows/src/sales-channel/steps/delete-sales-channels.ts @@ -12,7 +12,7 @@ export const deleteSalesChannelsStep = createStep( ModuleRegistrationName.SALES_CHANNEL ) - await service.softDelete(ids) + await service.softDeleteSalesChannels(ids) return new StepResponse(void 0, ids) }, @@ -25,6 +25,6 @@ export const deleteSalesChannelsStep = createStep( ModuleRegistrationName.SALES_CHANNEL ) - await service.restore(prevSalesChannelIds) + await service.restoreSalesChannels(prevSalesChannelIds) } ) diff --git a/packages/core/core-flows/src/sales-channel/steps/update-sales-channels.ts b/packages/core/core-flows/src/sales-channel/steps/update-sales-channels.ts index b02a0a4a93..455f03b1eb 100644 --- a/packages/core/core-flows/src/sales-channel/steps/update-sales-channels.ts +++ b/packages/core/core-flows/src/sales-channel/steps/update-sales-channels.ts @@ -24,12 +24,15 @@ export const updateSalesChannelsStep = createStep( data.update, ]) - const prevData = await service.list(data.selector, { + const prevData = await service.listSalesChannels(data.selector, { select: selects, relations, }) - const channels = await service.update(data.selector, data.update) + const channels = await service.updateSalesChannels( + data.selector, + data.update + ) return new StepResponse(channels, prevData) }, @@ -42,7 +45,7 @@ export const updateSalesChannelsStep = createStep( ModuleRegistrationName.SALES_CHANNEL ) - await service.upsert( + await service.upsertSalesChannels( prevData.map((r) => ({ id: r.id, name: r.name, diff --git a/packages/core/core-flows/src/stock-location/steps/create-stock-locations.ts b/packages/core/core-flows/src/stock-location/steps/create-stock-locations.ts index cd0d2fcbb1..8ae2a2ac9c 100644 --- a/packages/core/core-flows/src/stock-location/steps/create-stock-locations.ts +++ b/packages/core/core-flows/src/stock-location/steps/create-stock-locations.ts @@ -1,6 +1,6 @@ import { CreateStockLocationInput, - IStockLocationServiceNext, + IStockLocationService, } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" @@ -10,11 +10,11 @@ export const createStockLocationsStepId = "create-stock-locations" export const createStockLocations = createStep( createStockLocationsStepId, async (data: CreateStockLocationInput[], { container }) => { - const stockLocationService = container.resolve( + const stockLocationService = container.resolve( ModuleRegistrationName.STOCK_LOCATION ) - const created = await stockLocationService.create(data) + const created = await stockLocationService.createStockLocations(data) return new StepResponse( created, @@ -30,6 +30,6 @@ export const createStockLocations = createStep( ModuleRegistrationName.STOCK_LOCATION ) - await stockLocationService.delete(createdStockLocationIds) + await stockLocationService.deleteStockLocations(createdStockLocationIds) } ) diff --git a/packages/core/core-flows/src/stock-location/steps/delete-stock-locations.ts b/packages/core/core-flows/src/stock-location/steps/delete-stock-locations.ts index 245aa07650..13105067b0 100644 --- a/packages/core/core-flows/src/stock-location/steps/delete-stock-locations.ts +++ b/packages/core/core-flows/src/stock-location/steps/delete-stock-locations.ts @@ -11,7 +11,7 @@ export const deleteStockLocationsStep = createStep( async (input: string[], { container }) => { const service = container.resolve(ModuleRegistrationName.STOCK_LOCATION) - const softDeletedEntities = await service.softDelete(input) + const softDeletedEntities = await service.softDeleteStockLocations(input) return new StepResponse( { @@ -26,6 +26,6 @@ export const deleteStockLocationsStep = createStep( } const service = container.resolve(ModuleRegistrationName.STOCK_LOCATION) - await service.restore(deletedLocationIds) + await service.restoreStockLocations(deletedLocationIds) } ) diff --git a/packages/core/core-flows/src/stock-location/steps/update-stock-locations.ts b/packages/core/core-flows/src/stock-location/steps/update-stock-locations.ts index 9a3ea1ec66..3566a4f538 100644 --- a/packages/core/core-flows/src/stock-location/steps/update-stock-locations.ts +++ b/packages/core/core-flows/src/stock-location/steps/update-stock-locations.ts @@ -1,16 +1,12 @@ import { FilterableStockLocationProps, - IStockLocationServiceNext, - UpdateStockLocationNextInput, + IStockLocationService, + UpdateStockLocationInput, } from "@medusajs/types" import { StepResponse, createStep } from "@medusajs/workflows-sdk" -import { - convertItemResponseToUpdateRequest, - getSelectsAndRelationsFromObjectArray, -} from "@medusajs/utils" +import { getSelectsAndRelationsFromObjectArray } from "@medusajs/utils" import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import { UpdateStockLocationInput } from "@medusajs/types" interface StepInput { selector: FilterableStockLocationProps @@ -21,23 +17,27 @@ export const updateStockLocationsStepId = "update-stock-locations-step" export const updateStockLocationsStep = createStep( updateStockLocationsStepId, async (input: StepInput, { container }) => { - const stockLocationService = container.resolve( + const stockLocationService = container.resolve( ModuleRegistrationName.STOCK_LOCATION ) const { selects, relations } = getSelectsAndRelationsFromObjectArray([ input.update, ]) - const dataBeforeUpdate = await stockLocationService.list(input.selector, { - select: selects, - relations, - }) - - const updatedStockLocations = await stockLocationService.update( + const dataBeforeUpdate = await stockLocationService.listStockLocations( input.selector, - input.update + { + select: selects, + relations, + } ) + const updatedStockLocations = + await stockLocationService.updateStockLocations( + input.selector, + input.update + ) + return new StepResponse(updatedStockLocations, dataBeforeUpdate) }, async (revertInput, { container }) => { @@ -45,11 +45,11 @@ export const updateStockLocationsStep = createStep( return } - const stockLocationService = container.resolve( + const stockLocationService = container.resolve( ModuleRegistrationName.STOCK_LOCATION ) - await stockLocationService.upsert( + await stockLocationService.upsertStockLocations( revertInput.map((item) => ({ id: item.id, name: item.name, diff --git a/packages/core/core-flows/src/stock-location/workflows/update-stock-locations.ts b/packages/core/core-flows/src/stock-location/workflows/update-stock-locations.ts index 2ece07f72d..2115d5af68 100644 --- a/packages/core/core-flows/src/stock-location/workflows/update-stock-locations.ts +++ b/packages/core/core-flows/src/stock-location/workflows/update-stock-locations.ts @@ -1,12 +1,10 @@ import { - InventoryNext, StockLocationDTO, - UpdateStockLocationNextInput, + UpdateStockLocationInput, + FilterableStockLocationProps, } from "@medusajs/types" import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk" -import { FilterableStockLocationProps } from "@medusajs/types" -import { UpdateStockLocationInput } from "@medusajs/types" import { updateStockLocationsStep } from "../steps" interface WorkflowInput { diff --git a/packages/core/core-flows/src/store/steps/create-stores.ts b/packages/core/core-flows/src/store/steps/create-stores.ts index 96ec94c405..2d778111ee 100644 --- a/packages/core/core-flows/src/store/steps/create-stores.ts +++ b/packages/core/core-flows/src/store/steps/create-stores.ts @@ -14,7 +14,7 @@ export const createStoresStep = createStep( ModuleRegistrationName.STORE ) - const created = await service.create(data.stores) + const created = await service.createStores(data.stores) return new StepResponse( created, created.map((store) => store.id) @@ -29,6 +29,6 @@ export const createStoresStep = createStep( ModuleRegistrationName.STORE ) - await service.delete(createdIds) + await service.deleteStores(createdIds) } ) diff --git a/packages/core/core-flows/src/store/steps/delete-stores.ts b/packages/core/core-flows/src/store/steps/delete-stores.ts index 42f42b600e..ad5053c946 100644 --- a/packages/core/core-flows/src/store/steps/delete-stores.ts +++ b/packages/core/core-flows/src/store/steps/delete-stores.ts @@ -10,7 +10,7 @@ export const deleteStoresStep = createStep( ModuleRegistrationName.STORE ) - await storeModule.softDelete(ids) + await storeModule.softDeleteStores(ids) return new StepResponse(void 0, ids) }, async (idsToRestore, { container }) => { @@ -22,6 +22,6 @@ export const deleteStoresStep = createStep( ModuleRegistrationName.STORE ) - await storeModule.restore(idsToRestore) + await storeModule.restoreStores(idsToRestore) } ) diff --git a/packages/core/core-flows/src/store/steps/update-stores.ts b/packages/core/core-flows/src/store/steps/update-stores.ts index a5164e560a..76b9dcde90 100644 --- a/packages/core/core-flows/src/store/steps/update-stores.ts +++ b/packages/core/core-flows/src/store/steps/update-stores.ts @@ -24,12 +24,12 @@ export const updateStoresStep = createStep( data.update, ]) - const prevData = await service.list(data.selector, { + const prevData = await service.listStores(data.selector, { select: selects, relations, }) - const stores = await service.update(data.selector, data.update) + const stores = await service.updateStores(data.selector, data.update) return new StepResponse(stores, prevData) }, async (prevData, { container }) => { @@ -41,7 +41,7 @@ export const updateStoresStep = createStep( ModuleRegistrationName.STORE ) - await service.upsert( + await service.upsertStores( prevData.map((r) => ({ ...r, metadata: r.metadata || undefined, diff --git a/packages/core/core-flows/src/tax/steps/create-tax-rates.ts b/packages/core/core-flows/src/tax/steps/create-tax-rates.ts index 71e9bd8647..37672f5323 100644 --- a/packages/core/core-flows/src/tax/steps/create-tax-rates.ts +++ b/packages/core/core-flows/src/tax/steps/create-tax-rates.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { CreateTaxRateDTO, ITaxModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" export const createTaxRatesStepId = "create-tax-rates" export const createTaxRatesStep = createStep( @@ -10,7 +10,7 @@ export const createTaxRatesStep = createStep( ModuleRegistrationName.TAX ) - const created = await service.create(data) + const created = await service.createTaxRates(data) return new StepResponse( created, @@ -26,6 +26,6 @@ export const createTaxRatesStep = createStep( ModuleRegistrationName.TAX ) - await service.delete(createdIds) + await service.deleteTaxRates(createdIds) } ) diff --git a/packages/core/core-flows/src/tax/steps/create-tax-regions.ts b/packages/core/core-flows/src/tax/steps/create-tax-regions.ts index 03798769c3..b2e05e81ca 100644 --- a/packages/core/core-flows/src/tax/steps/create-tax-regions.ts +++ b/packages/core/core-flows/src/tax/steps/create-tax-regions.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { CreateTaxRegionDTO, ITaxModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" export const createTaxRegionsStepId = "create-tax-regions" export const createTaxRegionsStep = createStep( @@ -26,6 +26,6 @@ export const createTaxRegionsStep = createStep( ModuleRegistrationName.TAX ) - await service.delete(createdIds) + await service.deleteTaxRegions(createdIds) } ) diff --git a/packages/core/core-flows/src/tax/steps/delete-tax-rates.ts b/packages/core/core-flows/src/tax/steps/delete-tax-rates.ts index b574bf0a24..e2ec9842c6 100644 --- a/packages/core/core-flows/src/tax/steps/delete-tax-rates.ts +++ b/packages/core/core-flows/src/tax/steps/delete-tax-rates.ts @@ -1,6 +1,6 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ITaxModuleService } from "@medusajs/types" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" export const deleteTaxRatesStepId = "delete-tax-rates" export const deleteTaxRatesStep = createStep( @@ -10,7 +10,7 @@ export const deleteTaxRatesStep = createStep( ModuleRegistrationName.TAX ) - await service.softDelete(ids) + await service.softDeleteTaxRates(ids) return new StepResponse(void 0, ids) }, @@ -23,6 +23,6 @@ export const deleteTaxRatesStep = createStep( ModuleRegistrationName.TAX ) - await service.restore(prevIds) + await service.restoreTaxRates(prevIds) } ) diff --git a/packages/core/core-flows/src/tax/steps/list-tax-rate-ids.ts b/packages/core/core-flows/src/tax/steps/list-tax-rate-ids.ts index 30da06c237..b5b2f9d847 100644 --- a/packages/core/core-flows/src/tax/steps/list-tax-rate-ids.ts +++ b/packages/core/core-flows/src/tax/steps/list-tax-rate-ids.ts @@ -14,7 +14,7 @@ export const listTaxRateIdsStep = createStep( ModuleRegistrationName.TAX ) - const rates = await service.list(input.selector, { + const rates = await service.listTaxRates(input.selector, { select: ["id"], }) diff --git a/packages/core/core-flows/src/tax/steps/update-tax-rates.ts b/packages/core/core-flows/src/tax/steps/update-tax-rates.ts index 36dfbed8cf..7fee421263 100644 --- a/packages/core/core-flows/src/tax/steps/update-tax-rates.ts +++ b/packages/core/core-flows/src/tax/steps/update-tax-rates.ts @@ -5,7 +5,7 @@ import { UpdateTaxRateDTO, } from "@medusajs/types" import { getSelectsAndRelationsFromObjectArray } from "@medusajs/utils" -import { StepResponse, createStep } from "@medusajs/workflows-sdk" +import { createStep, StepResponse } from "@medusajs/workflows-sdk" type UpdateTaxRatesStepInput = { selector: FilterableTaxRateProps @@ -24,12 +24,12 @@ export const updateTaxRatesStep = createStep( data.update, ]) - const prevData = await service.list(data.selector, { + const prevData = await service.listTaxRates(data.selector, { select: selects, relations, }) - const taxRates = await service.update(data.selector, data.update) + const taxRates = await service.updateTaxRates(data.selector, data.update) return new StepResponse(taxRates, prevData) }, @@ -42,6 +42,6 @@ export const updateTaxRatesStep = createStep( ModuleRegistrationName.TAX ) - await service.upsert(prevData) + await service.upsertTaxRates(prevData) } ) diff --git a/packages/core/core-flows/src/user/steps/create-users.ts b/packages/core/core-flows/src/user/steps/create-users.ts index ca4f247e95..f632ff3ef6 100644 --- a/packages/core/core-flows/src/user/steps/create-users.ts +++ b/packages/core/core-flows/src/user/steps/create-users.ts @@ -9,7 +9,7 @@ export const createUsersStep = createStep( const service: IUserModuleService = container.resolve( ModuleRegistrationName.USER ) - const users = await service.create(input) + const users = await service.createUsers(input) return new StepResponse(users) }, async (createdUsers, { container }) => { @@ -17,6 +17,6 @@ export const createUsersStep = createStep( return } const service = container.resolve(ModuleRegistrationName.USER) - await service.delete(createdUsers.map((user) => user.id)) + await service.deleteUsers(createdUsers.map((user) => user.id)) } ) diff --git a/packages/core/core-flows/src/user/steps/delete-users.ts b/packages/core/core-flows/src/user/steps/delete-users.ts index 9df37c2790..50676329ab 100644 --- a/packages/core/core-flows/src/user/steps/delete-users.ts +++ b/packages/core/core-flows/src/user/steps/delete-users.ts @@ -10,7 +10,7 @@ export const deleteUsersStep = createStep( ModuleRegistrationName.USER ) - await service.softDelete(input) + await service.softDeleteUsers(input) return new StepResponse(void 0, input) }, @@ -23,6 +23,6 @@ export const deleteUsersStep = createStep( ModuleRegistrationName.USER ) - await service.restore(prevUserIds) + await service.restoreUsers(prevUserIds) } ) diff --git a/packages/core/core-flows/src/user/steps/update-users.ts b/packages/core/core-flows/src/user/steps/update-users.ts index 5e5b3743b4..978c7819e2 100644 --- a/packages/core/core-flows/src/user/steps/update-users.ts +++ b/packages/core/core-flows/src/user/steps/update-users.ts @@ -14,11 +14,11 @@ export const updateUsersStep = createStep( return new StepResponse([], []) } - const originalUsers = await service.list({ + const originalUsers = await service.listUsers({ id: input.map((u) => u.id), }) - const users = await service.update(input) + const users = await service.updateUsers(input) return new StepResponse(users, originalUsers) }, async (originalUsers, { container }) => { @@ -28,7 +28,7 @@ export const updateUsersStep = createStep( const service = container.resolve(ModuleRegistrationName.USER) - await service.update( + await service.updateUsers( originalUsers.map((u) => ({ id: u.id, first_name: u.first_name, diff --git a/packages/core/modules-sdk/src/remote-link.ts b/packages/core/modules-sdk/src/remote-link.ts index 8d77e06f63..4eec0fc494 100644 --- a/packages/core/modules-sdk/src/remote-link.ts +++ b/packages/core/modules-sdk/src/remote-link.ts @@ -168,7 +168,7 @@ export class RemoteLink { private async executeCascade( removedServices: DeleteEntityInput, - method: "softDelete" | "restore" + executionMethod: "softDelete" | "restore" ): Promise<[CascadeError[] | null, RemovedIds]> { const removedIds: RemovedIds = {} const returnIdsList: RemovedIds = {} @@ -191,6 +191,8 @@ export class RemoteLink { services: { serviceName: string; deleteKeys: DeleteEntities }[], isCascading: boolean = false ): Promise => { + let method = executionMethod + if (errors.length) { return returnIdsList } diff --git a/packages/core/types/src/api-key/service.ts b/packages/core/types/src/api-key/service.ts index da478ad6ed..79db3037b7 100644 --- a/packages/core/types/src/api-key/service.ts +++ b/packages/core/types/src/api-key/service.ts @@ -21,13 +21,16 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} The created API keys. * * @example - * const apiKey = await apiKeyModuleService.create([{ + * const apiKey = await apiKeyModuleService.createApiKeys([{ * title: "Development API key", * type: "publishable", * created_by: "user_123" * }]) */ - create(data: CreateApiKeyDTO[], sharedContext?: Context): Promise + createApiKeys( + data: CreateApiKeyDTO[], + sharedContext?: Context + ): Promise /** * This method creates an API key. @@ -37,13 +40,16 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} The created API key. * * @example - * const apiKey = await apiKeyModuleService.create({ + * const apiKey = await apiKeyModuleService.createApiKeys({ * title: "Development API key", * type: "publishable", * created_by: "user_123" * }) */ - create(data: CreateApiKeyDTO, sharedContext?: Context): Promise + createApiKeys( + data: CreateApiKeyDTO, + sharedContext?: Context + ): Promise /** * This method updates or creates API keys if they don't exist. @@ -53,7 +59,7 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} The created or updated API keys. * * @example - * const apiKey = await apiKeyModuleService.upsert([ + * const apiKey = await apiKeyModuleService.upsertApiKeys([ * { * id: "apk_123", * title: "My development key", @@ -65,7 +71,10 @@ export interface IApiKeyModuleService extends IModuleService { * }, * ]) */ - upsert(data: UpsertApiKeyDTO[], sharedContext?: Context): Promise + upsertApiKeys( + data: UpsertApiKeyDTO[], + sharedContext?: Context + ): Promise /** * This method updates or creates an API key if it doesn't exist. @@ -75,12 +84,15 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} The created or updated API key. * * @example - * const apiKey = await apiKeyModuleService.upsert({ + * const apiKey = await apiKeyModuleService.upsertApiKeys({ * id: "apk_123", * title: "My development key" * }) */ - upsert(data: UpsertApiKeyDTO, sharedContext?: Context): Promise + upsertApiKeys( + data: UpsertApiKeyDTO, + sharedContext?: Context + ): Promise /** * This method updates an existing API key. @@ -91,11 +103,11 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} The updated API key. * * @example - * const apiKey = await apiKeyModuleService.update("apk_123", { + * const apiKey = await apiKeyModuleService.updateApiKeys("apk_123", { * title: "My development key" * }) */ - update( + updateApiKeys( id: string, data: UpdateApiKeyDTO, sharedContext?: Context @@ -110,7 +122,7 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} The updated API keys. * * @example - * const apiKey = await apiKeyModuleService.update( + * const apiKey = await apiKeyModuleService.updateApiKeys( * { * title: "Development key", * }, @@ -119,7 +131,7 @@ export interface IApiKeyModuleService extends IModuleService { * } * ) */ - update( + updateApiKeys( selector: FilterableApiKeyProps, data: UpdateApiKeyDTO, sharedContext?: Context @@ -133,9 +145,9 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} Resolves when the API keys are deleted successfully. * * @example - * await apiKeyModuleService.delete(["apk_123"]) + * await apiKeyModuleService.deleteApiKeys(["apk_123"]) */ - delete(ids: string[], sharedContext?: Context): Promise + deleteApiKeys(ids: string[], sharedContext?: Context): Promise /** * This method deletes an API key by its ID. @@ -145,9 +157,9 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} Resolves when the API key is deleted successfully. * * @example - * await apiKeyModuleService.delete("apk_123") + * await apiKeyModuleService.deleteApiKeys("apk_123") */ - delete(id: string, sharedContext?: Context): Promise + deleteApiKeys(id: string, sharedContext?: Context): Promise /** * This method retrieves an API key by its ID. @@ -159,9 +171,9 @@ export interface IApiKeyModuleService extends IModuleService { * @returns {Promise} The retrieved API key. * * @example - * const apiKey = await apiKeyModuleService.retrieve("apk_123") + * const apiKey = await apiKeyModuleService.retrieveApiKey("apk_123") */ - retrieve( + retrieveApiKey( id: string, config?: FindConfig, sharedContext?: Context @@ -180,7 +192,7 @@ export interface IApiKeyModuleService extends IModuleService { * To retrieve a list of API keys using their IDs: * * ```ts - * const apiKeys = await apiKeyModuleService.list({ + * const apiKeys = await apiKeyModuleService.listApiKeys({ * id: ["apk_123", "apk_321"] * }) * ``` @@ -188,7 +200,7 @@ export interface IApiKeyModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const apiKeys = await apiKeyModuleService.list( + * const apiKeys = await apiKeyModuleService.listApiKeys( * { * id: ["apk_123", "apk_321"], * }, @@ -199,7 +211,7 @@ export interface IApiKeyModuleService extends IModuleService { * ) * ``` */ - list( + listApiKeys( filters?: FilterableApiKeyProps, config?: FindConfig, sharedContext?: Context @@ -219,7 +231,7 @@ export interface IApiKeyModuleService extends IModuleService { * * ```ts * const [apiKeys, count] = - * await apiKeyModuleService.listAndCount({ + * await apiKeyModuleService.listAndCountApiKeys({ * id: ["apk_123", "apk_321"], * }) * ``` @@ -228,7 +240,7 @@ export interface IApiKeyModuleService extends IModuleService { * * ```ts * const [apiKeys, count] = - * await apiKeyModuleService.listAndCount( + * await apiKeyModuleService.listAndCountApiKeys( * { * id: ["apk_123", "apk_321"], * }, @@ -239,7 +251,7 @@ export interface IApiKeyModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountApiKeys( filters?: FilterableApiKeyProps, config?: FindConfig, sharedContext?: Context diff --git a/packages/core/types/src/auth/service.ts b/packages/core/types/src/auth/service.ts index 10935a1882..88ff60805c 100644 --- a/packages/core/types/src/auth/service.ts +++ b/packages/core/types/src/auth/service.ts @@ -93,9 +93,9 @@ export interface IAuthModuleService extends IModuleService { * @returns {Promise} The retrieved auth identity. * * @example - * const authIdentity = await authModuleService.retrieve("authusr_1") + * const authIdentity = await authModuleService.retrieveAuthIdentity("authusr_1") */ - retrieve( + retrieveAuthIdentity( id: string, config?: FindConfig, sharedContext?: Context @@ -114,7 +114,7 @@ export interface IAuthModuleService extends IModuleService { * To retrieve a list of auth identities using their IDs: * * ```ts - * const authIdentities = await authModuleService.list({ + * const authIdentities = await authModuleService.listAuthIdentities({ * id: ["authusr_123", "authusr_321"], * }) * ``` @@ -122,7 +122,7 @@ export interface IAuthModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const authIdentities = await authModuleService.list( + * const authIdentities = await authModuleService.listAuthIdentities( * { * id: ["authusr_123", "authusr_321"], * }, @@ -133,7 +133,7 @@ export interface IAuthModuleService extends IModuleService { * ) * ``` */ - list( + listAuthIdentities( filters?: FilterableAuthIdentityProps, config?: FindConfig, sharedContext?: Context @@ -153,7 +153,7 @@ export interface IAuthModuleService extends IModuleService { * * ```ts * const [authIdentities, count] = - * await authModuleService.listAndCount({ + * await authModuleService.listAndCountAuthIdentities({ * id: ["authusr_123", "authusr_321"], * }) * ``` @@ -162,7 +162,7 @@ export interface IAuthModuleService extends IModuleService { * * ```ts * const [authIdentities, count] = - * await authModuleService.listAndCount( + * await authModuleService.listAndCountAuthIdentities( * { * id: ["authusr_123", "authusr_321"], * }, @@ -173,7 +173,7 @@ export interface IAuthModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountAuthIdentities( filters?: FilterableAuthIdentityProps, config?: FindConfig, sharedContext?: Context @@ -187,7 +187,7 @@ export interface IAuthModuleService extends IModuleService { * @returns {Promise} The created auth identities. * * @example - * const authIdentities = await authModuleService.create([ + * const authIdentities = await authModuleService.createAuthIdentities([ * { * provider_identities: [{ * provider: "emailpass", @@ -202,7 +202,7 @@ export interface IAuthModuleService extends IModuleService { * }, * ]) */ - create( + createAuthIdentities( data: CreateAuthIdentityDTO[], sharedContext?: Context ): Promise @@ -215,14 +215,14 @@ export interface IAuthModuleService extends IModuleService { * @returns {Promise} The created auth identity. * * @example - * const authIdentity = await authModuleService.create({ + * const authIdentity = await authModuleService.createAuthIdentities({ * provider_identities: [{ * provider: "emailpass", * entity_id: "user@example.com", * }] * }) */ - create( + createAuthIdentities( data: CreateAuthIdentityDTO, sharedContext?: Context ): Promise @@ -235,13 +235,13 @@ export interface IAuthModuleService extends IModuleService { * @returns {Promise} The updated auths. * * @example - * const authIdentities = await authModuleService.update([ + * const authIdentities = await authModuleService.updateAuthIdentites([ * { * id: "authusr_123", * }, * ]) */ - update( + updateAuthIdentites( data: UpdateAuthIdentityDTO[], sharedContext?: Context ): Promise @@ -254,11 +254,11 @@ export interface IAuthModuleService extends IModuleService { * @returns {Promise} The updated auth. * * @example - * const authIdentity = await authModuleService.update({ + * const authIdentity = await authModuleService.updateAuthIdentites({ * id: "authusr_123", * }) */ - update( + updateAuthIdentites( data: UpdateAuthIdentityDTO, sharedContext?: Context ): Promise @@ -271,7 +271,7 @@ export interface IAuthModuleService extends IModuleService { * @returns {Promise} Resolves when {summary} * * @example - * await authModuleService.delete(["authusr_123", "authusr_321"]) + * await authModuleService.deleteAuthIdentities(["authusr_123", "authusr_321"]) */ - delete(ids: string[], sharedContext?: Context): Promise + deleteAuthIdentities(ids: string[], sharedContext?: Context): Promise } diff --git a/packages/core/types/src/cart/mutations.ts b/packages/core/types/src/cart/mutations.ts index 6159d98e5e..d484ab4686 100644 --- a/packages/core/types/src/cart/mutations.ts +++ b/packages/core/types/src/cart/mutations.ts @@ -376,6 +376,10 @@ export interface CreateTaxLineDTO { * The associated provider's ID. */ provider_id?: string + /** + * The associated item's ID. + */ + item_id?: string } /** @@ -411,6 +415,11 @@ export interface UpdateTaxLineDTO { * The associated provider's ID. */ provider_id?: string + + /** + * The associated item's ID. + */ + item_id?: string } /** diff --git a/packages/core/types/src/cart/service.ts b/packages/core/types/src/cart/service.ts index 7f0b9f251c..cc2f315326 100644 --- a/packages/core/types/src/cart/service.ts +++ b/packages/core/types/src/cart/service.ts @@ -32,8 +32,8 @@ import { CreateShippingMethodForSingleCartDTO, CreateShippingMethodTaxLineDTO, UpdateAddressDTO, - UpdateCartDTO, UpdateCartDataDTO, + UpdateCartDTO, UpdateLineItemDTO, UpdateLineItemTaxLineDTO, UpdateLineItemWithSelectorDTO, @@ -59,18 +59,18 @@ export interface ICartModuleService extends IModuleService { * A simple example that retrieves a cart by its ID: * * ```ts - * const cart = await cartModuleService.retrieve("cart_123") + * const cart = await cartModuleService.retrieveCart("cart_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const cart = await cartModuleService.retrieve("cart_123", { + * const cart = await cartModuleService.retrieveCart("cart_123", { * relations: ["shipping_address"], * }) * ``` */ - retrieve( + retrieveCart( cartId: string, config?: FindConfig, sharedContext?: Context @@ -89,7 +89,7 @@ export interface ICartModuleService extends IModuleService { * To retrieve a list of carts using their IDs: * * ```ts - * const carts = await cartModuleService.list({ + * const carts = await cartModuleService.listCarts({ * id: ["cart_123", "cart_321"], * }) * ``` @@ -97,7 +97,7 @@ export interface ICartModuleService extends IModuleService { * To specify relations that should be retrieved within the carts: * * ```ts - * const carts = await cartModuleService.list( + * const carts = await cartModuleService.listCarts( * { * id: ["cart_123", "cart_321"], * }, @@ -110,7 +110,7 @@ export interface ICartModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const carts = await cartModuleService.list( + * const carts = await cartModuleService.listCarts( * { * id: ["cart_123", "cart_321"], * }, @@ -122,7 +122,7 @@ export interface ICartModuleService extends IModuleService { * ) * ``` */ - list( + listCarts( filters?: FilterableCartProps, config?: FindConfig, sharedContext?: Context @@ -141,7 +141,7 @@ export interface ICartModuleService extends IModuleService { * To retrieve a list of carts using their IDs: * * ```ts - * const [carts, count] = await cartModuleService.listAndCount({ + * const [carts, count] = await cartModuleService.listAndCountCarts({ * id: ["cart_123", "cart_321"], * }) * ``` @@ -149,7 +149,7 @@ export interface ICartModuleService extends IModuleService { * To specify relations that should be retrieved within the carts: * * ```ts - * const [carts, count] = await cartModuleService.listAndCount( + * const [carts, count] = await cartModuleService.listAndCountCarts( * { * id: ["cart_123", "cart_321"], * }, @@ -162,7 +162,7 @@ export interface ICartModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const [carts, count] = await cartModuleService.listAndCount( + * const [carts, count] = await cartModuleService.listAndCountCarts( * { * id: ["cart_123", "cart_321"], * }, @@ -174,7 +174,7 @@ export interface ICartModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountCarts( filters?: FilterableCartProps, config?: FindConfig, sharedContext?: Context @@ -188,7 +188,7 @@ export interface ICartModuleService extends IModuleService { * @returns {Promise} The created carts. * * @example - * const carts = await cartModuleService.create([ + * const carts = await cartModuleService.createCarts([ * { * currency_code: "usd", * }, @@ -197,7 +197,10 @@ export interface ICartModuleService extends IModuleService { * }, * ]) */ - create(data: CreateCartDTO[], sharedContext?: Context): Promise + createCarts( + data: CreateCartDTO[], + sharedContext?: Context + ): Promise /** * This method creates a cart. @@ -207,11 +210,11 @@ export interface ICartModuleService extends IModuleService { * @returns {Promise} The created cart. * * @example - * const cart = await cartModuleService.create({ + * const cart = await cartModuleService.createCarts({ * currency_code: "usd", * }) */ - create(data: CreateCartDTO, sharedContext?: Context): Promise + createCarts(data: CreateCartDTO, sharedContext?: Context): Promise /** * This method updates existing carts. @@ -220,7 +223,7 @@ export interface ICartModuleService extends IModuleService { * @returns {Promise} The updated carts. * * @example - * const carts = await cartModuleService.update([ + * const carts = await cartModuleService.updateCarts([ * { * id: "cart_123", * region_id: "reg_123", @@ -231,7 +234,7 @@ export interface ICartModuleService extends IModuleService { * }, * ]) */ - update(data: UpdateCartDTO[]): Promise + updateCarts(data: UpdateCartDTO[]): Promise /** * This method updates an existing cart. @@ -242,11 +245,11 @@ export interface ICartModuleService extends IModuleService { * @returns {Promise} The updated cart. * * @example - * const cart = await cartModuleService.update("cart_123", { + * const cart = await cartModuleService.updateCarts("cart_123", { * region_id: "reg_123", * }) */ - update( + updateCarts( cartId: string, data: UpdateCartDataDTO, sharedContext?: Context @@ -261,7 +264,7 @@ export interface ICartModuleService extends IModuleService { * @returns {Promise} The updated carts. * * @example - * const carts = await cartModuleService.update( + * const carts = await cartModuleService.updateCarts( * { * currency_code: "usd", * }, @@ -270,7 +273,7 @@ export interface ICartModuleService extends IModuleService { * } * ) */ - update( + updateCarts( selector: Partial, data: UpdateCartDataDTO, sharedContext?: Context @@ -284,9 +287,9 @@ export interface ICartModuleService extends IModuleService { * @returns {Promise} Resolves when the carts are deleted successfully. * * @example - * await cartModuleService.delete(["cart_123", "cart_321"]) + * await cartModuleService.deleteCarts(["cart_123", "cart_321"]) */ - delete(cartIds: string[], sharedContext?: Context): Promise + deleteCarts(cartIds: string[], sharedContext?: Context): Promise /** * This method deletes a cart by its ID. @@ -296,9 +299,9 @@ export interface ICartModuleService extends IModuleService { * @returns {Promise} Resolves when the carts are deleted successfully. * * @example - * await cartModuleService.delete("cart_123") + * await cartModuleService.deleteCarts("cart_123") */ - delete(cartId: string, sharedContext?: Context): Promise + deleteCarts(cartId: string, sharedContext?: Context): Promise /** * This method retrieves a paginated list of addresses based on optional filters and configuration. @@ -1460,30 +1463,6 @@ export interface ICartModuleService extends IModuleService { sharedContext?: Context ): Promise - /** - * This method deletes carts by their IDs. - * - * @param {string[]} ids - The IDs of the cart. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the carts are deleted successfully. - * - * @example - * await cartModuleService.delete(["cart_123", "cart_321"]) - */ - delete(ids: string[], sharedContext?: Context): Promise - - /** - * This method deletes a cart by its ID. - * - * @param {string} id - The ID of the cart. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when a cart is deleted successfully. - * - * @example - * await cartModuleService.delete("cart_123") - */ - delete(id: string, sharedContext?: Context): Promise - /** * This method deletes line items by their IDs. * @@ -1680,9 +1659,9 @@ export interface ICartModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await cartModuleService.softDelete(["cart_123", "cart_321"]) + * await cartModuleService.softDeleteCarts(["cart_123", "cart_321"]) */ - softDelete( + softDeleteCarts( ids: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -1703,9 +1682,9 @@ export interface ICartModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await cartModuleService.restore(["cart_123", "cart_321"]) + * await cartModuleService.restoreCarts(["cart_123", "cart_321"]) */ - restore( + restoreCarts( ids: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/common/common.ts b/packages/core/types/src/common/common.ts index 571036ac64..effb79ac00 100644 --- a/packages/core/types/src/common/common.ts +++ b/packages/core/types/src/common/common.ts @@ -332,7 +332,9 @@ export interface NumericalComparisonOperator { /** * @ignore */ -export type Pluralize = Singular extends `${infer R}y` +export type Pluralize = Singular extends `${infer R}ey` + ? `${R}eys` + : Singular extends `${infer R}y` ? `${R}ies` : Singular extends `${infer R}es` ? `${Singular}` diff --git a/packages/core/types/src/currency/service.ts b/packages/core/types/src/currency/service.ts index 87c8ac7700..0735d1e147 100644 --- a/packages/core/types/src/currency/service.ts +++ b/packages/core/types/src/currency/service.ts @@ -1,7 +1,7 @@ import { FindConfig } from "../common" import { IModuleService } from "../modules-sdk" import { Context } from "../shared-context" -import { FilterableCurrencyProps, CurrencyDTO } from "./common" +import { CurrencyDTO, FilterableCurrencyProps } from "./common" /** * The main service interface for the Currency Module. @@ -18,9 +18,9 @@ export interface ICurrencyModuleService extends IModuleService { * @returns {Promise} The retrieved currency. * * @example - * const currency = await currencyModuleService.retrieve("usd") + * const currency = await currencyModuleService.retrieveCurrency("usd") */ - retrieve( + retrieveCurrency( code: string, config?: FindConfig, sharedContext?: Context @@ -41,7 +41,7 @@ export interface ICurrencyModuleService extends IModuleService { * To retrieve a list of currencies using their codes: * * ```ts - * const currencies = await currencyModuleService.list({ + * const currencies = await currencyModuleService.listCurrencies({ * code: ["usd", "eur"], * }) * ``` @@ -49,7 +49,7 @@ export interface ICurrencyModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const currencies = await currencyModuleService.list( + * const currencies = await currencyModuleService.listCurrencies( * { * code: ["usd", "eur"], * }, @@ -60,7 +60,7 @@ export interface ICurrencyModuleService extends IModuleService { * ) * ``` */ - list( + listCurrencies( filters?: FilterableCurrencyProps, config?: FindConfig, sharedContext?: Context @@ -82,7 +82,7 @@ export interface ICurrencyModuleService extends IModuleService { * * ```ts * const [currencies, count] = - * await currencyModuleService.listAndCount({ + * await currencyModuleService.listAndCountCurrencies({ * code: ["usd", "eur"], * }) * ``` @@ -91,7 +91,7 @@ export interface ICurrencyModuleService extends IModuleService { * * ```ts * const [currencies, count] = - * await currencyModuleService.listAndCount( + * await currencyModuleService.listAndCountCurrencies( * { * code: ["usd", "eur"], * }, @@ -102,7 +102,7 @@ export interface ICurrencyModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountCurrencies( filters?: FilterableCurrencyProps, config?: FindConfig, sharedContext?: Context diff --git a/packages/core/types/src/customer/service.ts b/packages/core/types/src/customer/service.ts index 392b2da621..fb87afeb7f 100644 --- a/packages/core/types/src/customer/service.ts +++ b/packages/core/types/src/customer/service.ts @@ -40,13 +40,13 @@ export interface ICustomerModuleService extends IModuleService { * * ```ts * const customer = - * await customerModuleService.retrieve("cus_123") + * await customerModuleService.retrieveCustomer("cus_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const customer = await customerModuleService.retrieve( + * const customer = await customerModuleService.retrieveCustomer( * "cus_123", * { * relations: ["groups"], @@ -54,7 +54,7 @@ export interface ICustomerModuleService extends IModuleService { * ) * ``` */ - retrieve( + retrieveCustomer( customerId: string, config?: FindConfig, sharedContext?: Context @@ -68,7 +68,7 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} The created customers. * * @example - * const customers = await customerModuleService.create([ + * const customers = await customerModuleService.createCustomers([Customers * { * email: "john@smith.com", * first_name: "John", @@ -76,7 +76,7 @@ export interface ICustomerModuleService extends IModuleService { * }, * ]) */ - create( + createCustomers( data: CreateCustomerDTO[], sharedContext?: Context ): Promise @@ -89,13 +89,16 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} The created customer. * * @example - * const customer = await customerModuleService.create({ + * const customer = await customerModuleService.createCustomers({Customers * email: "john@smith.com", * first_name: "John", * last_name: "Smith", * }) */ - create(data: CreateCustomerDTO, sharedContext?: Context): Promise + createCustomers( + data: CreateCustomerDTO, + sharedContext?: Context + ): Promise /** * This method updates an existing customer. @@ -106,14 +109,14 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} The updated customer. * * @example - * const customer = await customerModuleService.update( + * const customer = await customerModuleService.updateCustomers( * "cus_123", * { * first_name: "Matt", * } * ) */ - update( + updateCustomers( customerId: string, data: CustomerUpdatableFields, sharedContext?: Context @@ -128,14 +131,14 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} The updated customers. * * @example - * const customers = await customerModuleService.update( + * const customers = await customerModuleService.updateCustomers( * ["cus_123", "cus_321"], * { * company_name: "Acme", * } * ) */ - update( + updateCustomers( customerIds: string[], data: CustomerUpdatableFields, sharedContext?: Context @@ -150,14 +153,14 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} The updated customers. * * @example - * const customers = await customerModuleService.update( + * const customers = await customerModuleService.updateCustomers( * { company_name: "Acme" }, * { * company_name: "Acme Inc.", * } * ) */ - update( + updateCustomers( selector: FilterableCustomerProps, data: CustomerUpdatableFields, sharedContext?: Context @@ -171,9 +174,9 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} Resolves when the customer is deleted successfully. * * @example - * await customerModuleService.delete("cus_123") + * await customerModuleService.deleteCustomers("cus_123") */ - delete(customerId: string, sharedContext?: Context): Promise + deleteCustomers(customerId: string, sharedContext?: Context): Promise /** * This method deletes customers by their IDs. @@ -183,9 +186,9 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} Resolves when the customers are deleted successfully. * * @example - * await customerModuleService.delete(["cus_123", "cus_321"]) + * await customerModuleService.deleteCustomers(["cus_123", "cus_321"]) */ - delete(customerIds: string[], sharedContext?: Context): Promise + deleteCustomers(customerIds: string[], sharedContext?: Context): Promise /** * This method deletes a customer matching the specified filters. @@ -195,11 +198,11 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} Resolves when the customers are deleted successfully. * * @example - * await customerModuleService.delete({ + * await customerModuleService.deleteCustomers({ * id: ["cus_123"], * }) */ - delete( + deleteCustomers( selector: FilterableCustomerProps, sharedContext?: Context ): Promise @@ -211,18 +214,15 @@ export interface ICustomerModuleService extends IModuleService { * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @returns {Promise} The created customer groups. * - * @privateRemarks - * TODO should be pluralized - * * @example * const customerGroup = - * await customerModuleService.createCustomerGroup([ + * await customerModuleService.createCustomerGroups([ * { * name: "VIP", * }, * ]) */ - createCustomerGroup( + createCustomerGroups( data: CreateCustomerGroupDTO[], sharedContext?: Context ): Promise @@ -239,11 +239,11 @@ export interface ICustomerModuleService extends IModuleService { * * @example * const customerGroup = - * await customerModuleService.createCustomerGroup({ + * await customerModuleService.createCustomerGroups({ * name: "VIP", * }) */ - createCustomerGroup( + createCustomerGroups( data: CreateCustomerGroupDTO, sharedContext?: Context ): Promise @@ -259,7 +259,7 @@ export interface ICustomerModuleService extends IModuleService { * * @example * const customerGroup = - * await customerModuleService.retrieve("cusgroup_123") + * await customerModuleService.retrieveCustomerGroup("cusgroup_123") */ retrieveCustomerGroup( groupId: string, @@ -491,7 +491,7 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} The list of created addresses. * * @example - * const addresses = await customerModuleService.addAddresses([ + * const addresses = await customerModuleService.createAddresses([ * { * customer_id: "cus_123", * address_name: "Home", @@ -501,7 +501,7 @@ export interface ICustomerModuleService extends IModuleService { * }, * ]) */ - addAddresses( + createAddresses( addresses: CreateCustomerAddressDTO[], sharedContext?: Context ): Promise @@ -514,7 +514,7 @@ export interface ICustomerModuleService extends IModuleService { * @returns {Promise} The created address. * * @example - * const address = await customerModuleService.addAddresses({ + * const address = await customerModuleService.createAddresses({ * customer_id: "cus_123", * address_name: "Home", * address_1: "432 Stierlin Rd", @@ -522,7 +522,7 @@ export interface ICustomerModuleService extends IModuleService { * country_code: "us", * }) */ - addAddresses( + createAddresses( address: CreateCustomerAddressDTO, sharedContext?: Context ): Promise @@ -815,7 +815,7 @@ export interface ICustomerModuleService extends IModuleService { * To retrieve a list of customers using their IDs: * * ```ts - * const customers = await customerModuleService.list({ + * const customers = await customerModuleService.listCustomers({ * id: ["cus_123", "cus_321"], * }) * ``` @@ -823,7 +823,7 @@ export interface ICustomerModuleService extends IModuleService { * To specify relations that should be retrieved within the customers: * * ```ts - * const customers = await customerModuleService.list( + * const customers = await customerModuleService.listCustomers( * { * id: ["cus_123", "cus_321"], * }, @@ -836,7 +836,7 @@ export interface ICustomerModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const customers = await customerModuleService.list( + * const customers = await customerModuleService.listCustomers( * { * id: ["cus_123", "cus_321"], * }, @@ -848,7 +848,7 @@ export interface ICustomerModuleService extends IModuleService { * ) * ``` */ - list( + listCustomers( filters?: FilterableCustomerProps, config?: FindConfig, sharedContext?: Context @@ -867,7 +867,7 @@ export interface ICustomerModuleService extends IModuleService { * To retrieve a list of customers using their IDs: * * ```ts - * const [customers, count] = await customerModuleService.list({ + * const [customers, count] = await customerModuleService.listAndCountCustomers({ * id: ["cus_123", "cus_321"], * }) * ``` @@ -875,7 +875,7 @@ export interface ICustomerModuleService extends IModuleService { * To specify relations that should be retrieved within the customers: * * ```ts - * const [customers, count] = await customerModuleService.list( + * const [customers, count] = await customerModuleService.listAndCountCustomers( * { * id: ["cus_123", "cus_321"], * }, @@ -888,7 +888,7 @@ export interface ICustomerModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const [customers, count] = await customerModuleService.list( + * const [customers, count] = await customerModuleService.listAndCountCustomers( * { * id: ["cus_123", "cus_321"], * }, @@ -900,7 +900,7 @@ export interface ICustomerModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountCustomers( filters?: FilterableCustomerProps, config?: FindConfig, sharedContext?: Context @@ -1029,9 +1029,9 @@ export interface ICustomerModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await customerModuleService.softDelete(["cus_123"]) + * await customerModuleService.softDeleteCustomers(["cus_123"]) */ - softDelete( + softDeleteCustomers( customerIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -1048,9 +1048,9 @@ export interface ICustomerModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await customerModuleService.restore(["cus_123"]) + * await customerModuleService.restoreCustomers(["cus_123"]) */ - restore( + restoreCustomers( customerIds: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/file/service.ts b/packages/core/types/src/file/service.ts index 190926bf38..8e98141e10 100644 --- a/packages/core/types/src/file/service.ts +++ b/packages/core/types/src/file/service.ts @@ -16,13 +16,16 @@ export interface IFileModuleService extends IModuleService { * @returns {Promise} The created files. * * @example - * const [file] = await fileModuleService.create([{ + * const [file] = await fileModuleService.createFiles([{ * filename: "product.png", * mimeType: "image/png", * content: "somecontent" * }]) */ - create(data: CreateFileDTO[], sharedContext?: Context): Promise + createFiles( + data: CreateFileDTO[], + sharedContext?: Context + ): Promise /** * This method uploads a file to the designated file storage system. @@ -32,14 +35,14 @@ export interface IFileModuleService extends IModuleService { * @returns {Promise} The created file. * * @example - * const file = await fileModuleService.create({ + * const file = await fileModuleService.createFiles({ * filename: "product.png", * mimeType: "image/png", * content: "somecontent" * }) */ - create(data: CreateFileDTO, sharedContext?: Context): Promise + createFiles(data: CreateFileDTO, sharedContext?: Context): Promise /** * This method deletes files by their IDs. @@ -49,9 +52,9 @@ export interface IFileModuleService extends IModuleService { * @returns {Promise} Resolves when the files are deleted successfully. * * @example - * await fileModuleService.delete(["file_123"]) + * await fileModuleService.deleteFiles(["file_123"]) */ - delete(ids: string[], sharedContext?: Context): Promise + deleteFiles(ids: string[], sharedContext?: Context): Promise /** * This method deletes a file by its ID. @@ -61,9 +64,9 @@ export interface IFileModuleService extends IModuleService { * @returns {Promise} Resolves when the file is deleted successfully. * * @example - * await fileModuleService.delete("file_123") + * await fileModuleService.deleteFiles("file_123") */ - delete(id: string, sharedContext?: Context): Promise + deleteFiles(id: string, sharedContext?: Context): Promise /** * This method retrieves a file with a downloadable URL by its ID. @@ -75,9 +78,9 @@ export interface IFileModuleService extends IModuleService { * @returns {Promise} The retrieved file. * * @example - * const file = await fileModuleService.retrieve("file_123") + * const file = await fileModuleService.retrieveFile("file_123") */ - retrieve( + retrieveFile( id: string, config?: FindConfig, sharedContext?: Context @@ -94,7 +97,7 @@ export interface IFileModuleService extends IModuleService { * @returns {Promise} The list of files. In this particular case, it will either be at most one file. * */ - list( + listFiles( filters?: FilterableFileProps, config?: FindConfig, sharedContext?: Context @@ -111,7 +114,7 @@ export interface IFileModuleService extends IModuleService { * @returns {Promise<[FileDTO[], number]>} The list of files and their count. In this particular case, it will either be at most one file. * */ - listAndCount( + listAndCountFiles( filters?: FilterableFileProps, config?: FindConfig, sharedContext?: Context diff --git a/packages/core/types/src/fulfillment/service.ts b/packages/core/types/src/fulfillment/service.ts index b9015cc815..736435194d 100644 --- a/packages/core/types/src/fulfillment/service.ts +++ b/packages/core/types/src/fulfillment/service.ts @@ -40,7 +40,10 @@ import { UpsertShippingOptionDTO, } from "./mutations" import { CreateFulfillmentDTO } from "./mutations/fulfillment" -import { CreateShippingProfileDTO, UpsertShippingProfileDTO } from "./mutations/shipping-profile" +import { + CreateShippingProfileDTO, + UpsertShippingProfileDTO, +} from "./mutations/shipping-profile" /** * The main service interface for the Fulfillment Module. @@ -60,13 +63,13 @@ export interface IFulfillmentModuleService extends IModuleService { * * ```ts * const fulfillmentSet = - * await fulfillmentModuleService.retrieve("fuset_123") + * await fulfillmentModuleService.retrieveFulfillmentSet("fuset_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const fulfillmentSet = await fulfillmentModuleService.retrieve( + * const fulfillmentSet = await fulfillmentModuleService.retrieveFulfillmentSet( * "fuset_123", * { * relations: ["service_zones"], @@ -74,7 +77,7 @@ export interface IFulfillmentModuleService extends IModuleService { * ) * ``` */ - retrieve( + retrieveFulfillmentSet( id: string, config?: FindConfig, sharedContext?: Context @@ -93,7 +96,7 @@ export interface IFulfillmentModuleService extends IModuleService { * To retrieve a list of fulfillment sets using their IDs: * * ```ts - * const fulfillmentSets = await fulfillmentModuleService.list({ + * const fulfillmentSets = await fulfillmentModuleService.listFulfillmentSets({ * id: ["fuset_123", "fuset_321"], * }) * ``` @@ -101,7 +104,7 @@ export interface IFulfillmentModuleService extends IModuleService { * To specify relations that should be retrieved within the fulfillment set: * * ```ts - * const fulfillmentSets = await fulfillmentModuleService.list( + * const fulfillmentSets = await fulfillmentModuleService.listFulfillmentSets( * { * id: ["fuset_123", "fuset_321"], * }, @@ -114,7 +117,7 @@ export interface IFulfillmentModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const fulfillmentSets = await fulfillmentModuleService.list( + * const fulfillmentSets = await fulfillmentModuleService.listFulfillmentSets( * { * id: ["fuset_123", "fuset_321"], * }, @@ -126,7 +129,7 @@ export interface IFulfillmentModuleService extends IModuleService { * ) * ``` */ - list( + listFulfillmentSets( filters?: FilterableFulfillmentSetProps, config?: FindConfig, sharedContext?: Context @@ -146,7 +149,7 @@ export interface IFulfillmentModuleService extends IModuleService { * * ```ts * const [fulfillmentSets, count] = - * await fulfillmentModuleService.listAndCount({ + * await fulfillmentModuleService.listAndCountFulfillmentSets({ * id: ["fuset_123", "fuset_321"], * }) * ``` @@ -155,7 +158,7 @@ export interface IFulfillmentModuleService extends IModuleService { * * ```ts * const [fulfillmentSets, count] = - * await fulfillmentModuleService.listAndCount( + * await fulfillmentModuleService.listAndCountFulfillmentSets( * { * id: ["fuset_123", "fuset_321"], * }, @@ -169,7 +172,7 @@ export interface IFulfillmentModuleService extends IModuleService { * * ```ts * const [fulfillmentSets, count] = - * await fulfillmentModuleService.listAndCount( + * await fulfillmentModuleService.listAndCountFulfillmentSets( * { * id: ["fuset_123", "fuset_321"], * }, @@ -181,7 +184,7 @@ export interface IFulfillmentModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountFulfillmentSets( filters?: FilterableFulfillmentSetProps, config?: FindConfig, sharedContext?: Context @@ -195,7 +198,7 @@ export interface IFulfillmentModuleService extends IModuleService { * @returns {Promise} The created fulfillment sets. * * @example - * const fulfillmentSets = await fulfillmentModuleService.create( + * const fulfillmentSets = await fulfillmentModuleService.createFulfillmentSets( * [ * { * name: "Shipping", @@ -208,7 +211,7 @@ export interface IFulfillmentModuleService extends IModuleService { * ] * ) */ - create( + createFulfillmentSets( data: CreateFulfillmentSetDTO[], sharedContext?: Context ): Promise @@ -221,12 +224,12 @@ export interface IFulfillmentModuleService extends IModuleService { * @returns {Promise} The created fulfillment set. * * @example - * const fulfillmentSet = await fulfillmentModuleService.create({ + * const fulfillmentSet = await fulfillmentModuleService.createFulfillmentSets({ * name: "Shipping", * type: "default", * }) */ - create( + createFulfillmentSets( data: CreateFulfillmentSetDTO, sharedContext?: Context ): Promise @@ -239,7 +242,7 @@ export interface IFulfillmentModuleService extends IModuleService { * @returns {Promise} The updated fulfillment sets. * * @example - * const fulfillmentSets = await fulfillmentModuleService.update( + * const fulfillmentSets = await fulfillmentModuleService.updateFulfillmentSets( * [ * { * id: "fuset_123", @@ -252,7 +255,7 @@ export interface IFulfillmentModuleService extends IModuleService { * ] * ) */ - update( + updateFulfillmentSets( data: UpdateFulfillmentSetDTO[], sharedContext?: Context ): Promise @@ -265,12 +268,12 @@ export interface IFulfillmentModuleService extends IModuleService { * @returns {Promise} The updated fulfillment set. * * @example - * const fulfillmentSet = await fulfillmentModuleService.update({ + * const fulfillmentSet = await fulfillmentModuleService.updateFulfillmentSets({ * id: "fuset_123", * name: "Shipping", * }) */ - update( + updateFulfillmentSets( data: UpdateFulfillmentSetDTO, sharedContext?: Context ): Promise @@ -283,12 +286,12 @@ export interface IFulfillmentModuleService extends IModuleService { * @returns {Promise} Resolves when the fulfillment sets are deleted successfully. * * @example - * await fulfillmentModuleService.delete([ + * await fulfillmentModuleService.deleteFulfillmentSets([ * "fuset_123", * "fuset_321", * ]) */ - delete(ids: string[], sharedContext?: Context): Promise + deleteFulfillmentSets(ids: string[], sharedContext?: Context): Promise /** * This method deletes a fulfillment set by its ID. @@ -298,9 +301,9 @@ export interface IFulfillmentModuleService extends IModuleService { * @returns {Promise} Resolves when the fulfillment set is deleted successfully. * * @example - * await fulfillmentModuleService.delete("fuset_123") + * await fulfillmentModuleService.deleteFulfillmentSets("fuset_123") */ - delete(id: string, sharedContext?: Context): Promise + deleteFulfillmentSets(id: string, sharedContext?: Context): Promise /** * This method soft deletes fulfillment sets by their IDs. @@ -312,12 +315,12 @@ export interface IFulfillmentModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await fulfillmentModuleService.softDelete([ + * await fulfillmentModuleService.softDeleteFulfillmentSets([ * "fuset_123", * "fuset_321", * ]) */ - softDelete( + softDeleteFulfillmentSets( fulfillmentIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -334,12 +337,12 @@ export interface IFulfillmentModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await fulfillmentModuleService.restore([ + * await fulfillmentModuleService.restoreFulfillmentSets([ * "fuset_123", * "fuset_321", * ]) */ - restore( + restoreFulfillmentSets( fulfillmentIds: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/inventory/bundle.ts b/packages/core/types/src/inventory/bundle.ts deleted file mode 100644 index b2e00cf768..0000000000 --- a/packages/core/types/src/inventory/bundle.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./common/index" -export * from "./mutations" diff --git a/packages/core/types/src/inventory/common.ts b/packages/core/types/src/inventory/common.ts deleted file mode 100644 index c17b3365b7..0000000000 --- a/packages/core/types/src/inventory/common.ts +++ /dev/null @@ -1,511 +0,0 @@ -import { - NumericalComparisonOperator, - StringComparisonOperator, -} from "../common" - -/** - * @schema InventoryItemDTO - * type: object - * required: - * - sku - * properties: - * id: - * description: The inventory item's ID. - * type: string - * example: "iitem_12334" - * sku: - * description: The Stock Keeping Unit (SKU) code of the Inventory Item. - * type: string - * hs_code: - * description: The Harmonized System code of the Inventory Item. May be used by Fulfillment Providers to pass customs information to shipping carriers. - * type: string - * origin_country: - * description: The country in which the Inventory Item was produced. May be used by Fulfillment Providers to pass customs information to shipping carriers. - * type: string - * mid_code: - * description: The Manufacturers Identification code that identifies the manufacturer of the Inventory Item. May be used by Fulfillment Providers to pass customs information to shipping carriers. - * type: string - * title: - * description: "Title of the inventory item" - * type: string - * description: - * description: "Description of the inventory item" - * type: string - * thumbnail: - * description: "Thumbnail for the inventory item" - * type: string - * material: - * description: The material and composition that the Inventory Item is made of, May be used by Fulfillment Providers to pass customs information to shipping carriers. - * type: string - * weight: - * description: The weight of the Inventory Item. May be used in shipping rate calculations. - * type: number - * height: - * description: The height of the Inventory Item. May be used in shipping rate calculations. - * type: number - * width: - * description: The width of the Inventory Item. May be used in shipping rate calculations. - * type: number - * length: - * description: The length of the Inventory Item. May be used in shipping rate calculations. - * type: number - * requires_shipping: - * description: Whether the item requires shipping. - * type: boolean - * metadata: - * type: object - * description: An optional key-value map with additional details - * example: {car: "white"} - * created_at: - * type: string - * description: "The date with timezone at which the resource was created." - * format: date-time - * updated_at: - * type: string - * description: "The date with timezone at which the resource was updated." - * format: date-time - * deleted_at: - * type: string - * description: "The date with timezone at which the resource was deleted." - * format: date-time - */ -export type InventoryItemDTO = { - id: string - sku?: string | null - origin_country?: string | null - hs_code?: string | null - requires_shipping: boolean - mid_code?: string | null - material?: string | null - weight?: number | null - length?: number | null - height?: number | null - width?: number | null - title?: string | null - description?: string | null - thumbnail?: string | null - metadata?: Record | null - created_at: string | Date - updated_at: string | Date - deleted_at: string | Date | null - location_levels?: InventoryLevelDTO[] -} - -/** - * @schema ReservationItemDTO - * title: "Reservation item" - * description: "Represents a reservation of an inventory item at a stock location" - * type: object - * required: - * - id - * - location_id - * - inventory_item_id - * - quantity - * properties: - * id: - * description: "The id of the reservation item" - * type: string - * location_id: - * description: "The id of the location of the reservation" - * type: string - * inventory_item_id: - * description: "The id of the inventory item the reservation relates to" - * type: string - * description: - * description: "Description of the reservation item" - * type: string - * created_by: - * description: "UserId of user who created the reservation item" - * type: string - * quantity: - * description: "The id of the reservation item" - * type: number - * metadata: - * type: object - * description: An optional key-value map with additional details - * example: {car: "white"} - * created_at: - * type: string - * description: "The date with timezone at which the resource was created." - * format: date-time - * updated_at: - * type: string - * description: "The date with timezone at which the resource was updated." - * format: date-time - * deleted_at: - * type: string - * description: "The date with timezone at which the resource was deleted." - * format: date-time - */ -export type ReservationItemDTO = { - id: string - location_id: string - inventory_item_id: string - quantity: number - line_item_id?: string | null - description?: string | null - created_by?: string | null - allow_backorder?: boolean - metadata: Record | null - created_at: string | Date - updated_at: string | Date - deleted_at: string | Date | null -} - -/** - * @schema InventoryLevelDTO - * type: object - * required: - * - inventory_item_id - * - location_id - * - stocked_quantity - * - reserved_quantity - * - incoming_quantity - * properties: - * location_id: - * description: the item location ID - * type: string - * stocked_quantity: - * description: the total stock quantity of an inventory item at the given location ID - * type: number - * reserved_quantity: - * description: the reserved stock quantity of an inventory item at the given location ID - * type: number - * incoming_quantity: - * description: the incoming stock quantity of an inventory item at the given location ID - * type: number - * metadata: - * type: object - * description: An optional key-value map with additional details - * example: {car: "white"} - * created_at: - * type: string - * description: "The date with timezone at which the resource was created." - * format: date-time - * updated_at: - * type: string - * description: "The date with timezone at which the resource was updated." - * format: date-time - * deleted_at: - * type: string - * description: "The date with timezone at which the resource was deleted." - * format: date-time - */ -export type InventoryLevelDTO = { - id: string - inventory_item_id: string - location_id: string - stocked_quantity: number - reserved_quantity: number - available_quantity: number - incoming_quantity: number - metadata: Record | null - created_at: string | Date - updated_at: string | Date - deleted_at: string | Date | null -} - -/** - * @interface - * - * The filters to apply on retrieved reservation items. - */ -export type FilterableReservationItemProps = { - /** - * The IDs to filter reservation items by. - */ - id?: string | string[] - /** - * @ignore - * - * @privateRemark - * This property is not used. - */ - type?: string | string[] - /** - * Filter reservation items by the ID of their associated line item. - */ - line_item_id?: string | string[] - /** - * Filter reservation items by the ID of their associated inventory item. - */ - inventory_item_id?: string | string[] - /** - * Filter reservation items by the ID of their associated location. - */ - location_id?: string | string[] - /** - * Description filters to apply on the reservation items' `description` attribute. - */ - description?: string | StringComparisonOperator - /** - * The "created by" values to filter reservation items by. - */ - created_by?: string | string[] - /** - * Filters to apply on the reservation items' `quantity` attribute. - */ - quantity?: number | NumericalComparisonOperator -} - -/** - * @interface - * - * The filters to apply on retrieved inventory items. - */ -export type FilterableInventoryItemProps = { - /** - * The IDs to filter inventory items by. - */ - id?: string | string[] - /** - * Filter inventory items by the ID of their associated location. - */ - location_id?: string | string[] - /** - * Search term to search inventory items' attributes. - */ - q?: string - /** - * The SKUs to filter inventory items by. - */ - sku?: string | string[] | StringComparisonOperator - /** - * The origin country to filter inventory items by. - */ - origin_country?: string | string[] - /** - * The HS Codes to filter inventory items by. - */ - hs_code?: string | string[] | StringComparisonOperator - /** - * Filter inventory items by whether they require shipping. - */ - requires_shipping?: boolean -} - -export interface UpdateInventoryItemInput - extends Partial { - id: string -} -/** - * @interface - * - * The details of the inventory item to be created. - */ -export interface CreateInventoryItemInput { - /** - * The SKU of the inventory item. - */ - sku?: string | null - /** - * The origin country of the inventory item. - */ - origin_country?: string | null - /** - * The MID code of the inventory item. - */ - mid_code?: string | null - /** - * The material of the inventory item. - */ - material?: string | null - /** - * The weight of the inventory item. - */ - weight?: number | null - /** - * The length of the inventory item. - */ - length?: number | null - /** - * The height of the inventory item. - */ - height?: number | null - /** - * The width of the inventory item. - */ - width?: number | null - /** - * The title of the inventory item. - */ - title?: string | null - /** - * The description of the inventory item. - */ - description?: string | null - /** - * The thumbnail of the inventory item. - */ - thumbnail?: string | null - /** - * Holds custom data in key-value pairs. - */ - metadata?: Record | null - /** - * The HS code of the inventory item. - */ - hs_code?: string | null - /** - * Whether the inventory item requires shipping. - */ - requires_shipping?: boolean -} - -/** - * @interface - * - * The details of the reservation item to be created. - */ -export type CreateReservationItemInput = { - /** - * The ID of the associated line item. - */ - line_item_id?: string - /** - * The ID of the associated inventory item. - */ - inventory_item_id: string - /** - * The ID of the associated location. - */ - location_id: string - /** - * The reserved quantity. - */ - quantity: number - /** - * The description of the reservation. - */ - description?: string - /** - * The user or system that created the reservation. Can be any form of identification string. - */ - created_by?: string - /** - * An ID associated with an external third-party system that the reservation item is connected to. - */ - external_id?: string - /** - * Holds custom data in key-value pairs. - */ - metadata?: Record | null -} - -/** - * @interface - * - * The filters to apply on retrieved inventory levels. - */ -export type FilterableInventoryLevelProps = { - /** - * Filter inventory levels by the ID of their associated inventory item. - */ - inventory_item_id?: string | string[] - /** - * Filter inventory levels by the ID of their associated inventory location. - */ - location_id?: string | string[] - /** - * Filters to apply on inventory levels' `stocked_quantity` attribute. - */ - stocked_quantity?: number | NumericalComparisonOperator - /** - * Filters to apply on inventory levels' `reserved_quantity` attribute. - */ - reserved_quantity?: number | NumericalComparisonOperator - /** - * Filters to apply on inventory levels' `incoming_quantity` attribute. - */ - incoming_quantity?: number | NumericalComparisonOperator -} - -/** - * @interface - * - * The details of the inventory level to be created. - */ -export type CreateInventoryLevelInput = { - /** - * The ID of the associated inventory item. - */ - inventory_item_id: string - /** - * The ID of the associated location. - */ - location_id: string - /** - * The stocked quantity of the associated inventory item in the associated location. - */ - stocked_quantity: number - /** - * The reserved quantity of the associated inventory item in the associated location. - */ - reserved_quantity?: number - /** - * The incoming quantity of the associated inventory item in the associated location. - */ - incoming_quantity?: number -} - -/** - * @interface - * - * The attributes to update in an inventory level. - */ -export type UpdateInventoryLevelInput = { - /** - * The stocked quantity of the associated inventory item in the associated location. - */ - stocked_quantity?: number - /** - * The incoming quantity of the associated inventory item in the associated location. - */ - incoming_quantity?: number -} - -/** - * @interface - * - * The attributes to update in an inventory level. The inventory level is identified by the IDs of its associated inventory item and location. - */ -export type BulkUpdateInventoryLevelInput = { - /** - * The ID of the associated inventory level. - */ - inventory_item_id: string - /** - * The ID of the associated location. - */ - location_id: string -} & UpdateInventoryLevelInput - -/** - * @interface - * - * The attributes to update in a reservation item. - */ -export type UpdateReservationItemInput = { - /** - * The reserved quantity. - */ - quantity?: number - /** - * The ID of the associated location. - */ - location_id?: string - /** - * The description of the reservation item. - */ - description?: string - /** - * Holds custom data in key-value pairs. - */ - metadata?: Record | null -} - -export type ReserveQuantityContext = { - locationId?: string - lineItemId?: string - salesChannelId?: string | null -} diff --git a/packages/core/types/src/inventory/index.ts b/packages/core/types/src/inventory/index.ts index 3b728a9630..0c73656566 100644 --- a/packages/core/types/src/inventory/index.ts +++ b/packages/core/types/src/inventory/index.ts @@ -1,4 +1,3 @@ -export * as InventoryNext from "./bundle" export * from "./common" +export * from "./mutations" export * from "./service" -export * from "./service-next" diff --git a/packages/core/types/src/inventory/service-next.ts b/packages/core/types/src/inventory/service-next.ts deleted file mode 100644 index e57df93213..0000000000 --- a/packages/core/types/src/inventory/service-next.ts +++ /dev/null @@ -1,1127 +0,0 @@ -import { RestoreReturn, SoftDeleteReturn } from "../dal" - -import { InventoryNext } from "." -import { FindConfig } from "../common" -import { IModuleService } from "../modules-sdk" -import { Context } from "../shared-context" - -/** - * The main service interface for the Inventory Module. - */ -export interface IInventoryServiceNext extends IModuleService { - /** - * This method retrieves a paginated list of inventory items based on optional filters and configuration. - * - * @param {FilterableInventoryItemProps} selector - The filters to apply on the retrieved inventory items. - * @param {FindConfig} config - The configurations determining how the inventory item is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a inventory item. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The list of inventory items. - * - * @example - * To retrieve a list of inventory items using their IDs: - * - * ```ts - * const inventoryItems = await inventoryModuleService.list({ - * id: ["iitem_123", "iitem_321"], - * }) - * ``` - * - * To specify relations that should be retrieved within the inventory items: - * - * ```ts - * const inventoryItems = await inventoryModuleService.list( - * { - * id: ["iitem_123", "iitem_321"], - * }, - * { - * relations: ["location_levels"], - * } - * ) - * ``` - * - * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: - * - * ```ts - * const inventoryItems = await inventoryModuleService.list( - * { - * id: ["iitem_123", "iitem_321"], - * }, - * { - * relations: ["location_levels"], - * take: 20, - * skip: 2, - * } - * ) - * ``` - */ - list( - selector: InventoryNext.FilterableInventoryItemProps, - config?: FindConfig, - context?: Context - ): Promise - - /** - * This method retrieves a paginated list of inventory items along with the total count of available inventory items satisfying the provided filters. - * - * @param {FilterableInventoryItemProps} selector - The filters to apply on the retrieved inventory items. - * @param {FindConfig} config - The configurations determining how the inventory item is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a inventory item. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise<[InventoryItemDTO[], number]>} The list of inventory items along with their total count. - * - * @example - * To retrieve a list of inventory items using their IDs: - * - * ```ts - * const [inventoryItems, count] = - * await inventoryModuleService.listAndCount({ - * id: ["iitem_123", "iitem_321"], - * }) - * ``` - * - * To specify relations that should be retrieved within the inventory items: - * - * ```ts - * const [inventoryItems, count] = - * await inventoryModuleService.listAndCount( - * { - * id: ["iitem_123", "iitem_321"], - * }, - * { - * relations: ["location_levels"], - * } - * ) - * ``` - * - * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: - * - * ```ts - * const [inventoryItems, count] = - * await inventoryModuleService.listAndCount( - * { - * id: ["iitem_123", "iitem_321"], - * }, - * { - * relations: ["location_levels"], - * take: 20, - * skip: 2, - * } - * ) - * ``` - */ - listAndCount( - selector: InventoryNext.FilterableInventoryItemProps, - config?: FindConfig, - context?: Context - ): Promise<[InventoryNext.InventoryItemDTO[], number]> - - /** - * This method retrieves a paginated list of reservation items based on optional filters and configuration. - * - * @param {FilterableReservationItemProps} selector - The filters to apply on the retrieved reservation items. - * @param {FindConfig} config - The configurations determining how the reservation item is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a reservation item. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The list of reservation items. - * - * @example - * To retrieve a list of reservation items using their IDs: - * - * ```ts - * const reservationItems = - * await inventoryModuleService.listReservationItems({ - * id: ["resitem_123", "resitem_321"], - * }) - * ``` - * - * To specify relations that should be retrieved within the reservation items: - * - * ```ts - * const reservationItems = - * await inventoryModuleService.listReservationItems( - * { - * id: ["resitem_123", "resitem_321"], - * }, - * { - * relations: ["inventory_item"], - * } - * ) - * ``` - * - * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: - * - * ```ts - * const reservationItems = - * await inventoryModuleService.listReservationItems( - * { - * id: ["resitem_123", "resitem_321"], - * }, - * { - * relations: ["inventory_item"], - * take: 20, - * skip: 2, - * } - * ) - * ``` - */ - listReservationItems( - selector: InventoryNext.FilterableReservationItemProps, - config?: FindConfig, - context?: Context - ): Promise - - /** - * This method retrieves a paginated list of reservation items along with the total count of available reservation items satisfying the provided filters. - * - * @param {FilterableReservationItemProps} selector - The filters to apply on the retrieved reservation items. - * @param {FindConfig} config - The configurations determining how the reservation item is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a reservation item. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise<[ReservationItemDTO[], number]>} The list of reservation items along with their total count. - * - * @example - * To retrieve a list of reservation items using their IDs: - * - * ```ts - * const [reservationItems, count] = - * await inventoryModuleService.listAndCountReservationItems({ - * id: ["resitem_123", "resitem_321"], - * }) - * ``` - * - * To specify relations that should be retrieved within the reservation items: - * - * ```ts - * const [reservationItems, count] = - * await inventoryModuleService.listAndCountReservationItems( - * { - * id: ["resitem_123", "resitem_321"], - * }, - * { - * relations: ["inventory_item"], - * } - * ) - * ``` - * - * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: - * - * ```ts - * const [reservationItems, count] = - * await inventoryModuleService.listAndCountReservationItems( - * { - * id: ["resitem_123", "resitem_321"], - * }, - * { - * relations: ["inventory_item"], - * take: 20, - * skip: 2, - * } - * ) - * ``` - */ - listAndCountReservationItems( - selector: InventoryNext.FilterableReservationItemProps, - config?: FindConfig, - context?: Context - ): Promise<[InventoryNext.ReservationItemDTO[], number]> - - /** - * This method retrieves a paginated list of inventory levels based on optional filters and configuration. - * - * @param {FilterableInventoryLevelProps} selector - The filters to apply on the retrieved inventory levels. - * @param {FindConfig} config - The configurations determining how the inventory level is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a inventory level. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The list of inventory levels. - * - * @example - * To retrieve a list of inventory levels using the IDs of their associated inventory items: - * - * ```ts - * const inventoryLevels = - * await inventoryModuleService.listInventoryLevels({ - * inventory_item_id: ["iitem_123", "iitem_321"], - * }) - * ``` - * - * To specify relations that should be retrieved within the inventory levels: - * - * ```ts - * const inventoryLevels = - * await inventoryModuleService.listInventoryLevels( - * { - * inventory_item_id: ["iitem_123", "iitem_321"], - * }, - * { - * relations: ["inventory_item"], - * } - * ) - * ``` - * - * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: - * - * ```ts - * const inventoryLevels = - * await inventoryModuleService.listInventoryLevels( - * { - * inventory_item_id: ["iitem_123", "iitem_321"], - * }, - * { - * relations: ["inventory_item"], - * take: 20, - * skip: 2, - * } - * ) - * ``` - */ - listInventoryLevels( - selector: InventoryNext.FilterableInventoryLevelProps, - config?: FindConfig, - context?: Context - ): Promise - - /** - * This method retrieves a paginated list of inventory levels along with the total count of available inventory levels satisfying the provided filters. - * - * @param {FilterableInventoryLevelProps} selector - The filters to apply on the retrieved inventory levels. - * @param {FindConfig} config - The configurations determining how the inventory level is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a inventory level. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise<[InventoryLevelDTO[], number]>} The list of inventory levels along with their total count. - * - * @example - * To retrieve a list of inventory levels using the IDs of their associated inventory items: - * - * ```ts - * const [inventoryLevels, count] = - * await inventoryModuleService.listAndCountInventoryLevels( - * { - * inventory_item_id: ["iitem_123", "iitem_321"], - * }, - * { - * relations: ["inventory_item"], - * take: 20, - * skip: 2, - * } - * ) - * ``` - * - * To specify relations that should be retrieved within the inventory levels: - * - * ```ts - * const [inventoryLevels, count] = - * await inventoryModuleService.listAndCountInventoryLevels( - * { - * inventory_item_id: ["iitem_123", "iitem_321"], - * }, - * { - * relations: ["inventory_item"], - * } - * ) - * ``` - * - * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: - * - * ```ts - * const [inventoryLevels, count] = - * await inventoryModuleService.listAndCountInventoryLevels({ - * inventory_item_id: ["iitem_123", "iitem_321"], - * }) - * ``` - */ - listAndCountInventoryLevels( - selector: InventoryNext.FilterableInventoryLevelProps, - config?: FindConfig, - context?: Context - ): Promise<[InventoryNext.InventoryLevelDTO[], number]> - - /** - * This method retrieves an inventory item by its ID. - * - * @param {string} inventoryItemId - The inventory item's ID. - * @param {FindConfig} config - The configurations determining how the inventory item is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a inventory item. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The retrieved inventory item. - * - * @example - * A simple example that retrieves a inventory item by its ID: - * - * ```ts - * const inventoryItem = - * await inventoryModuleService.retrieve("iitem_123") - * ``` - * - * To specify relations that should be retrieved: - * - * ```ts - * const inventoryItem = await inventoryModuleService.retrieve( - * "iitem_123", - * { - * relations: ["location_levels"], - * } - * ) - * ``` - */ - retrieve( - inventoryItemId: string, - config?: FindConfig, - context?: Context - ): Promise - - /** - * This method retrieves an inventory level based on its associated inventory item and location. - * - * @param {string} inventoryItemId - The inventory item's ID. - * @param {string} locationId - The location's ID. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The retrieved inventory level. - * - * @example - * const inventoryLevel = - * await inventoryModuleService.retrieveInventoryLevelByItemAndLocation( - * "iitem_123", - * "loc_123" - * ) - */ - retrieveInventoryLevelByItemAndLocation( - inventoryItemId: string, - locationId: string, - context?: Context - ): Promise - - /** - * This method retrieves an inventory level by its ID. - * - * @param {string} inventoryLevelId - The inventory level's ID. - * @param {FindConfig} config - The configurations determining how the inventory level is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a inventory level. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The retrieved inventory level. - * - * @example - * A simple example that retrieves a inventory level by its ID: - * - * ```ts - * const inventoryLevel = - * await inventoryModuleService.retrieveInventoryLevel( - * "iitem_123" - * ) - * ``` - * - * To specify relations that should be retrieved: - * - * ```ts - * const inventoryLevel = - * await inventoryModuleService.retrieveInventoryLevel( - * "iitem_123", - * { - * relations: ["inventory_item"], - * } - * ) - * ``` - */ - retrieveInventoryLevel( - inventoryLevelId: string, - config?: FindConfig, - context?: Context - ): Promise - - /** - * This method retrieves a reservation item by its ID. - * - * @param {string} reservationId - The reservation's ID. - * @param {FindConfig} config - The configurations determining how the reservation item is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a reservation item. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The retrieved reservation item. - * - * @example - * A simple example that retrieves a reservation item by its ID: - * - * ```ts - * const reservationItem = - * await inventoryModuleService.retrieveReservationItem( - * "resitem" - * ) - * ``` - * - * To specify relations that should be retrieved: - * - * ```ts - * const reservationItem = - * await inventoryModuleService.retrieveReservationItem( - * "resitem", - * { - * relations: ["inventory_item"], - * } - * ) - * ``` - */ - retrieveReservationItem( - reservationId: string, - config?: FindConfig, - context?: Context - ): Promise - - /** - * This method creates reservation items. - * - * @param {CreateReservationItemInput[]} input - The details of the reservation items to be created. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created reservation items. - * - * @example - * const reservationItems = - * await inventoryModuleService.createReservationItems([ - * { - * inventory_item_id: "iitem_123", - * location_id: "loc_123", - * quantity: 10, - * }, - * ]) - */ - createReservationItems( - input: InventoryNext.CreateReservationItemInput[], - context?: Context - ): Promise - - /** - * This method creates a reservation item. - * - * @param {CreateReservationItemInput} input - The details of the reservation item to be created. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created reservation item. - * - * @example - * const reservationItem = - * await inventoryModuleService.createReservationItems({ - * inventory_item_id: "iitem_123", - * location_id: "loc_123", - * quantity: 10, - * }) - */ - createReservationItems( - input: InventoryNext.CreateReservationItemInput, - context?: Context - ): Promise - - /** - * This method creates inventory items. - * - * @param {CreateInventoryItemInput[]} input - The details of the inventory items to be created. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created inventory items. - * - * @example - * const inventoryItems = await inventoryModuleService.create([ - * { - * sku: "SHIRT", - * }, - * ]) - */ - create( - input: InventoryNext.CreateInventoryItemInput[], - context?: Context - ): Promise - - /** - * This method creates an inventory item. - * - * @param {CreateInventoryItemInput} input - The details of the inventory item to be created. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created inventory item. - * - * @example - * const inventoryItem = await inventoryModuleService.create({ - * sku: "SHIRT", - * }) - */ - create( - input: InventoryNext.CreateInventoryItemInput, - context?: Context - ): Promise - - /** - * This method creates inventory levels. - * - * @param {CreateInventoryLevelInput[]} data - The details of the inventory levels to be created. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created inventory levels. - * - * @example - * const inventoryLevels = - * await inventoryModuleService.createInventoryLevels([ - * { - * inventory_item_id: "iitem_123", - * location_id: "loc_123", - * stocked_quantity: 10, - * }, - * { - * inventory_item_id: "iitem_321", - * location_id: "loc_321", - * stocked_quantity: 20, - * reserved_quantity: 10, - * }, - * ]) - */ - createInventoryLevels( - data: InventoryNext.CreateInventoryLevelInput[], - context?: Context - ): Promise - - /** - * This method creates an inventory level. - * - * @param {CreateInventoryLevelInput} data - The details of the inventory level to be created. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created inventory level. - * - * @example - * const inventoryLevels = - * await inventoryModuleService.createInventoryLevels({ - * inventory_item_id: "iitem_123", - * location_id: "loc_123", - * stocked_quantity: 10, - * }) - */ - createInventoryLevels( - data: InventoryNext.CreateInventoryLevelInput, - context?: Context - ): Promise - - /** - * This method updates existing inventory levels. - * - * @param {BulkUpdateInventoryLevelInput[]} updates - The list of The attributes to update in an inventory level. The inventory level is identified by the IDs of its associated inventory item and location. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated inventory levels. - * - * @example - * const inventoryLevels = - * await inventoryModuleService.updateInventoryLevels([ - * { - * inventory_item_id: "iitem_123", - * location_id: "loc_123", - * id: "ilev_123", - * stocked_quantity: 20, - * }, - * ]) - */ - updateInventoryLevels( - updates: InventoryNext.BulkUpdateInventoryLevelInput[], - context?: Context - ): Promise - - /** - * This method updates an existing inventory level. - * - * @param {BulkUpdateInventoryLevelInput} updates - The attributes to update in an inventory level. The inventory level is identified by the IDs of its associated inventory item and location. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated inventory level. - * - * @example - * const inventoryLevel = - * await inventoryModuleService.updateInventoryLevels({ - * inventory_item_id: "iitem_123", - * location_id: "loc_123", - * stocked_quantity: 20, - * }) - */ - updateInventoryLevels( - updates: InventoryNext.BulkUpdateInventoryLevelInput, - context?: Context - ): Promise - - /** - * This method updates an existing inventory item. - * - * @param {UpdateInventoryItemInput} input - The attributes to update in the inventory item. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated inventory item. - * - * @example - * const inventoryItem = await inventoryModuleService.update({ - * id: "iitem_123", - * title: "Medusa Shirt Inventory", - * }) - */ - update( - input: InventoryNext.UpdateInventoryItemInput, - context?: Context - ): Promise - - /** - * This method updates existing inventory items. - * - * @param {UpdateInventoryItemInput[]} input - The attributes to update in the inventory items. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated inventory items. - * - * @example - * const inventoryItems = await inventoryModuleService.update([ - * { - * id: "iitem_123", - * title: "Medusa Shirt Inventory", - * }, - * { - * id: "iitem_321", - * description: "The inventory of Medusa pants", - * }, - * ]) - */ - update( - input: InventoryNext.UpdateInventoryItemInput[], - context?: Context - ): Promise - - /** - * This method updates an existing reservation item. - * - * @param {UpdateReservationItemInput} input - The attributes to update in a reservation item. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated reservation item. - * - * @example - * const reservationItem = - * await inventoryModuleService.updateReservationItems({ - * id: "resitem_123", - * quantity: 10, - * }) - */ - updateReservationItems( - input: InventoryNext.UpdateReservationItemInput, - context?: Context - ): Promise - - /** - * This method updates existing reservation items. - * - * @param {UpdateReservationItemInput[]} input - The attributes to update in the reservation items. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated reservation items. - * - * @example - * const reservationItems = - * await inventoryModuleService.updateReservationItems([ - * { - * id: "resitem_123", - * quantity: 10, - * }, - * ]) - */ - updateReservationItems( - input: InventoryNext.UpdateReservationItemInput[], - context?: Context - ): Promise - - /** - * This method deletes a reservation item by its associated line item. - * - * @param {string | string[]} lineItemId - The line item's ID. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the reservation item is deleted. - * - * @example - * await inventoryModuleService.deleteReservationItemByLocationId( - * "cali_123" - * ) - */ - deleteReservationItemsByLineItem( - lineItemId: string | string[], - context?: Context - ): Promise - - /** - * This method is used to restore the reservation items associated with a line item or multiple line items that were deleted. - * - * @param {string | string[]} lineItemId - The ID(s) of the line item(s). - * @param {SharedContext} context - A context used to share re9sources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the reservation items are successfully deleted. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function restoreReservationItemsByLineItem ( - * lineItemIds: string[] - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * await inventoryModule.restoreReservationItemsByLineItem( - * lineItemIds - * ) - * } - */ - restoreReservationItemsByLineItem( - lineItemId: string | string[], - context?: Context - ): Promise - - /** - * This method deletes reservation items by their IDs. - * - * @param {string | string[]} reservationItemId - The reservation items' IDs. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the reservation item is deleted. - * - * @example - * await inventoryModuleService.deleteReservationItems( - * "resitem_123" - * ) - */ - deleteReservationItems( - reservationItemId: string | string[], - context?: Context - ): Promise - - /** - * This method soft deletes reservations by their IDs. - * - * @param {string[]} inventoryLevelIds - The reservations' IDs. - * @param {SoftDeleteReturn} config - An object that is used to specify an entity's related entities that should be soft-deleted when the main entity is soft-deleted. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise>} An object that includes the IDs of related records that were also soft deleted. - * If there are no related records, the promise resolves to `void`. - * - * @example - * await inventoryModuleService.softDeleteReservationItems([ - * "ilev_123", - * ]) - */ - softDeleteReservationItems( - ReservationItemIds: string[], - config?: SoftDeleteReturn, - sharedContext?: Context - ): Promise | void> - - /** - * This method restores soft deleted reservations by their IDs. - * - * @param {string[]} ReservationItemIds - The reservations' IDs. - * @param {RestoreReturn} config - Configurations determining which relations to restore along with each of the reservation. You can pass to its `returnLinkableKeys` - * property any of the reservation's relation attribute names, such as `{type relation name}`. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise>} An object that includes the IDs of related records that were restored. - * If there are no related records restored, the promise resolves to `void`. - * - * @example - * await inventoryModuleService.restoreReservationItems([ - * "ilev_123", - * ]) - */ - restoreReservationItems( - ReservationItemIds: string[], - config?: RestoreReturn, - sharedContext?: Context - ): Promise | void> - - /** - * This method deletes inventory items by their IDs. - * - * @param {string | string[]} inventoryItemId - The inventory item's ID. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the inventory items are deleted. - * - * @example - * await inventoryModuleService.delete("iitem_123") - */ - delete(inventoryItemId: string | string[], context?: Context): Promise - - /** - * This method soft deletes inventory items by their IDs. - * - * @param {string[]} inventoryItemIds - The inventory items' IDs. - * @param {SoftDeleteReturn} config - An object that is used to specify an entity's related entities that should be soft-deleted when the main entity is soft-deleted. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise>} An object that includes the IDs of related records that were also soft deleted, such as the ID of the associated location levels. - * The object's keys are the ID attribute names of the inventory service next entity's relations, such as `location_level_id`, and its value is an array of strings, each being the ID of a record associated - * with the inventory item through this relation, such as the IDs of associated location levels. - * - * If there are no related records, the promise resolves to `void`. - * - * @example - * await inventoryModuleService.softDelete( - * ["iitem_123", "iitem_321"], - * { - * returnLinkableKeys: ["location_level"], - * } - * ) - */ - softDelete( - inventoryItemIds: string[], - config?: SoftDeleteReturn, - sharedContext?: Context - ): Promise | void> - - /** - * This method restores soft deleted inventory items by their IDs. - * - * @param {string[]} inventoryItemIds - The inventory items' IDs. - * @param {RestoreReturn} config - Configurations determining which relations to restore along with each of the inventory items. You can pass to its `returnLinkableKeys` - * property any of the inventory item's relation attribute names, such as `location_levels`. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise>} An object that includes the IDs of related records that were restored, such as the ID of associated location levels. - * The object's keys are the ID attribute names of the inventory item entity's relations, such as `location_level_id`, - * and its value is an array of strings, each being the ID of the record associated with the inventory item through this relation, - * such as the IDs of associated location levels. - * - * If there are no related records restored, the promise resolves to `void`. - * - * @example - * await inventoryModuleService.restore( - * ["iitem_123", "iitem_321"], - * { - * returnLinkableKeys: ["location_level"], - * } - * ) - */ - restore( - inventoryItemIds: string[], - config?: RestoreReturn, - sharedContext?: Context - ): Promise | void> - - /** - * This method soft deletes inventory item's level by the associated location. - * - * @param {string | string[]} locationId - The locations' IDs. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise<[object[], Record]>} An array, where the first item is an array includes the soft-deleted inventory levels, - * and the second is an object that includes the IDs of related records that were soft-deleted. - * - * @example - * await inventoryModuleService.deleteInventoryItemLevelByLocationId( - * "loc_123" - * ) - */ - deleteInventoryItemLevelByLocationId( - locationId: string | string[], - context?: Context - ): Promise<[object[], Record]> - - /** - * This method deletes reservation items by their associated location. - * - * @param {string | string[]} locationId - The location's ID. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when then reservation items are deleted successfully. - * - * @example - * await inventoryModuleService.deleteReservationItemByLocationId( - * "loc_123" - * ) - */ - deleteReservationItemByLocationId( - locationId: string | string[], - context?: Context - ): Promise - - /** - * This method deletes an inventory level by its associated inventory item and location. - * - * @param {string} inventoryItemId - The inventory item's ID. - * @param {string} locationId - The location's ID. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the inventory level is deleted successfully. - * - * @example - * await inventoryModuleService.deleteInventoryLevel( - * "iitem_123", - * "loc_123" - * ) - */ - deleteInventoryLevel( - inventoryItemId: string, - locationId: string, - context?: Context - ): Promise - - /** - * This method deletes inventory levels by their IDs. - * - * @param {string | string[]} inventoryLevelIds - The inventory levels' IDs. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the inventory levels are deleted. - * - * @example - * await inventoryModuleService.deleteInventoryLevels("ilev_123") - */ - deleteInventoryLevels( - inventoryLevelIds: string | string[], - context?: Context - ): Promise - - /** - * This method soft deletes inventory levels by their IDs. - * - * @param {string[]} inventoryLevelIds - The inventory levels' IDs. - * @param {SoftDeleteReturn} config - An object that is used to specify an entity's related entities that should be soft-deleted when the main entity is soft-deleted. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise>} An object that includes the IDs of related records that were also soft deleted. - * If there are no related records, the promise resolves to `void`. - * - * @example - * await inventoryModuleService.softDeleteInventoryLevels([ - * "ilev_123", - * ]) - */ - softDeleteInventoryLevels( - inventoryLevelIds: string[], - config?: SoftDeleteReturn, - sharedContext?: Context - ): Promise | void> - - /** - * This method restores soft deleted inventory levels by their IDs. - * - * @param {string[]} inventoryLevelIds - The inventory levels' IDs. - * @param {RestoreReturn} config - Configurations determining which relations to restore along with each of the inventory level. You can pass to its `returnLinkableKeys` - * property any of the inventory level's relation attribute names, such as `{type relation name}`. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise>} An object that includes the IDs of related records that were restored. - * If there are no related records restored, the promise resolves to `void`. - * - * @example - * await inventoryModuleService.restoreInventoryLevels([ - * "ilev_123", - * ]) - */ - restoreInventoryLevels( - inventoryLevelIds: string[], - config?: RestoreReturn, - sharedContext?: Context - ): Promise | void> - - /** - * This method adjusts the inventory quantity of an item in a location. - * - * @param {string} inventoryItemId - The inventory item's ID. - * @param {string} locationId - The location's ID. - * @param {number} adjustment - the adjustment to make to the quantity. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated inventory level. - * - * @example - * // add to the inventory quantity - * const inventoryLevel1 = - * await inventoryModuleService.adjustInventory( - * "iitem_123", - * "loc_123", - * 5 - * ) - * - * // subtract from the inventory quantity - * const inventoryLevel2 = - * await inventoryModuleService.adjustInventory( - * "iitem_123", - * "loc_123", - * -5 - * ) - */ - - adjustInventory( - data: { - inventoryItemId: string - locationId: string - adjustment: number - }[], - context?: Context - ): Promise - - adjustInventory( - inventoryItemId: string, - locationId: string, - adjustment: number, - context?: Context - ): Promise - - /** - * This method confirms that a quantity is available of an inventory item in the specified locations. - * - * @param {string} inventoryItemId - The inventory item's ID. - * @param {string[]} locationIds - The locations' IDs. - * @param {number} quantity - The quantity to confirm its availability. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Whether the quantity is available. - * - * @example - * const isAvailable = - * await inventoryModuleService.confirmInventory( - * "iitem_123", - * ["loc_123", "loc_321"], - * 10 - * ) - */ - confirmInventory( - inventoryItemId: string, - locationIds: string[], - quantity: number, - context?: Context - ): Promise - - /** - * This method retrieves the available quantity of an inventory item in the specified locations. - * - * @param {string} inventoryItemId - The inventory item's ID. - * @param {string[]} locationIds - The locations' IDs. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The available quantity of the item. - * - * @example - * const availableQuantity = - * await inventoryModuleService.retrieveAvailableQuantity( - * "iitem_123", - * ["loc_123", "loc_321"] - * ) - */ - retrieveAvailableQuantity( - inventoryItemId: string, - locationIds: string[], - context?: Context - ): Promise - - /** - * This method retrieves the stocked quantity of an inventory item in the specified location. - * - * @param {string} inventoryItemId - The inventory item's ID. - * @param {string[]} locationIds - The locations' IDs. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The stocked quantity of the item. - * - * @example - * const stockedQuantity = - * await inventoryModuleService.retrieveStockedQuantity( - * "iitem_123", - * ["loc_123", "loc_321"] - * ) - */ - retrieveStockedQuantity( - inventoryItemId: string, - locationIds: string[], - context?: Context - ): Promise - - /** - * This method retrieves the reserved quantity of an inventory item in the specified location. - * - * @param {string} inventoryItemId - The inventory item's ID. - * @param {string[]} locationIds - The locations' IDs. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The reserved quantity of the item. - * - * @example - * const reservedQuantity = - * await inventoryModuleService.retrieveReservedQuantity( - * "iitem_123", - * ["loc_123", "loc_321"] - * ) - */ - retrieveReservedQuantity( - inventoryItemId: string, - locationIds: string[], - context?: Context - ): Promise -} diff --git a/packages/core/types/src/inventory/service.ts b/packages/core/types/src/inventory/service.ts index 4549f0617d..1f0ac5a4e2 100644 --- a/packages/core/types/src/inventory/service.ts +++ b/packages/core/types/src/inventory/service.ts @@ -1,689 +1,755 @@ +import { RestoreReturn, SoftDeleteReturn } from "../dal" + +import { FindConfig } from "../common" +import { IModuleService } from "../modules-sdk" +import { Context } from "../shared-context" import { - BulkUpdateInventoryLevelInput, - CreateInventoryItemInput, - CreateInventoryLevelInput, - CreateReservationItemInput, FilterableInventoryItemProps, FilterableInventoryLevelProps, FilterableReservationItemProps, InventoryItemDTO, InventoryLevelDTO, ReservationItemDTO, - UpdateInventoryLevelInput, - UpdateReservationItemInput, } from "./common" - -import { FindConfig } from "../common" -import { IModuleService } from "../modules-sdk" -import { SharedContext } from "../shared-context" +import { + BulkUpdateInventoryLevelInput, + CreateInventoryItemInput, + CreateInventoryLevelInput, + CreateReservationItemInput, + UpdateInventoryItemInput, + UpdateReservationItemInput, +} from "./mutations" /** - * The main service interface for the inventory module. + * The main service interface for the Inventory Module. */ export interface IInventoryService extends IModuleService { /** - * This method is used to retrieve a paginated list of inventory items along with the total count of available inventory items satisfying the provided filters. + * This method retrieves a paginated list of inventory items based on optional filters and configuration. + * * @param {FilterableInventoryItemProps} selector - The filters to apply on the retrieved inventory items. - * @param {FindConfig} config - - * The configurations determining how the inventory items are retrieved. Its properties, such as `select` or `relations`, accept the + * @param {FindConfig} config - The configurations determining how the inventory item is retrieved. Its properties, such as `select` or `relations`, accept the * attributes or relations associated with a inventory item. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @return {Promise<[InventoryItemDTO[], number]>} The list of inventory items along with the total count. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The list of inventory items. * * @example * To retrieve a list of inventory items using their IDs: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveInventoryItems (ids: string[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const [inventoryItems, count] = await inventoryModule.listInventoryItems({ - * id: ids - * }) - * - * // do something with the inventory items or return them - * } + * const inventoryItems = await inventoryModuleService.listInventoryItems({ + * id: ["iitem_123", "iitem_321"], + * }) * ``` * * To specify relations that should be retrieved within the inventory items: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveInventoryItems (ids: string[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const [inventoryItems, count] = await inventoryModule.listInventoryItems({ - * id: ids - * }, { - * relations: ["inventory_level"] - * }) - * - * // do something with the inventory items or return them - * } + * const inventoryItems = await inventoryModuleService.listInventoryItems( + * { + * id: ["iitem_123", "iitem_321"], + * }, + * { + * relations: ["location_levels"], + * } + * ) * ``` * * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveInventoryItems (ids: string[], skip: number, take: number) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const [inventoryItems, count] = await inventoryModule.listInventoryItems({ - * id: ids - * }, { - * relations: ["inventory_level"], - * skip, - * take - * }) - * - * // do something with the inventory items or return them - * } + * const inventoryItems = await inventoryModuleService.listInventoryItems( + * { + * id: ["iitem_123", "iitem_321"], + * }, + * { + * relations: ["location_levels"], + * take: 20, + * skip: 2, + * } + * ) * ``` */ listInventoryItems( selector: FilterableInventoryItemProps, config?: FindConfig, - context?: SharedContext + context?: Context + ): Promise + + /** + * This method retrieves a paginated list of inventory items along with the total count of available inventory items satisfying the provided filters. + * + * @param {FilterableInventoryItemProps} selector - The filters to apply on the retrieved inventory items. + * @param {FindConfig} config - The configurations determining how the inventory item is retrieved. Its properties, such as `select` or `relations`, accept the + * attributes or relations associated with a inventory item. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise<[InventoryItemDTO[], number]>} The list of inventory items along with their total count. + * + * @example + * To retrieve a list of inventory items using their IDs: + * + * ```ts + * const [inventoryItems, count] = + * await inventoryModuleService.listAndCountInventoryItems({ + * id: ["iitem_123", "iitem_321"], + * }) + * ``` + * + * To specify relations that should be retrieved within the inventory items: + * + * ```ts + * const [inventoryItems, count] = + * await inventoryModuleService.listAndCountInventoryItems( + * { + * id: ["iitem_123", "iitem_321"], + * }, + * { + * relations: ["location_levels"], + * } + * ) + * ``` + * + * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: + * + * ```ts + * const [inventoryItems, count] = + * await inventoryModuleService.listAndCountInventoryItems( + * { + * id: ["iitem_123", "iitem_321"], + * }, + * { + * relations: ["location_levels"], + * take: 20, + * skip: 2, + * } + * ) + * ``` + */ + listAndCountInventoryItems( + selector: FilterableInventoryItemProps, + config?: FindConfig, + context?: Context ): Promise<[InventoryItemDTO[], number]> /** - * This method is used to retrieve a paginated list of reservation items along with the total count of available reservation items satisfying the provided filters. + * This method retrieves a paginated list of reservation items based on optional filters and configuration. + * * @param {FilterableReservationItemProps} selector - The filters to apply on the retrieved reservation items. - * @param {FindConfig} config - - * The configurations determining how the reservation items are retrieved. Its properties, such as `select` or `relations`, accept the + * @param {FindConfig} config - The configurations determining how the reservation item is retrieved. Its properties, such as `select` or `relations`, accept the * attributes or relations associated with a reservation item. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @return {Promise<[ReservationItemDTO[], number]>} The list of reservation items along with the total count. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The list of reservation items. * * @example * To retrieve a list of reservation items using their IDs: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveReservationItems (ids: string[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const [reservationItems, count] = await inventoryModule.listReservationItems({ - * id: ids + * const reservationItems = + * await inventoryModuleService.listReservationItems({ + * id: ["resitem_123", "resitem_321"], * }) - * - * // do something with the reservation items or return them - * } * ``` * * To specify relations that should be retrieved within the reservation items: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveReservationItems (ids: string[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const [reservationItems, count] = await inventoryModule.listReservationItems({ - * id: ids - * }, { - * relations: ["inventory_item"] - * }) - * - * // do something with the reservation items or return them - * } + * const reservationItems = + * await inventoryModuleService.listReservationItems( + * { + * id: ["resitem_123", "resitem_321"], + * }, + * { + * relations: ["inventory_item"], + * } + * ) * ``` * * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveReservationItems (ids: string[], skip: number, take: number) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const [reservationItems, count] = await inventoryModule.listReservationItems({ - * id: ids - * }, { - * relations: ["inventory_item"], - * skip, - * take - * }) - * - * // do something with the reservation items or return them - * } + * const reservationItems = + * await inventoryModuleService.listReservationItems( + * { + * id: ["resitem_123", "resitem_321"], + * }, + * { + * relations: ["inventory_item"], + * take: 20, + * skip: 2, + * } + * ) * ``` */ listReservationItems( selector: FilterableReservationItemProps, config?: FindConfig, - context?: SharedContext - ): Promise<[ReservationItemDTO[], number]> + context?: Context + ): Promise /** - * This method is used to retrieve a paginated list of inventory levels along with the total count of available inventory levels satisfying the provided filters. - * @param {FilterableInventoryLevelProps} selector - The filters to apply on the retrieved inventory levels. - * @param {FindConfig} config - - * The configurations determining how the inventory levels are retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a inventory level. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @return {Promise<[InventoryLevelDTO[], number]>} The list of inventory levels along with the total count. + * This method retrieves a paginated list of reservation items along with the total count of available reservation items satisfying the provided filters. + * + * @param {FilterableReservationItemProps} selector - The filters to apply on the retrieved reservation items. + * @param {FindConfig} config - The configurations determining how the reservation item is retrieved. Its properties, such as `select` or `relations`, accept the + * attributes or relations associated with a reservation item. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise<[ReservationItemDTO[], number]>} The list of reservation items along with their total count. * * @example - * To retrieve a list of inventory levels using their IDs: + * To retrieve a list of reservation items using their IDs: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveInventoryLevels (inventoryItemIds: string[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const [inventoryLevels, count] = await inventoryModule.listInventoryLevels({ - * inventory_item_id: inventoryItemIds + * const [reservationItems, count] = + * await inventoryModuleService.listAndCountReservationItems({ + * id: ["resitem_123", "resitem_321"], * }) - * - * // do something with the inventory levels or return them - * } * ``` * - * To specify relations that should be retrieved within the inventory levels: + * To specify relations that should be retrieved within the reservation items: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveInventoryLevels (inventoryItemIds: string[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const [inventoryLevels, count] = await inventoryModule.listInventoryLevels({ - * inventory_item_id: inventoryItemIds - * }, { - * relations: ["inventory_item"] - * }) - * - * // do something with the inventory levels or return them - * } + * const [reservationItems, count] = + * await inventoryModuleService.listAndCountReservationItems( + * { + * id: ["resitem_123", "resitem_321"], + * }, + * { + * relations: ["inventory_item"], + * } + * ) * ``` * * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" + * const [reservationItems, count] = + * await inventoryModuleService.listAndCountReservationItems( + * { + * id: ["resitem_123", "resitem_321"], + * }, + * { + * relations: ["inventory_item"], + * take: 20, + * skip: 2, + * } + * ) + * ``` + */ + listAndCountReservationItems( + selector: FilterableReservationItemProps, + config?: FindConfig, + context?: Context + ): Promise<[ReservationItemDTO[], number]> + + /** + * This method retrieves a paginated list of inventory levels based on optional filters and configuration. * - * async function retrieveInventoryLevels (inventoryItemIds: string[], skip: number, take: number) { - * const inventoryModule = await initializeInventoryModule({}) + * @param {FilterableInventoryLevelProps} selector - The filters to apply on the retrieved inventory levels. + * @param {FindConfig} config - The configurations determining how the inventory level is retrieved. Its properties, such as `select` or `relations`, accept the + * attributes or relations associated with a inventory level. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The list of inventory levels. * - * const [inventoryLevels, count] = await inventoryModule.listInventoryLevels({ - * inventory_item_id: inventoryItemIds - * }, { - * relations: ["inventory_item"], - * skip, - * take + * @example + * To retrieve a list of inventory levels using the IDs of their associated inventory items: + * + * ```ts + * const inventoryLevels = + * await inventoryModuleService.listInventoryLevels({ + * inventory_item_id: ["iitem_123", "iitem_321"], * }) + * ``` * - * // do something with the inventory levels or return them - * } + * To specify relations that should be retrieved within the inventory levels: + * + * ```ts + * const inventoryLevels = + * await inventoryModuleService.listInventoryLevels( + * { + * inventory_item_id: ["iitem_123", "iitem_321"], + * }, + * { + * relations: ["inventory_item"], + * } + * ) + * ``` + * + * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: + * + * ```ts + * const inventoryLevels = + * await inventoryModuleService.listInventoryLevels( + * { + * inventory_item_id: ["iitem_123", "iitem_321"], + * }, + * { + * relations: ["inventory_item"], + * take: 20, + * skip: 2, + * } + * ) * ``` */ listInventoryLevels( selector: FilterableInventoryLevelProps, config?: FindConfig, - context?: SharedContext + context?: Context + ): Promise + + /** + * This method retrieves a paginated list of inventory levels along with the total count of available inventory levels satisfying the provided filters. + * + * @param {FilterableInventoryLevelProps} selector - The filters to apply on the retrieved inventory levels. + * @param {FindConfig} config - The configurations determining how the inventory level is retrieved. Its properties, such as `select` or `relations`, accept the + * attributes or relations associated with a inventory level. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise<[InventoryLevelDTO[], number]>} The list of inventory levels along with their total count. + * + * @example + * To retrieve a list of inventory levels using the IDs of their associated inventory items: + * + * ```ts + * const [inventoryLevels, count] = + * await inventoryModuleService.listAndCountInventoryLevels( + * { + * inventory_item_id: ["iitem_123", "iitem_321"], + * }, + * { + * relations: ["inventory_item"], + * take: 20, + * skip: 2, + * } + * ) + * ``` + * + * To specify relations that should be retrieved within the inventory levels: + * + * ```ts + * const [inventoryLevels, count] = + * await inventoryModuleService.listAndCountInventoryLevels( + * { + * inventory_item_id: ["iitem_123", "iitem_321"], + * }, + * { + * relations: ["inventory_item"], + * } + * ) + * ``` + * + * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: + * + * ```ts + * const [inventoryLevels, count] = + * await inventoryModuleService.listAndCountInventoryLevels({ + * inventory_item_id: ["iitem_123", "iitem_321"], + * }) + * ``` + */ + listAndCountInventoryLevels( + selector: FilterableInventoryLevelProps, + config?: FindConfig, + context?: Context ): Promise<[InventoryLevelDTO[], number]> /** - * This method is used to retrieve an inventory item by its ID + * This method retrieves an inventory item by its ID. * - * @param {string} inventoryItemId - The ID of the inventory item to retrieve. - * @param {FindConfig} config - - * The configurations determining how the inventory item is retrieved. Its properties, such as `select` or `relations`, accept the + * @param {string} inventoryItemId - The inventory item's ID. + * @param {FindConfig} config - The configurations determining how the inventory item is retrieved. Its properties, such as `select` or `relations`, accept the * attributes or relations associated with a inventory item. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. * @returns {Promise} The retrieved inventory item. * * @example * A simple example that retrieves a inventory item by its ID: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveInventoryItem (id: string) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryItem = await inventoryModule.retrieveInventoryItem(id) - * - * // do something with the inventory item or return it - * } + * const inventoryItem = + * await inventoryModuleService.retrieveInventoryItem("iitem_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveInventoryItem (id: string) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryItem = await inventoryModule.retrieveInventoryItem(id, { - * relations: ["inventory_level"] - * }) - * - * // do something with the inventory item or return it - * } + * const inventoryItem = await inventoryModuleService.retrieveInventoryItem( + * "iitem_123", + * { + * relations: ["location_levels"], + * } + * ) * ``` */ retrieveInventoryItem( inventoryItemId: string, config?: FindConfig, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to retrieve an inventory level for an inventory item and a location. + * This method retrieves an inventory level based on its associated inventory item and location. * - * @param {string} inventoryItemId - The ID of the inventory item. - * @param {string} locationId - The ID of the location. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. + * @param {string} inventoryItemId - The inventory item's ID. + * @param {string} locationId - The location's ID. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. * @returns {Promise} The retrieved inventory level. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveInventoryLevel ( - * inventoryItemId: string, - * locationId: string - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryLevel = await inventoryModule.retrieveInventoryLevel( - * inventoryItemId, - * locationId + * const inventoryLevel = + * await inventoryModuleService.retrieveInventoryLevelByItemAndLocation( + * "iitem_123", + * "loc_123" * ) - * - * // do something with the inventory level or return it - * } */ - retrieveInventoryLevel( + retrieveInventoryLevelByItemAndLocation( inventoryItemId: string, locationId: string, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to retrieve a reservation item by its ID. + * This method retrieves an inventory level by its ID. * - * @param {string} reservationId - The ID of the reservation item. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. + * @param {string} inventoryLevelId - The inventory level's ID. + * @param {FindConfig} config - The configurations determining how the inventory level is retrieved. Its properties, such as `select` or `relations`, accept the + * attributes or relations associated with a inventory level. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The retrieved inventory level. + * + * @example + * A simple example that retrieves a inventory level by its ID: + * + * ```ts + * const inventoryLevel = + * await inventoryModuleService.retrieveInventoryLevel( + * "iitem_123" + * ) + * ``` + * + * To specify relations that should be retrieved: + * + * ```ts + * const inventoryLevel = + * await inventoryModuleService.retrieveInventoryLevel( + * "iitem_123", + * { + * relations: ["inventory_item"], + * } + * ) + * ``` + */ + retrieveInventoryLevel( + inventoryLevelId: string, + config?: FindConfig, + context?: Context + ): Promise + + /** + * This method retrieves a reservation item by its ID. + * + * @param {string} reservationId - The reservation's ID. + * @param {FindConfig} config - The configurations determining how the reservation item is retrieved. Its properties, such as `select` or `relations`, accept the + * attributes or relations associated with a reservation item. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. * @returns {Promise} The retrieved reservation item. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" + * A simple example that retrieves a reservation item by its ID: * - * async function retrieveReservationItem (id: string) { - * const inventoryModule = await initializeInventoryModule({}) + * ```ts + * const reservationItem = + * await inventoryModuleService.retrieveReservationItem( + * "resitem" + * ) + * ``` * - * const reservationItem = await inventoryModule.retrieveReservationItem(id) + * To specify relations that should be retrieved: * - * // do something with the reservation item or return it - * } + * ```ts + * const reservationItem = + * await inventoryModuleService.retrieveReservationItem( + * "resitem", + * { + * relations: ["inventory_item"], + * } + * ) + * ``` */ retrieveReservationItem( reservationId: string, - context?: SharedContext + config?: FindConfig, + context?: Context ): Promise /** - * This method is used to create a reservation item. + * This method creates reservation items. * - * @param {CreateReservationItemInput} input - The details of the reservation item to create. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created reservation item's details. + * @param {CreateReservationItemInput[]} input - The details of the reservation items to be created. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created reservation items. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function createReservationItem (item: { - * inventory_item_id: string, - * location_id: string, - * quantity: number - * }) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const reservationItem = await inventoryModule.createReservationItems( - * item - * ) - * - * // do something with the reservation item or return them - * } - */ - createReservationItem( - input: CreateReservationItemInput, - context?: SharedContext - ): Promise - - /** - * This method is used to create reservation items. - * - * @param {CreateReservationItemInput[]} input - The details of the reservation items to create. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns { Promise} The created reservation items' details. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function createReservationItems (items: { - * inventory_item_id: string, - * location_id: string, - * quantity: number - * }[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const reservationItems = await inventoryModule.createReservationItems( - * items - * ) - * - * // do something with the reservation items or return them - * } + * const reservationItems = + * await inventoryModuleService.createReservationItems([ + * { + * inventory_item_id: "iitem_123", + * location_id: "loc_123", + * quantity: 10, + * }, + * ]) */ createReservationItems( input: CreateReservationItemInput[], - context?: SharedContext + context?: Context ): Promise /** - * This method is used to create an inventory item. + * This method creates a reservation item. * - * @param {CreateInventoryItemInput} input - The details of the inventory item to create. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created inventory item's details. + * @param {CreateReservationItemInput} input - The details of the reservation item to be created. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created reservation item. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function createInventoryItem (item: { - * sku: string, - * requires_shipping: boolean - * }) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryItem = await inventoryModule.createInventoryItem( - * item - * ) - * - * // do something with the inventory item or return it - * } + * const reservationItem = + * await inventoryModuleService.createReservationItems({ + * inventory_item_id: "iitem_123", + * location_id: "loc_123", + * quantity: 10, + * }) */ - createInventoryItem( - input: CreateInventoryItemInput, - context?: SharedContext - ): Promise - - /** - * This method is used to create inventory items. - * - * @param {CreateInventoryItemInput[]} input - The details of the inventory items to create. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created inventory items' details. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function createInventoryItems (items: { - * sku: string, - * requires_shipping: boolean - * }[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryItems = await inventoryModule.createInventoryItems( - * items - * ) - * - * // do something with the inventory items or return them - * } - */ - createInventoryItems( - input: CreateInventoryItemInput[], - context?: SharedContext - ): Promise - - /** - * This method is used to create inventory level. - * - * @param {CreateInventoryLevelInput} data - The details of the inventory level to create. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created inventory level's details. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function createInventoryLevel (item: { - * inventory_item_id: string - * location_id: string - * stocked_quantity: number - * }) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryLevel = await inventoryModule.createInventoryLevel( - * item - * ) - * - * // do something with the inventory level or return it - * } - */ - createInventoryLevel( - data: CreateInventoryLevelInput, - context?: SharedContext - ): Promise - - /** - * This method is used to create inventory levels. - * - * @param {CreateInventoryLevelInput[]} data - The details of the inventory levels to create. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created inventory levels' details. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function createInventoryLevels (items: { - * inventory_item_id: string - * location_id: string - * stocked_quantity: number - * }[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryLevels = await inventoryModule.createInventoryLevels( - * items - * ) - * - * // do something with the inventory levels or return them - * } - */ - createInventoryLevels( - data: CreateInventoryLevelInput[], - context?: SharedContext - ): Promise - - /** - * This method is used to update inventory levels. Each inventory level is identified by the IDs of its associated inventory item and location. - * - * @param {BulkUpdateInventoryLevelInput} updates - The attributes to update in each inventory level. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated inventory levels' details. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function updateInventoryLevels (items: { - * inventory_item_id: string, - * location_id: string, - * stocked_quantity: number - * }[]) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryLevels = await inventoryModule.updateInventoryLevels( - * items - * ) - * - * // do something with the inventory levels or return them - * } - */ - updateInventoryLevels( - updates: BulkUpdateInventoryLevelInput[], - context?: SharedContext - ): Promise - - /** - * This method is used to update an inventory level. The inventory level is identified by the IDs of its associated inventory item and location. - * - * @param {string} inventoryItemId - The ID of the inventory item. - * @param {string} locationId - The ID of the location. - * @param {UpdateInventoryLevelInput} update - The attributes to update in the location level. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated inventory level's details. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function updateInventoryLevel ( - * inventoryItemId: string, - * locationId: string, - * stockedQuantity: number - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryLevel = await inventoryModule.updateInventoryLevels( - * inventoryItemId, - * locationId, - * { - * stocked_quantity: stockedQuantity - * } - * ) - * - * // do something with the inventory level or return it - * } - */ - updateInventoryLevel( - inventoryItemId: string, - locationId: string, - update: UpdateInventoryLevelInput, - context?: SharedContext - ): Promise - - /** - * This method is used to update an inventory item. - * - * @param {string} inventoryItemId - The ID of the inventory item. - * @param {Partial} input - The attributes to update in the inventory item. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated inventory item's details. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function updateInventoryItem ( - * inventoryItemId: string, - * sku: string - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const inventoryItem = await inventoryModule.updateInventoryItem( - * inventoryItemId, - * { - * sku - * } - * ) - * - * // do something with the inventory item or return it - * } - */ - updateInventoryItem( - inventoryItemId: string, - input: Partial, - context?: SharedContext - ): Promise - - /** - * This method is used to update a reservation item. - * - * @param {string} reservationItemId - The ID of the reservation item. - * @param {UpdateReservationItemInput} input - The attributes to update in the reservation item. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated reservation item. - * - * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function updateReservationItem ( - * reservationItemId: string, - * quantity: number - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const reservationItem = await inventoryModule.updateReservationItem( - * reservationItemId, - * { - * quantity - * } - * ) - * - * // do something with the reservation item or return it - * } - */ - updateReservationItem( - reservationItemId: string, - input: UpdateReservationItemInput, - context?: SharedContext + createReservationItems( + input: CreateReservationItemInput, + context?: Context ): Promise /** - * This method is used to delete the reservation items associated with a line item or multiple line items. + * This method creates inventory items. + * + * @param {CreateInventoryItemInput[]} input - The details of the inventory items to be created. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created inventory items. + * + * @example + * const inventoryItems = await inventoryModuleService.createInventoryItems([ + * { + * sku: "SHIRT", + * }, + * ]) + */ + createInventoryItems( + input: CreateInventoryItemInput[], + context?: Context + ): Promise + + /** + * This method creates an inventory item. + * + * @param {CreateInventoryItemInput} input - The details of the inventory item to be created. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created inventory item. + * + * @example + * const inventoryItem = await inventoryModuleService.createInventoryItems({ + * sku: "SHIRT", + * }) + */ + createInventoryItems( + input: CreateInventoryItemInput, + context?: Context + ): Promise + + /** + * This method creates inventory levels. + * + * @param {CreateInventoryLevelInput[]} data - The details of the inventory levels to be created. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created inventory levels. + * + * @example + * const inventoryLevels = + * await inventoryModuleService.createInventoryLevels([ + * { + * inventory_item_id: "iitem_123", + * location_id: "loc_123", + * stocked_quantity: 10, + * }, + * { + * inventory_item_id: "iitem_321", + * location_id: "loc_321", + * stocked_quantity: 20, + * reserved_quantity: 10, + * }, + * ]) + */ + createInventoryLevels( + data: CreateInventoryLevelInput[], + context?: Context + ): Promise + + /** + * This method creates an inventory level. + * + * @param {CreateInventoryLevelInput} data - The details of the inventory level to be created. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created inventory level. + * + * @example + * const inventoryLevels = + * await inventoryModuleService.createInventoryLevels({ + * inventory_item_id: "iitem_123", + * location_id: "loc_123", + * stocked_quantity: 10, + * }) + */ + createInventoryLevels( + data: CreateInventoryLevelInput, + context?: Context + ): Promise + + /** + * This method updates existing inventory levels. + * + * @param {BulkUpdateInventoryLevelInput[]} updates - The list of The attributes to update in an inventory level. The inventory level is identified by the IDs of its associated inventory item and location. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated inventory levels. + * + * @example + * const inventoryLevels = + * await inventoryModuleService.updateInventoryLevels([ + * { + * inventory_item_id: "iitem_123", + * location_id: "loc_123", + * id: "ilev_123", + * stocked_quantity: 20, + * }, + * ]) + */ + updateInventoryLevels( + updates: BulkUpdateInventoryLevelInput[], + context?: Context + ): Promise + + /** + * This method updates an existing inventory level. + * + * @param {BulkUpdateInventoryLevelInput} updates - The attributes to update in an inventory level. The inventory level is identified by the IDs of its associated inventory item and location. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated inventory level. + * + * @example + * const inventoryLevel = + * await inventoryModuleService.updateInventoryLevels({ + * inventory_item_id: "iitem_123", + * location_id: "loc_123", + * stocked_quantity: 20, + * }) + */ + updateInventoryLevels( + updates: BulkUpdateInventoryLevelInput, + context?: Context + ): Promise + + /** + * This method updates an existing inventory item. + * + * @param {UpdateInventoryItemInput} input - The attributes to update in the inventory item. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated inventory item. + * + * @example + * const inventoryItem = await inventoryModuleService.updateInventoryItems({ + * id: "iitem_123", + * title: "Medusa Shirt Inventory", + * }) + */ + updateInventoryItems( + input: UpdateInventoryItemInput, + context?: Context + ): Promise + + /** + * This method updates existing inventory items. + * + * @param {UpdateInventoryItemInput[]} input - The attributes to update in the inventory items. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated inventory items. + * + * @example + * const inventoryItems = await inventoryModuleService.updateInventoryItems([ + * { + * id: "iitem_123", + * title: "Medusa Shirt Inventory", + * }, + * { + * id: "iitem_321", + * description: "The inventory of Medusa pants", + * }, + * ]) + */ + updateInventoryItems( + input: UpdateInventoryItemInput[], + context?: Context + ): Promise + + /** + * This method updates an existing reservation item. + * + * @param {UpdateReservationItemInput} input - The attributes to update in a reservation item. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated reservation item. + * + * @example + * const reservationItem = + * await inventoryModuleService.updateReservationItems({ + * id: "resitem_123", + * quantity: 10, + * }) + */ + updateReservationItems( + input: UpdateReservationItemInput, + context?: Context + ): Promise + + /** + * This method updates existing reservation items. + * + * @param {UpdateReservationItemInput[]} input - The attributes to update in the reservation items. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated reservation items. + * + * @example + * const reservationItems = + * await inventoryModuleService.updateReservationItems([ + * { + * id: "resitem_123", + * quantity: 10, + * }, + * ]) + */ + updateReservationItems( + input: UpdateReservationItemInput[], + context?: Context + ): Promise + + /** + * This method deletes a reservation item by its associated line item. + * + * @param {string | string[]} lineItemId - The line item's ID. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} Resolves when the reservation item is deleted. + * + * @example + * await inventoryModuleService.deleteReservationItemByLocationId( + * "cali_123" + * ) + */ + deleteReservationItemsByLineItem( + lineItemId: string | string[], + context?: Context + ): Promise + + /** + * This method is used to restore the reservation items associated with a line item or multiple line items that were deleted. * * @param {string | string[]} lineItemId - The ID(s) of the line item(s). * @param {SharedContext} context - A context used to share re9sources, such as transaction manager, between the application and the module. @@ -694,356 +760,386 @@ export interface IInventoryService extends IModuleService { * initialize as initializeInventoryModule, * } from "@medusajs/inventory" * - * async function deleteReservationItemsByLineItem ( + * async function restoreReservationItemsByLineItem ( * lineItemIds: string[] * ) { * const inventoryModule = await initializeInventoryModule({}) * - * await inventoryModule.deleteReservationItemsByLineItem( + * await inventoryModule.restoreReservationItemsByLineItem( * lineItemIds * ) * } */ - deleteReservationItemsByLineItem( + restoreReservationItemsByLineItem( lineItemId: string | string[], - context?: SharedContext + context?: Context ): Promise /** - * This method is used to delete a reservation item or multiple reservation items by their IDs. + * This method deletes reservation items by their IDs. * - * @param {string | string[]} reservationItemId - The ID(s) of the reservation item(s) to delete. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the reservation item(s) are successfully deleted. + * @param {string | string[]} reservationItemId - The reservation items' IDs. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} Resolves when the reservation item is deleted. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function deleteReservationItems ( - * reservationItemIds: string[] - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * await inventoryModule.deleteReservationItem( - * reservationItemIds - * ) - * } + * await inventoryModuleService.deleteReservationItems( + * "resitem_123" + * ) */ - deleteReservationItem( + deleteReservationItems( reservationItemId: string | string[], - context?: SharedContext + context?: Context ): Promise /** - * This method is used to delete an inventory item or multiple inventory items. The inventory items are only soft deleted and can be restored using the - * {@link restoreInventoryItem} method. + * This method soft deletes reservations by their IDs. * - * @param {string | string[]} inventoryItemId - The ID(s) of the inventory item(s) to delete. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the inventory item(s) are successfully deleted. + * @param {string[]} inventoryLevelIds - The reservations' IDs. + * @param {SoftDeleteReturn} config - An object that is used to specify an entity's related entities that should be soft-deleted when the main entity is soft-deleted. + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise>} An object that includes the IDs of related records that were also soft deleted. + * If there are no related records, the promise resolves to `void`. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function deleteInventoryItem ( - * inventoryItems: string[] - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * await inventoryModule.deleteInventoryItem( - * inventoryItems - * ) - * } + * await inventoryModuleService.softDeleteReservationItems([ + * "ilev_123", + * ]) */ - deleteInventoryItem( - inventoryItemId: string | string[], - context?: SharedContext - ): Promise + softDeleteReservationItems( + ReservationItemIds: string[], + config?: SoftDeleteReturn, + sharedContext?: Context + ): Promise | void> /** - * This method is used to restore an inventory item or multiple inventory items that were previously deleted using the {@link deleteInventoryItem} method. + * This method restores soft deleted reservations by their IDs. * - * @param {string | string[]} inventoryItemId - The ID(s) of the inventory item(s) to restore. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the inventory item(s) are successfully restored. + * @param {string[]} ReservationItemIds - The reservations' IDs. + * @param {RestoreReturn} config - Configurations determining which relations to restore along with each of the reservation. You can pass to its `returnLinkableKeys` + * property any of the reservation's relation attribute names, such as `{type relation name}`. + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise>} An object that includes the IDs of related records that were restored. + * If there are no related records restored, the promise resolves to `void`. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function restoreInventoryItem ( - * inventoryItems: string[] - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * await inventoryModule.restoreInventoryItem( - * inventoryItems - * ) - * } + * await inventoryModuleService.restoreReservationItems([ + * "ilev_123", + * ]) */ - restoreInventoryItem( + restoreReservationItems( + ReservationItemIds: string[], + config?: RestoreReturn, + sharedContext?: Context + ): Promise | void> + + /** + * This method deletes inventory items by their IDs. + * + * @param {string | string[]} inventoryItemId - The inventory item's ID. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} Resolves when the inventory items are deleted. + * + * @example + * await inventoryModuleService.deleteInventoryItems("iitem_123") + */ + deleteInventoryItems( inventoryItemId: string | string[], - context?: SharedContext + context?: Context ): Promise /** - * This method deletes the inventory item level(s) for the ID(s) of associated location(s). + * This method soft deletes inventory items by their IDs. * - * @param {string | string[]} locationId - The ID(s) of the associated location(s). - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the inventory item level(s) are successfully restored. + * @param {string[]} inventoryItemIds - The inventory items' IDs. + * @param {SoftDeleteReturn} config - An object that is used to specify an entity's related entities that should be soft-deleted when the main entity is soft-deleted. + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise>} An object that includes the IDs of related records that were also soft deleted, such as the ID of the associated location levels. + * The object's keys are the ID attribute names of the inventory service next entity's relations, such as `location_level_id`, and its value is an array of strings, each being the ID of a record associated + * with the inventory item through this relation, such as the IDs of associated location levels. + * + * If there are no related records, the promise resolves to `void`. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" + * await inventoryModuleService.softDeleteInventoryItems( + * ["iitem_123", "iitem_321"], + * { + * returnLinkableKeys: ["location_level"], + * } + * ) + */ + softDeleteInventoryItems( + inventoryItemIds: string[], + config?: SoftDeleteReturn, + sharedContext?: Context + ): Promise | void> + + /** + * This method restores soft deleted inventory items by their IDs. * - * async function deleteInventoryItemLevelByLocationId ( - * locationIds: string[] - * ) { - * const inventoryModule = await initializeInventoryModule({}) + * @param {string[]} inventoryItemIds - The inventory items' IDs. + * @param {RestoreReturn} config - Configurations determining which relations to restore along with each of the inventory items. You can pass to its `returnLinkableKeys` + * property any of the inventory item's relation attribute names, such as `location_levels`. + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise>} An object that includes the IDs of related records that were restored, such as the ID of associated location levels. + * The object's keys are the ID attribute names of the inventory item entity's relations, such as `location_level_id`, + * and its value is an array of strings, each being the ID of the record associated with the inventory item through this relation, + * such as the IDs of associated location levels. * - * await inventoryModule.deleteInventoryItemLevelByLocationId( - * locationIds - * ) - * } + * If there are no related records restored, the promise resolves to `void`. + * + * @example + * await inventoryModuleService.restoreInventoryItems( + * ["iitem_123", "iitem_321"], + * { + * returnLinkableKeys: ["location_level"], + * } + * ) + */ + restoreInventoryItems( + inventoryItemIds: string[], + config?: RestoreReturn, + sharedContext?: Context + ): Promise | void> + + /** + * This method soft deletes inventory item's level by the associated location. + * + * @param {string | string[]} locationId - The locations' IDs. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise<[object[], Record]>} An array, where the first item is an array includes the soft-deleted inventory levels, + * and the second is an object that includes the IDs of related records that were soft-deleted. + * + * @example + * await inventoryModuleService.deleteInventoryItemLevelByLocationId( + * "loc_123" + * ) */ deleteInventoryItemLevelByLocationId( locationId: string | string[], - context?: SharedContext - ): Promise + context?: Context + ): Promise<[object[], Record]> /** - * This method deletes reservation item(s) by the ID(s) of associated location(s). + * This method deletes reservation items by their associated location. * - * @param {string | string[]} locationId - The ID(s) of the associated location(s). - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the reservation item(s) are successfully restored. + * @param {string | string[]} locationId - The location's ID. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} Resolves when then reservation items are deleted successfully. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function deleteReservationItemByLocationId ( - * locationIds: string[] - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * await inventoryModule.deleteReservationItemByLocationId( - * locationIds - * ) - * } + * await inventoryModuleService.deleteReservationItemByLocationId( + * "loc_123" + * ) */ deleteReservationItemByLocationId( locationId: string | string[], - context?: SharedContext + context?: Context ): Promise /** - * This method is used to delete an inventory level. The inventory level is identified by the IDs of its associated inventory item and location. + * This method deletes an inventory level by its associated inventory item and location. * - * @param {string} inventoryItemId - The ID of the associated inventory item. - * @param {string} locationId - The ID of the associated location. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the inventory level(s) are successfully restored. + * @param {string} inventoryItemId - The inventory item's ID. + * @param {string} locationId - The location's ID. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} Resolves when the inventory level is deleted successfully. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function deleteInventoryLevel ( - * inventoryItemId: string, - * locationId: string - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * await inventoryModule.deleteInventoryLevel( - * inventoryItemId, - * locationId - * ) - * } + * await inventoryModuleService.deleteInventoryLevel( + * "iitem_123", + * "loc_123" + * ) */ deleteInventoryLevel( inventoryItemId: string, locationId: string, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to adjust the inventory level's stocked quantity. The inventory level is identified by the IDs of its associated inventory item and location. + * This method deletes inventory levels by their IDs. * - * @param {string} inventoryItemId - The ID of the associated inventory item. - * @param {string} locationId - The ID of the associated location. - * @param {number} adjustment - A positive or negative number used to adjust the inventory level's stocked quantity. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The inventory level's details. + * @param {string | string[]} inventoryLevelIds - The inventory levels' IDs. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} Resolves when the inventory levels are deleted. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" + * await inventoryModuleService.deleteInventoryLevels("ilev_123") + */ + deleteInventoryLevels( + inventoryLevelIds: string | string[], + context?: Context + ): Promise + + /** + * This method soft deletes inventory levels by their IDs. * - * async function adjustInventory ( - * inventoryItemId: string, - * locationId: string, - * adjustment: number - * ) { - * const inventoryModule = await initializeInventoryModule({}) + * @param {string[]} inventoryLevelIds - The inventory levels' IDs. + * @param {SoftDeleteReturn} config - An object that is used to specify an entity's related entities that should be soft-deleted when the main entity is soft-deleted. + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise>} An object that includes the IDs of related records that were also soft deleted. + * If there are no related records, the promise resolves to `void`. * - * const inventoryLevel = await inventoryModule.adjustInventory( - * inventoryItemId, - * locationId, - * adjustment + * @example + * await inventoryModuleService.softDeleteInventoryLevels([ + * "ilev_123", + * ]) + */ + softDeleteInventoryLevels( + inventoryLevelIds: string[], + config?: SoftDeleteReturn, + sharedContext?: Context + ): Promise | void> + + /** + * This method restores soft deleted inventory levels by their IDs. + * + * @param {string[]} inventoryLevelIds - The inventory levels' IDs. + * @param {RestoreReturn} config - Configurations determining which relations to restore along with each of the inventory level. You can pass to its `returnLinkableKeys` + * property any of the inventory level's relation attribute names, such as `{type relation name}`. + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise>} An object that includes the IDs of related records that were restored. + * If there are no related records restored, the promise resolves to `void`. + * + * @example + * await inventoryModuleService.restoreInventoryLevels([ + * "ilev_123", + * ]) + */ + restoreInventoryLevels( + inventoryLevelIds: string[], + config?: RestoreReturn, + sharedContext?: Context + ): Promise | void> + + /** + * This method adjusts the inventory quantity of an item in a location. + * + * @param {string} inventoryItemId - The inventory item's ID. + * @param {string} locationId - The location's ID. + * @param {number} adjustment - the adjustment to make to the quantity. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated inventory level. + * + * @example + * // add to the inventory quantity + * const inventoryLevel1 = + * await inventoryModuleService.adjustInventory( + * "iitem_123", + * "loc_123", + * 5 * ) * - * // do something with the inventory level or return it. - * } + * // subtract from the inventory quantity + * const inventoryLevel2 = + * await inventoryModuleService.adjustInventory( + * "iitem_123", + * "loc_123", + * -5 + * ) */ + + adjustInventory( + data: { + inventoryItemId: string + locationId: string + adjustment: number + }[], + context?: Context + ): Promise + adjustInventory( inventoryItemId: string, locationId: string, adjustment: number, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to confirm whether the specified quantity of an inventory item is available in the specified locations. + * This method confirms that a quantity is available of an inventory item in the specified locations. * - * @param {string} inventoryItemId - The ID of the inventory item to check its availability. - * @param {string[]} locationIds - The IDs of the locations to check the quantity availability in. - * @param {number} quantity - The quantity to check if available for the inventory item in the specified locations. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Whether the specified quantity is available for the inventory item in the specified locations. + * @param {string} inventoryItemId - The inventory item's ID. + * @param {string[]} locationIds - The locations' IDs. + * @param {number} quantity - The quantity to confirm its availability. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} Whether the quantity is available. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function confirmInventory ( - * inventoryItemId: string, - * locationIds: string[], - * quantity: number - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * return await inventoryModule.confirmInventory( - * inventoryItemId, - * locationIds, - * quantity + * const isAvailable = + * await inventoryModuleService.confirmInventory( + * "iitem_123", + * ["loc_123", "loc_321"], + * 10 * ) - * } */ confirmInventory( inventoryItemId: string, locationIds: string[], quantity: number, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to retrieve the available quantity of an inventory item within the specified locations. + * This method retrieves the available quantity of an inventory item in the specified locations. * - * @param {string} inventoryItemId - The ID of the inventory item to retrieve its quantity. - * @param {string[]} locationIds - The IDs of the locations to retrieve the available quantity from. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The available quantity of the inventory item in the specified locations. + * @param {string} inventoryItemId - The inventory item's ID. + * @param {string[]} locationIds - The locations' IDs. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The available quantity of the item. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveAvailableQuantity ( - * inventoryItemId: string, - * locationIds: string[], - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const quantity = await inventoryModule.retrieveAvailableQuantity( - * inventoryItemId, - * locationIds, + * const availableQuantity = + * await inventoryModuleService.retrieveAvailableQuantity( + * "iitem_123", + * ["loc_123", "loc_321"] * ) - * - * // do something with the quantity or return it - * } */ retrieveAvailableQuantity( inventoryItemId: string, locationIds: string[], - context?: SharedContext + context?: Context ): Promise /** - * This method is used to retrieve the stocked quantity of an inventory item within the specified locations. + * This method retrieves the stocked quantity of an inventory item in the specified location. * - * @param {string} inventoryItemId - The ID of the inventory item to retrieve its stocked quantity. - * @param {string[]} locationIds - The IDs of the locations to retrieve the stocked quantity from. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The stocked quantity of the inventory item in the specified locations. + * @param {string} inventoryItemId - The inventory item's ID. + * @param {string[]} locationIds - The locations' IDs. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The stocked quantity of the item. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveStockedQuantity ( - * inventoryItemId: string, - * locationIds: string[], - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const quantity = await inventoryModule.retrieveStockedQuantity( - * inventoryItemId, - * locationIds, + * const stockedQuantity = + * await inventoryModuleService.retrieveStockedQuantity( + * "iitem_123", + * ["loc_123", "loc_321"] * ) - * - * // do something with the quantity or return it - * } */ retrieveStockedQuantity( inventoryItemId: string, locationIds: string[], - context?: SharedContext + context?: Context ): Promise /** - * This method is used to retrieve the reserved quantity of an inventory item within the specified locations. + * This method retrieves the reserved quantity of an inventory item in the specified location. * - * @param {string} inventoryItemId - The ID of the inventory item to retrieve its reserved quantity. - * @param {string[]} locationIds - The IDs of the locations to retrieve the reserved quantity from. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The reserved quantity of the inventory item in the specified locations. + * @param {string} inventoryItemId - The inventory item's ID. + * @param {string[]} locationIds - The locations' IDs. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The reserved quantity of the item. * * @example - * import { - * initialize as initializeInventoryModule, - * } from "@medusajs/inventory" - * - * async function retrieveReservedQuantity ( - * inventoryItemId: string, - * locationIds: string[], - * ) { - * const inventoryModule = await initializeInventoryModule({}) - * - * const quantity = await inventoryModule.retrieveReservedQuantity( - * inventoryItemId, - * locationIds, + * const reservedQuantity = + * await inventoryModuleService.retrieveReservedQuantity( + * "iitem_123", + * ["loc_123", "loc_321"] * ) - * - * // do something with the quantity or return it - * } */ retrieveReservedQuantity( inventoryItemId: string, locationIds: string[], - context?: SharedContext + context?: Context ): Promise } diff --git a/packages/core/types/src/notification/service.ts b/packages/core/types/src/notification/service.ts index e968d04188..49ee65b4f2 100644 --- a/packages/core/types/src/notification/service.ts +++ b/packages/core/types/src/notification/service.ts @@ -16,7 +16,7 @@ export interface INotificationModuleService extends IModuleService { * @returns {Promise} The list of sent notifications. * * @example - * const notifications = await notificationModuleService.create([ + * const notifications = await notificationModuleService.createNotifications([ * { * to: "john@doe.me", * template: "order-confirmation", @@ -29,7 +29,7 @@ export interface INotificationModuleService extends IModuleService { * }, * ]) */ - create( + createNotifications( data: CreateNotificationDTO[], sharedContext?: Context ): Promise @@ -42,13 +42,13 @@ export interface INotificationModuleService extends IModuleService { * @returns {Promise} The sent notification. * * @example - * const notification = await notificationModuleService.create({ + * const notification = await notificationModuleService.createNotifications({ * to: "john@doe.me", * template: "order-confirmation", * channel: "email", * }) */ - create( + createNotifications( data: CreateNotificationDTO, sharedContext?: Context ): Promise @@ -68,13 +68,13 @@ export interface INotificationModuleService extends IModuleService { * * ```ts * const notification = - * await notificationModuleService.retrieve("noti_123") + * await notificationModuleService.retrieveNotification("noti_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const notification = await notificationModuleService.retrieve( + * const notification = await notificationModuleService.retrieveNotification( * "noti_123", * { * relations: ["provider"], @@ -82,7 +82,7 @@ export interface INotificationModuleService extends IModuleService { * ) * ``` */ - retrieve( + retrieveNotification( notificationId: string, config?: FindConfig, sharedContext?: Context @@ -102,7 +102,7 @@ export interface INotificationModuleService extends IModuleService { * To retrieve a list of notifications using their IDs: * * ```ts - * const notifications = await notificationModuleService.list({ + * const notifications = await notificationModuleService.listNotifications({ * id: ["noti_123", "noti_321"], * }) * ``` @@ -110,7 +110,7 @@ export interface INotificationModuleService extends IModuleService { * To specify relations that should be retrieved within the notifications: * * ```ts - * const notifications = await notificationModuleService.list( + * const notifications = await notificationModuleService.listNotifications( * { * id: ["noti_123", "noti_321"], * }, @@ -123,7 +123,7 @@ export interface INotificationModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const notifications = await notificationModuleService.list( + * const notifications = await notificationModuleService.listNotifications( * { * id: ["noti_123", "noti_321"], * }, @@ -135,7 +135,7 @@ export interface INotificationModuleService extends IModuleService { * ) * ``` */ - list( + listNotifications( filters?: FilterableNotificationProps, config?: FindConfig, sharedContext?: Context @@ -156,7 +156,7 @@ export interface INotificationModuleService extends IModuleService { * * ```ts * const [notifications, count] = - * await notificationModuleService.listAndCount({ + * await notificationModuleService.listAndCountNotifications({ * id: ["noti_123", "noti_321"], * }) * ``` @@ -165,7 +165,7 @@ export interface INotificationModuleService extends IModuleService { * * ```ts * const [notifications, count] = - * await notificationModuleService.listAndCount( + * await notificationModuleService.listAndCountNotifications( * { * id: ["noti_123", "noti_321"], * }, @@ -179,7 +179,7 @@ export interface INotificationModuleService extends IModuleService { * * ```ts * const [notifications, count] = - * await notificationModuleService.listAndCount( + * await notificationModuleService.listAndCountNotifications( * { * id: ["noti_123", "noti_321"], * }, @@ -191,7 +191,7 @@ export interface INotificationModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountNotifications( filters?: FilterableNotificationProps, config?: FindConfig, sharedContext?: Context diff --git a/packages/core/types/src/order/service.ts b/packages/core/types/src/order/service.ts index 27f15dca2b..1126c8e664 100644 --- a/packages/core/types/src/order/service.ts +++ b/packages/core/types/src/order/service.ts @@ -69,6 +69,7 @@ import { UpsertOrderLineItemAdjustmentDTO, } from "./mutations" +// TODO: missing listOrderShippingMethods and listOrderChanges, fix module integration to remove any cast /** * {summary} */ @@ -84,11 +85,11 @@ export interface IOrderModuleService extends IModuleService { * * @example * ```typescript - * const result = await orderModuleService.retrieve("orderId123"); + * const result = await orderModuleService.retrieveOrder("orderId123"); * ``` * */ - retrieve( + retrieveOrder( orderId: string, config?: FindConfig, sharedContext?: Context @@ -105,11 +106,11 @@ export interface IOrderModuleService extends IModuleService { * * @example * ```typescript - * const orderDTOs = await orderModuleService.list(); + * const orderDTOs = await orderModuleService.listOrders(); * ``` * */ - list( + listOrders( filters?: FilterableOrderProps, config?: FindConfig, sharedContext?: Context @@ -126,11 +127,11 @@ export interface IOrderModuleService extends IModuleService { * * @example * ```typescript - * await orderModuleService.listAndCount(); + * await orderModuleService.listAndCountOrders(); * ``` * */ - listAndCount( + listAndCountOrders( filters?: FilterableOrderProps, config?: FindConfig, sharedContext?: Context @@ -212,11 +213,14 @@ export interface IOrderModuleService extends IModuleService { * } * ]; * - * const result = await orderModuleService.create(orderData); + * const result = await orderModuleService.createOrders(orderData); * ``` * */ - create(data: CreateOrderDTO[], sharedContext?: Context): Promise + createOrders( + data: CreateOrderDTO[], + sharedContext?: Context + ): Promise /** * This method creates {return type}(s) @@ -232,11 +236,11 @@ export interface IOrderModuleService extends IModuleService { * currency_code: "USD" * }; * - * const createdOrder = await orderModuleService.create(orderData); + * const createdOrder = await orderModuleService.createOrders(orderData); * ``` * */ - create(data: CreateOrderDTO, sharedContext?: Context): Promise + createOrders(data: CreateOrderDTO, sharedContext?: Context): Promise /** * This method updates existing {return type}(s). @@ -246,7 +250,7 @@ export interface IOrderModuleService extends IModuleService { * * @example * ```typescript - * const updatedOrders = await orderModuleService.update([ + * const updatedOrders = await orderModuleService.updateOrders([ * { * id: "order_id_1", * status: "shipped" @@ -259,7 +263,7 @@ export interface IOrderModuleService extends IModuleService { * ``` * */ - update(data: UpdateOrderDTO[]): Promise + updateOrders(data: UpdateOrderDTO[]): Promise /** * This method updates existing {return type}(s). @@ -271,13 +275,13 @@ export interface IOrderModuleService extends IModuleService { * * @example * ```typescript - * await orderModuleService.update("orderId123", { + * await orderModuleService.updateOrders("orderId123", { * status: "shipped" * }); * ``` * */ - update( + updateOrders( orderId: string, data: UpdateOrderDTO, sharedContext?: Context @@ -293,14 +297,14 @@ export interface IOrderModuleService extends IModuleService { * * @example * ```typescript - * await orderModuleService.update( + * await orderModuleService.updateOrders( * { id: "order-123" }, * { status: "completed" } * ); * ``` * */ - update( + updateOrders( selector: Partial, data: UpdateOrderDTO, sharedContext?: Context @@ -315,11 +319,11 @@ export interface IOrderModuleService extends IModuleService { * * @example * ```typescript - * await orderModuleService.delete(["12345abc", "67890def"]); + * await orderModuleService.deleteOrders(["12345abc", "67890def"]); * ``` * */ - delete(orderIds: string[], sharedContext?: Context): Promise + deleteOrders(orderIds: string[], sharedContext?: Context): Promise /** * This method deletes {return type} by its ID. @@ -330,19 +334,19 @@ export interface IOrderModuleService extends IModuleService { * * @example * ```typescript - * await orderModuleService.delete("orderId"); + * await orderModuleService.deleteOrders("orderId"); * ``` * */ - delete(orderId: string, sharedContext?: Context): Promise + deleteOrders(orderId: string, sharedContext?: Context): Promise - softDelete( + softDeleteOrders( storeIds: string[], config?: SoftDeleteReturn, sharedContext?: Context ): Promise | void> - restore( + restoreOrders( storeIds: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/pricing/service.ts b/packages/core/types/src/pricing/service.ts index a95d266719..37fec68cab 100644 --- a/packages/core/types/src/pricing/service.ts +++ b/packages/core/types/src/pricing/service.ts @@ -119,13 +119,13 @@ export interface IPricingModuleService extends IModuleService { * * ```ts * const priceSet = - * await pricingModuleService.retrieve("pset_123") + * await pricingModuleService.retrievePriceSet("pset_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const priceSet = await pricingModuleService.retrieve( + * const priceSet = await pricingModuleService.retrievePriceSet( * "pset_123", * { * relations: ["prices"], @@ -133,7 +133,7 @@ export interface IPricingModuleService extends IModuleService { * ) * ``` */ - retrieve( + retrievePriceSet( id: string, config?: FindConfig, sharedContext?: Context @@ -154,7 +154,7 @@ export interface IPricingModuleService extends IModuleService { * To retrieve a list of price sets using their IDs: * * ```ts - * const priceSets = await pricingModuleService.list({ + * const priceSets = await pricingModuleService.listPriceSets({ * id: ["pset_123", "pset_321"], * }) * ``` @@ -162,7 +162,7 @@ export interface IPricingModuleService extends IModuleService { * To specify relations that should be retrieved within the price sets: * * ```ts - * const priceSets = await pricingModuleService.list( + * const priceSets = await pricingModuleService.listPriceSets( * { * id: ["pset_123", "pset_321"], * }, @@ -175,7 +175,7 @@ export interface IPricingModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const priceSets = await pricingModuleService.list( + * const priceSets = await pricingModuleService.listPriceSets( * { * id: ["pset_123", "pset_321"], * }, @@ -187,7 +187,7 @@ export interface IPricingModuleService extends IModuleService { * ) * ``` */ - list( + listPriceSets( filters?: FilterablePriceSetProps, config?: FindConfig, sharedContext?: Context @@ -209,7 +209,7 @@ export interface IPricingModuleService extends IModuleService { * * ```ts * const [priceSets, count] = - * await pricingModuleService.listAndCount({ + * await pricingModuleService.listAndCountPriceSets({ * id: ["pset_123", "pset_321"], * }) * ``` @@ -218,7 +218,7 @@ export interface IPricingModuleService extends IModuleService { * * ```ts * const [priceSets, count] = - * await pricingModuleService.listAndCount( + * await pricingModuleService.listAndCountPriceSets( * { * id: ["pset_123", "pset_321"], * }, @@ -232,7 +232,7 @@ export interface IPricingModuleService extends IModuleService { * * ```ts * const [priceSets, count] = - * await pricingModuleService.listAndCount( + * await pricingModuleService.listAndCountPriceSets( * { * id: ["pset_123", "pset_321"], * }, @@ -244,7 +244,7 @@ export interface IPricingModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountPriceSets( filters?: FilterablePriceSetProps, config?: FindConfig, sharedContext?: Context @@ -261,7 +261,7 @@ export interface IPricingModuleService extends IModuleService { * To create a default price set, don't pass any rules. For example: * * ```ts - * const priceSet = await pricingModuleService.create({ + * const priceSet = await pricingModuleService.createPriceSets({ * rules: [], * prices: [ * { @@ -285,7 +285,7 @@ export interface IPricingModuleService extends IModuleService { * To create a price set and associate it with rule types: * * ```ts - * const priceSet = await pricingModuleService.create({ + * const priceSet = await pricingModuleService.createPriceSets({ * rules: [ * { rule_attribute: "region_id" }, * { rule_attribute: "city" }, @@ -317,7 +317,10 @@ export interface IPricingModuleService extends IModuleService { * }) * ``` */ - create(data: CreatePriceSetDTO, sharedContext?: Context): Promise + createPriceSets( + data: CreatePriceSetDTO, + sharedContext?: Context + ): Promise /** * This method is used to create multiple price sets. @@ -327,7 +330,7 @@ export interface IPricingModuleService extends IModuleService { * @returns {Promise} The list of created price sets. * * @example - * const priceSets = await pricingModuleService.create([ + * const priceSets = await pricingModuleService.createPriceSets([ * // default price set * { * rules: [], @@ -381,7 +384,7 @@ export interface IPricingModuleService extends IModuleService { * }, * ]) */ - create( + createPriceSets( data: CreatePriceSetDTO[], sharedContext?: Context ): Promise @@ -394,7 +397,7 @@ export interface IPricingModuleService extends IModuleService { * @returns {Promise} The updated and created price sets. * * @example - * const priceSets = await pricingModuleService.upsert([ + * const priceSets = await pricingModuleService.upsertPriceSets([ * { * prices: [ * { @@ -409,7 +412,7 @@ export interface IPricingModuleService extends IModuleService { * }, * ]) */ - upsert( + upsertPriceSets( data: UpsertPriceSetDTO[], sharedContext?: Context ): Promise @@ -422,12 +425,15 @@ export interface IPricingModuleService extends IModuleService { * @returns {Promise} The updated or created price set. * * @example - * const priceSet = await pricingModuleService.upsert({ + * const priceSet = await pricingModuleService.upsertPriceSets({ * id: "pset_123", * rules: [{ rule_attribute: "region_id" }], * }) */ - upsert(data: UpsertPriceSetDTO, sharedContext?: Context): Promise + upsertPriceSets( + data: UpsertPriceSetDTO, + sharedContext?: Context + ): Promise /** * This method is used to update a price set. @@ -438,14 +444,14 @@ export interface IPricingModuleService extends IModuleService { * @returns {Promise} The updated price set. * * @example - * const priceSet = await pricingModuleService.update( + * const priceSet = await pricingModuleService.updatePriceSets( * "pset_123", * { * rules: [{ rule_attribute: "region_id" }], * } * ) */ - update( + updatePriceSets( id: string, data: UpdatePriceSetDTO, sharedContext?: Context @@ -460,7 +466,7 @@ export interface IPricingModuleService extends IModuleService { * @returns {Promise} The updated price sets. * * @example - * const priceSets = await pricingModuleService.update( + * const priceSets = await pricingModuleService.updatePriceSets( * { * id: ["pset_123", "pset_321"], * }, @@ -469,7 +475,7 @@ export interface IPricingModuleService extends IModuleService { * } * ) */ - update( + updatePriceSets( selector: FilterablePriceSetProps, data: UpdatePriceSetDTO, sharedContext?: Context @@ -503,9 +509,9 @@ export interface IPricingModuleService extends IModuleService { * @returns {Promise} Resolves when the price sets are successfully deleted. * * @example - * await pricingModuleService.delete(["pset_123", "pset_321"]) + * await pricingModuleService.deletePriceSets(["pset_123", "pset_321"]) */ - delete(ids: string[], sharedContext?: Context): Promise + deletePriceSets(ids: string[], sharedContext?: Context): Promise /** * This method adds prices to a price set. diff --git a/packages/core/types/src/product/common.ts b/packages/core/types/src/product/common.ts index 778a153179..9f0e046988 100644 --- a/packages/core/types/src/product/common.ts +++ b/packages/core/types/src/product/common.ts @@ -1356,6 +1356,10 @@ export interface UpdateProductVariantDTO { * A product to create. */ export interface CreateProductDTO { + /** + * Optionally pass an ID when creating a product. + */ + id?: string /** * The title of the product. */ diff --git a/packages/core/types/src/product/service.ts b/packages/core/types/src/product/service.ts index 88f23afc3f..4650e8b24f 100644 --- a/packages/core/types/src/product/service.ts +++ b/packages/core/types/src/product/service.ts @@ -60,13 +60,13 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const product = - * await productModuleService.retrieve("prod_123") + * await productModuleService.retrieveProduct("prod_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const product = await productModuleService.retrieve( + * const product = await productModuleService.retrieveProduct( * "prod_123", * { * relations: ["categories"], @@ -74,7 +74,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - retrieve( + retrieveProduct( productId: string, config?: FindConfig, sharedContext?: Context @@ -94,7 +94,7 @@ export interface IProductModuleService extends IModuleService { * To retrieve a list of products using their IDs: * * ```ts - * const products = await productModuleService.list({ + * const products = await productModuleService.listProducts({ * id: ["prod_123", "prod_321"], * }) * ``` @@ -102,7 +102,7 @@ export interface IProductModuleService extends IModuleService { * To specify relations that should be retrieved within the products: * * ```ts - * const products = await productModuleService.list( + * const products = await productModuleService.listProducts( * { * id: ["prod_123", "prod_321"], * }, @@ -115,7 +115,7 @@ export interface IProductModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const products = await productModuleService.list( + * const products = await productModuleService.listProducts( * { * id: ["prod_123", "prod_321"], * }, @@ -127,7 +127,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - list( + listProducts( filters?: FilterableProductProps, config?: FindConfig, sharedContext?: Context @@ -148,7 +148,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [products, count] = - * await productModuleService.listAndCount({ + * await productModuleService.listAndCountProducts({ * id: ["prod_123", "prod_321"], * }) * ``` @@ -157,7 +157,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [products, count] = - * await productModuleService.listAndCount( + * await productModuleService.listAndCountProducts( * { * id: ["prod_123", "prod_321"], * }, @@ -171,7 +171,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [products, count] = - * await productModuleService.listAndCount( + * await productModuleService.listAndCountProducts( * { * id: ["prod_123", "prod_321"], * }, @@ -183,7 +183,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountProducts( filters?: FilterableProductProps, config?: FindConfig, sharedContext?: Context @@ -197,7 +197,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The list of created products. * * @example - * const products = await productModuleService.create([ + * const products = await productModuleService.createProducts([ * { * title: "Shirt", * }, @@ -207,7 +207,7 @@ export interface IProductModuleService extends IModuleService { * }, * ]) */ - create( + createProducts( data: CreateProductDTO[], sharedContext?: Context ): Promise @@ -220,11 +220,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The created product. * * @example - * const product = await productModuleService.create({ + * const product = await productModuleService.createProducts({ * title: "Shirt", * }) */ - create(data: CreateProductDTO, sharedContext?: Context): Promise + createProducts( + data: CreateProductDTO, + sharedContext?: Context + ): Promise /** * This method updates existing products, or creates new ones if they don't exist. @@ -234,7 +237,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated and created products. * * @example - * const products = await productModuleService.upsert([ + * const products = await productModuleService.upsertProducts([ * { * id: "prod_123", * handle: "pant", @@ -244,7 +247,7 @@ export interface IProductModuleService extends IModuleService { * }, * ]) */ - upsert( + upsertProducts( data: UpsertProductDTO[], sharedContext?: Context ): Promise @@ -257,11 +260,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated or created product. * * @example - * const product = await productModuleService.upsert({ + * const product = await productModuleService.upsertProducts({ * title: "Shirt", * }) */ - upsert(data: UpsertProductDTO, sharedContext?: Context): Promise + upsertProducts( + data: UpsertProductDTO, + sharedContext?: Context + ): Promise /** * This method is used to update a product. @@ -272,14 +278,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated product. * * @example - * const product = await productModuleService.update( + * const product = await productModuleService.updateProducts( * "prod_123", * { * handle: "pant", * } * ) */ - update( + updateProducts( id: string, data: UpdateProductDTO, sharedContext?: Context @@ -294,7 +300,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated products. * * @example - * const products = await productModuleService.update( + * const products = await productModuleService.updateProducts( * { * title: "Pant", * }, @@ -303,7 +309,7 @@ export interface IProductModuleService extends IModuleService { * } * ) */ - update( + updateProducts( selector: FilterableProductProps, data: UpdateProductDTO, sharedContext?: Context @@ -317,9 +323,9 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} Resolves when the products are successfully deleted. * * @example - * await productModuleService.delete(["prod_123", "prod_321"]) + * await productModuleService.deleteProducts(["prod_123", "prod_321"]) */ - delete(productIds: string[], sharedContext?: Context): Promise + deleteProducts(productIds: string[], sharedContext?: Context): Promise /** * This method is used to delete products. Unlike the {@link delete} method, this method won't completely remove the product. It can still be accessed or retrieved using methods like {@link retrieve} if you pass the `withDeleted` property to the `config` object parameter. @@ -337,12 +343,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records, the promise resolved to `void`. * * @example - * await productModuleService.softDelete([ + * await productModuleService.softDeleteProducts([ * "prod_123", * "prod_321", * ]) */ - softDelete( + softDeleteProducts( productIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -362,9 +368,9 @@ export interface IProductModuleService extends IModuleService { * If there are no related records that were restored, the promise resolved to `void`. * * @example - * await productModuleService.restore(["prod_123", "prod_321"]) + * await productModuleService.restoreProducts(["prod_123", "prod_321"]) */ - restore( + restoreProducts( productIds: string[], config?: RestoreReturn, sharedContext?: Context @@ -384,13 +390,13 @@ export interface IProductModuleService extends IModuleService { * A simple example that retrieves a product tag by its ID: * * ```ts - * const tag = await productModuleService.retrieveTag("ptag_123") + * const tag = await productModuleService.retrieveProductTag("ptag_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const tag = await productModuleService.retrieveTag( + * const tag = await productModuleService.retrieveProductTag( * "ptag_123", * { * relations: ["products"], @@ -398,7 +404,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - retrieveTag( + retrieveProductTag( tagId: string, config?: FindConfig, sharedContext?: Context @@ -418,7 +424,7 @@ export interface IProductModuleService extends IModuleService { * To retrieve a list of product tags using their IDs: * * ```ts - * const tags = await productModuleService.listTags({ + * const tags = await productModuleService.listProductTags({ * id: ["ptag_123", "ptag_321"], * }) * ``` @@ -426,7 +432,7 @@ export interface IProductModuleService extends IModuleService { * To specify relations that should be retrieved within the product tags: * * ```ts - * const tags = await productModuleService.listTags( + * const tags = await productModuleService.listProductTags( * { * id: ["ptag_123", "ptag_321"], * }, @@ -439,7 +445,7 @@ export interface IProductModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const tags = await productModuleService.listTags( + * const tags = await productModuleService.listProductTags( * { * id: ["ptag_123", "ptag_321"], * }, @@ -451,7 +457,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listTags( + listProductTags( filters?: FilterableProductTagProps, config?: FindConfig, sharedContext?: Context @@ -472,7 +478,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [tags, count] = - * await productModuleService.listAndCountTags({ + * await productModuleService.listAndCountProductTags({ * id: ["ptag_123", "ptag_321"], * }) * ``` @@ -481,7 +487,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [tags, count] = - * await productModuleService.listAndCountTags( + * await productModuleService.listAndCountProductTags( * { * id: ["ptag_123", "ptag_321"], * }, @@ -495,7 +501,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [tags, count] = - * await productModuleService.listAndCountTags( + * await productModuleService.listAndCountProductTags( * { * id: ["ptag_123", "ptag_321"], * }, @@ -507,7 +513,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listAndCountTags( + listAndCountProductTags( filters?: FilterableProductTagProps, config?: FindConfig, sharedContext?: Context @@ -521,13 +527,13 @@ export interface IProductModuleService extends IModuleService { * @return {Promise} The list of created product tags. * * @example - * const productTags = await productModuleService.createTags([ + * const productTags = await productModuleService.createProductTags([ * { * value: "digital", * }, * ]) */ - createTags( + createProductTags( data: CreateProductTagDTO[], sharedContext?: Context ): Promise @@ -540,12 +546,12 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The created product tag. * * @example - * const productTag = await productModuleService.createTags({ + * const productTag = await productModuleService.createProductTags({ * value: "digital", * }) * */ - createTags( + createProductTags( data: CreateProductTagDTO, sharedContext?: Context ): Promise @@ -558,7 +564,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated and created tags. * * @example - * const productTags = await productModuleService.upsertTags([ + * const productTags = await productModuleService.upsertProductTags([ * { * id: "ptag_123", * metadata: { @@ -570,7 +576,7 @@ export interface IProductModuleService extends IModuleService { * }, * ]) */ - upsertTags( + upsertProductTags( data: UpsertProductTagDTO[], sharedContext?: Context ): Promise @@ -583,14 +589,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated or created tag. * * @example - * const productTag = await productModuleService.upsertTags({ + * const productTag = await productModuleService.upsertProductTags({ * id: "ptag_123", * metadata: { * test: true, * }, * }) */ - upsertTags( + upsertProductTags( data: UpsertProductTagDTO, sharedContext?: Context ): Promise @@ -604,14 +610,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated tag. * * @example - * const productTag = await productModuleService.updateTags( + * const productTag = await productModuleService.updateProductTags( * "ptag_123", * { * value: "Digital", * } * ) */ - updateTags( + updateProductTags( id: string, data: UpdateProductTagDTO, sharedContext?: Context @@ -626,7 +632,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated tags. * * @example - * const productTags = await productModuleService.updateTags( + * const productTags = await productModuleService.updateProductTags( * { * id: ["ptag_123", "ptag_321"], * }, @@ -635,7 +641,7 @@ export interface IProductModuleService extends IModuleService { * } * ) */ - updateTags( + updateProductTags( selector: FilterableProductTagProps, data: UpdateProductTagDTO, sharedContext?: Context @@ -649,12 +655,15 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} Resolves when the product tags are successfully deleted. * * @example - * await productModuleService.deleteTags([ + * await productModuleService.deleteProductTags([ * "ptag_123", * "ptag_321", * ]) */ - deleteTags(productTagIds: string[], sharedContext?: Context): Promise + deleteProductTags( + productTagIds: string[], + sharedContext?: Context + ): Promise /** * This method is used to delete tags. Unlike the {@link delete} method, this method won't completely remove the tag. It can still be accessed or retrieved using methods like {@link retrieve} if you pass the `withDeleted` property to the `config` object parameter. @@ -672,12 +681,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records, the promise resolved to `void`. * * @example - * await productModuleService.softDeleteTags([ + * await productModuleService.softDeleteProductTags([ * "ptag_123", * "ptag_321", * ]) */ - softDeleteTags( + softDeleteProductTags( tagIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -697,12 +706,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records that were restored, the promise resolved to `void`. * * @example - * await productModuleService.restoreTags([ + * await productModuleService.restoreProductTags([ * "ptag_123", * "ptag_321", * ]) */ - restoreTags( + restoreProductTags( tagIds: string[], config?: RestoreReturn, sharedContext?: Context @@ -720,9 +729,9 @@ export interface IProductModuleService extends IModuleService { * * @example * const productType = - * await productModuleService.retrieveType("ptyp_123") + * await productModuleService.retrieveProductType("ptyp_123") */ - retrieveType( + retrieveProductType( typeId: string, config?: FindConfig, sharedContext?: Context @@ -742,7 +751,7 @@ export interface IProductModuleService extends IModuleService { * To retrieve a list of product types using their IDs: * * ```ts - * const productTypes = await productModuleService.listTypes({ + * const productTypes = await productModuleService.listProductTypes({ * id: ["ptyp_123", "ptyp_321"], * }) * ``` @@ -750,7 +759,7 @@ export interface IProductModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const productTypes = await productModuleService.listTypes( + * const productTypes = await productModuleService.listProductTypes( * { * id: ["ptyp_123", "ptyp_321"], * }, @@ -761,7 +770,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listTypes( + listProductTypes( filters?: FilterableProductTypeProps, config?: FindConfig, sharedContext?: Context @@ -782,7 +791,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [productTypes, count] = - * await productModuleService.listAndCountTypes({ + * await productModuleService.listAndCountProductTypes({ * id: ["ptyp_123", "ptyp_321"], * }) * ``` @@ -791,7 +800,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [productTypes, count] = - * await productModuleService.listAndCountTypes( + * await productModuleService.listAndCountProductTypes( * { * id: ["ptyp_123", "ptyp_321"], * }, @@ -802,7 +811,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listAndCountTypes( + listAndCountProductTypes( filters?: FilterableProductTypeProps, config?: FindConfig, sharedContext?: Context @@ -816,13 +825,13 @@ export interface IProductModuleService extends IModuleService { * @return {Promise} The list of created product types. * * @example - * const productTypes = await productModuleService.createTypes([ + * const productTypes = await productModuleService.createProductTypes([ * { * value: "digital", * }, * ]) */ - createTypes( + createProductTypes( data: CreateProductTypeDTO[], sharedContext?: Context ): Promise @@ -835,12 +844,12 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The created product type. * * @example - * const productType = await productModuleService.createTypes({ + * const productType = await productModuleService.createProductTypes({ * value: "digital", * }) * */ - createTypes( + createProductTypes( data: CreateProductTypeDTO, sharedContext?: Context ): Promise @@ -853,7 +862,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated and created types. * * @example - * const productTypes = await productModuleService.upsertTypes([ + * const productTypes = await productModuleService.upsertProductTypes([ * { * id: "ptyp_123", * metadata: { @@ -865,7 +874,7 @@ export interface IProductModuleService extends IModuleService { * }, * ]) */ - upsertTypes( + upsertProductTypes( data: UpsertProductTypeDTO[], sharedContext?: Context ): Promise @@ -878,14 +887,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated or created type. * * @example - * const productType = await productModuleService.upsertTypes({ + * const productType = await productModuleService.upsertProductTypes({ * id: "ptyp_123", * metadata: { * test: true, * }, * }) */ - upsertTypes( + upsertProductTypes( data: UpsertProductTypeDTO, sharedContext?: Context ): Promise @@ -899,14 +908,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated type. * * @example - * const productType = await productModuleService.updateTypes( + * const productType = await productModuleService.updateProductTypes( * "ptyp_123", * { * value: "Digital", * } * ) */ - updateTypes( + updateProductTypes( id: string, data: UpdateProductTypeDTO, sharedContext?: Context @@ -921,7 +930,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated types. * * @example - * const productTypes = await productModuleService.updateTypes( + * const productTypes = await productModuleService.updateProductTypes( * { * id: ["ptyp_123", "ptyp_321"], * }, @@ -930,7 +939,7 @@ export interface IProductModuleService extends IModuleService { * } * ) */ - updateTypes( + updateProductTypes( selector: FilterableProductTypeProps, data: UpdateProductTypeDTO, sharedContext?: Context @@ -944,12 +953,15 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} Resolves when the product types are successfully deleted. * * @example - * await productModuleService.deleteTypes([ + * await productModuleService.deleteProductTypes([ * "ptyp_123", * "ptyp_321", * ]) */ - deleteTypes(productTypeIds: string[], sharedContext?: Context): Promise + deleteProductTypes( + productTypeIds: string[], + sharedContext?: Context + ): Promise /** * This method is used to delete types. Unlike the {@link delete} method, this method won't completely remove the type. It can still be accessed or retrieved using methods like {@link retrieve} if you pass the `withDeleted` property to the `config` object parameter. @@ -967,12 +979,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records, the promise resolved to `void`. * * @example - * await productModuleService.softDeleteTypes([ + * await productModuleService.softDeleteProductTypes([ * "ptyp_123", * "ptyp_321", * ]) */ - softDeleteTypes( + softDeleteProductTypes( typeIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -992,12 +1004,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records that were restored, the promise resolved to `void`. * * @example - * await productModuleService.restoreTypes([ + * await productModuleService.restoreProductTypes([ * "ptyp_123", * "ptyp_321", * ]) */ - restoreTypes( + restoreProductTypes( typeIds: string[], config?: RestoreReturn, sharedContext?: Context @@ -1018,13 +1030,13 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const option = - * await productModuleService.retrieveOption("opt_123") + * await productModuleService.retrieveProductOption("opt_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const option = await productModuleService.retrieveOption( + * const option = await productModuleService.retrieveProductOption( * "opt_123", * { * relations: ["product"], @@ -1032,7 +1044,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - retrieveOption( + retrieveProductOption( optionId: string, config?: FindConfig, sharedContext?: Context @@ -1052,7 +1064,7 @@ export interface IProductModuleService extends IModuleService { * To retrieve a list of product options using their IDs: * * ```ts - * const options = await productModuleService.listOptions({ + * const options = await productModuleService.listProductOptions({ id: ["opt_123", "opt_321"], * }) * ``` @@ -1060,7 +1072,7 @@ export interface IProductModuleService extends IModuleService { * To specify relations that should be retrieved within the product options: * * ```ts - * const options = await productModuleService.listOptions( + * const options = await productModuleService.listProductOptions( * { * id: ["opt_123", "opt_321"], * }, @@ -1073,7 +1085,7 @@ export interface IProductModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const options = await productModuleService.listOptions( + * const options = await productModuleService.listProductOptions( * { * id: ["opt_123", "opt_321"], * }, @@ -1086,7 +1098,7 @@ export interface IProductModuleService extends IModuleService { * ``` * */ - listOptions( + listProductOptions( filters?: FilterableProductOptionProps, config?: FindConfig, sharedContext?: Context @@ -1107,7 +1119,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [options, count] = - * await productModuleService.listAndCountOptions({ + * await productModuleService.listAndCountProductOptions({ * id: ["opt_123", "opt_321"], * }) * ``` @@ -1116,7 +1128,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [options, count] = - * await productModuleService.listAndCountOptions( + * await productModuleService.listAndCountProductOptions( * { * id: ["opt_123", "opt_321"], * }, @@ -1130,7 +1142,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [options, count] = - * await productModuleService.listAndCountOptions( + * await productModuleService.listAndCountProductOptions( * { * id: ["opt_123", "opt_321"], * }, @@ -1142,7 +1154,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listAndCountOptions( + listAndCountProductOptions( filters?: FilterableProductOptionProps, config?: FindConfig, sharedContext?: Context @@ -1156,7 +1168,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The list of created product options. * * @example - * const options = await productModuleService.createOptions([ + * const options = await productModuleService.createProductOptions([ * { * title: "Color", * values: ["Blue", "Green"], @@ -1170,7 +1182,7 @@ export interface IProductModuleService extends IModuleService { * ]) * */ - createOptions( + createProductOptions( data: CreateProductOptionDTO[], sharedContext?: Context ): Promise @@ -1183,14 +1195,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The created product option. * * @example - * const option = await productModuleService.createOptions({ + * const option = await productModuleService.createProductOptions({ * title: "Color", * values: ["Blue", "Green"], * product_id: "prod_123", * }) * */ - createOptions( + createProductOptions( data: CreateProductOptionDTO, sharedContext?: Context ): Promise @@ -1203,7 +1215,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated and created options. * * @example - * const options = await productModuleService.upsertOptions([ + * const options = await productModuleService.upsertProductOptions([ * { * id: "opt_123", * title: "Color", @@ -1215,7 +1227,7 @@ export interface IProductModuleService extends IModuleService { * }, * ]) */ - upsertOptions( + upsertProductOptions( data: UpsertProductOptionDTO[], sharedContext?: Context ): Promise @@ -1228,12 +1240,12 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated or created option. * * @example - * const option = await productModuleService.upsertOptions({ + * const option = await productModuleService.upsertProductOptions({ * id: "opt_123", * title: "Color", * }) */ - upsertOptions( + upsertProductOptions( data: UpsertProductOptionDTO, sharedContext?: Context ): Promise @@ -1247,14 +1259,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated option. * * @example - * const option = await productModuleService.updateOptions( + * const option = await productModuleService.updateProductOptions( * "opt_123", * { * title: "Color", * } * ) */ - updateOptions( + updateProductOptions( id: string, data: UpdateProductOptionDTO, sharedContext?: Context @@ -1269,7 +1281,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated options. * * @example - * const options = await productModuleService.updateOptions( + * const options = await productModuleService.updateProductOptions( * { * title: "Color", * }, @@ -1278,7 +1290,7 @@ export interface IProductModuleService extends IModuleService { * } * ) */ - updateOptions( + updateProductOptions( selector: FilterableProductOptionProps, data: UpdateProductOptionDTO, sharedContext?: Context @@ -1292,12 +1304,12 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} Resolves when the product options are successfully deleted. * * @example - * await productModuleService.deleteOptions([ + * await productModuleService.deleteProductOptions([ * "opt_123", * "opt_321", * ]) */ - deleteOptions( + deleteProductOptions( productOptionIds: string[], sharedContext?: Context ): Promise @@ -1318,12 +1330,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records, the promise resolved to `void`. * * @example - * await productModuleService.softDeleteOptions([ + * await productModuleService.softDeleteProductOptions([ * "opt_123", * "opt_321", * ]) */ - softDeleteOptions( + softDeleteProductOptions( optionIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -1343,12 +1355,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records that were restored, the promise resolved to `void`. * * @example - * await productModuleService.restoreOptions([ + * await productModuleService.restoreProductOptions([ * "opt_123", * "opt_321", * ]) */ - restoreOptions( + restoreProductOptions( optionIds: string[], config?: RestoreReturn, sharedContext?: Context @@ -1369,13 +1381,13 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const variant = - * await productModuleService.retrieveVariant("variant_123") + * await productModuleService.retrieveProductVariant("variant_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const variant = await productModuleService.retrieveVariant( + * const variant = await productModuleService.retrieveProductVariant( * "variant_123", * { * relations: ["options"], @@ -1383,7 +1395,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - retrieveVariant( + retrieveProductVariant( productVariantId: string, config?: FindConfig, sharedContext?: Context @@ -1403,7 +1415,7 @@ export interface IProductModuleService extends IModuleService { * To retrieve a list of product variants using their IDs: * * ```ts - * const variants = await productModuleService.listVariants({ + * const variants = await productModuleService.listProductVariants({ * id: ["variant_123", "variant_321"], * }) * ``` @@ -1411,7 +1423,7 @@ export interface IProductModuleService extends IModuleService { * To specify relations that should be retrieved within the product variants: * * ```ts - * const variants = await productModuleService.listVariants( + * const variants = await productModuleService.listProductVariants( * { * id: ["variant_123", "variant_321"], * }, @@ -1424,7 +1436,7 @@ export interface IProductModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const variants = await productModuleService.listVariants( + * const variants = await productModuleService.listProductVariants( * { * id: ["variant_123", "variant_321"], * }, @@ -1436,7 +1448,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listVariants( + listProductVariants( filters?: FilterableProductVariantProps, config?: FindConfig, sharedContext?: Context @@ -1457,7 +1469,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [variants, count] = - * await productModuleService.listAndCountVariants({ + * await productModuleService.listAndCountProductVariants({ * id: ["variant_123", "variant_321"], * }) * ``` @@ -1466,7 +1478,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [variants, count] = - * await productModuleService.listAndCountVariants( + * await productModuleService.listAndCountProductVariants( * { * id: ["variant_123", "variant_321"], * }, @@ -1480,7 +1492,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [variants, count] = - * await productModuleService.listAndCountVariants( + * await productModuleService.listAndCountProductVariants( * { * id: ["variant_123", "variant_321"], * }, @@ -1492,7 +1504,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listAndCountVariants( + listAndCountProductVariants( filters?: FilterableProductVariantProps, config?: FindConfig, sharedContext?: Context @@ -1506,7 +1518,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The list of created product variants. * * @example - * const variants = await productModuleService.createVariants([ + * const variants = await productModuleService.createProductVariants([ * { * title: "Blue Shirt", * product_id: "prod_123", @@ -1524,7 +1536,7 @@ export interface IProductModuleService extends IModuleService { * ]) * */ - createVariants( + createProductVariants( data: CreateProductVariantDTO[], sharedContext?: Context ): Promise @@ -1537,7 +1549,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The created product variant. * * @example - * const variant = await productModuleService.createVariants({ + * const variant = await productModuleService.createProductVariants({ * title: "Blue Shirt", * product_id: "prod_123", * options: { @@ -1546,7 +1558,7 @@ export interface IProductModuleService extends IModuleService { * }) * */ - createVariants( + createProductVariants( data: CreateProductVariantDTO, sharedContext?: Context ): Promise @@ -1559,7 +1571,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated and created variants. * * @example - * const variants = await productModuleService.upsertVariants([ + * const variants = await productModuleService.upsertProductVariants([ * { * id: "variant_123", * title: "Green Shirt", @@ -1572,7 +1584,7 @@ export interface IProductModuleService extends IModuleService { * }, * ]) */ - upsertVariants( + upsertProductVariants( data: UpsertProductVariantDTO[], sharedContext?: Context ): Promise @@ -1585,12 +1597,12 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated or created variant. * * @example - * const variant = await productModuleService.upsertVariants({ + * const variant = await productModuleService.upsertProductVariants({ * id: "variant_123", * title: "Green Shirt", * }) */ - upsertVariants( + upsertProductVariants( data: UpsertProductVariantDTO, sharedContext?: Context ): Promise @@ -1604,14 +1616,14 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated variant. * * @example - * const variant = await productModuleService.updateVariants( + * const variant = await productModuleService.updateProductVariants( * "variant_123", * { * title: "Blue Shirt", * } * ) */ - updateVariants( + updateProductVariants( id: string, data: UpdateProductVariantDTO, sharedContext?: Context @@ -1626,7 +1638,7 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} The updated variants. * * @example - * const variants = await productModuleService.updateVariants( + * const variants = await productModuleService.updateProductVariants( * { * id: ["variant_123", "variant_321"], * }, @@ -1635,7 +1647,7 @@ export interface IProductModuleService extends IModuleService { * } * ) */ - updateVariants( + updateProductVariants( selector: FilterableProductVariantProps, data: UpdateProductVariantDTO, sharedContext?: Context @@ -1649,12 +1661,12 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} Resolves when the ProductVariant are successfully deleted. * * @example - * await productModuleService.deleteVariants([ + * await productModuleService.deleteProductVariants([ * "variant_123", * "variant_321", * ]) */ - deleteVariants( + deleteProductVariants( productVariantIds: string[], sharedContext?: Context ): Promise @@ -1675,12 +1687,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records, the promise resolved to `void`. * * @example - * await productModuleService.softDeleteVariants([ + * await productModuleService.softDeleteProductVariants([ * "variant_123", * "variant_321", * ]) */ - softDeleteVariants( + softDeleteProductVariants( variantIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -1700,12 +1712,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records that were restored, the promise resolved to `void`. * * @example - * await productModuleService.restoreVariants([ + * await productModuleService.restoreProductVariants([ * "variant_123", * "variant_321", * ]) */ - restoreVariants( + restoreProductVariants( variantIds: string[], config?: RestoreReturn, sharedContext?: Context @@ -1726,19 +1738,19 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const collection = - * await productModuleService.retrieveCollection("pcol_123") + * await productModuleService.retrieveProductCollection("pcol_123") * ``` * * To specify relations that should be retrieved: * * ```ts * const collection = - * await productModuleService.retrieveCollection("pcol_123", { + * await productModuleService.retrieveProductCollection("pcol_123", { * relations: ["products"], * }) * ``` */ - retrieveCollection( + retrieveProductCollection( productCollectionId: string, config?: FindConfig, sharedContext?: Context @@ -1759,7 +1771,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const collections = - * await productModuleService.listCollections({ + * await productModuleService.listProductCollections({ * id: ["pcol_123", "pcol_321"], * }) * ``` @@ -1768,7 +1780,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const collections = - * await productModuleService.listCollections( + * await productModuleService.listProductCollections( * { * id: ["pcol_123", "pcol_321"], * }, @@ -1782,7 +1794,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const collections = - * await productModuleService.listCollections( + * await productModuleService.listProductCollections( * { * id: ["pcol_123", "pcol_321"], * }, @@ -1794,7 +1806,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listCollections( + listProductCollections( filters?: FilterableProductCollectionProps, config?: FindConfig, sharedContext?: Context @@ -1815,7 +1827,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [collections, count] = - * await productModuleService.listAndCountCollections({ + * await productModuleService.listAndCountProductCollections({ * id: ["pcol_123", "pcol_321"], * }) * ``` @@ -1824,7 +1836,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [collections, count] = - * await productModuleService.listAndCountCollections( + * await productModuleService.listAndCountProductCollections( * { * id: ["pcol_123", "pcol_321"], * }, @@ -1838,7 +1850,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [collections, count] = - * await productModuleService.listAndCountCollections( + * await productModuleService.listAndCountProductCollections( * { * id: ["pcol_123", "pcol_321"], * }, @@ -1850,7 +1862,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listAndCountCollections( + listAndCountProductCollections( filters?: FilterableProductCollectionProps, config?: FindConfig, sharedContext?: Context @@ -1865,7 +1877,7 @@ export interface IProductModuleService extends IModuleService { * * @example * const collections = - * await productModuleService.createCollections([ + * await productModuleService.createProductCollections([ * { * title: "Summer Collection", * }, @@ -1875,7 +1887,7 @@ export interface IProductModuleService extends IModuleService { * ]) * */ - createCollections( + createProductCollections( data: CreateProductCollectionDTO[], sharedContext?: Context ): Promise @@ -1889,12 +1901,12 @@ export interface IProductModuleService extends IModuleService { * * @example * const collection = - * await productModuleService.createCollections({ + * await productModuleService.createProductCollections({ * title: "Summer Collection", * }) * */ - createCollections( + createProductCollections( data: CreateProductCollectionDTO, sharedContext?: Context ): Promise @@ -1908,7 +1920,7 @@ export interface IProductModuleService extends IModuleService { * * @example * const collections = - * await productModuleService.upsertCollections([ + * await productModuleService.upsertProductCollections([ * { * id: "pcol_123", * title: "Winter Collection", @@ -1918,7 +1930,7 @@ export interface IProductModuleService extends IModuleService { * }, * ]) */ - upsertCollections( + upsertProductCollections( data: UpsertProductCollectionDTO[], sharedContext?: Context ): Promise @@ -1932,12 +1944,12 @@ export interface IProductModuleService extends IModuleService { * * @example * const collection = - * await productModuleService.upsertCollections({ + * await productModuleService.upsertProductCollections({ * id: "pcol_123", * title: "Winter Collection", * }) */ - upsertCollections( + upsertProductCollections( data: UpsertProductCollectionDTO, sharedContext?: Context ): Promise @@ -1952,11 +1964,11 @@ export interface IProductModuleService extends IModuleService { * * @example * const collection = - * await productModuleService.updateCollections("pcol_123", { + * await productModuleService.updateProductCollections("pcol_123", { * title: "Summer Collection", * }) */ - updateCollections( + updateProductCollections( id: string, data: UpdateProductCollectionDTO, sharedContext?: Context @@ -1972,7 +1984,7 @@ export interface IProductModuleService extends IModuleService { * * @example * const collections = - * await productModuleService.updateCollections( + * await productModuleService.updateProductCollections( * { * id: ["pcol_123", "pcol_321"], * }, @@ -1981,7 +1993,7 @@ export interface IProductModuleService extends IModuleService { * } * ) */ - updateCollections( + updateProductCollections( selector: FilterableProductCollectionProps, data: UpdateProductCollectionDTO, sharedContext?: Context @@ -1995,13 +2007,13 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} Resolves when the product options are successfully deleted. * * @example - * await productModuleService.deleteCollections([ + * await productModuleService.deleteProductCollections([ * "pcol_123", * "pcol_321", * ]) * */ - deleteCollections( + deleteProductCollections( productCollectionIds: string[], sharedContext?: Context ): Promise @@ -2022,12 +2034,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records, the promise resolved to `void`. * * @example - * await productModuleService.softDeleteCollections([ + * await productModuleService.softDeleteProductCollections([ * "pcol_123", * "pcol_321", * ]) */ - softDeleteCollections( + softDeleteProductCollections( collectionIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -2047,12 +2059,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records that were restored, the promise resolved to `void`. * * @example - * await productModuleService.restoreCollections([ + * await productModuleService.restoreProductCollections([ * "pcol_123", * "pcol_321", * ]) */ - restoreCollections( + restoreProductCollections( collectionIds: string[], config?: RestoreReturn, sharedContext?: Context @@ -2073,13 +2085,13 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const category = - * await productModuleService.retrieveCategory("pcat_123") + * await productModuleService.retrieveProductCategory("pcat_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const category = await productModuleService.retrieveCategory( + * const category = await productModuleService.retrieveProductCategory( * "pcat_123", * { * relations: ["products"], @@ -2087,7 +2099,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - retrieveCategory( + retrieveProductCategory( productCategoryId: string, config?: FindConfig, sharedContext?: Context @@ -2107,7 +2119,7 @@ export interface IProductModuleService extends IModuleService { * To retrieve a list of product categories using their IDs: * * ```ts - * const categories = await productModuleService.listCategories({ + * const categories = await productModuleService.listProductCategories({ * id: ["pcat_123", "pcat_321"], * }) * ``` @@ -2115,7 +2127,7 @@ export interface IProductModuleService extends IModuleService { * To specify relations that should be retrieved within the product categories: * * ```ts - * const categories = await productModuleService.listCategories( + * const categories = await productModuleService.listProductCategories( * { * id: ["pcat_123", "pcat_321"], * }, @@ -2128,7 +2140,7 @@ export interface IProductModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const categories = await productModuleService.listCategories( + * const categories = await productModuleService.listProductCategories( * { * id: ["pcat_123", "pcat_321"], * }, @@ -2140,7 +2152,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listCategories( + listProductCategories( filters?: FilterableProductCategoryProps, config?: FindConfig, sharedContext?: Context @@ -2161,7 +2173,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [categories, count] = - * await productModuleService.listAndCountCategories({ + * await productModuleService.listAndCountProductCategories({ * id: ["pcat_123", "pcat_321"], * }) * ``` @@ -2170,7 +2182,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [categories, count] = - * await productModuleService.listAndCountCategories( + * await productModuleService.listAndCountProductCategories( * { * id: ["pcat_123", "pcat_321"], * }, @@ -2184,7 +2196,7 @@ export interface IProductModuleService extends IModuleService { * * ```ts * const [categories, count] = - * await productModuleService.listAndCountCategories( + * await productModuleService.listAndCountProductCategories( * { * id: ["pcat_123", "pcat_321"], * }, @@ -2196,7 +2208,7 @@ export interface IProductModuleService extends IModuleService { * ) * ``` */ - listAndCountCategories( + listAndCountProductCategories( filters?: FilterableProductCategoryProps, config?: FindConfig, sharedContext?: Context @@ -2211,7 +2223,7 @@ export interface IProductModuleService extends IModuleService { * * @example * const categories = - * await productModuleService.createCategories([ + * await productModuleService.createProductCategories([ * { * name: "Tools", * }, @@ -2221,7 +2233,7 @@ export interface IProductModuleService extends IModuleService { * ]) * */ - createCategories( + createProductCategories( data: CreateProductCategoryDTO[], sharedContext?: Context ): Promise @@ -2235,12 +2247,12 @@ export interface IProductModuleService extends IModuleService { * * @example * const category = - * await productModuleService.createCategories({ + * await productModuleService.createProductCategories({ * name: "Tools", * }) * */ - createCategories( + createProductCategories( data: CreateProductCategoryDTO, sharedContext?: Context ): Promise @@ -2254,7 +2266,7 @@ export interface IProductModuleService extends IModuleService { * * @example * const categories = - * await productModuleService.upsertCategories([ + * await productModuleService.upsertProductCategories([ * { * id: "pcat_123", * name: "Clothing", @@ -2264,7 +2276,7 @@ export interface IProductModuleService extends IModuleService { * }, * ]) */ - upsertCategories( + upsertProductCategories( data: UpsertProductCategoryDTO[], sharedContext?: Context ): Promise @@ -2278,12 +2290,12 @@ export interface IProductModuleService extends IModuleService { * * @example * const category = - * await productModuleService.upsertCategories({ + * await productModuleService.upsertProductCategories({ * id: "pcat_123", * name: "Clothing", * }) */ - upsertCategories( + upsertProductCategories( data: UpsertProductCategoryDTO, sharedContext?: Context ): Promise @@ -2298,11 +2310,11 @@ export interface IProductModuleService extends IModuleService { * * @example * const category = - * await productModuleService.updateCategories("pcat_123", { + * await productModuleService.updateProductCategories("pcat_123", { * title: "Tools", * }) */ - updateCategories( + updateProductCategories( id: string, data: UpdateProductCategoryDTO, sharedContext?: Context @@ -2318,7 +2330,7 @@ export interface IProductModuleService extends IModuleService { * * @example * const categories = - * await productModuleService.updateCategories( + * await productModuleService.updateProductCategories( * { * id: ["pcat_123", "pcat_321"], * }, @@ -2327,7 +2339,7 @@ export interface IProductModuleService extends IModuleService { * } * ) */ - updateCategories( + updateProductCategories( selector: FilterableProductCategoryProps, data: UpdateProductCategoryDTO, sharedContext?: Context @@ -2341,13 +2353,13 @@ export interface IProductModuleService extends IModuleService { * @returns {Promise} Resolves when the product options are successfully deleted. * * @example - * await productModuleService.deleteCategories([ + * await productModuleService.deleteProductCategories([ * "pcat_123", * "pcat_321", * ]) * */ - deleteCategories( + deleteProductCategories( productCategoryIds: string[], sharedContext?: Context ): Promise @@ -2368,12 +2380,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records, the promise resolved to `void`. * * @example - * await productModuleService.softDeleteCategories([ + * await productModuleService.softDeleteProductCategories([ * "pcat_123", * "pcat_321", * ]) */ - softDeleteCategories( + softDeleteProductCategories( categoryIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -2393,12 +2405,12 @@ export interface IProductModuleService extends IModuleService { * If there are no related records that were restored, the promise resolved to `void`. * * @example - * await productModuleService.restoreCategories([ + * await productModuleService.restoreProductCategories([ * "pcat_123", * "pcat_321", * ]) */ - restoreCategories( + restoreProductCategories( categoryIds: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/promotion/service.ts b/packages/core/types/src/promotion/service.ts index d92e92a2d9..1b264b0d5c 100644 --- a/packages/core/types/src/promotion/service.ts +++ b/packages/core/types/src/promotion/service.ts @@ -102,7 +102,7 @@ export interface IPromotionModuleService extends IModuleService { * @returns {Promise} The created promotions. * * @example - * const promotions = await promotionModuleService.create([ + * const promotions = await promotionModuleService.createPromotions([ * { * code: "50OFF", * type: "standard", @@ -140,7 +140,7 @@ export interface IPromotionModuleService extends IModuleService { * }, * ]) */ - create( + createPromotions( data: CreatePromotionDTO[], sharedContext?: Context ): Promise @@ -153,7 +153,7 @@ export interface IPromotionModuleService extends IModuleService { * @returns {Promise} The created promotion. * * @example - * const promotionA = await promotionModuleService.create({ + * const promotionA = await promotionModuleService.createPromotions({ * code: "50OFF", * type: "standard", * application_method: { @@ -163,7 +163,7 @@ export interface IPromotionModuleService extends IModuleService { * }, * }) * - * const promotionB = await promotionModuleService.create({ + * const promotionB = await promotionModuleService.createPromotions({ * code: "FREESHIPPING", * type: "standard", * application_method: { @@ -173,7 +173,7 @@ export interface IPromotionModuleService extends IModuleService { * }, * }) * - * const promotionC = await promotionModuleService.create({ + * const promotionC = await promotionModuleService.createPromotions({ * code: "BUY2GET1", * type: "buyget", * application_method: { @@ -191,7 +191,7 @@ export interface IPromotionModuleService extends IModuleService { * }, * }) */ - create( + createPromotions( data: CreatePromotionDTO, sharedContext?: Context ): Promise @@ -204,14 +204,14 @@ export interface IPromotionModuleService extends IModuleService { * @returns {Promise} The updated promotions. * * @example - * const promotions = await promotionModuleService.update([ + * const promotions = await promotionModuleService.updatePromotions([ * { * id: "promo_123", * is_automatic: true, * }, * ]) */ - update( + updatePromotions( data: UpdatePromotionDTO[], sharedContext?: Context ): Promise @@ -224,12 +224,12 @@ export interface IPromotionModuleService extends IModuleService { * @returns {Promise} The updated promotion. * * @example - * const promotion = await promotionModuleService.update({ + * const promotion = await promotionModuleService.updatePromotions({ * id: "promo_123", * is_automatic: true, * }) */ - update( + updatePromotions( data: UpdatePromotionDTO, sharedContext?: Context ): Promise @@ -247,7 +247,7 @@ export interface IPromotionModuleService extends IModuleService { * To retrieve a list of promotions using their IDs: * * ```ts - * const promotions = await promotionModuleService.list({ + * const promotions = await promotionModuleService.listPromotions({ * id: ["promo_123", "promo_321"], * }) * ``` @@ -255,7 +255,7 @@ export interface IPromotionModuleService extends IModuleService { * To specify relations that should be retrieved within the promotions: * * ```ts - * const promotions = await promotionModuleService.list( + * const promotions = await promotionModuleService.listPromotions( * { * id: ["promo_123", "promo_321"], * }, @@ -268,7 +268,7 @@ export interface IPromotionModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const promotions = await promotionModuleService.list( + * const promotions = await promotionModuleService.listPromotions( * { * id: ["promo_123", "promo_321"], * }, @@ -280,7 +280,7 @@ export interface IPromotionModuleService extends IModuleService { * ) * ``` */ - list( + listPromotions( filters?: FilterablePromotionProps, config?: FindConfig, sharedContext?: Context @@ -300,7 +300,7 @@ export interface IPromotionModuleService extends IModuleService { * * ```ts * const [promotions, count] = - * await promotionModuleService.listAndCount({ + * await promotionModuleService.listAndCountPromotions({ * id: ["promo_123", "promo_321"], * }) * ``` @@ -309,7 +309,7 @@ export interface IPromotionModuleService extends IModuleService { * * ```ts * const [promotions, count] = - * await promotionModuleService.listAndCount( + * await promotionModuleService.listAndCountPromotions( * { * id: ["promo_123", "promo_321"], * }, @@ -323,7 +323,7 @@ export interface IPromotionModuleService extends IModuleService { * * ```ts * const [promotions, count] = - * await promotionModuleService.listAndCount( + * await promotionModuleService.listAndCountPromotions( * { * id: ["promo_123", "promo_321"], * }, @@ -335,7 +335,7 @@ export interface IPromotionModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountPromotions( filters?: FilterablePromotionProps, config?: FindConfig, sharedContext?: Context @@ -355,13 +355,13 @@ export interface IPromotionModuleService extends IModuleService { * * ```ts * const promotion = - * await promotionModuleService.retrieve("promo_123") + * await promotionModuleService.retrievePromotion("promo_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const promotion = await promotionModuleService.retrieve( + * const promotion = await promotionModuleService.retrievePromotion( * "promo_123", * { * relations: ["application_method"], @@ -369,7 +369,7 @@ export interface IPromotionModuleService extends IModuleService { * ) * ``` */ - retrieve( + retrievePromotion( id: string, config?: FindConfig, sharedContext?: Context @@ -383,12 +383,12 @@ export interface IPromotionModuleService extends IModuleService { * @returns {Promise} Resolves when the promotions are deleted. * * @example - * await promotionModuleService.delete([ + * await promotionModuleService.deletePromotions([ * "promo_123", * "promo_321", * ]) */ - delete(ids: string[], sharedContext?: Context): Promise + deletePromotions(ids: string[], sharedContext?: Context): Promise /** * This method deletes a promotion by its ID. @@ -398,9 +398,9 @@ export interface IPromotionModuleService extends IModuleService { * @returns {Promise} Resolves when the promotion is deleted. * * @example - * await promotionModuleService.delete("promo_123") + * await promotionModuleService.deletePromotions("promo_123") */ - delete(ids: string, sharedContext?: Context): Promise + deletePromotions(ids: string, sharedContext?: Context): Promise /** * This method soft deletes a promotion by its IDs. @@ -415,9 +415,9 @@ export interface IPromotionModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await promotionModuleService.softDelete("promo_123") + * await promotionModuleService.softDeletePromotions("promo_123") */ - softDelete( + softDeletePromotions( promotionIds: string | string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -438,9 +438,9 @@ export interface IPromotionModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await promotionModuleService.restore("promo_123") + * await promotionModuleService.restorePromotions("promo_123") */ - restore( + restorePromotions( promotionIds: string | string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/region/service.ts b/packages/core/types/src/region/service.ts index c570e6d925..82aae077e6 100644 --- a/packages/core/types/src/region/service.ts +++ b/packages/core/types/src/region/service.ts @@ -22,7 +22,7 @@ export interface IRegionModuleService extends IModuleService { * @returns {Promise} The created regions. * * @example - * const region = await regionModuleService.create([ + * const region = await regionModuleService.createRegions([ * { * name: "Europe", * currency_code: "eur", @@ -35,7 +35,10 @@ export interface IRegionModuleService extends IModuleService { * }, * ]) */ - create(data: CreateRegionDTO[], sharedContext?: Context): Promise + createRegions( + data: CreateRegionDTO[], + sharedContext?: Context + ): Promise /** * This method creates a region. @@ -45,13 +48,16 @@ export interface IRegionModuleService extends IModuleService { * @returns {Promise} The created region. * * @example - * const region = await regionModuleService.create({ + * const region = await regionModuleService.createRegions({ * name: "Europe", * currency_code: "eur", * countries: ["dk", "de", "fr"], * }) */ - create(data: CreateRegionDTO, sharedContext?: Context): Promise + createRegions( + data: CreateRegionDTO, + sharedContext?: Context + ): Promise /** * This method updates or creates regions if they don't exist. @@ -61,7 +67,7 @@ export interface IRegionModuleService extends IModuleService { * @returns {Promise} The created or updated regions. * * @example - * const region = await regionModuleService.upsert([ + * const region = await regionModuleService.upsertRegions([ * { * id: "reg_123", * automatic_taxes: false, @@ -72,7 +78,10 @@ export interface IRegionModuleService extends IModuleService { * }, * ]) */ - upsert(data: UpsertRegionDTO[], sharedContext?: Context): Promise + upsertRegions( + data: UpsertRegionDTO[], + sharedContext?: Context + ): Promise /** * This method updates or creates a region if it doesn't exist. @@ -82,12 +91,15 @@ export interface IRegionModuleService extends IModuleService { * @returns {Promise} The created or updated region. * * @example - * const region = await regionModuleService.upsert({ + * const region = await regionModuleService.upsertRegions({ * id: "reg_123", * automatic_taxes: false, * }) */ - upsert(data: UpsertRegionDTO, sharedContext?: Context): Promise + upsertRegions( + data: UpsertRegionDTO, + sharedContext?: Context + ): Promise /** * This method updates an existing region. @@ -98,11 +110,11 @@ export interface IRegionModuleService extends IModuleService { * @returns {Promise} The updated region. * * @example - * const region = await regionModuleService.update("reg_123", { + * const region = await regionModuleService.updateRegions("reg_123", { * automatic_taxes: false, * }) */ - update( + updateRegions( id: string, data: UpdateRegionDTO, sharedContext?: Context @@ -117,7 +129,7 @@ export interface IRegionModuleService extends IModuleService { * @returns {Promise} The updated regions. * * @example - * const region = await regionModuleService.update( + * const region = await regionModuleService.updateRegions( * { * name: "Europe", * }, @@ -126,7 +138,7 @@ export interface IRegionModuleService extends IModuleService { * } * ) */ - update( + updateRegions( selector: FilterableRegionProps, data: UpdateRegionDTO, sharedContext?: Context @@ -140,9 +152,9 @@ export interface IRegionModuleService extends IModuleService { * @returns {Promise} Resolves when the regions are deleted. * * @example - * await regionModuleService.delete(["reg_123", "reg_321"]) + * await regionModuleService.deleteRegions(["reg_123", "reg_321"]) */ - delete(ids: string[], sharedContext?: Context): Promise + deleteRegions(ids: string[], sharedContext?: Context): Promise /** * This method deletes a region by its ID. @@ -152,9 +164,9 @@ export interface IRegionModuleService extends IModuleService { * @returns {Promise} Resolves when the region is deleted. * * @example - * await regionModuleService.delete("reg_123") + * await regionModuleService.deleteRegions("reg_123") */ - delete(id: string, sharedContext?: Context): Promise + deleteRegions(id: string, sharedContext?: Context): Promise /** * This method retrieves a region by its ID. @@ -169,18 +181,18 @@ export interface IRegionModuleService extends IModuleService { * A simple example that retrieves a region by its ID: * * ```ts - * const region = await regionModuleService.retrieve("reg_123") + * const region = await regionModuleService.retrieveRegion("reg_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const region = await regionModuleService.retrieve("reg_123", { + * const region = await regionModuleService.retrieveRegion("reg_123", { * relations: ["countries"], * }) * ``` */ - retrieve( + retrieveRegion( id: string, config?: FindConfig, sharedContext?: Context @@ -199,7 +211,7 @@ export interface IRegionModuleService extends IModuleService { * To retrieve a list of regions using their IDs: * * ```ts - * const regions = await regionModuleService.list({ + * const regions = await regionModuleService.listRegions({ * id: ["reg_123", "reg_321"], * }) * ``` @@ -207,7 +219,7 @@ export interface IRegionModuleService extends IModuleService { * To specify relations that should be retrieved within the regions: * * ```ts - * const regions = await regionModuleService.list( + * const regions = await regionModuleService.listRegions( * { * id: ["reg_123", "reg_321"], * }, @@ -220,7 +232,7 @@ export interface IRegionModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const regions = await regionModuleService.list( + * const regions = await regionModuleService.listRegions( * { * id: ["reg_123", "reg_321"], * }, @@ -232,7 +244,7 @@ export interface IRegionModuleService extends IModuleService { * ) * ``` */ - list( + listRegions( filters?: FilterableRegionProps, config?: FindConfig, sharedContext?: Context @@ -252,7 +264,7 @@ export interface IRegionModuleService extends IModuleService { * * ```ts * const [regions, count] = - * await regionModuleService.listAndCount({ + * await regionModuleService.listAndCountRegions({ * id: ["reg_123", "reg_321"], * }) * ``` @@ -261,7 +273,7 @@ export interface IRegionModuleService extends IModuleService { * * ```ts * const [regions, count] = - * await regionModuleService.listAndCount( + * await regionModuleService.listAndCountRegions( * { * id: ["reg_123", "reg_321"], * }, @@ -275,7 +287,7 @@ export interface IRegionModuleService extends IModuleService { * * ```ts * const [regions, count] = - * await regionModuleService.listAndCount( + * await regionModuleService.listAndCountRegions( * { * id: ["reg_123", "reg_321"], * }, @@ -287,7 +299,7 @@ export interface IRegionModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountRegions( filters?: FilterableRegionProps, config?: FindConfig, sharedContext?: Context @@ -447,11 +459,11 @@ export interface IRegionModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await regionModuleService.softDelete(["reg_123", "reg_321"], { + * await regionModuleService.softDeleteRegions(["reg_123", "reg_321"], { * returnLinkableKeys: ["country_id"], * }) */ - softDelete( + softDeleteRegions( regionIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -472,11 +484,11 @@ export interface IRegionModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await regionModuleService.restore(["reg_123", "reg_321"], { + * await regionModuleService.restoreRegions(["reg_123", "reg_321"], { * returnLinkableKeys: ["country_id"], * }) */ - restore( + restoreRegions( regionIds: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/sales-channel/service.ts b/packages/core/types/src/sales-channel/service.ts index 509f048f9c..bab42a7529 100644 --- a/packages/core/types/src/sales-channel/service.ts +++ b/packages/core/types/src/sales-channel/service.ts @@ -21,13 +21,13 @@ export interface ISalesChannelModuleService extends IModuleService { * @returns {Promise} The created sales channels. * * @example - * const salesChannels = await salesChannelModuleService.create([ + * const salesChannels = await salesChannelModuleService.createSalesChannels([ * { * name: "B2B", * }, * ]) */ - create( + createSalesChannels( data: CreateSalesChannelDTO[], sharedContext?: Context ): Promise @@ -40,11 +40,11 @@ export interface ISalesChannelModuleService extends IModuleService { * @returns {Promise} The created sales channel. * * @example - * const salesChannel = await salesChannelModuleService.create({ + * const salesChannel = await salesChannelModuleService.createSalesChannels({ * name: "B2B", * }) */ - create( + createSalesChannels( data: CreateSalesChannelDTO, sharedContext?: Context ): Promise @@ -58,14 +58,14 @@ export interface ISalesChannelModuleService extends IModuleService { * @returns {Promise} The updated sales channel. * * @example - * const salesChannel = await salesChannelModuleService.update( + * const salesChannel = await salesChannelModuleService.updateSalesChannels( * "sc_123", * { * description: "Sales channel for B2B customers", * } * ) */ - update( + updateSalesChannels( channelId: string, data: UpdateSalesChannelDTO, sharedContext?: Context @@ -80,7 +80,7 @@ export interface ISalesChannelModuleService extends IModuleService { * @returns {Promise} The updated sales channels. * * @example - * const salesChannels = await salesChannelModuleService.update( + * const salesChannels = await salesChannelModuleService.updateSalesChannels( * { * name: "B2B", * }, @@ -89,7 +89,7 @@ export interface ISalesChannelModuleService extends IModuleService { * } * ) */ - update( + updateSalesChannels( selector: FilterableSalesChannelProps, data: UpdateSalesChannelDTO, sharedContext?: Context @@ -103,11 +103,11 @@ export interface ISalesChannelModuleService extends IModuleService { * @returns {Promise} The created or updated sales channel. * * @example - * const salesChannel = await salesChannelModuleService.upsert({ + * const salesChannel = await salesChannelModuleService.upsertSalesChannels({ * name: "B2B", * }) */ - upsert( + upsertSalesChannels( data: UpsertSalesChannelDTO, sharedContext?: Context ): Promise @@ -120,7 +120,7 @@ export interface ISalesChannelModuleService extends IModuleService { * @returns {Promise} The created or updated sales channels. * * @example - * const salesChannels = await salesChannelModuleService.upsert([ + * const salesChannels = await salesChannelModuleService.upsertSalesChannels([ * { * name: "B2B", * }, @@ -130,7 +130,7 @@ export interface ISalesChannelModuleService extends IModuleService { * }, * ]) */ - upsert( + upsertSalesChannels( data: UpsertSalesChannelDTO[], sharedContext?: Context ): Promise @@ -143,9 +143,9 @@ export interface ISalesChannelModuleService extends IModuleService { * @returns {Promise} Resolves when the sales channels are deleted successfully. * * @example - * await salesChannelModuleService.delete(["sc_123", "sc_321"]) + * await salesChannelModuleService.deleteSalesChannels(["sc_123", "sc_321"]) */ - delete(ids: string[], sharedContext?: Context): Promise + deleteSalesChannels(ids: string[], sharedContext?: Context): Promise /** * This method deletes a sales channel by its ID. @@ -155,9 +155,9 @@ export interface ISalesChannelModuleService extends IModuleService { * @returns {Promise} Resolves when the sales channel is deleted successfully. * * @example - * await salesChannelModuleService.delete("sc_123") + * await salesChannelModuleService.deleteSalesChannels("sc_123") */ - delete(id: string, sharedContext?: Context): Promise + deleteSalesChannels(id: string, sharedContext?: Context): Promise /** * This method retrieves a sales channel by its ID. @@ -170,9 +170,9 @@ export interface ISalesChannelModuleService extends IModuleService { * * @example * const salesChannel = - * await salesChannelModuleService.retrieve("sc_123") + * await salesChannelModuleService.retrieveSalesChannel("sc_123") */ - retrieve( + retrieveSalesChannel( id: string, config?: FindConfig, sharedContext?: Context @@ -191,7 +191,7 @@ export interface ISalesChannelModuleService extends IModuleService { * To retrieve a list of sales channels using their IDs: * * ```ts - * const salesChannels = await salesChannelModuleService.list({ + * const salesChannels = await salesChannelModuleService.listSalesChannels({ * id: ["sc_123", "sc_321"], * }) * ``` @@ -199,7 +199,7 @@ export interface ISalesChannelModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const salesChannels = await salesChannelModuleService.list( + * const salesChannels = await salesChannelModuleService.listSalesChannels( * { * id: ["sc_123", "sc_321"], * }, @@ -210,7 +210,7 @@ export interface ISalesChannelModuleService extends IModuleService { * ) * ``` */ - list( + listSalesChannels( filters?: FilterableSalesChannelProps, config?: FindConfig, sharedContext?: Context @@ -230,7 +230,7 @@ export interface ISalesChannelModuleService extends IModuleService { * * ```ts * const [salesChannels, count] = - * await salesChannelModuleService.listAndCount({ + * await salesChannelModuleService.listAndCountSalesChannels({ * id: ["sc_123", "sc_321"], * }) * ``` @@ -239,7 +239,7 @@ export interface ISalesChannelModuleService extends IModuleService { * * ```ts * const [salesChannels, count] = - * await salesChannelModuleService.listAndCount( + * await salesChannelModuleService.listAndCountSalesChannels( * { * id: ["sc_123", "sc_321"], * }, @@ -250,7 +250,7 @@ export interface ISalesChannelModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountSalesChannels( filters?: FilterableSalesChannelProps, config?: FindConfig, sharedContext?: Context @@ -266,9 +266,9 @@ export interface ISalesChannelModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await salesChannelModuleService.delete(["sc_123", "sc_321"]) + * await salesChannelModuleService.softDeleteSalesChannels(["sc_123", "sc_321"]) */ - softDelete( + softDeleteSalesChannels( salesChannelIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -285,9 +285,9 @@ export interface ISalesChannelModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await salesChannelModuleService.restore(["sc_123", "sc_321"]) + * await salesChannelModuleService.restoreSalesChannels(["sc_123", "sc_321"]) */ - restore( + restoreSalesChannels( salesChannelIds: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/stock-location/common.ts b/packages/core/types/src/stock-location/common.ts index 703e46c197..f158c63320 100644 --- a/packages/core/types/src/stock-location/common.ts +++ b/packages/core/types/src/stock-location/common.ts @@ -439,22 +439,15 @@ export type UpdateStockLocationInput = { metadata?: Record } -/** - * @interface - * - * The attributes to update in a stock location. - */ -export type UpdateStockLocationNextInput = UpdateStockLocationInput & { - /** - * The ID of the stock location. - */ - id: string -} - /** * @interface * * A stock location to create or update. If the `id` property isn't provided, * the stock location is created. In that case, the `name` property is required. */ -export type UpsertStockLocationInput = Partial +export type UpsertStockLocationInput = Partial & { + /** + * The ID of the stock location, if updating. + */ + id?: string +} diff --git a/packages/core/types/src/stock-location/index.ts b/packages/core/types/src/stock-location/index.ts index 1d8d51e51e..eade309433 100644 --- a/packages/core/types/src/stock-location/index.ts +++ b/packages/core/types/src/stock-location/index.ts @@ -1,3 +1,2 @@ export * from "./common" export * from "./service" -export * from "./service-next" diff --git a/packages/core/types/src/stock-location/service-next.ts b/packages/core/types/src/stock-location/service-next.ts deleted file mode 100644 index b5c78093b5..0000000000 --- a/packages/core/types/src/stock-location/service-next.ts +++ /dev/null @@ -1,336 +0,0 @@ -import { - CreateStockLocationInput, - FilterableStockLocationProps, - StockLocationDTO, - UpdateStockLocationInput, - UpsertStockLocationInput, -} from "./common" -import { RestoreReturn, SoftDeleteReturn } from "../dal" -import { Context } from "../shared-context" -import { FindConfig } from "../common/common" -import { IModuleService } from "../modules-sdk" - -/** - * The main service interface for the Stock Location Module. - */ -export interface IStockLocationServiceNext extends IModuleService { - /** - * This method retrieves a paginated list of stock locations based on optional filters and configuration. - * - * @param {FilterableStockLocationProps} selector - The filters to apply on the retrieved stock locations. - * @param {FindConfig} config - The configurations determining how the stock location is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a stock location. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The list of stock locations. - * - * @example - * To retrieve a list of stock locations using their IDs: - * - * ```ts - * const stockLocations = await stockLocationModuleService.list({ - * id: ["sloc_123", "sloc_321"], - * }) - * ``` - * - * To specify relations that should be retrieved within the stock locations: - * - * ```ts - * const stockLocations = await stockLocationModuleService.list( - * { - * id: ["sloc_123", "sloc_321"], - * }, - * { - * relations: ["address"], - * } - * ) - * ``` - * - * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: - * - * ```ts - * const stockLocations = await stockLocationModuleService.list( - * { - * id: ["sloc_123", "sloc_321"], - * }, - * { - * relations: ["address"], - * take: 20, - * skip: 2, - * } - * ) - * ``` - */ - list( - selector: FilterableStockLocationProps, - config?: FindConfig, - context?: Context - ): Promise - - /** - * This method retrieves a paginated list of stock locations along with the total count of available stock locations satisfying the provided filters. - * - * @param {FilterableStockLocationProps} selector - The filters to apply on the retrieved stock locations. - * @param {FindConfig} config - The configurations determining how the stock location is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a stock location. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise<[StockLocationDTO[], number]>} The list of stock locations along with their total count. - * - * @example - * To retrieve a list of stock locations using their IDs: - * - * ```ts - * const [stockLocations, count] = - * await stockLocationModuleService.list({ - * id: ["sloc_123", "sloc_321"], - * }) - * ``` - * - * To specify relations that should be retrieved within the stock locations: - * - * ```ts - * const [stockLocations, count] = - * await stockLocationModuleService.list( - * { - * id: ["sloc_123", "sloc_321"], - * }, - * { - * relations: ["address"], - * } - * ) - * ``` - * - * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: - * - * ```ts - * const [stockLocations, count] = - * await stockLocationModuleService.list( - * { - * id: ["sloc_123", "sloc_321"], - * }, - * { - * relations: ["address"], - * take: 20, - * skip: 2, - * } - * ) - * ``` - */ - listAndCount( - selector: FilterableStockLocationProps, - config?: FindConfig, - context?: Context - ): Promise<[StockLocationDTO[], number]> - - /** - * This method retrieves a stock location by its ID. - * - * @param {string} id - The ID of the stock location. - * @param {FindConfig} config - The configurations determining how the stock location is retrieved. Its properties, such as `select` or `relations`, accept the - * attributes or relations associated with a stock location. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The retrieved stock location. - * - * @example - * const stockLocation = - * await stockLocationModuleService.retrieve("sloc_123") - */ - retrieve( - id: string, - config?: FindConfig, - context?: Context - ): Promise - - /** - * This method creates a stock location. - * - * @param {CreateStockLocationInput} input - The stock location to create. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created stock location. - * - * @example - * const stockLocation = await stockLocationModuleService.create( - * { - * name: "Warehouse", - * address: { - * address_1: "1855 Powder Mill Rd", - * country_code: "us", - * }, - * } - * ) - */ - create( - input: CreateStockLocationInput, - context?: Context - ): Promise - - /** - * This method creates stock locations. - * - * @param {CreateStockLocationInput[]} input - The stock locations to create. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created stock locations. - * - * @example - * const stockLocations = - * await stockLocationModuleService.create([ - * { - * name: "Warehouse", - * address: { - * address_1: "1855 Powder Mill Rd", - * country_code: "us", - * }, - * }, - * { - * name: "Warehouse 2", - * address_id: "laddr_123", - * }, - * ]) - */ - create( - input: CreateStockLocationInput[], - context?: Context - ): Promise - - /** - * This method updates or creates stock location service nexts if they don't exist. - * - * @param {Partial[]} data - The list of Make all properties in t optional - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created or updated stock location service nexts. - * - * @example - * {example-code} - */ - upsert( - data: UpsertStockLocationInput[], - sharedContext?: Context - ): Promise - - /** - * This method updates or creates a stock location service next if it doesn't exist. - * - * @param {Partial} data - Make all properties in T optional - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created or updated stock location service next. - * - * @example - * {example-code} - */ - upsert( - data: UpsertStockLocationInput, - sharedContext?: Context - ): Promise - - /** - * This method updates existing stock locations. - * - * @param {UpdateStockLocationNextInput[]} input - The attributes to update in the stock locations. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated stock locations. - * - * @example - * const stockLocations = - * await stockLocationModuleService.update([ - * { - * id: "sloc_123", - * name: "Warehouse", - * }, - * { - * id: "sloc_321", - * address_id: "laddr_123", - * }, - * ]) - */ - update( - id: string, - input: UpdateStockLocationInput, - context?: Context - ): Promise - - /** - * This method updates existing stock locations matching the specified filters. - * - * @param {FilterableStockLocationProps} selector - The filters specifying which stock locations to update. - * @param {UpdateStockLocationInput} input - The attributes to update in the stock locations. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The updated stock locations. - * - * @example - * const stockLocations = - * await stockLocationModuleService.update( - * { - * name: "Warehouse", - * }, - * { - * address_id: "laddr_123", - * } - * ) - */ - update( - selector: FilterableStockLocationProps, - input: UpdateStockLocationInput, - context?: Context - ): Promise - - /** - * This method deletes a stock location by its ID. - * - * @param {string} id - The ID of the stock location. - * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the stock location is deleted successfully. - * - * @example - * await stockLocationModuleService.delete("sloc_123") - */ - delete(id: string | string[], context?: Context): Promise - - /** - * This method soft deletes stock locations by their IDs. - * - * @param {string[]} stockLocationIds - The IDs of the stock locations. - * @param {SoftDeleteReturn} config - An object that is used to specify an entity's related entities that should be soft-deleted when the main entity is soft-deleted. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise>} An object that includes the IDs of related records that were also soft deleted, such as the ID of the associated address. - * The object's keys are the ID attribute names of the stock location entity's relations, such as `address_id`, and its value is an array of strings, each being the ID of a record associated - * with the stock location through this relation, such as the IDs of associated address. - * - * If there are no related records, the promise resolves to `void`. - * - * @example - * await stockLocationModuleService.softDelete([ - * "sloc_123", - * "sloc_321", - * ]) - */ - softDelete( - stockLocationIds: string[], - config?: SoftDeleteReturn, - sharedContext?: Context - ): Promise | void> - - /** - * This method restores soft deleted stock locations by their IDs. - * - * @param {string[]} stockLocationIds - The IDs of the stock locations. - * @param {RestoreReturn} config - Configurations determining which relations to restore along with each of the stock location. You can pass to its `returnLinkableKeys` - * property any of the stock location's relation attribute names, such as `address`. - * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise>} An object that includes the IDs of related records that were restored, such as the ID of associated address. - * The object's keys are the ID attribute names of the stock location entity's relations, such as `address_id`, - * and its value is an array of strings, each being the ID of the record associated with the stock location through this relation, - * such as the ID of associated address. - * - * If there are no related records restored, the promise resolves to `void`. - * - * @example - * await stockLocationModuleService.restore([ - * "sloc_123", - * "sloc_321", - * ]) - */ - restore( - stockLocationIds: string[], - config?: RestoreReturn, - sharedContext?: Context - ): Promise | void> -} diff --git a/packages/core/types/src/stock-location/service.ts b/packages/core/types/src/stock-location/service.ts index 6b6028014c..4d58ad1c48 100644 --- a/packages/core/types/src/stock-location/service.ts +++ b/packages/core/types/src/stock-location/service.ts @@ -3,294 +3,334 @@ import { FilterableStockLocationProps, StockLocationDTO, UpdateStockLocationInput, + UpsertStockLocationInput, } from "./common" - +import { RestoreReturn, SoftDeleteReturn } from "../dal" +import { Context } from "../shared-context" import { FindConfig } from "../common/common" import { IModuleService } from "../modules-sdk" -import { SharedContext } from "../shared-context" /** - * The main service interface for the stock location's module. + * The main service interface for the Stock Location Module. */ export interface IStockLocationService extends IModuleService { /** - * This method is used to retrieve a paginated list of stock locations based on optional filters and configuration. + * This method retrieves a paginated list of stock locations based on optional filters and configuration. * * @param {FilterableStockLocationProps} selector - The filters to apply on the retrieved stock locations. - * @param {FindConfig} config - - * The configurations determining how the stock locations are retrieved. Its properties, such as `select` or `relations`, accept the + * @param {FindConfig} config - The configurations determining how the stock location is retrieved. Its properties, such as `select` or `relations`, accept the * attributes or relations associated with a stock location. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @return {Promise} The list of stock locations. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The list of stock locations. * * @example * To retrieve a list of stock locations using their IDs: * * ```ts - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function listStockLocations (ids: string[]) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const stockLocations = await stockLocationModule.list({ - * id: ids - * }) - * - * // do something with the stock locations or return them - * } + * const stockLocations = await stockLocationModuleService.listStockLocations({ + * id: ["sloc_123", "sloc_321"], + * }) * ``` * * To specify relations that should be retrieved within the stock locations: * * ```ts - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function listStockLocations (ids: string[]) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const stockLocations = await stockLocationModule.list({ - * id: ids - * }, { - * relations: ["address"] - * }) - * - * // do something with the stock locations or return them - * } + * const stockLocations = await stockLocationModuleService.listStockLocations( + * { + * id: ["sloc_123", "sloc_321"], + * }, + * { + * relations: ["address"], + * } + * ) * ``` * * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function listStockLocations (ids: string[], skip: number, take: number) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const stockLocations = await stockLocationModule.list({ - * id: ids - * }, { + * const stockLocations = await stockLocationModuleService.listStockLocations( + * { + * id: ["sloc_123", "sloc_321"], + * }, + * { * relations: ["address"], - * skip, - * take - * }) - * - * // do something with the stock locations or return them - * } + * take: 20, + * skip: 2, + * } + * ) * ``` */ - list( + listStockLocations( selector: FilterableStockLocationProps, config?: FindConfig, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to retrieve a paginated list of stock locations along with the total count of available stock locations satisfying the provided filters. + * This method retrieves a paginated list of stock locations along with the total count of available stock locations satisfying the provided filters. * * @param {FilterableStockLocationProps} selector - The filters to apply on the retrieved stock locations. - * @param {FindConfig} config - - * The configurations determining how the stock locations are retrieved. Its properties, such as `select` or `relations`, accept the + * @param {FindConfig} config - The configurations determining how the stock location is retrieved. Its properties, such as `select` or `relations`, accept the * attributes or relations associated with a stock location. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @return {Promise<[StockLocationDTO[], number]>} The list of stock locations along with the total count. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise<[StockLocationDTO[], number]>} The list of stock locations along with their total count. * * @example * To retrieve a list of stock locations using their IDs: * * ```ts - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function listStockLocations (ids: string[]) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const [stockLocations, count] = await stockLocationModule.listAndCount({ - * id: ids + * const [stockLocations, count] = + * await stockLocationModuleService.listandCountStockLocations({ + * id: ["sloc_123", "sloc_321"], * }) - * - * // do something with the stock locations or return them - * } * ``` * * To specify relations that should be retrieved within the stock locations: * * ```ts - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function listStockLocations (ids: string[]) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const [stockLocations, count] = await stockLocationModule.listAndCount({ - * id: ids - * }, { - * relations: ["address"] - * }) - * - * // do something with the stock locations or return them - * } + * const [stockLocations, count] = + * await stockLocationModuleService.listandCountStockLocations( + * { + * id: ["sloc_123", "sloc_321"], + * }, + * { + * relations: ["address"], + * } + * ) * ``` * * By default, only the first `10` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function listStockLocations (ids: string[], skip: number, take: number) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const [stockLocations, count] = await stockLocationModule.listAndCount({ - * id: ids - * }, { - * relations: ["address"], - * skip, - * take - * }) - * - * // do something with the stock locations or return them - * } + * const [stockLocations, count] = + * await stockLocationModuleService.listandCountStockLocations( + * { + * id: ["sloc_123", "sloc_321"], + * }, + * { + * relations: ["address"], + * take: 20, + * skip: 2, + * } + * ) * ``` */ - listAndCount( + listAndCountStockLocations( selector: FilterableStockLocationProps, config?: FindConfig, - context?: SharedContext + context?: Context ): Promise<[StockLocationDTO[], number]> /** - * This method is used to retrieve a stock location by its ID + * This method retrieves a stock location by its ID. * - * @param {string} id - The ID of the stock location - * @param {FindConfig} config - - * The configurations determining how the stock location is retrieved. Its properties, such as `select` or `relations`, accept the + * @param {string} id - The ID of the stock location. + * @param {FindConfig} config - The configurations determining how the stock location is retrieved. Its properties, such as `select` or `relations`, accept the * attributes or relations associated with a stock location. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The stock location's details. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The retrieved stock location. * * @example - * A simple example that retrieves a inventory item by its ID: - * - * ```ts - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function retrieveStockLocation (id: string) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const stockLocation = await stockLocationModule.retrieve(id) - * - * // do something with the stock location or return it - * } - * ``` - * - * To specify relations that should be retrieved: - * - * ```ts - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function retrieveStockLocation (id: string) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const stockLocation = await stockLocationModule.retrieve(id, { - * relations: ["address"] - * }) - * - * // do something with the stock location or return it - * } - * ``` + * const stockLocation = + * await stockLocationModuleService.retrieveStockLocation("sloc_123") */ - retrieve( + retrieveStockLocation( id: string, config?: FindConfig, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to create a stock location. + * This method creates a stock location. * - * @param {CreateStockLocationInput} input - The details of the stock location to create. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The created stock location's details. + * @param {CreateStockLocationInput} input - The stock location to create. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created stock location. * * @example - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function createStockLocation (name: string) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const stockLocation = await stockLocationModule.create({ - * name - * }) - * - * // do something with the stock location or return it - * } + * const stockLocation = await stockLocationModuleService.createStockLocations( + * { + * name: "Warehouse", + * address: { + * address_1: "1855 Powder Mill Rd", + * country_code: "us", + * }, + * } + * ) */ - create( + createStockLocations( input: CreateStockLocationInput, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to update a stock location. + * This method creates stock locations. * - * @param {string} id - The ID of the stock location. - * @param {UpdateStockLocationInput} input - The attributes to update in the stock location. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} The stock location's details. + * @param {CreateStockLocationInput[]} input - The stock locations to create. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created stock locations. * * @example - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function updateStockLocation (id:string, name: string) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * const stockLocation = await stockLocationModule.update(id, { - * name - * }) - * - * // do something with the stock location or return it - * } + * const stockLocations = + * await stockLocationModuleService.createStockLocations([ + * { + * name: "Warehouse", + * address: { + * address_1: "1855 Powder Mill Rd", + * country_code: "us", + * }, + * }, + * { + * name: "Warehouse 2", + * address_id: "laddr_123", + * }, + * ]) */ - update( + createStockLocations( + input: CreateStockLocationInput[], + context?: Context + ): Promise + + /** + * This method updates or creates stock location service nexts if they don't exist. + * + * @param {Partial[]} data - The list of Make all properties in t optional + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created or updated stock location service nexts. + * + * @example + * {example-code} + */ + upsertStockLocations( + data: UpsertStockLocationInput[], + sharedContext?: Context + ): Promise + + /** + * This method updates or creates a stock location service next if it doesn't exist. + * + * @param {Partial} data - Make all properties in T optional + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The created or updated stock location service next. + * + * @example + * {example-code} + */ + upsertStockLocations( + data: UpsertStockLocationInput, + sharedContext?: Context + ): Promise + + /** + * This method updates existing stock locations. + * + * @param {UpdateStockLocationInput[]} input - The attributes to update in the stock locations. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated stock locations. + * + * @example + * const stockLocations = + * await stockLocationModuleService.updateStockLocations([ + * { + * id: "sloc_123", + * name: "Warehouse", + * }, + * { + * id: "sloc_321", + * address_id: "laddr_123", + * }, + * ]) + */ + updateStockLocations( id: string, input: UpdateStockLocationInput, - context?: SharedContext + context?: Context ): Promise /** - * This method is used to delete a stock location. + * This method updates existing stock locations matching the specified filters. * - * @param {string} id - The ID of the stock location. - * @param {SharedContext} context - A context used to share resources, such as transaction manager, between the application and the module. - * @returns {Promise} Resolves when the stock location is successfully deleted. + * @param {FilterableStockLocationProps} selector - The filters specifying which stock locations to update. + * @param {UpdateStockLocationInput} input - The attributes to update in the stock locations. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} The updated stock locations. * * @example - * import { - * initialize as initializeStockLocationModule, - * } from "@medusajs/stock-location" - * - * async function deleteStockLocation (id:string) { - * const stockLocationModule = await initializeStockLocationModule({}) - * - * await stockLocationModule.delete(id) - * } + * const stockLocations = + * await stockLocationModuleService.updateStockLocations( + * { + * name: "Warehouse", + * }, + * { + * address_id: "laddr_123", + * } + * ) */ - delete(id: string, context?: SharedContext): Promise + updateStockLocations( + selector: FilterableStockLocationProps, + input: UpdateStockLocationInput, + context?: Context + ): Promise + + /** + * This method deletes a stock location by its ID. + * + * @param {string} id - The ID of the stock location. + * @param {Context} context - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise} Resolves when the stock location is deleted successfully. + * + * @example + * await stockLocationModuleService.deleteStockLocations("sloc_123") + */ + deleteStockLocations(id: string | string[], context?: Context): Promise + + /** + * This method soft deletes stock locations by their IDs. + * + * @param {string[]} stockLocationIds - The IDs of the stock locations. + * @param {SoftDeleteReturn} config - An object that is used to specify an entity's related entities that should be soft-deleted when the main entity is soft-deleted. + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise>} An object that includes the IDs of related records that were also soft deleted, such as the ID of the associated address. + * The object's keys are the ID attribute names of the stock location entity's relations, such as `address_id`, and its value is an array of strings, each being the ID of a record associated + * with the stock location through this relation, such as the IDs of associated address. + * + * If there are no related records, the promise resolves to `void`. + * + * @example + * await stockLocationModuleService.softDeleteStockLocations([ + * "sloc_123", + * "sloc_321", + * ]) + */ + softDeleteStockLocations( + stockLocationIds: string[], + config?: SoftDeleteReturn, + sharedContext?: Context + ): Promise | void> + + /** + * This method restores soft deleted stock locations by their IDs. + * + * @param {string[]} stockLocationIds - The IDs of the stock locations. + * @param {RestoreReturn} config - Configurations determining which relations to restore along with each of the stock location. You can pass to its `returnLinkableKeys` + * property any of the stock location's relation attribute names, such as `address`. + * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. + * @returns {Promise>} An object that includes the IDs of related records that were restored, such as the ID of associated address. + * The object's keys are the ID attribute names of the stock location entity's relations, such as `address_id`, + * and its value is an array of strings, each being the ID of the record associated with the stock location through this relation, + * such as the ID of associated address. + * + * If there are no related records restored, the promise resolves to `void`. + * + * @example + * await stockLocationModuleService.restoreStockLocations([ + * "sloc_123", + * "sloc_321", + * ]) + */ + restoreStockLocations( + stockLocationIds: string[], + config?: RestoreReturn, + sharedContext?: Context + ): Promise | void> } diff --git a/packages/core/types/src/store/service.ts b/packages/core/types/src/store/service.ts index bb2e8b50d8..24074d3c6a 100644 --- a/packages/core/types/src/store/service.ts +++ b/packages/core/types/src/store/service.ts @@ -17,7 +17,7 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} The created stores. * * @example - * const stores = await storeModuleService.create([ + * const stores = await storeModuleService.createStores([ * { * name: "Acme", * supported_currency_codes: ["usd", "eur"], @@ -30,7 +30,10 @@ export interface IStoreModuleService extends IModuleService { * }, * ]) */ - create(data: CreateStoreDTO[], sharedContext?: Context): Promise + createStores( + data: CreateStoreDTO[], + sharedContext?: Context + ): Promise /** * This method creates a store. @@ -40,13 +43,13 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} The created store. * * @example - * const store = await storeModuleService.create({ + * const store = await storeModuleService.createStores({ * name: "Acme", * supported_currency_codes: ["usd", "eur"], * default_currency_code: "usd", * }) */ - create(data: CreateStoreDTO, sharedContext?: Context): Promise + createStores(data: CreateStoreDTO, sharedContext?: Context): Promise /** * This method updates or creates stores if they don't exist. @@ -56,7 +59,7 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} The created or updated stores. * * @example - * const stores = await storeModuleService.upsert([ + * const stores = await storeModuleService.upsertStores([ * { * id: "store_123", * name: "Acme", @@ -68,7 +71,10 @@ export interface IStoreModuleService extends IModuleService { * }, * ]) */ - upsert(data: UpsertStoreDTO[], sharedContext?: Context): Promise + upsertStores( + data: UpsertStoreDTO[], + sharedContext?: Context + ): Promise /** * This method updates or creates a store if it doesn't exist. @@ -78,12 +84,12 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} The created or updated store. * * @example - * const store = await storeModuleService.upsert({ + * const store = await storeModuleService.upsertStores({ * id: "store_123", * name: "Acme", * }) */ - upsert(data: UpsertStoreDTO, sharedContext?: Context): Promise + upsertStores(data: UpsertStoreDTO, sharedContext?: Context): Promise /** * This method updates an existing store. @@ -94,11 +100,11 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} The updated store. * * @example - * const store = await storeModuleService.update("store_123", { + * const store = await storeModuleService.updateStores("store_123", { * name: "Acme", * }) */ - update( + updateStores( id: string, data: UpdateStoreDTO, sharedContext?: Context @@ -113,7 +119,7 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} The updated stores. * * @example - * const store = await storeModuleService.update( + * const store = await storeModuleService.updateStores( * { * name: ["Acme"], * }, @@ -122,7 +128,7 @@ export interface IStoreModuleService extends IModuleService { * } * ) */ - update( + updateStores( selector: FilterableStoreProps, data: UpdateStoreDTO, sharedContext?: Context @@ -136,9 +142,9 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} Resolves when the stores are deleted successfully. * * @example - * await storeModuleService.delete(["store_123", "store_321"]) + * await storeModuleService.deleteStores(["store_123", "store_321"]) */ - delete(ids: string[], sharedContext?: Context): Promise + deleteStores(ids: string[], sharedContext?: Context): Promise /** * This method deletes a store by its ID. @@ -148,9 +154,9 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} Resolves when the store is deleted successfully. * * @example - * await storeModuleService.delete("store_123") + * await storeModuleService.deleteStores("store_123") */ - delete(id: string, sharedContext?: Context): Promise + deleteStores(id: string, sharedContext?: Context): Promise /** * This method retrieves a store by its ID. @@ -162,9 +168,9 @@ export interface IStoreModuleService extends IModuleService { * @returns {Promise} The retrieved store. * * @example - * const store = await storeModuleService.retrieve("store_123") + * const store = await storeModuleService.retrieveStore("store_123") */ - retrieve( + retrieveStore( id: string, config?: FindConfig, sharedContext?: Context @@ -183,7 +189,7 @@ export interface IStoreModuleService extends IModuleService { * To retrieve a list of stores using their IDs: * * ```ts - * const stores = await storeModuleService.list({ + * const stores = await storeModuleService.listStores({ * id: ["store_123", "store_321"], * }) * ``` @@ -191,7 +197,7 @@ export interface IStoreModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const stores = await storeModuleService.list( + * const stores = await storeModuleService.listStores( * { * id: ["store_123", "store_321"], * }, @@ -202,7 +208,7 @@ export interface IStoreModuleService extends IModuleService { * ) * ``` */ - list( + listStores( filters?: FilterableStoreProps, config?: FindConfig, sharedContext?: Context @@ -221,7 +227,7 @@ export interface IStoreModuleService extends IModuleService { * To retrieve a list of stores using their IDs: * * ```ts - * const [stores, count] = await storeModuleService.listAndCount( + * const [stores, count] = await storeModuleService.listAndCountStores( * { * id: ["store_123", "store_321"], * } @@ -231,7 +237,7 @@ export interface IStoreModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const [stores, count] = await storeModuleService.listAndCount( + * const [stores, count] = await storeModuleService.listAndCountStores( * { * id: ["store_123", "store_321"], * }, @@ -242,7 +248,7 @@ export interface IStoreModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountStores( filters?: FilterableStoreProps, config?: FindConfig, sharedContext?: Context @@ -258,12 +264,12 @@ export interface IStoreModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await storeModuleService.softDelete([ + * await storeModuleService.softDeleteStores([ * "store_123", * "store_321", * ]) */ - softDelete( + softDeleteStores( storeIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -280,9 +286,9 @@ export interface IStoreModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await storeModuleService.restore(["store_123", "store_321"]) + * await storeModuleService.restoreStores(["store_123", "store_321"]) */ - restore( + restoreStores( storeIds: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/tax/service.ts b/packages/core/types/src/tax/service.ts index 7eb771203c..2f9773eb1b 100644 --- a/packages/core/types/src/tax/service.ts +++ b/packages/core/types/src/tax/service.ts @@ -3,21 +3,21 @@ import { RestoreReturn, SoftDeleteReturn } from "../dal" import { IModuleService } from "../modules-sdk" import { Context } from "../shared-context" import { - FilterableTaxRegionProps, FilterableTaxRateProps, - TaxRateDTO, - TaxRegionDTO, - TaxRateRuleDTO, FilterableTaxRateRuleProps, - TaxableItemDTO, - TaxCalculationContext, + FilterableTaxRegionProps, ItemTaxLineDTO, ShippingTaxLineDTO, + TaxableItemDTO, TaxableShippingDTO, + TaxCalculationContext, + TaxRateDTO, + TaxRateRuleDTO, + TaxRegionDTO, } from "./common" import { - CreateTaxRateRuleDTO, CreateTaxRateDTO, + CreateTaxRateRuleDTO, CreateTaxRegionDTO, UpdateTaxRateDTO, UpsertTaxRateDTO, @@ -40,18 +40,18 @@ export interface ITaxModuleService extends IModuleService { * A simple example that retrieves a tax rate by its ID: * * ```ts - * const taxRate = await taxModuleService.retrieve("txr_123") + * const taxRate = await taxModuleService.retrieveTaxRate("txr_123") * ``` * * To specify relations that should be retrieved: * * ```ts - * const taxRate = await taxModuleService.retrieve("txr_123", { + * const taxRate = await taxModuleService.retrieveTaxRate("txr_123", { * relations: ["tax_region"], * }) * ``` */ - retrieve( + retrieveTaxRate( taxRateId: string, config?: FindConfig, sharedContext?: Context @@ -70,7 +70,7 @@ export interface ITaxModuleService extends IModuleService { * To retrieve a list of tax rates using their IDs: * * ```ts - * const taxRates = await taxModuleService.list({ + * const taxRates = await taxModuleService.listTaxRates({ * id: ["txr_123", "txr_321"], * }) * ``` @@ -78,7 +78,7 @@ export interface ITaxModuleService extends IModuleService { * To specify relations that should be retrieved within the tax rate: * * ```ts - * const taxRates = await taxModuleService.list( + * const taxRates = await taxModuleService.listTaxRates( * { * id: ["txr_123", "txr_321"], * }, @@ -91,7 +91,7 @@ export interface ITaxModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const taxRates = await taxModuleService.list( + * const taxRates = await taxModuleService.listTaxRates( * { * id: ["txr_123", "txr_321"], * }, @@ -103,7 +103,7 @@ export interface ITaxModuleService extends IModuleService { * ) * ``` */ - list( + listTaxRates( filters?: FilterableTaxRateProps, config?: FindConfig, sharedContext?: Context @@ -122,7 +122,7 @@ export interface ITaxModuleService extends IModuleService { * To retrieve a list of tax rates using their IDs: * * ```ts - * const [taxRates, count] = await taxModuleService.listAndCount( + * const [taxRates, count] = await taxModuleService.listAndCountTaxRates( * { * id: ["txr_123", "txr_321"], * } @@ -132,7 +132,7 @@ export interface ITaxModuleService extends IModuleService { * To specify relations that should be retrieved within the tax rate: * * ```ts - * const [taxRates, count] = await taxModuleService.listAndCount( + * const [taxRates, count] = await taxModuleService.listAndCountTaxRates( * { * id: ["txr_123", "txr_321"], * }, @@ -145,7 +145,7 @@ export interface ITaxModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const [taxRates, count] = await taxModuleService.listAndCount( + * const [taxRates, count] = await taxModuleService.listAndCountTaxRates( * { * id: ["txr_123", "txr_321"], * }, @@ -157,7 +157,7 @@ export interface ITaxModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountTaxRates( filters?: FilterableTaxRateProps, config?: FindConfig, sharedContext?: Context @@ -171,7 +171,7 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} The created tax rates. * * @example - * const taxRates = await taxModuleService.create([ + * const taxRates = await taxModuleService.createTaxRates([ * { * tax_region_id: "txreg_123", * name: "Default rate", @@ -194,7 +194,7 @@ export interface ITaxModuleService extends IModuleService { * }, * ]) */ - create( + createTaxRates( data: CreateTaxRateDTO[], sharedContext?: Context ): Promise @@ -207,13 +207,16 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} The created tax rate. * * @example - * const taxRate = await taxModuleService.create({ + * const taxRate = await taxModuleService.createTaxRates({ * tax_region_id: "txreg_123", * name: "Default rate", * rate: 10, * }) */ - create(data: CreateTaxRateDTO, sharedContext?: Context): Promise + createTaxRates( + data: CreateTaxRateDTO, + sharedContext?: Context + ): Promise /** * This method updates an existing tax rate. @@ -224,11 +227,11 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} The updated tax rate. * * @example - * const taxRate = await taxModuleService.update("txr_123", { + * const taxRate = await taxModuleService.updateTaxRates("txr_123", { * rate: 10, * }) */ - update( + updateTaxRates( taxRateId: string, data: UpdateTaxRateDTO, sharedContext?: Context @@ -243,14 +246,14 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} The updated tax rates. * * @example - * const taxRates = await taxModuleService.update( + * const taxRates = await taxModuleService.updateTaxRates( * ["txr_123", "txr_321"], * { * rate: 10, * } * ) */ - update( + updateTaxRates( taxRateIds: string[], data: UpdateTaxRateDTO, sharedContext?: Context @@ -265,7 +268,7 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} The updated tax rates. * * @example - * const taxRates = await taxModuleService.update( + * const taxRates = await taxModuleService.updateTaxRates( * { * id: ["txr_123", "txr_321"], * }, @@ -274,7 +277,7 @@ export interface ITaxModuleService extends IModuleService { * } * ) */ - update( + updateTaxRates( selector: FilterableTaxRateProps, data: UpdateTaxRateDTO, sharedContext?: Context @@ -288,12 +291,15 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} The created or updated tax rate. * * @example - * const taxRate = await taxModuleService.upsert({ + * const taxRate = await taxModuleService.upsertTaxRates({ * id: "txr_123", * rate: 10, * }) */ - upsert(data: UpsertTaxRateDTO, sharedContext?: Context): Promise + upsertTaxRates( + data: UpsertTaxRateDTO, + sharedContext?: Context + ): Promise /** * This method updates or creates tax rates if they don't exist. @@ -303,14 +309,14 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} The created or updated tax rates. * * @example - * const taxRates = await taxModuleService.upsert([ + * const taxRates = await taxModuleService.upsertTaxRates([ * { * id: "txr_123", * rate: 10, * }, * ]) */ - upsert( + upsertTaxRates( data: UpsertTaxRateDTO[], sharedContext?: Context ): Promise @@ -323,9 +329,9 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} Resolves when the tax rates are deleted successfully. * * @example - * await taxModuleService.delete(["txr_123", "txr_321"]) + * await taxModuleService.deleteTaxRates(["txr_123", "txr_321"]) */ - delete(taxRateIds: string[], sharedContext?: Context): Promise + deleteTaxRates(taxRateIds: string[], sharedContext?: Context): Promise /** * This method deletes a tax rate by its ID. @@ -335,9 +341,9 @@ export interface ITaxModuleService extends IModuleService { * @returns {Promise} Resolves when the tax rate is deleted successfully. * * @example - * await taxModuleService.delete("txr_123") + * await taxModuleService.deleteTaxRates("txr_123") */ - delete(taxRateId: string, sharedContext?: Context): Promise + deleteTaxRates(taxRateId: string, sharedContext?: Context): Promise /** * This method restores soft deleted tax rates by their IDs. @@ -354,9 +360,9 @@ export interface ITaxModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await taxModuleService.restore(["txr_123", "txr_321"]) + * await taxModuleService.restoreTaxRates(["txr_123", "txr_321"]) */ - restore( + restoreTaxRates( taxRateIds: string[], config?: RestoreReturn, sharedContext?: Context @@ -668,9 +674,9 @@ export interface ITaxModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await taxModuleService.softDelete(["txr_123", "txr_321"]) + * await taxModuleService.softDeleteTaxRates(["txr_123", "txr_321"]) */ - softDelete( + softDeleteTaxRates( taxRateIds: string[], config?: SoftDeleteReturn, sharedContext?: Context diff --git a/packages/core/types/src/user/service.ts b/packages/core/types/src/user/service.ts index 1a92c1aa16..7f7230f632 100644 --- a/packages/core/types/src/user/service.ts +++ b/packages/core/types/src/user/service.ts @@ -61,9 +61,9 @@ export interface IUserModuleService extends IModuleService { * @returns {Promise} The retrieved user. * * @example - * const user = await userModuleService.retrieve("user_123") + * const user = await userModuleService.retrieveUser("user_123") */ - retrieve( + retrieveUser( id: string, config?: FindConfig, sharedContext?: Context @@ -82,7 +82,7 @@ export interface IUserModuleService extends IModuleService { * To retrieve a list of users using their IDs: * * ```ts - * const users = await userModuleService.list({ + * const users = await userModuleService.listUsers({ * id: ["user_123", "user_321"] * }) * ``` @@ -90,7 +90,7 @@ export interface IUserModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const users = await userModuleService.list( + * const users = await userModuleService.listUsers( * { * id: ["user_123", "user_321"] * }, @@ -101,7 +101,7 @@ export interface IUserModuleService extends IModuleService { * ) * ``` */ - list( + listUsers( filters?: FilterableUserProps, config?: FindConfig, sharedContext?: Context @@ -120,7 +120,7 @@ export interface IUserModuleService extends IModuleService { * To retrieve a list of users using their IDs: * * ```ts - * const [users, count] = await userModuleService.listAndCount({ + * const [users, count] = await userModuleService.listAndCountUsers({ * id: ["user_123", "user_321"] * }) * ``` @@ -128,7 +128,7 @@ export interface IUserModuleService extends IModuleService { * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * * ```ts - * const [users, count] = await userModuleService.listAndCount( + * const [users, count] = await userModuleService.listAndCountUsers( * { * id: ["user_123", "user_321"] * }, @@ -139,7 +139,7 @@ export interface IUserModuleService extends IModuleService { * ) * ``` */ - listAndCount( + listAndCountUsers( filters?: FilterableUserProps, config?: FindConfig, sharedContext?: Context @@ -153,7 +153,7 @@ export interface IUserModuleService extends IModuleService { * @returns {Promise} The created users. * * @example - * const users = await userModuleService.create([ + * const users = await userModuleService.createUsers([ * { * email: "john@doe.com" * }, @@ -162,7 +162,10 @@ export interface IUserModuleService extends IModuleService { * } * ]) */ - create(data: CreateUserDTO[], sharedContext?: Context): Promise + createUsers( + data: CreateUserDTO[], + sharedContext?: Context + ): Promise /** * This method creates a user. @@ -172,11 +175,11 @@ export interface IUserModuleService extends IModuleService { * @returns {Promise} The created user. * * @example - * const user = await userModuleService.create({ + * const user = await userModuleService.createUsers({ * email: "john@doe.com" * }) */ - create(data: CreateUserDTO, sharedContext?: Context): Promise + createUsers(data: CreateUserDTO, sharedContext?: Context): Promise /** * This method updates existing users. @@ -186,7 +189,7 @@ export interface IUserModuleService extends IModuleService { * @returns {Promise} The updated users. * * @example - * const users = await userModuleService.update([ + * const users = await userModuleService.updateUsers([ * { * id: "user_123", * first_name: "John" @@ -197,7 +200,10 @@ export interface IUserModuleService extends IModuleService { * } * ]) */ - update(data: UpdateUserDTO[], sharedContext?: Context): Promise + updateUsers( + data: UpdateUserDTO[], + sharedContext?: Context + ): Promise /** * This method updates an existing user. @@ -207,12 +213,12 @@ export interface IUserModuleService extends IModuleService { * @returns {Promise} The updated user. * * @example - * const user = await userModuleService.update({ + * const user = await userModuleService.updateUsers({ * id: "user_123", * first_name: "John" * }) */ - update(data: UpdateUserDTO, sharedContext?: Context): Promise + updateUsers(data: UpdateUserDTO, sharedContext?: Context): Promise /** * This method deletes users by their IDs. @@ -222,11 +228,11 @@ export interface IUserModuleService extends IModuleService { * @returns {Promise} Resolves when the users are deleted successfully. * * @example - * await userModuleService.delete([ + * await userModuleService.deleteUsers([ * "user_123", "user_321" * ]) */ - delete(ids: string[], sharedContext?: Context): Promise + deleteUsers(ids: string[], sharedContext?: Context): Promise /** * This method soft deletes a user by its IDs. @@ -238,11 +244,11 @@ export interface IUserModuleService extends IModuleService { * If there are no related records, the promise resolves to `void`. * * @example - * await userModuleService.softDelete([ + * await userModuleService.softDeleteUsers([ * "user_123", "user_321" * ]) */ - softDelete( + softDeleteUsers( userIds: string[], config?: SoftDeleteReturn, sharedContext?: Context @@ -260,11 +266,11 @@ export interface IUserModuleService extends IModuleService { * If there are no related records restored, the promise resolves to `void`. * * @example - * await userModuleService.restore([ + * await userModuleService.restoreUsers([ * "user_123", "user_321" * ]) */ - restore( + restoreUsers( userIds: string[], config?: RestoreReturn, sharedContext?: Context diff --git a/packages/core/types/src/workflow/reservation/create-reservations.ts b/packages/core/types/src/workflow/reservation/create-reservations.ts index 18f4efcd31..be7d53a454 100644 --- a/packages/core/types/src/workflow/reservation/create-reservations.ts +++ b/packages/core/types/src/workflow/reservation/create-reservations.ts @@ -1,8 +1,7 @@ -import { InventoryNext } from "../../inventory" +import { CreateReservationItemInput, ReservationItemDTO } from "../../inventory" export interface CreateReservationsWorkflowInput { - reservations: InventoryNext.CreateReservationItemInput[] + reservations: CreateReservationItemInput[] } -export type CreateReservationsWorkflowOutput = - InventoryNext.ReservationItemDTO[] +export type CreateReservationsWorkflowOutput = ReservationItemDTO[] diff --git a/packages/core/types/src/workflow/reservation/update-reservations.ts b/packages/core/types/src/workflow/reservation/update-reservations.ts index df2be4dbe3..d8f22cc332 100644 --- a/packages/core/types/src/workflow/reservation/update-reservations.ts +++ b/packages/core/types/src/workflow/reservation/update-reservations.ts @@ -1,8 +1,7 @@ -import { InventoryNext } from "../../inventory" +import { ReservationItemDTO, UpdateReservationItemInput } from "../../inventory" export interface UpdateReservationsWorkflowInput { - updates: InventoryNext.UpdateReservationItemInput[] + updates: UpdateReservationItemInput[] } -export type UpdateReservationsWorkflowOutput = - InventoryNext.ReservationItemDTO[] +export type UpdateReservationsWorkflowOutput = ReservationItemDTO[] diff --git a/packages/core/types/src/workflows-sdk/service.ts b/packages/core/types/src/workflows-sdk/service.ts index 8c71d1afd7..38076a3c79 100644 --- a/packages/core/types/src/workflows-sdk/service.ts +++ b/packages/core/types/src/workflows-sdk/service.ts @@ -39,13 +39,13 @@ export interface IWorkflowEngineService extends IModuleService { sharedContext?: Context ): Promise - listWorkflowExecution( + listWorkflowExecutions( filters?: FilterableWorkflowExecutionProps, config?: FindConfig, sharedContext?: Context ): Promise - listAndCountWorkflowExecution( + listAndCountWorkflowExecutions( filters?: FilterableWorkflowExecutionProps, config?: FindConfig, sharedContext?: Context diff --git a/packages/core/utils/src/common/get-caller-file-path.ts b/packages/core/utils/src/common/get-caller-file-path.ts new file mode 100644 index 0000000000..c4f1dd25bc --- /dev/null +++ b/packages/core/utils/src/common/get-caller-file-path.ts @@ -0,0 +1,27 @@ +/** + * return the file path of the caller of the function calling this function + * @param position + */ +export function getCallerFilePath(position = 2) { + if (position >= Error.stackTraceLimit) { + throw new TypeError( + "getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `" + + position + + "` and Error.stackTraceLimit was: `" + + Error.stackTraceLimit + + "`" + ) + } + + const oldPrepareStackTrace = Error.prepareStackTrace + Error.prepareStackTrace = (_, stack) => stack + const stack = new Error().stack + Error.prepareStackTrace = oldPrepareStackTrace + + if (stack !== null && typeof stack === "object") { + // stack[0] holds this file + // stack[1] holds where this function was called + // stack[2] holds the file we're interested in + return stack[position] ? (stack[position] as any).getFileName() : undefined + } +} diff --git a/packages/core/utils/src/common/index.ts b/packages/core/utils/src/common/index.ts index 95977c4cee..abac60fb68 100644 --- a/packages/core/utils/src/common/index.ts +++ b/packages/core/utils/src/common/index.ts @@ -65,3 +65,4 @@ export * from "./load-env" export * from "./define-config" export * from "./file-system" export * from "./graceful-shutdown-server" +export * from "./get-caller-file-path" diff --git a/packages/core/utils/src/modules-sdk/__tests__/joiner-config-builder.spec.ts b/packages/core/utils/src/modules-sdk/__tests__/joiner-config-builder.spec.ts new file mode 100644 index 0000000000..af42bf7d84 --- /dev/null +++ b/packages/core/utils/src/modules-sdk/__tests__/joiner-config-builder.spec.ts @@ -0,0 +1,282 @@ +import { defineJoinerConfig } from "../joiner-config-builder" +import { Modules } from "../definition" + +const FulfillmentSet = { + name: "FulfillmentSet", +} +const ShippingOption = { + name: "ShippingOption", +} +const ShippingProfile = { + name: "ShippingProfile", +} +const Fulfillment = { + name: "Fulfillment", +} +const FulfillmentProvider = { + name: "FulfillmentProvider", +} +const ServiceZone = { + name: "ServiceZone", +} +const GeoZone = { + name: "GeoZone", +} +const ShippingOptionRule = { + name: "ShippingOptionRule", +} + +describe("defineJoiner", () => { + it("should return a full joiner configuration", () => { + const joinerConfig = defineJoinerConfig(Modules.FULFILLMENT, { + entityQueryingConfig: [ + FulfillmentSet, + ShippingOption, + ShippingProfile, + Fulfillment, + FulfillmentProvider, + ServiceZone, + GeoZone, + ShippingOptionRule, + ], + }) + + expect(joinerConfig).toEqual({ + serviceName: Modules.FULFILLMENT, + primaryKeys: ["id"], + schema: undefined, + linkableKeys: { + fulfillment_set_id: FulfillmentSet.name, + shipping_option_id: ShippingOption.name, + shipping_profile_id: ShippingProfile.name, + fulfillment_id: Fulfillment.name, + fulfillment_provider_id: FulfillmentProvider.name, + service_zone_id: ServiceZone.name, + geo_zone_id: GeoZone.name, + shipping_option_rule_id: ShippingOptionRule.name, + }, + alias: [ + { + name: ["fulfillment_set", "fulfillment_sets"], + args: { + entity: FulfillmentSet.name, + methodSuffix: "FulfillmentSets", + }, + }, + { + name: ["shipping_option", "shipping_options"], + args: { + entity: ShippingOption.name, + methodSuffix: "ShippingOptions", + }, + }, + { + name: ["shipping_profile", "shipping_profiles"], + args: { + entity: ShippingProfile.name, + methodSuffix: "ShippingProfiles", + }, + }, + { + name: ["fulfillment", "fulfillments"], + args: { + entity: Fulfillment.name, + methodSuffix: "Fulfillments", + }, + }, + { + name: ["fulfillment_provider", "fulfillment_providers"], + args: { + entity: FulfillmentProvider.name, + methodSuffix: "FulfillmentProviders", + }, + }, + { + name: ["service_zone", "service_zones"], + args: { + entity: ServiceZone.name, + methodSuffix: "ServiceZones", + }, + }, + { + name: ["geo_zone", "geo_zones"], + args: { + entity: GeoZone.name, + methodSuffix: "GeoZones", + }, + }, + { + name: ["shipping_option_rule", "shipping_option_rules"], + args: { + entity: ShippingOptionRule.name, + methodSuffix: "ShippingOptionRules", + }, + }, + ], + }) + }) + + it("should return a full joiner configuration with custom aliases", () => { + const joinerConfig = defineJoinerConfig(Modules.FULFILLMENT, { + alias: [ + { + name: ["custom", "customs"], + args: { + entity: "Custom", + methodSuffix: "Customs", + }, + }, + ], + }) + + expect(joinerConfig).toEqual({ + serviceName: Modules.FULFILLMENT, + primaryKeys: ["id"], + schema: undefined, + linkableKeys: {}, + alias: [ + { + name: ["custom", "customs"], + args: { + entity: "Custom", + methodSuffix: "Customs", + }, + }, + ], + }) + }) + + it("should return a full joiner configuration with custom aliases and models", () => { + const joinerConfig = defineJoinerConfig(Modules.FULFILLMENT, { + entityQueryingConfig: [ + FulfillmentSet, + ShippingOption, + ShippingProfile, + Fulfillment, + FulfillmentProvider, + ServiceZone, + GeoZone, + ShippingOptionRule, + ], + alias: [ + { + name: ["custom", "customs"], + args: { + entity: "Custom", + methodSuffix: "Customs", + }, + }, + ], + }) + + expect(joinerConfig).toEqual({ + serviceName: Modules.FULFILLMENT, + primaryKeys: ["id"], + schema: undefined, + linkableKeys: { + fulfillment_set_id: FulfillmentSet.name, + shipping_option_id: ShippingOption.name, + shipping_profile_id: ShippingProfile.name, + fulfillment_id: Fulfillment.name, + fulfillment_provider_id: FulfillmentProvider.name, + service_zone_id: ServiceZone.name, + geo_zone_id: GeoZone.name, + shipping_option_rule_id: ShippingOptionRule.name, + }, + alias: [ + { + name: ["custom", "customs"], + args: { + entity: "Custom", + methodSuffix: "Customs", + }, + }, + { + name: ["fulfillment_set", "fulfillment_sets"], + args: { + entity: FulfillmentSet.name, + methodSuffix: "FulfillmentSets", + }, + }, + { + name: ["shipping_option", "shipping_options"], + args: { + entity: ShippingOption.name, + methodSuffix: "ShippingOptions", + }, + }, + { + name: ["shipping_profile", "shipping_profiles"], + args: { + entity: ShippingProfile.name, + methodSuffix: "ShippingProfiles", + }, + }, + { + name: ["fulfillment", "fulfillments"], + args: { + entity: Fulfillment.name, + methodSuffix: "Fulfillments", + }, + }, + { + name: ["fulfillment_provider", "fulfillment_providers"], + args: { + entity: FulfillmentProvider.name, + methodSuffix: "FulfillmentProviders", + }, + }, + { + name: ["service_zone", "service_zones"], + args: { + entity: ServiceZone.name, + methodSuffix: "ServiceZones", + }, + }, + { + name: ["geo_zone", "geo_zones"], + args: { + entity: GeoZone.name, + methodSuffix: "GeoZones", + }, + }, + { + name: ["shipping_option_rule", "shipping_option_rules"], + args: { + entity: ShippingOptionRule.name, + methodSuffix: "ShippingOptionRules", + }, + }, + ], + }) + }) + + it("should return a full joiner configuration with custom aliases without method suffix", () => { + const joinerConfig = defineJoinerConfig(Modules.FULFILLMENT, { + alias: [ + { + name: ["custom", "customs"], + args: { + entity: "Custom", + }, + }, + ], + }) + + expect(joinerConfig).toEqual({ + serviceName: Modules.FULFILLMENT, + primaryKeys: ["id"], + schema: undefined, + linkableKeys: {}, + alias: [ + { + name: ["custom", "customs"], + args: { + entity: "Custom", + methodSuffix: "Customs", + }, + }, + ], + }) + }) +}) diff --git a/packages/core/utils/src/modules-sdk/__tests__/medusa-service.spec.ts b/packages/core/utils/src/modules-sdk/__tests__/medusa-service.spec.ts index c7c92451ea..a9946210ff 100644 --- a/packages/core/utils/src/modules-sdk/__tests__/medusa-service.spec.ts +++ b/packages/core/utils/src/modules-sdk/__tests__/medusa-service.spec.ts @@ -45,35 +45,22 @@ describe("Abstract Module Service Factory", () => { class OtherModelMock1 {} class OtherModelMock2 {} - const abstractModuleService = MedusaService< + const medusaService = MedusaService({ MainModelMock, - { - OtherModelMock1: { - dto: any - singular: "OtherModelMock1" - plural: "OtherModelMock1s" - } - OtherModelMock2: { - dto: any - singular: "OtherModelMock2" - plural: "OtherModelMock2s" - } - } - >(MainModelMock, { OtherModelMock1, OtherModelMock2, }) describe("Main Model Methods", () => { - let instance + let instance: medusaService beforeEach(() => { jest.clearAllMocks() - instance = new abstractModuleService(containerMock) + instance = new medusaService(containerMock) }) it("should have retrieve method", async () => { - const result = await instance.retrieve("1") + const result = await instance.retrieveMainModelMock("1") expect(result).toEqual({ id: "1", name: "Item" }) expect(containerMock.mainModelMockService.retrieve).toHaveBeenCalledWith( "1", @@ -83,7 +70,7 @@ describe("Abstract Module Service Factory", () => { }) it("should have list method", async () => { - const result = await instance.list() + const result = await instance.listMainModelMocks() expect(result).toEqual([{ id: "1", name: "Item" }]) expect(containerMock.mainModelMockService.list).toHaveBeenCalledWith( {}, @@ -93,7 +80,7 @@ describe("Abstract Module Service Factory", () => { }) it("should have delete method", async () => { - await instance.delete("1") + await instance.deleteMainModelMocks("1") expect(containerMock.mainModelMockService.delete).toHaveBeenCalledWith( ["1"], defaultTransactionContext @@ -101,7 +88,7 @@ describe("Abstract Module Service Factory", () => { }) it("should have softDelete method", async () => { - const result = await instance.softDelete("1") + const result = await instance.softDeleteMainModelMocks("1") expect(result).toEqual({}) expect( containerMock.mainModelMockService.softDelete @@ -109,7 +96,7 @@ describe("Abstract Module Service Factory", () => { }) it("should have restore method", async () => { - const result = await instance.restore("1") + const result = await instance.restoreMainModelMocks("1") expect(result).toEqual({}) expect(containerMock.mainModelMockService.restore).toHaveBeenCalledWith( ["1"], @@ -118,7 +105,7 @@ describe("Abstract Module Service Factory", () => { }) it("should have delete method with selector", async () => { - await instance.delete({ selector: { id: "1" } }) + await instance.deleteMainModelMocks({ selector: { id: "1" } }) expect(containerMock.mainModelMockService.delete).toHaveBeenCalledWith( [{ selector: { id: "1" } }], defaultTransactionContext @@ -131,7 +118,7 @@ describe("Abstract Module Service Factory", () => { beforeEach(() => { jest.clearAllMocks() - instance = new abstractModuleService(containerMock) + instance = new medusaService(containerMock) }) it("should have retrieve method for other models", async () => { diff --git a/packages/core/utils/src/modules-sdk/definition.ts b/packages/core/utils/src/modules-sdk/definition.ts index a750b0f273..dabc9b8655 100644 --- a/packages/core/utils/src/modules-sdk/definition.ts +++ b/packages/core/utils/src/modules-sdk/definition.ts @@ -8,7 +8,7 @@ import type { IEventBusModuleService, IFileModuleService, IFulfillmentModuleService, - IInventoryServiceNext, + IInventoryService, INotificationModuleService, IOrderModuleService, IPaymentModuleService, @@ -17,7 +17,7 @@ import type { IPromotionModuleService, IRegionModuleService, ISalesChannelModuleService, - IStockLocationServiceNext, + IStockLocationService, IStoreModuleService, ITaxModuleService, IUserModuleService, @@ -84,7 +84,7 @@ declare module "@medusajs/types" { [ModuleRegistrationName.CART]: ICartModuleService [ModuleRegistrationName.CUSTOMER]: ICustomerModuleService [ModuleRegistrationName.EVENT_BUS]: IEventBusModuleService - [ModuleRegistrationName.INVENTORY]: IInventoryServiceNext + [ModuleRegistrationName.INVENTORY]: IInventoryService [ModuleRegistrationName.PAYMENT]: IPaymentModuleService [ModuleRegistrationName.PRICING]: IPricingModuleService [ModuleRegistrationName.PRODUCT]: IProductModuleService @@ -92,7 +92,7 @@ declare module "@medusajs/types" { [ModuleRegistrationName.SALES_CHANNEL]: ISalesChannelModuleService [ModuleRegistrationName.TAX]: ITaxModuleService [ModuleRegistrationName.FULFILLMENT]: IFulfillmentModuleService - [ModuleRegistrationName.STOCK_LOCATION]: IStockLocationServiceNext + [ModuleRegistrationName.STOCK_LOCATION]: IStockLocationService [ModuleRegistrationName.USER]: IUserModuleService [ModuleRegistrationName.WORKFLOW_ENGINE]: IWorkflowEngineService [ModuleRegistrationName.REGION]: IRegionModuleService diff --git a/packages/core/utils/src/modules-sdk/index.ts b/packages/core/utils/src/modules-sdk/index.ts index f093862c76..01c6796c75 100644 --- a/packages/core/utils/src/modules-sdk/index.ts +++ b/packages/core/utils/src/modules-sdk/index.ts @@ -10,3 +10,4 @@ export * from "./medusa-internal-service" export * from "./medusa-service" export * from "./definition" export * from "./event-builder-factory" +export * from "./joiner-config-builder" diff --git a/packages/core/utils/src/modules-sdk/joiner-config-builder.ts b/packages/core/utils/src/modules-sdk/joiner-config-builder.ts new file mode 100644 index 0000000000..fce24aaf6f --- /dev/null +++ b/packages/core/utils/src/modules-sdk/joiner-config-builder.ts @@ -0,0 +1,147 @@ +import { ModuleJoinerConfig } from "@medusajs/types" +import { + camelToSnakeCase, + deduplicate, + getCallerFilePath, + MapToConfig, + pluralize, + upperCaseFirst, +} from "../common" +import { join } from "path" +import { readdirSync, statSync } from "fs" + +/** + * Define joiner config for a module based on the models (object representation or entities) present in the models directory. This action will be sync until + * we move to at least es2022 to have access to top-leve await. + * + * The aliases will be built from the entityQueryingConfig and custom aliases if provided, in case of aliases provided if the methodSuffix is not provided + * then it will be inferred from the entity name of the alias args. + * + * @param moduleName + * @param alias + * @param schema + * @param entityQueryingConfig + * @param linkableKeys + * @param primaryKeys + */ +export function defineJoinerConfig( + moduleName: string, + { + alias, + schema, + entityQueryingConfig, + linkableKeys, + primaryKeys, + }: { + alias?: ModuleJoinerConfig["alias"] + schema?: string + entityQueryingConfig?: { name: string }[] + linkableKeys?: Record + primaryKeys?: string[] + } = {} +): Omit< + ModuleJoinerConfig, + "serviceName" | "primaryKeys" | "linkableKeys" | "alias" +> & + Required< + Pick< + ModuleJoinerConfig, + "serviceName" | "primaryKeys" | "linkableKeys" | "alias" + > + > { + let basePath = getCallerFilePath() + basePath = basePath.includes("dist") + ? basePath.split("dist")[0] + "dist" + : basePath.split("src")[0] + "src" + basePath = join(basePath, "models") + + const models = deduplicate( + [...(entityQueryingConfig ?? loadModels(basePath))].flatMap((v) => v!.name) + ).map((name) => ({ name })) + + return { + serviceName: moduleName, + primaryKeys: primaryKeys ?? ["id"], + schema, + linkableKeys: + linkableKeys ?? + models.reduce((acc, entity) => { + acc[`${camelToSnakeCase(entity.name).toLowerCase()}_id`] = entity.name + return acc + }, {} as Record), + alias: [ + ...[...(alias ?? ([] as any))].map((alias) => ({ + name: alias.name, + args: { + entity: alias.args.entity, + methodSuffix: + alias.args.methodSuffix ?? + pluralize(upperCaseFirst(alias.args.entity)), + }, + })), + ...models.map((entity, i) => ({ + name: [ + `${camelToSnakeCase(entity.name).toLowerCase()}`, + `${pluralize(camelToSnakeCase(entity.name).toLowerCase())}`, + ], + args: { + entity: entity.name, + methodSuffix: pluralize(upperCaseFirst(entity.name)), + }, + })), + ], + } +} + +/** + * Build entities name to linkable keys map + * @param linkableKeys + */ +export function buildEntitiesNameToLinkableKeysMap( + linkableKeys: Record +): MapToConfig { + const entityLinkableKeysMap: MapToConfig = {} + Object.entries(linkableKeys).forEach(([key, value]) => { + entityLinkableKeysMap[value] ??= [] + entityLinkableKeysMap[value].push({ + mapTo: key, + valueFrom: key.split("_").pop()!, + }) + }) + + return entityLinkableKeysMap +} + +function loadModels(basePath: string) { + const excludedExtensions = [".ts.map", ".js.map", ".d.ts"] + + let modelsFiles: any[] = [] + try { + modelsFiles = readdirSync(basePath) + } catch (e) {} + + return modelsFiles + .flatMap((file) => { + if ( + file.startsWith("index.") || + excludedExtensions.some((ext) => file.endsWith(ext)) + ) { + return + } + + const filePath = join(basePath, file) + const stats = statSync(filePath) + + if (stats.isFile()) { + try { + const required = require(filePath) + return Object.values(required).filter( + (resource) => typeof resource === "function" && !!resource.name + ) + } catch (e) {} + } + + return + }) + .filter(Boolean) as { name: string }[] +} diff --git a/packages/core/utils/src/modules-sdk/medusa-service.ts b/packages/core/utils/src/modules-sdk/medusa-service.ts index a46aac5963..fe389deffc 100644 --- a/packages/core/utils/src/modules-sdk/medusa-service.ts +++ b/packages/core/utils/src/modules-sdk/medusa-service.ts @@ -50,93 +50,60 @@ type ModelDTOConfig = { update?: any /** * @internal + * @deprecated */ singular?: string /** * @internal + * @deprecated */ plural?: string } type EntitiesConfigTemplate = { [key: string]: ModelDTOConfig } -type ModelConfigurationToDto = - T extends abstract new (...args: any) => infer R - ? R - : T extends { dto: infer DTO } - ? DTO - : any - -type ModelConfigurationsToConfigTemplate< - T extends Record -> = { +type ModelConfigurationsToConfigTemplate = { [Key in keyof T as `${Capitalize}`]: { - dto: ModelConfigurationToDto + dto: T[Key] extends Constructor ? InstanceType : any create: any update: any + singular: T[Key] extends { singular: string } ? T[Key]["singular"] : string + plural: T[Key] extends { plural: string } ? T[Key]["plural"] : string } } +/** + * @deprecated should all notion of singular and plural be removed once all modules are aligned with the convention + */ type ExtractSingularName, K = keyof T> = Capitalize< T[K] extends { singular?: string } ? T[K]["singular"] & string : K & string > +/** + * @deprecated should all notion of singular and plural be removed once all modules are aligned with the convention + * The pluralize will move to where it should be used instead + */ type ExtractPluralName, K = keyof T> = T[K] extends { plural?: string } ? T[K]["plural"] & string : Pluralize -// TODO: this will be removed in the follow up pr once the main entity concept will be removed -type ModelConfiguration = Constructor | ModelDTOConfig | any +// TODO: The future expected entry will be a DML object but in the meantime we have to maintain backward compatibility for ouw own modules and therefore we need to support Constructor as well as this temporary object +type TEntityEntries = Record< + Keys & string, + Constructor | { name?: string; singular?: string; plural?: string } +> -type ExtractMutationDtoOrAny = T extends unknown ? any : T - -export interface AbstractModuleServiceBase { - new (container: Record, ...args: any[]): this - - get __container__(): Record - - retrieve( - id: string, - config?: FindConfig, - sharedContext?: Context - ): Promise - - list( - filters?: any, - config?: FindConfig, - sharedContext?: Context - ): Promise - - listAndCount( - filters?: any, - config?: FindConfig, - sharedContext?: Context - ): Promise<[TEntryEntityConfig[], number]> - - delete( - primaryKeyValues: string | object | string[] | object[], - sharedContext?: Context - ): Promise - - softDelete( - primaryKeyValues: string | object | string[] | object[], - config?: SoftDeleteReturn, - sharedContext?: Context - ): Promise | void> - - restore( - primaryKeyValues: string | object | string[] | object[], - config?: RestoreReturn, - sharedContext?: Context - ): Promise | void> +type ExtractKeysFromConfig = EntitiesConfig extends { + __empty: any } + ? string + : keyof EntitiesConfig export type AbstractModuleService< - TEntryEntityConfig extends ModelConfiguration, TEntitiesDtoConfig extends EntitiesConfigTemplate -> = AbstractModuleServiceBase & { +> = { [TEntityName in keyof TEntitiesDtoConfig as `retrieve${ExtractSingularName< TEntitiesDtoConfig, TEntityName @@ -269,27 +236,21 @@ export type AbstractModuleService< * @internal */ function buildMethodNamesFromModel( - model: ModelConfiguration, - suffixed: boolean = true + modelName: string, + model: TEntityEntries[keyof TEntityEntries] ): Record { return methods.reduce((acc, method) => { - let modelName: string = "" + let normalizedModelName: string = "" if (method === "retrieve") { - modelName = - "singular" in model && model.singular - ? model.singular - : (model as { name: string }).name + normalizedModelName = + "singular" in model && model.singular ? model.singular : modelName } else { - modelName = - "plural" in model && model.plural - ? model.plural - : pluralize((model as { name: string }).name) + normalizedModelName = + "plural" in model && model.plural ? model.plural : pluralize(modelName) } - const methodName = suffixed - ? `${method}${upperCaseFirst(modelName)}` - : method + const methodName = `${method}${upperCaseFirst(normalizedModelName)}` return { ...acc, [method]: methodName } }, {}) @@ -300,31 +261,6 @@ function buildMethodNamesFromModel( * * @example * - * const entities = { - * Currency, - * Price, - * PriceList, - * PriceListRule, - * PriceListRuleValue, - * PriceRule, - * PriceSetRuleType, - * RuleType, - * } - * - * class MyService extends ModulesSdkUtils.MedusaService< - * PricingTypes.PriceSetDTO, - * { - * Currency: { dto: PricingTypes.CurrencyDTO } - * Price: { dto: PricingTypes.PriceDTO } - * PriceRule: { dto: PricingTypes.PriceRuleDTO } - * RuleType: { dto: PricingTypes.RuleTypeDTO } - * PriceList: { dto: PricingTypes.PriceListDTO } - * PriceListRule: { dto: PricingTypes.PriceListRuleDTO } - * } - * >(PriceSet, entities, entityNameToLinkableKeysMap) {} - * - * @example - * * // Here the DTO's and names will be inferred from the arguments * * const entities = { @@ -338,26 +274,21 @@ function buildMethodNamesFromModel( * RuleType, * } * - * class MyService extends ModulesSdkUtils.MedusaService(PriceSet, entities, entityNameToLinkableKeysMap) {} + * class MyService extends ModulesSdkUtils.MedusaService(entities, entityNameToLinkableKeysMap) {} * - * @param entryEntity * @param entities * @param entityNameToLinkableKeysMap */ export function MedusaService< - TEntryEntityConfig extends ModelConfiguration = ModelConfiguration, EntitiesConfig extends EntitiesConfigTemplate = { __empty: any }, - TEntities extends Record = Record< - string, - ModelConfiguration - > + TEntities extends TEntityEntries< + ExtractKeysFromConfig + > = TEntityEntries> >( - entryEntity: (TEntryEntityConfig & { name: string }) | Constructor, entities: TEntities, entityNameToLinkableKeysMap: MapToConfig = {} ): { new (...args: any[]): AbstractModuleService< - ModelConfigurationToDto, EntitiesConfig extends { __empty: any } ? ModelConfigurationsToConfigTemplate : EntitiesConfig @@ -595,7 +526,6 @@ export function MedusaService< this.baseRepository_ = container.baseRepository const hasEventBusModuleService = Object.keys(this.__container__).find( - // TODO: Should use ModuleRegistrationName.EVENT_BUS but it would require to move it to the utils package to prevent circular dependencies (key) => key === ModuleRegistrationName.EVENT_BUS ) @@ -618,33 +548,18 @@ export function MedusaService< } } - const entryEntityMethods = buildMethodNamesFromModel(entryEntity, false) - - /** - * Build the main retrieve/list/listAndCount/delete/softDelete/restore methods for the main model - */ - - for (let [method, methodName] of Object.entries(entryEntityMethods)) { - buildAndAssignMethodImpl( - AbstractModuleService_.prototype, - method, - methodName, - entryEntity.name - ) - } - /** * Build the retrieve/list/listAndCount/delete/softDelete/restore methods for all the other models */ const entitiesMethods: [ string, - ModelConfiguration, + TEntities[keyof TEntities], Record ][] = Object.entries(entities).map(([name, config]) => [ name, - config, - buildMethodNamesFromModel(config), + config as TEntities[keyof TEntities], + buildMethodNamesFromModel(name, config as TEntities[keyof TEntities]), ]) for (let [modelName, model, modelsMethods] of entitiesMethods) { diff --git a/packages/core/workflows-sdk/src/utils/composer/create-step.ts b/packages/core/workflows-sdk/src/utils/composer/create-step.ts index c8213d0fc1..2e602579f4 100644 --- a/packages/core/workflows-sdk/src/utils/composer/create-step.ts +++ b/packages/core/workflows-sdk/src/utils/composer/create-step.ts @@ -321,7 +321,7 @@ function wrapAsyncHandler( * const productService = context.container.resolve( * "productService" * ) - * const product = await productService.create(input) + * const product = await productService.createProducts(input) * return new StepResponse({ * product * }, { @@ -335,7 +335,7 @@ function wrapAsyncHandler( * const productService = context.container.resolve( * "productService" * ) - * await productService.delete(input.product_id) + * await productService.deleteProducts(input.product_id) * } * ) */ diff --git a/packages/core/workflows-sdk/src/utils/composer/helpers/step-response.ts b/packages/core/workflows-sdk/src/utils/composer/helpers/step-response.ts index b8d887a8b8..e0ba54ef28 100644 --- a/packages/core/workflows-sdk/src/utils/composer/helpers/step-response.ts +++ b/packages/core/workflows-sdk/src/utils/composer/helpers/step-response.ts @@ -66,7 +66,7 @@ export class StepResponse { * ) * * try { - * const product = await productService.create(input) + * const product = await productService.createProducts(input) * return new StepResponse({ * product * }, { diff --git a/packages/core/workflows-sdk/src/utils/composer/hook.ts b/packages/core/workflows-sdk/src/utils/composer/hook.ts index 952ec0f866..e6ac6f0691 100644 --- a/packages/core/workflows-sdk/src/utils/composer/hook.ts +++ b/packages/core/workflows-sdk/src/utils/composer/hook.ts @@ -1,6 +1,6 @@ -import { WorkflowStepHandlerArguments } from "@medusajs/orchestration" -import { OrchestrationUtils, deepCopy } from "@medusajs/utils" -import { resolveValue } from "./helpers" +import {WorkflowStepHandlerArguments} from "@medusajs/orchestration" +import {deepCopy, OrchestrationUtils} from "@medusajs/utils" +import {resolveValue} from "./helpers" import { CreateWorkflowComposerContext, StepExecutionContext, @@ -68,7 +68,7 @@ import { * async (product, context: StepExecutionContext) => { * const productService: ProductService = context.container.resolve("productService") * - * const updatedProduct = await productService.update(product.id, { + * const updatedProduct = await productService.updateProducts(product.id, { * description: "a cool shirt" * }) * diff --git a/packages/medusa/src/api/admin/currencies/[code]/route.ts b/packages/medusa/src/api/admin/currencies/[code]/route.ts index f800e80dc2..29e4d9dde9 100644 --- a/packages/medusa/src/api/admin/currencies/[code]/route.ts +++ b/packages/medusa/src/api/admin/currencies/[code]/route.ts @@ -8,7 +8,7 @@ import { MedusaRequest, MedusaResponse } from "../../../../types/routing" export const GET = async (req: MedusaRequest, res: MedusaResponse) => { const remoteQuery = req.scope.resolve(ContainerRegistrationKeys.REMOTE_QUERY) - const variables = { code: req.params.code } + const variables = { filters: { code: req.params.code } } const queryObject = remoteQueryObjectFromString({ entryPoint: "currency", diff --git a/packages/medusa/src/api/admin/fulfillment-sets/[id]/service-zones/[zone_id]/route.ts b/packages/medusa/src/api/admin/fulfillment-sets/[id]/service-zones/[zone_id]/route.ts index 9311de204f..15b3ed50ad 100644 --- a/packages/medusa/src/api/admin/fulfillment-sets/[id]/service-zones/[zone_id]/route.ts +++ b/packages/medusa/src/api/admin/fulfillment-sets/[id]/service-zones/[zone_id]/route.ts @@ -55,7 +55,7 @@ export const POST = async ( ) // ensure fulfillment set exists and that the service zone is part of it - const fulfillmentSet = await fulfillmentModuleService.retrieve( + const fulfillmentSet = await fulfillmentModuleService.retrieveFulfillmentSet( req.params.id, { relations: ["service_zones"] } ) @@ -102,9 +102,12 @@ export const DELETE = async ( ) // ensure fulfillment set exists and that the service zone is part of it - const fulfillmentSet = await fulfillmentModuleService.retrieve(id, { - relations: ["service_zones"], - }) + const fulfillmentSet = await fulfillmentModuleService.retrieveFulfillmentSet( + id, + { + relations: ["service_zones"], + } + ) if (!fulfillmentSet.service_zones.find((s) => s.id === zone_id)) { throw new MedusaError( diff --git a/packages/medusa/src/api/admin/price-lists/queries/list-prices.ts b/packages/medusa/src/api/admin/price-lists/queries/list-prices.ts index fcbb6265b9..43dd4eab50 100644 --- a/packages/medusa/src/api/admin/price-lists/queries/list-prices.ts +++ b/packages/medusa/src/api/admin/price-lists/queries/list-prices.ts @@ -4,7 +4,7 @@ import { remoteQueryObjectFromString, } from "@medusajs/utils" -export const listPrices = ( +export const listPrices = async ( ids: string[], scope: MedusaContainer, fields: string[] @@ -18,5 +18,5 @@ export const listPrices = ( fields, }) - return remoteQuery(queryObject) + return await remoteQuery(queryObject) } diff --git a/packages/medusa/src/api/store/currencies/[code]/route.ts b/packages/medusa/src/api/store/currencies/[code]/route.ts index f800e80dc2..29e4d9dde9 100644 --- a/packages/medusa/src/api/store/currencies/[code]/route.ts +++ b/packages/medusa/src/api/store/currencies/[code]/route.ts @@ -8,7 +8,7 @@ import { MedusaRequest, MedusaResponse } from "../../../../types/routing" export const GET = async (req: MedusaRequest, res: MedusaResponse) => { const remoteQuery = req.scope.resolve(ContainerRegistrationKeys.REMOTE_QUERY) - const variables = { code: req.params.code } + const variables = { filters: { code: req.params.code } } const queryObject = remoteQueryObjectFromString({ entryPoint: "currency", diff --git a/packages/medusa/src/api/store/shipping-options/route.ts b/packages/medusa/src/api/store/shipping-options/route.ts index 8c6351672f..e4733f1428 100644 --- a/packages/medusa/src/api/store/shipping-options/route.ts +++ b/packages/medusa/src/api/store/shipping-options/route.ts @@ -17,7 +17,7 @@ export const GET = async (req: MedusaRequest, res: MedusaResponse) => { ModuleRegistrationName.CART ) - const cart = await cartService.retrieve(cart_id, { + const cart = await cartService.retrieveCart(cart_id, { select: [ "id", "sales_channel_id", diff --git a/packages/medusa/src/api/utils/maybe-apply-link-filter.ts b/packages/medusa/src/api/utils/maybe-apply-link-filter.ts index 0df9508ea2..50d1b7ab17 100644 --- a/packages/medusa/src/api/utils/maybe-apply-link-filter.ts +++ b/packages/medusa/src/api/utils/maybe-apply-link-filter.ts @@ -1,7 +1,7 @@ import { + arrayIntersection, ContainerRegistrationKeys, remoteQueryObjectFromString, - arrayIntersection, } from "@medusajs/utils" import { NextFunction } from "express" import { MedusaRequest } from "../../types/routing" @@ -33,7 +33,7 @@ export function maybeApplyLinkFilter({ const queryObject = remoteQueryObjectFromString({ entryPoint, fields: [resourceId], - variables: { [filterableField]: idsToFilterBy }, + variables: { filters: { [filterableField]: idsToFilterBy } }, }) const resources = await remoteQuery(queryObject) diff --git a/packages/medusa/src/commands/user.ts b/packages/medusa/src/commands/user.ts index 9f1f2eeac3..f35920b4ef 100644 --- a/packages/medusa/src/commands/user.ts +++ b/packages/medusa/src/commands/user.ts @@ -42,7 +42,7 @@ export default async function ({ Invite token: ${invite.token} Open the invite in Medusa Admin at: [your-admin-url]/invite?token=${invite.token}`) } else { - const user = await userService.create({ email }) + const user = await userService.createUsers({ email }) const { authIdentity, error } = await authService.authenticate(provider, { body: { @@ -57,7 +57,7 @@ export default async function ({ } // We know the authIdentity is not undefined - await authService.update({ + await authService.updateAuthIdentites({ id: authIdentity!.id, app_metadata: { user_id: user.id, diff --git a/packages/medusa/src/subscribers/configurable-notifications.ts b/packages/medusa/src/subscribers/configurable-notifications.ts index cc622134d7..e1c3541239 100644 --- a/packages/medusa/src/subscribers/configurable-notifications.ts +++ b/packages/medusa/src/subscribers/configurable-notifications.ts @@ -69,7 +69,7 @@ export default async function configurableNotifications({ // We don't want to fail all handlers, so we catch and log errors only try { - await notificationService.create(notificationData) + await notificationService.createNotifications(notificationData) } catch (err) { logger.error( `Failed to send notification for ${eventName}`, diff --git a/packages/modules/api-key/integration-tests/__tests__/api-key-module-service.spec.ts b/packages/modules/api-key/integration-tests/__tests__/api-key-module-service.spec.ts index d335df613e..64649a0797 100644 --- a/packages/modules/api-key/integration-tests/__tests__/api-key-module-service.spec.ts +++ b/packages/modules/api-key/integration-tests/__tests__/api-key-module-service.spec.ts @@ -2,7 +2,7 @@ import { Modules } from "@medusajs/modules-sdk" import { IApiKeyModuleService } from "@medusajs/types" import { ApiKeyType } from "@medusajs/utils" import crypto from "crypto" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { createPublishableKeyFixture, createSecretKeyFixture, @@ -33,12 +33,9 @@ const mockSecretKeyBytes = () => { }) } -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.API_KEY, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { afterEach(() => { jest.restoreAllMocks() }) @@ -47,7 +44,9 @@ moduleIntegrationTestRunner({ describe("creating a publishable API key", () => { it("should create it successfully", async function () { mockPublishableKeyBytes() - const apiKey = await service.create(createPublishableKeyFixture) + const apiKey = await service.createApiKeys( + createPublishableKeyFixture + ) expect(apiKey).toEqual( expect.objectContaining({ @@ -69,7 +68,7 @@ moduleIntegrationTestRunner({ describe("creating a secret API key", () => { it("should get created successfully", async function () { mockSecretKeyBytes() - const apiKey = await service.create(createSecretKeyFixture) + const apiKey = await service.createApiKeys(createSecretKeyFixture) expect(apiKey).toEqual( expect.objectContaining({ @@ -89,14 +88,17 @@ moduleIntegrationTestRunner({ it("should only allow creating one active token", async function () { await expect( - service.create([createSecretKeyFixture, createSecretKeyFixture]) + service.createApiKeys([ + createSecretKeyFixture, + createSecretKeyFixture, + ]) ).rejects.toThrow( "You can only create one secret key at a time. You tried to create 2 secret keys." ) - await service.create(createSecretKeyFixture) + await service.createApiKeys(createSecretKeyFixture) const err = await service - .create(createSecretKeyFixture) + .createApiKeys(createSecretKeyFixture) .catch((e) => e) expect(err.message).toEqual( "You can only have one active secret key a time. Revoke or delete your existing key before creating a new one." @@ -104,7 +106,9 @@ moduleIntegrationTestRunner({ }) it("should allow for at most two tokens, where one is revoked", async function () { - const firstApiKey = await service.create(createSecretKeyFixture) + const firstApiKey = await service.createApiKeys( + createSecretKeyFixture + ) await service.revoke( { id: firstApiKey.id }, { @@ -112,9 +116,9 @@ moduleIntegrationTestRunner({ } ) - await service.create(createSecretKeyFixture) + await service.createApiKeys(createSecretKeyFixture) const err = await service - .create(createSecretKeyFixture) + .createApiKeys(createSecretKeyFixture) .catch((e) => e) expect(err.message).toEqual( "You can only have one active secret key a time. Revoke or delete your existing key before creating a new one." @@ -124,7 +128,9 @@ moduleIntegrationTestRunner({ describe("revoking API keys", () => { it("should have the revoked at and revoked by set when a key is revoked", async function () { - const firstApiKey = await service.create(createSecretKeyFixture) + const firstApiKey = await service.createApiKeys( + createSecretKeyFixture + ) const revokedKey = await service.revoke(firstApiKey.id, { revoked_by: "test", }) @@ -142,7 +148,7 @@ moduleIntegrationTestRunner({ const hourInSec = 3600 jest.useFakeTimers().setSystemTime(now) - const createdKey = await service.create(createSecretKeyFixture) + const createdKey = await service.createApiKeys(createSecretKeyFixture) const revokedKey = await service.revoke(createdKey.id, { revoked_by: "test", revoke_in: hourInSec, @@ -159,17 +165,21 @@ moduleIntegrationTestRunner({ }) it("should do nothing if the revokal list is empty", async function () { - const firstApiKey = await service.create(createSecretKeyFixture) + const firstApiKey = await service.createApiKeys( + createSecretKeyFixture + ) let revokedKeys = await service.revoke([]) expect(revokedKeys).toHaveLength(0) - const apiKey = await service.retrieve(firstApiKey.id) + const apiKey = await service.retrieveApiKey(firstApiKey.id) expect(apiKey.revoked_at).toBeFalsy() expect(apiKey.revoked_by).toBeFalsy() }) it("should not allow revoking an already revoked API key", async function () { - const firstApiKey = await service.create(createSecretKeyFixture) + const firstApiKey = await service.createApiKeys( + createSecretKeyFixture + ) await service.revoke(firstApiKey.id, { revoked_by: "test", }) @@ -188,18 +198,22 @@ moduleIntegrationTestRunner({ describe("updating an API key", () => { it("should update the name successfully", async function () { - const createdApiKey = await service.create(createSecretKeyFixture) + const createdApiKey = await service.createApiKeys( + createSecretKeyFixture + ) - const updatedApiKey = await service.update(createdApiKey.id, { + const updatedApiKey = await service.updateApiKeys(createdApiKey.id, { title: "New Name", }) expect(updatedApiKey.title).toEqual("New Name") }) it("should not reflect any updates on other fields", async function () { - const createdApiKey = await service.create(createSecretKeyFixture) + const createdApiKey = await service.createApiKeys( + createSecretKeyFixture + ) - const updatedApiKey = await service.update(createdApiKey.id, { + const updatedApiKey = await service.updateApiKeys(createdApiKey.id, { title: createdApiKey.title, revoked_by: "test", revoked_at: new Date(), @@ -214,27 +228,34 @@ moduleIntegrationTestRunner({ describe("deleting API keys", () => { it("should successfully delete existing api keys", async function () { - const createdApiKeys = await service.create([ + const createdApiKeys = await service.createApiKeys([ createPublishableKeyFixture, createSecretKeyFixture, ]) - await service.delete([createdApiKeys[0].id, createdApiKeys[1].id]) + await service.deleteApiKeys([ + createdApiKeys[0].id, + createdApiKeys[1].id, + ]) - const apiKeysInDatabase = await service.list() + const apiKeysInDatabase = await service.listApiKeys() expect(apiKeysInDatabase).toHaveLength(0) }) }) describe("authenticating with API keys", () => { it("should authenticate a secret key successfully", async function () { - const createdApiKey = await service.create(createSecretKeyFixture) + const createdApiKey = await service.createApiKeys( + createSecretKeyFixture + ) const authenticated = await service.authenticate(createdApiKey.token) expect(authenticated).toBeTruthy() expect(authenticated.title).toEqual(createSecretKeyFixture.title) }) it("should authenticate with a token to be revoked in the future", async function () { - const createdApiKey = await service.create(createSecretKeyFixture) + const createdApiKey = await service.createApiKeys( + createSecretKeyFixture + ) // We simulate setting the revoked_at in the future here jest.useFakeTimers().setSystemTime(new Date().setFullYear(3000)) @@ -249,7 +270,7 @@ moduleIntegrationTestRunner({ }) it("should not authenticate a publishable key", async function () { - const createdApiKey = await service.create( + const createdApiKey = await service.createApiKeys( createPublishableKeyFixture ) const authenticated = await service.authenticate(createdApiKey.token) @@ -257,13 +278,17 @@ moduleIntegrationTestRunner({ expect(authenticated).toBeFalsy() }) it("should not authenticate with a non-existent token", async function () { - const createdApiKey = await service.create(createSecretKeyFixture) + const createdApiKey = await service.createApiKeys( + createSecretKeyFixture + ) const authenticated = await service.authenticate("some-token") expect(authenticated).toBeFalsy() }) it("should not authenticate with a revoked token", async function () { - const createdApiKey = await service.create(createSecretKeyFixture) + const createdApiKey = await service.createApiKeys( + createSecretKeyFixture + ) await service.revoke(createdApiKey.id, { revoked_by: "test", }) @@ -275,22 +300,22 @@ moduleIntegrationTestRunner({ describe("retrieving API keys", () => { it("should successfully return all existing api keys", async function () { - await service.create([ + await service.createApiKeys([ createPublishableKeyFixture, createSecretKeyFixture, ]) - const apiKeysInDatabase = await service.list() + const apiKeysInDatabase = await service.listApiKeys() expect(apiKeysInDatabase).toHaveLength(2) }) it("should only return keys with matching token", async function () { - const created = await service.create([ + const created = await service.createApiKeys([ createPublishableKeyFixture, createPublishableKeyFixture, ]) - const apiKeysInDatabase = await service.list({ + const apiKeysInDatabase = await service.listApiKeys({ token: created[0].token, }) expect(apiKeysInDatabase).toHaveLength(1) @@ -298,55 +323,61 @@ moduleIntegrationTestRunner({ }) it("should not return the token and salt for secret keys when listing", async function () { - await service.create([createSecretKeyFixture]) + await service.createApiKeys([createSecretKeyFixture]) - const apiKeysInDatabase = await service.list() + const apiKeysInDatabase = await service.listApiKeys() expect(apiKeysInDatabase).toHaveLength(1) expect(apiKeysInDatabase[0].token).toBeFalsy() expect(apiKeysInDatabase[0].salt).toBeFalsy() }) it("should return the token for publishable keys when listing", async function () { - await service.create([createPublishableKeyFixture]) + await service.createApiKeys([createPublishableKeyFixture]) - const apiKeysInDatabase = await service.list() + const apiKeysInDatabase = await service.listApiKeys() expect(apiKeysInDatabase).toHaveLength(1) expect(apiKeysInDatabase[0].token).toBeTruthy() expect(apiKeysInDatabase[0].salt).toBeFalsy() }) it("should not return the token and salt for secret keys when listing and counting", async function () { - await service.create([createSecretKeyFixture]) + await service.createApiKeys([createSecretKeyFixture]) - const [apiKeysInDatabase] = await service.listAndCount() + const [apiKeysInDatabase] = await service.listAndCountApiKeys() expect(apiKeysInDatabase).toHaveLength(1) expect(apiKeysInDatabase[0].token).toBeFalsy() expect(apiKeysInDatabase[0].salt).toBeFalsy() }) it("should return the token for publishable keys when listing and counting", async function () { - await service.create([createPublishableKeyFixture]) + await service.createApiKeys([createPublishableKeyFixture]) - const [apiKeysInDatabase] = await service.listAndCount() + const [apiKeysInDatabase] = await service.listAndCountApiKeys() expect(apiKeysInDatabase).toHaveLength(1) expect(apiKeysInDatabase[0].token).toBeTruthy() expect(apiKeysInDatabase[0].salt).toBeFalsy() }) it("should not return the token and salt for secret keys when retrieving", async function () { - const [createdApiKey] = await service.create([createSecretKeyFixture]) + const [createdApiKey] = await service.createApiKeys([ + createSecretKeyFixture, + ]) - const apiKeyInDatabase = await service.retrieve(createdApiKey.id) + const apiKeyInDatabase = await service.retrieveApiKey( + createdApiKey.id + ) expect(apiKeyInDatabase.token).toBeFalsy() expect(apiKeyInDatabase.salt).toBeFalsy() }) it("should return the token for publishable keys when retrieving", async function () { - const [createdApiKey] = await service.create([ + const [createdApiKey] = await service.createApiKeys([ createPublishableKeyFixture, ]) - const apiKeyInDatabase = await service.retrieve(createdApiKey.id) + const apiKeyInDatabase = await service.retrieveApiKey( + createdApiKey.id + ) expect(apiKeyInDatabase.token).toBeTruthy() expect(apiKeyInDatabase.salt).toBeFalsy() }) diff --git a/packages/modules/api-key/package.json b/packages/modules/api-key/package.json index b805102b8c..5c0d98eafc 100644 --- a/packages/modules/api-key/package.json +++ b/packages/modules/api-key/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-api-key-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/api-key/src/index.ts b/packages/modules/api-key/src/index.ts index 5dc2ece165..f783378890 100644 --- a/packages/modules/api-key/src/index.ts +++ b/packages/modules/api-key/src/index.ts @@ -1,7 +1,5 @@ -import { moduleDefinition } from "./module-definition" - -export * from "./types" -export * from "./models" -export * from "./services" +import { ModuleExports } from "@medusajs/types" +import { ApiKeyModuleService } from "@services" +const moduleDefinition: ModuleExports = { service: ApiKeyModuleService } export default moduleDefinition diff --git a/packages/modules/api-key/src/joiner-config.ts b/packages/modules/api-key/src/joiner-config.ts index e80a16c2f0..f58891d8f3 100644 --- a/packages/modules/api-key/src/joiner-config.ts +++ b/packages/modules/api-key/src/joiner-config.ts @@ -1,31 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import ApiKey from "./models/api-key" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys: Record = { - api_key_id: ApiKey.name, -} +export const joinerConfig = defineJoinerConfig(Modules.API_KEY) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.API_KEY, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["api_key", "api_keys"], - args: { entity: ApiKey.name }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/api-key/src/module-definition.ts b/packages/modules/api-key/src/module-definition.ts deleted file mode 100644 index 27f88e7b12..0000000000 --- a/packages/modules/api-key/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { ApiKeyModuleService } from "@services" - -const service = ApiKeyModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/api-key/src/repositories/index.ts b/packages/modules/api-key/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/api-key/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/api-key/src/scripts/bin/run-seed.ts b/packages/modules/api-key/src/scripts/bin/run-seed.ts deleted file mode 100644 index 27098566d0..0000000000 --- a/packages/modules/api-key/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node - -import { ModulesSdkUtils } from "@medusajs/utils" -import { Modules } from "@medusajs/modules-sdk" -import * as Models from "@models" -import { EOL } from "os" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-api-key-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.API_KEY, - models: Models, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - // TODO: Add seed logic - }, - }) - await run({ path }) -})() diff --git a/packages/modules/api-key/src/services/api-key-module-service.ts b/packages/modules/api-key/src/services/api-key-module-service.ts index 860ea2ddaf..15fb077286 100644 --- a/packages/modules/api-key/src/services/api-key-module-service.ts +++ b/packages/modules/api-key/src/services/api-key-module-service.ts @@ -27,7 +27,7 @@ import { isString, MedusaContext, MedusaError, - ModulesSdkUtils, + MedusaService, promiseAll, } from "@medusajs/utils" @@ -38,17 +38,14 @@ type InjectedDependencies = { apiKeyService: ModulesSdkTypes.IMedusaInternalService } -export default class ApiKeyModuleService - extends ModulesSdkUtils.MedusaService< - ApiKeyTypes.ApiKeyDTO, - { - ApiKey: { dto: ApiKeyTypes.ApiKeyDTO } - } - >(ApiKey, {}, entityNameToLinkableKeysMap) +export default class ApiKeyModuleService + extends MedusaService<{ + ApiKey: { dto: ApiKeyTypes.ApiKeyDTO } + }>({ ApiKey }, entityNameToLinkableKeysMap) implements IApiKeyModuleService { protected baseRepository_: DAL.RepositoryService - protected readonly apiKeyService_: ModulesSdkTypes.IMedusaInternalService + protected readonly apiKeyService_: ModulesSdkTypes.IMedusaInternalService constructor( { baseRepository, apiKeyService }: InjectedDependencies, @@ -63,22 +60,22 @@ export default class ApiKeyModuleService __joinerConfig(): ModuleJoinerConfig { return joinerConfig } - - create( + //@ts-expect-error + createApiKeys( data: ApiKeyTypes.CreateApiKeyDTO[], sharedContext?: Context ): Promise - create( + createApiKeys( data: ApiKeyTypes.CreateApiKeyDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createApiKeys( data: ApiKeyTypes.CreateApiKeyDTO | ApiKeyTypes.CreateApiKeyDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { - const [createdApiKeys, generatedTokens] = await this.create_( + const [createdApiKeys, generatedTokens] = await this.createApiKeys_( Array.isArray(data) ? data : [data], sharedContext ) @@ -102,10 +99,10 @@ export default class ApiKeyModuleService } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createApiKeys_( data: ApiKeyTypes.CreateApiKeyDTO[], @MedusaContext() sharedContext: Context = {} - ): Promise<[TEntity[], TokenDTO[]]> { + ): Promise<[ApiKey[], TokenDTO[]]> { await this.validateCreateApiKeys_(data, sharedContext) const normalizedInput: CreateApiKeyDTO[] = [] @@ -135,17 +132,17 @@ export default class ApiKeyModuleService return [createdApiKeys, generatedTokens] } - async upsert( + async upsertApiKeys( data: ApiKeyTypes.UpsertApiKeyDTO[], sharedContext?: Context ): Promise - async upsert( + async upsertApiKeys( data: ApiKeyTypes.UpsertApiKeyDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async upsert( + async upsertApiKeys( data: ApiKeyTypes.UpsertApiKeyDTO | ApiKeyTypes.UpsertApiKeyDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -161,7 +158,7 @@ export default class ApiKeyModuleService if (forCreate.length) { const op = async () => { - const [createdApiKeys, generatedTokens] = await this.create_( + const [createdApiKeys, generatedTokens] = await this.createApiKeys_( forCreate, sharedContext ) @@ -188,7 +185,7 @@ export default class ApiKeyModuleService if (forUpdate.length) { const op = async () => { - const updateResp = await this.update_(forUpdate, sharedContext) + const updateResp = await this.updateApiKeys_(forUpdate, sharedContext) return await this.baseRepository_.serialize( updateResp ) @@ -201,19 +198,20 @@ export default class ApiKeyModuleService return Array.isArray(data) ? result : result[0] } - async update( + //@ts-expect-error + async updateApiKeys( id: string, data: ApiKeyTypes.UpdateApiKeyDTO, sharedContext?: Context ): Promise - async update( + async updateApiKeys( selector: FilterableApiKeyProps, data: ApiKeyTypes.UpdateApiKeyDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async update( + async updateApiKeys( idOrSelector: string | FilterableApiKeyProps, data: ApiKeyTypes.UpdateApiKeyDTO, @MedusaContext() sharedContext: Context = {} @@ -224,7 +222,10 @@ export default class ApiKeyModuleService sharedContext ) - const updatedApiKeys = await this.update_(normalizedInput, sharedContext) + const updatedApiKeys = await this.updateApiKeys_( + normalizedInput, + sharedContext + ) const serializedResponse = await this.baseRepository_.serialize< ApiKeyTypes.ApiKeyDTO[] @@ -236,10 +237,10 @@ export default class ApiKeyModuleService } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updateApiKeys_( normalizedInput: UpdateApiKeyInput[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const updateRequest = normalizedInput.map((k) => ({ id: k.id, title: k.title, @@ -253,7 +254,8 @@ export default class ApiKeyModuleService } @InjectManager("baseRepository_") - async retrieve( + // @ts-expect-error + async retrieveApiKey( id: string, config?: FindConfig, sharedContext?: Context @@ -269,7 +271,8 @@ export default class ApiKeyModuleService } @InjectManager("baseRepository_") - async list( + //@ts-expect-error + async listApiKeys( filters?: ApiKeyTypes.FilterableApiKeyProps, config?: FindConfig, sharedContext?: Context @@ -289,7 +292,8 @@ export default class ApiKeyModuleService } @InjectManager("baseRepository_") - async listAndCount( + //@ts-expect-error + async listAndCountApiKeys( filters?: ApiKeyTypes.FilterableApiKeyProps, config?: FindConfig, sharedContext?: Context @@ -347,7 +351,7 @@ export default class ApiKeyModuleService async revoke_( normalizedInput: RevokeApiKeyInput[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { await this.validateRevokeApiKeys_(normalizedInput) const updateRequest = normalizedInput.map((k) => { diff --git a/packages/modules/auth/integration-tests/__fixtures__/auth-identity/index.ts b/packages/modules/auth/integration-tests/__fixtures__/auth-identity/index.ts index 953188c1ea..187d16edba 100644 --- a/packages/modules/auth/integration-tests/__fixtures__/auth-identity/index.ts +++ b/packages/modules/auth/integration-tests/__fixtures__/auth-identity/index.ts @@ -32,5 +32,5 @@ export async function createAuthIdentities( }, ] ): Promise { - return await service.create(userData) + return await service.createAuthIdentities(userData) } diff --git a/packages/modules/auth/integration-tests/__tests__/auth-module-service/auth-identity.spec.ts b/packages/modules/auth/integration-tests/__tests__/auth-module-service/auth-identity.spec.ts index c7b70bb9d2..340b67191b 100644 --- a/packages/modules/auth/integration-tests/__tests__/auth-module-service/auth-identity.spec.ts +++ b/packages/modules/auth/integration-tests/__tests__/auth-module-service/auth-identity.spec.ts @@ -5,12 +5,9 @@ import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.AUTH, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("AuthModuleService - AuthIdentity", () => { beforeEach(async () => { await createAuthIdentities(service) @@ -18,7 +15,7 @@ moduleIntegrationTestRunner({ describe("listAuthIdentities", () => { it("should list authIdentities", async () => { - const authIdentities = await service.list( + const authIdentities = await service.listAuthIdentities( {}, { relations: ["provider_identities"] } ) @@ -43,7 +40,7 @@ moduleIntegrationTestRunner({ }) it("should list authIdentities by id", async () => { - const authIdentities = await service.list({ + const authIdentities = await service.listAuthIdentities({ id: ["test-id"], }) @@ -55,7 +52,7 @@ moduleIntegrationTestRunner({ }) it("should list authIdentities by provider", async () => { - const authIdentities = await service.list({ + const authIdentities = await service.listAuthIdentities({ provider_identities: { provider: "manual", }, @@ -74,10 +71,11 @@ moduleIntegrationTestRunner({ describe("listAndCountAuthIdentities", () => { it("should list and count authIdentities", async () => { - const [authIdentities, count] = await service.listAndCount( - {}, - { relations: ["provider_identities"] } - ) + const [authIdentities, count] = + await service.listAndCountAuthIdentities( + {}, + { relations: ["provider_identities"] } + ) expect(count).toEqual(3) expect(authIdentities).toEqual([ @@ -100,9 +98,10 @@ moduleIntegrationTestRunner({ }) it("should listAndCount authIdentities by provider_id", async () => { - const [authIdentities, count] = await service.listAndCount({ - provider_identities: { provider: "manual" }, - }) + const [authIdentities, count] = + await service.listAndCountAuthIdentities({ + provider_identities: { provider: "manual" }, + }) expect(count).toEqual(2) expect(authIdentities).toEqual([ @@ -120,7 +119,7 @@ moduleIntegrationTestRunner({ const id = "test-id" it("should return an authIdentity for the given id", async () => { - const authIdentity = await service.retrieve(id) + const authIdentity = await service.retrieveAuthIdentity(id) expect(authIdentity).toEqual( expect.objectContaining({ @@ -133,7 +132,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve("does-not-exist") + await service.retrieveAuthIdentity("does-not-exist") } catch (e) { error = e } @@ -144,7 +143,7 @@ moduleIntegrationTestRunner({ }) it("should not return an authIdentity with password hash", async () => { - const authIdentity = await service.retrieve("test-id-1") + const authIdentity = await service.retrieveAuthIdentity("test-id-1") expect(authIdentity).toEqual( expect.objectContaining({ @@ -162,7 +161,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve(undefined as unknown as string) + await service.retrieveAuthIdentity(undefined as unknown as string) } catch (e) { error = e } @@ -171,7 +170,7 @@ moduleIntegrationTestRunner({ }) it("should return authIdentity based on config select param", async () => { - const authIdentity = await service.retrieve(id, { + const authIdentity = await service.retrieveAuthIdentity(id, { select: ["id"], }) @@ -185,9 +184,9 @@ moduleIntegrationTestRunner({ const id = "test-id" it("should delete the authIdentities given an id successfully", async () => { - await service.delete([id]) + await service.deleteAuthIdentities([id]) - const authIdentities = await service.list({ + const authIdentities = await service.listAuthIdentities({ id: [id], }) @@ -202,7 +201,7 @@ moduleIntegrationTestRunner({ let error try { - await service.update([ + await service.updateAuthIdentites([ { id: "does-not-exist", }, @@ -217,14 +216,14 @@ moduleIntegrationTestRunner({ }) it("should update authIdentity", async () => { - await service.update([ + await service.updateAuthIdentites([ { id, app_metadata: { email: "test@email.com" }, }, ]) - const [authIdentity] = await service.list({ id: [id] }) + const [authIdentity] = await service.listAuthIdentities({ id: [id] }) expect(authIdentity).toEqual( expect.objectContaining({ app_metadata: { email: "test@email.com" }, @@ -235,7 +234,7 @@ moduleIntegrationTestRunner({ describe("createAuthIdentity", () => { it("should create a authIdentity successfully", async () => { - await service.create([ + await service.createAuthIdentities([ { id: "test", provider_identities: [ @@ -247,9 +246,10 @@ moduleIntegrationTestRunner({ }, ]) - const [authIdentity, count] = await service.listAndCount({ - id: ["test"], - }) + const [authIdentity, count] = + await service.listAndCountAuthIdentities({ + id: ["test"], + }) expect(count).toEqual(1) expect(authIdentity[0]).toEqual( diff --git a/packages/modules/auth/integration-tests/__tests__/auth-module-service/index.spec.ts b/packages/modules/auth/integration-tests/__tests__/auth-module-service/index.spec.ts index 2d54159b24..489f54075f 100644 --- a/packages/modules/auth/integration-tests/__tests__/auth-module-service/index.spec.ts +++ b/packages/modules/auth/integration-tests/__tests__/auth-module-service/index.spec.ts @@ -27,7 +27,7 @@ moduleIntegrationTestRunner({ testSuite: ({ service }: SuiteOptions) => describe("Auth Module Service", () => { beforeEach(async () => { - await service.create({ + await service.createAuthIdentities({ provider_identities: [ { entity_id: "test@admin.com", @@ -103,7 +103,7 @@ moduleIntegrationTestRunner({ }, }) - const dbAuthIdentity = await service.retrieve( + const dbAuthIdentity = await service.retrieveAuthIdentity( result.authIdentity?.id!, { relations: ["provider_identities"] } ) diff --git a/packages/modules/auth/package.json b/packages/modules/auth/package.json index f160ec1ee2..f58798e328 100644 --- a/packages/modules/auth/package.json +++ b/packages/modules/auth/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-auth-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/auth/src/index.ts b/packages/modules/auth/src/index.ts index dd414e1b19..45b01a150c 100644 --- a/packages/modules/auth/src/index.ts +++ b/packages/modules/auth/src/index.ts @@ -1,3 +1,9 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { AuthModuleService } from "@services" +import loadProviders from "./loaders/providers" +const moduleDefinition: ModuleExports = { + service: AuthModuleService, + loaders: [loadProviders] as any, +} export default moduleDefinition diff --git a/packages/modules/auth/src/joiner-config.ts b/packages/modules/auth/src/joiner-config.ts index dd97bcd7f3..dd8c39a668 100644 --- a/packages/modules/auth/src/joiner-config.ts +++ b/packages/modules/auth/src/joiner-config.ts @@ -1,31 +1,14 @@ import { AuthIdentity } from "@models" -import { MapToConfig } from "@medusajs/utils" -import { ModuleJoinerConfig } from "@medusajs/types" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" import { Modules } from "@medusajs/modules-sdk" -export const LinkableKeys = { - auth_identity_id: AuthIdentity.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) +export const joinerConfig = defineJoinerConfig(Modules.AUTH, { + entityQueryingConfig: [AuthIdentity], }) -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.AUTH, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: { - name: ["auth_identity", "auth_identities"], - args: { - entity: AuthIdentity.name, - }, - }, -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/auth/src/module-definition.ts b/packages/modules/auth/src/module-definition.ts deleted file mode 100644 index dbf1db9d85..0000000000 --- a/packages/modules/auth/src/module-definition.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { AuthModuleService } from "@services" -import loadProviders from "./loaders/providers" - -const service = AuthModuleService -const loaders = [loadProviders] as any - -export const moduleDefinition: ModuleExports = { - service, - loaders, -} diff --git a/packages/modules/auth/src/repositories/index.ts b/packages/modules/auth/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/auth/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/auth/src/services/auth-module.ts b/packages/modules/auth/src/services/auth-module.ts index 3bee34f61e..d8c3342159 100644 --- a/packages/modules/auth/src/services/auth-module.ts +++ b/packages/modules/auth/src/services/auth-module.ts @@ -18,7 +18,7 @@ import { InjectManager, MedusaContext, MedusaError, - ModulesSdkUtils, + MedusaService, } from "@medusajs/utils" import AuthProviderService from "./auth-provider" @@ -28,25 +28,16 @@ type InjectedDependencies = { providerIdentityService: ModulesSdkTypes.IMedusaInternalService authProviderService: AuthProviderService } - -const generateMethodForModels = { AuthIdentity, ProviderIdentity } - -export default class AuthModuleService< - TAuthIdentity extends AuthIdentity = AuthIdentity, - TProviderIdentity extends ProviderIdentity = ProviderIdentity - > - extends ModulesSdkUtils.MedusaService< - AuthTypes.AuthIdentityDTO, - { - AuthIdentity: { dto: AuthTypes.AuthIdentityDTO } - ProviderIdentity: { dto: AuthTypes.ProviderIdentityDTO } - } - >(AuthIdentity, generateMethodForModels, entityNameToLinkableKeysMap) +export default class AuthModuleService + extends MedusaService<{ + AuthIdentity: { dto: AuthTypes.AuthIdentityDTO } + ProviderIdentity: { dto: AuthTypes.ProviderIdentityDTO } + }>({ AuthIdentity, ProviderIdentity }, entityNameToLinkableKeysMap) implements AuthTypes.IAuthModuleService { protected baseRepository_: DAL.RepositoryService - protected authIdentityService_: ModulesSdkTypes.IMedusaInternalService - protected providerIdentityService_: ModulesSdkTypes.IMedusaInternalService + protected authIdentityService_: ModulesSdkTypes.IMedusaInternalService + protected providerIdentityService_: ModulesSdkTypes.IMedusaInternalService protected readonly authProviderService_: AuthProviderService constructor( @@ -71,18 +62,19 @@ export default class AuthModuleService< return joinerConfig } - create( + // @ts-expect-error + createAuthIdentities( data: AuthTypes.CreateAuthIdentityDTO[], sharedContext?: Context ): Promise - create( + createAuthIdentities( data: AuthTypes.CreateAuthIdentityDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createAuthIdentities( data: AuthTypes.CreateAuthIdentityDTO[] | AuthTypes.CreateAuthIdentityDTO, @MedusaContext() sharedContext: Context = {} ): Promise { @@ -99,19 +91,19 @@ export default class AuthModuleService< ) } - update( + // TODO: Update to follow convention + updateAuthIdentites( data: AuthTypes.UpdateAuthIdentityDTO[], sharedContext?: Context ): Promise - update( + updateAuthIdentites( data: AuthTypes.UpdateAuthIdentityDTO, sharedContext?: Context ): Promise - // TODO: should be pluralized, see convention about the methods naming or the abstract module service interface definition @engineering @InjectManager("baseRepository_") - async update( + async updateAuthIdentites( data: AuthTypes.UpdateAuthIdentityDTO | AuthTypes.UpdateAuthIdentityDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { diff --git a/packages/modules/cache-inmemory/package.json b/packages/modules/cache-inmemory/package.json index 060d752428..8442a9d586 100644 --- a/packages/modules/cache-inmemory/package.json +++ b/packages/modules/cache-inmemory/package.json @@ -9,7 +9,7 @@ "directory": "packages/cache-inmemory" }, "engines": { - "node": ">=16" + "node": ">=20" }, "publishConfig": { "access": "public" diff --git a/packages/modules/cache-redis/package.json b/packages/modules/cache-redis/package.json index c353d63ea3..ee37a21e6b 100644 --- a/packages/modules/cache-redis/package.json +++ b/packages/modules/cache-redis/package.json @@ -12,7 +12,7 @@ "access": "public" }, "engines": { - "node": ">=16" + "node": ">=20" }, "files": [ "dist" diff --git a/packages/modules/cart/integration-tests/__tests__/services/cart-module/index.spec.ts b/packages/modules/cart/integration-tests/__tests__/services/cart-module/index.spec.ts index fea491991c..d234ffbe0a 100644 --- a/packages/modules/cart/integration-tests/__tests__/services/cart-module/index.spec.ts +++ b/packages/modules/cart/integration-tests/__tests__/services/cart-module/index.spec.ts @@ -2,21 +2,18 @@ import { Modules } from "@medusajs/modules-sdk" import { ICartModuleService } from "@medusajs/types" import { BigNumber } from "@medusajs/utils" import { CheckConstraintViolationException } from "@mikro-orm/core" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(50000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.CART, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { describe("Cart Module Service", () => { describe("create", () => { it("should throw an error when required params are not passed", async () => { const error = await service - .create([ + .createCarts([ { email: "test@email.com", } as any, @@ -29,13 +26,13 @@ moduleIntegrationTestRunner({ }) it("should create a cart successfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, ]) - const [cart] = await service.list({ id: [createdCart.id] }) + const [cart] = await service.listCarts({ id: [createdCart.id] }) expect(cart).toEqual( expect.objectContaining({ @@ -46,7 +43,7 @@ moduleIntegrationTestRunner({ }) it("should create a cart with billing + shipping address successfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", billing_address: { @@ -60,7 +57,7 @@ moduleIntegrationTestRunner({ }, ]) - const [cart] = await service.list( + const [cart] = await service.listCarts( { id: [createdCart.id] }, { relations: ["billing_address", "shipping_address"] } ) @@ -89,7 +86,7 @@ moduleIntegrationTestRunner({ }, ]) - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", billing_address_id: createdAddress.id, @@ -116,7 +113,7 @@ moduleIntegrationTestRunner({ }) it("should create a cart with items", async () => { - const createdCart = await service.create({ + const createdCart = await service.createCarts({ currency_code: "eur", items: [ { @@ -127,7 +124,7 @@ moduleIntegrationTestRunner({ ], }) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items"], }) @@ -146,7 +143,7 @@ moduleIntegrationTestRunner({ }) it("should create multiple carts with items", async () => { - const createdCarts = await service.create([ + const createdCarts = await service.createCarts([ { currency_code: "eur", items: [ @@ -169,7 +166,7 @@ moduleIntegrationTestRunner({ }, ]) - const carts = await service.list( + const carts = await service.listCarts( { id: createdCarts.map((c) => c.id) }, { relations: ["items"], @@ -204,7 +201,7 @@ moduleIntegrationTestRunner({ describe("update", () => { it("should throw an error if cart does not exist", async () => { const error = await service - .update([ + .updateCarts([ { id: "none-existing", }, @@ -217,20 +214,20 @@ moduleIntegrationTestRunner({ }) it("should update a cart successfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, ]) - const [updatedCart] = await service.update([ + const [updatedCart] = await service.updateCarts([ { id: createdCart.id, email: "test@email.com", }, ]) - const [cart] = await service.list({ id: [createdCart.id] }) + const [cart] = await service.listCarts({ id: [createdCart.id] }) expect(cart).toEqual( expect.objectContaining({ @@ -242,20 +239,20 @@ moduleIntegrationTestRunner({ }) it("should update a cart with selector successfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, ]) - const [updatedCart] = await service.update( + const [updatedCart] = await service.updateCarts( { id: createdCart.id }, { email: "test@email.com", } ) - const [cart] = await service.list({ id: [createdCart.id] }) + const [cart] = await service.listCarts({ id: [createdCart.id] }) expect(cart).toEqual( expect.objectContaining({ @@ -267,17 +264,17 @@ moduleIntegrationTestRunner({ }) it("should update a cart with id successfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, ]) - const updatedCart = await service.update(createdCart.id, { + const updatedCart = await service.updateCarts(createdCart.id, { email: "test@email.com", }) - const [cart] = await service.list({ id: [createdCart.id] }) + const [cart] = await service.listCarts({ id: [createdCart.id] }) expect(cart).toEqual( expect.objectContaining({ @@ -291,15 +288,15 @@ moduleIntegrationTestRunner({ describe("delete", () => { it("should delete a cart successfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, ]) - await service.delete([createdCart.id]) + await service.deleteCarts([createdCart.id]) - const carts = await service.list({ id: [createdCart.id] }) + const carts = await service.listCarts({ id: [createdCart.id] }) expect(carts.length).toEqual(0) }) @@ -367,7 +364,7 @@ moduleIntegrationTestRunner({ describe("addLineItems", () => { it("should add a line item to cart succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -381,7 +378,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items"], }) @@ -396,7 +393,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple line items to cart succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -417,7 +414,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items"], }) @@ -440,13 +437,13 @@ moduleIntegrationTestRunner({ }) it("should add multiple line items to multiple carts succesfully", async () => { - let [eurCart] = await service.create([ + let [eurCart] = await service.createCarts([ { currency_code: "eur", }, ]) - let [usdCart] = await service.create([ + let [usdCart] = await service.createCarts([ { currency_code: "usd", }, @@ -467,7 +464,7 @@ moduleIntegrationTestRunner({ }, ]) - const carts = await service.list( + const carts = await service.listCarts( { id: [eurCart.id, usdCart.id] }, { relations: ["items"] } ) @@ -501,7 +498,7 @@ moduleIntegrationTestRunner({ }) it("should throw an error when required params are not passed adding to a single cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -522,7 +519,7 @@ moduleIntegrationTestRunner({ }) it("should throw a generic error when required params are not passed using bulk add method", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -546,7 +543,7 @@ moduleIntegrationTestRunner({ describe("updateLineItems", () => { it("should update a line item in cart succesfully with selector approach", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -574,7 +571,7 @@ moduleIntegrationTestRunner({ }) it("should update a line item in cart succesfully with id approach", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -599,7 +596,7 @@ moduleIntegrationTestRunner({ }) it("should update line items in carts succesfully with multi-selector approach", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -670,7 +667,7 @@ moduleIntegrationTestRunner({ describe("removeLineItems", () => { it("should remove a line item succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -689,7 +686,7 @@ moduleIntegrationTestRunner({ await service.softDeleteLineItems([item.id]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items"], }) @@ -697,7 +694,7 @@ moduleIntegrationTestRunner({ }) it("should remove multiple line items succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -718,7 +715,7 @@ moduleIntegrationTestRunner({ await service.softDeleteLineItems([item.id, item2.id]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items"], }) @@ -728,7 +725,7 @@ moduleIntegrationTestRunner({ describe("addShippingMethods", () => { it("should add a shipping method to cart succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -741,7 +738,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["shipping_methods"], }) @@ -749,7 +746,7 @@ moduleIntegrationTestRunner({ }) it("should throw when amount is negative", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -768,13 +765,13 @@ moduleIntegrationTestRunner({ }) it("should add multiple shipping methods to multiple carts succesfully", async () => { - let [eurCart] = await service.create([ + let [eurCart] = await service.createCarts([ { currency_code: "eur", }, ]) - let [usdCart] = await service.create([ + let [usdCart] = await service.createCarts([ { currency_code: "usd", }, @@ -793,7 +790,7 @@ moduleIntegrationTestRunner({ }, ]) - const carts = await service.list( + const carts = await service.listCarts( { id: [eurCart.id, usdCart.id] }, { relations: ["shipping_methods"] } ) @@ -814,7 +811,7 @@ moduleIntegrationTestRunner({ describe("removeShippingMethods", () => { it("should remove a line item succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -831,7 +828,7 @@ moduleIntegrationTestRunner({ await service.softDeleteShippingMethods([method.id]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["shipping_methods"], }) @@ -841,7 +838,7 @@ moduleIntegrationTestRunner({ describe("setLineItemAdjustments", () => { it("should set line item adjustments for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -896,7 +893,7 @@ moduleIntegrationTestRunner({ }) it("should replace line item adjustments for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -939,7 +936,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items.adjustments"], }) @@ -963,7 +960,7 @@ moduleIntegrationTestRunner({ }) it("should remove all line item adjustments for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1000,7 +997,7 @@ moduleIntegrationTestRunner({ await service.setLineItemAdjustments(createdCart.id, []) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items.adjustments"], }) @@ -1018,7 +1015,7 @@ moduleIntegrationTestRunner({ }) it("should update line item adjustments for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1062,7 +1059,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items.adjustments"], }) @@ -1089,7 +1086,7 @@ moduleIntegrationTestRunner({ describe("addLineItemAdjustments", () => { it("should add line item adjustments for items in a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1126,7 +1123,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple line item adjustments for multiple line items", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1180,12 +1177,12 @@ moduleIntegrationTestRunner({ }) it("should add line item adjustments for line items on multiple carts", async () => { - const [cartOne] = await service.create([ + const [cartOne] = await service.createCarts([ { currency_code: "eur", }, ]) - const [cartTwo] = await service.create([ + const [cartTwo] = await service.createCarts([ { currency_code: "usd", }, @@ -1261,7 +1258,7 @@ moduleIntegrationTestRunner({ describe("removeLineItemAdjustments", () => { it("should remove a line item succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1279,6 +1276,7 @@ moduleIntegrationTestRunner({ createdCart.id, [ { + code: "50", item_id: item.id, amount: 50, }, @@ -1299,7 +1297,7 @@ moduleIntegrationTestRunner({ describe("setShippingMethodAdjustments", () => { it("should set shipping method adjustments for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1358,7 +1356,7 @@ moduleIntegrationTestRunner({ }) it("should replace shipping method adjustments for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1403,7 +1401,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["shipping_methods.adjustments"], }) @@ -1428,7 +1426,7 @@ moduleIntegrationTestRunner({ }) it("should remove all shipping method adjustments for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1467,7 +1465,7 @@ moduleIntegrationTestRunner({ await service.setShippingMethodAdjustments(createdCart.id, []) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["shipping_methods.adjustments"], }) @@ -1485,7 +1483,7 @@ moduleIntegrationTestRunner({ }) it("should update shipping method adjustments for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1530,7 +1528,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["shipping_methods.adjustments"], }) @@ -1557,7 +1555,7 @@ moduleIntegrationTestRunner({ describe("addShippingMethodAdjustments", () => { it("should add shipping method adjustments in a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1596,7 +1594,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple shipping method adjustments for multiple shipping methods", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1654,12 +1652,12 @@ moduleIntegrationTestRunner({ }) it("should add shipping method adjustments for shipping methods on multiple carts", async () => { - const [cartOne] = await service.create([ + const [cartOne] = await service.createCarts([ { currency_code: "eur", }, ]) - const [cartTwo] = await service.create([ + const [cartTwo] = await service.createCarts([ { currency_code: "usd", }, @@ -1738,13 +1736,13 @@ moduleIntegrationTestRunner({ }) it("should throw if shipping method is not associated with cart", async () => { - const [cartOne] = await service.create([ + const [cartOne] = await service.createCarts([ { currency_code: "eur", }, ]) - const [cartTwo] = await service.create([ + const [cartTwo] = await service.createCarts([ { currency_code: "eur", }, @@ -1778,7 +1776,7 @@ moduleIntegrationTestRunner({ describe("removeShippingMethodAdjustments", () => { it("should remove a shipping method succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1816,7 +1814,7 @@ moduleIntegrationTestRunner({ describe("setLineItemTaxLines", () => { it("should set line item tax lines for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1868,7 +1866,7 @@ moduleIntegrationTestRunner({ }) it("should replace line item tax lines for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1908,7 +1906,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items.tax_lines"], }) @@ -1932,7 +1930,7 @@ moduleIntegrationTestRunner({ }) it("should remove all line item tax lines for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -1966,7 +1964,7 @@ moduleIntegrationTestRunner({ await service.setLineItemTaxLines(createdCart.id, []) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items.tax_lines"], }) @@ -1984,7 +1982,7 @@ moduleIntegrationTestRunner({ }) it("should update line item tax lines for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -2025,7 +2023,7 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items.tax_lines"], }) @@ -2050,7 +2048,7 @@ moduleIntegrationTestRunner({ }) it("should remove, update, and create line item tax lines for a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -2110,7 +2108,7 @@ moduleIntegrationTestRunner({ // remove: should remove the initial tax line for itemOne ]) - const cart = await service.retrieve(createdCart.id, { + const cart = await service.retrieveCart(createdCart.id, { relations: ["items.tax_lines"], }) @@ -2142,7 +2140,7 @@ moduleIntegrationTestRunner({ describe("addLineItemAdjustments", () => { it("should add line item tax lines for items in a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -2176,7 +2174,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple line item tax lines for multiple line items", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -2227,12 +2225,12 @@ moduleIntegrationTestRunner({ }) it("should add line item tax lines for line items on multiple carts", async () => { - const [cartOne] = await service.create([ + const [cartOne] = await service.createCarts([ { currency_code: "eur", }, ]) - const [cartTwo] = await service.create([ + const [cartTwo] = await service.createCarts([ { currency_code: "usd", }, @@ -2308,7 +2306,7 @@ moduleIntegrationTestRunner({ describe("removeLineItemAdjustments", () => { it("should remove line item tax line succesfully", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -2344,7 +2342,7 @@ moduleIntegrationTestRunner({ }) it("should calculate totals of a cart", async () => { - const [createdCart] = await service.create([ + const [createdCart] = await service.createCarts([ { currency_code: "eur", }, @@ -2386,7 +2384,9 @@ moduleIntegrationTestRunner({ }, ]) - const cart = await service.retrieve(createdCart.id, { select: ["total"] }) + const cart = await service.retrieveCart(createdCart.id, { + select: ["total"], + }) expect(cart.total).toBeInstanceOf(BigNumber) const asJson = JSON.parse(JSON.stringify(cart)) diff --git a/packages/modules/cart/package.json b/packages/modules/cart/package.json index 81d34896d0..6770ea3113 100644 --- a/packages/modules/cart/package.json +++ b/packages/modules/cart/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-cart-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/cart/src/index.ts b/packages/modules/cart/src/index.ts index dd414e1b19..b771f94cb5 100644 --- a/packages/modules/cart/src/index.ts +++ b/packages/modules/cart/src/index.ts @@ -1,3 +1,10 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { CartModuleService } from "./services" + +const service = CartModuleService + +export const moduleDefinition: ModuleExports = { + service, +} export default moduleDefinition diff --git a/packages/modules/cart/src/joiner-config.ts b/packages/modules/cart/src/joiner-config.ts index 840fed9661..1ce87ac804 100644 --- a/packages/modules/cart/src/joiner-config.ts +++ b/packages/modules/cart/src/joiner-config.ts @@ -1,98 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" import { - Address, - Cart, - LineItem, - LineItemAdjustment, - LineItemTaxLine, - ShippingMethod, - ShippingMethodAdjustment, - ShippingMethodTaxLine, -} from "@models" + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys = { - cart_id: Cart.name, - line_item_id: LineItem.name, - shipping_method_id: ShippingMethod.name, - address_id: Address.name, - line_item_adjustment_id: LineItemAdjustment.name, - shipping_method_adjustment_id: ShippingMethodAdjustment.name, - line_item_tax_line_id: LineItemTaxLine.name, - shipping_method_tax_line_id: ShippingMethodTaxLine.name, -} +export const joinerConfig = defineJoinerConfig(Modules.CART) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.CART, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["cart", "carts"], - args: { - entity: Cart.name, - }, - }, - { - name: ["line_item", "line_items"], - args: { - entity: LineItem.name, - methodSuffix: "LineItems", - }, - }, - { - name: ["shipping_method", "shipping_methods"], - args: { - entity: ShippingMethod.name, - methodSuffix: "ShippingMethods", - }, - }, - { - name: ["address", "addresses"], - args: { - entity: Address.name, - methodSuffix: "Addresses", - }, - }, - { - name: ["line_item_adjustment", "line_item_adjustments"], - args: { - entity: LineItemAdjustment.name, - methodSuffix: "LineItemAdjustments", - }, - }, - { - name: ["shipping_method_adjustment", "shipping_method_adjustments"], - args: { - entity: ShippingMethodAdjustment.name, - methodSuffix: "ShippingMethodAdjustments", - }, - }, - { - name: ["line_item_tax_line", "line_item_tax_lines"], - args: { - entity: LineItemTaxLine.name, - methodSuffix: "LineItemTaxLines", - }, - }, - { - name: ["shipping_method_tax_line", "shipping_method_tax_lines"], - args: { - entity: ShippingMethodTaxLine.name, - methodSuffix: "ShippingMethodTaxLines", - }, - }, - ], -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/cart/src/module-definition.ts b/packages/modules/cart/src/module-definition.ts deleted file mode 100644 index efcb04d5fe..0000000000 --- a/packages/modules/cart/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { CartModuleService } from "./services" - -const service = CartModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/cart/src/repositories/index.ts b/packages/modules/cart/src/repositories/index.ts deleted file mode 100644 index d905f87a65..0000000000 --- a/packages/modules/cart/src/repositories/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"; - diff --git a/packages/modules/cart/src/scripts/bin/run-seed.ts b/packages/modules/cart/src/scripts/bin/run-seed.ts deleted file mode 100644 index 21f41d64b5..0000000000 --- a/packages/modules/cart/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env node - -import { EOL } from "os" -import { run } from "../seed" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-cart-seed ` - ) - } - - await run({ path }) -})() diff --git a/packages/modules/cart/src/scripts/seed.ts b/packages/modules/cart/src/scripts/seed.ts deleted file mode 100644 index 2933c93823..0000000000 --- a/packages/modules/cart/src/scripts/seed.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { Modules } from "@medusajs/modules-sdk" -import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types" -import { DALUtils, ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as CartModels from "@models" -import { EOL } from "os" -import { resolve } from "path" - -export async function run({ - options, - logger, - path, -}: Partial< - Pick< - LoaderOptions, - "options" | "logger" - > -> & { - path: string -}) { - logger ??= console as unknown as Logger - - logger.info(`Loading seed data from ${path}...`) - - const { cartData } = await import( - resolve(process.cwd(), path) - ).catch((e) => { - logger?.error( - `Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: cartData.${EOL}${e}` - ) - throw e - }) - - const dbData = ModulesSdkUtils.loadDatabaseConfig( - Modules.CART, - options - )! - const entities = Object.values( - CartModels - ) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - const orm = await DALUtils.mikroOrmCreateConnection( - dbData, - entities, - pathToMigrations - ) - - const manager = orm.em.fork() - - try { - logger.info("Seeding cart data..") - - // TODO: implement cart seed data - // await createCarts(manager, cartsData) - } catch (e) { - logger.error( - `Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}` - ) - } - - await orm.close(true) -} diff --git a/packages/modules/cart/src/services/cart-module.ts b/packages/modules/cart/src/services/cart-module.ts index adee5a7b3d..3afc413245 100644 --- a/packages/modules/cart/src/services/cart-module.ts +++ b/packages/modules/cart/src/services/cart-module.ts @@ -54,6 +54,7 @@ type InjectedDependencies = { } const generateMethodForModels = { + Cart, Address, LineItem, LineItemAdjustment, @@ -63,39 +64,28 @@ const generateMethodForModels = { ShippingMethodTaxLine, } -export default class CartModuleService< - TCart extends Cart = Cart, - TAddress extends Address = Address, - TLineItem extends LineItem = LineItem, - TLineItemAdjustment extends LineItemAdjustment = LineItemAdjustment, - TLineItemTaxLine extends LineItemTaxLine = LineItemTaxLine, - TShippingMethodAdjustment extends ShippingMethodAdjustment = ShippingMethodAdjustment, - TShippingMethodTaxLine extends ShippingMethodTaxLine = ShippingMethodTaxLine, - TShippingMethod extends ShippingMethod = ShippingMethod - > - extends ModulesSdkUtils.MedusaService< - CartTypes.CartDTO, - { - Address: { dto: CartTypes.CartAddressDTO } - LineItem: { dto: CartTypes.CartLineItemDTO } - LineItemAdjustment: { dto: CartTypes.LineItemAdjustmentDTO } - LineItemTaxLine: { dto: CartTypes.LineItemTaxLineDTO } - ShippingMethod: { dto: CartTypes.CartShippingMethodDTO } - ShippingMethodAdjustment: { dto: CartTypes.ShippingMethodAdjustmentDTO } - ShippingMethodTaxLine: { dto: CartTypes.ShippingMethodTaxLineDTO } - } - >(Cart, generateMethodForModels, entityNameToLinkableKeysMap) +export default class CartModuleService + extends ModulesSdkUtils.MedusaService<{ + Cart: { dto: CartTypes.CartDTO } + Address: { dto: CartTypes.CartAddressDTO } + LineItem: { dto: CartTypes.CartLineItemDTO } + LineItemAdjustment: { dto: CartTypes.LineItemAdjustmentDTO } + LineItemTaxLine: { dto: CartTypes.LineItemTaxLineDTO } + ShippingMethod: { dto: CartTypes.CartShippingMethodDTO } + ShippingMethodAdjustment: { dto: CartTypes.ShippingMethodAdjustmentDTO } + ShippingMethodTaxLine: { dto: CartTypes.ShippingMethodTaxLineDTO } + }>(generateMethodForModels, entityNameToLinkableKeysMap) implements ICartModuleService { protected baseRepository_: DAL.RepositoryService - protected cartService_: ModulesSdkTypes.IMedusaInternalService - protected addressService_: ModulesSdkTypes.IMedusaInternalService - protected lineItemService_: ModulesSdkTypes.IMedusaInternalService - protected shippingMethodAdjustmentService_: ModulesSdkTypes.IMedusaInternalService - protected shippingMethodService_: ModulesSdkTypes.IMedusaInternalService - protected lineItemAdjustmentService_: ModulesSdkTypes.IMedusaInternalService - protected lineItemTaxLineService_: ModulesSdkTypes.IMedusaInternalService - protected shippingMethodTaxLineService_: ModulesSdkTypes.IMedusaInternalService + protected cartService_: ModulesSdkTypes.IMedusaInternalService + protected addressService_: ModulesSdkTypes.IMedusaInternalService
+ protected lineItemService_: ModulesSdkTypes.IMedusaInternalService + protected shippingMethodAdjustmentService_: ModulesSdkTypes.IMedusaInternalService + protected shippingMethodService_: ModulesSdkTypes.IMedusaInternalService + protected lineItemAdjustmentService_: ModulesSdkTypes.IMedusaInternalService + protected lineItemTaxLineService_: ModulesSdkTypes.IMedusaInternalService + protected shippingMethodTaxLineService_: ModulesSdkTypes.IMedusaInternalService constructor( { @@ -189,7 +179,8 @@ export default class CartModuleService< }) } - async retrieve( + // @ts-expect-error + async retrieveCart( id: string, config?: FindConfig | undefined, sharedContext?: Context | undefined @@ -197,7 +188,7 @@ export default class CartModuleService< config ??= {} const includeTotals = this.shouldIncludeTotals(config) - const cart = await super.retrieve(id, config, sharedContext) + const cart = await super.retrieveCart(id, config, sharedContext) if (includeTotals) { createRawPropertiesFromBigNumber(decorateCartTotals(cart)) @@ -206,7 +197,8 @@ export default class CartModuleService< return cart } - async list( + // @ts-expect-error + async listCarts( filters?: any, config?: FindConfig | undefined, sharedContext?: Context | undefined @@ -214,7 +206,7 @@ export default class CartModuleService< config ??= {} const includeTotals = this.shouldIncludeTotals(config) - const carts = await super.list(filters, config, sharedContext) + const carts = await super.listCarts(filters, config, sharedContext) if (includeTotals) { carts.forEach((cart) => { @@ -225,7 +217,8 @@ export default class CartModuleService< return carts } - async listAndCount( + // @ts-expect-error + async listAndCountCarts( filters?: any, config?: FindConfig | undefined, sharedContext?: Context | undefined @@ -233,7 +226,7 @@ export default class CartModuleService< config ??= {} const includeTotals = this.shouldIncludeTotals(config) - const [carts, count] = await super.listAndCount( + const [carts, count] = await super.listAndCountCarts( filters, config, sharedContext @@ -248,26 +241,27 @@ export default class CartModuleService< return [carts, count] } - async create( + // @ts-expect-error + async createCarts( data: CartTypes.CreateCartDTO[], sharedContext?: Context ): Promise - async create( + async createCarts( data: CartTypes.CreateCartDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createCarts( data: CartTypes.CreateCartDTO[] | CartTypes.CreateCartDTO, @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const carts = await this.create_(input, sharedContext) + const carts = await this.createCarts_(input, sharedContext) - const result = await this.list( + const result = await this.listCarts( { id: carts.map((p) => p!.id) }, { relations: ["shipping_address", "billing_address"], @@ -281,7 +275,7 @@ export default class CartModuleService< } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createCarts_( data: CartTypes.CreateCartDTO[], @MedusaContext() sharedContext: Context = {} ) { @@ -311,20 +305,23 @@ export default class CartModuleService< return createdCarts } - async update(data: CartTypes.UpdateCartDTO[]): Promise - async update( + // @ts-expect-error + async updateCarts( + data: CartTypes.UpdateCartDTO[] + ): Promise + async updateCarts( cartId: string, data: CartTypes.UpdateCartDataDTO, sharedContext?: Context ): Promise - async update( + async updateCarts( selector: Partial, data: CartTypes.UpdateCartDataDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async update( + async updateCarts( dataOrIdOrSelector: | CartTypes.UpdateCartDTO[] | string @@ -332,7 +329,11 @@ export default class CartModuleService< data?: CartTypes.UpdateCartDataDTO, @MedusaContext() sharedContext: Context = {} ): Promise { - const result = await this.update_(dataOrIdOrSelector, data, sharedContext) + const result = await this.updateCarts_( + dataOrIdOrSelector, + data, + sharedContext + ) const serializedResult = await this.baseRepository_.serialize< CartTypes.CartDTO[] @@ -344,7 +345,7 @@ export default class CartModuleService< } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updateCarts_( dataOrIdOrSelector: | CartTypes.UpdateCartDTO[] | string @@ -428,7 +429,11 @@ export default class CartModuleService< items: CartTypes.CreateLineItemDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { - const cart = await this.retrieve(cartId, { select: ["id"] }, sharedContext) + const cart = await this.retrieveCart( + cartId, + { select: ["id"] }, + sharedContext + ) const toUpdate: CreateLineItemDTO[] = items.map((item) => { return { @@ -666,7 +671,11 @@ export default class CartModuleService< data: CartTypes.CreateShippingMethodForSingleCartDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { - const cart = await this.retrieve(cartId, { select: ["id"] }, sharedContext) + const cart = await this.retrieveCart( + cartId, + { select: ["id"] }, + sharedContext + ) const methods = data.map((method) => { return { @@ -712,7 +721,7 @@ export default class CartModuleService< ): Promise { let addedAdjustments: LineItemAdjustment[] = [] if (isString(cartIdOrData)) { - const cart = await this.retrieve( + const cart = await this.retrieveCart( cartIdOrData, { select: ["id"], relations: ["items"] }, sharedContext @@ -758,7 +767,7 @@ export default class CartModuleService< )[], @MedusaContext() sharedContext: Context = {} ): Promise { - const cart = await this.retrieve( + const cart = await this.retrieveCart( cartId, { select: ["id"], relations: ["items.adjustments"] }, sharedContext @@ -813,7 +822,7 @@ export default class CartModuleService< )[], @MedusaContext() sharedContext: Context = {} ): Promise { - const cart = await this.retrieve( + const cart = await this.retrieveCart( cartId, { select: ["id"], relations: ["shipping_methods.adjustments"] }, sharedContext @@ -887,7 +896,7 @@ export default class CartModuleService< > { let addedAdjustments: ShippingMethodAdjustment[] = [] if (isString(cartIdOrData)) { - const cart = await this.retrieve( + const cart = await this.retrieveCart( cartIdOrData, { select: ["id"], relations: ["shipping_methods"] }, sharedContext @@ -961,7 +970,7 @@ export default class CartModuleService< let addedTaxLines: LineItemTaxLine[] if (isString(cartIdOrData)) { // existence check - await this.retrieve(cartIdOrData, { select: ["id"] }, sharedContext) + await this.retrieveCart(cartIdOrData, { select: ["id"] }, sharedContext) const lines = Array.isArray(taxLines) ? taxLines : [taxLines] @@ -1000,7 +1009,7 @@ export default class CartModuleService< )[], @MedusaContext() sharedContext: Context = {} ): Promise { - const cart = await this.retrieve( + const cart = await this.retrieveCart( cartId, { select: ["id"], relations: ["items.tax_lines"] }, sharedContext @@ -1077,7 +1086,7 @@ export default class CartModuleService< let addedTaxLines: ShippingMethodTaxLine[] if (isString(cartIdOrData)) { // existence check - await this.retrieve(cartIdOrData, { select: ["id"] }, sharedContext) + await this.retrieveCart(cartIdOrData, { select: ["id"] }, sharedContext) const lines = Array.isArray(taxLines) ? taxLines : [taxLines] @@ -1116,7 +1125,7 @@ export default class CartModuleService< )[], @MedusaContext() sharedContext: Context = {} ): Promise { - const cart = await this.retrieve( + const cart = await this.retrieveCart( cartId, { select: ["id"], relations: ["shipping_methods.tax_lines"] }, sharedContext diff --git a/packages/modules/currency/integration-tests/__tests__/currency-module-service.spec.ts b/packages/modules/currency/integration-tests/__tests__/currency-module-service.spec.ts index f2bf6bc796..060ab2e2c9 100644 --- a/packages/modules/currency/integration-tests/__tests__/currency-module-service.spec.ts +++ b/packages/modules/currency/integration-tests/__tests__/currency-module-service.spec.ts @@ -1,19 +1,19 @@ import { Modules } from "@medusajs/modules-sdk" import { ICurrencyModuleService } from "@medusajs/types" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(100000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.CURRENCY, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Currency Module Service", () => { describe("list", () => { it("list currencies", async () => { - const currenciesResult = await service.list({}, { take: null }) + const currenciesResult = await service.listCurrencies( + {}, + { take: null } + ) expect(currenciesResult).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -31,7 +31,7 @@ moduleIntegrationTestRunner({ }) it("list currencies by code", async () => { - const currenciesResult = await service.list( + const currenciesResult = await service.listCurrencies( { code: ["usd"] }, { take: null } ) @@ -45,7 +45,7 @@ moduleIntegrationTestRunner({ }) it("list currencies by code regardless of case-sensitivity", async () => { - const currenciesResult = await service.list( + const currenciesResult = await service.listCurrencies( { code: ["Usd"] }, { take: null } ) @@ -59,12 +59,10 @@ moduleIntegrationTestRunner({ }) }) - describe("listAndCount", () => { + describe("listAndCountCurrenciesCurrencies", () => { it("should return currencies and count", async () => { - const [currenciesResult, count] = await service.listAndCount( - {}, - { take: null } - ) + const [currenciesResult, count] = + await service.listAndCountCurrencies({}, { take: null }) expect(count).toEqual(120) expect(currenciesResult).toEqual( @@ -82,12 +80,13 @@ moduleIntegrationTestRunner({ }) it("should return currencies and count when filtered", async () => { - const [currenciesResult, count] = await service.listAndCount( - { - code: ["usd"], - }, - { take: null } - ) + const [currenciesResult, count] = + await service.listAndCountCurrencies( + { + code: ["usd"], + }, + { take: null } + ) expect(count).toEqual(1) expect(currenciesResult).toEqual([ @@ -99,10 +98,8 @@ moduleIntegrationTestRunner({ }) it("should return currencies and count when using skip and take", async () => { - const [currenciesResult, count] = await service.listAndCount( - {}, - { skip: 5, take: 1 } - ) + const [currenciesResult, count] = + await service.listAndCountCurrencies({}, { skip: 5, take: 1 }) expect(count).toEqual(120) expect(currenciesResult).toEqual([ @@ -114,13 +111,14 @@ moduleIntegrationTestRunner({ }) it("should return requested fields", async () => { - const [currenciesResult, count] = await service.listAndCount( - {}, - { - take: 1, - select: ["code", "rounding"], - } - ) + const [currenciesResult, count] = + await service.listAndCountCurrencies( + {}, + { + take: 1, + select: ["code", "rounding"], + } + ) const serialized = JSON.parse(JSON.stringify(currenciesResult)) @@ -140,7 +138,7 @@ moduleIntegrationTestRunner({ const name = "US Dollar" it("should return currency for the given code", async () => { - const currency = await service.retrieve(code) + const currency = await service.retrieveCurrency(code) expect(currency).toEqual( expect.objectContaining({ @@ -150,7 +148,7 @@ moduleIntegrationTestRunner({ }) it("should return currency for the given code in a case-insensitive manner", async () => { - const currency = await service.retrieve(code.toUpperCase()) + const currency = await service.retrieveCurrency(code.toUpperCase()) expect(currency).toEqual( expect.objectContaining({ @@ -163,7 +161,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve("does-not-exist") + await service.retrieveCurrency("does-not-exist") } catch (e) { error = e } @@ -177,7 +175,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve(undefined as unknown as string) + await service.retrieveCurrency(undefined as unknown as string) } catch (e) { error = e } @@ -186,7 +184,7 @@ moduleIntegrationTestRunner({ }) it("should return currency based on config select param", async () => { - const currency = await service.retrieve(code, { + const currency = await service.retrieveCurrency(code, { select: ["code", "name"], }) diff --git a/packages/modules/currency/package.json b/packages/modules/currency/package.json index ed74a95c12..b3eafbad19 100644 --- a/packages/modules/currency/package.json +++ b/packages/modules/currency/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-currency-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/currency/src/index.ts b/packages/modules/currency/src/index.ts index 5dc2ece165..0e087b98b6 100644 --- a/packages/modules/currency/src/index.ts +++ b/packages/modules/currency/src/index.ts @@ -1,7 +1,13 @@ -import { moduleDefinition } from "./module-definition" +import { CurrencyModuleService } from "@services" +import initialDataLoader from "./loaders/initial-data" +import { ModuleExports } from "@medusajs/types" -export * from "./types" -export * from "./models" -export * from "./services" +const service = CurrencyModuleService +const loaders = [initialDataLoader] + +export const moduleDefinition: ModuleExports = { + service, + loaders, +} export default moduleDefinition diff --git a/packages/modules/currency/src/joiner-config.ts b/packages/modules/currency/src/joiner-config.ts index 0dff80b695..a7c930d48a 100644 --- a/packages/modules/currency/src/joiner-config.ts +++ b/packages/modules/currency/src/joiner-config.ts @@ -1,33 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import Currency from "./models/currency" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys: Record = { - code: Currency.name, - currency_code: Currency.name, - default_currency_code: Currency.name, -} +export const joinerConfig = defineJoinerConfig(Modules.CURRENCY) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.CURRENCY, - primaryKeys: ["code"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["currency", "currencies"], - args: { entity: Currency.name }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/currency/src/module-definition.ts b/packages/modules/currency/src/module-definition.ts deleted file mode 100644 index 1c1e5469a3..0000000000 --- a/packages/modules/currency/src/module-definition.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { CurrencyModuleService } from "@services" -import initialDataLoader from "./loaders/initial-data" - -const service = CurrencyModuleService -const loaders = [initialDataLoader] - -export const moduleDefinition: ModuleExports = { - service, - loaders, -} diff --git a/packages/modules/currency/src/repositories/index.ts b/packages/modules/currency/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/currency/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/currency/src/scripts/bin/run-seed.ts b/packages/modules/currency/src/scripts/bin/run-seed.ts deleted file mode 100644 index caf653ed15..0000000000 --- a/packages/modules/currency/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node - -import { ModulesSdkUtils } from "@medusajs/utils" -import { Modules } from "@medusajs/modules-sdk" -import * as Models from "@models" -import { EOL } from "os" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-currency-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.CURRENCY, - models: Models, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - // TODO: Add seed logic - }, - }) - await run({ path }) -})() diff --git a/packages/modules/currency/src/services/currency-module-service.ts b/packages/modules/currency/src/services/currency-module-service.ts index 985adfedb7..19f931f4d2 100644 --- a/packages/modules/currency/src/services/currency-module-service.ts +++ b/packages/modules/currency/src/services/currency-module-service.ts @@ -10,29 +10,24 @@ import { ModuleJoinerConfig, ModulesSdkTypes, } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" import { Currency } from "@models" import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" - -const generateMethodForModels = {} +import { MedusaService } from "@medusajs/utils" type InjectedDependencies = { baseRepository: DAL.RepositoryService currencyService: ModulesSdkTypes.IMedusaInternalService } -export default class CurrencyModuleService - extends ModulesSdkUtils.MedusaService< - CurrencyTypes.CurrencyDTO, - { - Currency: { dto: CurrencyTypes.CurrencyDTO } - } - >(Currency, generateMethodForModels, entityNameToLinkableKeysMap) +export default class CurrencyModuleService + extends MedusaService<{ + Currency: { dto: CurrencyTypes.CurrencyDTO } + }>({ Currency }, entityNameToLinkableKeysMap) implements ICurrencyModuleService { protected baseRepository_: DAL.RepositoryService - protected readonly currencyService_: ModulesSdkTypes.IMedusaInternalService + protected readonly currencyService_: ModulesSdkTypes.IMedusaInternalService constructor( { baseRepository, currencyService }: InjectedDependencies, @@ -48,36 +43,39 @@ export default class CurrencyModuleService return joinerConfig } - retrieve( + // @ts-expect-error + async retrieveCurrency( code: string, config?: FindConfig, sharedContext?: Context ): Promise { - return this.currencyService_.retrieve( - code?.toLowerCase(), + return await super.retrieveCurrency( + CurrencyModuleService.normalizeFilters({ code: [code] })!.code![0], config, sharedContext ) } - list( + // @ts-expect-error + async listCurrencies( filters?: FilterableCurrencyProps, config?: FindConfig, sharedContext?: Context ): Promise { - return this.currencyService_.list( + return await super.listCurrencies( CurrencyModuleService.normalizeFilters(filters), config, sharedContext ) } - listAndCount( + // @ts-expect-error + async listAndCountCurrencies( filters?: FilterableCurrencyProps, config?: FindConfig, sharedContext?: Context ): Promise<[CurrencyTypes.CurrencyDTO[], number]> { - return this.currencyService_.listAndCount( + return await super.listAndCountCurrencies( CurrencyModuleService.normalizeFilters(filters), config, sharedContext diff --git a/packages/modules/customer/integration-tests/__tests__/services/customer-module/index.spec.ts b/packages/modules/customer/integration-tests/__tests__/services/customer-module/index.spec.ts index 7201cce550..2e0c2c6475 100644 --- a/packages/modules/customer/integration-tests/__tests__/services/customer-module/index.spec.ts +++ b/packages/modules/customer/integration-tests/__tests__/services/customer-module/index.spec.ts @@ -1,15 +1,12 @@ import { ICustomerModuleService } from "@medusajs/types" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { Modules } from "@medusajs/modules-sdk" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.CUSTOMER, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Customer Module Service", () => { describe("create", () => { it("should create a single customer", async () => { @@ -22,7 +19,7 @@ moduleIntegrationTestRunner({ created_by: "admin", metadata: { membership: "gold" }, } - const customer = await service.create(customerData) + const customer = await service.createCustomers(customerData) expect(customer).toEqual( expect.objectContaining({ @@ -52,7 +49,7 @@ moduleIntegrationTestRunner({ ...customerData, has_account: true, } - const [customer, customer2] = await service.create([ + const [customer, customer2] = await service.createCustomers([ customerData, customerData2, ]) @@ -96,7 +93,7 @@ moduleIntegrationTestRunner({ } const err = await service - .create([customerData, customerData]) + .createCustomers([customerData, customerData]) .catch((err) => err) expect(err.message).toBe( @@ -117,7 +114,7 @@ moduleIntegrationTestRunner({ } const err = await service - .create([customerData, customerData]) + .createCustomers([customerData, customerData]) .catch((err) => err) expect(err.message).toBe( @@ -144,7 +141,7 @@ moduleIntegrationTestRunner({ }, ], } - const customer = await service.create(customerData) + const customer = await service.createCustomers(customerData) const [address] = await service.listAddresses({ customer_id: customer.id, @@ -192,7 +189,7 @@ moduleIntegrationTestRunner({ }, ], } - await expect(service.create(customerData)).rejects.toThrow( + await expect(service.createCustomers(customerData)).rejects.toThrow( /Customer address with customer_id: .*? already exists./ ) }) @@ -216,7 +213,7 @@ moduleIntegrationTestRunner({ metadata: { membership: "silver" }, }, ] - const customer = await service.create(customersData) + const customer = await service.createCustomers(customersData) expect(customer).toEqual( expect.arrayContaining([ @@ -245,7 +242,7 @@ moduleIntegrationTestRunner({ describe("createCustomerGroup", () => { it("should create a single customer group", async () => { - const group = await service.createCustomerGroup({ + const group = await service.createCustomerGroups({ name: "VIP Customers", metadata: { priority: "high" }, created_by: "admin", @@ -262,7 +259,7 @@ moduleIntegrationTestRunner({ }) it("should create multiple customer groups", async () => { - const groups = await service.createCustomerGroup([ + const groups = await service.createCustomerGroups([ { name: "VIP Customers", metadata: { priority: "high" }, @@ -296,7 +293,7 @@ moduleIntegrationTestRunner({ describe("list", () => { it("should list all customers when no filters are applied", async () => { - await service.create([ + await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -309,7 +306,7 @@ moduleIntegrationTestRunner({ }, ]) - const customers = await service.list() + const customers = await service.listCustomers() expect(customers.length).toBeGreaterThanOrEqual(2) expect(customers).toEqual( @@ -329,7 +326,7 @@ moduleIntegrationTestRunner({ }) it("should list customers filtered by a specific email", async () => { - await service.create([ + await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -343,7 +340,7 @@ moduleIntegrationTestRunner({ ]) const filter = { email: "unique.email@example.com" } - const customers = await service.list(filter) + const customers = await service.listCustomers(filter) expect(customers.length).toBe(1) expect(customers[0]).toEqual( @@ -356,9 +353,9 @@ moduleIntegrationTestRunner({ }) it("should list customers by a specific customer group", async () => { - const vipGroup = await service.createCustomerGroup({ name: "VIP" }) + const vipGroup = await service.createCustomerGroups({ name: "VIP" }) - const [john] = await service.create([ + const [john] = await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -377,7 +374,7 @@ moduleIntegrationTestRunner({ }) const filter = { groups: vipGroup.id } - const customers = await service.list(filter) + const customers = await service.listCustomers(filter) expect(customers).toEqual( expect.arrayContaining([ @@ -402,14 +399,14 @@ moduleIntegrationTestRunner({ describe("addCustomerToGroup", () => { it("should add a single customer to a customer group", async () => { - const [customer] = await service.create([ + const [customer] = await service.createCustomers([ { first_name: "John", last_name: "Doe", email: "john.doe@example.com", }, ]) - const [group] = await service.createCustomerGroup([{ name: "VIP" }]) + const [group] = await service.createCustomerGroups([{ name: "VIP" }]) const result = await service.addCustomerToGroup({ customer_id: customer.id, @@ -421,7 +418,7 @@ moduleIntegrationTestRunner({ ) // Additional validation (optional): retrieve the customer and check if the group is assigned - const updatedCustomer = await service.retrieve(customer.id, { + const updatedCustomer = await service.retrieveCustomer(customer.id, { relations: ["groups"], }) expect(updatedCustomer.groups).toContainEqual( @@ -430,7 +427,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple customers to customer groups", async () => { - const customers = await service.create([ + const customers = await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -442,7 +439,7 @@ moduleIntegrationTestRunner({ email: "jane.smith@example.com", }, ]) - const groups = await service.createCustomerGroup([ + const groups = await service.createCustomerGroups([ { name: "VIP" }, { name: "Regular" }, ]) @@ -462,9 +459,12 @@ moduleIntegrationTestRunner({ ) for (const customer of customers) { - const updatedCustomer = await service.retrieve(customer.id, { - relations: ["groups"], - }) + const updatedCustomer = await service.retrieveCustomer( + customer.id, + { + relations: ["groups"], + } + ) expect(updatedCustomer.groups).toContainEqual( expect.objectContaining({ id: groups[customers.indexOf(customer) % groups.length].id, @@ -476,7 +476,7 @@ moduleIntegrationTestRunner({ describe("update", () => { it("should update a single customer", async () => { - const [customer] = await service.create([ + const [customer] = await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -485,7 +485,10 @@ moduleIntegrationTestRunner({ ]) const updateData = { first_name: "Jonathan" } - const updatedCustomer = await service.update(customer.id, updateData) + const updatedCustomer = await service.updateCustomers( + customer.id, + updateData + ) expect(updatedCustomer).toEqual( expect.objectContaining({ id: customer.id, first_name: "Jonathan" }) @@ -493,7 +496,7 @@ moduleIntegrationTestRunner({ }) it("should update multiple customers by IDs", async () => { - const customers = await service.create([ + const customers = await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -508,7 +511,10 @@ moduleIntegrationTestRunner({ const updateData = { last_name: "Updated" } const customerIds = customers.map((customer) => customer.id) - const updatedCustomers = await service.update(customerIds, updateData) + const updatedCustomers = await service.updateCustomers( + customerIds, + updateData + ) updatedCustomers.forEach((updatedCustomer) => { expect(updatedCustomer).toEqual( @@ -518,7 +524,7 @@ moduleIntegrationTestRunner({ }) it("should update customers using a selector", async () => { - await service.create([ + await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -533,7 +539,10 @@ moduleIntegrationTestRunner({ const selector = { last_name: "Doe" } const updateData = { last_name: "Updated" } - const updatedCustomers = await service.update(selector, updateData) + const updatedCustomers = await service.updateCustomers( + selector, + updateData + ) updatedCustomers.forEach((updatedCustomer) => { expect(updatedCustomer).toEqual( @@ -545,7 +554,7 @@ moduleIntegrationTestRunner({ describe("delete", () => { it("should delete a single customer", async () => { - const [customer] = await service.create([ + const [customer] = await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -553,15 +562,15 @@ moduleIntegrationTestRunner({ }, ]) - await service.delete(customer.id) + await service.deleteCustomers(customer.id) - await expect(service.retrieve(customer.id)).rejects.toThrow( + await expect(service.retrieveCustomer(customer.id)).rejects.toThrow( `Customer with id: ${customer.id} was not found` ) }) it("should delete multiple customers by IDs", async () => { - const customers = await service.create([ + const customers = await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -575,17 +584,17 @@ moduleIntegrationTestRunner({ ]) const customerIds = customers.map((customer) => customer.id) - await service.delete(customerIds) + await service.deleteCustomers(customerIds) for (const customer of customers) { - await expect(service.retrieve(customer.id)).rejects.toThrow( + await expect(service.retrieveCustomer(customer.id)).rejects.toThrow( `Customer with id: ${customer.id} was not found` ) } }) it("should delete customers using a selector", async () => { - await service.create([ + await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -599,19 +608,21 @@ moduleIntegrationTestRunner({ ]) const selector = { last_name: "Doe" } - await service.delete(selector) + await service.deleteCustomers(selector) - const remainingCustomers = await service.list({ last_name: "Doe" }) + const remainingCustomers = await service.listCustomers({ + last_name: "Doe", + }) expect(remainingCustomers.length).toBe(0) }) it("should cascade address relationship when deleting customer", async () => { // Creating a customer and an address - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - await service.addAddresses({ + await service.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -620,12 +631,15 @@ moduleIntegrationTestRunner({ }) // verify that the address was added - const customerWithAddress = await service.retrieve(customer.id, { - relations: ["addresses"], - }) + const customerWithAddress = await service.retrieveCustomer( + customer.id, + { + relations: ["addresses"], + } + ) expect(customerWithAddress.addresses?.length).toBe(1) - await service.delete(customer.id) + await service.deleteCustomers(customer.id) const res = await service.listAddresses({ customer_id: customer.id, @@ -635,11 +649,11 @@ moduleIntegrationTestRunner({ it("should cascade relationship when deleting customer", async () => { // Creating a customer and a group - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const group = await service.createCustomerGroup({ name: "VIP" }) + const group = await service.createCustomerGroups({ name: "VIP" }) // Adding the customer to the groups await service.addCustomerToGroup({ @@ -647,7 +661,7 @@ moduleIntegrationTestRunner({ customer_group_id: group.id, }) - await service.delete(customer.id) + await service.deleteCustomers(customer.id) const res = await service.listCustomerGroupCustomers({ customer_id: customer.id, @@ -659,7 +673,7 @@ moduleIntegrationTestRunner({ describe("deleteCustomerGroup", () => { it("should delete a single customer group", async () => { - const [group] = await service.createCustomerGroup([{ name: "VIP" }]) + const [group] = await service.createCustomerGroups([{ name: "VIP" }]) await service.deleteCustomerGroups(group.id) await expect( @@ -670,7 +684,7 @@ moduleIntegrationTestRunner({ }) it("should delete multiple customer groups by IDs", async () => { - const groups = await service.createCustomerGroup([ + const groups = await service.createCustomerGroups([ { name: "VIP" }, { name: "Regular" }, ]) @@ -688,7 +702,7 @@ moduleIntegrationTestRunner({ }) it("should delete customer groups using a selector", async () => { - await service.createCustomerGroup([ + await service.createCustomerGroups([ { name: "VIP" }, { name: "Regular" }, ]) @@ -704,11 +718,11 @@ moduleIntegrationTestRunner({ it("should cascade relationship when deleting customer group", async () => { // Creating a customer and a group - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const group = await service.createCustomerGroup({ name: "VIP" }) + const group = await service.createCustomerGroups({ name: "VIP" }) // Adding the customer to the groups await service.addCustomerToGroup({ @@ -728,18 +742,18 @@ moduleIntegrationTestRunner({ describe("addAddresses", () => { it("should add a single address to a customer", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const address = await service.addAddresses({ + const address = await service.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", postal_code: "10001", country_code: "US", }) - const [customerWithAddress] = await service.list( + const [customerWithAddress] = await service.listCustomers( { id: customer.id }, { relations: ["addresses"] } ) @@ -750,11 +764,11 @@ moduleIntegrationTestRunner({ }) it("should add multiple addresses to a customer", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const addresses = await service.addAddresses([ + const addresses = await service.createAddresses([ { customer_id: customer.id, first_name: "John", @@ -770,7 +784,7 @@ moduleIntegrationTestRunner({ country_code: "US", }, ]) - const [customerWithAddresses] = await service.list( + const [customerWithAddresses] = await service.listCustomers( { id: customer.id }, { relations: ["addresses"] } ) @@ -784,11 +798,11 @@ moduleIntegrationTestRunner({ }) it("should only be possible to add one default shipping address per customer", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - await service.addAddresses({ + await service.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -796,7 +810,7 @@ moduleIntegrationTestRunner({ country_code: "US", is_default_shipping: true, }) - await service.addAddresses({ + await service.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -806,7 +820,7 @@ moduleIntegrationTestRunner({ }) await expect( - service.addAddresses({ + service.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -820,11 +834,11 @@ moduleIntegrationTestRunner({ }) it("should only be possible to add one default billing address per customer", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - await service.addAddresses({ + await service.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -832,7 +846,7 @@ moduleIntegrationTestRunner({ country_code: "US", is_default_billing: true, }) - await service.addAddresses({ + await service.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -842,7 +856,7 @@ moduleIntegrationTestRunner({ }) await expect( - service.addAddresses({ + service.createAddresses({ customer_id: customer.id, first_name: "John", last_name: "Doe", @@ -858,11 +872,11 @@ moduleIntegrationTestRunner({ describe("updateAddresses", () => { it("should update a single address", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const address = await service.addAddresses({ + const address = await service.createAddresses({ customer_id: customer.id, address_name: "Home", address_1: "123 Main St", @@ -873,7 +887,7 @@ moduleIntegrationTestRunner({ address_1: "456 Main St", }) - const updatedCustomer = await service.retrieve(customer.id, { + const updatedCustomer = await service.retrieveCustomer(customer.id, { select: ["id"], relations: ["addresses"], }) @@ -888,16 +902,16 @@ moduleIntegrationTestRunner({ }) it("should update multiple addresses", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const address1 = await service.addAddresses({ + const address1 = await service.createAddresses({ customer_id: customer.id, address_name: "Home", address_1: "123 Main St", }) - const address2 = await service.addAddresses({ + const address2 = await service.createAddresses({ customer_id: customer.id, address_name: "Work", address_1: "456 Main St", @@ -910,7 +924,7 @@ moduleIntegrationTestRunner({ } ) - const updatedCustomer = await service.retrieve(customer.id, { + const updatedCustomer = await service.retrieveCustomer(customer.id, { select: ["id"], relations: ["addresses"], }) @@ -930,11 +944,11 @@ moduleIntegrationTestRunner({ }) it("should update multiple addresses with ids", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const [address1, address2] = await service.addAddresses([ + const [address1, address2] = await service.createAddresses([ { customer_id: customer.id, address_name: "Home", @@ -951,7 +965,7 @@ moduleIntegrationTestRunner({ address_name: "Under Construction", }) - const updatedCustomer = await service.retrieve(customer.id, { + const updatedCustomer = await service.retrieveCustomer(customer.id, { select: ["id"], relations: ["addresses"], }) @@ -971,7 +985,7 @@ moduleIntegrationTestRunner({ }) it("should fail when updating address to a default shipping address when one already exists", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", addresses: [ @@ -982,7 +996,7 @@ moduleIntegrationTestRunner({ }, ], }) - const address = await service.addAddresses({ + const address = await service.createAddresses({ customer_id: customer.id, address_name: "Work", address_1: "456 Main St", @@ -998,11 +1012,11 @@ moduleIntegrationTestRunner({ describe("listAddresses", () => { it("should list all addresses for a customer", async () => { - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const [address1, address2] = await service.addAddresses([ + const [address1, address2] = await service.createAddresses([ { customer_id: customer.id, address_name: "Home", @@ -1040,14 +1054,14 @@ moduleIntegrationTestRunner({ describe("removeCustomerFromGroup", () => { it("should remove a single customer from a group", async () => { // Creating a customer and a group - const [customer] = await service.create([ + const [customer] = await service.createCustomers([ { first_name: "John", last_name: "Doe", email: "john.doe@example.com", }, ]) - const [group] = await service.createCustomerGroup([{ name: "VIP" }]) + const [group] = await service.createCustomerGroups([{ name: "VIP" }]) // Adding the customer to the group await service.addCustomerToGroup({ @@ -1055,7 +1069,7 @@ moduleIntegrationTestRunner({ customer_group_id: group.id, }) - const [customerInGroup] = await service.list( + const [customerInGroup] = await service.listCustomers( { id: customer.id }, { relations: ["groups"] } ) @@ -1069,7 +1083,7 @@ moduleIntegrationTestRunner({ customer_group_id: group.id, }) - const [updatedCustomer] = await service.list( + const [updatedCustomer] = await service.listCustomers( { id: customer.id }, { relations: ["groups"] } ) @@ -1078,7 +1092,7 @@ moduleIntegrationTestRunner({ it("should remove multiple customers from groups", async () => { // Creating multiple customers and groups - const customers = await service.create([ + const customers = await service.createCustomers([ { first_name: "John", last_name: "Doe", @@ -1090,7 +1104,7 @@ moduleIntegrationTestRunner({ email: "jane.smith@example.com", }, ]) - const groups = await service.createCustomerGroup([ + const groups = await service.createCustomerGroups([ { name: "VIP" }, { name: "Regular" }, ]) @@ -1111,7 +1125,7 @@ moduleIntegrationTestRunner({ // Verification for each customer for (const pair of pairsToRemove) { - const [updatedCustomer] = await service.list( + const [updatedCustomer] = await service.listCustomers( { id: pair.customer_id }, { relations: ["groups"] } ) @@ -1124,15 +1138,15 @@ moduleIntegrationTestRunner({ describe("softDelete", () => { it("should soft delete a single customer", async () => { - const [customer] = await service.create([ + const [customer] = await service.createCustomers([ { first_name: "John", last_name: "Doe" }, ]) - await service.softDelete([customer.id]) + await service.softDeleteCustomers([customer.id]) - const res = await service.list({ id: customer.id }) + const res = await service.listCustomers({ id: customer.id }) expect(res.length).toBe(0) - const deletedCustomer = await service.retrieve(customer.id, { + const deletedCustomer = await service.retrieveCustomer(customer.id, { withDeleted: true, }) @@ -1140,17 +1154,17 @@ moduleIntegrationTestRunner({ }) it("should soft delete multiple customers", async () => { - const customers = await service.create([ + const customers = await service.createCustomers([ { first_name: "John", last_name: "Doe" }, { first_name: "Jane", last_name: "Smith" }, ]) const customerIds = customers.map((customer) => customer.id) - await service.softDelete(customerIds) + await service.softDeleteCustomers(customerIds) - const res = await service.list({ id: customerIds }) + const res = await service.listCustomers({ id: customerIds }) expect(res.length).toBe(0) - const deletedCustomers = await service.list( + const deletedCustomers = await service.listCustomers( { id: customerIds }, { withDeleted: true } ) @@ -1159,11 +1173,11 @@ moduleIntegrationTestRunner({ it("should remove customer in group relation", async () => { // Creating a customer and a group - const customer = await service.create({ + const customer = await service.createCustomers({ first_name: "John", last_name: "Doe", }) - const group = await service.createCustomerGroup({ name: "VIP" }) + const group = await service.createCustomerGroups({ name: "VIP" }) // Adding the customer to the group await service.addCustomerToGroup({ @@ -1171,7 +1185,7 @@ moduleIntegrationTestRunner({ customer_group_id: group.id, }) - await service.softDelete([customer.id]) + await service.softDeleteCustomers([customer.id]) const resGroup = await service.retrieveCustomerGroup(group.id, { relations: ["customers"], @@ -1182,36 +1196,36 @@ moduleIntegrationTestRunner({ describe("restore", () => { it("should restore a single customer", async () => { - const [customer] = await service.create([ + const [customer] = await service.createCustomers([ { first_name: "John", last_name: "Doe" }, ]) - await service.softDelete([customer.id]) + await service.softDeleteCustomers([customer.id]) - const res = await service.list({ id: customer.id }) + const res = await service.listCustomers({ id: customer.id }) expect(res.length).toBe(0) - await service.restore([customer.id]) + await service.restoreCustomers([customer.id]) - const restoredCustomer = await service.retrieve(customer.id, { + const restoredCustomer = await service.retrieveCustomer(customer.id, { withDeleted: true, }) expect(restoredCustomer.deleted_at).toBeNull() }) it("should restore multiple customers", async () => { - const customers = await service.create([ + const customers = await service.createCustomers([ { first_name: "John", last_name: "Doe" }, { first_name: "Jane", last_name: "Smith" }, ]) const customerIds = customers.map((customer) => customer.id) - await service.softDelete(customerIds) + await service.softDeleteCustomers(customerIds) - const res = await service.list({ id: customerIds }) + const res = await service.listCustomers({ id: customerIds }) expect(res.length).toBe(0) - await service.restore(customerIds) + await service.restoreCustomers(customerIds) - const restoredCustomers = await service.list( + const restoredCustomers = await service.listCustomers( { id: customerIds }, { withDeleted: true } ) @@ -1221,7 +1235,7 @@ moduleIntegrationTestRunner({ describe("softDeleteCustomerGroup", () => { it("should soft delete a single customer group", async () => { - const [group] = await service.createCustomerGroup([{ name: "VIP" }]) + const [group] = await service.createCustomerGroups([{ name: "VIP" }]) await service.softDeleteCustomerGroups([group.id]) const res = await service.listCustomerGroups({ id: group.id }) @@ -1235,7 +1249,7 @@ moduleIntegrationTestRunner({ }) it("should soft delete multiple customer groups", async () => { - const groups = await service.createCustomerGroup([ + const groups = await service.createCustomerGroups([ { name: "VIP" }, { name: "Regular" }, ]) @@ -1255,7 +1269,7 @@ moduleIntegrationTestRunner({ describe("restoreCustomerGroup", () => { it("should restore a single customer group", async () => { - const [group] = await service.createCustomerGroup([{ name: "VIP" }]) + const [group] = await service.createCustomerGroups([{ name: "VIP" }]) await service.softDeleteCustomerGroups([group.id]) const res = await service.listCustomerGroups({ id: group.id }) @@ -1270,7 +1284,7 @@ moduleIntegrationTestRunner({ }) it("should restore multiple customer groups", async () => { - const groups = await service.createCustomerGroup([ + const groups = await service.createCustomerGroups([ { name: "VIP" }, { name: "Regular" }, ]) diff --git a/packages/modules/customer/package.json b/packages/modules/customer/package.json index 4f980274aa..b31e9a0df7 100644 --- a/packages/modules/customer/package.json +++ b/packages/modules/customer/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-customer-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/customer/src/index.ts b/packages/modules/customer/src/index.ts index dd414e1b19..4a9223e048 100644 --- a/packages/modules/customer/src/index.ts +++ b/packages/modules/customer/src/index.ts @@ -1,3 +1,7 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { CustomerModuleService } from "@services" +const moduleDefinition: ModuleExports = { + service: CustomerModuleService, +} export default moduleDefinition diff --git a/packages/modules/customer/src/joiner-config.ts b/packages/modules/customer/src/joiner-config.ts index c6c3cfb52d..a9ede100f2 100644 --- a/packages/modules/customer/src/joiner-config.ts +++ b/packages/modules/customer/src/joiner-config.ts @@ -1,49 +1,21 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import { Address, Customer, CustomerGroup } from "@models" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys = { - customer_id: Customer.name, - customer_group_id: CustomerGroup.name, - customer_address_id: Address.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.CUSTOMER, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, +export const joinerConfig = defineJoinerConfig(Modules.CUSTOMER, { alias: [ - { - name: ["customer", "customers"], - args: { - entity: Customer.name, - }, - }, - { - name: ["customer_group", "customer_groups"], - args: { - entity: CustomerGroup.name, - methodSuffix: "CustomerGroups", - }, - }, { name: ["customer_address", "customer_addresses"], args: { - entity: Address.name, + entity: "Address", methodSuffix: "Addresses", }, }, ], -} +}) + +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/customer/src/models/index.ts b/packages/modules/customer/src/models/index.ts index c2b6c076f9..09a25f763e 100644 --- a/packages/modules/customer/src/models/index.ts +++ b/packages/modules/customer/src/models/index.ts @@ -2,3 +2,4 @@ export { default as Address } from "./address" export { default as Customer } from "./customer" export { default as CustomerGroup } from "./customer-group" export { default as CustomerGroupCustomer } from "./customer-group-customer" + diff --git a/packages/modules/customer/src/module-definition.ts b/packages/modules/customer/src/module-definition.ts deleted file mode 100644 index 65563913a2..0000000000 --- a/packages/modules/customer/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { CustomerModuleService } from "@services" - -const service = CustomerModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/customer/src/scripts/bin/run-seed.ts b/packages/modules/customer/src/scripts/bin/run-seed.ts deleted file mode 100644 index 21f41d64b5..0000000000 --- a/packages/modules/customer/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env node - -import { EOL } from "os" -import { run } from "../seed" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-cart-seed ` - ) - } - - await run({ path }) -})() diff --git a/packages/modules/customer/src/scripts/seed.ts b/packages/modules/customer/src/scripts/seed.ts deleted file mode 100644 index 103e1bff4b..0000000000 --- a/packages/modules/customer/src/scripts/seed.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { Modules } from "@medusajs/modules-sdk" -import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types" -import { DALUtils, ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as CustomerModels from "@models" -import { EOL } from "os" -import { resolve } from "path" - -export async function run({ - options, - logger, - path, -}: Partial< - Pick< - LoaderOptions, - "options" | "logger" - > -> & { - path: string -}) { - logger ??= console as unknown as Logger - - logger.info(`Loading seed data from ${path}...`) - - const { customerData } = await import(resolve(process.cwd(), path)).catch( - (e) => { - logger?.error( - `Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: customerData.${EOL}${e}` - ) - throw e - } - ) - - const dbData = ModulesSdkUtils.loadDatabaseConfig(Modules.CUSTOMER, options)! - const entities = Object.values(CustomerModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - const orm = await DALUtils.mikroOrmCreateConnection( - dbData, - entities, - pathToMigrations - ) - - const manager = orm.em.fork() - - try { - logger.info("Seeding customer data..") - - // TODO: implement customer seed data - // await createCustomers(manager, customersData) - } catch (e) { - logger.error( - `Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}` - ) - } - - await orm.close(true) -} diff --git a/packages/modules/customer/src/services/customer-module.ts b/packages/modules/customer/src/services/customer-module.ts index 1934868547..70ef8e221f 100644 --- a/packages/modules/customer/src/services/customer-module.ts +++ b/packages/modules/customer/src/services/customer-module.ts @@ -1,6 +1,9 @@ import { Context, + CustomerAddressDTO, CustomerDTO, + CustomerGroupCustomerDTO, + CustomerGroupDTO, CustomerTypes, DAL, ICustomerModuleService, @@ -14,16 +17,16 @@ import { InjectTransactionManager, isString, MedusaContext, - ModulesSdkUtils, + MedusaService, } from "@medusajs/utils" -import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" +import { EntityManager } from "@mikro-orm/core" import { Address, Customer, CustomerGroup, CustomerGroupCustomer, } from "@models" -import { EntityManager } from "@mikro-orm/core" +import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" type InjectedDependencies = { baseRepository: DAL.RepositoryService @@ -33,33 +36,23 @@ type InjectedDependencies = { customerGroupCustomerService: ModulesSdkTypes.IMedusaInternalService } -const generateMethodForModels = { - Address: { singular: "Address", plural: "Addresses" }, - CustomerGroup, - CustomerGroupCustomer, -} - -export default class CustomerModuleService< - TAddress extends Address = Address, - TCustomer extends Customer = Customer, - TCustomerGroup extends CustomerGroup = CustomerGroup, - TCustomerGroupCustomer extends CustomerGroupCustomer = CustomerGroupCustomer - > - extends ModulesSdkUtils.MedusaService< - CustomerDTO, - { - Address: { dto: any } - CustomerGroup: { dto: any } - CustomerGroupCustomer: { dto: any } - } - >(Customer, generateMethodForModels, entityNameToLinkableKeysMap) +export default class CustomerModuleService + extends MedusaService<{ + Address: { dto: CustomerAddressDTO } + Customer: { dto: CustomerDTO } + CustomerGroup: { dto: CustomerGroupDTO } + CustomerGroupCustomer: { dto: CustomerGroupCustomerDTO } + }>( + { Address, Customer, CustomerGroup, CustomerGroupCustomer }, + entityNameToLinkableKeysMap + ) implements ICustomerModuleService { protected baseRepository_: DAL.RepositoryService - protected customerService_: ModulesSdkTypes.IMedusaInternalService - protected addressService_: ModulesSdkTypes.IMedusaInternalService - protected customerGroupService_: ModulesSdkTypes.IMedusaInternalService - protected customerGroupCustomerService_: ModulesSdkTypes.IMedusaInternalService + protected customerService_: ModulesSdkTypes.IMedusaInternalService + protected addressService_: ModulesSdkTypes.IMedusaInternalService
+ protected customerGroupService_: ModulesSdkTypes.IMedusaInternalService + protected customerGroupCustomerService_: ModulesSdkTypes.IMedusaInternalService constructor( { @@ -85,24 +78,25 @@ export default class CustomerModuleService< return joinerConfig } - async create( + // @ts-expect-error + async createCustomers( data: CustomerTypes.CreateCustomerDTO, sharedContext?: Context ): Promise - async create( + async createCustomers( data: CustomerTypes.CreateCustomerDTO[], sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createCustomers( dataOrArray: | CustomerTypes.CreateCustomerDTO | CustomerTypes.CreateCustomerDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { - const customers = await this.create_(dataOrArray, sharedContext) + const customers = await this.createCustomers_(dataOrArray, sharedContext) const serialized = await this.baseRepository_.serialize< CustomerTypes.CustomerDTO[] @@ -114,7 +108,7 @@ export default class CustomerModuleService< } @InjectTransactionManager("baseRepository_") - async create_( + async createCustomers_( dataOrArray: | CustomerTypes.CreateCustomerDTO | CustomerTypes.CreateCustomerDTO[], @@ -137,29 +131,30 @@ export default class CustomerModuleService< }) .flat() - await this.addAddresses(addressDataWithCustomerIds, sharedContext) + await this.createAddresses(addressDataWithCustomerIds, sharedContext) return customers as unknown as CustomerTypes.CustomerDTO[] } - update( + // @ts-expect-error + updateCustomers( customerId: string, data: CustomerTypes.CustomerUpdatableFields, sharedContext?: Context ): Promise - update( + updateCustomers( customerIds: string[], data: CustomerTypes.CustomerUpdatableFields, sharedContext?: Context ): Promise - update( + updateCustomers( selector: CustomerTypes.FilterableCustomerProps, data: CustomerTypes.CustomerUpdatableFields, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") - async update( + async updateCustomers( idsOrSelector: string | string[] | CustomerTypes.FilterableCustomerProps, data: CustomerTypes.CustomerUpdatableFields, @MedusaContext() sharedContext: Context = {} @@ -203,18 +198,19 @@ export default class CustomerModuleService< return isString(idsOrSelector) ? serialized[0] : serialized } - async createCustomerGroup( + // @ts-expect-error + async createCustomerGroups( dataOrArrayOfData: CustomerTypes.CreateCustomerGroupDTO, sharedContext?: Context ): Promise - async createCustomerGroup( + async createCustomerGroups( dataOrArrayOfData: CustomerTypes.CreateCustomerGroupDTO[], sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") - async createCustomerGroup( + async createCustomerGroups( dataOrArrayOfData: | CustomerTypes.CreateCustomerGroupDTO | CustomerTypes.CreateCustomerGroupDTO[], @@ -232,7 +228,7 @@ export default class CustomerModuleService< }) } - // @ts-ignore + // @ts-expect-error async updateCustomerGroups( groupId: string, data: CustomerTypes.CustomerGroupUpdatableFields, @@ -319,7 +315,7 @@ export default class CustomerModuleService< ) if (Array.isArray(data)) { - return (groupCustomers as unknown as TCustomerGroupCustomer[]).map( + return (groupCustomers as unknown as CustomerGroupCustomer[]).map( (gc) => ({ id: gc.id }) ) } @@ -327,18 +323,18 @@ export default class CustomerModuleService< return { id: groupCustomers.id } } - // TODO: should be createAddresses to conform to the convention - async addAddresses( + // @ts-expect-error + async createAddresses( addresses: CustomerTypes.CreateCustomerAddressDTO[], sharedContext?: Context ): Promise - async addAddresses( + async createAddresses( address: CustomerTypes.CreateCustomerAddressDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async addAddresses( + async createAddresses( data: | CustomerTypes.CreateCustomerAddressDTO | CustomerTypes.CreateCustomerAddressDTO[], @@ -346,7 +342,7 @@ export default class CustomerModuleService< ): Promise< CustomerTypes.CustomerAddressDTO | CustomerTypes.CustomerAddressDTO[] > { - const addresses = await this.addAddresses_(data, sharedContext) + const addresses = await this.createAddresses_(data, sharedContext) const serialized = await this.baseRepository_.serialize< CustomerTypes.CustomerAddressDTO[] @@ -360,7 +356,7 @@ export default class CustomerModuleService< } @InjectTransactionManager("baseRepository_") - private async addAddresses_( + private async createAddresses_( data: | CustomerTypes.CreateCustomerAddressDTO | CustomerTypes.CreateCustomerAddressDTO[], @@ -372,7 +368,7 @@ export default class CustomerModuleService< ) } - // @ts-ignore + // @ts-expect-error async updateAddresses( addressId: string, data: CustomerTypes.UpdateCustomerAddressDTO, diff --git a/packages/modules/event-bus-local/package.json b/packages/modules/event-bus-local/package.json index 153a39987d..be19e140e9 100644 --- a/packages/modules/event-bus-local/package.json +++ b/packages/modules/event-bus-local/package.json @@ -15,7 +15,7 @@ "access": "public" }, "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/event-bus-redis/package.json b/packages/modules/event-bus-redis/package.json index f596f398e7..3349b282cf 100644 --- a/packages/modules/event-bus-redis/package.json +++ b/packages/modules/event-bus-redis/package.json @@ -15,7 +15,7 @@ "access": "public" }, "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/file/integration-tests/__tests__/module.spec.ts b/packages/modules/file/integration-tests/__tests__/module.spec.ts index 50c3f324fb..df02a3a11e 100644 --- a/packages/modules/file/integration-tests/__tests__/module.spec.ts +++ b/packages/modules/file/integration-tests/__tests__/module.spec.ts @@ -1,7 +1,8 @@ import { resolve } from "path" import { Modules } from "@medusajs/utils" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { Entity, PrimaryKey } from "@mikro-orm/core" +import { IFileModuleService } from "@medusajs/types" jest.setTimeout(100000) @@ -28,15 +29,14 @@ const moduleOptions = { ], } -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.FILE, moduleOptions: moduleOptions, moduleModels: [DummyEntity], - // TODO: Fix the type of service, it complains for some reason if we pass IFileModuleService - testSuite: ({ service }: SuiteOptions) => { + testSuite: ({ service }) => { describe("File Module Service", () => { it("creates and gets a file", async () => { - const res = await service.create({ + const res = await service.createFiles({ filename: "test.jpg", mimeType: "image/jpeg", content: Buffer.from("test"), @@ -48,7 +48,7 @@ moduleIntegrationTestRunner({ }) // The fake provider returns the file content as the url - const downloadUrl = await service.retrieve("test.jpg") + const downloadUrl = await service.retrieveFile("test.jpg") expect(await new Response(downloadUrl.url).text()).toEqual("test") }) }) diff --git a/packages/modules/file/package.json b/packages/modules/file/package.json index 2bd52b0620..05da32dff3 100644 --- a/packages/modules/file/package.json +++ b/packages/modules/file/package.json @@ -8,7 +8,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/file/src/index.ts b/packages/modules/file/src/index.ts index 5167ac59b5..997845768c 100644 --- a/packages/modules/file/src/index.ts +++ b/packages/modules/file/src/index.ts @@ -1,5 +1,13 @@ -import { moduleDefinition } from "./module-definition" -export * from "./types" -export * from "./services" +import { ModuleExports } from "@medusajs/types" +import { FileModuleService } from "@services" +import loadProviders from "./loaders/providers" + +const loaders = [loadProviders] as any + +const service = FileModuleService +export const moduleDefinition: ModuleExports = { + service, + loaders, +} export default moduleDefinition diff --git a/packages/modules/file/src/joiner-config.ts b/packages/modules/file/src/joiner-config.ts index 1f1075f4c6..e6caec270e 100644 --- a/packages/modules/file/src/joiner-config.ts +++ b/packages/modules/file/src/joiner-config.ts @@ -1,22 +1,13 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys = {} +export const joinerConfig = defineJoinerConfig(Modules.FILE, { + entityQueryingConfig: [{ name: "File" }], +}) -const entityLinkableKeysMap: MapToConfig = {} -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.FILE, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["file", "files"], - args: { - entity: "File", - }, - }, - ], -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap({}) diff --git a/packages/modules/file/src/module-definition.ts b/packages/modules/file/src/module-definition.ts deleted file mode 100644 index c663589052..0000000000 --- a/packages/modules/file/src/module-definition.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { FileModuleService } from "@services" -import loadProviders from "./loaders/providers" - -const loaders = [loadProviders] as any - -const service = FileModuleService -export const moduleDefinition: ModuleExports = { - service, - loaders, -} diff --git a/packages/modules/file/src/services/file-module-service.ts b/packages/modules/file/src/services/file-module-service.ts index d912ab9605..9ee076557b 100644 --- a/packages/modules/file/src/services/file-module-service.ts +++ b/packages/modules/file/src/services/file-module-service.ts @@ -2,10 +2,10 @@ import { Context, CreateFileDTO, FileDTO, - ModuleJoinerConfig, FileTypes, FilterableFileProps, FindConfig, + ModuleJoinerConfig, } from "@medusajs/types" import { joinerConfig } from "../joiner-config" @@ -26,10 +26,13 @@ export default class FileModuleService implements FileTypes.IFileModuleService { return joinerConfig } - create(data: CreateFileDTO[], sharedContext?: Context): Promise - create(data: CreateFileDTO, sharedContext?: Context): Promise + createFiles( + data: CreateFileDTO[], + sharedContext?: Context + ): Promise + createFiles(data: CreateFileDTO, sharedContext?: Context): Promise - async create( + async createFiles( data: CreateFileDTO[] | CreateFileDTO ): Promise { const input = Array.isArray(data) ? data : [data] @@ -46,9 +49,9 @@ export default class FileModuleService implements FileTypes.IFileModuleService { return Array.isArray(data) ? result : result[0] } - async delete(ids: string[], sharedContext?: Context): Promise - async delete(id: string, sharedContext?: Context): Promise - async delete(ids: string[] | string): Promise { + async deleteFiles(ids: string[], sharedContext?: Context): Promise + async deleteFiles(id: string, sharedContext?: Context): Promise + async deleteFiles(ids: string[] | string): Promise { const input = Array.isArray(ids) ? ids : [ids] await Promise.all( input.map((id) => this.fileProviderService_.delete({ fileKey: id })) @@ -57,7 +60,7 @@ export default class FileModuleService implements FileTypes.IFileModuleService { return } - async retrieve(id: string): Promise { + async retrieveFile(id: string): Promise { const res = await this.fileProviderService_.getPresignedDownloadUrl({ fileKey: id, }) @@ -68,7 +71,7 @@ export default class FileModuleService implements FileTypes.IFileModuleService { } } - async list( + async listFiles( filters?: FilterableFileProps, config?: FindConfig, sharedContext?: Context @@ -97,7 +100,7 @@ export default class FileModuleService implements FileTypes.IFileModuleService { ] } - async listAndCount( + async listAndCountFiles( filters?: FilterableFileProps, config?: FindConfig, sharedContext?: Context diff --git a/packages/modules/fulfillment/integration-tests/__fixtures__/index.ts b/packages/modules/fulfillment/integration-tests/__fixtures__/index.ts index cd0b42db58..4a445b804e 100644 --- a/packages/modules/fulfillment/integration-tests/__fixtures__/index.ts +++ b/packages/modules/fulfillment/integration-tests/__fixtures__/index.ts @@ -21,7 +21,7 @@ export async function createFullDataStructure( name: "test_" + randomString, type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test_" + randomString, type: "test-type", }) diff --git a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/fulfillment-set.spec.ts b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/fulfillment-set.spec.ts index 25059b5125..2ed8b21eb0 100644 --- a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/fulfillment-set.spec.ts +++ b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/fulfillment-set.spec.ts @@ -1,4 +1,7 @@ -import { Modules } from "@medusajs/modules-sdk" +import { FulfillmentEvents, GeoZoneType, Modules } from "@medusajs/utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" +import { MockEventBusService } from "medusa-test-utils/dist" +import { buildExpectedEventMessageShape } from "../../__fixtures__" import { CreateFulfillmentSetDTO, CreateServiceZoneDTO, @@ -6,10 +9,6 @@ import { ServiceZoneDTO, UpdateFulfillmentSetDTO, } from "@medusajs/types" -import { FulfillmentEvents, GeoZoneType } from "@medusajs/utils" -import { moduleIntegrationTestRunner } from "medusa-test-utils" -import { MockEventBusService } from "medusa-test-utils/dist" -import { buildExpectedEventMessageShape } from "../../__fixtures__" jest.setTimeout(100000) @@ -29,11 +28,11 @@ moduleIntegrationTestRunner({ describe("Fulfillment Module Service", () => { describe("read", () => { it("should list fulfillment sets with a filter", async function () { - const createdSet1 = await service.create({ + const createdSet1 = await service.createFulfillmentSets({ name: "test", type: "test-type", }) - const createdSet2 = await service.create({ + const createdSet2 = await service.createFulfillmentSets({ name: "test2", type: "test-type", service_zones: [ @@ -67,7 +66,7 @@ moduleIntegrationTestRunner({ ], }) - let listedSets = await service.list( + let listedSets = await service.listFulfillmentSets( { type: createdSet1.type, }, @@ -76,7 +75,7 @@ moduleIntegrationTestRunner({ } ) - const listedSets2 = await service.list( + const listedSets2 = await service.listFulfillmentSets( { type: createdSet1.type, }, @@ -101,7 +100,7 @@ moduleIntegrationTestRunner({ expect(listedSets2).toEqual(listedSets2) - listedSets = await service.list({ + listedSets = await service.listFulfillmentSets({ name: createdSet2.name, }) @@ -116,7 +115,7 @@ moduleIntegrationTestRunner({ ]) ) - listedSets = await service.list({ + listedSets = await service.listFulfillmentSets({ service_zones: { name: "test" }, }) @@ -131,7 +130,7 @@ moduleIntegrationTestRunner({ ]) ) - listedSets = await service.list({ + listedSets = await service.listFulfillmentSets({ service_zones: { geo_zones: { country_code: "fr" } }, }) @@ -156,7 +155,7 @@ moduleIntegrationTestRunner({ type: "test-type", } - const fulfillmentSet = await service.create(data) + const fulfillmentSet = await service.createFulfillmentSets(data) expect(fulfillmentSet).toEqual( expect.objectContaining({ @@ -188,7 +187,7 @@ moduleIntegrationTestRunner({ }, ] - const fulfillmentSets = await service.create(data) + const fulfillmentSets = await service.createFulfillmentSets(data) expect(fulfillmentSets).toHaveLength(2) @@ -228,7 +227,7 @@ moduleIntegrationTestRunner({ ], } - const fulfillmentSet = await service.create(data) + const fulfillmentSet = await service.createFulfillmentSets(data) expect(fulfillmentSet).toEqual( expect.objectContaining({ @@ -291,7 +290,7 @@ moduleIntegrationTestRunner({ }, ] - const fulfillmentSets = await service.create(data) + const fulfillmentSets = await service.createFulfillmentSets(data) expect(fulfillmentSets).toHaveLength(3) @@ -349,7 +348,7 @@ moduleIntegrationTestRunner({ ], } - const fulfillmentSet = await service.create(data) + const fulfillmentSet = await service.createFulfillmentSets(data) expect(fulfillmentSet).toEqual( expect.objectContaining({ @@ -445,7 +444,7 @@ moduleIntegrationTestRunner({ }, ] - const fulfillmentSets = await service.create(data) + const fulfillmentSets = await service.createFulfillmentSets(data) expect(fulfillmentSets).toHaveLength(3) @@ -508,8 +507,10 @@ moduleIntegrationTestRunner({ type: "test-type", } - await service.create(data) - const err = await service.create(data).catch((e) => e) + await service.createFulfillmentSets(data) + const err = await service + .createFulfillmentSets(data) + .catch((e) => e) expect(err).toBeDefined() expect(err.message).toContain("exists") @@ -532,7 +533,7 @@ moduleIntegrationTestRunner({ ], } - let err = await service.create(data).catch((e) => e) + let err = await service.createFulfillmentSets(data).catch((e) => e) expect(err.message).toBe( "Missing required property province_code for geo zone type province" ) @@ -554,7 +555,7 @@ moduleIntegrationTestRunner({ ], } - err = await service.create(data).catch((e) => e) + err = await service.createFulfillmentSets(data).catch((e) => e) expect(err.message).toBe( "Missing required property city for geo zone type city" ) @@ -575,7 +576,7 @@ moduleIntegrationTestRunner({ ], } - err = await service.create(data).catch((e) => e) + err = await service.createFulfillmentSets(data).catch((e) => e) expect(err.message).toBe( "Missing required property country_code for geo zone type zip" ) @@ -596,7 +597,7 @@ moduleIntegrationTestRunner({ ], } - err = await service.create(data).catch((e) => e) + err = await service.createFulfillmentSets(data).catch((e) => e) expect(err.message).toBe(`Invalid geo zone type: unknown`) }) }) @@ -608,7 +609,9 @@ moduleIntegrationTestRunner({ type: "test-type", } - const createdFulfillmentSet = await service.create(createData) + const createdFulfillmentSet = await service.createFulfillmentSets( + createData + ) const updateData = { id: createdFulfillmentSet.id, @@ -616,7 +619,9 @@ moduleIntegrationTestRunner({ type: "updated-test-type", } - const updatedFulfillmentSets = await service.update(updateData) + const updatedFulfillmentSets = await service.updateFulfillmentSets( + updateData + ) expect(updatedFulfillmentSets).toEqual( expect.objectContaining({ @@ -648,7 +653,9 @@ moduleIntegrationTestRunner({ }, ] - const createdFulfillmentSets = await service.create(createData) + const createdFulfillmentSets = await service.createFulfillmentSets( + createData + ) const updateData = createdFulfillmentSets.map( (fulfillmentSet, index) => ({ @@ -658,8 +665,10 @@ moduleIntegrationTestRunner({ }) ) - const updatedFulfillmentSets = await service.update(updateData) - const fullfillmentSets = await service.list({ + const updatedFulfillmentSets = await service.updateFulfillmentSets( + updateData + ) + const fullfillmentSets = await service.listFulfillmentSets({ id: updateData.map((ud) => ud.id), }) @@ -669,7 +678,7 @@ moduleIntegrationTestRunner({ for (const data_ of updateData) { const currentFullfillmentSet = fullfillmentSets.find( (fs) => fs.id === data_.id - ) + )! expect(currentFullfillmentSet).toEqual( expect.objectContaining({ @@ -709,7 +718,9 @@ moduleIntegrationTestRunner({ ], } - const createdFulfillmentSet = await service.create(createData) + const createdFulfillmentSet = await service.createFulfillmentSets( + createData + ) const createServiceZoneData: CreateServiceZoneDTO = { fulfillment_set_id: createdFulfillmentSet.id, @@ -729,7 +740,9 @@ moduleIntegrationTestRunner({ service_zones: [createServiceZoneData], } - const updatedFulfillmentSet = await service.update(updateData) + const updatedFulfillmentSet = await service.updateFulfillmentSets( + updateData + ) expect(updatedFulfillmentSet).toEqual( expect.objectContaining({ @@ -822,7 +835,9 @@ moduleIntegrationTestRunner({ ], } - const createdFulfillmentSet = await service.create(createData) + const createdFulfillmentSet = await service.createFulfillmentSets( + createData + ) const createServiceZoneData: CreateServiceZoneDTO = { fulfillment_set_id: createdFulfillmentSet.id, @@ -845,7 +860,9 @@ moduleIntegrationTestRunner({ ], } - const updatedFulfillmentSet = await service.update(updateData) + const updatedFulfillmentSet = await service.updateFulfillmentSets( + updateData + ) expect(updatedFulfillmentSet).toEqual( expect.objectContaining({ @@ -876,7 +893,7 @@ moduleIntegrationTestRunner({ const createdServiceZone = updatedFulfillmentSet.service_zones.find( (s) => s.name === "service-zone-test2" - ) + )! expect(eventBusEmitSpy.mock.calls[1][0]).toHaveLength(3) expect(eventBusEmitSpy).toHaveBeenLastCalledWith( @@ -917,7 +934,9 @@ moduleIntegrationTestRunner({ }, ] - const createdFulfillmentSets = await service.create(createData) + const createdFulfillmentSets = await service.createFulfillmentSets( + createData + ) const updateData = { id: createdFulfillmentSets[1].id, @@ -925,7 +944,9 @@ moduleIntegrationTestRunner({ type: "updated-test-type2", } - const err = await service.update(updateData).catch((e) => e) + const err = await service + .updateFulfillmentSets(updateData) + .catch((e) => e) expect(err).toBeDefined() expect(err.message).toContain("exists") @@ -965,7 +986,9 @@ moduleIntegrationTestRunner({ }, ] - const createdFulfillmentSets = await service.create(createData) + const createdFulfillmentSets = await service.createFulfillmentSets( + createData + ) const updateData: UpdateFulfillmentSetDTO[] = createdFulfillmentSets.map((fulfillmentSet, index) => ({ @@ -985,7 +1008,9 @@ moduleIntegrationTestRunner({ ], })) - const updatedFulfillmentSets = await service.update(updateData) + const updatedFulfillmentSets = await service.updateFulfillmentSets( + updateData + ) expect(updatedFulfillmentSets).toHaveLength(2) expect(eventBusEmitSpy.mock.calls[1][0]).toHaveLength(10) @@ -993,10 +1018,10 @@ moduleIntegrationTestRunner({ for (const data_ of updateData) { const expectedFulfillmentSet = updatedFulfillmentSets.find( (f) => f.id === data_.id - ) + )! const originalFulfillmentSet = createdFulfillmentSets.find( (f) => f.id === data_.id - ) + )! expect(expectedFulfillmentSet).toEqual( expect.objectContaining({ @@ -1115,7 +1140,9 @@ moduleIntegrationTestRunner({ }, ] - const createdFulfillmentSets = await service.create(createData) + const createdFulfillmentSets = await service.createFulfillmentSets( + createData + ) const updateData: UpdateFulfillmentSetDTO[] = createdFulfillmentSets.map((fulfillmentSet, index) => ({ @@ -1136,7 +1163,9 @@ moduleIntegrationTestRunner({ ], })) - const updatedFulfillmentSets = await service.update(updateData) + const updatedFulfillmentSets = await service.updateFulfillmentSets( + updateData + ) expect(updatedFulfillmentSets).toHaveLength(2) expect(eventBusEmitSpy.mock.calls[1][0]).toHaveLength(6) @@ -1144,7 +1173,7 @@ moduleIntegrationTestRunner({ for (const data_ of updateData) { const expectedFulfillmentSet = updatedFulfillmentSets.find( (f) => f.id === data_.id - ) + )! expect(expectedFulfillmentSet).toEqual( expect.objectContaining({ id: data_.id, @@ -1175,7 +1204,7 @@ moduleIntegrationTestRunner({ const createdServiceZone = expectedFulfillmentSet.service_zones.find((s) => s.name.includes(`added-service-zone-test`) - ) + )! expect(eventBusEmitSpy).toHaveBeenLastCalledWith( expect.arrayContaining([ diff --git a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/fulfillment.spec.ts b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/fulfillment.spec.ts index d8553899e0..e0e553ed06 100644 --- a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/fulfillment.spec.ts +++ b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/fulfillment.spec.ts @@ -56,7 +56,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -104,7 +104,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -191,7 +191,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -280,7 +280,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -332,7 +332,6 @@ moduleIntegrationTestRunner({ )! const updateData: UpdateFulfillmentDTO = { - id: fulfillment.id, labels: [ { id: label1.id }, { ...label2, label_url: "updated-test-label-url-2" }, @@ -417,7 +416,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) diff --git a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/geo-zone.spec.ts b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/geo-zone.spec.ts index 81dd5da57d..e582405cfe 100644 --- a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/geo-zone.spec.ts +++ b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/geo-zone.spec.ts @@ -29,7 +29,7 @@ moduleIntegrationTestRunner({ describe("Fulfillment Module Service", () => { describe("read", () => { it("should list geo zones with a filter", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -80,7 +80,7 @@ moduleIntegrationTestRunner({ describe("mutations", () => { describe("on create", () => { it("should create a new geo zone", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -119,7 +119,7 @@ moduleIntegrationTestRunner({ }) it("should create a collection of geo zones", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -174,7 +174,7 @@ moduleIntegrationTestRunner({ }) it("should fail to create new geo zones that are not valid", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -230,7 +230,7 @@ moduleIntegrationTestRunner({ describe("on update", () => { it("should update an existing geo zone", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -277,7 +277,7 @@ moduleIntegrationTestRunner({ }) it("should update a collection of geo zones", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) diff --git a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/index.spec.ts b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/index.spec.ts index 5e5ec72e3e..0660394199 100644 --- a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/index.spec.ts +++ b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/index.spec.ts @@ -30,7 +30,7 @@ let providerId = "fixtures-fulfillment-provider_test-provider" async function list( service: IFulfillmentModuleService, - ...args: Parameters + ...args: Parameters ) { const [filters = {}, config = {}] = args @@ -48,7 +48,7 @@ async function list( ...config, } - return await service.list(filters, finalConfig) + return await service.listFulfillmentSets(filters, finalConfig) } function expectSoftDeleted( @@ -109,7 +109,7 @@ moduleIntegrationTestRunner({ it("should load and save all the providers on bootstrap with the correct is_enabled value", async () => { const databaseConfig = { schema: "public", - clientUrl: MikroOrmWrapper.clientUrl, + clientUrl: MikroOrmWrapper.clientUrl!, } const providersConfig = {} @@ -159,7 +159,7 @@ moduleIntegrationTestRunner({ name ) ) - }) + })! expect(provider).toBeDefined() expect(provider.is_enabled).toBeTruthy() } @@ -222,7 +222,7 @@ moduleIntegrationTestRunner({ name ) ) - }) + })! expect(provider).toBeDefined() const isEnabled = !!providersConfig2[name] @@ -242,7 +242,7 @@ moduleIntegrationTestRunner({ * Soft delete the fulfillment set */ - await service.softDelete(fulfillmentSets[0].id) + await service.softDeleteFulfillmentSets([fulfillmentSets[0].id]) const deletedFulfillmentSets = await list( service, {}, @@ -256,7 +256,7 @@ moduleIntegrationTestRunner({ * Restore the fulfillment set */ - await service.restore(fulfillmentSets[0].id) + await service.restoreFulfillmentSets([fulfillmentSets[0].id]) const restoredFulfillmentSets = await list(service) expectSoftDeleted(restoredFulfillmentSets) }) diff --git a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/service-zone.spec.ts b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/service-zone.spec.ts index 2748a09b0f..839e0a5cb3 100644 --- a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/service-zone.spec.ts +++ b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/service-zone.spec.ts @@ -30,7 +30,7 @@ moduleIntegrationTestRunner({ describe("Fulfillment Module Service", () => { describe("read", () => { it("should list service zones with a filter", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -85,7 +85,7 @@ moduleIntegrationTestRunner({ describe("mutations", () => { describe("on create", () => { it("should create a new service zone", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -119,7 +119,7 @@ moduleIntegrationTestRunner({ }) it("should create a collection of service zones", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -181,7 +181,7 @@ moduleIntegrationTestRunner({ }) it("should fail on duplicated service zone name", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -205,7 +205,7 @@ moduleIntegrationTestRunner({ }) it("should fail on creating a service zone and new geo zones that are not valid", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -277,7 +277,7 @@ moduleIntegrationTestRunner({ describe("on update", () => { it("should update an existing service zone", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -396,7 +396,7 @@ moduleIntegrationTestRunner({ }) it("should fail on duplicated service zone name", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -449,7 +449,7 @@ moduleIntegrationTestRunner({ describe("on upsert", () => { it("should upsert a collection of service zones", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) diff --git a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/shipping-option.spec.ts b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/shipping-option.spec.ts index 6a53dea52f..4972fba8ac 100644 --- a/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/shipping-option.spec.ts +++ b/packages/modules/fulfillment/integration-tests/__tests__/fulfillment-module-service/shipping-option.spec.ts @@ -57,7 +57,7 @@ moduleIntegrationTestRunner({ describe("Fulfillment Module Service", () => { describe("read", () => { it("should list shipping options with a filter", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", service_zones: [ @@ -113,7 +113,7 @@ moduleIntegrationTestRunner({ }) it("should list shipping options with a context", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", service_zones: [ @@ -224,7 +224,7 @@ moduleIntegrationTestRunner({ }) it(`should list the shipping options for a context with a specific address`, async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", service_zones: [ @@ -341,7 +341,7 @@ moduleIntegrationTestRunner({ }) it("should validate if a shipping option is applicable to a context", async function () { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", service_zones: [ @@ -432,7 +432,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -509,7 +509,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -601,7 +601,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -637,7 +637,7 @@ moduleIntegrationTestRunner({ describe("on update", () => { it("should update a shipping option", async () => { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -789,7 +789,7 @@ moduleIntegrationTestRunner({ }) it("should update a shipping option without updating the rules or the type", async () => { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -880,7 +880,7 @@ moduleIntegrationTestRunner({ }) it("should update a collection of shipping options", async () => { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -1027,7 +1027,7 @@ moduleIntegrationTestRunner({ }) it("should fail to update a non-existent shipping option", async () => { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -1075,7 +1075,7 @@ moduleIntegrationTestRunner({ }) it("should fail to update a shipping option when adding non existing rules", async () => { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -1120,7 +1120,7 @@ moduleIntegrationTestRunner({ }) it("should fail to update a shipping option when adding invalid rules", async () => { - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -1173,7 +1173,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) @@ -1250,7 +1250,7 @@ moduleIntegrationTestRunner({ name: "test", type: "default", }) - const fulfillmentSet = await service.create({ + const fulfillmentSet = await service.createFulfillmentSets({ name: "test", type: "test-type", }) diff --git a/packages/modules/fulfillment/package.json b/packages/modules/fulfillment/package.json index 2094762876..ed6e56e5f6 100644 --- a/packages/modules/fulfillment/package.json +++ b/packages/modules/fulfillment/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-fulfillment-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/fulfillment/src/index.ts b/packages/modules/fulfillment/src/index.ts index 5dc2ece165..f747355fac 100644 --- a/packages/modules/fulfillment/src/index.ts +++ b/packages/modules/fulfillment/src/index.ts @@ -1,7 +1,15 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { FulfillmentModuleService } from "@services" +import loadProviders from "./loaders/providers" -export * from "./types" -export * from "./models" -export * from "./services" +const service = FulfillmentModuleService +const loaders = [loadProviders] +export const moduleDefinition: ModuleExports = { + service, + loaders, +} export default moduleDefinition + +// Module options types +export { FulfillmentModuleOptions } from "./types" diff --git a/packages/modules/fulfillment/src/joiner-config.ts b/packages/modules/fulfillment/src/joiner-config.ts index 06b0d3b35c..d4b7358816 100644 --- a/packages/modules/fulfillment/src/joiner-config.ts +++ b/packages/modules/fulfillment/src/joiner-config.ts @@ -1,94 +1,24 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" import { Fulfillment, - FulfillmentProvider, FulfillmentSet, - GeoZone, - ServiceZone, ShippingOption, ShippingOptionRule, - ShippingProfile, } from "@models" -export const LinkableKeys: Record = { - fulfillment_id: Fulfillment.name, - fulfillment_set_id: FulfillmentSet.name, - shipping_option_id: ShippingOption.name, - shipping_option_rule_id: ShippingOptionRule.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) +export const joinerConfig = defineJoinerConfig(Modules.FULFILLMENT, { + linkableKeys: { + fulfillment_id: Fulfillment.name, + fulfillment_set_id: FulfillmentSet.name, + shipping_option_id: ShippingOption.name, + shipping_option_rule_id: ShippingOptionRule.name, + }, }) -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.FULFILLMENT, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["fulfillment_set", "fulfillment_sets"], - args: { - entity: FulfillmentSet.name, - }, - }, - { - name: ["shipping_option", "shipping_options"], - args: { - entity: ShippingOption.name, - methodSuffix: "ShippingOptions", - }, - }, - { - name: ["shipping_profile", "shipping_profiles"], - args: { - entity: ShippingProfile.name, - methodSuffix: "ShippingProfiles", - }, - }, - { - name: ["fulfillment", "fulfillments"], - args: { - entity: Fulfillment.name, - methodSuffix: "Fulfillments", - }, - }, - { - name: ["fulfillment_provider", "fulfillment_providers"], - args: { - entity: FulfillmentProvider.name, - methodSuffix: "FulfillmentProviders", - }, - }, - { - name: ["service_zone", "service_zones"], - args: { - entity: ServiceZone.name, - methodSuffix: "ServiceZones", - }, - }, - { - name: ["geo_zone", "geo_zones"], - args: { - entity: GeoZone.name, - methodSuffix: "GeoZones", - }, - }, - { - name: ["shipping_option_rule", "shipping_option_rules"], - args: { - entity: ShippingOptionRule.name, - methodSuffix: "ShippingOptionRules", - }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/fulfillment/src/module-definition.ts b/packages/modules/fulfillment/src/module-definition.ts deleted file mode 100644 index 6c922130c2..0000000000 --- a/packages/modules/fulfillment/src/module-definition.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { FulfillmentModuleService } from "@services" -import loadProviders from "./loaders/providers" - -const service = FulfillmentModuleService -const loaders = [loadProviders] - -export const moduleDefinition: ModuleExports = { - service, - loaders, -} diff --git a/packages/modules/fulfillment/src/scripts/bin/run-seed.ts b/packages/modules/fulfillment/src/scripts/bin/run-seed.ts deleted file mode 100644 index 5fa19060a0..0000000000 --- a/packages/modules/fulfillment/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node - -import { ModulesSdkUtils } from "@medusajs/utils" -import { Modules } from "@medusajs/modules-sdk" -import * as Models from "@models" -import { EOL } from "os" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-fulfillment-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.FULFILLMENT, - models: Models, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - // TODO: Add seed logic - }, - }) - await run({ path }) -})() diff --git a/packages/modules/fulfillment/src/services/fulfillment-module-service.ts b/packages/modules/fulfillment/src/services/fulfillment-module-service.ts index 435919a70b..dda983e782 100644 --- a/packages/modules/fulfillment/src/services/fulfillment-module-service.ts +++ b/packages/modules/fulfillment/src/services/fulfillment-module-service.ts @@ -53,6 +53,7 @@ import { buildCreatedShippingOptionEvents } from "../utils/events" import FulfillmentProviderService from "./fulfillment-provider" const generateMethodForModels = { + FulfillmentSet, ServiceZone, ShippingOption, GeoZone, @@ -76,41 +77,29 @@ type InjectedDependencies = { fulfillmentService: ModulesSdkTypes.IMedusaInternalService } -export default class FulfillmentModuleService< - TEntity extends FulfillmentSet = FulfillmentSet, - TServiceZoneEntity extends ServiceZone = ServiceZone, - TGeoZoneEntity extends GeoZone = GeoZone, - TShippingProfileEntity extends ShippingProfile = ShippingProfile, - TShippingOptionEntity extends ShippingOption = ShippingOption, - TShippingOptionRuleEntity extends ShippingOptionRule = ShippingOptionRule, - TSippingOptionTypeEntity extends ShippingOptionType = ShippingOptionType, - TFulfillmentEntity extends Fulfillment = Fulfillment - > - extends ModulesSdkUtils.MedusaService< - FulfillmentTypes.FulfillmentSetDTO, - { - FulfillmentSet: { dto: FulfillmentTypes.FulfillmentSetDTO } - ServiceZone: { dto: FulfillmentTypes.ServiceZoneDTO } - ShippingOption: { dto: FulfillmentTypes.ShippingOptionDTO } - GeoZone: { dto: FulfillmentTypes.GeoZoneDTO } - ShippingProfile: { dto: FulfillmentTypes.ShippingProfileDTO } - ShippingOptionRule: { dto: FulfillmentTypes.ShippingOptionRuleDTO } - ShippingOptionType: { dto: FulfillmentTypes.ShippingOptionTypeDTO } - FulfillmentProvider: { dto: FulfillmentTypes.FulfillmentProviderDTO } - } - >(FulfillmentSet, generateMethodForModels, entityNameToLinkableKeysMap) +export default class FulfillmentModuleService + extends ModulesSdkUtils.MedusaService<{ + FulfillmentSet: { dto: FulfillmentTypes.FulfillmentSetDTO } + ServiceZone: { dto: FulfillmentTypes.ServiceZoneDTO } + ShippingOption: { dto: FulfillmentTypes.ShippingOptionDTO } + GeoZone: { dto: FulfillmentTypes.GeoZoneDTO } + ShippingProfile: { dto: FulfillmentTypes.ShippingProfileDTO } + ShippingOptionRule: { dto: FulfillmentTypes.ShippingOptionRuleDTO } + ShippingOptionType: { dto: FulfillmentTypes.ShippingOptionTypeDTO } + FulfillmentProvider: { dto: FulfillmentTypes.FulfillmentProviderDTO } + }>(generateMethodForModels, entityNameToLinkableKeysMap) implements IFulfillmentModuleService { protected baseRepository_: DAL.RepositoryService - protected readonly fulfillmentSetService_: ModulesSdkTypes.IMedusaInternalService - protected readonly serviceZoneService_: ModulesSdkTypes.IMedusaInternalService - protected readonly geoZoneService_: ModulesSdkTypes.IMedusaInternalService - protected readonly shippingProfileService_: ModulesSdkTypes.IMedusaInternalService - protected readonly shippingOptionService_: ModulesSdkTypes.IMedusaInternalService - protected readonly shippingOptionRuleService_: ModulesSdkTypes.IMedusaInternalService - protected readonly shippingOptionTypeService_: ModulesSdkTypes.IMedusaInternalService + protected readonly fulfillmentSetService_: ModulesSdkTypes.IMedusaInternalService + protected readonly serviceZoneService_: ModulesSdkTypes.IMedusaInternalService + protected readonly geoZoneService_: ModulesSdkTypes.IMedusaInternalService + protected readonly shippingProfileService_: ModulesSdkTypes.IMedusaInternalService + protected readonly shippingOptionService_: ModulesSdkTypes.IMedusaInternalService + protected readonly shippingOptionRuleService_: ModulesSdkTypes.IMedusaInternalService + protected readonly shippingOptionTypeService_: ModulesSdkTypes.IMedusaInternalService protected readonly fulfillmentProviderService_: FulfillmentProviderService - protected readonly fulfillmentService_: ModulesSdkTypes.IMedusaInternalService + protected readonly fulfillmentService_: ModulesSdkTypes.IMedusaInternalService constructor( { @@ -258,18 +247,19 @@ export default class FulfillmentModuleService< ] } - create( + // @ts-expect-error + createFulfillmentSets( data: FulfillmentTypes.CreateFulfillmentSetDTO[], sharedContext?: Context ): Promise - create( + createFulfillmentSets( data: FulfillmentTypes.CreateFulfillmentSetDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") @EmitEvents() - async create( + async createFulfillmentSets( data: | FulfillmentTypes.CreateFulfillmentSetDTO | FulfillmentTypes.CreateFulfillmentSetDTO[], @@ -277,7 +267,10 @@ export default class FulfillmentModuleService< ): Promise< FulfillmentTypes.FulfillmentSetDTO | FulfillmentTypes.FulfillmentSetDTO[] > { - const createdFulfillmentSets = await this.create_(data, sharedContext) + const createdFulfillmentSets = await this.createFulfillmentSets_( + data, + sharedContext + ) const returnedFulfillmentSets = Array.isArray(data) ? createdFulfillmentSets @@ -289,12 +282,12 @@ export default class FulfillmentModuleService< } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createFulfillmentSets_( data: | FulfillmentTypes.CreateFulfillmentSetDTO | FulfillmentTypes.CreateFulfillmentSetDTO[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const data_ = Array.isArray(data) ? data : [data] if (!data_.length) { @@ -360,7 +353,7 @@ export default class FulfillmentModuleService< | FulfillmentTypes.CreateServiceZoneDTO[] | FulfillmentTypes.CreateServiceZoneDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const data_ = Array.isArray(data) ? data : [data] if (!data_.length) { @@ -424,7 +417,7 @@ export default class FulfillmentModuleService< | FulfillmentTypes.CreateShippingOptionDTO[] | FulfillmentTypes.CreateShippingOptionDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const data_ = Array.isArray(data) ? data : [data] if (!data_.length) { @@ -493,7 +486,7 @@ export default class FulfillmentModuleService< | FulfillmentTypes.CreateShippingProfileDTO[] | FulfillmentTypes.CreateShippingProfileDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const data_ = Array.isArray(data) ? data : [data] if (!data_.length) { @@ -582,7 +575,7 @@ export default class FulfillmentModuleService< | FulfillmentTypes.CreateShippingOptionRuleDTO[] | FulfillmentTypes.CreateShippingOptionRuleDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const data_ = Array.isArray(data) ? data : [data] if (!data_.length) { @@ -698,24 +691,28 @@ export default class FulfillmentModuleService< ) } - update( + // @ts-expect-error + updateFulfillmentSets( data: FulfillmentTypes.UpdateFulfillmentSetDTO[], sharedContext?: Context ): Promise - update( + updateFulfillmentSets( data: FulfillmentTypes.UpdateFulfillmentSetDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") @EmitEvents() - async update( + async updateFulfillmentSets( data: UpdateFulfillmentSetDTO[] | UpdateFulfillmentSetDTO, @MedusaContext() sharedContext: Context = {} ): Promise< FulfillmentTypes.FulfillmentSetDTO[] | FulfillmentTypes.FulfillmentSetDTO > { - const updatedFulfillmentSets = await this.update_(data, sharedContext) + const updatedFulfillmentSets = await this.updateFulfillmentSets_( + data, + sharedContext + ) return await this.baseRepository_.serialize< FulfillmentTypes.FulfillmentSetDTO | FulfillmentTypes.FulfillmentSetDTO[] @@ -723,10 +720,10 @@ export default class FulfillmentModuleService< } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updateFulfillmentSets_( data: UpdateFulfillmentSetDTO[] | UpdateFulfillmentSetDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const data_ = Array.isArray(data) ? data : [data] if (!data_.length) { @@ -765,7 +762,7 @@ export default class FulfillmentModuleService< ) } - const fulfillmentSetMap = new Map( + const fulfillmentSetMap = new Map( fulfillmentSets.map((f) => [f.id, f]) ) @@ -989,7 +986,7 @@ export default class FulfillmentModuleService< | FulfillmentTypes.UpdateServiceZoneDTO[] | FulfillmentTypes.UpdateServiceZoneDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const data_ = Array.isArray(data) ? data : [data] if (!data_.length) { @@ -1028,7 +1025,7 @@ export default class FulfillmentModuleService< ) } - const serviceZoneMap = new Map( + const serviceZoneMap = new Map( serviceZones.map((s) => [s.id, s]) ) @@ -1185,7 +1182,7 @@ export default class FulfillmentModuleService< | FulfillmentTypes.UpsertServiceZoneDTO[] | FulfillmentTypes.UpsertServiceZoneDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const input = Array.isArray(data) ? data : [data] const forUpdate = input.filter( (serviceZone): serviceZone is FulfillmentTypes.UpdateServiceZoneDTO => @@ -1196,8 +1193,8 @@ export default class FulfillmentModuleService< !serviceZone.id ) - const created: TServiceZoneEntity[] = [] - const updated: TServiceZoneEntity[] = [] + const created: ServiceZone[] = [] + const updated: ServiceZone[] = [] if (forCreate.length) { const createdServiceZones = await this.createServiceZones_( @@ -1280,7 +1277,7 @@ export default class FulfillmentModuleService< async updateShippingOptions_( data: UpdateShippingOptionsInput[] | UpdateShippingOptionsInput, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const dataArray = Array.isArray(data) ? data : [data] if (!dataArray.length) { @@ -1506,7 +1503,7 @@ export default class FulfillmentModuleService< | FulfillmentTypes.UpsertShippingOptionDTO[] | FulfillmentTypes.UpsertShippingOptionDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const input = Array.isArray(data) ? data : [data] const forUpdate = input.filter( (shippingOption): shippingOption is UpdateShippingOptionsInput => @@ -1519,8 +1516,8 @@ export default class FulfillmentModuleService< !shippingOption.id ) - let created: TShippingOptionEntity[] = [] - let updated: TShippingOptionEntity[] = [] + let created: ShippingOption[] = [] + let updated: ShippingOption[] = [] if (forCreate.length) { const createdShippingOptions = await this.createShippingOptions_( @@ -1731,7 +1728,7 @@ export default class FulfillmentModuleService< | FulfillmentTypes.UpdateShippingOptionRuleDTO[] | FulfillmentTypes.UpdateShippingOptionRuleDTO, @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const data_ = Array.isArray(data) ? data : [data] if (!data_.length) { @@ -1772,8 +1769,8 @@ export default class FulfillmentModuleService< id: string, data: FulfillmentTypes.UpdateFulfillmentDTO, @MedusaContext() sharedContext: Context - ): Promise { - const existingFulfillment: TFulfillmentEntity = + ): Promise { + const existingFulfillment: Fulfillment = await this.fulfillmentService_.retrieve( id, { diff --git a/packages/modules/inventory-next/integration-tests/__tests__/inventory-module-service.spec.ts b/packages/modules/inventory-next/integration-tests/__tests__/inventory-module-service.spec.ts index 6d07dbed03..f5644bc43d 100644 --- a/packages/modules/inventory-next/integration-tests/__tests__/inventory-module-service.spec.ts +++ b/packages/modules/inventory-next/integration-tests/__tests__/inventory-module-service.spec.ts @@ -1,22 +1,18 @@ -import { IInventoryServiceNext, InventoryItemDTO } from "@medusajs/types" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { IInventoryService, InventoryItemDTO } from "@medusajs/types" +import { moduleIntegrationTestRunner } from "medusa-test-utils" -import { Modules } from "@medusajs/modules-sdk" +import { ModuleRegistrationName, Modules } from "@medusajs/modules-sdk" jest.setTimeout(100000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.INVENTORY, - resolve: "@medusajs/inventory-next", - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Inventory Module Service", () => { describe("create", () => { it("should create an inventory item", async () => { const data = { sku: "test-sku", origin_country: "test-country" } - const inventoryItem = await service.create(data) + const inventoryItem = await service.createInventoryItems(data) expect(inventoryItem).toEqual( expect.objectContaining({ id: expect.any(String), ...data }) @@ -28,7 +24,7 @@ moduleIntegrationTestRunner({ { sku: "test-sku", origin_country: "test-country" }, { sku: "test-sku-1", origin_country: "test-country-1" }, ] - const inventoryItems = await service.create(data) + const inventoryItems = await service.createInventoryItems(data) expect(inventoryItems).toEqual([ expect.objectContaining({ id: expect.any(String), ...data[0] }), @@ -40,7 +36,7 @@ moduleIntegrationTestRunner({ describe("createReservationItem", () => { let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -169,7 +165,7 @@ moduleIntegrationTestRunner({ let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -234,7 +230,7 @@ moduleIntegrationTestRunner({ let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -245,13 +241,13 @@ moduleIntegrationTestRunner({ id: inventoryItem.id, sku: "updated-sku", } - const updated = await service.update(update) + const updated = await service.updateInventoryItems(update) expect(updated).toEqual(expect.objectContaining(update)) }) it("should update multiple inventory items", async () => { - const item2 = await service.create({ + const item2 = await service.createInventoryItems({ sku: "test-sku-1", }) @@ -265,7 +261,7 @@ moduleIntegrationTestRunner({ sku: "updated-sku-2", }, ] - const updated = await service.update(updates) + const updated = await service.updateInventoryItems(updates) expect(updated).toEqual([ expect.objectContaining(updates[0]), @@ -279,7 +275,7 @@ moduleIntegrationTestRunner({ let inventoryItem beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -323,7 +319,7 @@ moduleIntegrationTestRunner({ let inventoryItem beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -413,7 +409,7 @@ moduleIntegrationTestRunner({ let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -526,7 +522,7 @@ moduleIntegrationTestRunner({ describe("deleteReservationItemByLocationId", () => { let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -619,7 +615,7 @@ moduleIntegrationTestRunner({ let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -681,7 +677,7 @@ moduleIntegrationTestRunner({ describe("deleteInventoryLevel", () => { let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -720,7 +716,7 @@ moduleIntegrationTestRunner({ describe("adjustInventory", () => { let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) @@ -756,11 +752,11 @@ moduleIntegrationTestRunner({ describe("retrieveInventoryLevelByItemAndLocation", () => { let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) - const inventoryItem1 = await service.create({ + const inventoryItem1 = await service.createInventoryItems({ sku: "test-sku-1", origin_country: "test-country", }) @@ -797,11 +793,11 @@ moduleIntegrationTestRunner({ let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) - const inventoryItem1 = await service.create({ + const inventoryItem1 = await service.createInventoryItems({ sku: "test-sku-1", origin_country: "test-country", }) @@ -851,12 +847,12 @@ moduleIntegrationTestRunner({ let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) - const inventoryItem1 = await service.create({ + const inventoryItem1 = await service.createInventoryItems({ sku: "test-sku-1", origin_country: "test-country", }) @@ -899,12 +895,12 @@ moduleIntegrationTestRunner({ let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) - const inventoryItem1 = await service.create({ + const inventoryItem1 = await service.createInventoryItems({ sku: "test-sku-1", origin_country: "test-country", }) @@ -965,7 +961,7 @@ moduleIntegrationTestRunner({ let inventoryItem: InventoryItemDTO beforeEach(async () => { - inventoryItem = await service.create({ + inventoryItem = await service.createInventoryItems({ sku: "test-sku", origin_country: "test-country", }) diff --git a/packages/modules/inventory-next/package.json b/packages/modules/inventory-next/package.json index 66290e2beb..09676bf2fb 100644 --- a/packages/modules/inventory-next/package.json +++ b/packages/modules/inventory-next/package.json @@ -15,7 +15,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/inventory-next/src/index.ts b/packages/modules/inventory-next/src/index.ts index 5fb9170fa0..a00d955d7d 100644 --- a/packages/modules/inventory-next/src/index.ts +++ b/packages/modules/inventory-next/src/index.ts @@ -1,6 +1,7 @@ -import { moduleDefinition } from "./module-definition" - -export * from "./models" -export * from "./services" +import { ModuleExports } from "@medusajs/types" +import InventoryService from "./services/inventory-module" +const moduleDefinition: ModuleExports = { + service: InventoryService, +} export default moduleDefinition diff --git a/packages/modules/inventory-next/src/joiner-config.ts b/packages/modules/inventory-next/src/joiner-config.ts index 7e007f6cba..fef4b81e5b 100644 --- a/packages/modules/inventory-next/src/joiner-config.ts +++ b/packages/modules/inventory-next/src/joiner-config.ts @@ -1,40 +1,17 @@ -import { InventoryItem, InventoryLevel, ReservationItem } from "./models" - -import { MapToConfig } from "@medusajs/utils" -import { ModuleJoinerConfig } from "@medusajs/types" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" import { Modules } from "@medusajs/modules-sdk" -import moduleSchema from "./schema" -export const LinkableKeys = { - inventory_item_id: InventoryItem.name, - inventory_level_id: InventoryLevel.name, - reservation_item_id: ReservationItem.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.INVENTORY, - primaryKeys: ["id"], - linkableKeys: { - inventory_item_id: InventoryItem.name, - inventory_level_id: InventoryLevel.name, - reservation_item_id: ReservationItem.name, - }, - schema: moduleSchema, +export const joinerConfig = defineJoinerConfig(Modules.INVENTORY, { alias: [ { name: ["inventory_items", "inventory_item", "inventory"], args: { entity: "InventoryItem", + methodSuffix: "InventoryItems", }, }, { @@ -57,4 +34,7 @@ export const joinerConfig: ModuleJoinerConfig = { }, }, ], -} +}) + +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/inventory-next/src/module-definition.ts b/packages/modules/inventory-next/src/module-definition.ts deleted file mode 100644 index c55dc2e8ce..0000000000 --- a/packages/modules/inventory-next/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import InventoryService from "./services/inventory-module" - -const service = InventoryService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/inventory-next/src/services/inventory-module.ts b/packages/modules/inventory-next/src/services/inventory-module.ts index 5185dff8ed..1b2fe6007e 100644 --- a/packages/modules/inventory-next/src/services/inventory-module.ts +++ b/packages/modules/inventory-next/src/services/inventory-module.ts @@ -2,8 +2,6 @@ import { InternalModuleDeclaration } from "@medusajs/modules-sdk" import { Context, DAL, - IInventoryServiceNext, - InventoryNext, InventoryTypes, ModuleJoinerConfig, ModulesSdkTypes, @@ -20,13 +18,14 @@ import { isString, MedusaContext, MedusaError, - ModulesSdkUtils, + MedusaService, partitionArray, promiseAll, } from "@medusajs/utils" import { InventoryItem, InventoryLevel, ReservationItem } from "@models" import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" import InventoryLevelService from "./inventory-level" +import { IInventoryService } from "@medusajs/types/dist/inventory" type InjectedDependencies = { baseRepository: DAL.RepositoryService @@ -35,38 +34,32 @@ type InjectedDependencies = { reservationItemService: ModulesSdkTypes.IMedusaInternalService } -const generateMethodForModels = { - InventoryItem, - InventoryLevel, - ReservationItem, -} - -export default class InventoryModuleService< - TInventoryItem extends InventoryItem = InventoryItem, - TInventoryLevel extends InventoryLevel = InventoryLevel, - TReservationItem extends ReservationItem = ReservationItem - > - extends ModulesSdkUtils.MedusaService< - InventoryNext.InventoryItemDTO, - { - InventoryItem: { - dto: InventoryNext.InventoryItemDTO - } - InventoryLevel: { - dto: InventoryNext.InventoryLevelDTO - } - ReservationItem: { - dto: InventoryNext.ReservationItemDTO - } +export default class InventoryModuleService + extends MedusaService<{ + InventoryItem: { + dto: InventoryTypes.InventoryItemDTO } - >(InventoryItem, generateMethodForModels, entityNameToLinkableKeysMap) - implements IInventoryServiceNext + InventoryLevel: { + dto: InventoryTypes.InventoryLevelDTO + } + ReservationItem: { + dto: InventoryTypes.ReservationItemDTO + } + }>( + { + InventoryItem, + InventoryLevel, + ReservationItem, + }, + entityNameToLinkableKeysMap + ) + implements IInventoryService { protected baseRepository_: DAL.RepositoryService - protected readonly inventoryItemService_: ModulesSdkTypes.IMedusaInternalService - protected readonly reservationItemService_: ModulesSdkTypes.IMedusaInternalService - protected readonly inventoryLevelService_: InventoryLevelService + protected readonly inventoryItemService_: ModulesSdkTypes.IMedusaInternalService + protected readonly reservationItemService_: ModulesSdkTypes.IMedusaInternalService + protected readonly inventoryLevelService_: InventoryLevelService constructor( { @@ -97,7 +90,7 @@ export default class InventoryModuleService< | { id: string } )[], context: Context - ): Promise { + ): Promise { const [idData, itemLocationData] = partitionArray( data, ({ id }) => !!id @@ -117,12 +110,12 @@ export default class InventoryModuleService< context ) - const inventoryLevelIdMap: Map = + const inventoryLevelIdMap: Map = new Map(inventoryLevels.map((level) => [level.id, level])) const inventoryLevelItemLocationMap: Map< string, - Map + Map > = inventoryLevels.reduce((acc, curr) => { const inventoryLevelMap = acc.get(curr.inventory_item_id) ?? new Map() inventoryLevelMap.set(curr.location_id, curr) @@ -214,23 +207,23 @@ export default class InventoryModuleService< // @ts-ignore async createReservationItems( - input: InventoryNext.CreateReservationItemInput[], + input: InventoryTypes.CreateReservationItemInput[], context?: Context - ): Promise + ): Promise async createReservationItems( - input: InventoryNext.CreateReservationItemInput, + input: InventoryTypes.CreateReservationItemInput, context?: Context - ): Promise + ): Promise @InjectManager("baseRepository_") @EmitEvents() async createReservationItems( input: - | InventoryNext.CreateReservationItemInput[] - | InventoryNext.CreateReservationItemInput, + | InventoryTypes.CreateReservationItemInput[] + | InventoryTypes.CreateReservationItemInput, @MedusaContext() context: Context = {} ): Promise< - InventoryNext.ReservationItemDTO[] | InventoryNext.ReservationItemDTO + InventoryTypes.ReservationItemDTO[] | InventoryTypes.ReservationItemDTO > { const toCreate = Array.isArray(input) ? input : [input] const sanitized = toCreate.map((d) => ({ @@ -254,7 +247,7 @@ export default class InventoryModuleService< ) const serializedReservations = await this.baseRepository_.serialize< - InventoryNext.ReservationItemDTO[] | InventoryNext.ReservationItemDTO + InventoryTypes.ReservationItemDTO[] | InventoryTypes.ReservationItemDTO >(created, { populate: true, }) @@ -266,9 +259,9 @@ export default class InventoryModuleService< @InjectTransactionManager("baseRepository_") async createReservationItems_( - input: InventoryNext.CreateReservationItemInput[], + input: InventoryTypes.CreateReservationItemInput[], @MedusaContext() context: Context = {} - ): Promise { + ): Promise { const inventoryLevels = await this.ensureInventoryLevels( input.map(({ location_id, inventory_item_id }) => ({ location_id, @@ -311,30 +304,25 @@ export default class InventoryModuleService< return created } - /** - * Creates an inventory item - * @param input - the input object - * @param context - * @return The created inventory item - */ - create( - input: InventoryNext.CreateInventoryItemInput, + // @ts-expect-error + createInventoryItems( + input: InventoryTypes.CreateInventoryItemInput, context?: Context - ): Promise - create( - input: InventoryNext.CreateInventoryItemInput[], + ): Promise + createInventoryItems( + input: InventoryTypes.CreateInventoryItemInput[], context?: Context - ): Promise + ): Promise @InjectManager("baseRepository_") @EmitEvents() - async create( + async createInventoryItems( input: - | InventoryNext.CreateInventoryItemInput - | InventoryNext.CreateInventoryItemInput[], + | InventoryTypes.CreateInventoryItemInput + | InventoryTypes.CreateInventoryItemInput[], @MedusaContext() context: Context = {} ): Promise< - InventoryNext.InventoryItemDTO | InventoryNext.InventoryItemDTO[] + InventoryTypes.InventoryItemDTO | InventoryTypes.InventoryItemDTO[] > { const toCreate = this.sanitizeInventoryItemInput( Array.isArray(input) ? input : [input] @@ -353,7 +341,7 @@ export default class InventoryModuleService< ) const serializedItems = await this.baseRepository_.serialize< - InventoryNext.InventoryItemDTO | InventoryNext.InventoryItemDTO[] + InventoryTypes.InventoryItemDTO | InventoryTypes.InventoryItemDTO[] >(result, { populate: true, }) @@ -363,31 +351,31 @@ export default class InventoryModuleService< @InjectTransactionManager("baseRepository_") async createInventoryItems_( - input: InventoryNext.CreateInventoryItemInput[], + input: InventoryTypes.CreateInventoryItemInput[], @MedusaContext() context: Context = {} - ): Promise { + ): Promise { return await this.inventoryItemService_.create(input) } // @ts-ignore createInventoryLevels( - input: InventoryNext.CreateInventoryLevelInput, + input: InventoryTypes.CreateInventoryLevelInput, context?: Context - ): Promise + ): Promise createInventoryLevels( - input: InventoryNext.CreateInventoryLevelInput[], + input: InventoryTypes.CreateInventoryLevelInput[], context?: Context - ): Promise + ): Promise @InjectManager("baseRepository_") @EmitEvents() async createInventoryLevels( input: - | InventoryNext.CreateInventoryLevelInput[] - | InventoryNext.CreateInventoryLevelInput, + | InventoryTypes.CreateInventoryLevelInput[] + | InventoryTypes.CreateInventoryLevelInput, @MedusaContext() context: Context = {} ): Promise< - InventoryNext.InventoryLevelDTO[] | InventoryNext.InventoryLevelDTO + InventoryTypes.InventoryLevelDTO[] | InventoryTypes.InventoryLevelDTO > { const toCreate = this.sanitizeInventoryLevelInput( Array.isArray(input) ? input : [input] @@ -407,7 +395,7 @@ export default class InventoryModuleService< ) const serialized = await this.baseRepository_.serialize< - InventoryNext.InventoryLevelDTO[] | InventoryNext.InventoryLevelDTO + InventoryTypes.InventoryLevelDTO[] | InventoryTypes.InventoryLevelDTO >(created, { populate: true, }) @@ -417,37 +405,31 @@ export default class InventoryModuleService< @InjectTransactionManager("baseRepository_") async createInventoryLevels_( - input: InventoryNext.CreateInventoryLevelInput[], + input: InventoryTypes.CreateInventoryLevelInput[], @MedusaContext() context: Context = {} - ): Promise { + ): Promise { return await this.inventoryLevelService_.create(input, context) } - /** - * Updates inventory items - * @param inventoryItemId - the id of the inventory item to update - * @param input - the input object - * @param context - * @return The updated inventory item - */ - update( - input: InventoryNext.UpdateInventoryItemInput[], + // @ts-expect-error + updateInventoryItems( + input: InventoryTypes.UpdateInventoryItemInput[], context?: Context - ): Promise - update( - input: InventoryNext.UpdateInventoryItemInput, + ): Promise + updateInventoryItems( + input: InventoryTypes.UpdateInventoryItemInput, context?: Context - ): Promise + ): Promise @InjectManager("baseRepository_") @EmitEvents() - async update( + async updateInventoryItems( input: - | InventoryNext.UpdateInventoryItemInput - | InventoryNext.UpdateInventoryItemInput[], + | InventoryTypes.UpdateInventoryItemInput + | InventoryTypes.UpdateInventoryItemInput[], @MedusaContext() context: Context = {} ): Promise< - InventoryNext.InventoryItemDTO | InventoryNext.InventoryItemDTO[] + InventoryTypes.InventoryItemDTO | InventoryTypes.InventoryItemDTO[] > { const updates = this.sanitizeInventoryItemInput( Array.isArray(input) ? input : [input] @@ -467,7 +449,7 @@ export default class InventoryModuleService< ) const serializedItems = await this.baseRepository_.serialize< - InventoryNext.InventoryItemDTO | InventoryNext.InventoryItemDTO[] + InventoryTypes.InventoryItemDTO | InventoryTypes.InventoryItemDTO[] >(result, { populate: true, }) @@ -477,9 +459,11 @@ export default class InventoryModuleService< @InjectTransactionManager("baseRepository_") async updateInventoryItems_( - input: (Partial & { id: string })[], + input: (Partial & { + id: string + })[], @MedusaContext() context: Context = {} - ): Promise { + ): Promise { return await this.inventoryItemService_.update(input, context) } @@ -546,11 +530,11 @@ export default class InventoryModuleService< async updateInventoryLevels( updates: InventoryTypes.BulkUpdateInventoryLevelInput[], context?: Context - ): Promise + ): Promise async updateInventoryLevels( updates: InventoryTypes.BulkUpdateInventoryLevelInput, context?: Context - ): Promise + ): Promise @InjectManager("baseRepository_") @EmitEvents() @@ -560,7 +544,7 @@ export default class InventoryModuleService< | InventoryTypes.BulkUpdateInventoryLevelInput, @MedusaContext() context: Context = {} ): Promise< - InventoryNext.InventoryLevelDTO | InventoryNext.InventoryLevelDTO[] + InventoryTypes.InventoryLevelDTO | InventoryTypes.InventoryLevelDTO[] > { const input = this.sanitizeInventoryLevelInput( Array.isArray(updates) ? updates : [updates] @@ -580,8 +564,7 @@ export default class InventoryModuleService< ) const updatedLevels = await this.baseRepository_.serialize< - | InventoryTypes.InventoryNext.InventoryLevelDTO - | InventoryTypes.InventoryNext.InventoryLevelDTO[] + InventoryTypes.InventoryLevelDTO | InventoryTypes.InventoryLevelDTO[] >(levels, { populate: true, }) @@ -631,23 +614,23 @@ export default class InventoryModuleService< */ // @ts-ignore async updateReservationItems( - input: InventoryNext.UpdateReservationItemInput[], + input: InventoryTypes.UpdateReservationItemInput[], context?: Context - ): Promise + ): Promise async updateReservationItems( - input: InventoryNext.UpdateReservationItemInput, + input: InventoryTypes.UpdateReservationItemInput, context?: Context - ): Promise + ): Promise @InjectManager("baseRepository_") @EmitEvents() async updateReservationItems( input: - | InventoryNext.UpdateReservationItemInput - | InventoryNext.UpdateReservationItemInput[], + | InventoryTypes.UpdateReservationItemInput + | InventoryTypes.UpdateReservationItemInput[], @MedusaContext() context: Context = {} ): Promise< - InventoryNext.ReservationItemDTO | InventoryNext.ReservationItemDTO[] + InventoryTypes.ReservationItemDTO | InventoryTypes.ReservationItemDTO[] > { const update = Array.isArray(input) ? input : [input] const result = await this.updateReservationItems_(update, context) @@ -664,7 +647,7 @@ export default class InventoryModuleService< ) const serialized = await this.baseRepository_.serialize< - InventoryNext.ReservationItemDTO | InventoryNext.ReservationItemDTO[] + InventoryTypes.ReservationItemDTO | InventoryTypes.ReservationItemDTO[] >(result, { populate: true, }) @@ -674,9 +657,9 @@ export default class InventoryModuleService< @InjectTransactionManager("baseRepository_") async updateReservationItems_( - input: (InventoryNext.UpdateReservationItemInput & { id: string })[], + input: (InventoryTypes.UpdateReservationItemInput & { id: string })[], @MedusaContext() context: Context = {} - ): Promise { + ): Promise { const ids = input.map((u) => u.id) const reservationItems = await this.listReservationItems( { id: ids }, @@ -797,7 +780,7 @@ export default class InventoryModuleService< locationId: string | string[], @MedusaContext() context: Context = {} ): Promise { - const reservations: InventoryNext.ReservationItemDTO[] = + const reservations: InventoryTypes.ReservationItemDTO[] = await this.listReservationItems({ location_id: locationId }, {}, context) await this.reservationItemService_.softDelete( @@ -834,7 +817,7 @@ export default class InventoryModuleService< lineItemId: string | string[], @MedusaContext() context: Context = {} ): Promise { - const reservations: InventoryNext.ReservationItemDTO[] = + const reservations: InventoryTypes.ReservationItemDTO[] = await this.listReservationItems({ line_item_id: lineItemId }, {}, context) await this.reservationItemService_.softDelete( @@ -871,7 +854,7 @@ export default class InventoryModuleService< lineItemId: string | string[], @MedusaContext() context: Context = {} ): Promise { - const reservations: InventoryNext.ReservationItemDTO[] = + const reservations: InventoryTypes.ReservationItemDTO[] = await this.listReservationItems({ line_item_id: lineItemId }, {}, context) await this.reservationItemService_.restore( @@ -910,7 +893,7 @@ export default class InventoryModuleService< locationId: string, adjustment: number, context: Context - ): Promise + ): Promise adjustInventory( data: { @@ -919,7 +902,7 @@ export default class InventoryModuleService< adjustment: number }[], context: Context - ): Promise + ): Promise @InjectManager("baseRepository_") @EmitEvents() @@ -929,7 +912,7 @@ export default class InventoryModuleService< adjustment?: number, @MedusaContext() context: Context = {} ): Promise< - InventoryNext.InventoryLevelDTO | InventoryNext.InventoryLevelDTO[] + InventoryTypes.InventoryLevelDTO | InventoryTypes.InventoryLevelDTO[] > { let all: any = inventoryItemIdOrData @@ -943,7 +926,7 @@ export default class InventoryModuleService< ] } - const results: TInventoryLevel[] = [] + const results: InventoryLevel[] = [] for (const data of all) { const result = await this.adjustInventory_( @@ -964,7 +947,7 @@ export default class InventoryModuleService< }) } - return await this.baseRepository_.serialize( + return await this.baseRepository_.serialize( Array.isArray(inventoryItemIdOrData) ? results : results[0], { populate: true, @@ -978,7 +961,7 @@ export default class InventoryModuleService< locationId: string, adjustment: number, @MedusaContext() context: Context = {} - ): Promise { + ): Promise { const inventoryLevel = await this.retrieveInventoryLevelByItemAndLocation( inventoryItemId, locationId, @@ -1001,7 +984,7 @@ export default class InventoryModuleService< inventoryItemId: string, locationId: string, @MedusaContext() context: Context = {} - ): Promise { + ): Promise { const [inventoryLevel] = await this.listInventoryLevels( { inventory_item_id: inventoryItemId, location_id: locationId }, { take: 1 }, diff --git a/packages/modules/link-modules/package.json b/packages/modules/link-modules/package.json index efe843b304..4ab73ec0bc 100644 --- a/packages/modules/link-modules/package.json +++ b/packages/modules/link-modules/package.json @@ -16,7 +16,7 @@ "access": "public" }, "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/link-modules/src/definitions/cart-payment-collection.ts b/packages/modules/link-modules/src/definitions/cart-payment-collection.ts index dd35089522..acd2fabbc9 100644 --- a/packages/modules/link-modules/src/definitions/cart-payment-collection.ts +++ b/packages/modules/link-modules/src/definitions/cart-payment-collection.ts @@ -24,12 +24,18 @@ export const CartPaymentCollection: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "cart_id", alias: "cart", + args: { + methodSuffix: "Carts", + }, }, { serviceName: Modules.PAYMENT, primaryKey: "id", foreignKey: "payment_collection_id", alias: "payment_collection", + args: { + methodSuffix: "PaymentCollections", + }, }, ], extends: [ diff --git a/packages/modules/link-modules/src/definitions/cart-promotion.ts b/packages/modules/link-modules/src/definitions/cart-promotion.ts index 2b595f64f5..c8322d4467 100644 --- a/packages/modules/link-modules/src/definitions/cart-promotion.ts +++ b/packages/modules/link-modules/src/definitions/cart-promotion.ts @@ -24,12 +24,18 @@ export const CartPromotion: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "cart_id", alias: "cart", + args: { + methodSuffix: "Carts", + }, }, { serviceName: Modules.PROMOTION, primaryKey: "id", foreignKey: "promotion_id", alias: "promotions", + args: { + methodSuffix: "Promotions", + }, }, ], extends: [ diff --git a/packages/modules/link-modules/src/definitions/fulfillment-set-location.ts b/packages/modules/link-modules/src/definitions/fulfillment-set-location.ts index 579d01afdb..9f23d73b62 100644 --- a/packages/modules/link-modules/src/definitions/fulfillment-set-location.ts +++ b/packages/modules/link-modules/src/definitions/fulfillment-set-location.ts @@ -24,12 +24,18 @@ export const LocationFulfillmentSet: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "stock_location_id", alias: "location", + args: { + methodSuffix: "StockLocations", + }, }, { serviceName: Modules.FULFILLMENT, primaryKey: "id", foreignKey: "fulfillment_set_id", alias: "fulfillment_set", + args: { + methodSuffix: "FulfillmentSets", + }, deleteCascade: true, }, ], diff --git a/packages/modules/link-modules/src/definitions/order-cart.ts b/packages/modules/link-modules/src/definitions/order-cart.ts index f48dce4380..9621fbfd61 100644 --- a/packages/modules/link-modules/src/definitions/order-cart.ts +++ b/packages/modules/link-modules/src/definitions/order-cart.ts @@ -24,12 +24,18 @@ export const OrderCart: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "order_id", alias: "order", + args: { + methodSuffix: "Orders", + }, }, { serviceName: Modules.CART, primaryKey: "id", foreignKey: "cart_id", alias: "cart", + args: { + methodSuffix: "Carts", + }, }, ], extends: [ diff --git a/packages/modules/link-modules/src/definitions/order-fulfillment.ts b/packages/modules/link-modules/src/definitions/order-fulfillment.ts index d64c155ab1..3542e1577e 100644 --- a/packages/modules/link-modules/src/definitions/order-fulfillment.ts +++ b/packages/modules/link-modules/src/definitions/order-fulfillment.ts @@ -24,6 +24,9 @@ export const OrderFulfillment: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "order_id", alias: "order", + args: { + methodSuffix: "Orders", + }, }, { serviceName: Modules.FULFILLMENT, diff --git a/packages/modules/link-modules/src/definitions/order-payment-collection.ts b/packages/modules/link-modules/src/definitions/order-payment-collection.ts index f309498ec9..5327afbe3c 100644 --- a/packages/modules/link-modules/src/definitions/order-payment-collection.ts +++ b/packages/modules/link-modules/src/definitions/order-payment-collection.ts @@ -24,12 +24,18 @@ export const OrderPaymentCollection: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "order_id", alias: "order", + args: { + methodSuffix: "Orders", + }, }, { serviceName: Modules.PAYMENT, primaryKey: "id", foreignKey: "payment_collection_id", alias: "payment_collection", + args: { + methodSuffix: "PaymentCollections", + }, }, ], extends: [ diff --git a/packages/modules/link-modules/src/definitions/order-promotion.ts b/packages/modules/link-modules/src/definitions/order-promotion.ts index feaf8d65e5..e701ca71a1 100644 --- a/packages/modules/link-modules/src/definitions/order-promotion.ts +++ b/packages/modules/link-modules/src/definitions/order-promotion.ts @@ -24,12 +24,18 @@ export const OrderPromotion: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "order_id", alias: "order", + args: { + methodSuffix: "Orders", + }, }, { serviceName: Modules.PROMOTION, primaryKey: "id", foreignKey: "promotion_id", alias: "promotion", + args: { + methodSuffix: "Promotions", + }, }, ], extends: [ diff --git a/packages/modules/link-modules/src/definitions/product-sales-channel.ts b/packages/modules/link-modules/src/definitions/product-sales-channel.ts index ea36bd18a7..f3a7efac99 100644 --- a/packages/modules/link-modules/src/definitions/product-sales-channel.ts +++ b/packages/modules/link-modules/src/definitions/product-sales-channel.ts @@ -24,12 +24,18 @@ export const ProductSalesChannel: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "product_id", alias: "product", + args: { + methodSuffix: "Products", + }, }, { serviceName: Modules.SALES_CHANNEL, primaryKey: "id", foreignKey: "sales_channel_id", alias: "sales_channel", + args: { + methodSuffix: "SalesChannels", + }, }, ], extends: [ diff --git a/packages/modules/link-modules/src/definitions/product-variant-inventory-item.ts b/packages/modules/link-modules/src/definitions/product-variant-inventory-item.ts index a4687d493c..d75ef5f261 100644 --- a/packages/modules/link-modules/src/definitions/product-variant-inventory-item.ts +++ b/packages/modules/link-modules/src/definitions/product-variant-inventory-item.ts @@ -34,7 +34,7 @@ export const ProductVariantInventoryItem: ModuleJoinerConfig = { foreignKey: "variant_id", alias: "variant", args: { - methodSuffix: "Variants", + methodSuffix: "ProductVariants", }, }, { @@ -42,6 +42,9 @@ export const ProductVariantInventoryItem: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "inventory_item_id", alias: "inventory", + args: { + methodSuffix: "InventoryItems", + }, deleteCascade: true, }, ], diff --git a/packages/modules/link-modules/src/definitions/product-variant-price-set.ts b/packages/modules/link-modules/src/definitions/product-variant-price-set.ts index 54c441cd18..e2f80a678a 100644 --- a/packages/modules/link-modules/src/definitions/product-variant-price-set.ts +++ b/packages/modules/link-modules/src/definitions/product-variant-price-set.ts @@ -25,7 +25,7 @@ export const ProductVariantPriceSet: ModuleJoinerConfig = { foreignKey: "variant_id", alias: "variant", args: { - methodSuffix: "Variants", + methodSuffix: "ProductVariants", }, }, { @@ -33,6 +33,9 @@ export const ProductVariantPriceSet: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "price_set_id", alias: "price_set", + args: { + methodSuffix: "PriceSets", + }, deleteCascade: true, }, ], diff --git a/packages/modules/link-modules/src/definitions/publishable-api-key-sales-channel.ts b/packages/modules/link-modules/src/definitions/publishable-api-key-sales-channel.ts index 0d4bb07780..9da3cb1133 100644 --- a/packages/modules/link-modules/src/definitions/publishable-api-key-sales-channel.ts +++ b/packages/modules/link-modules/src/definitions/publishable-api-key-sales-channel.ts @@ -24,12 +24,18 @@ export const PublishableApiKeySalesChannel: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "publishable_key_id", alias: "api_key", + args: { + methodSuffix: "ApiKeys", + }, }, { serviceName: Modules.SALES_CHANNEL, primaryKey: "id", foreignKey: "sales_channel_id", alias: "sales_channel", + args: { + methodSuffix: "SalesChannels", + }, }, ], extends: [ diff --git a/packages/modules/link-modules/src/definitions/readonly/cart-customer.ts b/packages/modules/link-modules/src/definitions/readonly/cart-customer.ts index b32bb9eff7..30b8437803 100644 --- a/packages/modules/link-modules/src/definitions/readonly/cart-customer.ts +++ b/packages/modules/link-modules/src/definitions/readonly/cart-customer.ts @@ -12,6 +12,9 @@ export const CartCustomer: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "customer_id", alias: "customer", + args: { + methodSuffix: "Customers", + }, }, }, { @@ -21,6 +24,9 @@ export const CartCustomer: ModuleJoinerConfig = { primaryKey: "customer_id", foreignKey: "id", alias: "carts", + args: { + methodSuffix: "Carts", + }, isList: true, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/cart-product.ts b/packages/modules/link-modules/src/definitions/readonly/cart-product.ts index 610b1b960b..a494d9d584 100644 --- a/packages/modules/link-modules/src/definitions/readonly/cart-product.ts +++ b/packages/modules/link-modules/src/definitions/readonly/cart-product.ts @@ -12,6 +12,9 @@ export const CartProduct: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "items.product_id", alias: "product", + args: { + methodSuffix: "Products", + }, }, }, { @@ -22,7 +25,7 @@ export const CartProduct: ModuleJoinerConfig = { foreignKey: "items.variant_id", alias: "variant", args: { - methodSuffix: "Variants", + methodSuffix: "ProductVariants", }, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/cart-region.ts b/packages/modules/link-modules/src/definitions/readonly/cart-region.ts index 7cf54ca125..f7428fc02d 100644 --- a/packages/modules/link-modules/src/definitions/readonly/cart-region.ts +++ b/packages/modules/link-modules/src/definitions/readonly/cart-region.ts @@ -12,6 +12,9 @@ export const CartRegion: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "region_id", alias: "region", + args: { + methodSuffix: "Regions", + }, }, }, { @@ -21,6 +24,9 @@ export const CartRegion: ModuleJoinerConfig = { primaryKey: "region_id", foreignKey: "id", alias: "carts", + args: { + methodSuffix: "Carts", + }, isList: true, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/cart-sales-channel.ts b/packages/modules/link-modules/src/definitions/readonly/cart-sales-channel.ts index b3c949973c..5e1cc94510 100644 --- a/packages/modules/link-modules/src/definitions/readonly/cart-sales-channel.ts +++ b/packages/modules/link-modules/src/definitions/readonly/cart-sales-channel.ts @@ -12,6 +12,9 @@ export const CartSalesChannel: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "sales_channel_id", alias: "sales_channel", + args: { + methodSuffix: "SalesChannels", + }, }, }, { @@ -21,6 +24,9 @@ export const CartSalesChannel: ModuleJoinerConfig = { primaryKey: "sales_channel_id", foreignKey: "id", alias: "carts", + args: { + methodSuffix: "Carts", + }, isList: true, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/inventory-level-stock-location.ts b/packages/modules/link-modules/src/definitions/readonly/inventory-level-stock-location.ts index e7c6eb4e6a..212f6c7df6 100644 --- a/packages/modules/link-modules/src/definitions/readonly/inventory-level-stock-location.ts +++ b/packages/modules/link-modules/src/definitions/readonly/inventory-level-stock-location.ts @@ -12,6 +12,9 @@ export const InventoryLevelStockLocation: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "location_id", alias: "stock_locations", + args: { + methodSuffix: "StockLocations", + }, isList: true, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/line-item-adjustment-promotion.ts b/packages/modules/link-modules/src/definitions/readonly/line-item-adjustment-promotion.ts index b6df51fb14..57a35b87c6 100644 --- a/packages/modules/link-modules/src/definitions/readonly/line-item-adjustment-promotion.ts +++ b/packages/modules/link-modules/src/definitions/readonly/line-item-adjustment-promotion.ts @@ -12,6 +12,9 @@ export const LineItemAdjustmentPromotion: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "promotion_id", alias: "promotion", + args: { + methodSuffix: "Promotions", + }, }, }, ], diff --git a/packages/modules/link-modules/src/definitions/readonly/order-customer.ts b/packages/modules/link-modules/src/definitions/readonly/order-customer.ts index 03c7bfc852..aea2ee7612 100644 --- a/packages/modules/link-modules/src/definitions/readonly/order-customer.ts +++ b/packages/modules/link-modules/src/definitions/readonly/order-customer.ts @@ -12,6 +12,9 @@ export const OrderCustomer: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "customer_id", alias: "customer", + args: { + methodSuffix: "Customers", + }, }, }, { @@ -21,6 +24,9 @@ export const OrderCustomer: ModuleJoinerConfig = { primaryKey: "customer_id", foreignKey: "id", alias: "orders", + args: { + methodSuffix: "Orders", + }, isList: true, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/order-product.ts b/packages/modules/link-modules/src/definitions/readonly/order-product.ts index 73148abc9a..0a7562aeb4 100644 --- a/packages/modules/link-modules/src/definitions/readonly/order-product.ts +++ b/packages/modules/link-modules/src/definitions/readonly/order-product.ts @@ -12,6 +12,9 @@ export const OrderProduct: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "items.product_id", alias: "product", + args: { + methodSuffix: "Products", + }, }, }, { @@ -22,7 +25,7 @@ export const OrderProduct: ModuleJoinerConfig = { foreignKey: "items.variant_id", alias: "variant", args: { - methodSuffix: "Variants", + methodSuffix: "ProductVariants", }, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/order-region.ts b/packages/modules/link-modules/src/definitions/readonly/order-region.ts index 5c7640c5b5..a09bdb2b6d 100644 --- a/packages/modules/link-modules/src/definitions/readonly/order-region.ts +++ b/packages/modules/link-modules/src/definitions/readonly/order-region.ts @@ -12,6 +12,9 @@ export const OrderRegion: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "region_id", alias: "region", + args: { + methodSuffix: "Regions", + }, }, }, { @@ -21,6 +24,9 @@ export const OrderRegion: ModuleJoinerConfig = { primaryKey: "region_id", foreignKey: "id", alias: "orders", + args: { + methodSuffix: "Orders", + }, isList: true, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/order-sales-channel.ts b/packages/modules/link-modules/src/definitions/readonly/order-sales-channel.ts index 1e86614f66..0b37eb8841 100644 --- a/packages/modules/link-modules/src/definitions/readonly/order-sales-channel.ts +++ b/packages/modules/link-modules/src/definitions/readonly/order-sales-channel.ts @@ -13,6 +13,9 @@ export const OrderSalesChannel: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "sales_channel_id", alias: "sales_channel", + args: { + methodSuffix: "SalesChannels", + }, }, }, { @@ -22,6 +25,9 @@ export const OrderSalesChannel: ModuleJoinerConfig = { primaryKey: "sales_channel_id", foreignKey: "id", alias: "orders", + args: { + methodSuffix: "Orders", + }, isList: true, }, }, diff --git a/packages/modules/link-modules/src/definitions/readonly/store-default-currency.ts b/packages/modules/link-modules/src/definitions/readonly/store-default-currency.ts index b2d3828256..9f0e82402c 100644 --- a/packages/modules/link-modules/src/definitions/readonly/store-default-currency.ts +++ b/packages/modules/link-modules/src/definitions/readonly/store-default-currency.ts @@ -12,6 +12,9 @@ export const StoreDefaultCurrency: ModuleJoinerConfig = { primaryKey: "code", foreignKey: "default_currency_code", alias: "default_currency", + args: { + methodSuffix: "Currencies", + }, }, }, ], diff --git a/packages/modules/link-modules/src/definitions/region-payment-provider.ts b/packages/modules/link-modules/src/definitions/region-payment-provider.ts index 3b98256bc1..71d02ca56e 100644 --- a/packages/modules/link-modules/src/definitions/region-payment-provider.ts +++ b/packages/modules/link-modules/src/definitions/region-payment-provider.ts @@ -24,6 +24,9 @@ export const RegionPaymentProvider: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "region_id", alias: "region", + args: { + methodSuffix: "Regions", + }, }, { serviceName: Modules.PAYMENT, diff --git a/packages/modules/link-modules/src/definitions/sales-channel-location.ts b/packages/modules/link-modules/src/definitions/sales-channel-location.ts index fd79ef239e..20c4f6cfb2 100644 --- a/packages/modules/link-modules/src/definitions/sales-channel-location.ts +++ b/packages/modules/link-modules/src/definitions/sales-channel-location.ts @@ -24,12 +24,18 @@ export const SalesChannelLocation: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "sales_channel_id", alias: "sales_channel", + args: { + methodSuffix: "SalesChannels", + }, }, { serviceName: Modules.STOCK_LOCATION, primaryKey: "id", foreignKey: "stock_location_id", alias: "location", + args: { + methodSuffix: "StockLocations", + }, }, ], extends: [ diff --git a/packages/modules/link-modules/src/definitions/shipping-option-price-set.ts b/packages/modules/link-modules/src/definitions/shipping-option-price-set.ts index 475400366e..bbac11e125 100644 --- a/packages/modules/link-modules/src/definitions/shipping-option-price-set.ts +++ b/packages/modules/link-modules/src/definitions/shipping-option-price-set.ts @@ -33,6 +33,9 @@ export const ShippingOptionPriceSet: ModuleJoinerConfig = { primaryKey: "id", foreignKey: "price_set_id", alias: "price_set", + args: { + methodSuffix: "PriceSets", + }, deleteCascade: true, }, ], diff --git a/packages/modules/notification/integration-tests/__tests__/notification-module-service/index.spec.ts b/packages/modules/notification/integration-tests/__tests__/notification-module-service/index.spec.ts index 8d2fb76c4a..93657addf7 100644 --- a/packages/modules/notification/integration-tests/__tests__/notification-module-service/index.spec.ts +++ b/packages/modules/notification/integration-tests/__tests__/notification-module-service/index.spec.ts @@ -40,7 +40,7 @@ moduleIntegrationTestRunner({ data: {}, } - const result = await service.create(notification) + const result = await service.createNotifications(notification) expect(result).toEqual( expect.objectContaining({ provider_id: "test-provider", @@ -58,7 +58,7 @@ moduleIntegrationTestRunner({ idempotency_key: "idempotency-key", } - const result = await service.create(notification) + const result = await service.createNotifications(notification) expect(result).toEqual( expect.objectContaining({ provider_id: "test-provider", @@ -66,7 +66,7 @@ moduleIntegrationTestRunner({ }) ) - const secondResult = await service.create(notification) + const secondResult = await service.createNotifications(notification) expect(secondResult).toBe(undefined) }) }), diff --git a/packages/modules/notification/package.json b/packages/modules/notification/package.json index 5a1fe33499..0ffb71e31b 100644 --- a/packages/modules/notification/package.json +++ b/packages/modules/notification/package.json @@ -8,7 +8,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/notification/src/index.ts b/packages/modules/notification/src/index.ts index 5dc2ece165..e1278f1f87 100644 --- a/packages/modules/notification/src/index.ts +++ b/packages/modules/notification/src/index.ts @@ -1,7 +1,10 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { NotificationModuleService } from "@services" +import loadProviders from "./loaders/providers" -export * from "./types" -export * from "./models" -export * from "./services" +export const moduleDefinition: ModuleExports = { + service: NotificationModuleService, + loaders: [loadProviders], +} export default moduleDefinition diff --git a/packages/modules/notification/src/joiner-config.ts b/packages/modules/notification/src/joiner-config.ts index 5f1a5203c4..f4d265f557 100644 --- a/packages/modules/notification/src/joiner-config.ts +++ b/packages/modules/notification/src/joiner-config.ts @@ -1,33 +1,13 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import { NotificationModel } from "@models" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys: Record = { - notification_id: NotificationModel.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) +export const joinerConfig = defineJoinerConfig(Modules.NOTIFICATION, { + entityQueryingConfig: [{ name: "Notification" }], }) -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.NOTIFICATION, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["notification", "notifications"], - args: { - entity: NotificationModel.name, - }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/notification/src/models/index.ts b/packages/modules/notification/src/models/index.ts index 297e2809d1..a6486c89a6 100644 --- a/packages/modules/notification/src/models/index.ts +++ b/packages/modules/notification/src/models/index.ts @@ -1,2 +1,3 @@ -export { default as NotificationModel } from "./notification" +export { default as Notification } from "./notification" export { default as NotificationProvider } from "./notification-provider" + diff --git a/packages/modules/notification/src/models/notification-provider.ts b/packages/modules/notification/src/models/notification-provider.ts index 56d3c081e0..a795e9e7e2 100644 --- a/packages/modules/notification/src/models/notification-provider.ts +++ b/packages/modules/notification/src/models/notification-provider.ts @@ -9,7 +9,7 @@ import { PrimaryKey, Property, } from "@mikro-orm/core" -import NotificationModel from "./notification" +import Notification from "./notification" @Entity() export default class NotificationProvider { @@ -29,10 +29,10 @@ export default class NotificationProvider { channels: string[] @OneToMany({ - entity: () => NotificationModel, + entity: () => Notification, mappedBy: (notification) => notification.provider_id, }) - notifications = new Collection(this) + notifications = new Collection(this) @BeforeCreate() onCreate() { diff --git a/packages/modules/notification/src/models/notification.ts b/packages/modules/notification/src/models/notification.ts index 9bbf504b05..d5967289e7 100644 --- a/packages/modules/notification/src/models/notification.ts +++ b/packages/modules/notification/src/models/notification.ts @@ -35,7 +35,7 @@ const NotificationReceiverIdIndex = createPsqlIndexStatementHelper({ @NotificationReceiverIdIndex.MikroORMIndex() @Entity({ tableName: "notification" }) // Since there is a native `Notification` type, we have to call this something else here and in a couple of other places. -export default class NotificationModel { +export default class Notification { @PrimaryKey({ columnType: "text" }) id: string diff --git a/packages/modules/notification/src/module-definition.ts b/packages/modules/notification/src/module-definition.ts deleted file mode 100644 index 4c067f8212..0000000000 --- a/packages/modules/notification/src/module-definition.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { NotificationModuleService } from "@services" -import loadProviders from "./loaders/providers" - -const service = NotificationModuleService -const loaders = [loadProviders] - -export const moduleDefinition: ModuleExports = { - service, - loaders, -} diff --git a/packages/modules/notification/src/services/notification-module-service.ts b/packages/modules/notification/src/services/notification-module-service.ts index 1413d04f09..43a67e5741 100644 --- a/packages/modules/notification/src/services/notification-module-service.ts +++ b/packages/modules/notification/src/services/notification-module-service.ts @@ -12,40 +12,33 @@ import { InjectTransactionManager, MedusaContext, MedusaError, - ModulesSdkUtils, + MedusaService, promiseAll, } from "@medusajs/utils" +import { Notification } from "@models" import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" import NotificationProviderService from "./notification-provider" -import { NotificationModel, NotificationProvider } from "@models" - -const generateMethodForModels = { NotificationProvider } type InjectedDependencies = { baseRepository: DAL.RepositoryService - notificationModelService: ModulesSdkTypes.IMedusaInternalService + notificationService: ModulesSdkTypes.IMedusaInternalService notificationProviderService: NotificationProviderService } -export default class NotificationModuleService< - TEntity extends NotificationModel = NotificationModel - > - extends ModulesSdkUtils.MedusaService< - NotificationTypes.NotificationDTO, - { - NotificationProvider: { dto: NotificationTypes.NotificationProviderDTO } - } - >(NotificationModel, generateMethodForModels, entityNameToLinkableKeysMap) +export default class NotificationModuleService + extends MedusaService<{ + Notification: { dto: NotificationTypes.NotificationDTO } + }>({ Notification }, entityNameToLinkableKeysMap) implements INotificationModuleService { protected baseRepository_: DAL.RepositoryService - protected readonly notificationService_: ModulesSdkTypes.IMedusaInternalService + protected readonly notificationService_: ModulesSdkTypes.IMedusaInternalService protected readonly notificationProviderService_: NotificationProviderService constructor( { baseRepository, - notificationModelService, + notificationService, notificationProviderService, }: InjectedDependencies, protected readonly moduleDeclaration: InternalModuleDeclaration @@ -53,24 +46,26 @@ export default class NotificationModuleService< // @ts-ignore super(...arguments) this.baseRepository_ = baseRepository - this.notificationService_ = notificationModelService + this.notificationService_ = notificationService this.notificationProviderService_ = notificationProviderService } __joinerConfig(): ModuleJoinerConfig { return joinerConfig } - create( + + // @ts-expect-error + createNotifications( data: NotificationTypes.CreateNotificationDTO[], sharedContext?: Context ): Promise - create( + createNotifications( data: NotificationTypes.CreateNotificationDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createNotifications( data: | NotificationTypes.CreateNotificationDTO | NotificationTypes.CreateNotificationDTO[], @@ -80,7 +75,10 @@ export default class NotificationModuleService< > { const normalized = Array.isArray(data) ? data : [data] - const createdNotifications = await this.create_(normalized, sharedContext) + const createdNotifications = await this.createNotifications_( + normalized, + sharedContext + ) const serialized = await this.baseRepository_.serialize< NotificationTypes.NotificationDTO[] @@ -90,10 +88,10 @@ export default class NotificationModuleService< } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createNotifications_( data: NotificationTypes.CreateNotificationDTO[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { if (!data.length) { return [] } diff --git a/packages/modules/notification/src/utils/index.ts b/packages/modules/notification/src/utils/index.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/modules/order/integration-tests/__tests__/create-order.ts b/packages/modules/order/integration-tests/__tests__/create-order.ts index 33c146afb1..c353622c4b 100644 --- a/packages/modules/order/integration-tests/__tests__/create-order.ts +++ b/packages/modules/order/integration-tests/__tests__/create-order.ts @@ -1,12 +1,12 @@ import { Modules } from "@medusajs/modules-sdk" import { CreateOrderDTO, IOrderModuleService } from "@medusajs/types" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(100000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.ORDER, - testSuite: ({ service }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Order Module Service", () => { const input = { email: "foo@bar.com", @@ -193,7 +193,7 @@ moduleIntegrationTestRunner({ }) it("should create an order, shipping method and items. Including taxes and adjustments associated with them", async function () { - const createdOrder = await service.create(input) + const createdOrder = await service.createOrders(input) const serializedOrder = JSON.parse(JSON.stringify(createdOrder)) @@ -201,12 +201,12 @@ moduleIntegrationTestRunner({ }) it("should create an order, shipping method and items. Including taxes and adjustments associated with them and add new transactions", async function () { - const inpCopy = JSON.parse(JSON.stringify(input)) - inpCopy.transactions.push({ + const inpCopy = JSON.parse(JSON.stringify(input)) as CreateOrderDTO + inpCopy.transactions!.push({ amount: 10, currency_code: "USD", }) - const created = await service.create(inpCopy) + const created = await service.createOrders(inpCopy) const refund = await service.addTransactions([ { @@ -218,7 +218,7 @@ moduleIntegrationTestRunner({ const serializedOrder = JSON.parse( JSON.stringify( - await service.retrieve(created.id, { + await service.retrieveOrder(created.id, { select: ["id", "summary"], }) ) @@ -231,11 +231,11 @@ moduleIntegrationTestRunner({ }) ) - await service.softDeleteTransactions(refund[0].id) + await service.softDeleteTransactions([refund[0].id]) const serializedOrder2 = JSON.parse( JSON.stringify( - await service.retrieve(created.id, { + await service.retrieveOrder(created.id, { select: ["id", "summary"], }) ) @@ -258,7 +258,7 @@ moduleIntegrationTestRunner({ const serializedOrder3 = JSON.parse( JSON.stringify( - await service.retrieve(created.id, { + await service.retrieveOrder(created.id, { select: ["id", "summary"], }) ) @@ -271,11 +271,11 @@ moduleIntegrationTestRunner({ }) ) - await service.restoreTransactions(refund[0].id) + await service.restoreTransactions([refund[0].id]) const serializedOrder4 = JSON.parse( JSON.stringify( - await service.retrieve(created.id, { + await service.retrieveOrder(created.id, { select: ["id", "summary"], }) ) @@ -290,8 +290,8 @@ moduleIntegrationTestRunner({ }) it("should transform requested fields and relations to match the db schema and return the order", async function () { - const createdOrder = await service.create(input) - const getOrder = await service.retrieve(createdOrder.id, { + const createdOrder = await service.createOrders(input) + const getOrder = await service.retrieveOrder(createdOrder.id, { select: [ "id", "display_id", @@ -330,8 +330,8 @@ moduleIntegrationTestRunner({ }) it("should return order transactions", async function () { - const createdOrder = await service.create(input) - const getOrder = await service.retrieve(createdOrder.id, { + const createdOrder = await service.createOrders(input) + const getOrder = await service.retrieveOrder(createdOrder.id, { select: [ "id", "transactions.amount", @@ -357,8 +357,8 @@ moduleIntegrationTestRunner({ }) it("should transform where clause to match the db schema and return the order", async function () { - await service.create(input) - const orders = await service.list( + await service.createOrders(input) + const orders = await service.listOrders( { items: { quantity: 2, @@ -372,7 +372,7 @@ moduleIntegrationTestRunner({ ) expect(orders.length).toEqual(1) - const orders2 = await service.list( + const orders2 = await service.listOrders( { items: { quantity: 5, @@ -386,7 +386,7 @@ moduleIntegrationTestRunner({ ) expect(orders2.length).toEqual(0) - const orders3 = await service.list( + const orders3 = await service.listOrders( { items: { detail: { @@ -402,7 +402,7 @@ moduleIntegrationTestRunner({ ) expect(orders3.length).toEqual(1) - const orders4 = await service.list( + const orders4 = await service.listOrders( { items: { detail: { diff --git a/packages/modules/order/integration-tests/__tests__/order-claim.ts b/packages/modules/order/integration-tests/__tests__/order-claim.ts index 5c7e70ea35..c06f7a61b0 100644 --- a/packages/modules/order/integration-tests/__tests__/order-claim.ts +++ b/packages/modules/order/integration-tests/__tests__/order-claim.ts @@ -1,7 +1,7 @@ -import { Modules } from "@medusajs/modules-sdk" -import { CreateOrderDTO, IOrderModuleService } from "@medusajs/types" -import { ClaimType } from "@medusajs/utils" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import {Modules} from "@medusajs/modules-sdk" +import {CreateOrderDTO, IOrderModuleService} from "@medusajs/types" +import {ClaimType} from "@medusajs/utils" +import {moduleIntegrationTestRunner, SuiteOptions} from "medusa-test-utils" jest.setTimeout(100000) @@ -104,7 +104,7 @@ moduleIntegrationTestRunner({ } as CreateOrderDTO it("should claim an item and add two new items to the order", async function () { - const createdOrder = await service.create(input) + const createdOrder = await service.createOrders(input) // Fullfilment await service.registerFulfillment({ diff --git a/packages/modules/order/integration-tests/__tests__/order-edit.ts b/packages/modules/order/integration-tests/__tests__/order-edit.ts index f4710bd1ba..320725ae71 100644 --- a/packages/modules/order/integration-tests/__tests__/order-edit.ts +++ b/packages/modules/order/integration-tests/__tests__/order-edit.ts @@ -6,15 +6,15 @@ import { IOrderModuleService, } from "@medusajs/types" import { BigNumber } from "@medusajs/utils" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { ChangeActionType } from "../../src/utils" jest.setTimeout(100000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ debug: false, moduleName: Modules.ORDER, - testSuite: ({ service }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Order Module Service - Order Edits", () => { const input = { email: "foo@bar.com", @@ -128,7 +128,7 @@ moduleIntegrationTestRunner({ } as CreateOrderDTO it("should change an order by adding actions to it", async function () { - const createdOrder = await service.create(input) + const createdOrder = await service.createOrders(input) await service.addOrderAction([ { @@ -210,7 +210,7 @@ moduleIntegrationTestRunner({ await service.applyPendingOrderActions(createdOrder.id) - const finalOrder = await service.retrieve(createdOrder.id, { + const finalOrder = await service.retrieveOrder(createdOrder.id, { select: [ "id", "version", @@ -337,7 +337,7 @@ moduleIntegrationTestRunner({ }) it("should create an order change, add actions to it, confirm the changes, revert all the changes and restore the changes again.", async function () { - const createdOrder = await service.create(input) + const createdOrder = await service.createOrders(input) const orderChange = await service.createOrderChange({ order_id: createdOrder.id, @@ -418,7 +418,7 @@ moduleIntegrationTestRunner({ service.confirmOrderChange(orderChange.id) ).rejects.toThrow(`Order Change cannot be modified: ${orderChange.id}`) - const modified = await service.retrieve(createdOrder.id, { + const modified = await service.retrieveOrder(createdOrder.id, { select: [ "id", "version", @@ -483,7 +483,7 @@ moduleIntegrationTestRunner({ // Revert Last Changes await service.revertLastVersion(createdOrder.id) - const revertedOrder = await service.retrieve(createdOrder.id, { + const revertedOrder = await service.retrieveOrder(createdOrder.id, { select: [ "id", "version", @@ -549,7 +549,7 @@ moduleIntegrationTestRunner({ }) it("should create order changes, cancel and reject them.", async function () { - const createdOrder = await service.create(input) + const createdOrder = await service.createOrders(input) const orderChange = await service.createOrderChange({ order_id: createdOrder.id, @@ -598,7 +598,7 @@ moduleIntegrationTestRunner({ service.declineOrderChange(orderChange2.id) ).rejects.toThrow("Order Change cannot be modified") - const [change1, change2] = await service.listOrderChanges( + const [change1, change2] = await (service as any).listOrderChanges( { id: [orderChange.id, orderChange2.id], }, diff --git a/packages/modules/order/integration-tests/__tests__/order-exchange.ts b/packages/modules/order/integration-tests/__tests__/order-exchange.ts index d89fc0a612..e058f31e12 100644 --- a/packages/modules/order/integration-tests/__tests__/order-exchange.ts +++ b/packages/modules/order/integration-tests/__tests__/order-exchange.ts @@ -1,6 +1,6 @@ -import { Modules } from "@medusajs/modules-sdk" -import { CreateOrderDTO, IOrderModuleService } from "@medusajs/types" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import {Modules} from "@medusajs/modules-sdk" +import {CreateOrderDTO, IOrderModuleService} from "@medusajs/types" +import {moduleIntegrationTestRunner, SuiteOptions} from "medusa-test-utils" jest.setTimeout(100000) @@ -103,7 +103,7 @@ moduleIntegrationTestRunner({ } as CreateOrderDTO it("should exchange an item and add two new items to the order", async function () { - const createdOrder = await service.create(input) + const createdOrder = await service.createOrders(input) // Fullfilment await service.registerFulfillment({ diff --git a/packages/modules/order/integration-tests/__tests__/order-items-shipping.spec.ts b/packages/modules/order/integration-tests/__tests__/order-items-shipping.spec.ts index 5b4839b79f..2bb32369af 100644 --- a/packages/modules/order/integration-tests/__tests__/order-items-shipping.spec.ts +++ b/packages/modules/order/integration-tests/__tests__/order-items-shipping.spec.ts @@ -4,18 +4,18 @@ import { IOrderModuleService, } from "@medusajs/types" import { OrderStatus } from "@medusajs/utils" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(100000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.ORDER, - testSuite: ({ service }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Order - Items and Shipping methods", () => { describe("create", () => { it("should throw an error when required params are not passed", async () => { const error = await service - .create([ + .createOrders([ { email: "test@email.com", } as any, @@ -28,7 +28,7 @@ moduleIntegrationTestRunner({ }) it("should create an order successfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", items: [ @@ -41,7 +41,7 @@ moduleIntegrationTestRunner({ }, ]) - const [order] = await service.list({ id: [createdOrder.id] }) + const [order] = await service.listOrders({ id: [createdOrder.id] }) expect(order).toEqual( expect.objectContaining({ @@ -52,7 +52,7 @@ moduleIntegrationTestRunner({ }) it("should create an order with billing + shipping address successfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", billing_address: { @@ -66,7 +66,7 @@ moduleIntegrationTestRunner({ }, ]) - const [order] = await service.list( + const [order] = await service.listOrders( { id: [createdOrder.id] }, { relations: ["billing_address", "shipping_address"] } ) @@ -95,7 +95,7 @@ moduleIntegrationTestRunner({ }, ]) - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", billing_address_id: createdAddress.id, @@ -122,7 +122,7 @@ moduleIntegrationTestRunner({ }) it("should create an order with items", async () => { - const createdOrder = await service.create({ + const createdOrder = await service.createOrders({ currency_code: "eur", items: [ { @@ -133,7 +133,7 @@ moduleIntegrationTestRunner({ ], }) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item"], }) @@ -153,7 +153,7 @@ moduleIntegrationTestRunner({ }) it("should create multiple orders with items", async () => { - const createdOrders = await service.create([ + const createdOrders = await service.createOrders([ { currency_code: "eur", items: [ @@ -176,7 +176,7 @@ moduleIntegrationTestRunner({ }, ]) - const orders = await service.list( + const orders = await service.listOrders( { id: createdOrders.map((c) => c.id) }, { relations: ["items.item"], @@ -222,7 +222,7 @@ moduleIntegrationTestRunner({ describe("update", () => { it("should throw an error if order does not exist", async () => { const error = await service - .update([ + .updateOrders([ { id: "none-existing", }, @@ -235,20 +235,20 @@ moduleIntegrationTestRunner({ }) it("should update an order successfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, ]) - const [updatedOrder] = await service.update([ + const [updatedOrder] = await service.updateOrders([ { id: createdOrder.id, email: "test@email.com", }, ]) - const [order] = await service.list({ id: [createdOrder.id] }) + const [order] = await service.listOrders({ id: [createdOrder.id] }) expect(order).toEqual( expect.objectContaining({ @@ -260,11 +260,11 @@ moduleIntegrationTestRunner({ }) it("should update an order with selector successfully", async () => { - const createdOrder = await service.create({ + const createdOrder = await service.createOrders({ currency_code: "eur", }) - const [updatedOrder] = await service.update( + const [updatedOrder] = await service.updateOrders( { id: createdOrder.id }, { email: "test@email.com", @@ -272,7 +272,7 @@ moduleIntegrationTestRunner({ } ) - const [order] = await service.list({ id: [createdOrder.id] }) + const [order] = await service.listOrders({ id: [createdOrder.id] }) expect(order).toEqual( expect.objectContaining({ @@ -285,17 +285,17 @@ moduleIntegrationTestRunner({ }) it("should update an order with id successfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, ]) - const updatedOrder = await service.update(createdOrder.id, { + const updatedOrder = await service.updateOrders(createdOrder.id, { email: "test@email.com", }) - const [order] = await service.list({ id: [createdOrder.id] }) + const [order] = await service.listOrders({ id: [createdOrder.id] }) expect(order).toEqual( expect.objectContaining({ @@ -309,15 +309,15 @@ moduleIntegrationTestRunner({ describe("delete", () => { it("should delete an order successfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, ]) - await service.delete([createdOrder.id]) + await service.deleteOrders([createdOrder.id]) - const orders = await service.list({ id: [createdOrder.id] }) + const orders = await service.listOrders({ id: [createdOrder.id] }) expect(orders.length).toEqual(0) }) @@ -385,7 +385,7 @@ moduleIntegrationTestRunner({ describe("createLineItems", () => { it("should add a line item to order succesfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -399,7 +399,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item"], }) @@ -415,7 +415,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple line items to order succesfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -438,7 +438,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item"], }) @@ -462,7 +462,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple line items to multiple orders succesfully", async () => { - let [eurOrder, usdOrder] = await service.create([ + let [eurOrder, usdOrder] = await service.createOrders([ { currency_code: "eur", status: OrderStatus.DRAFT, @@ -488,7 +488,7 @@ moduleIntegrationTestRunner({ }, ]) - const orders = await service.list( + const orders = await service.listOrders( { id: [eurOrder.id, usdOrder.id] }, { relations: ["items.item"] } ) @@ -523,7 +523,7 @@ moduleIntegrationTestRunner({ }) it("should throw an error when required params are not passed adding to a single order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -544,7 +544,7 @@ moduleIntegrationTestRunner({ }) it("should throw a generic error when required params are not passed using bulk add method", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -568,7 +568,7 @@ moduleIntegrationTestRunner({ describe("updateLineItems", () => { it("should update a line item in order succesfully with selector approach", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -596,7 +596,7 @@ moduleIntegrationTestRunner({ }) it("should update a line item in order succesfully with id approach", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -621,7 +621,7 @@ moduleIntegrationTestRunner({ }) it("should update line items in orders succesfully with multi-selector approach", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -672,7 +672,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item"], }) @@ -696,7 +696,7 @@ moduleIntegrationTestRunner({ describe("deleteLineItems", () => { it("should delete a line item succesfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -715,7 +715,7 @@ moduleIntegrationTestRunner({ await service.deleteLineItems([item.id]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items"], }) @@ -723,7 +723,7 @@ moduleIntegrationTestRunner({ }) it("should delete multiple line items succesfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -744,7 +744,7 @@ moduleIntegrationTestRunner({ await service.deleteLineItems([item.id, item2.id]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items"], }) @@ -754,7 +754,7 @@ moduleIntegrationTestRunner({ describe("createShippingMethods", () => { it("should add a shipping method to order succesfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -770,7 +770,7 @@ moduleIntegrationTestRunner({ ] ) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["shipping_methods"], }) @@ -778,13 +778,13 @@ moduleIntegrationTestRunner({ }) it("should add multiple shipping methods to multiple orders succesfully", async () => { - let [eurOrder] = await service.create([ + let [eurOrder] = await service.createOrders([ { currency_code: "eur", }, ]) - let [usdOrder] = await service.create([ + let [usdOrder] = await service.createOrders([ { currency_code: "usd", }, @@ -803,7 +803,7 @@ moduleIntegrationTestRunner({ }, ]) - const orders = await service.list( + const orders = await service.listOrders( { id: [eurOrder.id, usdOrder.id] }, { relations: ["shipping_methods"] } ) @@ -821,7 +821,7 @@ moduleIntegrationTestRunner({ describe("setLineItemAdjustments", () => { it("should set line item adjustments for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -876,7 +876,7 @@ moduleIntegrationTestRunner({ }) it("should replace line item adjustments for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -919,7 +919,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item.adjustments"], }) @@ -944,7 +944,7 @@ moduleIntegrationTestRunner({ }) it("should delete all line item adjustments for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -981,7 +981,7 @@ moduleIntegrationTestRunner({ await service.setLineItemAdjustments(createdOrder.id, []) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item.adjustments"], }) @@ -999,7 +999,7 @@ moduleIntegrationTestRunner({ }) it("should update line item adjustments for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1043,7 +1043,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item.adjustments"], }) @@ -1071,7 +1071,7 @@ moduleIntegrationTestRunner({ describe("createLineItemAdjustments", () => { it("should add line item adjustments for items in an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1108,7 +1108,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple line item adjustments for multiple line items", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1162,7 +1162,7 @@ moduleIntegrationTestRunner({ }) it("should add line item adjustments for line items on multiple orders", async () => { - let [orderOne, orderTwo] = await service.create([ + let [orderOne, orderTwo] = await service.createOrders([ { currency_code: "eur", }, @@ -1203,7 +1203,7 @@ moduleIntegrationTestRunner({ const [checkOrderOne, checkOrderTwo] = JSON.parse( JSON.stringify( - await service.list({}, { relations: ["items.item.adjustments"] }) + await service.listOrders({}, { relations: ["items.item.adjustments"] }) ) ) @@ -1241,7 +1241,7 @@ moduleIntegrationTestRunner({ describe("deleteLineItemAdjustments", () => { it("should delete a line item succesfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1277,7 +1277,7 @@ moduleIntegrationTestRunner({ }) it("should delete a line item succesfully with selector", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1315,7 +1315,7 @@ moduleIntegrationTestRunner({ describe("setShippingMethodAdjustments", () => { it("should set shipping method adjustments for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1374,7 +1374,7 @@ moduleIntegrationTestRunner({ }) it("should replace shipping method adjustments for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1419,7 +1419,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["shipping_methods.adjustments"], }) @@ -1446,7 +1446,7 @@ moduleIntegrationTestRunner({ }) it("should delete all shipping method adjustments for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1485,7 +1485,7 @@ moduleIntegrationTestRunner({ await service.setShippingMethodAdjustments(createdOrder.id, []) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["shipping_methods.adjustments"], }) @@ -1503,7 +1503,7 @@ moduleIntegrationTestRunner({ }) it("should update shipping method adjustments for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1548,7 +1548,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["shipping_methods.adjustments"], }) @@ -1576,7 +1576,7 @@ moduleIntegrationTestRunner({ describe("createShippingMethodAdjustments", () => { it("should add shipping method adjustments in an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1615,7 +1615,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple shipping method adjustments for multiple shipping methods", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1673,12 +1673,12 @@ moduleIntegrationTestRunner({ }) it("should add shipping method adjustments for shipping methods on multiple orders", async () => { - const [orderOne] = await service.create([ + const [orderOne] = await service.createOrders([ { currency_code: "eur", }, ]) - const [orderTwo] = await service.create([ + const [orderTwo] = await service.createOrders([ { currency_code: "usd", }, @@ -1718,12 +1718,12 @@ moduleIntegrationTestRunner({ }, ]) - const orderOneMethods = await service.listOrderShippingMethods( + const orderOneMethods = await (service as any).listOrderShippingMethods( { order_id: orderOne.id }, { relations: ["shipping_method.adjustments"] } ) - const orderTwoMethods = await service.listOrderShippingMethods( + const orderTwoMethods = await (service as any).listOrderShippingMethods( { order_id: orderTwo.id }, { relations: ["shipping_method.adjustments"] } ) @@ -1761,13 +1761,13 @@ moduleIntegrationTestRunner({ }) it("should throw if shipping method is not associated with order", async () => { - const [orderOne] = await service.create([ + const [orderOne] = await service.createOrders([ { currency_code: "eur", }, ]) - const [orderTwo] = await service.create([ + const [orderTwo] = await service.createOrders([ { currency_code: "eur", }, @@ -1801,7 +1801,7 @@ moduleIntegrationTestRunner({ describe("deleteShippingMethodAdjustments", () => { it("should delete a shipping method adjustment succesfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1840,7 +1840,7 @@ moduleIntegrationTestRunner({ }) it("should delete a shipping method succesfully with selector", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1883,7 +1883,7 @@ moduleIntegrationTestRunner({ describe("setLineItemTaxLines", () => { it("should set line item tax lines for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1935,7 +1935,7 @@ moduleIntegrationTestRunner({ }) it("should replace line item tax lines for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -1975,7 +1975,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item.tax_lines"], }) @@ -2000,7 +2000,7 @@ moduleIntegrationTestRunner({ }) it("should delete all line item tax lines for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -2034,7 +2034,7 @@ moduleIntegrationTestRunner({ await service.setLineItemTaxLines(createdOrder.id, []) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item.tax_lines"], }) @@ -2052,7 +2052,7 @@ moduleIntegrationTestRunner({ }) it("should update line item tax lines for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -2093,7 +2093,7 @@ moduleIntegrationTestRunner({ }, ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item.tax_lines"], }) @@ -2119,7 +2119,7 @@ moduleIntegrationTestRunner({ }) it("should delete, update, and create line item tax lines for an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -2179,7 +2179,7 @@ moduleIntegrationTestRunner({ // delete: should delete the initial tax line for itemOne ]) - const order = await service.retrieve(createdOrder.id, { + const order = await service.retrieveOrder(createdOrder.id, { relations: ["items.item.tax_lines"], }) @@ -2212,7 +2212,7 @@ moduleIntegrationTestRunner({ describe("createLineItemAdjustments", () => { it("should add line item tax lines for items in an order", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -2249,7 +2249,7 @@ moduleIntegrationTestRunner({ }) it("should add multiple line item tax lines for multiple line items", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -2303,12 +2303,12 @@ moduleIntegrationTestRunner({ }) it("should add line item tax lines for line items on multiple orders", async () => { - const [orderOne] = await service.create([ + const [orderOne] = await service.createOrders([ { currency_code: "eur", }, ]) - const [orderTwo] = await service.create([ + const [orderTwo] = await service.createOrders([ { currency_code: "usd", }, @@ -2346,7 +2346,7 @@ moduleIntegrationTestRunner({ const [checkOrderOne, checkOrderTwo] = JSON.parse( JSON.stringify( - await service.list({}, { relations: ["items.item.tax_lines"] }) + await service.listOrders({}, { relations: ["items.item.tax_lines"] }) ) ) @@ -2384,7 +2384,7 @@ moduleIntegrationTestRunner({ describe("deleteLineItemAdjustments", () => { it("should delete line item tax line succesfully", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, @@ -2421,7 +2421,7 @@ moduleIntegrationTestRunner({ }) it("should delete line item tax lines succesfully with selector", async () => { - const [createdOrder] = await service.create([ + const [createdOrder] = await service.createOrders([ { currency_code: "eur", }, diff --git a/packages/modules/order/integration-tests/__tests__/order-return.ts b/packages/modules/order/integration-tests/__tests__/order-return.ts index 6ae43a13be..86b516dce2 100644 --- a/packages/modules/order/integration-tests/__tests__/order-return.ts +++ b/packages/modules/order/integration-tests/__tests__/order-return.ts @@ -1,12 +1,12 @@ import { Modules } from "@medusajs/modules-sdk" import { CreateOrderDTO, IOrderModuleService } from "@medusajs/types" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(1000000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.ORDER, - testSuite: ({ service }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Order Module Service - Return flows", () => { const input = { email: "foo@bar.com", @@ -103,7 +103,7 @@ moduleIntegrationTestRunner({ } as CreateOrderDTO it("should create an order, fulfill, ship and return the items and cancel some item return", async function () { - const createdOrder = await service.create(input) + const createdOrder = await service.createOrders(input) // Fullfilment await service.registerFulfillment({ @@ -116,7 +116,7 @@ moduleIntegrationTestRunner({ }), }) - let getOrder = await service.retrieve(createdOrder.id, { + let getOrder = await service.retrieveOrder(createdOrder.id, { select: [ "id", "version", @@ -176,7 +176,7 @@ moduleIntegrationTestRunner({ }), }) - getOrder = await service.retrieve(createdOrder.id, { + getOrder = await service.retrieveOrder(createdOrder.id, { select: [ "id", "version", @@ -269,7 +269,7 @@ moduleIntegrationTestRunner({ ], }) - getOrder = await service.retrieve(createdOrder.id, { + getOrder = await service.retrieveOrder(createdOrder.id, { select: [ "id", "version", @@ -421,7 +421,7 @@ moduleIntegrationTestRunner({ }) ) - getOrder = await service.retrieve(createdOrder.id, { + getOrder = await service.retrieveOrder(createdOrder.id, { select: [ "id", "version", diff --git a/packages/modules/order/integration-tests/__tests__/returns.ts b/packages/modules/order/integration-tests/__tests__/returns.ts index a78113e578..74b5b558bc 100644 --- a/packages/modules/order/integration-tests/__tests__/returns.ts +++ b/packages/modules/order/integration-tests/__tests__/returns.ts @@ -1,12 +1,12 @@ import { Modules } from "@medusajs/modules-sdk" import { IOrderModuleService } from "@medusajs/types" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(100000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.ORDER, - testSuite: ({ service }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Order Module Service - Returns", () => { it("should create return reasons", async function () { const reason = await service.createReturnReasons({ diff --git a/packages/modules/order/integration-tests/setup-env.js b/packages/modules/order/integration-tests/setup-env.js deleted file mode 100644 index 739649eae6..0000000000 --- a/packages/modules/order/integration-tests/setup-env.js +++ /dev/null @@ -1,6 +0,0 @@ -if (typeof process.env.DB_TEMP_NAME === "undefined") { - const tempName = parseInt(process.env.JEST_WORKER_ID || "1") - process.env.DB_TEMP_NAME = `medusa-order-integration-${tempName}` -} - -process.env.MEDUSA_ORDER_DB_SCHEMA = "public" diff --git a/packages/modules/order/integration-tests/setup.js b/packages/modules/order/integration-tests/setup.js deleted file mode 100644 index 43f99aab4a..0000000000 --- a/packages/modules/order/integration-tests/setup.js +++ /dev/null @@ -1,3 +0,0 @@ -import { JestUtils } from "medusa-test-utils" - -JestUtils.afterAllHookDropDatabase() diff --git a/packages/modules/order/jest.config.js b/packages/modules/order/jest.config.js index dce2002dae..0c652264ea 100644 --- a/packages/modules/order/jest.config.js +++ b/packages/modules/order/jest.config.js @@ -17,6 +17,4 @@ module.exports = { testEnvironment: `node`, moduleFileExtensions: [`js`, `ts`], modulePathIgnorePatterns: ["dist/"], - setupFiles: ["/integration-tests/setup-env.js"], - setupFilesAfterEnv: ["/integration-tests/setup.js"], } diff --git a/packages/modules/order/package.json b/packages/modules/order/package.json index 8443b33a3e..79843a39a4 100644 --- a/packages/modules/order/package.json +++ b/packages/modules/order/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-order-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/order/src/index.ts b/packages/modules/order/src/index.ts index 54d1b85909..2953aad39e 100644 --- a/packages/modules/order/src/index.ts +++ b/packages/modules/order/src/index.ts @@ -1,4 +1,11 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { OrderModuleService } from "@services" + +const service = OrderModuleService + +export const moduleDefinition: ModuleExports = { + service, +} export * from "./models" export * from "./services" diff --git a/packages/modules/order/src/joiner-config.ts b/packages/modules/order/src/joiner-config.ts index d3250a4c6d..4d045bf1e6 100644 --- a/packages/modules/order/src/joiner-config.ts +++ b/packages/modules/order/src/joiner-config.ts @@ -1,44 +1,12 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig, pluralize } from "@medusajs/utils" -import { LineItem, ReturnReason } from "@models" -import Order from "./models/order" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys: Record = { - order_id: Order.name, - order_item_id: LineItem.name, - return_reason_id: ReturnReason.name, - return_reason_value: ReturnReason.name, -} +// TODO: review configuration +export const joinerConfig = defineJoinerConfig(Modules.ORDER) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.ORDER, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["order", "orders"], - args: { - entity: Order.name, - }, - }, - { - name: ["return_reason", "return_reasons"], - args: { - entity: ReturnReason.name, - methodSuffix: pluralize(ReturnReason.name), - }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/order/src/module-definition.ts b/packages/modules/order/src/module-definition.ts deleted file mode 100644 index eb7db999f6..0000000000 --- a/packages/modules/order/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { OrderModuleService } from "@services" - -const service = OrderModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/order/src/scripts/bin/run-seed.ts b/packages/modules/order/src/scripts/bin/run-seed.ts deleted file mode 100644 index f32d9cdf33..0000000000 --- a/packages/modules/order/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node - -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as Models from "@models" -import { EOL } from "os" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-order-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.ORDER, - models: Models, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - // TODO: Add seed logic - }, - }) - await run({ path }) -})() diff --git a/packages/modules/order/src/services/order-module-service.ts b/packages/modules/order/src/services/order-module-service.ts index d20c20045c..4ce51f43a3 100644 --- a/packages/modules/order/src/services/order-module-service.ts +++ b/packages/modules/order/src/services/order-module-service.ts @@ -3,8 +3,8 @@ import { Context, DAL, FindConfig, - IOrderModuleService, InternalModuleDeclaration, + IOrderModuleService, ModuleJoinerConfig, ModulesSdkTypes, OrderDTO, @@ -16,18 +16,18 @@ import { } from "@medusajs/types" import { BigNumber, + createRawPropertiesFromBigNumber, + decorateCartTotals, + deduplicate, InjectManager, InjectTransactionManager, + isObject, + isString, MathBN, MedusaContext, MedusaError, ModulesSdkUtils, OrderStatus, - createRawPropertiesFromBigNumber, - decorateCartTotals, - deduplicate, - isObject, - isString, promiseAll, transformPropertiesToBigNumber, } from "@medusajs/utils" @@ -67,8 +67,8 @@ import { } from "@types" import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" import { - ApplyOrderChangeDTO, applyChangesToOrder, + ApplyOrderChangeDTO, calculateOrderChange, formatOrder, } from "../utils" @@ -100,6 +100,7 @@ type InjectedDependencies = { } const generateMethodForModels = { + Order, Address, LineItem, LineItemAdjustment, @@ -120,6 +121,7 @@ const generateMethodForModels = { OrderExchange, } +// TODO: rm template args here, keep it for later to not collide with carlos work at least as little as possible export default class OrderModuleService< TOrder extends Order = Order, TAddress extends Address = Address, @@ -141,31 +143,29 @@ export default class OrderModuleService< TClaim extends OrderClaim = OrderClaim, TExchange extends OrderExchange = OrderExchange > - extends ModulesSdkUtils.MedusaService< - OrderTypes.OrderDTO, - { - Address: { dto: OrderTypes.OrderAddressDTO } - LineItem: { dto: OrderTypes.OrderLineItemDTO } - LineItemAdjustment: { dto: OrderTypes.OrderLineItemAdjustmentDTO } - LineItemTaxLine: { dto: OrderTypes.OrderLineItemTaxLineDTO } - ShippingMethod: { dto: OrderTypes.OrderShippingMethodDTO } - ShippingMethodAdjustment: { - dto: OrderTypes.OrderShippingMethodAdjustmentDTO - } - ShippingMethodTaxLine: { dto: OrderTypes.OrderShippingMethodTaxLineDTO } - OrderChange: { dto: OrderTypes.OrderChangeDTO } - OrderChangeAction: { dto: OrderTypes.OrderChangeActionDTO } - OrderItem: { dto: OrderTypes.OrderItemDTO } - OrderShippingMethod: { dto: OrderShippingMethod } - ReturnReason: { dto: OrderTypes.OrderReturnReasonDTO } - OrderSummary: { dto: OrderTypes.OrderSummaryDTO } - Transaction: { dto: OrderTypes.OrderTransactionDTO } - Return: { dto: any } // TODO: Add return dto - ReturnItem: { dto: any } // TODO: Add return item dto - OrderClaim: { dto: any } // TODO: Add claim dto - OrderExchange: { dto: any } // TODO: Add exchange dto + extends ModulesSdkUtils.MedusaService<{ + Order: { dto: OrderTypes.OrderDTO } + Address: { dto: OrderTypes.OrderAddressDTO } + LineItem: { dto: OrderTypes.OrderLineItemDTO } + LineItemAdjustment: { dto: OrderTypes.OrderLineItemAdjustmentDTO } + LineItemTaxLine: { dto: OrderTypes.OrderLineItemTaxLineDTO } + ShippingMethod: { dto: OrderTypes.OrderShippingMethodDTO } + ShippingMethodAdjustment: { + dto: OrderTypes.OrderShippingMethodAdjustmentDTO } - >(Order, generateMethodForModels, entityNameToLinkableKeysMap) + ShippingMethodTaxLine: { dto: OrderTypes.OrderShippingMethodTaxLineDTO } + OrderChange: { dto: OrderTypes.OrderChangeDTO } + OrderChangeAction: { dto: OrderTypes.OrderChangeActionDTO } + OrderItem: { dto: OrderTypes.OrderItemDTO } + OrderShippingMethod: { dto: OrderShippingMethod } + ReturnReason: { dto: OrderTypes.OrderReturnReasonDTO } + OrderSummary: { dto: OrderTypes.OrderSummaryDTO } + Transaction: { dto: OrderTypes.OrderTransactionDTO } + Return: { dto: any } // TODO: Add return dto + ReturnItem: { dto: any } // TODO: Add return item dto + OrderClaim: { dto: any } // TODO: Add claim dto + OrderExchange: { dto: any } // TODO: Add exchange dto + }>(generateMethodForModels, entityNameToLinkableKeysMap) implements IOrderModuleService { protected baseRepository_: DAL.RepositoryService @@ -303,7 +303,8 @@ export default class OrderModuleService< }) } - async retrieve( + // @ts-expect-error + async retrieveOrder( id: string, config?: FindConfig | undefined, @MedusaContext() sharedContext?: Context | undefined @@ -311,7 +312,7 @@ export default class OrderModuleService< config ??= {} const includeTotals = this.shouldIncludeTotals(config) - const order = await super.retrieve(id, config, sharedContext) + const order = await super.retrieveOrder(id, config, sharedContext) return formatOrder(order, { entity: Order, @@ -319,7 +320,8 @@ export default class OrderModuleService< }) as OrderTypes.OrderDTO } - async list( + // @ts-expect-error + async listOrders( filters?: any, config?: FindConfig | undefined, @MedusaContext() sharedContext?: Context | undefined @@ -327,7 +329,7 @@ export default class OrderModuleService< config ??= {} const includeTotals = this.shouldIncludeTotals(config) - const orders = await super.list(filters, config, sharedContext) + const orders = await super.listOrders(filters, config, sharedContext) return formatOrder(orders, { entity: Order, @@ -335,7 +337,8 @@ export default class OrderModuleService< }) as OrderTypes.OrderDTO[] } - async listAndCount( + // @ts-expect-error + async listAndCountOrders( filters?: any, config?: FindConfig | undefined, @MedusaContext() sharedContext?: Context | undefined @@ -343,7 +346,7 @@ export default class OrderModuleService< config ??= {} const includeTotals = this.shouldIncludeTotals(config) - const [orders, count] = await super.listAndCount( + const [orders, count] = await super.listAndCountOrders( filters, config, sharedContext @@ -548,26 +551,27 @@ export default class OrderModuleService< ] } - async create( + // @ts-expect-error + async createOrders( data: OrderTypes.CreateOrderDTO[], sharedContext?: Context ): Promise - async create( + async createOrders( data: OrderTypes.CreateOrderDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createOrders( data: OrderTypes.CreateOrderDTO[] | OrderTypes.CreateOrderDTO, @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const orders = await this.create_(input, sharedContext) + const orders = await this.createOrders_(input, sharedContext) - const result = await this.list( + const result = await this.listOrders( { id: orders.map((p) => p!.id), }, @@ -594,7 +598,7 @@ export default class OrderModuleService< } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createOrders_( data: OrderTypes.CreateOrderDTO[], @MedusaContext() sharedContext: Context = {} ) { @@ -650,22 +654,23 @@ export default class OrderModuleService< return createdOrders } - async update( + // @ts-expect-error + async updateOrders( data: OrderTypes.UpdateOrderDTO[] ): Promise - async update( + async updateOrders( orderId: string, data: OrderTypes.UpdateOrderDTO, sharedContext?: Context ): Promise - async update( + async updateOrders( selector: Partial, data: OrderTypes.UpdateOrderDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async update( + async updateOrders( dataOrIdOrSelector: | OrderTypes.UpdateOrderDTO[] | string @@ -673,7 +678,11 @@ export default class OrderModuleService< data?: OrderTypes.UpdateOrderDTO, @MedusaContext() sharedContext: Context = {} ): Promise { - const result = await this.update_(dataOrIdOrSelector, data, sharedContext) + const result = await this.updateOrders_( + dataOrIdOrSelector, + data, + sharedContext + ) const serializedResult = await this.baseRepository_.serialize< OrderTypes.OrderDTO[] @@ -685,7 +694,7 @@ export default class OrderModuleService< } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updateOrders_( dataOrIdOrSelector: | OrderTypes.UpdateOrderDTO[] | string @@ -759,7 +768,7 @@ export default class OrderModuleService< : [orderIdOrData] const allOrderIds = data.map((dt) => dt.order_id) - const order = await this.list( + const order = await this.listOrders( { id: allOrderIds }, { select: ["id", "version"] }, sharedContext @@ -793,7 +802,7 @@ export default class OrderModuleService< items: OrderTypes.CreateOrderLineItemDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { - const order = await this.retrieve( + const order = await this.retrieveOrder( orderId, { select: ["id", "version"] }, sharedContext @@ -1165,7 +1174,7 @@ export default class OrderModuleService< : [orderIdOrData] const allOrderIds = data.map((dt) => dt.order_id) - const order = await this.list( + const order = await this.listOrders( { id: allOrderIds }, { select: ["id", "version"] }, sharedContext @@ -1199,7 +1208,7 @@ export default class OrderModuleService< data: CreateOrderShippingMethodDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { - const order = await this.retrieve( + const order = await this.retrieveOrder( orderId, { select: ["id", "version"] }, sharedContext @@ -1257,7 +1266,7 @@ export default class OrderModuleService< ): Promise { let addedAdjustments: LineItemAdjustment[] = [] if (isString(orderIdOrData)) { - const order = await this.retrieve( + const order = await this.retrieveOrder( orderIdOrData, { select: ["id"], relations: ["items.item"] }, sharedContext @@ -1305,7 +1314,7 @@ export default class OrderModuleService< )[], @MedusaContext() sharedContext: Context = {} ): Promise { - const order = await this.retrieve( + const order = await this.retrieveOrder( orderId, { select: ["id"], relations: ["items.item.adjustments"] }, sharedContext @@ -1356,7 +1365,7 @@ export default class OrderModuleService< )[], @MedusaContext() sharedContext: Context = {} ): Promise { - const order = await this.retrieve( + const order = await this.retrieveOrder( orderId, { select: ["id"], relations: ["shipping_methods.adjustments"] }, sharedContext @@ -1430,7 +1439,7 @@ export default class OrderModuleService< > { let addedAdjustments: ShippingMethodAdjustment[] = [] if (isString(orderIdOrData)) { - const order = await this.retrieve( + const order = await this.retrieveOrder( orderIdOrData, { select: ["id"], relations: ["shipping_methods"] }, sharedContext @@ -1547,7 +1556,7 @@ export default class OrderModuleService< )[], @MedusaContext() sharedContext: Context = {} ): Promise { - const order = await this.retrieve( + const order = await this.retrieveOrder( orderId, { select: ["id"], relations: ["items.item.tax_lines"] }, sharedContext @@ -1657,7 +1666,7 @@ export default class OrderModuleService< )[], @MedusaContext() sharedContext: Context = {} ): Promise { - const order = await this.retrieve( + const order = await this.retrieveOrder( orderId, { select: ["id"], relations: ["shipping_methods.tax_lines"] }, sharedContext @@ -1739,7 +1748,7 @@ export default class OrderModuleService< dataMap[change.order_id] = change } - const orders = await this.list( + const orders = await this.listOrders( { id: orderIds, }, @@ -1925,7 +1934,7 @@ export default class OrderModuleService< ): Promise { const orderIds = Array.isArray(orderId) ? orderId : [orderId] - const orders = await this.list( + const orders = await this.listOrders( { id: orderIds }, { select: ["id", "version"], @@ -1972,7 +1981,7 @@ export default class OrderModuleService< orderId: string, @MedusaContext() sharedContext?: Context ) { - const order = await super.retrieve( + const order = await super.retrieveOrder( orderId, { select: ["id", "version"], @@ -2241,7 +2250,7 @@ export default class OrderModuleService< } } - let orders = await super.list( + let orders = await super.listOrders( { id: deduplicate(ordersIds) }, { select: [ @@ -2650,7 +2659,7 @@ export default class OrderModuleService< @MedusaContext() sharedContext?: Context ): Promise { const orderIds = Array.isArray(orderId) ? orderId : [orderId] - const orders = await this.list( + const orders = await this.listOrders( { id: orderIds, }, @@ -2708,7 +2717,7 @@ export default class OrderModuleService< @MedusaContext() sharedContext?: Context ): Promise { const orderIds = Array.isArray(orderId) ? orderId : [orderId] - const orders = await this.list( + const orders = await this.listOrders( { id: orderIds, }, @@ -2760,7 +2769,7 @@ export default class OrderModuleService< @MedusaContext() sharedContext?: Context ): Promise { const orderIds = Array.isArray(orderId) ? orderId : [orderId] - const orders = await this.list( + const orders = await this.listOrders( { id: orderIds, }, diff --git a/packages/modules/payment/integration-tests/__tests__/loaders/providers.spec.ts b/packages/modules/payment/integration-tests/__tests__/loaders/providers.spec.ts index 64b0ff646e..d5a6bd6b32 100644 --- a/packages/modules/payment/integration-tests/__tests__/loaders/providers.spec.ts +++ b/packages/modules/payment/integration-tests/__tests__/loaders/providers.spec.ts @@ -1,76 +1,49 @@ import { IPaymentModuleService } from "@medusajs/types" -import { SqlEntityManager } from "@mikro-orm/postgresql" import { Modules } from "@medusajs/modules-sdk" -import { initModules } from "medusa-test-utils" -import { MikroOrmWrapper } from "../../utils" -import { getInitModuleConfig } from "../../utils/get-init-module-config" -import { createPaymentCollections } from "../../__fixtures__" +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(30000) -describe("Payment Module Service", () => { - let service: IPaymentModuleService - let repositoryManager: SqlEntityManager - let shutdownFunc: () => Promise +moduleIntegrationTestRunner({ + moduleName: Modules.PAYMENT, + testSuite: ({ service }) => { + describe("Payment Module Service", () => { + describe("providers", () => { + it("should load payment plugins", async () => { + let error = await service + .createPaymentCollections([ + { + amount: 200, + region_id: "req_123", + } as any, + ]) + .catch((e) => e) - beforeAll(async () => { - await MikroOrmWrapper.setupDatabase() - - const initModulesConfig = getInitModuleConfig() - const { medusaApp, shutdown } = await initModules(initModulesConfig) - service = medusaApp.modules[Modules.PAYMENT] - - shutdownFunc = shutdown - }) - - afterAll(async () => { - await shutdownFunc() - }) - - beforeEach(async () => { - await MikroOrmWrapper.setupDatabase() - repositoryManager = await MikroOrmWrapper.forkManager() - - await createPaymentCollections(repositoryManager) - }) - - afterEach(async () => { - await MikroOrmWrapper.clearDatabase() - }) - - describe("providers", () => { - it("should load payment plugins", async () => { - let error = await service - .createPaymentCollections([ - { - amount: 200, - region_id: "req_123", - } as any, - ]) - .catch((e) => e) - - expect(error.message).toContain( - "Value for PaymentCollection.currency_code is required, 'undefined' found" - ) - }) - - it("should create a payment collection successfully", async () => { - const [createdPaymentCollection] = await service.createPaymentCollections( - [{ currency_code: "USD", amount: 200, region_id: "reg_123" }] - ) - - expect(createdPaymentCollection).toEqual( - expect.objectContaining({ - id: expect.any(String), - status: "not_paid", - payment_providers: [], - payment_sessions: [], - payments: [], - currency_code: "USD", - amount: 200, + expect(error.message).toContain( + "Value for PaymentCollection.currency_code is required, 'undefined' found" + ) }) - ) + + it("should create a payment collection successfully", async () => { + const [createdPaymentCollection] = + await service.createPaymentCollections([ + { currency_code: "USD", amount: 200, region_id: "reg_123" }, + ]) + + expect(createdPaymentCollection).toEqual( + expect.objectContaining({ + id: expect.any(String), + status: "not_paid", + payment_providers: [], + payment_sessions: [], + payments: [], + currency_code: "USD", + amount: 200, + }) + ) + }) + }) }) - }) + }, }) diff --git a/packages/modules/payment/integration-tests/__tests__/services/payment-module/index.spec.ts b/packages/modules/payment/integration-tests/__tests__/services/payment-module/index.spec.ts index 58f1f54a59..a83c5995af 100644 --- a/packages/modules/payment/integration-tests/__tests__/services/payment-module/index.spec.ts +++ b/packages/modules/payment/integration-tests/__tests__/services/payment-module/index.spec.ts @@ -1,10 +1,7 @@ import { Modules } from "@medusajs/modules-sdk" import { IPaymentModuleService } from "@medusajs/types" import { promiseAll } from "@medusajs/utils" -import { - moduleIntegrationTestRunner, - SuiteOptions, -} from "medusa-test-utils/dist" +import { moduleIntegrationTestRunner } from "medusa-test-utils/dist" import { createPaymentCollections, createPayments, @@ -13,12 +10,9 @@ import { jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.PAYMENT, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { describe("Payment Module Service", () => { describe("Payment Flow", () => { it("complete payment flow successfully", async () => { diff --git a/packages/modules/payment/integration-tests/setup-env.js b/packages/modules/payment/integration-tests/setup-env.js deleted file mode 100644 index ca80a7dace..0000000000 --- a/packages/modules/payment/integration-tests/setup-env.js +++ /dev/null @@ -1,6 +0,0 @@ -if (typeof process.env.DB_TEMP_NAME === "undefined") { - const tempName = parseInt(process.env.JEST_WORKER_ID || "1") - process.env.DB_TEMP_NAME = `medusa-payment-integration-${tempName}` -} - -process.env.MEDUSA_PAYMENT_DB_SCHEMA = "public" diff --git a/packages/modules/payment/integration-tests/setup.js b/packages/modules/payment/integration-tests/setup.js deleted file mode 100644 index 43f99aab4a..0000000000 --- a/packages/modules/payment/integration-tests/setup.js +++ /dev/null @@ -1,3 +0,0 @@ -import { JestUtils } from "medusa-test-utils" - -JestUtils.afterAllHookDropDatabase() diff --git a/packages/modules/payment/integration-tests/utils/config.ts b/packages/modules/payment/integration-tests/utils/config.ts deleted file mode 100644 index 5017bc79f0..0000000000 --- a/packages/modules/payment/integration-tests/utils/config.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { ModuleServiceInitializeOptions } from "@medusajs/types" - -export const databaseOptions: ModuleServiceInitializeOptions["database"] = { - schema: "public", - clientUrl: "medusa-payment-test", -} diff --git a/packages/modules/payment/integration-tests/utils/database.ts b/packages/modules/payment/integration-tests/utils/database.ts deleted file mode 100644 index 5afd38fe2c..0000000000 --- a/packages/modules/payment/integration-tests/utils/database.ts +++ /dev/null @@ -1,18 +0,0 @@ -import {TestDatabaseUtils} from "medusa-test-utils" - -import * as PaymentModules from "@models" - -const pathToMigrations = "../../src/migrations" -const mikroOrmEntities = PaymentModules as unknown as any[] - -export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({ - mikroOrmEntities, - pathToMigrations, -}) - -export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({ - mikroOrmEntities, - pathToMigrations, -}) - -export const DB_URL = TestDatabaseUtils.getDatabaseURL() diff --git a/packages/modules/payment/integration-tests/utils/get-init-module-config.ts b/packages/modules/payment/integration-tests/utils/get-init-module-config.ts deleted file mode 100644 index f3b49e9763..0000000000 --- a/packages/modules/payment/integration-tests/utils/get-init-module-config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { Modules, ModulesDefinition } from "@medusajs/modules-sdk" - -import { DB_URL } from "./database" - -export function getInitModuleConfig() { - const moduleOptions = { - providers: [ - { - resolve: "@medusajs/payment-stripe", - options: { - config: { - dkk: { - apiKey: "pk_test_123", - }, - usd: { - apiKey: "pk_test_456", - }, - }, - }, - }, - ], - } - - const injectedDependencies = {} - - const modulesConfig_ = { - [Modules.PAYMENT]: { - definition: ModulesDefinition[Modules.PAYMENT], - options: moduleOptions, - }, - } - - return { - injectedDependencies, - modulesConfig: modulesConfig_, - databaseConfig: { - clientUrl: DB_URL, - schema: process.env.MEDUSA_PAYMENT_DB_SCHEMA, - }, - joinerConfig: [], - } -} diff --git a/packages/modules/payment/integration-tests/utils/index.ts b/packages/modules/payment/integration-tests/utils/index.ts deleted file mode 100644 index 5ca5d1bdc0..0000000000 --- a/packages/modules/payment/integration-tests/utils/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./config" -export * from "./database" diff --git a/packages/modules/payment/jest.config.js b/packages/modules/payment/jest.config.js index fc8bdef49c..88c5539673 100644 --- a/packages/modules/payment/jest.config.js +++ b/packages/modules/payment/jest.config.js @@ -16,6 +16,4 @@ module.exports = { testEnvironment: `node`, moduleFileExtensions: [`js`, `ts`], modulePathIgnorePatterns: ["dist/"], - setupFiles: ["/integration-tests/setup-env.js"], - setupFilesAfterEnv: ["/integration-tests/setup.js"], } diff --git a/packages/modules/payment/package.json b/packages/modules/payment/package.json index bdd425c9c1..c278737167 100644 --- a/packages/modules/payment/package.json +++ b/packages/modules/payment/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-payment-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/payment/src/index.ts b/packages/modules/payment/src/index.ts index 17fdedcd8b..258757a402 100644 --- a/packages/modules/payment/src/index.ts +++ b/packages/modules/payment/src/index.ts @@ -1,5 +1,17 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" + +import { PaymentModuleService } from "@services" +import loadProviders from "./loaders/providers" +import loadDefaults from "./loaders/defaults" + +const service = PaymentModuleService +const loaders = [loadProviders, loadDefaults] as any + +export const moduleDefinition: ModuleExports = { + service, + loaders, +} export default moduleDefinition -export * from "./types" +export { PaymentModuleOptions } from "./types" diff --git a/packages/modules/payment/src/joiner-config.ts b/packages/modules/payment/src/joiner-config.ts index dfbd145b7b..045046193f 100644 --- a/packages/modules/payment/src/joiner-config.ts +++ b/packages/modules/payment/src/joiner-config.ts @@ -1,6 +1,9 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" import { Payment, PaymentCollection, @@ -8,54 +11,19 @@ import { PaymentSession, } from "@models" -export const LinkableKeys = { - payment_id: Payment.name, - payment_collection_id: PaymentCollection.name, - payment_provider_id: PaymentProvider.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) +export const joinerConfig = defineJoinerConfig(Modules.PAYMENT, { + entityQueryingConfig: [ + Payment, + PaymentCollection, + PaymentProvider, + PaymentSession, + ], + linkableKeys: { + payment_id: Payment.name, + payment_collection_id: PaymentCollection.name, + payment_provider_id: PaymentProvider.name, + }, }) -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.PAYMENT, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["payment", "payments"], - args: { - entity: Payment.name, - methodSuffix: "Payments", - }, - }, - { - name: ["payment_collection", "payment_collections"], - args: { - entity: PaymentCollection.name, - }, - }, - { - name: ["payment_session", "payment_sessions"], - args: { - entity: PaymentSession.name, - methodSuffix: "PaymentSessions", - }, - }, - { - name: ["payment_provider", "payment_providers"], - args: { - entity: PaymentProvider.name, - methodSuffix: "PaymentProviders", - }, - }, - ], -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/payment/src/module-definition.ts b/packages/modules/payment/src/module-definition.ts deleted file mode 100644 index ae5058a1cc..0000000000 --- a/packages/modules/payment/src/module-definition.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { ModuleExports } from "@medusajs/types" - -import { PaymentModuleService } from "@services" -import loadProviders from "./loaders/providers" -import loadDefaults from "./loaders/defaults" - -const service = PaymentModuleService -const loaders = [loadProviders, loadDefaults] as any - -export const moduleDefinition: ModuleExports = { - service, - loaders, -} diff --git a/packages/modules/payment/src/repositories/index.ts b/packages/modules/payment/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/payment/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/payment/src/scripts/bin/run-seed.ts b/packages/modules/payment/src/scripts/bin/run-seed.ts deleted file mode 100644 index ab7eacb3f3..0000000000 --- a/packages/modules/payment/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env node - -import { EOL } from "os" -import { ModulesSdkUtils } from "@medusajs/utils" -import { Modules } from "@medusajs/modules-sdk" - -import * as PaymentModels from "@models" - -import { createPayments } from "../seed-utils" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-payment-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.PAYMENT, - models: PaymentModels, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - const { paymentsData } = data - await createPayments(manager, paymentsData) - }, - }) - await run({ path }) -})() diff --git a/packages/modules/payment/src/scripts/seed-utils.ts b/packages/modules/payment/src/scripts/seed-utils.ts deleted file mode 100644 index a507d0b6bc..0000000000 --- a/packages/modules/payment/src/scripts/seed-utils.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { SqlEntityManager } from "@mikro-orm/postgresql" - -export async function createPayments( - manager: SqlEntityManager, - paymentsData: any[] -): Promise { - return [] -} diff --git a/packages/modules/payment/src/services/payment-module.ts b/packages/modules/payment/src/services/payment-module.ts index e4fd5ec0ff..b0861a212c 100644 --- a/packages/modules/payment/src/services/payment-module.ts +++ b/packages/modules/payment/src/services/payment-module.ts @@ -9,6 +9,7 @@ import { DAL, FilterablePaymentCollectionProps, FilterablePaymentProviderProps, + FilterablePaymentSessionProps, FindConfig, InternalModuleDeclaration, IPaymentModuleService, @@ -62,38 +63,29 @@ type InjectedDependencies = { const generateMethodForModels = { PaymentCollection, - Payment, PaymentSession, + Payment, Capture, Refund, } -export default class PaymentModuleService< - TPaymentCollection extends PaymentCollection = PaymentCollection, - TPayment extends Payment = Payment, - TCapture extends Capture = Capture, - TRefund extends Refund = Refund, - TPaymentSession extends PaymentSession = PaymentSession - > - extends ModulesSdkUtils.MedusaService< - PaymentCollectionDTO, - { - PaymentCollection: { dto: PaymentCollectionDTO } - PaymentSession: { dto: PaymentSessionDTO } - Payment: { dto: PaymentDTO } - Capture: { dto: CaptureDTO } - Refund: { dto: RefundDTO } - } - >(PaymentCollection, generateMethodForModels, entityNameToLinkableKeysMap) +export default class PaymentModuleService + extends ModulesSdkUtils.MedusaService<{ + PaymentCollection: { dto: PaymentCollectionDTO } + PaymentSession: { dto: PaymentSessionDTO } + Payment: { dto: PaymentDTO } + Capture: { dto: CaptureDTO } + Refund: { dto: RefundDTO } + }>(generateMethodForModels, entityNameToLinkableKeysMap) implements IPaymentModuleService { protected baseRepository_: DAL.RepositoryService - protected paymentService_: ModulesSdkTypes.IMedusaInternalService - protected captureService_: ModulesSdkTypes.IMedusaInternalService - protected refundService_: ModulesSdkTypes.IMedusaInternalService - protected paymentSessionService_: ModulesSdkTypes.IMedusaInternalService - protected paymentCollectionService_: ModulesSdkTypes.IMedusaInternalService + protected paymentService_: ModulesSdkTypes.IMedusaInternalService + protected captureService_: ModulesSdkTypes.IMedusaInternalService + protected refundService_: ModulesSdkTypes.IMedusaInternalService + protected paymentSessionService_: ModulesSdkTypes.IMedusaInternalService + protected paymentCollectionService_: ModulesSdkTypes.IMedusaInternalService protected paymentProviderService_: PaymentProviderService constructor( @@ -155,7 +147,7 @@ export default class PaymentModuleService< ) } - @InjectManager("baseRepository_") + @InjectTransactionManager("baseRepository_") async createPaymentCollections_( data: CreatePaymentCollectionDTO[], @MedusaContext() sharedContext?: Context @@ -527,6 +519,38 @@ export default class PaymentModuleService< return payment } + @InjectManager("baseRepository_") + // @ts-expect-error + async retrievePaymentSession( + id: string, + config: FindConfig = {}, + @MedusaContext() sharedContext?: Context + ): Promise { + const session = await this.paymentSessionService_.retrieve( + id, + config, + sharedContext + ) + + return await this.baseRepository_.serialize(session) + } + + @InjectManager("baseRepository_") + // @ts-expect-error + async listPaymentSessions( + filters?: FilterablePaymentSessionProps, + config?: FindConfig, + sharedContext?: Context + ): Promise { + const sessions = await this.paymentSessionService_.list( + filters, + config, + sharedContext + ) + + return await this.baseRepository_.serialize(sessions) + } + @InjectManager("baseRepository_") async updatePayment( data: UpdatePaymentDTO, @@ -822,7 +846,7 @@ export default class PaymentModuleService< case PaymentActions.SUCCESSFUL: { const [payment] = await this.listPayments( { - session_id: event.data.resource_id, + payment_session_id: event.data.resource_id, }, {}, sharedContext diff --git a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/calculate-price.spec.ts b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/calculate-price.spec.ts index 4fa786f4e1..e891208536 100644 --- a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/calculate-price.spec.ts +++ b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/calculate-price.spec.ts @@ -6,7 +6,7 @@ import { PricingTypes, } from "@medusajs/types" import { PriceListStatus, PriceListType } from "@medusajs/utils" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { seedPriceData } from "../../../__fixtures__/seed-price-data" jest.setTimeout(30000) @@ -49,12 +49,9 @@ const createPriceLists = async ( ]) } -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.PRICING, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { describe("PricingModule Service - Calculate Price", () => { describe("calculatePrices", () => { beforeEach(async () => { diff --git a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-list-rule.spec.ts b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-list-rule.spec.ts index 1e7372666b..c82864b993 100644 --- a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-list-rule.spec.ts +++ b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-list-rule.spec.ts @@ -1,19 +1,16 @@ import { Modules } from "@medusajs/modules-sdk" import { IPricingModuleService } from "@medusajs/types" import { SqlEntityManager } from "@mikro-orm/postgresql" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { createPriceLists } from "../../../__fixtures__/price-list" import { createPriceListRules } from "../../../__fixtures__/price-list-rules" import { createRuleTypes } from "../../../__fixtures__/rule-type" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.PRICING, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { describe("PriceListRule Service", () => { let testManager: SqlEntityManager beforeEach(async () => { diff --git a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-list.spec.ts b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-list.spec.ts index 2fdf75a4ac..f07c9c1718 100644 --- a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-list.spec.ts +++ b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-list.spec.ts @@ -3,7 +3,6 @@ import { IPricingModuleService } from "@medusajs/types" import { MockEventBusService, moduleIntegrationTestRunner, - SuiteOptions, } from "medusa-test-utils" import { createPriceLists } from "../../../__fixtures__/price-list" import { createPriceSets } from "../../../__fixtures__/price-set" @@ -11,12 +10,9 @@ import { CommonEvents, composeMessage, PricingEvents } from "@medusajs/utils" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.PRICING, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { let eventBusEmitSpy beforeEach(() => { @@ -886,7 +882,7 @@ moduleIntegrationTestRunner({ describe("updatePriceListPrices", () => { it("should update a price to a priceList successfully", async () => { - const [priceSet] = await service.create([ + const [priceSet] = await service.createPriceSets([ { rules: [ { rule_attribute: "region_id" }, @@ -988,7 +984,7 @@ moduleIntegrationTestRunner({ { name: "region_id", rule_attribute: "region_id" }, ]) - const [priceSet] = await service.create([ + const [priceSet] = await service.createPriceSets([ { rules: [{ rule_attribute: "region_id" }] }, ]) @@ -1031,7 +1027,7 @@ moduleIntegrationTestRunner({ describe("removePrices", () => { it("should remove prices from a priceList successfully", async () => { - const [priceSet] = await service.create([ + const [priceSet] = await service.createPriceSets([ { rules: [{ rule_attribute: "region_id" }] }, ]) diff --git a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-rule.spec.ts b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-rule.spec.ts index 962c5aabba..a5ab2dba6e 100644 --- a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-rule.spec.ts +++ b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-rule.spec.ts @@ -1,8 +1,8 @@ import { Modules } from "@medusajs/modules-sdk" import { IPricingModuleService } from "@medusajs/types" import { SqlEntityManager } from "@mikro-orm/postgresql" -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" -import { Price } from "../../../../src" +import { moduleIntegrationTestRunner } from "medusa-test-utils" +import { Price } from "../../../../src/models" import { createPrices } from "../../../__fixtures__/price" import { createPriceRules } from "../../../__fixtures__/price-rule" import { createPriceSets } from "../../../__fixtures__/price-set" @@ -10,12 +10,9 @@ import { createRuleTypes } from "../../../__fixtures__/rule-type" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.PRICING, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { describe("PricingModule Service - PriceRule", () => { let testManager: SqlEntityManager beforeEach(async () => { @@ -279,7 +276,7 @@ moduleIntegrationTestRunner({ price_set_id: "price-set-1", title: "test", rules_count: 0, - }) + } as Price) await testManager.persist(price).flush() diff --git a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-set.spec.ts b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-set.spec.ts index 62599f453f..efa05d3700 100644 --- a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-set.spec.ts +++ b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/price-set.spec.ts @@ -8,9 +8,8 @@ import { SqlEntityManager } from "@mikro-orm/postgresql" import { MockEventBusService, moduleIntegrationTestRunner, - SuiteOptions, } from "medusa-test-utils" -import { PriceSetRuleType } from "../../../../src" +import { PriceSetRuleType } from "../../../../src/models" import { seedPriceData } from "../../../__fixtures__/seed-price-data" import { CommonEvents, composeMessage, PricingEvents } from "@medusajs/utils" @@ -31,12 +30,9 @@ async function createPriceSetPriceRules( await manager.persistAndFlush(priceSetRules) } -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.PRICING, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { let eventBusEmitSpy beforeEach(() => { @@ -65,7 +61,7 @@ moduleIntegrationTestRunner({ describe("list", () => { it("list priceSets", async () => { - const priceSetsResult = await service.list() + const priceSetsResult = await service.listPriceSets() expect(priceSetsResult).toEqual([ expect.objectContaining({ @@ -81,7 +77,7 @@ moduleIntegrationTestRunner({ }) it("list priceSets by id", async () => { - const priceSetsResult = await service.list({ + const priceSetsResult = await service.listPriceSets({ id: ["price-set-1"], }) @@ -93,7 +89,7 @@ moduleIntegrationTestRunner({ }) it("list priceSets with relations and selects", async () => { - const priceSetsResult = await service.list( + const priceSetsResult = await service.listPriceSets( { id: ["price-set-1"], }, @@ -121,7 +117,7 @@ moduleIntegrationTestRunner({ describe("listAndCount", () => { it("should return priceSets and count", async () => { - const [priceSetsResult, count] = await service.listAndCount() + const [priceSetsResult, count] = await service.listAndCountPriceSets() expect(count).toEqual(3) expect(priceSetsResult).toEqual([ @@ -138,7 +134,7 @@ moduleIntegrationTestRunner({ }) it("should return priceSets and count when filtered", async () => { - const [priceSetsResult, count] = await service.listAndCount({ + const [priceSetsResult, count] = await service.listAndCountPriceSets({ id: ["price-set-1"], }) @@ -151,7 +147,7 @@ moduleIntegrationTestRunner({ }) it("list priceSets with relations and selects", async () => { - const [priceSetsResult, count] = await service.listAndCount( + const [priceSetsResult, count] = await service.listAndCountPriceSets( { id: ["price-set-1"], }, @@ -178,7 +174,7 @@ moduleIntegrationTestRunner({ }) it("should return priceSets and count when using skip and take", async () => { - const [priceSetsResult, count] = await service.listAndCount( + const [priceSetsResult, count] = await service.listAndCountPriceSets( {}, { skip: 1, take: 1 } ) @@ -192,7 +188,7 @@ moduleIntegrationTestRunner({ }) it("should return requested fields", async () => { - const [priceSetsResult, count] = await service.listAndCount( + const [priceSetsResult, count] = await service.listAndCountPriceSets( {}, { take: 1, @@ -215,7 +211,7 @@ moduleIntegrationTestRunner({ const id = "price-set-1" it("should return priceSet for the given id", async () => { - const priceSet = await service.retrieve(id) + const priceSet = await service.retrievePriceSet(id) expect(priceSet).toEqual( expect.objectContaining({ @@ -228,7 +224,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve("does-not-exist") + await service.retrievePriceSet("does-not-exist") } catch (e) { error = e } @@ -242,7 +238,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve(undefined as unknown as string) + await service.retrievePriceSet(undefined as unknown as string) } catch (e) { error = e } @@ -251,7 +247,7 @@ moduleIntegrationTestRunner({ }) it("should return priceSet based on config select param", async () => { - const priceSet = await service.retrieve(id, { + const priceSet = await service.retrievePriceSet(id, { select: ["id"], }) @@ -267,9 +263,9 @@ moduleIntegrationTestRunner({ const id = "price-set-1" it("should delete the priceSets given an id successfully", async () => { - await service.delete([id]) + await service.deletePriceSets([id]) - const priceSets = await service.list({ + const priceSets = await service.listPriceSets({ id: [id], }) @@ -282,7 +278,7 @@ moduleIntegrationTestRunner({ it("should throw an error when an id does not exist", async () => { let error = await service - .update("does-not-exist", {}) + .updatePriceSets("does-not-exist", {}) .catch((e) => e.message) expect(error).toEqual( @@ -291,18 +287,21 @@ moduleIntegrationTestRunner({ }) it("should create, update, and delete prices to a price set", async () => { - const priceSetBefore = await service.retrieve(id, { + const priceSetBefore = await service.retrievePriceSet(id, { relations: ["prices"], }) - const updateResponse = await service.update(priceSetBefore.id, { - prices: [ - { amount: 100, currency_code: "USD" }, - { amount: 200, currency_code: "EUR" }, - ], - }) + const updateResponse = await service.updatePriceSets( + priceSetBefore.id, + { + prices: [ + { amount: 100, currency_code: "USD" }, + { amount: 200, currency_code: "EUR" }, + ], + } + ) - const priceSetAfter = await service.retrieve(id, { + const priceSetAfter = await service.retrievePriceSet(id, { relations: ["prices"], }) expect(priceSetBefore.prices).toHaveLength(1) @@ -347,7 +346,7 @@ moduleIntegrationTestRunner({ let error try { - await service.create([ + await service.createPriceSets([ { rules: [{ rule_attribute: "does-not-exist" }], }, @@ -365,7 +364,7 @@ moduleIntegrationTestRunner({ let error try { - await service.create([ + await service.createPriceSets([ { rules: [{ rule_attribute: "region_id" }], prices: [ @@ -388,7 +387,7 @@ moduleIntegrationTestRunner({ }) it("should create a price set with rule types", async () => { - const [priceSet] = await service.create([ + const [priceSet] = await service.createPriceSets([ { rules: [{ rule_attribute: "region_id" }], }, @@ -406,7 +405,7 @@ moduleIntegrationTestRunner({ }) it("should create a price set with rule types and money amounts", async () => { - const [priceSet] = await service.create([ + const [priceSet] = await service.createPriceSets([ { rules: [{ rule_attribute: "region_id" }], prices: [ @@ -475,7 +474,7 @@ moduleIntegrationTestRunner({ }) it("should create a price set with money amounts with and without rules", async () => { - const [priceSet] = await service.create([ + const [priceSet] = await service.createPriceSets([ { rules: [{ rule_attribute: "region_id" }], prices: [ @@ -516,7 +515,7 @@ moduleIntegrationTestRunner({ }) it("should create a price set with rule types and money amounts", async () => { - const [priceSet] = await service.create([ + const [priceSet] = await service.createPriceSets([ { rules: [{ rule_attribute: "region_id" }], prices: [ @@ -554,13 +553,13 @@ moduleIntegrationTestRunner({ }) it("should create a priceSet successfully", async () => { - await service.create([ + await service.createPriceSets([ { id: "price-set-new", } as unknown as CreatePriceSetDTO, ]) - const [priceSet] = await service.list({ + const [priceSet] = await service.listPriceSets({ id: ["price-set-new"], }) @@ -574,7 +573,7 @@ moduleIntegrationTestRunner({ describe("removeRules", () => { it("should delete prices for a price set associated to the rules that are deleted", async () => { - const createdPriceSet = await service.create([ + const createdPriceSet = await service.createPriceSets([ { rules: [ { rule_attribute: "region_id" }, @@ -604,7 +603,7 @@ moduleIntegrationTestRunner({ { id: createdPriceSet[0].id, rules: ["region_id"] }, ]) - let priceSet = await service.list( + let priceSet = await service.listPriceSets( { id: [createdPriceSet[0].id] }, { relations: ["rule_types", "prices", "price_rules"] } ) @@ -640,7 +639,7 @@ moduleIntegrationTestRunner({ { id: createdPriceSet[0].id, rules: ["currency_code"] }, ]) - priceSet = await service.list( + priceSet = await service.listPriceSets( { id: [createdPriceSet[0].id] }, { relations: ["rule_types", "prices", "price_rules"] } ) @@ -673,7 +672,7 @@ moduleIntegrationTestRunner({ }, ]) - const [priceSet] = await service.list( + const [priceSet] = await service.listPriceSets( { id: ["price-set-1"] }, { relations: ["prices", "prices.price_rules"] } ) @@ -734,7 +733,7 @@ moduleIntegrationTestRunner({ }, ]) - const priceSets = await service.list( + const priceSets = await service.listPriceSets( { id: ["price-set-1", "price-set-2"] }, { relations: ["prices"] } ) @@ -791,7 +790,7 @@ moduleIntegrationTestRunner({ }, ]) - const [priceSet] = await service.list( + const [priceSet] = await service.listPriceSets( { id: ["price-set-1"] }, { relations: ["rule_types"] } ) diff --git a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/rule-type.spec.ts b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/rule-type.spec.ts index 8ecb4af0d6..82efd6ba6f 100644 --- a/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/rule-type.spec.ts +++ b/packages/modules/pricing/integration-tests/__tests__/services/pricing-module/rule-type.spec.ts @@ -1,16 +1,13 @@ import { createRuleTypes } from "../../../__fixtures__/rule-type" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { Modules } from "@medusajs/modules-sdk" import { IPricingModuleService } from "@medusajs/types" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.PRICING, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { describe("PricingModuleService ruleType", () => { beforeEach(async () => { const testManager = MikroOrmWrapper.forkManager() diff --git a/packages/modules/pricing/package.json b/packages/modules/pricing/package.json index f5580f8d56..14301d691b 100644 --- a/packages/modules/pricing/package.json +++ b/packages/modules/pricing/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-pricing-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/pricing/src/index.ts b/packages/modules/pricing/src/index.ts index be203865a1..30003a7cfb 100644 --- a/packages/modules/pricing/src/index.ts +++ b/packages/modules/pricing/src/index.ts @@ -1,7 +1,12 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { PricingModuleService } from "@services" + +const service = PricingModuleService + +export const moduleDefinition: ModuleExports = { + service, +} export default moduleDefinition -export * from "./models" -export * from "./services" export * from "./types" diff --git a/packages/modules/pricing/src/joiner-config.ts b/packages/modules/pricing/src/joiner-config.ts index 8a573bfcc6..ce7c3cd2cb 100644 --- a/packages/modules/pricing/src/joiner-config.ts +++ b/packages/modules/pricing/src/joiner-config.ts @@ -1,56 +1,20 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" import { Price, PriceList, PriceSet, RuleType } from "@models" -import schema from "./schema" -export const LinkableKeys = { - price_set_id: PriceSet.name, - price_list_id: PriceList.name, - price_id: Price.name, - rule_type_id: RuleType.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) +export const joinerConfig = defineJoinerConfig(Modules.PRICING, { + entityQueryingConfig: [PriceSet, PriceList, Price, RuleType], + linkableKeys: { + price_set_id: PriceSet.name, + price_list_id: PriceList.name, + price_id: Price.name, + rule_type_id: RuleType.name, + }, }) -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.PRICING, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - schema, - alias: [ - { - name: ["price_set", "price_sets"], - args: { - entity: "PriceSet", - }, - }, - { - name: ["price_list", "price_lists"], - args: { - methodSuffix: "PriceLists", - }, - }, - { - name: ["price", "prices"], - args: { - methodSuffix: "Prices", - }, - }, - { - name: ["rule_type", "rule_types"], - args: { - methodSuffix: "RuleTypes", - }, - }, - ], -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/pricing/src/module-definition.ts b/packages/modules/pricing/src/module-definition.ts deleted file mode 100644 index f3d0ca848e..0000000000 --- a/packages/modules/pricing/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { PricingModuleService } from "@services" - -const service = PricingModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/pricing/src/scripts/bin/run-seed.ts b/packages/modules/pricing/src/scripts/bin/run-seed.ts deleted file mode 100644 index 26880f61fb..0000000000 --- a/packages/modules/pricing/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env node - -import { EOL } from "os" -import { run } from "../seed" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-pricing-seed ` - ) - } - - await run({ path }) -})() diff --git a/packages/modules/pricing/src/scripts/seed.ts b/packages/modules/pricing/src/scripts/seed.ts deleted file mode 100644 index c34fbe349a..0000000000 --- a/packages/modules/pricing/src/scripts/seed.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types" -import { DALUtils, ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema, RequiredEntityData } from "@mikro-orm/core" -import { PostgreSqlDriver, SqlEntityManager } from "@mikro-orm/postgresql" -import * as PricingModels from "@models" -import { EOL } from "os" -import { resolve } from "path" - -export async function run({ - options, - logger, - path, -}: Partial< - Pick< - LoaderOptions, - "options" | "logger" - > -> & { - path: string -}) { - logger ??= console as unknown as Logger - - logger.info(`Loading seed data from ${path}...`) - - const { priceSetsData, pricesData } = await import( - resolve(process.cwd(), path) - ).catch((e) => { - logger?.error( - `Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: priceSetsData and pricesData.${EOL}${e}` - ) - throw e - }) - - const dbData = ModulesSdkUtils.loadDatabaseConfig("pricing", options)! - const entities = Object.values(PricingModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - const orm = await DALUtils.mikroOrmCreateConnection( - dbData, - entities, - pathToMigrations - ) - - const manager = orm.em.fork() - - try { - logger.info("Inserting price_sets & prices") - - await createPriceSets(manager, priceSetsData) - await createPrices(manager, pricesData) - } catch (e) { - logger.error( - `Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}` - ) - } - - await orm.close(true) -} - -async function createPriceSets( - manager: SqlEntityManager, - data: RequiredEntityData[] -) { - const priceSets = data.map((priceSetData) => { - return manager.create(PricingModels.PriceSet, priceSetData) - }) - - await manager.persistAndFlush(priceSets) - - return priceSets -} - -async function createPrices( - manager: SqlEntityManager, - data: RequiredEntityData[] -) { - const prices = data.map((priceData) => { - return manager.create(PricingModels.Price, priceData) - }) - - await manager.persistAndFlush(prices) - - return prices -} diff --git a/packages/modules/pricing/src/services/pricing-module.ts b/packages/modules/pricing/src/services/pricing-module.ts index 467cb8a0fd..5841277085 100644 --- a/packages/modules/pricing/src/services/pricing-module.ts +++ b/packages/modules/pricing/src/services/pricing-module.ts @@ -68,6 +68,7 @@ type InjectedDependencies = { } const generateMethodForModels = { + PriceSet, PriceList, PriceListRule, PriceListRuleValue, @@ -77,46 +78,35 @@ const generateMethodForModels = { RuleType, } -export default class PricingModuleService< - TPriceSet extends PriceSet = PriceSet, - TRuleType extends RuleType = RuleType, - TPriceRule extends PriceRule = PriceRule, - TPriceSetRuleType extends PriceSetRuleType = PriceSetRuleType, - TPrice extends Price = Price, - TPriceList extends PriceList = PriceList, - TPriceListRule extends PriceListRule = PriceListRule, - TPriceListRuleValue extends PriceListRuleValue = PriceListRuleValue - > - extends ModulesSdkUtils.MedusaService< - PricingTypes.PriceSetDTO, - { - Price: { dto: PricingTypes.PriceDTO } - PriceRule: { - dto: PricingTypes.PriceRuleDTO - create: PricingTypes.CreatePriceRuleDTO - update: PricingTypes.UpdatePriceRuleDTO - } - RuleType: { - dto: PricingTypes.RuleTypeDTO - create: PricingTypes.CreateRuleTypeDTO - update: PricingTypes.UpdateRuleTypeDTO - } - PriceList: { dto: PricingTypes.PriceListDTO } - PriceListRule: { dto: PricingTypes.PriceListRuleDTO } +export default class PricingModuleService + extends ModulesSdkUtils.MedusaService<{ + PriceSet: { dto: PricingTypes.PriceSetDTO } + Price: { dto: PricingTypes.PriceDTO } + PriceRule: { + dto: PricingTypes.PriceRuleDTO + create: PricingTypes.CreatePriceRuleDTO + update: PricingTypes.UpdatePriceRuleDTO } - >(PriceSet, generateMethodForModels, entityNameToLinkableKeysMap) + RuleType: { + dto: PricingTypes.RuleTypeDTO + create: PricingTypes.CreateRuleTypeDTO + update: PricingTypes.UpdateRuleTypeDTO + } + PriceList: { dto: PricingTypes.PriceListDTO } + PriceListRule: { dto: PricingTypes.PriceListRuleDTO } + }>(generateMethodForModels, entityNameToLinkableKeysMap) implements PricingTypes.IPricingModuleService { protected baseRepository_: DAL.RepositoryService protected readonly pricingRepository_: PricingRepositoryService - protected readonly ruleTypeService_: RuleTypeService - protected readonly priceSetService_: ModulesSdkTypes.IMedusaInternalService - protected readonly priceRuleService_: ModulesSdkTypes.IMedusaInternalService - protected readonly priceSetRuleTypeService_: ModulesSdkTypes.IMedusaInternalService - protected readonly priceService_: ModulesSdkTypes.IMedusaInternalService - protected readonly priceListService_: PriceListService - protected readonly priceListRuleService_: ModulesSdkTypes.IMedusaInternalService - protected readonly priceListRuleValueService_: ModulesSdkTypes.IMedusaInternalService + protected readonly ruleTypeService_: RuleTypeService + protected readonly priceSetService_: ModulesSdkTypes.IMedusaInternalService + protected readonly priceRuleService_: ModulesSdkTypes.IMedusaInternalService + protected readonly priceSetRuleTypeService_: ModulesSdkTypes.IMedusaInternalService + protected readonly priceService_: ModulesSdkTypes.IMedusaInternalService + protected readonly priceListService_: PriceListService + protected readonly priceListRuleService_: ModulesSdkTypes.IMedusaInternalService + protected readonly priceListRuleValueService_: ModulesSdkTypes.IMedusaInternalService constructor( { @@ -174,14 +164,15 @@ export default class PricingModuleService< } @InjectManager("baseRepository_") - async list( + // @ts-expect-error + async listPriceSets( filters: PricingTypes.FilterablePriceSetProps = {}, config: FindConfig = {}, @MedusaContext() sharedContext: Context = {} ): Promise { const pricingContext = this.setupCalculatedPriceConfig_(filters, config) - const priceSets = await super.list(filters, config, sharedContext) + const priceSets = await super.listPriceSets(filters, config, sharedContext) if (pricingContext && priceSets.length) { const priceSetIds: string[] = [] @@ -207,14 +198,15 @@ export default class PricingModuleService< } @InjectManager("baseRepository_") - async listAndCount( + // @ts-expect-error + async listAndCountPriceSets( filters: PricingTypes.FilterablePriceSetProps = {}, config: FindConfig = {}, @MedusaContext() sharedContext: Context = {} ): Promise<[PriceSetDTO[], number]> { const pricingContext = this.setupCalculatedPriceConfig_(filters, config) - const [priceSets, count] = await super.listAndCount( + const [priceSets, count] = await super.listAndCountPriceSets( filters, config, sharedContext @@ -315,27 +307,28 @@ export default class PricingModuleService< return JSON.parse(JSON.stringify(calculatedPrices)) } - async create( + // @ts-expect-error + async createPriceSets( data: PricingTypes.CreatePriceSetDTO, sharedContext?: Context ): Promise - async create( + async createPriceSets( data: PricingTypes.CreatePriceSetDTO[], sharedContext?: Context ): Promise @InjectManager("baseRepository_") @EmitEvents() - async create( + async createPriceSets( data: PricingTypes.CreatePriceSetDTO | PricingTypes.CreatePriceSetDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const priceSets = await this.create_(input, sharedContext) + const priceSets = await this.createPriceSets_(input, sharedContext) // TODO: Remove the need to refetch the data here - const dbPriceSets = await this.list( + const dbPriceSets = await this.listPriceSets( { id: priceSets.map((p) => p.id) }, { relations: [ @@ -358,17 +351,17 @@ export default class PricingModuleService< ) } - async upsert( + async upsertPriceSets( data: UpsertPriceSetDTO[], sharedContext?: Context ): Promise - async upsert( + async upsertPriceSets( data: UpsertPriceSetDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async upsert( + async upsertPriceSets( data: UpsertPriceSetDTO | UpsertPriceSetDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -383,10 +376,10 @@ export default class PricingModuleService< const operations: Promise[] = [] if (forCreate.length) { - operations.push(this.create_(forCreate, sharedContext)) + operations.push(this.createPriceSets_(forCreate, sharedContext)) } if (forUpdate.length) { - operations.push(this.update_(forUpdate, sharedContext)) + operations.push(this.updatePriceSets_(forUpdate, sharedContext)) } const result = (await promiseAll(operations)).flat() @@ -395,19 +388,20 @@ export default class PricingModuleService< ) } - async update( + // @ts-expect-error + async updatePriceSets( id: string, data: PricingTypes.UpdatePriceSetDTO, sharedContext?: Context ): Promise - async update( + async updatePriceSets( selector: PricingTypes.FilterablePriceSetProps, data: PricingTypes.UpdatePriceSetDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async update( + async updatePriceSets( idOrSelector: string | PricingTypes.FilterablePriceSetProps, data: PricingTypes.UpdatePriceSetDTO, @MedusaContext() sharedContext: Context = {} @@ -430,7 +424,10 @@ export default class PricingModuleService< })) } - const updateResult = await this.update_(normalizedInput, sharedContext) + const updateResult = await this.updatePriceSets_( + normalizedInput, + sharedContext + ) const priceSets = await this.baseRepository_.serialize< PriceSetDTO[] | PriceSetDTO >(updateResult) @@ -487,7 +484,7 @@ export default class PricingModuleService< } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updatePriceSets_( data: ServiceTypes.UpdatePriceSetInput[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -549,7 +546,7 @@ export default class PricingModuleService< const priceSets = await this.addRules_(inputs, sharedContext) - const dbPriceSets = await this.list( + const dbPriceSets = await this.listPriceSets( { id: priceSets.map(({ id }) => id) }, { relations: ["rule_types"] } ) @@ -581,7 +578,7 @@ export default class PricingModuleService< await this.addPrices_(input, sharedContext) - const dbPrices = await this.list( + const dbPrices = await this.listPriceSets( { id: input.map((d) => d.priceSetId) }, { relations: ["prices"] }, sharedContext @@ -719,7 +716,7 @@ export default class PricingModuleService< } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createPriceSets_( data: PricingTypes.CreatePriceSetDTO[], @MedusaContext() sharedContext: Context = {} ) { @@ -767,11 +764,11 @@ export default class PricingModuleService< ) } - const ruleSetRuleTypeToCreateMap: Map = new Map() + const ruleSetRuleTypeToCreateMap: Map = new Map() const toCreate = input.map((inputData) => { const id = generateEntityId( - (inputData as unknown as TPriceSet).id, + (inputData as unknown as PriceSet).id, PriceSetIdPrefix ) @@ -783,7 +780,7 @@ export default class PricingModuleService< const priceSetRuleType = { rule_type_id: ruleTypeMap.get(rule.rule_attribute).id, price_set_id: id, - } as TPriceSetRuleType + } as PriceSetRuleType ruleSetRuleTypeToCreateMap.set( JSON.stringify(priceSetRuleType), @@ -810,7 +807,7 @@ export default class PricingModuleService< const priceSetRuleType = { rule_type_id: ruleTypeMap.get(attribute).id, price_set_id: id, - } as TPriceSetRuleType + } as PriceSetRuleType ruleSetRuleTypeToCreateMap.set( JSON.stringify(priceSetRuleType), @@ -897,7 +894,7 @@ export default class PricingModuleService< protected async addRules_( inputs: PricingTypes.AddRulesDTO[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const priceSets = await this.priceSetService_.list( { id: inputs.map((d) => d.priceSetId) }, { relations: ["rule_types"] }, @@ -981,7 +978,7 @@ export default class PricingModuleService< input: AddPricesDTO[], @MedusaContext() sharedContext: Context = {} ) { - const priceSets = await this.list( + const priceSets = await this.listPriceSets( { id: input.map((d) => d.priceSetId) }, { relations: ["rule_types"] }, sharedContext @@ -1137,7 +1134,7 @@ export default class PricingModuleService< const priceListsToCreate: PricingTypes.CreatePriceListDTO[] = data.map( (priceListData) => { const id = generateEntityId( - (priceListData as unknown as TPriceList).id, + (priceListData as unknown as PriceList).id, PriceListIdPrefix ) @@ -1364,7 +1361,7 @@ export default class PricingModuleService< protected async updatePriceListPrices_( data: PricingTypes.UpdatePriceListPricesDTO[], sharedContext: Context = {} - ): Promise { + ): Promise { const ruleTypeAttributes: string[] = [] const priceListIds: string[] = [] const priceIds: string[] = [] @@ -1401,7 +1398,7 @@ export default class PricingModuleService< ruleTypes.map((rt) => [rt.rule_attribute, rt]) ) - const priceSets = await this.list( + const priceSets = await this.listPriceSets( { id: priceSetIds }, { relations: ["rule_types"] }, sharedContext @@ -1456,7 +1453,7 @@ export default class PricingModuleService< const priceListMap = new Map(priceLists.map((p) => [p.id, p])) - const pricesToUpdate: Partial[] = [] + const pricesToUpdate: Partial[] = [] const priceRuleIdsToDelete: string[] = [] const priceRulesToCreate: CreatePriceRuleDTO[] = [] @@ -1487,7 +1484,7 @@ export default class PricingModuleService< pricesToUpdate.push({ ...rest, rules_count: Object.keys(rules).length, - } as unknown as TPrice) + } as unknown as Price) priceRuleIdsToDelete.push(...priceRules.map((pr) => pr.id)) } @@ -1515,7 +1512,7 @@ export default class PricingModuleService< protected async addPriceListPrices_( data: PricingTypes.AddPriceListPricesDTO[], sharedContext: Context = {} - ): Promise { + ): Promise { const ruleTypeAttributes: string[] = [] const priceListIds: string[] = [] const priceSetIds: string[] = [] @@ -1535,7 +1532,7 @@ export default class PricingModuleService< sharedContext ) - const priceSets = await this.list( + const priceSets = await this.listPriceSets( { id: priceSetIds }, { relations: ["rule_types"] }, sharedContext @@ -1593,7 +1590,7 @@ export default class PricingModuleService< const priceListMap = new Map(priceLists.map((p) => [p.id, p])) - const pricesToCreate: Partial[] = [] + const pricesToCreate: Partial[] = [] for (const { price_list_id: priceListId, prices } of data) { const priceList = priceListMap.get(priceListId) @@ -1626,7 +1623,7 @@ export default class PricingModuleService< price_list_id: priceList.id, rules_count: noOfRules, price_rules: priceRulesToCreate, - } as unknown as TPrice + } as unknown as Price }) pricesToCreate.push(...priceListPricesToCreate) @@ -1676,7 +1673,7 @@ export default class PricingModuleService< protected async setPriceListRules_( data: PricingTypes.SetPriceListRulesDTO[], sharedContext: Context = {} - ): Promise { + ): Promise { // TODO: re think this method const priceLists = await this.priceListService_.list( @@ -1791,7 +1788,7 @@ export default class PricingModuleService< protected async removePriceListRules_( data: PricingTypes.RemovePriceListRulesDTO[], sharedContext: Context = {} - ): Promise { + ): Promise { const priceLists = await this.priceListService_.list( { id: data.map((d) => d.price_list_id) }, { relations: ["price_list_rules", "price_list_rules.rule_type"] }, diff --git a/packages/modules/product/integration-tests/__tests__/product-category.ts b/packages/modules/product/integration-tests/__tests__/product-category.ts index 082b1df6f0..d75285d105 100644 --- a/packages/modules/product/integration-tests/__tests__/product-category.ts +++ b/packages/modules/product/integration-tests/__tests__/product-category.ts @@ -17,7 +17,7 @@ type Service = IProductModuleService & { moduleIntegrationTestRunner({ moduleName: Modules.PRODUCT, - testSuite: ({ MikroOrmWrapper, service: moduleService }) => { + testSuite: ({ service: moduleService }) => { describe("Product category Service", () => { let service: ProductCategoryService diff --git a/packages/modules/product/integration-tests/__tests__/product-module-service/product-categories.spec.ts b/packages/modules/product/integration-tests/__tests__/product-module-service/product-categories.spec.ts index 4bda341642..f0b0db9fa9 100644 --- a/packages/modules/product/integration-tests/__tests__/product-module-service/product-categories.spec.ts +++ b/packages/modules/product/integration-tests/__tests__/product-module-service/product-categories.spec.ts @@ -53,7 +53,7 @@ moduleIntegrationTestRunner({ productCategories = [] for (const entry of productCategoriesData) { - productCategories.push(await service.createCategories(entry)) + productCategories.push(await service.createProductCategories(entry)) } productCategoryOne = productCategories[0] productCategoryTwo = productCategories[1] @@ -65,7 +65,7 @@ moduleIntegrationTestRunner({ describe("listCategories", () => { it("should return categories queried by ID", async () => { - const results = await service.listCategories({ + const results = await service.listProductCategories({ id: productCategoryOne.id, }) @@ -77,7 +77,7 @@ moduleIntegrationTestRunner({ }) it("should return categories based on the options and filter parameter", async () => { - let results = await service.listCategories( + let results = await service.listProductCategories( { id: productCategoryOne.id, }, @@ -92,7 +92,10 @@ moduleIntegrationTestRunner({ }), ]) - results = await service.listCategories({}, { take: 1, skip: 1 }) + results = await service.listProductCategories( + {}, + { take: 1, skip: 1 } + ) expect(results).toEqual([ expect.objectContaining({ @@ -102,7 +105,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for categories", async () => { - const results = await service.listCategories( + const results = await service.listProductCategories( { id: productCategoryOne.id, }, @@ -129,7 +132,7 @@ moduleIntegrationTestRunner({ describe("listAndCountCategories", () => { it("should return categories and count queried by ID", async () => { - const results = await service.listAndCountCategories({ + const results = await service.listAndCountProductCategories({ id: productCategoryOne.id, }) @@ -142,7 +145,7 @@ moduleIntegrationTestRunner({ }) it("should return categories and count based on the options and filter parameter", async () => { - let results = await service.listAndCountCategories( + let results = await service.listAndCountProductCategories( { id: productCategoryOne.id, }, @@ -158,11 +161,11 @@ moduleIntegrationTestRunner({ }), ]) - results = await service.listAndCountCategories({}, { take: 1 }) + results = await service.listAndCountProductCategories({}, { take: 1 }) expect(results[1]).toEqual(2) - results = await service.listAndCountCategories( + results = await service.listAndCountProductCategories( {}, { take: 1, skip: 1 } ) @@ -176,7 +179,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for categories", async () => { - const results = await service.listAndCountCategories( + const results = await service.listAndCountProductCategories( { id: productCategoryOne.id, }, @@ -204,9 +207,12 @@ moduleIntegrationTestRunner({ describe("retrieveCategory", () => { it("should return the requested category", async () => { - const result = await service.retrieveCategory(productCategoryOne.id, { - select: ["id", "name"], - }) + const result = await service.retrieveProductCategory( + productCategoryOne.id, + { + select: ["id", "name"], + } + ) expect(result).toEqual( expect.objectContaining({ @@ -217,10 +223,13 @@ moduleIntegrationTestRunner({ }) it("should return requested attributes when requested through config", async () => { - const result = await service.retrieveCategory(productCategoryOne.id, { - select: ["id", "name", "products.title"], - relations: ["products"], - }) + const result = await service.retrieveProductCategory( + productCategoryOne.id, + { + select: ["id", "name", "products.title"], + relations: ["products"], + } + ) expect(result).toEqual( expect.objectContaining({ @@ -240,7 +249,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieveCategory("does-not-exist") + await service.retrieveProductCategory("does-not-exist") } catch (e) { error = e } @@ -253,12 +262,12 @@ moduleIntegrationTestRunner({ describe("createCategory", () => { it("should create a category successfully", async () => { - await service.createCategories({ + await service.createProductCategories({ name: "New Category", parent_category_id: productCategoryOne.id, }) - const [productCategory] = await service.listCategories( + const [productCategory] = await service.listProductCategories( { name: "New Category", }, @@ -278,7 +287,7 @@ moduleIntegrationTestRunner({ it("should emit events through event bus", async () => { const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") - const category = await service.createCategories({ + const category = await service.createProductCategories({ name: "New Category", parent_category_id: productCategoryOne.id, }) @@ -293,18 +302,18 @@ moduleIntegrationTestRunner({ }) it("should append rank from an existing category depending on parent", async () => { - await service.createCategories({ + await service.createProductCategories({ name: "New Category", parent_category_id: productCategoryOne.id, rank: 0, }) - await service.createCategories({ + await service.createProductCategories({ name: "New Category 2", parent_category_id: productCategoryOne.id, }) - const [productCategoryNew] = await service.listCategories( + const [productCategoryNew] = await service.listProductCategories( { name: "New Category 2", }, @@ -320,19 +329,20 @@ moduleIntegrationTestRunner({ }) ) - await service.createCategories({ + await service.createProductCategories({ name: "New Category 2.1", parent_category_id: productCategoryNew.id, }) - const [productCategoryWithParent] = await service.listCategories( - { - name: "New Category 2.1", - }, - { - select: ["name", "rank", "parent_category_id"], - } - ) + const [productCategoryWithParent] = + await service.listProductCategories( + { + name: "New Category 2.1", + }, + { + select: ["name", "rank", "parent_category_id"], + } + ) expect(productCategoryWithParent).toEqual( expect.objectContaining({ @@ -356,7 +366,7 @@ moduleIntegrationTestRunner({ beforeEach(async () => { categories = [] for (const entry of productCategoriesRankData) { - categories.push(await service.createCategories(entry)) + categories.push(await service.createProductCategories(entry)) } productCategoryZero = categories[0] @@ -371,7 +381,7 @@ moduleIntegrationTestRunner({ const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") eventBusSpy.mockClear() - await service.updateCategories(productCategoryZero.id, { + await service.updateProductCategories(productCategoryZero.id, { name: "New Category", }) @@ -385,11 +395,11 @@ moduleIntegrationTestRunner({ }) it("should update the name of the category successfully", async () => { - await service.updateCategories(productCategoryZero.id, { + await service.updateProductCategories(productCategoryZero.id, { name: "New Category", }) - const productCategory = await service.retrieveCategory( + const productCategory = await service.retrieveProductCategory( productCategoryZero.id, { select: ["name"], @@ -403,7 +413,7 @@ moduleIntegrationTestRunner({ let error try { - await service.updateCategories("does-not-exist", { + await service.updateProductCategories("does-not-exist", { name: "New Category", }) } catch (e) { @@ -416,11 +426,11 @@ moduleIntegrationTestRunner({ }) it("should reorder rank successfully in the same parent", async () => { - await service.updateCategories(productCategoryTwo.id, { + await service.updateProductCategories(productCategoryTwo.id, { rank: 0, }) - const productCategories = await service.listCategories( + const productCategories = await service.listProductCategories( { parent_category_id: null, }, @@ -448,12 +458,12 @@ moduleIntegrationTestRunner({ }) it("should reorder rank successfully when changing parent", async () => { - await service.updateCategories(productCategoryTwo.id, { + await service.updateProductCategories(productCategoryTwo.id, { rank: 0, parent_category_id: productCategoryZero.id, }) - const productCategories = await service.listCategories( + const productCategories = await service.listProductCategories( { parent_category_id: productCategoryZero.id, }, @@ -485,12 +495,12 @@ moduleIntegrationTestRunner({ }) it("should reorder rank successfully when changing parent and in first position", async () => { - await service.updateCategories(productCategoryTwo.id, { + await service.updateProductCategories(productCategoryTwo.id, { rank: 0, parent_category_id: productCategoryZero.id, }) - const productCategories = await service.listCategories( + const productCategories = await service.listProductCategories( { parent_category_id: productCategoryZero.id, }, @@ -531,7 +541,7 @@ moduleIntegrationTestRunner({ beforeEach(async () => { categories = [] for (const entry of productCategoriesRankData) { - categories.push(await service.createCategories(entry)) + categories.push(await service.createProductCategories(entry)) } productCategoryZero = categories[0] @@ -544,7 +554,7 @@ moduleIntegrationTestRunner({ const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") eventBusSpy.mockClear() - await service.deleteCategories([productCategoryOne.id]) + await service.deleteProductCategories([productCategoryOne.id]) expect(eventBusSpy).toHaveBeenCalledTimes(1) expect(eventBusSpy).toHaveBeenCalledWith([ @@ -559,7 +569,7 @@ moduleIntegrationTestRunner({ let error try { - await service.deleteCategories(["does-not-exist"]) + await service.deleteProductCategories(["does-not-exist"]) } catch (e) { error = e } @@ -573,7 +583,7 @@ moduleIntegrationTestRunner({ let error try { - await service.deleteCategories([productCategoryZero.id]) + await service.deleteProductCategories([productCategoryZero.id]) } catch (e) { error = e } @@ -584,9 +594,9 @@ moduleIntegrationTestRunner({ }) it("should reorder siblings rank successfully on deleting", async () => { - await service.deleteCategories([productCategoryOne.id]) + await service.deleteProductCategories([productCategoryOne.id]) - const productCategories = await service.listCategories( + const productCategories = await service.listProductCategories( { parent_category_id: null, }, diff --git a/packages/modules/product/integration-tests/__tests__/product-module-service/product-collections.spec.ts b/packages/modules/product/integration-tests/__tests__/product-module-service/product-collections.spec.ts index 85f18bb589..a0761949c8 100644 --- a/packages/modules/product/integration-tests/__tests__/product-module-service/product-collections.spec.ts +++ b/packages/modules/product/integration-tests/__tests__/product-module-service/product-collections.spec.ts @@ -66,7 +66,7 @@ moduleIntegrationTestRunner({ describe("listCollections", () => { it("should return collections queried by ID", async () => { - const results = await service.listCollections({ + const results = await service.listProductCollections({ id: productCollectionOne.id, }) @@ -78,7 +78,7 @@ moduleIntegrationTestRunner({ }) it("should return collections based on the options and filter parameter", async () => { - let results = await service.listCollections( + let results = await service.listProductCollections( { id: productCollectionOne.id, }, @@ -93,7 +93,10 @@ moduleIntegrationTestRunner({ }), ]) - results = await service.listCollections({}, { take: 1, skip: 1 }) + results = await service.listProductCollections( + {}, + { take: 1, skip: 1 } + ) expect(results).toEqual([ expect.objectContaining({ @@ -103,7 +106,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for collections", async () => { - const results = await service.listCollections( + const results = await service.listProductCollections( { id: productCollectionOne.id, }, @@ -130,7 +133,7 @@ moduleIntegrationTestRunner({ describe("listAndCountCollections", () => { it("should return collections and count queried by ID", async () => { - const results = await service.listAndCountCollections({ + const results = await service.listAndCountProductCollections({ id: productCollectionOne.id, }) @@ -143,7 +146,7 @@ moduleIntegrationTestRunner({ }) it("should return collections and count based on the options and filter parameter", async () => { - let results = await service.listAndCountCollections( + let results = await service.listAndCountProductCollections( { id: productCollectionOne.id, }, @@ -159,11 +162,14 @@ moduleIntegrationTestRunner({ }), ]) - results = await service.listAndCountCollections({}, { take: 1 }) + results = await service.listAndCountProductCollections( + {}, + { take: 1 } + ) expect(results[1]).toEqual(2) - results = await service.listAndCountCollections( + results = await service.listAndCountProductCollections( {}, { take: 1, skip: 1 } ) @@ -177,7 +183,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for collections", async () => { - const results = await service.listAndCountCollections( + const results = await service.listAndCountProductCollections( { id: productCollectionOne.id, }, @@ -205,7 +211,7 @@ moduleIntegrationTestRunner({ describe("retrieveCollection", () => { it("should return the requested collection", async () => { - const result = await service.retrieveCollection( + const result = await service.retrieveProductCollection( productCollectionOne.id ) @@ -218,7 +224,7 @@ moduleIntegrationTestRunner({ }) it("should return requested attributes when requested through config", async () => { - const result = await service.retrieveCollection( + const result = await service.retrieveProductCollection( productCollectionOne.id, { select: ["id", "title", "products.title"], @@ -244,7 +250,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieveCollection("does-not-exist") + await service.retrieveProductCollection("does-not-exist") } catch (e) { error = e } @@ -259,9 +265,9 @@ moduleIntegrationTestRunner({ const collectionId = "test-1" it("should delete the product collection given an ID successfully", async () => { - await service.deleteCollections([collectionId]) + await service.deleteProductCollections([collectionId]) - const collections = await service.listCollections({ + const collections = await service.listProductCollections({ id: collectionId, }) @@ -270,7 +276,7 @@ moduleIntegrationTestRunner({ it("should emit events through event bus", async () => { const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") - await service.deleteCollections([collectionId]) + await service.deleteProductCollections([collectionId]) expect(eventBusSpy).toHaveBeenCalledTimes(1) expect(eventBusSpy).toHaveBeenCalledWith([ @@ -288,7 +294,7 @@ moduleIntegrationTestRunner({ it("should emit events through event bus", async () => { const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") - await service.upsertCollections([ + await service.upsertProductCollections([ { id: collectionId, title: "New Collection", @@ -305,14 +311,14 @@ moduleIntegrationTestRunner({ }) it("should update the value of the collection successfully", async () => { - await service.upsertCollections([ + await service.upsertProductCollections([ { id: collectionId, title: "New Collection", }, ]) - const productCollection = await service.retrieveCollection( + const productCollection = await service.retrieveProductCollection( collectionId ) @@ -320,14 +326,14 @@ moduleIntegrationTestRunner({ }) it("should add products to a collection successfully", async () => { - await service.upsertCollections([ + await service.upsertProductCollections([ { id: collectionId, product_ids: [productOne.id, productTwo.id], }, ]) - const productCollection = await service.retrieveCollection( + const productCollection = await service.retrieveProductCollection( collectionId, { select: ["products.id"], @@ -354,7 +360,7 @@ moduleIntegrationTestRunner({ let error try { - await service.updateCollections("does-not-exist", { + await service.updateProductCollections("does-not-exist", { title: "New Collection", }) } catch (e) { @@ -367,7 +373,7 @@ moduleIntegrationTestRunner({ }) it("should dissociate existing products when new products are synced", async () => { - await service.upsertCollections([ + await service.upsertProductCollections([ { id: collectionId, product_ids: [productOne.id, productTwo.id], @@ -377,14 +383,14 @@ moduleIntegrationTestRunner({ /** * Another upsert should remove the first productOne */ - await service.upsertCollections([ + await service.upsertProductCollections([ { id: collectionId, product_ids: [productTwo.id], }, ]) - const productCollection = await service.retrieveCollection( + const productCollection = await service.retrieveProductCollection( collectionId, { select: ["products.id"], @@ -405,7 +411,7 @@ moduleIntegrationTestRunner({ }) it("should dissociate all existing products", async () => { - await service.upsertCollections([ + await service.upsertProductCollections([ { id: collectionId, product_ids: [productOne.id, productTwo.id], @@ -415,14 +421,14 @@ moduleIntegrationTestRunner({ /** * Another upsert should remove the first productOne */ - await service.upsertCollections([ + await service.upsertProductCollections([ { id: collectionId, product_ids: [], }, ]) - const productCollection = await service.retrieveCollection( + const productCollection = await service.retrieveProductCollection( collectionId, { select: ["products.id"], @@ -436,13 +442,13 @@ moduleIntegrationTestRunner({ describe("createCollections", () => { it("should create a collection successfully", async () => { - const res = await service.createCollections([ + const res = await service.createProductCollections([ { title: "New Collection", }, ]) - const [productCollection] = await service.listCollections({ + const [productCollection] = await service.listProductCollections({ title: "New Collection", }) @@ -450,7 +456,7 @@ moduleIntegrationTestRunner({ }) it("should create collection with products successfully", async () => { - await service.createCollections([ + await service.createProductCollections([ { title: "New Collection with products", handle: "new-collection-with-products", @@ -458,7 +464,7 @@ moduleIntegrationTestRunner({ }, ]) - const [productCollection] = await service.listCollections( + const [productCollection] = await service.listProductCollections( { handle: "new-collection-with-products", }, @@ -487,7 +493,7 @@ moduleIntegrationTestRunner({ it("should emit events through event bus", async () => { const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") - const collections = await service.createCollections([ + const collections = await service.createProductCollections([ { title: "New Collection" }, ]) diff --git a/packages/modules/product/integration-tests/__tests__/product-module-service/product-options.spec.ts b/packages/modules/product/integration-tests/__tests__/product-module-service/product-options.spec.ts index 80ca3a64b8..4208c190cf 100644 --- a/packages/modules/product/integration-tests/__tests__/product-module-service/product-options.spec.ts +++ b/packages/modules/product/integration-tests/__tests__/product-module-service/product-options.spec.ts @@ -46,7 +46,7 @@ moduleIntegrationTestRunner({ describe("listOptions", () => { it("should return options and count queried by ID", async () => { - const options = await service.listOptions({ + const options = await service.listProductOptions({ id: optionOne.id, }) @@ -58,7 +58,7 @@ moduleIntegrationTestRunner({ }) it("should return options and count based on the options and filter parameter", async () => { - let options = await service.listOptions( + let options = await service.listProductOptions( { id: optionOne.id, }, @@ -73,7 +73,7 @@ moduleIntegrationTestRunner({ }), ]) - options = await service.listOptions({}, { take: 1, skip: 1 }) + options = await service.listProductOptions({}, { take: 1, skip: 1 }) expect(options).toEqual([ expect.objectContaining({ @@ -83,7 +83,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for options", async () => { - const options = await service.listOptions( + const options = await service.listProductOptions( { id: optionOne.id, }, @@ -111,7 +111,7 @@ moduleIntegrationTestRunner({ describe("listAndCountOptions", () => { it("should return options and count queried by ID", async () => { - const [options, count] = await service.listAndCountOptions({ + const [options, count] = await service.listAndCountProductOptions({ id: optionOne.id, }) @@ -124,7 +124,7 @@ moduleIntegrationTestRunner({ }) it("should return options and count based on the options and filter parameter", async () => { - let [options, count] = await service.listAndCountOptions( + let [options, count] = await service.listAndCountProductOptions( { id: optionOne.id, }, @@ -139,10 +139,13 @@ moduleIntegrationTestRunner({ id: optionOne.id, }), ]) - ;[options, count] = await service.listAndCountOptions({}, { take: 1 }) + ;[options, count] = await service.listAndCountProductOptions( + {}, + { take: 1 } + ) expect(count).toEqual(2) - ;[options, count] = await service.listAndCountOptions( + ;[options, count] = await service.listAndCountProductOptions( {}, { take: 1, skip: 1 } ) @@ -156,7 +159,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for options", async () => { - const [options, count] = await service.listAndCountOptions( + const [options, count] = await service.listAndCountProductOptions( { id: optionOne.id, }, @@ -185,7 +188,7 @@ moduleIntegrationTestRunner({ describe("retrieveOption", () => { it("should return the requested option", async () => { - const option = await service.retrieveOption(optionOne.id) + const option = await service.retrieveProductOption(optionOne.id) expect(option).toEqual( expect.objectContaining({ @@ -195,7 +198,7 @@ moduleIntegrationTestRunner({ }) it("should return requested attributes when requested through config", async () => { - const option = await service.retrieveOption(optionOne.id, { + const option = await service.retrieveProductOption(optionOne.id, { select: ["id", "product.title"], relations: ["product"], }) @@ -219,7 +222,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieveOption("does-not-exist") + await service.retrieveProductOption("does-not-exist") } catch (e) { error = e } @@ -234,9 +237,9 @@ moduleIntegrationTestRunner({ const optionId = "option-1" it("should delete the product option given an ID successfully", async () => { - await service.deleteOptions([optionId]) + await service.deleteProductOptions([optionId]) - const options = await service.listOptions({ + const options = await service.listProductOptions({ id: optionId, }) @@ -248,14 +251,14 @@ moduleIntegrationTestRunner({ const optionId = "option-1" it("should update the title of the option successfully", async () => { - await service.upsertOptions([ + await service.upsertProductOptions([ { id: optionId, title: "new test", }, ]) - const productOption = await service.retrieveOption(optionId) + const productOption = await service.retrieveProductOption(optionId) expect(productOption.title).toEqual("new test") }) @@ -264,7 +267,7 @@ moduleIntegrationTestRunner({ let error try { - await service.updateOptions("does-not-exist", {}) + await service.updateProductOptions("does-not-exist", {}) } catch (e) { error = e } @@ -277,7 +280,7 @@ moduleIntegrationTestRunner({ describe("createOptions", () => { it("should create a option successfully", async () => { - const res = await service.createOptions([ + const res = await service.createProductOptions([ { title: "test", values: [], @@ -285,7 +288,7 @@ moduleIntegrationTestRunner({ }, ]) - const [productOption] = await service.listOptions( + const [productOption] = await service.listProductOptions( { title: "test", }, diff --git a/packages/modules/product/integration-tests/__tests__/product-module-service/product-tags.spec.ts b/packages/modules/product/integration-tests/__tests__/product-module-service/product-tags.spec.ts index 888da6d203..49e7d49018 100644 --- a/packages/modules/product/integration-tests/__tests__/product-module-service/product-tags.spec.ts +++ b/packages/modules/product/integration-tests/__tests__/product-module-service/product-tags.spec.ts @@ -64,7 +64,7 @@ moduleIntegrationTestRunner({ describe("listTags", () => { it("should return tags and count queried by ID", async () => { - const tags = await service.listTags({ + const tags = await service.listProductTags({ id: tagOne.id, }) @@ -76,7 +76,7 @@ moduleIntegrationTestRunner({ }) it("should return tags and count based on the options and filter parameter", async () => { - let tags = await service.listTags( + let tags = await service.listProductTags( { id: tagOne.id, }, @@ -91,7 +91,7 @@ moduleIntegrationTestRunner({ }), ]) - tags = await service.listTags({}, { take: 1, skip: 1 }) + tags = await service.listProductTags({}, { take: 1, skip: 1 }) expect(tags).toEqual([ expect.objectContaining({ @@ -101,7 +101,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for tags", async () => { - const tags = await service.listTags( + const tags = await service.listProductTags( { id: tagOne.id, }, @@ -130,7 +130,7 @@ moduleIntegrationTestRunner({ describe("listAndCountTags", () => { it("should return tags and count queried by ID", async () => { - const [tags, count] = await service.listAndCountTags({ + const [tags, count] = await service.listAndCountProductTags({ id: tagOne.id, }) @@ -143,7 +143,7 @@ moduleIntegrationTestRunner({ }) it("should return tags and count based on the options and filter parameter", async () => { - let [tags, count] = await service.listAndCountTags( + let [tags, count] = await service.listAndCountProductTags( { id: tagOne.id, }, @@ -158,10 +158,13 @@ moduleIntegrationTestRunner({ id: tagOne.id, }), ]) - ;[tags, count] = await service.listAndCountTags({}, { take: 1 }) + ;[tags, count] = await service.listAndCountProductTags( + {}, + { take: 1 } + ) expect(count).toEqual(2) - ;[tags, count] = await service.listAndCountTags( + ;[tags, count] = await service.listAndCountProductTags( {}, { take: 1, skip: 1 } ) @@ -175,7 +178,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for tags", async () => { - const [tags, count] = await service.listAndCountTags( + const [tags, count] = await service.listAndCountProductTags( { id: tagOne.id, }, @@ -205,7 +208,7 @@ moduleIntegrationTestRunner({ describe("retrieveTag", () => { it("should return the requested tag", async () => { - const tag = await service.retrieveTag(tagOne.id) + const tag = await service.retrieveProductTag(tagOne.id) expect(tag).toEqual( expect.objectContaining({ @@ -215,7 +218,7 @@ moduleIntegrationTestRunner({ }) it("should return requested attributes when requested through config", async () => { - const tag = await service.retrieveTag(tagOne.id, { + const tag = await service.retrieveProductTag(tagOne.id, { select: ["id", "value", "products.title"], relations: ["products"], }) @@ -237,7 +240,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieveTag("does-not-exist") + await service.retrieveProductTag("does-not-exist") } catch (e) { error = e } @@ -252,9 +255,9 @@ moduleIntegrationTestRunner({ const tagId = "tag-1" it("should delete the product tag given an ID successfully", async () => { - await service.deleteTags([tagId]) + await service.deleteProductTags([tagId]) - const tags = await service.listTags({ + const tags = await service.listProductTags({ id: tagId, }) @@ -266,11 +269,11 @@ moduleIntegrationTestRunner({ const tagId = "tag-1" it("should update the value of the tag successfully", async () => { - await service.updateTags(tagId, { + await service.updateProductTags(tagId, { value: "UK", }) - const productTag = await service.retrieveTag(tagId) + const productTag = await service.retrieveProductTag(tagId) expect(productTag.value).toEqual("UK") @@ -289,7 +292,7 @@ moduleIntegrationTestRunner({ let error try { - await service.updateTags("does-not-exist", { + await service.updateProductTags("does-not-exist", { value: "UK", }) } catch (e) { @@ -304,13 +307,13 @@ moduleIntegrationTestRunner({ describe("createTags", () => { it("should create a tag successfully", async () => { - await service.createTags([ + await service.createProductTags([ { value: "UK", }, ]) - const productTag = await service.listTags({ + const productTag = await service.listProductTags({ value: "UK", }) @@ -330,13 +333,13 @@ moduleIntegrationTestRunner({ describe("upsertTags", () => { it("should upsert tags successfully", async () => { - await service.createTags([ + await service.createProductTags([ { value: "UK", }, ]) - let productTags = await service.listTags({ + let productTags = await service.listProductTags({ value: "UK", }) @@ -352,9 +355,9 @@ moduleIntegrationTestRunner({ jest.clearAllMocks() - await service.upsertTags(tagsData) + await service.upsertProductTags(tagsData) - productTags = await service.listTags() + productTags = await service.listProductTags() expect(productTags).toEqual( expect.arrayContaining([ diff --git a/packages/modules/product/integration-tests/__tests__/product-module-service/product-types.spec.ts b/packages/modules/product/integration-tests/__tests__/product-module-service/product-types.spec.ts index b4831a1f04..c6d9ff6034 100644 --- a/packages/modules/product/integration-tests/__tests__/product-module-service/product-types.spec.ts +++ b/packages/modules/product/integration-tests/__tests__/product-module-service/product-types.spec.ts @@ -30,7 +30,7 @@ moduleIntegrationTestRunner({ describe("listTypes", () => { it("should return types and count queried by ID", async () => { - const types = await service.listTypes({ + const types = await service.listProductTypes({ id: typeOne.id, }) @@ -42,7 +42,7 @@ moduleIntegrationTestRunner({ }) it("should return types and count based on the options and filter parameter", async () => { - let types = await service.listTypes( + let types = await service.listProductTypes( { id: typeOne.id, }, @@ -57,7 +57,7 @@ moduleIntegrationTestRunner({ }), ]) - types = await service.listTypes({}, { take: 1, skip: 1 }) + types = await service.listProductTypes({}, { take: 1, skip: 1 }) expect(types).toEqual([ expect.objectContaining({ @@ -67,7 +67,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields for types", async () => { - const types = await service.listTypes( + const types = await service.listProductTypes( { id: typeOne.id, }, @@ -88,7 +88,7 @@ moduleIntegrationTestRunner({ describe("listAndCountTypes", () => { it("should return types and count queried by ID", async () => { - const [types, count] = await service.listAndCountTypes({ + const [types, count] = await service.listAndCountProductTypes({ id: typeOne.id, }) @@ -101,7 +101,7 @@ moduleIntegrationTestRunner({ }) it("should return types and count based on the options and filter parameter", async () => { - let [types, count] = await service.listAndCountTypes( + let [types, count] = await service.listAndCountProductTypes( { id: typeOne.id, }, @@ -116,10 +116,13 @@ moduleIntegrationTestRunner({ id: typeOne.id, }), ]) - ;[types, count] = await service.listAndCountTypes({}, { take: 1 }) + ;[types, count] = await service.listAndCountProductTypes( + {}, + { take: 1 } + ) expect(count).toEqual(2) - ;[types, count] = await service.listAndCountTypes( + ;[types, count] = await service.listAndCountProductTypes( {}, { take: 1, skip: 1 } ) @@ -133,7 +136,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields for types", async () => { - const [types, count] = await service.listAndCountTypes( + const [types, count] = await service.listAndCountProductTypes( { id: typeOne.id, }, @@ -155,7 +158,7 @@ moduleIntegrationTestRunner({ describe("retrieveType", () => { it("should return the requested type", async () => { - const type = await service.retrieveType(typeOne.id) + const type = await service.retrieveProductType(typeOne.id) expect(type).toEqual( expect.objectContaining({ @@ -165,7 +168,7 @@ moduleIntegrationTestRunner({ }) it("should return requested attributes when requested through config", async () => { - const type = await service.retrieveType(typeOne.id, { + const type = await service.retrieveProductType(typeOne.id, { select: ["id", "value"], }) @@ -179,7 +182,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieveType("does-not-exist") + await service.retrieveProductType("does-not-exist") } catch (e) { error = e } @@ -194,9 +197,9 @@ moduleIntegrationTestRunner({ const typeId = "type-1" it("should delete the product type given an ID successfully", async () => { - await service.deleteTypes([typeId]) + await service.deleteProductTypes([typeId]) - const types = await service.listTypes({ + const types = await service.listProductTypes({ id: typeId, }) @@ -208,11 +211,11 @@ moduleIntegrationTestRunner({ const typeId = "type-1" it("should update the value of the type successfully", async () => { - await service.updateTypes(typeId, { + await service.updateProductTypes(typeId, { value: "UK", }) - const productType = await service.retrieveType(typeId) + const productType = await service.retrieveProductType(typeId) expect(productType.value).toEqual("UK") }) @@ -221,7 +224,7 @@ moduleIntegrationTestRunner({ let error try { - await service.updateTypes("does-not-exist", { + await service.updateProductTypes("does-not-exist", { value: "UK", }) } catch (e) { @@ -236,13 +239,13 @@ moduleIntegrationTestRunner({ describe("createTypes", () => { it("should create a type successfully", async () => { - const res = await service.createTypes([ + const res = await service.createProductTypes([ { value: "UK", }, ]) - const productType = await service.listTypes({ + const productType = await service.listProductTypes({ value: "UK", }) diff --git a/packages/modules/product/integration-tests/__tests__/product-module-service/product-variants.spec.ts b/packages/modules/product/integration-tests/__tests__/product-module-service/product-variants.spec.ts index be7db8ef47..2dc8caaefe 100644 --- a/packages/modules/product/integration-tests/__tests__/product-module-service/product-variants.spec.ts +++ b/packages/modules/product/integration-tests/__tests__/product-module-service/product-variants.spec.ts @@ -40,7 +40,7 @@ moduleIntegrationTestRunner({ let productTwo: ProductDTO beforeEach(async () => { - productOne = await service.create({ + productOne = await service.createProducts({ id: "product-1", title: "product 1", status: ProductStatus.PUBLISHED, @@ -56,20 +56,20 @@ moduleIntegrationTestRunner({ ], } as CreateProductDTO) - productTwo = await service.create({ + productTwo = await service.createProducts({ id: "product-2", title: "product 2", status: ProductStatus.PUBLISHED, } as CreateProductDTO) - variantOne = await service.createVariants({ + variantOne = await service.createProductVariants({ id: "test-1", title: "variant 1", product_id: productOne.id, options: { size: "large" }, } as CreateProductVariantDTO) - variantTwo = await service.createVariants({ + variantTwo = await service.createProductVariants({ id: "test-2", title: "variant", product_id: productTwo.id, @@ -80,7 +80,7 @@ moduleIntegrationTestRunner({ describe("listAndCountVariants", () => { it("should return variants and count queried by ID", async () => { - const results = await service.listAndCountVariants({ + const results = await service.listAndCountProductVariants({ id: variantOne.id, }) @@ -93,7 +93,7 @@ moduleIntegrationTestRunner({ }) it("should return variants and count based on the options and filter parameter", async () => { - let results = await service.listAndCountVariants( + let results = await service.listAndCountProductVariants( { id: variantOne.id, }, @@ -109,11 +109,14 @@ moduleIntegrationTestRunner({ }), ]) - results = await service.listAndCountVariants({}, { take: 1 }) + results = await service.listAndCountProductVariants({}, { take: 1 }) expect(results[1]).toEqual(2) - results = await service.listAndCountVariants({}, { take: 1, skip: 1 }) + results = await service.listAndCountProductVariants( + {}, + { take: 1, skip: 1 } + ) expect(results[1]).toEqual(2) expect(results[0]).toEqual([ @@ -124,7 +127,7 @@ moduleIntegrationTestRunner({ }) it("should return only requested fields and relations for variants", async () => { - const results = await service.listAndCountVariants( + const results = await service.listAndCountProductVariants( { id: variantOne.id, }, @@ -151,7 +154,7 @@ moduleIntegrationTestRunner({ describe("retrieveVariant", () => { it("should return the requested variant", async () => { - const result = await service.retrieveVariant(variantOne.id) + const result = await service.retrieveProductVariant(variantOne.id) expect(result).toEqual( expect.objectContaining({ @@ -162,7 +165,7 @@ moduleIntegrationTestRunner({ }) it("should return requested attributes when requested through config", async () => { - const result = await service.retrieveVariant(variantOne.id, { + const result = await service.retrieveProductVariant(variantOne.id, { select: ["id", "title", "product.title"] as any, relations: ["product"], }) @@ -183,7 +186,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieveVariant("does-not-exist") + await service.retrieveProductVariant("does-not-exist") } catch (e) { error = e } @@ -196,14 +199,16 @@ moduleIntegrationTestRunner({ describe("updateVariants", () => { it("should update the title of the variant successfully", async () => { - await service.upsertVariants([ + await service.upsertProductVariants([ { id: variantOne.id, title: "new test", }, ]) - const productVariant = await service.retrieveVariant(variantOne.id) + const productVariant = await service.retrieveProductVariant( + variantOne.id + ) expect(productVariant.title).toEqual("new test") expect(eventBusEmitSpy.mock.calls[0][0]).toHaveLength(1) @@ -218,16 +223,19 @@ moduleIntegrationTestRunner({ }) it("should upsert the options of a variant successfully", async () => { - await service.upsertVariants([ + await service.upsertProductVariants([ { id: variantOne.id, options: { size: "small" }, }, ]) - const productVariant = await service.retrieveVariant(variantOne.id, { - relations: ["options"], - }) + const productVariant = await service.retrieveProductVariant( + variantOne.id, + { + relations: ["options"], + } + ) expect(productVariant.options).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -248,13 +256,16 @@ moduleIntegrationTestRunner({ }) it("should do a partial update on the options of a variant successfully", async () => { - await service.updateVariants(variantOne.id, { + await service.updateProductVariants(variantOne.id, { options: { size: "small", color: "red" }, }) - const productVariant = await service.retrieveVariant(variantOne.id, { - relations: ["options"], - }) + const productVariant = await service.retrieveProductVariant( + variantOne.id, + { + relations: ["options"], + } + ) expect(productVariant.options).toEqual( expect.arrayContaining([ @@ -272,7 +283,7 @@ moduleIntegrationTestRunner({ let error try { - await service.updateVariants("does-not-exist", {}) + await service.updateProductVariants("does-not-exist", {}) } catch (e) { error = e } @@ -293,7 +304,7 @@ moduleIntegrationTestRunner({ options: { size: "small" }, } - const variant = await service.createVariants(data) + const variant = await service.createProductVariants(data) expect(variant).toEqual( expect.objectContaining({ @@ -321,15 +332,15 @@ moduleIntegrationTestRunner({ describe("softDelete variant", () => { it("should soft delete a variant and its relations", async () => { - const beforeDeletedVariants = await service.listVariants( + const beforeDeletedVariants = await service.listProductVariants( { id: variantOne.id }, { relations: ["options"], } ) - await service.softDeleteVariants([variantOne.id]) - const deletedVariants = await service.listVariants( + await service.softDeleteProductVariants([variantOne.id]) + const deletedVariants = await service.listProductVariants( { id: variantOne.id }, { relations: ["options"], diff --git a/packages/modules/product/integration-tests/__tests__/product-module-service/products.spec.ts b/packages/modules/product/integration-tests/__tests__/product-module-service/products.spec.ts index f43a2b226b..82a90f7e47 100644 --- a/packages/modules/product/integration-tests/__tests__/product-module-service/products.spec.ts +++ b/packages/modules/product/integration-tests/__tests__/product-module-service/products.spec.ts @@ -102,13 +102,13 @@ moduleIntegrationTestRunner({ const categories: ProductCategoryDTO[] = [] for (const entry of productCategoriesData) { - categories.push(await service.createCategories(entry)) + categories.push(await service.createProductCategories(entry)) } productCategoryOne = categories[0] productCategoryTwo = categories[1] - productOne = service.create({ + productOne = service.createProducts({ id: "product-1", title: "product 1", status: ProductStatus.PUBLISHED, @@ -120,7 +120,7 @@ moduleIntegrationTestRunner({ ], }) - productTwo = service.create({ + productTwo = service.createProducts({ id: "product-2", title: "product 2", status: ProductStatus.PUBLISHED, @@ -166,7 +166,7 @@ moduleIntegrationTestRunner({ const variantTitle = data.variants[0].title - const productBefore = (await service.retrieve(productOne.id, { + const productBefore = (await service.retrieveProduct(productOne.id, { relations: [ "images", "variants", @@ -187,10 +187,10 @@ moduleIntegrationTestRunner({ productBefore.images = data.images productBefore.thumbnail = data.thumbnail productBefore.tags = data.tags - const updatedProducts = await service.upsert([productBefore]) + const updatedProducts = await service.upsertProducts([productBefore]) expect(updatedProducts).toHaveLength(1) - const product = await service.retrieve(productBefore.id, { + const product = await service.retrieveProduct(productBefore.id, { relations: [ "images", "variants", @@ -279,7 +279,7 @@ moduleIntegrationTestRunner({ title: "updated title", } - await service.upsert([updateData]) + await service.upsertProducts([updateData]) expect(eventBusSpy).toHaveBeenCalledTimes(1) expect(eventBusSpy).toHaveBeenCalledWith([ @@ -302,9 +302,9 @@ moduleIntegrationTestRunner({ type_id: productTypeOne.id, } - await service.upsert([updateData]) + await service.upsertProducts([updateData]) - const product = await service.retrieve(updateData.id, { + const product = await service.retrieveProduct(updateData.id, { relations: ["categories", "collection", "type"], }) @@ -332,9 +332,9 @@ moduleIntegrationTestRunner({ type_id: productTypeOne.id, } - await service.upsert([updateData]) + await service.upsertProducts([updateData]) - let product = await service.retrieve(updateData.id, { + let product = await service.retrieveProduct(updateData.id, { relations: ["type"], }) @@ -366,9 +366,9 @@ moduleIntegrationTestRunner({ tags: [newTagData], } - await service.upsert([updateData]) + await service.upsertProducts([updateData]) - const product = await service.retrieve(updateData.id, { + const product = await service.retrieveProduct(updateData.id, { relations: ["categories", "collection", "tags", "type"], }) @@ -405,9 +405,9 @@ moduleIntegrationTestRunner({ tags: [], } - await service.upsert([updateData]) + await service.upsertProducts([updateData]) - const product = await service.retrieve(updateData.id, { + const product = await service.retrieveProduct(updateData.id, { relations: ["categories", "collection", "tags"], }) @@ -425,7 +425,7 @@ moduleIntegrationTestRunner({ it("should throw an error when product ID does not exist", async () => { let error try { - await service.update("does-not-exist", { title: "test" }) + await service.updateProducts("does-not-exist", { title: "test" }) } catch (e) { error = e.message } @@ -448,9 +448,9 @@ moduleIntegrationTestRunner({ ], } - await service.upsert([updateData]) + await service.upsertProducts([updateData]) - const product = await service.retrieve(updateData.id, { + const product = await service.retrieveProduct(updateData.id, { relations: ["variants"], }) @@ -473,7 +473,7 @@ moduleIntegrationTestRunner({ }) it("should do a partial update on the options of a variant successfully", async () => { - await service.update(productTwo.id, { + await service.updateProducts(productTwo.id, { variants: [ { id: "variant-3", @@ -482,7 +482,7 @@ moduleIntegrationTestRunner({ ], }) - const fetchedProduct = await service.retrieve(productTwo.id, { + const fetchedProduct = await service.retrieveProduct(productTwo.id, { relations: ["variants", "variants.options"], }) @@ -513,8 +513,8 @@ moduleIntegrationTestRunner({ ], } - await service.upsert([updateData]) - const retrieved = await service.retrieve(updateData.id, { + await service.upsertProducts([updateData]) + const retrieved = await service.retrieveProduct(updateData.id, { relations: ["variants"], }) @@ -542,9 +542,9 @@ moduleIntegrationTestRunner({ thumbnail: images[0].url, }) - const productsCreated = await service.create([data]) + const productsCreated = await service.createProducts([data]) - const products = await service.list( + const products = await service.listProducts( { id: productsCreated[0].id }, { relations: [ @@ -628,7 +628,7 @@ moduleIntegrationTestRunner({ thumbnail: images[0].url, }) - const products = await service.create([data]) + const products = await service.createProducts([data]) expect(eventBusSpy).toHaveBeenCalledTimes(1) expect(eventBusSpy).toHaveBeenCalledWith([ { @@ -647,11 +647,11 @@ moduleIntegrationTestRunner({ thumbnail: images[0].url, }) - const products = await service.create([data]) + const products = await service.createProducts([data]) - await service.softDelete([products[0].id]) + await service.softDeleteProducts([products[0].id]) - const deletedProducts = await service.list( + const deletedProducts = await service.listProducts( { id: products[0].id }, { relations: [ @@ -698,11 +698,11 @@ moduleIntegrationTestRunner({ thumbnail: images[0].url, }) - const products = await service.create([data]) + const products = await service.createProducts([data]) - await service.softDelete([products[0].id]) + await service.softDeleteProducts([products[0].id]) - const softDeleted = await service.list({ + const softDeleted = await service.listProducts({ deleted_at: { $gt: "01-01-2022" }, }) @@ -716,9 +716,9 @@ moduleIntegrationTestRunner({ thumbnail: images[0].url, }) - const products = await service.create([data]) + const products = await service.createProducts([data]) - await service.softDelete([products[0].id]) + await service.softDeleteProducts([products[0].id]) expect(eventBusSpy).toHaveBeenCalledWith([ { @@ -738,16 +738,18 @@ moduleIntegrationTestRunner({ thumbnail: images[0].url, }) - const products = await service.create([data]) + const products = await service.createProducts([data]) - let retrievedProducts = await service.list({ id: products[0].id }) + let retrievedProducts = await service.listProducts({ + id: products[0].id, + }) expect(retrievedProducts).toHaveLength(1) expect(retrievedProducts[0].deleted_at).toBeNull() - await service.softDelete([products[0].id]) + await service.softDeleteProducts([products[0].id]) - retrievedProducts = await service.list( + retrievedProducts = await service.listProducts( { id: products[0].id }, { withDeleted: true, @@ -757,9 +759,9 @@ moduleIntegrationTestRunner({ expect(retrievedProducts).toHaveLength(1) expect(retrievedProducts[0].deleted_at).not.toBeNull() - await service.restore([products[0].id]) + await service.restoreProducts([products[0].id]) - const deletedProducts = await service.list( + const deletedProducts = await service.listProducts( { id: products[0].id }, { relations: [ @@ -820,11 +822,11 @@ moduleIntegrationTestRunner({ tags: [], }) - await service.create([productOneData, productTwoData]) + await service.createProducts([productOneData, productTwoData]) }) it("should return a list of products scoped by collection id", async () => { - const productsWithCollectionOne = await service.list( + const productsWithCollectionOne = await service.listProducts( { collection_id: productCollectionOne.id }, { relations: ["collection"], @@ -843,7 +845,7 @@ moduleIntegrationTestRunner({ }) it("should return empty array when querying for a collection that doesnt exist", async () => { - const products = await service.list( + const products = await service.listProducts( { categories: { id: ["collection-doesnt-exist-id"] }, }, diff --git a/packages/modules/product/package.json b/packages/modules/product/package.json index acb20b7949..0c9878a572 100644 --- a/packages/modules/product/package.json +++ b/packages/modules/product/package.json @@ -7,11 +7,8 @@ "files": [ "dist" ], - "bin": { - "medusa-product-seed": "dist/scripts/bin/run-seed.js" - }, "engines": { - "node": ">=16" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/product/src/index.ts b/packages/modules/product/src/index.ts index be203865a1..d96d952eac 100644 --- a/packages/modules/product/src/index.ts +++ b/packages/modules/product/src/index.ts @@ -1,7 +1,7 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { ProductModuleService } from "@services" +const moduleDefinition: ModuleExports = { + service: ProductModuleService, +} export default moduleDefinition - -export * from "./models" -export * from "./services" -export * from "./types" diff --git a/packages/modules/product/src/joiner-config.ts b/packages/modules/product/src/joiner-config.ts index 2892b0fd6b..176497a006 100644 --- a/packages/modules/product/src/joiner-config.ts +++ b/packages/modules/product/src/joiner-config.ts @@ -1,44 +1,12 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" import { - Product, - ProductCategory, - ProductCollection, - ProductOption, - ProductTag, - ProductType, - ProductVariant, -} from "@models" -import ProductImage from "./models/product-image" + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys = { - product_id: Product.name, - product_handle: Product.name, - variant_id: ProductVariant.name, - variant_sku: ProductVariant.name, - product_option_id: ProductOption.name, - product_type_id: ProductType.name, - product_category_id: ProductCategory.name, - product_collection_id: ProductCollection.name, - product_tag_id: ProductTag.name, - product_image_id: ProductImage.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.PRODUCT, - primaryKeys: ["id", "handle"], - linkableKeys: LinkableKeys, +export const joinerConfig = defineJoinerConfig(Modules.PRODUCT, { + // This module provides more alias than the default config builder alias: [ { name: ["product", "products"], @@ -50,50 +18,46 @@ export const joinerConfig: ModuleJoinerConfig = { name: ["product_variant", "product_variants", "variant", "variants"], args: { entity: "ProductVariant", - methodSuffix: "Variants", }, }, { name: ["product_option", "product_options"], args: { entity: "ProductOption", - methodSuffix: "Options", }, }, { name: ["product_type", "product_types"], args: { entity: "ProductType", - methodSuffix: "Types", }, }, { name: ["product_image", "product_images"], args: { entity: "ProductImage", - methodSuffix: "Images", }, }, { name: ["product_tag", "product_tags"], args: { entity: "ProductTag", - methodSuffix: "Tags", }, }, { name: ["product_collection", "product_collections"], args: { entity: "ProductCollection", - methodSuffix: "Collections", }, }, { name: ["product_category", "product_categories"], args: { entity: "ProductCategory", - methodSuffix: "Categories", }, }, ], -} +}) + +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/product/src/module-definition.ts b/packages/modules/product/src/module-definition.ts deleted file mode 100644 index 6b4ba9b2a9..0000000000 --- a/packages/modules/product/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { ProductModuleService } from "@services" - -const service = ProductModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/product/src/scripts/bin/run-seed.ts b/packages/modules/product/src/scripts/bin/run-seed.ts deleted file mode 100644 index ce168bede0..0000000000 --- a/packages/modules/product/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env node - -import { ModulesSdkUtils } from "@medusajs/utils" -import { Modules } from "@medusajs/modules-sdk" -import * as ProductModels from "@models" -import { - createProductCategories, - createProducts, - createProductVariants, -} from "../seed-utils" -import { EOL } from "os" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-product-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.PRODUCT, - models: ProductModels, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - const { productCategoriesData, productsData, variantsData } = data - await createProductCategories(manager, productCategoriesData) - await createProducts(manager, productsData) - await createProductVariants(manager, variantsData) - }, - }) - await run({ path }) -})() diff --git a/packages/modules/product/src/scripts/seed-utils.ts b/packages/modules/product/src/scripts/seed-utils.ts deleted file mode 100644 index 829ad271b9..0000000000 --- a/packages/modules/product/src/scripts/seed-utils.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { SqlEntityManager } from "@mikro-orm/postgresql" -import { Product, ProductCategory, ProductVariant } from "@models" - -export async function createProductCategories( - manager: SqlEntityManager, - categoriesData: any[] -): Promise { - const categories: ProductCategory[] = [] - - for (let categoryData of categoriesData) { - let categoryDataClone = { ...categoryData } - let parentCategory: ProductCategory | null = null - const parentCategoryId = categoryDataClone.parent_category_id as string - delete categoryDataClone.parent_category_id - - if (parentCategoryId) { - parentCategory = await manager.findOne(ProductCategory, parentCategoryId) - } - - const category = manager.create(ProductCategory, { - ...categoryDataClone, - parent_category: parentCategory, - }) - - categories.push(category) - } - - await manager.persistAndFlush(categories) - - return categories -} - -export async function createProducts(manager: SqlEntityManager, data: any[]) { - const products: any[] = data.map((productData) => { - return manager.create(Product, productData) - }) - - await manager.persistAndFlush(products) - - return products -} - -export async function createProductVariants( - manager: SqlEntityManager, - data: any[] -) { - const variants: any[] = data.map((variantsData) => { - return manager.create(ProductVariant, variantsData) - }) - - await manager.persistAndFlush(variants) - - return variants -} diff --git a/packages/modules/product/src/services/product-module-service.ts b/packages/modules/product/src/services/product-module-service.ts index 2ac5023be3..47c7fb25b7 100644 --- a/packages/modules/product/src/services/product-module-service.ts +++ b/packages/modules/product/src/services/product-module-service.ts @@ -8,7 +8,7 @@ import { ProductTypes, } from "@medusajs/types" import { - Image, + Image as ProductImage, Product, ProductCategory, ProductCollection, @@ -31,15 +31,13 @@ import { kebabCase, MedusaContext, MedusaError, - ModulesSdkUtils, + MedusaService, ProductStatus, promiseAll, removeUndefined, toHandle, } from "@medusajs/utils" import { - ProductCategoryEventData, - ProductCategoryEvents, ProductCollectionEventData, ProductCollectionEvents, ProductEventData, @@ -69,81 +67,53 @@ type InjectedDependencies = { eventBusModuleService?: IEventBusModuleService } -const generateMethodForModels = { - ProductCategory: { singular: "Category", plural: "Categories" }, - ProductCollection: { singular: "Collection", plural: "Collections" }, - ProductOption: { singular: "Option", plural: "Options" }, - ProductTag: { singular: "Tag", plural: "Tags" }, - ProductType: { singular: "Type", plural: "Types" }, - ProductVariant: { singular: "Variant", plural: "Variants" }, -} - -export default class ProductModuleService< - TProduct extends Product = Product, - TProductVariant extends ProductVariant = ProductVariant, - TProductTag extends ProductTag = ProductTag, - TProductCollection extends ProductCollection = ProductCollection, - TProductCategory extends ProductCategory = ProductCategory, - TProductImage extends Image = Image, - TProductType extends ProductType = ProductType, - TProductOption extends ProductOption = ProductOption, - TProductOptionValue extends ProductOptionValue = ProductOptionValue - > - extends ModulesSdkUtils.MedusaService< - ProductTypes.ProductDTO, - { - ProductCategory: { - dto: ProductTypes.ProductCategoryDTO - singular: "Category" - plural: "Categories" - } - ProductCollection: { - dto: ProductTypes.ProductCollectionDTO - singular: "Collection" - plural: "Collections" - } - ProductOption: { - dto: ProductTypes.ProductOptionDTO - singular: "Option" - plural: "Options" - } - ProductTag: { - dto: ProductTypes.ProductTagDTO - singular: "Tag" - plural: "Tags" - } - ProductType: { - dto: ProductTypes.ProductTypeDTO - singular: "Type" - plural: "Types" - } - ProductVariant: { - dto: ProductTypes.ProductVariantDTO - singular: "Variant" - plural: "Variants" - } +export default class ProductModuleService + extends MedusaService<{ + Product: { + dto: ProductTypes.ProductDTO } - >(Product, generateMethodForModels, entityNameToLinkableKeysMap) + ProductCategory: { + dto: ProductTypes.ProductCategoryDTO + } + ProductCollection: { + dto: ProductTypes.ProductCollectionDTO + } + ProductOption: { + dto: ProductTypes.ProductOptionDTO + } + ProductTag: { + dto: ProductTypes.ProductTagDTO + } + ProductType: { + dto: ProductTypes.ProductTypeDTO + } + ProductVariant: { + dto: ProductTypes.ProductVariantDTO + } + }>( + { + Product, + ProductCategory, + ProductCollection, + ProductOption, + ProductTag, + ProductType, + ProductVariant, + }, + entityNameToLinkableKeysMap + ) implements ProductTypes.IProductModuleService { protected baseRepository_: DAL.RepositoryService - protected readonly productService_: ProductService - // eslint-disable-next-line max-len - protected readonly productVariantService_: ModulesSdkTypes.IMedusaInternalService - // eslint-disable-next-line max-len - protected readonly productCategoryService_: ProductCategoryService - // eslint-disable-next-line max-len - protected readonly productTagService_: ModulesSdkTypes.IMedusaInternalService - // eslint-disable-next-line max-len - protected readonly productCollectionService_: ModulesSdkTypes.IMedusaInternalService - // eslint-disable-next-line max-len - protected readonly productImageService_: ModulesSdkTypes.IMedusaInternalService - // eslint-disable-next-line max-len - protected readonly productTypeService_: ModulesSdkTypes.IMedusaInternalService - // eslint-disable-next-line max-len - protected readonly productOptionService_: ModulesSdkTypes.IMedusaInternalService - // eslint-disable-next-line max-len - protected readonly productOptionValueService_: ModulesSdkTypes.IMedusaInternalService + protected readonly productService_: ProductService + protected readonly productVariantService_: ModulesSdkTypes.IMedusaInternalService + protected readonly productCategoryService_: ProductCategoryService + protected readonly productTagService_: ModulesSdkTypes.IMedusaInternalService + protected readonly productCollectionService_: ModulesSdkTypes.IMedusaInternalService + protected readonly productImageService_: ModulesSdkTypes.IMedusaInternalService + protected readonly productTypeService_: ModulesSdkTypes.IMedusaInternalService + protected readonly productOptionService_: ModulesSdkTypes.IMedusaInternalService + protected readonly productOptionValueService_: ModulesSdkTypes.IMedusaInternalService protected readonly eventBusModuleService_?: IEventBusModuleService constructor( @@ -185,18 +155,18 @@ export default class ProductModuleService< // TODO: Add options validation, among other things // @ts-ignore - createVariants( + createProductVariants( data: ProductTypes.CreateProductVariantDTO[], sharedContext?: Context ): Promise - createVariants( + createProductVariants( data: ProductTypes.CreateProductVariantDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") @EmitEvents() - async createVariants( + async createProductVariants( data: | ProductTypes.CreateProductVariantDTO[] | ProductTypes.CreateProductVariantDTO, @@ -254,18 +224,18 @@ export default class ProductModuleService< return createdVariants } - async upsertVariants( + async upsertProductVariants( data: ProductTypes.UpsertProductVariantDTO[], sharedContext?: Context ): Promise - async upsertVariants( + async upsertProductVariants( data: ProductTypes.UpsertProductVariantDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") @EmitEvents() - async upsertVariants( + async upsertProductVariants( data: | ProductTypes.UpsertProductVariantDTO[] | ProductTypes.UpsertProductVariantDTO, @@ -300,12 +270,12 @@ export default class ProductModuleService< } // @ts-ignore - updateVariants( + updateProductVariants( id: string, data: ProductTypes.UpdateProductVariantDTO, sharedContext?: Context ): Promise - updateVariants( + updateProductVariants( selector: ProductTypes.FilterableProductVariantProps, data: ProductTypes.UpdateProductVariantDTO, sharedContext?: Context @@ -313,7 +283,7 @@ export default class ProductModuleService< @InjectManager("baseRepository_") @EmitEvents() - async updateVariants( + async updateProductVariants( idOrSelector: string | ProductTypes.FilterableProductVariantProps, data: ProductTypes.UpdateProductVariantDTO, @MedusaContext() sharedContext: Context = {} @@ -349,7 +319,7 @@ export default class ProductModuleService< protected async updateVariants_( data: UpdateProductVariantInput[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { // Validation step const variantIdsToUpdate = data.map(({ id }) => id) const variants = await this.productVariantService_.list( @@ -415,18 +385,18 @@ export default class ProductModuleService< } // @ts-ignore - createTags( + createProductTags( data: ProductTypes.CreateProductTagDTO[], sharedContext?: Context ): Promise - createTags( + createProductTags( data: ProductTypes.CreateProductTagDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") @EmitEvents() - async createTags( + async createProductTags( data: ProductTypes.CreateProductTagDTO[] | ProductTypes.CreateProductTagDTO, @MedusaContext() sharedContext: Context = {} ): Promise { @@ -446,18 +416,18 @@ export default class ProductModuleService< return Array.isArray(data) ? createdTags : createdTags[0] } - async upsertTags( + async upsertProductTags( data: ProductTypes.UpsertProductTagDTO[], sharedContext?: Context ): Promise - async upsertTags( + async upsertProductTags( data: ProductTypes.UpsertProductTagDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") @EmitEvents() - async upsertTags( + async upsertProductTags( data: ProductTypes.UpsertProductTagDTO[] | ProductTypes.UpsertProductTagDTO, @MedusaContext() sharedContext: Context = {} ): Promise { @@ -494,12 +464,12 @@ export default class ProductModuleService< } // @ts-ignore - updateTags( + updateProductTags( id: string, data: ProductTypes.UpdateProductTagDTO, sharedContext?: Context ): Promise - updateTags( + updateProductTags( selector: ProductTypes.FilterableProductTagProps, data: ProductTypes.UpdateProductTagDTO, sharedContext?: Context @@ -507,7 +477,7 @@ export default class ProductModuleService< @InjectManager("baseRepository_") @EmitEvents() - async updateTags( + async updateProductTags( idOrSelector: string | ProductTypes.FilterableProductTagProps, data: ProductTypes.UpdateProductTagDTO, @MedusaContext() sharedContext: Context = {} @@ -548,17 +518,17 @@ export default class ProductModuleService< } // @ts-ignore - createTypes( + createProductTypes( data: ProductTypes.CreateProductTypeDTO[], sharedContext?: Context ): Promise - createTypes( + createProductTypes( data: ProductTypes.CreateProductTypeDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async createTypes( + async createProductTypes( data: | ProductTypes.CreateProductTypeDTO[] | ProductTypes.CreateProductTypeDTO, @@ -575,17 +545,17 @@ export default class ProductModuleService< return Array.isArray(data) ? createdTypes : createdTypes[0] } - async upsertTypes( + async upsertProductTypes( data: ProductTypes.UpsertProductTypeDTO[], sharedContext?: Context ): Promise - async upsertTypes( + async upsertProductTypes( data: ProductTypes.UpsertProductTypeDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") - async upsertTypes( + async upsertProductTypes( data: | ProductTypes.UpsertProductTypeDTO[] | ProductTypes.UpsertProductTypeDTO, @@ -616,19 +586,19 @@ export default class ProductModuleService< } // @ts-ignore - updateTypes( + updateProductTypes( id: string, data: ProductTypes.UpdateProductTypeDTO, sharedContext?: Context ): Promise - updateTypes( + updateProductTypes( selector: ProductTypes.FilterableProductTypeProps, data: ProductTypes.UpdateProductTypeDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async updateTypes( + async updateProductTypes( idOrSelector: string | ProductTypes.FilterableProductTypeProps, data: ProductTypes.UpdateProductTypeDTO, @MedusaContext() sharedContext: Context = {} @@ -664,17 +634,17 @@ export default class ProductModuleService< } // @ts-ignore - createOptions( + createProductOptions( data: ProductTypes.CreateProductOptionDTO[], sharedContext?: Context ): Promise - createOptions( + createProductOptions( data: ProductTypes.CreateProductOptionDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async createOptions( + async createProductOptions( data: | ProductTypes.CreateProductOptionDTO[] | ProductTypes.CreateProductOptionDTO, @@ -718,17 +688,17 @@ export default class ProductModuleService< ) } - async upsertOptions( + async upsertProductOptions( data: ProductTypes.UpsertProductOptionDTO[], sharedContext?: Context ): Promise - async upsertOptions( + async upsertProductOptions( data: ProductTypes.UpsertProductOptionDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") - async upsertOptions( + async upsertProductOptions( data: | ProductTypes.UpsertProductOptionDTO[] | ProductTypes.UpsertProductOptionDTO, @@ -761,19 +731,19 @@ export default class ProductModuleService< } // @ts-ignore - updateOptions( + updateProductOptions( id: string, data: ProductTypes.UpdateProductOptionDTO, sharedContext?: Context ): Promise - updateOptions( + updateProductOptions( selector: ProductTypes.FilterableProductOptionProps, data: ProductTypes.UpdateProductOptionDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async updateOptions( + async updateProductOptions( idOrSelector: string | ProductTypes.FilterableProductOptionProps, data: ProductTypes.UpdateProductOptionDTO, @MedusaContext() sharedContext: Context = {} @@ -878,17 +848,17 @@ export default class ProductModuleService< } // @ts-ignore - createCollections( + createProductCollections( data: ProductTypes.CreateProductCollectionDTO[], sharedContext?: Context ): Promise - createCollections( + createProductCollections( data: ProductTypes.CreateProductCollectionDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async createCollections( + async createProductCollections( data: | ProductTypes.CreateProductCollectionDTO[] | ProductTypes.CreateProductCollectionDTO, @@ -918,7 +888,7 @@ export default class ProductModuleService< async createCollections_( data: ProductTypes.CreateProductCollectionDTO[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const normalizedInput = data.map( ProductModuleService.normalizeCreateProductCollectionInput ) @@ -935,16 +905,16 @@ export default class ProductModuleService< return productCollections } - async upsertCollections( + async upsertProductCollections( data: ProductTypes.UpsertProductCollectionDTO[], sharedContext?: Context ): Promise - async upsertCollections( + async upsertProductCollections( data: ProductTypes.UpsertProductCollectionDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") - async upsertCollections( + async upsertProductCollections( data: | ProductTypes.UpsertProductCollectionDTO[] | ProductTypes.UpsertProductCollectionDTO, @@ -998,19 +968,19 @@ export default class ProductModuleService< } // @ts-ignore - updateCollections( + updateProductCollections( id: string, data: ProductTypes.UpdateProductCollectionDTO, sharedContext?: Context ): Promise - updateCollections( + updateProductCollections( selector: ProductTypes.FilterableProductCollectionProps, data: ProductTypes.UpdateProductCollectionDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async updateCollections( + async updateProductCollections( idOrSelector: string | ProductTypes.FilterableProductCollectionProps, data: ProductTypes.UpdateProductCollectionDTO, @MedusaContext() sharedContext: Context = {} @@ -1061,7 +1031,7 @@ export default class ProductModuleService< protected async updateCollections_( data: UpdateCollectionInput[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const normalizedInput = data.map( ProductModuleService.normalizeUpdateProductCollectionInput ) as UpdateCollectionInput[] @@ -1075,7 +1045,7 @@ export default class ProductModuleService< sharedContext ) - const collections: TProductCollection[] = [] + const collections: ProductCollection[] = [] const updateSelectorAndData = updatedCollections.flatMap( (collectionData) => { @@ -1114,7 +1084,7 @@ export default class ProductModuleService< collections.push({ ...collectionData, products: productsToUpdate ?? [], - }) + } as ProductCollection) return result } @@ -1125,18 +1095,18 @@ export default class ProductModuleService< } // @ts-ignore - createCategories( + createProductCategories( data: ProductTypes.CreateProductCategoryDTO[], sharedContext?: Context ): Promise - createCategories( + createProductCategories( data: ProductTypes.CreateProductCategoryDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") @EmitEvents() - async createCategories( + async createProductCategories( data: | ProductTypes.CreateProductCategoryDTO[] | ProductTypes.CreateProductCategoryDTO, @@ -1163,18 +1133,18 @@ export default class ProductModuleService< return Array.isArray(data) ? createdCategories : createdCategories[0] } - async upsertCategories( + async upsertProductCategories( data: ProductTypes.UpsertProductCategoryDTO[], sharedContext?: Context ): Promise - async upsertCategories( + async upsertProductCategories( data: ProductTypes.UpsertProductCategoryDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") @EmitEvents() - async upsertCategories( + async upsertProductCategories( data: | ProductTypes.UpsertProductCategoryDTO[] | ProductTypes.UpsertProductCategoryDTO, @@ -1229,12 +1199,12 @@ export default class ProductModuleService< } // @ts-ignore - updateCategories( + updateProductCategories( id: string, data: ProductTypes.UpdateProductCategoryDTO, sharedContext?: Context ): Promise - updateCategories( + updateProductCategories( selector: ProductTypes.FilterableProductTypeProps, data: ProductTypes.UpdateProductCategoryDTO, sharedContext?: Context @@ -1242,7 +1212,7 @@ export default class ProductModuleService< @InjectManager("baseRepository_") @EmitEvents() - async updateCategories( + async updateProductCategories( idOrSelector: string | ProductTypes.FilterableProductTypeProps, data: ProductTypes.UpdateProductCategoryDTO, @MedusaContext() sharedContext: Context = {} @@ -1288,22 +1258,23 @@ export default class ProductModuleService< return isString(idOrSelector) ? updatedCategories[0] : updatedCategories } - create( + //@ts-expect-error + createProducts( data: ProductTypes.CreateProductDTO[], sharedContext?: Context ): Promise - create( + createProducts( data: ProductTypes.CreateProductDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createProducts( data: ProductTypes.CreateProductDTO[] | ProductTypes.CreateProductDTO, @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const products = await this.create_(input, sharedContext) + const products = await this.createProducts_(input, sharedContext) const createdProducts = await this.baseRepository_.serialize< ProductTypes.ProductDTO[] @@ -1319,16 +1290,17 @@ export default class ProductModuleService< return Array.isArray(data) ? createdProducts : createdProducts[0] } - async upsert( + async upsertProducts( data: ProductTypes.UpsertProductDTO[], sharedContext?: Context ): Promise - async upsert( + async upsertProducts( data: ProductTypes.UpsertProductDTO, sharedContext?: Context ): Promise + @InjectTransactionManager("baseRepository_") - async upsert( + async upsertProducts( data: ProductTypes.UpsertProductDTO[] | ProductTypes.UpsertProductDTO, @MedusaContext() sharedContext: Context = {} ): Promise { @@ -1344,10 +1316,10 @@ export default class ProductModuleService< let updated: Product[] = [] if (forCreate.length) { - created = await this.create_(forCreate, sharedContext) + created = await this.createProducts_(forCreate, sharedContext) } if (forUpdate.length) { - updated = await this.update_(forUpdate, sharedContext) + updated = await this.updateProducts_(forUpdate, sharedContext) } const result = [...created, ...updated] @@ -1376,19 +1348,20 @@ export default class ProductModuleService< return Array.isArray(data) ? allProducts : allProducts[0] } - update( + // @ts-expect-error + updateProducts( id: string, data: ProductTypes.UpdateProductDTO, sharedContext?: Context ): Promise - update( + updateProducts( selector: ProductTypes.FilterableProductProps, data: ProductTypes.UpdateProductDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async update( + async updateProducts( idOrSelector: string | ProductTypes.FilterableProductProps, data: ProductTypes.UpdateProductDTO, @MedusaContext() sharedContext: Context = {} @@ -1412,7 +1385,7 @@ export default class ProductModuleService< })) } - const products = await this.update_(normalizedInput, sharedContext) + const products = await this.updateProducts_(normalizedInput, sharedContext) const updatedProducts = await this.baseRepository_.serialize< ProductTypes.ProductDTO[] @@ -1429,10 +1402,10 @@ export default class ProductModuleService< } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createProducts_( data: ProductTypes.CreateProductDTO[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const normalizedInput = await promiseAll( data.map(async (d) => { const normalized = await this.normalizeCreateProductInput( @@ -1495,10 +1468,10 @@ export default class ProductModuleService< } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updateProducts_( data: UpdateProductInput[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const normalizedInput = await promiseAll( data.map(async (d) => { const normalized = await this.normalizeUpdateProductInput( diff --git a/packages/modules/promotion/integration-tests/__fixtures__/promotion/index.ts b/packages/modules/promotion/integration-tests/__fixtures__/promotion/index.ts index d8df9ba7b0..fe3b3a01b9 100644 --- a/packages/modules/promotion/integration-tests/__fixtures__/promotion/index.ts +++ b/packages/modules/promotion/integration-tests/__fixtures__/promotion/index.ts @@ -48,7 +48,7 @@ export async function createDefaultPromotion( ): Promise { const { application_method = {}, campaign = {}, ...promotion } = data - return await service.create({ + return await service.createPromotions({ code: "PROMOTION_TEST", type: "standard", campaign_id: "campaign-id-1", diff --git a/packages/modules/promotion/integration-tests/__tests__/services/promotion-module/campaign.spec.ts b/packages/modules/promotion/integration-tests/__tests__/services/promotion-module/campaign.spec.ts index 49b9223c7d..890d319d68 100644 --- a/packages/modules/promotion/integration-tests/__tests__/services/promotion-module/campaign.spec.ts +++ b/packages/modules/promotion/integration-tests/__tests__/services/promotion-module/campaign.spec.ts @@ -1,18 +1,15 @@ import { Modules } from "@medusajs/modules-sdk" import { IPromotionModuleService } from "@medusajs/types" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { CampaignBudgetType } from "../../../../../../core/utils/src/promotion/index" import { createCampaigns } from "../../../__fixtures__/campaigns" import { createPromotions } from "../../../__fixtures__/promotion" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.PROMOTION, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ MikroOrmWrapper, service }) => { describe("Promotion Module Service: Campaigns", () => { describe("listAndCountCampaigns", () => { beforeEach(async () => { diff --git a/packages/modules/promotion/integration-tests/__tests__/services/promotion-module/promotion.spec.ts b/packages/modules/promotion/integration-tests/__tests__/services/promotion-module/promotion.spec.ts index 55a74f85b7..695314d3bf 100644 --- a/packages/modules/promotion/integration-tests/__tests__/services/promotion-module/promotion.spec.ts +++ b/packages/modules/promotion/integration-tests/__tests__/services/promotion-module/promotion.spec.ts @@ -40,7 +40,7 @@ moduleIntegrationTestRunner({ it("should create a basic promotion successfully", async () => { const createdPromotion = await createDefaultPromotion(service, {}) - const [promotion] = await service.list({ + const [promotion] = await service.listPromotions({ id: [createdPromotion.id], }) @@ -113,7 +113,7 @@ moduleIntegrationTestRunner({ }, }) - const [promotion] = await service.list( + const [promotion] = await service.listPromotions( { id: [createdPromotion.id] }, { relations: ["campaign.budget"] } ) @@ -146,7 +146,7 @@ moduleIntegrationTestRunner({ code: "PROMOTION_TEST", }) - const [promotion] = await service.list( + const [promotion] = await service.listPromotions( { id: [createdPromotion.id] }, { relations: ["campaign.budget"] } ) @@ -225,7 +225,7 @@ moduleIntegrationTestRunner({ ], }) - const [promotion] = await service.list( + const [promotion] = await service.listPromotions( { id: [createdPromotion.id] }, { relations: ["rules", "rules.values"] } ) @@ -264,7 +264,7 @@ moduleIntegrationTestRunner({ ], }) - const [promotion] = await service.list( + const [promotion] = await service.listPromotions( { id: [createdPromotion.id] }, { relations: ["rules", "rules.values"] } ) @@ -358,7 +358,7 @@ moduleIntegrationTestRunner({ } as any, }) - const [promotion] = await service.list({ + const [promotion] = await service.listPromotions({ id: [createdPromotion.id], }) @@ -512,7 +512,7 @@ moduleIntegrationTestRunner({ describe("update", () => { it("should throw an error when required params are not passed", async () => { const error = await service - .update([ + .updatePromotions([ { type: PromotionType.STANDARD, } as any, @@ -525,7 +525,7 @@ moduleIntegrationTestRunner({ it("should update the attributes of a promotion successfully", async () => { await createDefaultPromotions(service) - const [updatedPromotion] = await service.update([ + const [updatedPromotion] = await service.updatePromotions([ { id: "promotion-id-1", is_automatic: true, @@ -549,7 +549,7 @@ moduleIntegrationTestRunner({ } as any) const applicationMethod = createdPromotion.application_method - const [updatedPromotion] = await service.update([ + const [updatedPromotion] = await service.updatePromotions([ { id: createdPromotion.id, application_method: { @@ -574,7 +574,7 @@ moduleIntegrationTestRunner({ } as any) const applicationMethod = createdPromotion.application_method - const [updatedPromotion] = await service.update([ + const [updatedPromotion] = await service.updatePromotions([ { id: createdPromotion.id, application_method: { @@ -608,7 +608,7 @@ moduleIntegrationTestRunner({ const applicationMethod = createdPromotion.application_method let error = await service - .update([ + .updatePromotions([ { id: createdPromotion.id, application_method: { @@ -624,7 +624,7 @@ moduleIntegrationTestRunner({ ) error = await service - .update([ + .updatePromotions([ { id: createdPromotion.id, application_method: { @@ -640,7 +640,7 @@ moduleIntegrationTestRunner({ ) error = await service - .update([ + .updatePromotions([ { id: createdPromotion.id, application_method: { @@ -661,7 +661,7 @@ moduleIntegrationTestRunner({ campaign_id: "campaign-id-1", }) - const [updatedPromotion] = await service.update([ + const [updatedPromotion] = await service.updatePromotions([ { id: createdPromotion.id, campaign_id: "campaign-id-2", @@ -686,7 +686,7 @@ moduleIntegrationTestRunner({ const id = "promotion-id-1" it("should return promotion for the given id", async () => { - const promotion = await service.retrieve(id) + const promotion = await service.retrievePromotion(id) expect(promotion).toEqual( expect.objectContaining({ @@ -699,7 +699,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve("does-not-exist") + await service.retrievePromotion("does-not-exist") } catch (e) { error = e } @@ -713,7 +713,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve(undefined as unknown as string) + await service.retrievePromotion(undefined as unknown as string) } catch (e) { error = e } @@ -722,7 +722,7 @@ moduleIntegrationTestRunner({ }) it("should return promotion based on config select param", async () => { - const promotion = await service.retrieve(id, { + const promotion = await service.retrievePromotion(id, { select: ["id"], }) @@ -757,7 +757,7 @@ moduleIntegrationTestRunner({ }) it("should return all promotions and count", async () => { - const [promotions, count] = await service.listAndCount() + const [promotions, count] = await service.listAndCountPromotions() expect(count).toEqual(2) expect(promotions).toEqual([ @@ -789,7 +789,7 @@ moduleIntegrationTestRunner({ }) it("should return all promotions based on config select and relations param", async () => { - const [promotions, count] = await service.listAndCount( + const [promotions, count] = await service.listAndCountPromotions( { id: ["promotion-id-1"], }, @@ -820,9 +820,9 @@ moduleIntegrationTestRunner({ type: "standard", }) - await service.delete([createdPromotion.id]) + await service.deletePromotions([createdPromotion.id]) - const promotions = await service.list( + const promotions = await service.listPromotions( { id: [createdPromotion.id], }, @@ -840,9 +840,9 @@ moduleIntegrationTestRunner({ type: "standard", }) - await service.softDelete([createdPromotion.id]) + await service.softDeletePromotions([createdPromotion.id]) - const promotions = await service.list({ + const promotions = await service.listPromotions({ id: [createdPromotion.id], }) @@ -857,14 +857,18 @@ moduleIntegrationTestRunner({ type: "standard", }) - await service.softDelete([createdPromotion.id]) + await service.softDeletePromotions([createdPromotion.id]) - let promotions = await service.list({ id: [createdPromotion.id] }) + let promotions = await service.listPromotions({ + id: [createdPromotion.id], + }) expect(promotions).toHaveLength(0) - await service.restore([createdPromotion.id]) + await service.restorePromotions([createdPromotion.id]) - promotions = await service.list({ id: [createdPromotion.id] }) + promotions = await service.listPromotions({ + id: [createdPromotion.id], + }) expect(promotions).toHaveLength(1) }) }) @@ -1127,9 +1131,12 @@ moduleIntegrationTestRunner({ await service.removePromotionRules(promotion.id, ruleIds) - const updatedPromotion = await service.retrieve(promotion.id, { - relations: ["rules", "rules.values"], - }) + const updatedPromotion = await service.retrievePromotion( + promotion.id, + { + relations: ["rules", "rules.values"], + } + ) expect(updatedPromotion).toEqual( expect.objectContaining({ @@ -1193,9 +1200,12 @@ moduleIntegrationTestRunner({ await service.removePromotionTargetRules(promotion.id, ruleIds) - const updatedPromotion = await service.retrieve(promotion.id, { - relations: ["application_method.target_rules.values"], - }) + const updatedPromotion = await service.retrievePromotion( + promotion.id, + { + relations: ["application_method.target_rules.values"], + } + ) expect(updatedPromotion).toEqual( expect.objectContaining({ @@ -1271,9 +1281,12 @@ moduleIntegrationTestRunner({ await service.removePromotionBuyRules(promotion.id, ruleIds) - const updatedPromotion = await service.retrieve(promotion.id, { - relations: ["application_method.buy_rules.values"], - }) + const updatedPromotion = await service.retrievePromotion( + promotion.id, + { + relations: ["application_method.buy_rules.values"], + } + ) expect(updatedPromotion).toEqual( expect.objectContaining({ diff --git a/packages/modules/promotion/package.json b/packages/modules/promotion/package.json index 2bb247ef2d..390ec73e15 100644 --- a/packages/modules/promotion/package.json +++ b/packages/modules/promotion/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-promotion-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/promotion/src/index.ts b/packages/modules/promotion/src/index.ts index dd414e1b19..4446120144 100644 --- a/packages/modules/promotion/src/index.ts +++ b/packages/modules/promotion/src/index.ts @@ -1,3 +1,7 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { PromotionModuleService } from "@services" +const moduleDefinition: ModuleExports = { + service: PromotionModuleService, +} export default moduleDefinition diff --git a/packages/modules/promotion/src/joiner-config.ts b/packages/modules/promotion/src/joiner-config.ts index b8ec012881..a3cefbb16f 100644 --- a/packages/modules/promotion/src/joiner-config.ts +++ b/packages/modules/promotion/src/joiner-config.ts @@ -1,40 +1,19 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { generateLinkableKeysMap } from "@medusajs/utils" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" import { Campaign, Promotion, PromotionRule } from "@models" -export const LinkableKeys = { - promotion_id: Promotion.name, - campaign_id: Campaign.name, - promotion_rule_id: PromotionRule.name, -} +export const joinerConfig = defineJoinerConfig(Modules.PROMOTION, { + entityQueryingConfig: [Promotion, Campaign, PromotionRule], + linkableKeys: { + promotion_id: Promotion.name, + campaign_id: Campaign.name, + promotion_rule_id: PromotionRule.name, + }, +}) -export const entityNameToLinkableKeysMap = generateLinkableKeysMap(LinkableKeys) - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.PROMOTION, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["promotion", "promotions"], - args: { - entity: Promotion.name, - }, - }, - { - name: ["campaign", "campaigns"], - args: { - entity: Campaign.name, - methodSuffix: "Campaigns", - }, - }, - { - name: ["promotion_rule", "promotion_rules"], - args: { - entity: PromotionRule.name, - methodSuffix: "PromotionRules", - }, - }, - ], -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/promotion/src/module-definition.ts b/packages/modules/promotion/src/module-definition.ts deleted file mode 100644 index d40766cf05..0000000000 --- a/packages/modules/promotion/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { PromotionModuleService } from "@services" - -const service = PromotionModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/promotion/src/repositories/index.ts b/packages/modules/promotion/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/promotion/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/promotion/src/services/promotion-module.ts b/packages/modules/promotion/src/services/promotion-module.ts index 3f2bc7d183..f7fa40efa7 100644 --- a/packages/modules/promotion/src/services/promotion-module.ts +++ b/packages/modules/promotion/src/services/promotion-module.ts @@ -22,6 +22,7 @@ import { MathBN, MedusaContext, MedusaError, + MedusaService, ModulesSdkUtils, PromotionType, transformPropertiesToBigNumber, @@ -66,41 +67,34 @@ type InjectedDependencies = { campaignBudgetService: ModulesSdkTypes.IMedusaInternalService } -const generateMethodForModels = { - ApplicationMethod, - Campaign, - CampaignBudget, - PromotionRule, - PromotionRuleValue, -} - -export default class PromotionModuleService< - TApplicationMethod extends ApplicationMethod = ApplicationMethod, - TPromotion extends Promotion = Promotion, - TPromotionRule extends PromotionRule = PromotionRule, - TPromotionRuleValue extends PromotionRuleValue = PromotionRuleValue, - TCampaign extends Campaign = Campaign, - TCampaignBudget extends CampaignBudget = CampaignBudget - > - extends ModulesSdkUtils.MedusaService< - PromotionTypes.PromotionDTO, +export default class PromotionModuleService + extends MedusaService<{ + Promotion: { dto: PromotionTypes.PromotionDTO } + ApplicationMethod: { dto: PromotionTypes.ApplicationMethodDTO } + Campaign: { dto: PromotionTypes.CampaignDTO } + CampaignBudget: { dto: PromotionTypes.CampaignBudgetDTO } + PromotionRule: { dto: PromotionTypes.PromotionRuleDTO } + PromotionRuleValue: { dto: PromotionTypes.PromotionRuleValueDTO } + }>( { - ApplicationMethod: { dto: PromotionTypes.ApplicationMethodDTO } - Campaign: { dto: PromotionTypes.CampaignDTO } - CampaignBudget: { dto: PromotionTypes.CampaignBudgetDTO } - PromotionRule: { dto: PromotionTypes.PromotionRuleDTO } - PromotionRuleValue: { dto: PromotionTypes.PromotionRuleValueDTO } - } - >(Promotion, generateMethodForModels, entityNameToLinkableKeysMap) + Promotion, + ApplicationMethod, + Campaign, + CampaignBudget, + PromotionRule, + PromotionRuleValue, + }, + entityNameToLinkableKeysMap + ) implements PromotionTypes.IPromotionModuleService { protected baseRepository_: DAL.RepositoryService - protected promotionService_: ModulesSdkTypes.IMedusaInternalService - protected applicationMethodService_: ModulesSdkTypes.IMedusaInternalService - protected promotionRuleService_: ModulesSdkTypes.IMedusaInternalService - protected promotionRuleValueService_: ModulesSdkTypes.IMedusaInternalService - protected campaignService_: ModulesSdkTypes.IMedusaInternalService - protected campaignBudgetService_: ModulesSdkTypes.IMedusaInternalService + protected promotionService_: ModulesSdkTypes.IMedusaInternalService + protected applicationMethodService_: ModulesSdkTypes.IMedusaInternalService + protected promotionRuleService_: ModulesSdkTypes.IMedusaInternalService + protected promotionRuleValueService_: ModulesSdkTypes.IMedusaInternalService + protected campaignService_: ModulesSdkTypes.IMedusaInternalService + protected campaignBudgetService_: ModulesSdkTypes.IMedusaInternalService constructor( { @@ -145,7 +139,7 @@ export default class PromotionModuleService< >() const promotionCodeUsageMap = new Map() - const existingPromotions = await this.list( + const existingPromotions = await this.listPromotions( { code: promotionCodes }, { relations: ["application_method", "campaign", "campaign.budget"] }, sharedContext @@ -256,7 +250,7 @@ export default class PromotionModuleService< const methodIdPromoValueMap = new Map() const automaticPromotions = preventAutoPromotions ? [] - : await this.list( + : await this.listPromotions( { is_automatic: true }, { select: ["code"], take: null }, sharedContext @@ -296,7 +290,7 @@ export default class PromotionModuleService< }) }) - const promotions = await this.list( + const promotions = await this.listPromotions( { code: [ ...promotionCodesToApply, @@ -432,27 +426,28 @@ export default class PromotionModuleService< return computedActions } - async create( + // @ts-expect-error + async createPromotions( data: PromotionTypes.CreatePromotionDTO, sharedContext?: Context ): Promise - async create( + async createPromotions( data: PromotionTypes.CreatePromotionDTO[], sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createPromotions( data: | PromotionTypes.CreatePromotionDTO | PromotionTypes.CreatePromotionDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const createdPromotions = await this.create_(input, sharedContext) + const createdPromotions = await this.createPromotions_(input, sharedContext) - const promotions = await this.list( + const promotions = await this.listPromotions( { id: createdPromotions.map((p) => p!.id) }, { relations: [ @@ -475,7 +470,7 @@ export default class PromotionModuleService< } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createPromotions_( data: PromotionTypes.CreatePromotionDTO[], @MedusaContext() sharedContext: Context = {} ) { @@ -699,27 +694,28 @@ export default class PromotionModuleService< return createdPromotions } - async update( + // @ts-expect-error + async updatePromotions( data: PromotionTypes.UpdatePromotionDTO, sharedContext?: Context ): Promise - async update( + async updatePromotions( data: PromotionTypes.UpdatePromotionDTO[], sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async update( + async updatePromotions( data: | PromotionTypes.UpdatePromotionDTO | PromotionTypes.UpdatePromotionDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const updatedPromotions = await this.update_(input, sharedContext) + const updatedPromotions = await this.updatePromotions_(input, sharedContext) - const promotions = await this.list( + const promotions = await this.listPromotions( { id: updatedPromotions.map((p) => p!.id) }, { relations: [ @@ -740,7 +736,7 @@ export default class PromotionModuleService< } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updatePromotions_( data: PromotionTypes.UpdatePromotionDTO[], @MedusaContext() sharedContext: Context = {} ) { @@ -1014,8 +1010,8 @@ export default class PromotionModuleService< relationName: "promotions" | "method_target_rules" | "method_buy_rules", relation: Promotion | ApplicationMethod, @MedusaContext() sharedContext: Context = {} - ): Promise { - const createdPromotionRules: TPromotionRule[] = [] + ): Promise { + const createdPromotionRules: PromotionRule[] = [] const promotion = relation instanceof ApplicationMethod ? relation.promotion : relation diff --git a/packages/modules/providers/auth-emailpass/package.json b/packages/modules/providers/auth-emailpass/package.json index 6d9a037f3e..118a52b279 100644 --- a/packages/modules/providers/auth-emailpass/package.json +++ b/packages/modules/providers/auth-emailpass/package.json @@ -12,7 +12,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/providers/file-local/package.json b/packages/modules/providers/file-local/package.json index 6cec2b9a52..0954cc9fc6 100644 --- a/packages/modules/providers/file-local/package.json +++ b/packages/modules/providers/file-local/package.json @@ -12,7 +12,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/providers/file-local/src/services/local-file.ts b/packages/modules/providers/file-local/src/services/local-file.ts index 322707c56e..3976462a41 100644 --- a/packages/modules/providers/file-local/src/services/local-file.ts +++ b/packages/modules/providers/file-local/src/services/local-file.ts @@ -39,7 +39,7 @@ export class LocalFileService extends AbstractFileProviderService { const filePath = this.getUploadFilePath(fileKey) const fileUrl = this.getUploadFileUrl(fileKey) - const content = Buffer.from(file.content, "binary") + const content = Buffer.from(file.content as string, "binary") await fs.writeFile(filePath, content) return { diff --git a/packages/modules/providers/file-s3/package.json b/packages/modules/providers/file-s3/package.json index 81974d46f5..aafa7677d3 100644 --- a/packages/modules/providers/file-s3/package.json +++ b/packages/modules/providers/file-s3/package.json @@ -12,7 +12,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/providers/fulfillment-manual/package.json b/packages/modules/providers/fulfillment-manual/package.json index d4c92fd74a..ce5ae57b40 100644 --- a/packages/modules/providers/fulfillment-manual/package.json +++ b/packages/modules/providers/fulfillment-manual/package.json @@ -12,7 +12,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/providers/notification-local/package.json b/packages/modules/providers/notification-local/package.json index 135f217e20..41604d853a 100644 --- a/packages/modules/providers/notification-local/package.json +++ b/packages/modules/providers/notification-local/package.json @@ -12,7 +12,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/providers/notification-sendgrid/package.json b/packages/modules/providers/notification-sendgrid/package.json index 61bc33f563..3a9993e7de 100644 --- a/packages/modules/providers/notification-sendgrid/package.json +++ b/packages/modules/providers/notification-sendgrid/package.json @@ -12,7 +12,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/providers/payment-stripe/package.json b/packages/modules/providers/payment-stripe/package.json index f5f38536a0..81ce5131fc 100644 --- a/packages/modules/providers/payment-stripe/package.json +++ b/packages/modules/providers/payment-stripe/package.json @@ -12,7 +12,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "author": "Medusa", "license": "MIT", diff --git a/packages/modules/region/integration-tests/__tests__/region-module.spec.ts b/packages/modules/region/integration-tests/__tests__/region-module.spec.ts index 0ae7072c7d..6dc99b29fe 100644 --- a/packages/modules/region/integration-tests/__tests__/region-module.spec.ts +++ b/packages/modules/region/integration-tests/__tests__/region-module.spec.ts @@ -1,15 +1,12 @@ import { Modules } from "@medusajs/modules-sdk" import { IRegionModuleService } from "@medusajs/types" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.REGION, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Region Module Service", () => { it("should create countries on application start", async () => { const countries = await service.listCountries({}, { take: null }) @@ -17,7 +14,7 @@ moduleIntegrationTestRunner({ }) it("should create and list a region", async () => { - const createdRegion = await service.create({ + const createdRegion = await service.createRegions({ name: "Europe", currency_code: "EUR", automatic_taxes: false, @@ -33,7 +30,7 @@ moduleIntegrationTestRunner({ }) ) - const region = await service.retrieve(createdRegion.id, { + const region = await service.retrieveRegion(createdRegion.id, { relations: ["countries"], }) @@ -48,13 +45,13 @@ moduleIntegrationTestRunner({ }) it("should create a region with countries", async () => { - const createdRegion = await service.create({ + const createdRegion = await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) - const region = await service.retrieve(createdRegion.id, { + const region = await service.retrieveRegion(createdRegion.id, { relations: ["countries"], }) @@ -80,7 +77,7 @@ moduleIntegrationTestRunner({ it("should throw when country doesn't exist", async () => { await expect( - service.create({ + service.createRegions({ name: "North America", currency_code: "USD", countries: ["neverland"], @@ -89,14 +86,14 @@ moduleIntegrationTestRunner({ }) it("should throw when country is already assigned to a region", async () => { - await service.create({ + await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us"], }) await expect( - service.create({ + service.createRegions({ name: "United States", currency_code: "USD", countries: ["us"], @@ -108,7 +105,7 @@ moduleIntegrationTestRunner({ it("should throw when country is being assigned to multiple regions", async () => { await expect( - service.create([ + service.createRegions([ { name: "United States", currency_code: "USD", @@ -126,13 +123,13 @@ moduleIntegrationTestRunner({ }) it("should upsert the region successfully", async () => { - const createdRegion = await service.upsert({ + const createdRegion = await service.upsertRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) - await service.upsert({ + await service.upsertRegions({ id: createdRegion.id, name: "Americas", currency_code: "MXN", @@ -140,7 +137,7 @@ moduleIntegrationTestRunner({ automatic_taxes: false, }) - const latestRegion = await service.retrieve(createdRegion.id, { + const latestRegion = await service.retrieveRegion(createdRegion.id, { relations: ["countries"], }) @@ -154,13 +151,13 @@ moduleIntegrationTestRunner({ }) it("should allow mixing create and update operations in upsert", async () => { - const createdRegion = await service.upsert({ + const createdRegion = await service.upsertRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) - const upserted = await service.upsert([ + const upserted = await service.upsertRegions([ { id: createdRegion.id, name: "Americas", @@ -190,29 +187,29 @@ moduleIntegrationTestRunner({ }) it("should update the region successfully", async () => { - const createdRegion = await service.create({ + const createdRegion = await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) - const shouldNotBeChangedRegion = await service.create({ + const shouldNotBeChangedRegion = await service.createRegions({ name: "Europe", currency_code: "EUR", countries: ["hr"], }) - await service.update(createdRegion.id, { + await service.updateRegions(createdRegion.id, { name: "Americas", currency_code: "MXN", countries: ["us", "mx"], }) - const latestRegion = await service.retrieve(createdRegion.id, { + const latestRegion = await service.retrieveRegion(createdRegion.id, { relations: ["countries"], }) - const shouldNotBeChangedRegionAfter = await service.retrieve( + const shouldNotBeChangedRegionAfter = await service.retrieveRegion( shouldNotBeChangedRegion.id, { relations: ["countries"], @@ -235,18 +232,18 @@ moduleIntegrationTestRunner({ }) it("should update the region without affecting countries if countries are undefined", async () => { - const createdRegion = await service.create({ + const createdRegion = await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) - await service.update(createdRegion.id, { + await service.updateRegions(createdRegion.id, { name: "Americas", currency_code: "MXN", }) - const updatedRegion = await service.retrieve(createdRegion.id, { + const updatedRegion = await service.retrieveRegion(createdRegion.id, { relations: ["countries"], }) @@ -263,19 +260,19 @@ moduleIntegrationTestRunner({ }) it("should remove the countries in a region successfully", async () => { - const createdRegion = await service.create({ + const createdRegion = await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) - await service.update(createdRegion.id, { + await service.updateRegions(createdRegion.id, { name: "Americas", currency_code: "MXN", countries: [], }) - const updatedRegion = await service.retrieve(createdRegion.id, { + const updatedRegion = await service.retrieveRegion(createdRegion.id, { relations: ["countries"], }) @@ -289,14 +286,14 @@ moduleIntegrationTestRunner({ }) it("should fail updating the region countries to non-existent ones", async () => { - const createdRegion = await service.create({ + const createdRegion = await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) await expect( - service.update( + service.updateRegions( { id: createdRegion.id }, { countries: ["us", "neverland"], @@ -306,14 +303,14 @@ moduleIntegrationTestRunner({ }) it("should fail updating the region if there are duplicate countries", async () => { - const createdRegion = await service.create({ + const createdRegion = await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) await expect( - service.update( + service.updateRegions( { id: createdRegion.id }, { countries: ["us", "us"], @@ -325,7 +322,7 @@ moduleIntegrationTestRunner({ }) it("should fail updating the region if country is already used", async () => { - const [createdRegion] = await service.create([ + const [createdRegion] = await service.createRegions([ { name: "North America", currency_code: "USD", @@ -339,7 +336,7 @@ moduleIntegrationTestRunner({ ]) await expect( - service.update( + service.updateRegions( { id: createdRegion.id }, { countries: ["us", "mx"], @@ -351,21 +348,21 @@ moduleIntegrationTestRunner({ }) it("should unset the region ID on the country when deleting a region", async () => { - const createdRegion = await service.create({ + const createdRegion = await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) - await service.delete(createdRegion.id) + await service.deleteRegions(createdRegion.id) - const newRegion = await service.create({ + const newRegion = await service.createRegions({ name: "North America", currency_code: "USD", countries: ["us", "ca"], }) - const resp = await service.retrieve(newRegion.id, { + const resp = await service.retrieveRegion(newRegion.id, { relations: ["countries"], }) diff --git a/packages/modules/region/package.json b/packages/modules/region/package.json index b519818eb3..376326c103 100644 --- a/packages/modules/region/package.json +++ b/packages/modules/region/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-region-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/region/src/index.ts b/packages/modules/region/src/index.ts index dd414e1b19..b5eec03e31 100644 --- a/packages/modules/region/src/index.ts +++ b/packages/modules/region/src/index.ts @@ -1,3 +1,9 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { RegionModuleService } from "./services" +import loadDefaults from "./loaders/defaults" +const moduleDefinition: ModuleExports = { + service: RegionModuleService, + loaders: [loadDefaults], +} export default moduleDefinition diff --git a/packages/modules/region/src/joiner-config.ts b/packages/modules/region/src/joiner-config.ts index 28ec186528..780be956c6 100644 --- a/packages/modules/region/src/joiner-config.ts +++ b/packages/modules/region/src/joiner-config.ts @@ -1,36 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import { Country, Region } from "@models" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys = { - region_id: Region.name, - country_iso: Country.name, -} +export const joinerConfig = defineJoinerConfig(Modules.REGION) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.REGION, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["region", "regions"], - args: { entity: Region.name }, - }, - { - name: ["country", "countries"], - args: { entity: Country.name, methodSuffix: "Countries" }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/region/src/module-definition.ts b/packages/modules/region/src/module-definition.ts deleted file mode 100644 index 6446066774..0000000000 --- a/packages/modules/region/src/module-definition.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { RegionModuleService } from "./services" -import loadDefaults from "./loaders/defaults" - -const service = RegionModuleService -const loaders = [loadDefaults] - -export const moduleDefinition: ModuleExports = { - service, - loaders, -} diff --git a/packages/modules/region/src/repositories/index.ts b/packages/modules/region/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/region/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/region/src/scripts/bin/run-seed.ts b/packages/modules/region/src/scripts/bin/run-seed.ts deleted file mode 100644 index 1fd7d8d178..0000000000 --- a/packages/modules/region/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env node - -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as RegionModels from "@models" -import { EOL } from "os" -import { createRegions } from "../seed-utils" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-region-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.REGION, - models: RegionModels, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - const { regionData } = data - await createRegions(manager, regionData) - }, - }) - await run({ path }) -})() diff --git a/packages/modules/region/src/scripts/seed-utils.ts b/packages/modules/region/src/scripts/seed-utils.ts deleted file mode 100644 index 0c41dd5cce..0000000000 --- a/packages/modules/region/src/scripts/seed-utils.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { RequiredEntityData } from "@mikro-orm/core" -import { SqlEntityManager } from "@mikro-orm/postgresql" -import { Region } from "@models" - -export async function createRegions( - manager: SqlEntityManager, - data: RequiredEntityData[] -) { - const regions = data.map((region) => { - return manager.create(Region, region) - }) - - await manager.persistAndFlush(regions) - - return regions -} diff --git a/packages/modules/region/src/services/region-module.ts b/packages/modules/region/src/services/region-module.ts index 1ad48b15a9..7d3ddbba38 100644 --- a/packages/modules/region/src/services/region-module.ts +++ b/packages/modules/region/src/services/region-module.ts @@ -20,7 +20,7 @@ import { isString, MedusaContext, MedusaError, - ModulesSdkUtils, + MedusaService, promiseAll, removeUndefined, } from "@medusajs/utils" @@ -36,25 +36,20 @@ type InjectedDependencies = { countryService: ModulesSdkTypes.IMedusaInternalService } -const generateMethodForModels = { Country } - -export default class RegionModuleService< - TRegion extends Region = Region, - TCountry extends Country = Country - > - extends ModulesSdkUtils.MedusaService< - RegionDTO, - { - Country: { - dto: RegionCountryDTO - } +export default class RegionModuleService + extends MedusaService<{ + Region: { + dto: RegionDTO } - >(Region, generateMethodForModels, entityNameToLinkableKeysMap) + Country: { + dto: RegionCountryDTO + } + }>({ Region, Country }, entityNameToLinkableKeysMap) implements IRegionModuleService { protected baseRepository_: DAL.RepositoryService - protected readonly regionService_: ModulesSdkTypes.IMedusaInternalService - protected readonly countryService_: ModulesSdkTypes.IMedusaInternalService + protected readonly regionService_: ModulesSdkTypes.IMedusaInternalService + protected readonly countryService_: ModulesSdkTypes.IMedusaInternalService constructor( { baseRepository, regionService, countryService }: InjectedDependencies, @@ -71,22 +66,24 @@ export default class RegionModuleService< return joinerConfig } - async create( + //@ts-expect-error + async createRegions( data: CreateRegionDTO[], sharedContext?: Context ): Promise - async create( + async createRegions( data: CreateRegionDTO, sharedContext?: Context ): Promise + @InjectManager("baseRepository_") - async create( + async createRegions( data: CreateRegionDTO | CreateRegionDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const result = await this.create_(input, sharedContext) + const result = await this.createRegions_(input, sharedContext) return await this.baseRepository_.serialize( Array.isArray(data) ? result : result[0] @@ -94,7 +91,7 @@ export default class RegionModuleService< } @InjectTransactionManager("baseRepository_") - async create_( + async createRegions_( data: CreateRegionDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -132,16 +129,17 @@ export default class RegionModuleService< return result } - async upsert( + async upsertRegions( data: UpsertRegionDTO[], sharedContext?: Context ): Promise - async upsert( + async upsertRegions( data: UpsertRegionDTO, sharedContext?: Context ): Promise + @InjectTransactionManager("baseRepository_") - async upsert( + async upsertRegions( data: UpsertRegionDTO | UpsertRegionDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -156,10 +154,10 @@ export default class RegionModuleService< const operations: Promise[] = [] if (forCreate.length) { - operations.push(this.create_(forCreate, sharedContext)) + operations.push(this.createRegions_(forCreate, sharedContext)) } if (forUpdate.length) { - operations.push(this.update_(forUpdate, sharedContext)) + operations.push(this.updateRegions_(forUpdate, sharedContext)) } const result = (await promiseAll(operations)).flat() @@ -168,18 +166,20 @@ export default class RegionModuleService< ) } - async update( + //@ts-expect-error + async updateRegions( id: string, data: UpdateRegionDTO, sharedContext?: Context ): Promise - async update( + async updateRegions( selector: FilterableRegionProps, data: UpdateRegionDTO, sharedContext?: Context ): Promise + @InjectManager("baseRepository_") - async update( + async updateRegions( idOrSelector: string | FilterableRegionProps, data: UpdateRegionDTO, @MedusaContext() sharedContext: Context = {} @@ -200,7 +200,10 @@ export default class RegionModuleService< })) } - const updateResult = await this.update_(normalizedInput, sharedContext) + const updateResult = await this.updateRegions_( + normalizedInput, + sharedContext + ) const regions = await this.baseRepository_.serialize< RegionDTO[] | RegionDTO @@ -210,7 +213,7 @@ export default class RegionModuleService< } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updateRegions_( data: UpdateRegionInput[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -282,7 +285,7 @@ export default class RegionModuleService< private async validateCountries( countries: string[] | undefined, sharedContext: Context - ): Promise { + ): Promise { if (!countries?.length) { return [] } diff --git a/packages/modules/region/src/types/index.ts b/packages/modules/region/src/types/index.ts index bac2b3b320..a9f2f2a7e3 100644 --- a/packages/modules/region/src/types/index.ts +++ b/packages/modules/region/src/types/index.ts @@ -1,5 +1,4 @@ import { Logger, UpdateRegionDTO } from "@medusajs/types" -import { Country } from "@models" export type InitializeModuleInjectableDependencies = { logger?: Logger diff --git a/packages/modules/sales-channel/integration-tests/__fixtures__/index.ts b/packages/modules/sales-channel/integration-tests/__fixtures__/index.ts deleted file mode 100644 index 919cd51e4e..0000000000 --- a/packages/modules/sales-channel/integration-tests/__fixtures__/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { SqlEntityManager } from "@mikro-orm/postgresql" -import { SalesChannel } from "@models" - -const salesChannelData = [ - { - id: "channel-1", - name: "Channel 1", - description: "Channel description 1", - is_disabled: false, - }, - { - id: "channel-2", - name: "Channel 2", - description: "Channel description 2", - is_disabled: false, - }, - { - id: "channel-3", - name: "Channel 3", - description: "Channel description 3", - is_disabled: true, - }, -] - -export async function createSalesChannels( - manager: SqlEntityManager, - channelData: any[] = salesChannelData -): Promise { - const channels: SalesChannel[] = [] - - for (let data of channelData) { - const sc = manager.create(SalesChannel, data) - - channels.push(sc) - } - - await manager.persistAndFlush(channels) - - return channels -} diff --git a/packages/modules/sales-channel/integration-tests/__tests__/services/sales-channel-module.spec.ts b/packages/modules/sales-channel/integration-tests/__tests__/services/sales-channel-module.spec.ts index 70c3cc7c4c..94610fb43f 100644 --- a/packages/modules/sales-channel/integration-tests/__tests__/services/sales-channel-module.spec.ts +++ b/packages/modules/sales-channel/integration-tests/__tests__/services/sales-channel-module.spec.ts @@ -1,46 +1,48 @@ -import { SqlEntityManager } from "@mikro-orm/postgresql" - import { ISalesChannelModuleService } from "@medusajs/types" - -import { createSalesChannels } from "../../__fixtures__" import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" import { Modules } from "@medusajs/modules-sdk" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +const salesChannelData = [ + { + id: "channel-1", + name: "Channel 1", + description: "Channel description 1", + is_disabled: false, + }, + { + id: "channel-2", + name: "Channel 2", + description: "Channel description 2", + is_disabled: false, + }, + { + id: "channel-3", + name: "Channel 3", + description: "Channel description 3", + is_disabled: true, + }, +] + +moduleIntegrationTestRunner({ moduleName: Modules.SALES_CHANNEL, - testSuite: ({ - MikroOrmWrapper, - medusaApp, - }: SuiteOptions) => { - let service: ISalesChannelModuleService - - beforeEach(() => { - service = medusaApp.modules[Modules.SALES_CHANNEL] - }) - + testSuite: ({ service }) => { describe("Sales Channel Service", () => { - let testManager: SqlEntityManager - let repositoryManager: SqlEntityManager - beforeEach(async () => { - repositoryManager = await MikroOrmWrapper.forkManager() - testManager = await MikroOrmWrapper.forkManager() - - await createSalesChannels(testManager) + await service.createSalesChannels(salesChannelData) }) describe("create", () => { it("should create a SalesChannel successfully", async () => { - const [created] = await service.create([ + const [created] = await service.createSalesChannels([ { name: "test", description: "test", }, ]) - const [channel] = await service.list({ + const [channel] = await service.listSalesChannels({ name: [created.name], }) @@ -53,7 +55,7 @@ moduleIntegrationTestRunner({ const id = "channel-1" it("should return SalesChannel for the given id", async () => { - const result = await service.retrieve(id) + const result = await service.retrieveSalesChannel(id) expect(result).toEqual( expect.objectContaining({ @@ -66,7 +68,7 @@ moduleIntegrationTestRunner({ let error try { - await service.retrieve("does-not-exist") + await service.retrieveSalesChannel("does-not-exist") } catch (e) { error = e } @@ -81,12 +83,12 @@ moduleIntegrationTestRunner({ const id = "channel-2" it("should update the name of the SalesChannel successfully", async () => { - await service.update(id, { + await service.updateSalesChannels(id, { name: "Update name 2", is_disabled: true, }) - const channel = await service.retrieve(id) + const channel = await service.retrieveSalesChannel(id) expect(channel.name).toEqual("Update name 2") expect(channel.is_disabled).toEqual(true) @@ -96,7 +98,7 @@ moduleIntegrationTestRunner({ let error try { - await service.update("does-not-exist", { + await service.updateSalesChannels("does-not-exist", { name: "does-not-exist", }) } catch (e) { @@ -111,7 +113,7 @@ moduleIntegrationTestRunner({ describe("list", () => { it("should return a list of SalesChannels", async () => { - const result = await service.list() + const result = await service.listSalesChannels() expect(result).toEqual([ expect.objectContaining({ @@ -127,7 +129,7 @@ moduleIntegrationTestRunner({ }) it("should list SalesChannels by name", async () => { - const result = await service.list({ + const result = await service.listSalesChannels({ name: ["Channel 2", "Channel 3"], }) @@ -144,7 +146,7 @@ moduleIntegrationTestRunner({ describe("listAndCount", () => { it("should return sales channels and count", async () => { - const [result, count] = await service.listAndCount() + const [result, count] = await service.listAndCountSalesChannels() expect(count).toEqual(3) expect(result).toEqual([ @@ -161,7 +163,7 @@ moduleIntegrationTestRunner({ }) it("should return sales channels and count when filtered", async () => { - const [result, count] = await service.listAndCount({ + const [result, count] = await service.listAndCountSalesChannels({ id: ["channel-2"], }) @@ -174,7 +176,7 @@ moduleIntegrationTestRunner({ }) it("should return sales channels and count when using skip and take", async () => { - const [results, count] = await service.listAndCount( + const [results, count] = await service.listAndCountSalesChannels( {}, { skip: 1, take: 1 } ) @@ -188,7 +190,7 @@ moduleIntegrationTestRunner({ }) it("should return requested fields", async () => { - const [result, count] = await service.listAndCount( + const [result, count] = await service.listAndCountSalesChannels( {}, { take: 1, @@ -208,7 +210,7 @@ moduleIntegrationTestRunner({ }) it("should filter disabled channels", async () => { - const [result, count] = await service.listAndCount( + const [result, count] = await service.listAndCountSalesChannels( { is_disabled: true }, { select: ["id"] } ) @@ -228,9 +230,9 @@ moduleIntegrationTestRunner({ const id = "channel-2" it("should delete the SalesChannel given an id successfully", async () => { - await service.delete([id]) + await service.deleteSalesChannels([id]) - const result = await service.list({ + const result = await service.listSalesChannels({ id: [id], }) diff --git a/packages/modules/sales-channel/integration-tests/setup-env.js b/packages/modules/sales-channel/integration-tests/setup-env.js deleted file mode 100644 index 5daa6d8584..0000000000 --- a/packages/modules/sales-channel/integration-tests/setup-env.js +++ /dev/null @@ -1,6 +0,0 @@ -if (typeof process.env.DB_TEMP_NAME === "undefined") { - const tempName = parseInt(process.env.JEST_WORKER_ID || "1") - process.env.DB_TEMP_NAME = `medusa-sales-channel-integration-${tempName}` -} - -process.env.MEDUSA_SALES_CHANNEL_DB_SCHEMA = "public" diff --git a/packages/modules/sales-channel/integration-tests/setup.js b/packages/modules/sales-channel/integration-tests/setup.js deleted file mode 100644 index 43f99aab4a..0000000000 --- a/packages/modules/sales-channel/integration-tests/setup.js +++ /dev/null @@ -1,3 +0,0 @@ -import { JestUtils } from "medusa-test-utils" - -JestUtils.afterAllHookDropDatabase() diff --git a/packages/modules/sales-channel/integration-tests/utils/config.ts b/packages/modules/sales-channel/integration-tests/utils/config.ts deleted file mode 100644 index 73f470e65b..0000000000 --- a/packages/modules/sales-channel/integration-tests/utils/config.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { ModuleServiceInitializeOptions } from "@medusajs/types" - -export const databaseOptions: ModuleServiceInitializeOptions["database"] = { - schema: "public", - clientUrl: "medusa-sales-channel-test", -} diff --git a/packages/modules/sales-channel/integration-tests/utils/database.ts b/packages/modules/sales-channel/integration-tests/utils/database.ts deleted file mode 100644 index 26681dd7fc..0000000000 --- a/packages/modules/sales-channel/integration-tests/utils/database.ts +++ /dev/null @@ -1,18 +0,0 @@ -import {TestDatabaseUtils} from "medusa-test-utils" - -import * as SalesChannelModels from "@models" - -const pathToMigrations = "../../src/migrations" -const mikroOrmEntities = SalesChannelModels as unknown as any[] - -export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper({ - mikroOrmEntities, - pathToMigrations, -}) - -export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig({ - mikroOrmEntities, - pathToMigrations, -}) - -export const DB_URL = TestDatabaseUtils.getDatabaseURL() diff --git a/packages/modules/sales-channel/integration-tests/utils/index.ts b/packages/modules/sales-channel/integration-tests/utils/index.ts deleted file mode 100644 index 6b917ed30e..0000000000 --- a/packages/modules/sales-channel/integration-tests/utils/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./database" diff --git a/packages/modules/sales-channel/jest.config.js b/packages/modules/sales-channel/jest.config.js index dce2002dae..0c652264ea 100644 --- a/packages/modules/sales-channel/jest.config.js +++ b/packages/modules/sales-channel/jest.config.js @@ -17,6 +17,4 @@ module.exports = { testEnvironment: `node`, moduleFileExtensions: [`js`, `ts`], modulePathIgnorePatterns: ["dist/"], - setupFiles: ["/integration-tests/setup-env.js"], - setupFilesAfterEnv: ["/integration-tests/setup.js"], } diff --git a/packages/modules/sales-channel/package.json b/packages/modules/sales-channel/package.json index 206e2a970d..fb2c2d9c47 100644 --- a/packages/modules/sales-channel/package.json +++ b/packages/modules/sales-channel/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-sales-channel-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/sales-channel/src/index.ts b/packages/modules/sales-channel/src/index.ts index d464b550c0..b7a661d136 100644 --- a/packages/modules/sales-channel/src/index.ts +++ b/packages/modules/sales-channel/src/index.ts @@ -1,7 +1,7 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { SalesChannelModuleService } from "@services" +const moduleDefinition: ModuleExports = { + service: SalesChannelModuleService, +} export default moduleDefinition - -export * from "./types" -export * from "./models" -export * from "./services" diff --git a/packages/modules/sales-channel/src/joiner-config.ts b/packages/modules/sales-channel/src/joiner-config.ts index 44673e2f69..d16648cb2b 100644 --- a/packages/modules/sales-channel/src/joiner-config.ts +++ b/packages/modules/sales-channel/src/joiner-config.ts @@ -1,31 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import { SalesChannel } from "@models" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys = { - sales_channel_id: SalesChannel.name, -} +export const joinerConfig = defineJoinerConfig(Modules.SALES_CHANNEL) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.SALES_CHANNEL, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["sales_channel", "sales_channels"], - args: { entity: "SalesChannel" }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/sales-channel/src/module-definition.ts b/packages/modules/sales-channel/src/module-definition.ts deleted file mode 100644 index 55251db041..0000000000 --- a/packages/modules/sales-channel/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { SalesChannelModuleService } from "@services" - -const service = SalesChannelModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/sales-channel/src/scripts/bin/run-seed.ts b/packages/modules/sales-channel/src/scripts/bin/run-seed.ts deleted file mode 100644 index 750138065c..0000000000 --- a/packages/modules/sales-channel/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env node - -import { ModulesSdkUtils } from "@medusajs/utils" -import { Modules } from "@medusajs/modules-sdk" -import * as ProductModels from "@models" -import { createSalesChannels } from "../seed-utils" -import { EOL } from "os" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-product-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.PRODUCT, - models: ProductModels, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - const { salesChannelData } = data - await createSalesChannels(manager, salesChannelData) - }, - }) - await run({ path }) -})() diff --git a/packages/modules/sales-channel/src/scripts/seed-utils.ts b/packages/modules/sales-channel/src/scripts/seed-utils.ts deleted file mode 100644 index 61c3f27a95..0000000000 --- a/packages/modules/sales-channel/src/scripts/seed-utils.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { SalesChannel } from "@models" -import { RequiredEntityData } from "@mikro-orm/core" -import { SqlEntityManager } from "@mikro-orm/postgresql" - -export async function createSalesChannels( - manager: SqlEntityManager, - data: RequiredEntityData[] -) { - const channels = data.map((channel) => { - return manager.create(SalesChannel, channel) - }) - - await manager.persistAndFlush(channels) - - return channels -} diff --git a/packages/modules/sales-channel/src/services/sales-channel-module.ts b/packages/modules/sales-channel/src/services/sales-channel-module.ts index 8fc3def9dc..45debc2507 100644 --- a/packages/modules/sales-channel/src/services/sales-channel-module.ts +++ b/packages/modules/sales-channel/src/services/sales-channel-module.ts @@ -15,7 +15,7 @@ import { InjectTransactionManager, isString, MedusaContext, - ModulesSdkUtils, + MedusaService, promiseAll, } from "@medusajs/utils" @@ -30,18 +30,15 @@ type InjectedDependencies = { salesChannelService: ModulesSdkTypes.IMedusaInternalService } -export default class SalesChannelModuleService< - TEntity extends SalesChannel = SalesChannel - > - extends ModulesSdkUtils.MedusaService( - SalesChannel, - {}, +export default class SalesChannelModuleService + extends MedusaService<{ SalesChannel: { dto: SalesChannelDTO } }>( + { SalesChannel }, entityNameToLinkableKeysMap ) implements ISalesChannelModuleService { protected baseRepository_: DAL.RepositoryService - protected readonly salesChannelService_: ModulesSdkTypes.IMedusaInternalService + protected readonly salesChannelService_: ModulesSdkTypes.IMedusaInternalService constructor( { baseRepository, salesChannelService }: InjectedDependencies, @@ -57,22 +54,24 @@ export default class SalesChannelModuleService< return joinerConfig } - async create( + // @ts-expect-error + async createSalesChannels( data: CreateSalesChannelDTO[], sharedContext?: Context ): Promise - async create( + async createSalesChannels( data: CreateSalesChannelDTO, sharedContext?: Context ): Promise + @InjectManager("baseRepository_") - async create( + async createSalesChannels( data: CreateSalesChannelDTO | CreateSalesChannelDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const result = await this.create_(input, sharedContext) + const result = await this.createSalesChannels_(input, sharedContext) return await this.baseRepository_.serialize( Array.isArray(data) ? result : result[0], @@ -83,25 +82,27 @@ export default class SalesChannelModuleService< } @InjectTransactionManager("baseRepository_") - async create_( + async createSalesChannels_( data: CreateSalesChannelDTO[], @MedusaContext() sharedContext: Context ): Promise { return await this.salesChannelService_.create(data, sharedContext) } - async update( + // @ts-expect-error + async updateSalesChannels( id: string, data: UpdateSalesChannelDTO, sharedContext?: Context ): Promise - async update( + async updateSalesChannels( selector: FilterableSalesChannelProps, data: UpdateSalesChannelDTO, sharedContext?: Context ): Promise + @InjectManager("baseRepository_") - async update( + async updateSalesChannels( idOrSelector: string | FilterableSalesChannelProps, data: UpdateSalesChannelDTO | UpdateSalesChannelDTO[], @MedusaContext() sharedContext: Context = {} @@ -122,7 +123,10 @@ export default class SalesChannelModuleService< })) } - const result = await this.update_(normalizedInput, sharedContext) + const result = await this.updateSalesChannels_( + normalizedInput, + sharedContext + ) return await this.baseRepository_.serialize( Array.isArray(data) ? result : result[0], @@ -133,20 +137,23 @@ export default class SalesChannelModuleService< } @InjectTransactionManager("baseRepository_") - async update_(data: UpdateSalesChannelDTO[], sharedContext: Context) { + async updateSalesChannels_( + data: UpdateSalesChannelDTO[], + sharedContext: Context + ) { return await this.salesChannelService_.update(data, sharedContext) } - async upsert( + async upsertSalesChannels( data: UpsertSalesChannelDTO[], sharedContext?: Context ): Promise - async upsert( + async upsertSalesChannels( data: UpsertSalesChannelDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") - async upsert( + async upsertSalesChannels( data: UpsertSalesChannelDTO | UpsertSalesChannelDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -161,10 +168,10 @@ export default class SalesChannelModuleService< const operations: Promise[] = [] if (forCreate.length) { - operations.push(this.create_(forCreate, sharedContext)) + operations.push(this.createSalesChannels_(forCreate, sharedContext)) } if (forUpdate.length) { - operations.push(this.update_(forUpdate, sharedContext)) + operations.push(this.updateSalesChannels_(forUpdate, sharedContext)) } const result = (await promiseAll(operations)).flat() diff --git a/packages/modules/stock-location-next/integration-tests/__tests__/stock-location-module-service.spec.ts b/packages/modules/stock-location-next/integration-tests/__tests__/stock-location-module-service.spec.ts index 5083dc7423..31d0eba5f0 100644 --- a/packages/modules/stock-location-next/integration-tests/__tests__/stock-location-module-service.spec.ts +++ b/packages/modules/stock-location-next/integration-tests/__tests__/stock-location-module-service.spec.ts @@ -1,22 +1,18 @@ -import { SuiteOptions, moduleIntegrationTestRunner } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { IStockLocationService } from "@medusajs/types" import { Modules } from "@medusajs/modules-sdk" jest.setTimeout(100000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.STOCK_LOCATION, - resolve: "@medusajs/stock-location-next", - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Stock Location Module Service", () => { describe("create", () => { it("should create a stock location", async () => { const data = { name: "location" } - const location = await service.create(data) + const location = await service.createStockLocations(data) expect(location).toEqual( expect.objectContaining({ id: expect.any(String), ...data }) @@ -25,7 +21,7 @@ moduleIntegrationTestRunner({ it("should create stock locations for arrray", async () => { const data = [{ name: "location" }, { name: "location-1" }] - const locations = await service.create(data) + const locations = await service.createStockLocations(data) expect(locations).toEqual([ expect.objectContaining({ id: expect.any(String), ...data[0] }), @@ -38,7 +34,7 @@ moduleIntegrationTestRunner({ name: "location", address: { city: "city", address_1: "street", country_code: "US" }, } - const location = await service.create(data) + const location = await service.createStockLocations(data) expect(location).toEqual( expect.objectContaining({ @@ -71,7 +67,7 @@ moduleIntegrationTestRunner({ }, }, ] - const location = await service.create(data) + const location = await service.createStockLocations(data) expect(location).toEqual( expect.arrayContaining([ @@ -99,7 +95,9 @@ moduleIntegrationTestRunner({ describe("update", () => { let stockLocation beforeEach(async () => { - stockLocation = await service.create({ name: "location" }) + stockLocation = await service.createStockLocations({ + name: "location", + }) }) it("should update a stock location", async () => { @@ -107,7 +105,7 @@ moduleIntegrationTestRunner({ id: stockLocation.id, name: "updated location", } - const location = await service.upsert(data) + const location = await service.upsertStockLocations(data) expect(location).toEqual(expect.objectContaining(data)) }) @@ -122,7 +120,7 @@ moduleIntegrationTestRunner({ }, } - const location = await service.upsert(data) + const location = await service.upsertStockLocations(data) expect(location).toEqual( expect.objectContaining({ @@ -135,7 +133,7 @@ moduleIntegrationTestRunner({ describe("updateStockLocationAddress", () => { let stockLocation beforeEach(async () => { - stockLocation = await service.create({ + stockLocation = await service.createStockLocations({ name: "location", address: { city: "city", address_1: "street", country_code: "US" }, }) @@ -148,7 +146,9 @@ moduleIntegrationTestRunner({ address_1: "updated address_1", country_code: "updated country_code", } - const location = await service.updateStockLocationAddress(data) + const location = await (service as any).updateStockLocationAddresses( + data + ) expect(location).toEqual(expect.objectContaining(data)) }) diff --git a/packages/modules/stock-location-next/package.json b/packages/modules/stock-location-next/package.json index d4dd965952..a110dc1df0 100644 --- a/packages/modules/stock-location-next/package.json +++ b/packages/modules/stock-location-next/package.json @@ -9,7 +9,7 @@ "directory": "packages/stock-location" }, "engines": { - "node": ">=16" + "node": ">=20" }, "publishConfig": { "access": "public" diff --git a/packages/modules/stock-location-next/src/index.ts b/packages/modules/stock-location-next/src/index.ts index 5fb9170fa0..2249ce249c 100644 --- a/packages/modules/stock-location-next/src/index.ts +++ b/packages/modules/stock-location-next/src/index.ts @@ -1,6 +1,7 @@ -import { moduleDefinition } from "./module-definition" - -export * from "./models" -export * from "./services" +import { StockLocationModuleService } from "@services" +import { ModuleExports } from "@medusajs/types" +const moduleDefinition: ModuleExports = { + service: StockLocationModuleService, +} export default moduleDefinition diff --git a/packages/modules/stock-location-next/src/joiner-config.ts b/packages/modules/stock-location-next/src/joiner-config.ts index 527125f9ec..07eaef92f6 100644 --- a/packages/modules/stock-location-next/src/joiner-config.ts +++ b/packages/modules/stock-location-next/src/joiner-config.ts @@ -1,35 +1,17 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" import { StockLocation } from "./models" -import moduleSchema from "./schema" -export const LinkableKeys = { - stock_location_id: StockLocation.name, - location_id: StockLocation.name, -} - -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) +export const joinerConfig = defineJoinerConfig(Modules.STOCK_LOCATION, { + linkableKeys: { + stock_location_id: StockLocation.name, + location_id: StockLocation.name, + }, }) -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.STOCK_LOCATION, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - schema: moduleSchema, - alias: [ - { - name: ["stock_location", "stock_locations"], - args: { - entity: "StockLocation", - }, - }, - ], -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/stock-location-next/src/module-definition.ts b/packages/modules/stock-location-next/src/module-definition.ts deleted file mode 100644 index 028bc7f989..0000000000 --- a/packages/modules/stock-location-next/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { StockLocationModuleService } from "@services" -import { ModuleExports } from "@medusajs/types" - -const service = StockLocationModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/stock-location-next/src/repositories/index.ts b/packages/modules/stock-location-next/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/stock-location-next/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/stock-location-next/src/schema/index.ts b/packages/modules/stock-location-next/src/schema/index.ts deleted file mode 100644 index 9a7b198d62..0000000000 --- a/packages/modules/stock-location-next/src/schema/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -export default ` -scalar DateTime -scalar JSON -type StockLocation { - id: ID! - created_at: DateTime! - updated_at: DateTime! - deleted_at: DateTime - name: String! - address_id: String - address: StockLocationAddress - metadata: JSON -} -type StockLocationAddress { - id: ID! - created_at: DateTime! - updated_at: DateTime! - deleted_at: DateTime - address_1: String! - address_2: String - company: String - city: String - country_code: String! - phone: String - province: String - postal_code: String - metadata: JSON -} -` diff --git a/packages/modules/stock-location-next/src/services/stock-location-module.ts b/packages/modules/stock-location-next/src/services/stock-location-module.ts index 32b2f0f716..45e3706145 100644 --- a/packages/modules/stock-location-next/src/services/stock-location-module.ts +++ b/packages/modules/stock-location-next/src/services/stock-location-module.ts @@ -5,12 +5,12 @@ import { DAL, FilterableStockLocationProps, IEventBusService, - IStockLocationServiceNext, + IStockLocationService, ModuleJoinerConfig, ModulesSdkTypes, StockLocationAddressInput, StockLocationTypes, - UpdateStockLocationNextInput, + UpdateStockLocationInput, UpsertStockLocationInput, } from "@medusajs/types" import { @@ -18,7 +18,7 @@ import { InjectTransactionManager, isString, MedusaContext, - ModulesSdkUtils, + MedusaService, promiseAll, } from "@medusajs/utils" import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" @@ -31,28 +31,20 @@ type InjectedDependencies = { stockLocationAddressService: ModulesSdkTypes.IMedusaInternalService } -const generateMethodForModels = { StockLocationAddress } - /** * Service for managing stock locations. */ -export default class StockLocationModuleService< - TEntity extends StockLocation = StockLocation, - TStockLocationAddress extends StockLocationAddress = StockLocationAddress - > - extends ModulesSdkUtils.MedusaService< - StockLocationTypes.StockLocationDTO, - { - StockLocation: { dto: StockLocationTypes.StockLocationDTO } - StockLocationAddress: { dto: StockLocationTypes.StockLocationAddressDTO } - } - >(StockLocation, generateMethodForModels, entityNameToLinkableKeysMap) - implements IStockLocationServiceNext +export default class StockLocationModuleService + extends MedusaService<{ + StockLocation: { dto: StockLocationTypes.StockLocationDTO } + StockLocationAddress: { dto: StockLocationTypes.StockLocationAddressDTO } + }>({ StockLocation, StockLocationAddress }, entityNameToLinkableKeysMap) + implements IStockLocationService { protected readonly eventBusModuleService_: IEventBusService protected baseRepository_: DAL.RepositoryService - protected readonly stockLocationService_: ModulesSdkTypes.IMedusaInternalService - protected readonly stockLocationAddressService_: ModulesSdkTypes.IMedusaInternalService + protected readonly stockLocationService_: ModulesSdkTypes.IMedusaInternalService + protected readonly stockLocationAddressService_: ModulesSdkTypes.IMedusaInternalService constructor( { @@ -76,23 +68,18 @@ export default class StockLocationModuleService< return joinerConfig } - create( + // @ts-expect-error + createStockLocations( data: CreateStockLocationInput, context: Context ): Promise - create( + createStockLocations( data: CreateStockLocationInput[], context: Context ): Promise - /** - * Creates a new stock location. - * @param data - The input data for creating a Stock Location. - * @param context - * @returns The created stock location. - */ @InjectManager("baseRepository_") - async create( + async createStockLocations( data: CreateStockLocationInput | CreateStockLocationInput[], @MedusaContext() context: Context = {} ): Promise< @@ -100,7 +87,7 @@ export default class StockLocationModuleService< > { const input = Array.isArray(data) ? data : [data] - const created = await this.create_(input, context) + const created = await this.createStockLocations_(input, context) const serialized = await this.baseRepository_.serialize< | StockLocationTypes.StockLocationDTO @@ -111,24 +98,24 @@ export default class StockLocationModuleService< } @InjectTransactionManager("baseRepository_") - async create_( + async createStockLocations_( data: CreateStockLocationInput[], @MedusaContext() context: Context = {} - ): Promise { + ): Promise { return await this.stockLocationService_.create(data, context) } - async upsert( + async upsertStockLocations( data: UpsertStockLocationInput, context?: Context ): Promise - async upsert( + async upsertStockLocations( data: UpsertStockLocationInput[], context?: Context ): Promise @InjectManager("baseRepository_") - async upsert( + async upsertStockLocations( data: UpsertStockLocationInput | UpsertStockLocationInput[], @MedusaContext() context: Context = {} ): Promise< @@ -136,7 +123,7 @@ export default class StockLocationModuleService< > { const input = Array.isArray(data) ? data : [data] - const result = await this.upsert_(input, context) + const result = await this.upsertStockLocations_(input, context) return await this.baseRepository_.serialize< | StockLocationTypes.StockLocationDTO[] @@ -145,13 +132,13 @@ export default class StockLocationModuleService< } @InjectTransactionManager("baseRepository_") - async upsert_( + async upsertStockLocations_( input: UpsertStockLocationInput[], @MedusaContext() context: Context = {} ) { const toUpdate = input.filter( - (location): location is UpdateStockLocationNextInput => !!location.id - ) as UpdateStockLocationNextInput[] + (location): location is UpdateStockLocationInput => !!location.id + ) as UpdateStockLocationInput[] const toCreate = input.filter( (location) => !location.id ) as CreateStockLocationInput[] @@ -159,23 +146,24 @@ export default class StockLocationModuleService< const operations: Promise[] = [] if (toCreate.length) { - operations.push(this.create_(toCreate, context)) + operations.push(this.createStockLocations_(toCreate, context)) } if (toUpdate.length) { - operations.push(this.update_(toUpdate, context)) + operations.push(this.updateStockLocations_(toUpdate, context)) } return (await promiseAll(operations)).flat() } - update( + // @ts-expect-error + updateStockLocations( id: string, - input: UpdateStockLocationNextInput, + input: UpdateStockLocationInput, context?: Context ): Promise - update( + updateStockLocations( selector: FilterableStockLocationProps, - input: UpdateStockLocationNextInput, + input: UpdateStockLocationInput, context?: Context ): Promise /** @@ -186,22 +174,22 @@ export default class StockLocationModuleService< * @returns The updated stock location. */ @InjectManager("baseRepository_") - async update( + async updateStockLocations( idOrSelector: string | FilterableStockLocationProps, - data: UpdateStockLocationNextInput | UpdateStockLocationNextInput[], + data: UpdateStockLocationInput | UpdateStockLocationInput[], @MedusaContext() context: Context = {} ): Promise< StockLocationTypes.StockLocationDTO | StockLocationTypes.StockLocationDTO[] > { let normalizedInput: - | (UpdateStockLocationNextInput & { id: string })[] + | (UpdateStockLocationInput & { id: string })[] | { data: any; selector: FilterableStockLocationProps } = [] if (isString(idOrSelector)) { normalizedInput = [{ id: idOrSelector, ...data }] } else { normalizedInput = { data, selector: idOrSelector } } - const updated = await this.update_(normalizedInput, context) + const updated = await this.updateStockLocations_(normalizedInput, context) const serialized = await this.baseRepository_.serialize< | StockLocationTypes.StockLocationDTO @@ -212,27 +200,28 @@ export default class StockLocationModuleService< } @InjectTransactionManager("baseRepository_") - async update_( + async updateStockLocations_( data: - | UpdateStockLocationNextInput[] - | UpdateStockLocationNextInput + | UpdateStockLocationInput[] + | UpdateStockLocationInput | { data: any; selector: FilterableStockLocationProps }, @MedusaContext() context: Context = {} - ): Promise { + ): Promise { return await this.stockLocationService_.update(data, context) } - updateStockLocationAddress( + // @ts-expect-error + updateStockLocationAddresses( data: StockLocationAddressInput & { id: string }, context?: Context ): Promise - updateStockLocationAddress( + updateStockLocationAddresses( data: (StockLocationAddressInput & { id: string })[], context?: Context ): Promise @InjectManager("baseRepository_") - async updateStockLocationAddress( + async updateStockLocationAddresses( data: | (StockLocationAddressInput & { id: string }) | (StockLocationAddressInput & { id: string })[], @@ -240,7 +229,7 @@ export default class StockLocationModuleService< ) { const input = Array.isArray(data) ? data : [data] - const updated = await this.updateStockLocationAddress_(input, context) + const updated = await this.updateStockLocationAddresses_(input, context) const serialized = await this.baseRepository_.serialize< | StockLocationTypes.StockLocationAddressDTO @@ -251,7 +240,7 @@ export default class StockLocationModuleService< } @InjectTransactionManager("baseRepository_") - private async updateStockLocationAddress_( + private async updateStockLocationAddresses_( input: (StockLocationAddressInput & { id: string })[], @MedusaContext() context: Context ) { diff --git a/packages/modules/store/integration-tests/__tests__/store-module-service.spec.ts b/packages/modules/store/integration-tests/__tests__/store-module-service.spec.ts index f0c92bb06a..2a8e05c7eb 100644 --- a/packages/modules/store/integration-tests/__tests__/store-module-service.spec.ts +++ b/packages/modules/store/integration-tests/__tests__/store-module-service.spec.ts @@ -1,20 +1,17 @@ import { Modules } from "@medusajs/modules-sdk" import { IStoreModuleService } from "@medusajs/types" -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { createStoreFixture } from "../__fixtures__" jest.setTimeout(100000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.STORE, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("Store Module Service", () => { describe("creating a store", () => { it("should get created successfully", async function () { - const store = await service.create(createStoreFixture) + const store = await service.createStores(createStoreFixture) expect(store).toEqual( expect.objectContaining({ @@ -32,7 +29,7 @@ moduleIntegrationTestRunner({ it("should fail to get created if default currency code is not in list of supported currency codes", async function () { const err = await service - .create({ ...createStoreFixture, default_currency_code: "jpy" }) + .createStores({ ...createStoreFixture, default_currency_code: "jpy" }) .catch((err) => err.message) expect(err).toEqual("Store does not have currency: jpy") @@ -40,7 +37,7 @@ moduleIntegrationTestRunner({ describe("upserting a store", () => { it("should get created if it does not exist", async function () { - const store = await service.upsert(createStoreFixture) + const store = await service.upsertStores(createStoreFixture) expect(store).toEqual( expect.objectContaining({ @@ -55,8 +52,10 @@ moduleIntegrationTestRunner({ }) it("should get created if it does not exist", async function () { - const createdStore = await service.upsert(createStoreFixture) - const upsertedStore = await service.upsert({ name: "Upserted store" }) + const createdStore = await service.upsertStores(createStoreFixture) + const upsertedStore = await service.upsertStores({ + name: "Upserted store", + }) expect(upsertedStore).toEqual( expect.objectContaining({ @@ -69,17 +68,17 @@ moduleIntegrationTestRunner({ describe("updating a store", () => { it("should update the name successfully", async function () { - const createdStore = await service.create(createStoreFixture) - const updatedStore = await service.update(createdStore.id, { - title: "Updated store", + const createdStore = await service.createStores(createStoreFixture) + const updatedStore = await service.updateStores(createdStore.id, { + name: "Updated store", }) - expect(updatedStore.title).toEqual("Updated store") + expect(updatedStore.name).toEqual("Updated store") }) it("should fail updating default currency code to an unsupported one", async function () { - const createdStore = await service.create(createStoreFixture) + const createdStore = await service.createStores(createStoreFixture) const updateErr = await service - .update(createdStore.id, { + .updateStores(createdStore.id, { default_currency_code: "jpy", }) .catch((err) => err.message) @@ -88,9 +87,9 @@ moduleIntegrationTestRunner({ }) it("should fail updating default currency code to an unsupported one if the supported currencies are also updated", async function () { - const createdStore = await service.create(createStoreFixture) + const createdStore = await service.createStores(createStoreFixture) const updateErr = await service - .update(createdStore.id, { + .updateStores(createdStore.id, { supported_currency_codes: ["mkd"], default_currency_code: "jpy", }) @@ -100,12 +99,12 @@ moduleIntegrationTestRunner({ }) it("should fail updating supported currencies if one of them is used as a default one", async function () { - const createdStore = await service.create({ + const createdStore = await service.createStores({ ...createStoreFixture, default_currency_code: "eur", }) const updateErr = await service - .update(createdStore.id, { + .updateStores(createdStore.id, { supported_currency_codes: ["jpy"], }) .catch((err) => err.message) @@ -118,26 +117,26 @@ moduleIntegrationTestRunner({ describe("deleting a store", () => { it("should successfully delete existing stores", async function () { - const createdStore = await service.create([ + const createdStore = await service.createStores([ createStoreFixture, createStoreFixture, ]) - await service.delete([createdStore[0].id, createdStore[1].id]) + await service.deleteStores([createdStore[0].id, createdStore[1].id]) - const storeInDatabase = await service.list() + const storeInDatabase = await service.listStores() expect(storeInDatabase).toHaveLength(0) }) }) describe("retrieving a store", () => { it("should successfully return all existing stores", async function () { - await service.create([ + await service.createStores([ createStoreFixture, { ...createStoreFixture, name: "Another store" }, ]) - const storesInDatabase = await service.list() + const storesInDatabase = await service.listStores() expect(storesInDatabase).toHaveLength(2) expect(storesInDatabase.map((s) => s.name)).toEqual( expect.arrayContaining(["Test store", "Another store"]) diff --git a/packages/modules/store/package.json b/packages/modules/store/package.json index 332b8d3dbd..5b1d0f62dd 100644 --- a/packages/modules/store/package.json +++ b/packages/modules/store/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-store-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/store/src/index.ts b/packages/modules/store/src/index.ts index 5dc2ece165..a8b48a441f 100644 --- a/packages/modules/store/src/index.ts +++ b/packages/modules/store/src/index.ts @@ -1,7 +1,8 @@ -import { moduleDefinition } from "./module-definition" +import { StoreModuleService } from "@services" +import { ModuleExports } from "@medusajs/types" -export * from "./types" -export * from "./models" -export * from "./services" +export const moduleDefinition: ModuleExports = { + service: StoreModuleService, +} export default moduleDefinition diff --git a/packages/modules/store/src/joiner-config.ts b/packages/modules/store/src/joiner-config.ts index ce3bba36c0..9e370a9f41 100644 --- a/packages/modules/store/src/joiner-config.ts +++ b/packages/modules/store/src/joiner-config.ts @@ -1,29 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import Store from "./models/store" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys: Record = {} +export const joinerConfig = defineJoinerConfig(Modules.STORE) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.STORE, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["store", "stores"], - args: { entity: Store.name }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/store/src/module-definition.ts b/packages/modules/store/src/module-definition.ts deleted file mode 100644 index 462ef1004d..0000000000 --- a/packages/modules/store/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { StoreModuleService } from "@services" - -const service = StoreModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/store/src/repositories/index.ts b/packages/modules/store/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/store/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/store/src/scripts/bin/run-seed.ts b/packages/modules/store/src/scripts/bin/run-seed.ts deleted file mode 100644 index 9860747c5e..0000000000 --- a/packages/modules/store/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node - -import { ModulesSdkUtils } from "@medusajs/utils" -import { Modules } from "@medusajs/modules-sdk" -import * as Models from "@models" -import { EOL } from "os" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-store-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.STORE, - models: Models, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - // TODO: Add seed logic - }, - }) - await run({ path }) -})() diff --git a/packages/modules/store/src/services/store-module-service.ts b/packages/modules/store/src/services/store-module-service.ts index 42cf6599a3..0c83c1c79a 100644 --- a/packages/modules/store/src/services/store-module-service.ts +++ b/packages/modules/store/src/services/store-module-service.ts @@ -13,7 +13,7 @@ import { isString, MedusaContext, MedusaError, - ModulesSdkUtils, + MedusaService, promiseAll, removeUndefined, } from "@medusajs/utils" @@ -22,24 +22,19 @@ import { Store } from "@models" import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" import { UpdateStoreInput } from "@types" -const generateMethodForModels = {} - type InjectedDependencies = { baseRepository: DAL.RepositoryService storeService: ModulesSdkTypes.IMedusaInternalService } -export default class StoreModuleService - extends ModulesSdkUtils.MedusaService< - StoreTypes.StoreDTO, - { - Store: { dto: StoreTypes.StoreDTO } - } - >(Store, generateMethodForModels, entityNameToLinkableKeysMap) +export default class StoreModuleService + extends MedusaService<{ + Store: { dto: StoreTypes.StoreDTO } + }>({ Store }, entityNameToLinkableKeysMap) implements IStoreModuleService { protected baseRepository_: DAL.RepositoryService - protected readonly storeService_: ModulesSdkTypes.IMedusaInternalService + protected readonly storeService_: ModulesSdkTypes.IMedusaInternalService constructor( { baseRepository, storeService }: InjectedDependencies, @@ -55,16 +50,17 @@ export default class StoreModuleService return joinerConfig } - async create( + // @ts-expect-error + async createStores( data: StoreTypes.CreateStoreDTO[], sharedContext?: Context ): Promise - async create( + async createStores( data: StoreTypes.CreateStoreDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createStores( data: StoreTypes.CreateStoreDTO | StoreTypes.CreateStoreDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -88,16 +84,16 @@ export default class StoreModuleService return await this.storeService_.create(normalizedInput, sharedContext) } - async upsert( + async upsertStores( data: StoreTypes.UpsertStoreDTO[], sharedContext?: Context ): Promise - async upsert( + async upsertStores( data: StoreTypes.UpsertStoreDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") - async upsert( + async upsertStores( data: StoreTypes.UpsertStoreDTO | StoreTypes.UpsertStoreDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -124,18 +120,19 @@ export default class StoreModuleService >(Array.isArray(data) ? result : result[0]) } - async update( + // @ts-expect-error + async updateStores( id: string, data: StoreTypes.UpdateStoreDTO, sharedContext?: Context ): Promise - async update( + async updateStores( selector: StoreTypes.FilterableStoreProps, data: StoreTypes.UpdateStoreDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async update( + async updateStores( idOrSelector: string | StoreTypes.FilterableStoreProps, data: StoreTypes.UpdateStoreDTO, @MedusaContext() sharedContext: Context = {} diff --git a/packages/modules/tax/integration-tests/__tests__/index.spec.ts b/packages/modules/tax/integration-tests/__tests__/index.spec.ts index c52d85b274..1e90c3e5c9 100644 --- a/packages/modules/tax/integration-tests/__tests__/index.spec.ts +++ b/packages/modules/tax/integration-tests/__tests__/index.spec.ts @@ -1,13 +1,13 @@ -import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { moduleIntegrationTestRunner } from "medusa-test-utils" import { ITaxModuleService } from "@medusajs/types" import { Modules } from "@medusajs/modules-sdk" import { setupTaxStructure } from "../utils/setup-tax-structure" jest.setTimeout(30000) -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.TAX, - testSuite: ({ service }: SuiteOptions) => { + testSuite: ({ service }) => { describe("TaxModuleService", function () { it("should create tax rates and update them", async () => { const region = await service.createTaxRegions({ @@ -18,14 +18,14 @@ moduleIntegrationTestRunner({ }, }) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, name: "Shipping Rate", code: "test", rate: 8.23, }) - const updatedRate = await service.update(rate.id, { + const updatedRate = await service.updateTaxRates(rate.id, { name: "Updated Rate", code: "TEST", rate: 8.25, @@ -41,7 +41,7 @@ moduleIntegrationTestRunner({ }) ) - const updatedDefaultRate = await service.update( + const updatedDefaultRate = await service.updateTaxRates( { tax_region_id: region.id, is_default: true }, { rate: 2 } ) @@ -56,7 +56,7 @@ moduleIntegrationTestRunner({ }), ]) - const rates = await service.list() + const rates = await service.listTaxRates() expect(rates).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -85,14 +85,14 @@ moduleIntegrationTestRunner({ }, }) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, name: "Shipping Rate", code: "test", rate: 8.23, }) - await service.update(rate.id, { + await service.updateTaxRates(rate.id, { name: "Updated Rate", code: "TEST", rate: 8.25, @@ -117,7 +117,7 @@ moduleIntegrationTestRunner({ ]) ) - await service.update(rate.id, { + await service.updateTaxRates(rate.id, { rules: [ { reference: "product", reference_id: "product_id_1" }, { reference: "product", reference_id: "product_id_2" }, @@ -198,7 +198,7 @@ moduleIntegrationTestRunner({ ]) ) - const rates = await service.list() + const rates = await service.listTaxRates() expect(rates).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -228,7 +228,7 @@ moduleIntegrationTestRunner({ }, ]) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, name: "Shipping Rate", rate: 8.23, @@ -453,16 +453,16 @@ moduleIntegrationTestRunner({ country_code: "US", }) - const taxRate = await service.create({ + const taxRate = await service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", name: "test", }) - await service.delete(taxRate.id) + await service.deleteTaxRates(taxRate.id) - const rates = await service.list({ tax_region_id: region.id }) + const rates = await service.listTaxRates({ tax_region_id: region.id }) expect(rates).toEqual([]) }) @@ -472,16 +472,16 @@ moduleIntegrationTestRunner({ country_code: "US", }) - const taxRate = await service.create({ + const taxRate = await service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", name: "test", }) - await service.softDelete([taxRate.id]) + await service.softDeleteTaxRates([taxRate.id]) - const rates = await service.list( + const rates = await service.listTaxRates( { tax_region_id: region.id }, { withDeleted: true } ) @@ -504,7 +504,7 @@ moduleIntegrationTestRunner({ }, }) - await service.create({ + await service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", @@ -514,7 +514,7 @@ moduleIntegrationTestRunner({ await service.deleteTaxRegions(region.id) const taxRegions = await service.listTaxRegions() - const rates = await service.list() + const rates = await service.listTaxRates() expect(taxRegions).toEqual([]) expect(rates).toEqual([]) @@ -530,7 +530,7 @@ moduleIntegrationTestRunner({ }, }) - await service.create({ + await service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", @@ -543,7 +543,7 @@ moduleIntegrationTestRunner({ {}, { withDeleted: true } ) - const rates = await service.list({}, { withDeleted: true }) + const rates = await service.listTaxRates({}, { withDeleted: true }) expect(taxRegions).toEqual([ expect.objectContaining({ @@ -567,7 +567,7 @@ moduleIntegrationTestRunner({ country_code: "US", }) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", @@ -578,10 +578,10 @@ moduleIntegrationTestRunner({ ], }) - await service.delete(rate.id) + await service.deleteTaxRates(rate.id) const taxRegions = await service.listTaxRegions() - const rates = await service.list() + const rates = await service.listTaxRates() const rules = await service.listTaxRateRules() expect(taxRegions).toEqual([expect.objectContaining({ id: region.id })]) @@ -594,7 +594,7 @@ moduleIntegrationTestRunner({ country_code: "US", }) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", @@ -605,13 +605,13 @@ moduleIntegrationTestRunner({ ], }) - await service.softDelete(rate.id) + await service.softDeleteTaxRates(rate.id) const taxRegions = await service.listTaxRegions( {}, { withDeleted: true } ) - const rates = await service.list({}, { withDeleted: true }) + const rates = await service.listTaxRates({}, { withDeleted: true }) const rules = await service.listTaxRateRules({}, { withDeleted: true }) expect(taxRegions).toEqual([ @@ -640,7 +640,7 @@ moduleIntegrationTestRunner({ country_code: "US", }) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", @@ -676,7 +676,7 @@ moduleIntegrationTestRunner({ ]) ) - const rateWithRules = await service.retrieve(rate.id, { + const rateWithRules = await service.retrieveTaxRate(rate.id, { relations: ["rules"], }) expect(rateWithRules.rules.length).toBe(1) @@ -688,7 +688,7 @@ moduleIntegrationTestRunner({ reference_id: ruleOne.reference_id, }) - const rateWithRulesAfterReAdd = await service.retrieve(rate.id, { + const rateWithRulesAfterReAdd = await service.retrieveTaxRate(rate.id, { relations: ["rules"], }) expect(rateWithRulesAfterReAdd.rules.length).toBe(2) @@ -700,7 +700,7 @@ moduleIntegrationTestRunner({ }) await expect( - service.create({ + service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", @@ -714,7 +714,7 @@ moduleIntegrationTestRunner({ /Tax rate rule with tax_rate_id: .*?, reference_id: product_id_1, already exists./ ) - const rate = await service.create({ + const rate = await service.createTaxRates({ tax_region_id: region.id, value: 10, code: "test", @@ -790,7 +790,7 @@ moduleIntegrationTestRunner({ }) await expect( - service.create({ + service.createTaxRates({ tax_region_id: rate.id, name: "Shipping Rate", rate: 8.23, diff --git a/packages/modules/tax/integration-tests/utils/setup-tax-structure.ts b/packages/modules/tax/integration-tests/utils/setup-tax-structure.ts index 52f16860db..0813e0a662 100644 --- a/packages/modules/tax/integration-tests/utils/setup-tax-structure.ts +++ b/packages/modules/tax/integration-tests/utils/setup-tax-structure.ts @@ -102,7 +102,7 @@ export const setupTaxStructure = async (service: ITaxModuleService) => { ]) const [calProd, calType, deType, canProd, canType, qcType] = - await service.create([ + await service.createTaxRates([ { tax_region_id: cal.id, name: "CA Reduced Rate for Products", diff --git a/packages/modules/tax/package.json b/packages/modules/tax/package.json index c532eba948..421fe5bf1e 100644 --- a/packages/modules/tax/package.json +++ b/packages/modules/tax/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-tax-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/tax/src/index.ts b/packages/modules/tax/src/index.ts index 5fb9170fa0..542ac55bcc 100644 --- a/packages/modules/tax/src/index.ts +++ b/packages/modules/tax/src/index.ts @@ -1,6 +1,13 @@ -import { moduleDefinition } from "./module-definition" +import { ModuleExports } from "@medusajs/types" +import { TaxModuleService } from "@services" +import loadProviders from "./loaders/providers" -export * from "./models" -export * from "./services" +const service = TaxModuleService +const loaders = [loadProviders] + +export const moduleDefinition: ModuleExports = { + service, + loaders, +} export default moduleDefinition diff --git a/packages/modules/tax/src/joiner-config.ts b/packages/modules/tax/src/joiner-config.ts index 5f47703061..ad1d349c1e 100644 --- a/packages/modules/tax/src/joiner-config.ts +++ b/packages/modules/tax/src/joiner-config.ts @@ -1,57 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import { TaxProvider, TaxRate, TaxRateRule, TaxRegion } from "@models" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys: Record = { - tax_rate_id: TaxRate.name, - tax_region_id: TaxRegion.name, - tax_rate_rule_id: TaxRateRule.name, - tax_provider_id: TaxProvider.name, -} +export const joinerConfig = defineJoinerConfig(Modules.TAX) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.TAX, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["tax_rate", "tax_rates"], - args: { - entity: TaxRate.name, - }, - }, - { - name: ["tax_region", "tax_regions"], - args: { - entity: TaxRegion.name, - methodSuffix: "TaxRegions", - }, - }, - { - name: ["tax_rate_rule", "tax_rate_rules"], - args: { - entity: TaxRateRule.name, - methodSuffix: "TaxRateRules", - }, - }, - { - name: ["tax_provider", "tax_providers"], - args: { - entity: TaxProvider.name, - methodSuffix: "TaxProviders", - }, - }, - ], -} as ModuleJoinerConfig +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/tax/src/module-definition.ts b/packages/modules/tax/src/module-definition.ts deleted file mode 100644 index 2744a70ef0..0000000000 --- a/packages/modules/tax/src/module-definition.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ModuleExports } from "@medusajs/types" -import { TaxModuleService } from "@services" -import loadProviders from "./loaders/providers" - -const service = TaxModuleService -const loaders = [loadProviders] - -export const moduleDefinition: ModuleExports = { - service, - loaders, -} diff --git a/packages/modules/tax/src/scripts/bin/run-seed.ts b/packages/modules/tax/src/scripts/bin/run-seed.ts deleted file mode 100644 index 27e8d551b9..0000000000 --- a/packages/modules/tax/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node - -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as Models from "@models" -import { EOL } from "os" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-tax-seed ` - ) - } - - const run = ModulesSdkUtils.buildSeedScript({ - moduleName: Modules.TAX, - models: Models, - pathToMigrations: __dirname + "/../../migrations", - seedHandler: async ({ manager, data }) => { - // TODO: Add seed logic - }, - }) - await run({ path }) -})() diff --git a/packages/modules/tax/src/services/tax-module-service.ts b/packages/modules/tax/src/services/tax-module-service.ts index 651b9eeccc..91057882d6 100644 --- a/packages/modules/tax/src/services/tax-module-service.ts +++ b/packages/modules/tax/src/services/tax-module-service.ts @@ -31,35 +31,28 @@ type InjectedDependencies = { [key: `tp_${string}`]: ITaxProvider } -const generateForModels = { TaxRegion, TaxRateRule, TaxProvider } +const generateForModels = { TaxRate, TaxRegion, TaxRateRule, TaxProvider } type ItemWithRates = { rates: TaxRate[] item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO } -export default class TaxModuleService< - TTaxRate extends TaxRate = TaxRate, - TTaxRegion extends TaxRegion = TaxRegion, - TTaxRateRule extends TaxRateRule = TaxRateRule, - TTaxProvider extends TaxProvider = TaxProvider - > - extends ModulesSdkUtils.MedusaService< - TaxTypes.TaxRateDTO, - { - TaxRegion: { dto: TaxTypes.TaxRegionDTO } - TaxRateRule: { dto: TaxTypes.TaxRateRuleDTO } - TaxProvider: { dto: TaxTypes.TaxProviderDTO } - } - >(TaxRate, generateForModels, entityNameToLinkableKeysMap) +export default class TaxModuleService + extends ModulesSdkUtils.MedusaService<{ + TaxRate: { dto: TaxTypes.TaxRateDTO } + TaxRegion: { dto: TaxTypes.TaxRegionDTO } + TaxRateRule: { dto: TaxTypes.TaxRateRuleDTO } + TaxProvider: { dto: TaxTypes.TaxProviderDTO } + }>(generateForModels, entityNameToLinkableKeysMap) implements ITaxModuleService { protected readonly container_: InjectedDependencies protected baseRepository_: DAL.RepositoryService - protected taxRateService_: ModulesSdkTypes.IMedusaInternalService - protected taxRegionService_: ModulesSdkTypes.IMedusaInternalService - protected taxRateRuleService_: ModulesSdkTypes.IMedusaInternalService - protected taxProviderService_: ModulesSdkTypes.IMedusaInternalService + protected taxRateService_: ModulesSdkTypes.IMedusaInternalService + protected taxRegionService_: ModulesSdkTypes.IMedusaInternalService + protected taxRateRuleService_: ModulesSdkTypes.IMedusaInternalService + protected taxProviderService_: ModulesSdkTypes.IMedusaInternalService constructor( { @@ -86,28 +79,29 @@ export default class TaxModuleService< return joinerConfig } - async create( + // @ts-expect-error + async createTaxRates( data: TaxTypes.CreateTaxRateDTO[], sharedContext?: Context ): Promise - async create( + async createTaxRates( data: TaxTypes.CreateTaxRateDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async create( + async createTaxRates( data: TaxTypes.CreateTaxRateDTO[] | TaxTypes.CreateTaxRateDTO, @MedusaContext() sharedContext: Context = {} ): Promise { const input = Array.isArray(data) ? data : [data] - const rates = await this.create_(input, sharedContext) + const rates = await this.createTaxRates_(input, sharedContext) return Array.isArray(data) ? rates : rates[0] } @InjectTransactionManager("baseRepository_") - protected async create_( + protected async createTaxRates_( data: TaxTypes.CreateTaxRateDTO[], @MedusaContext() sharedContext: Context = {} ) { @@ -152,29 +146,30 @@ export default class TaxModuleService< }) } - async update( + // @ts-expect-error + async updateTaxRates( id: string, data: TaxTypes.UpdateTaxRateDTO, sharedContext?: Context ): Promise - async update( + async updateTaxRates( ids: string[], data: TaxTypes.UpdateTaxRateDTO, sharedContext?: Context ): Promise - async update( + async updateTaxRates( selector: TaxTypes.FilterableTaxRateProps, data: TaxTypes.UpdateTaxRateDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") - async update( + async updateTaxRates( selector: string | string[] | TaxTypes.FilterableTaxRateProps, data: TaxTypes.UpdateTaxRateDTO, @MedusaContext() sharedContext: Context = {} ): Promise { - const rates = await this.update_(selector, data, sharedContext) + const rates = await this.updateTaxRates_(selector, data, sharedContext) const serialized = await this.baseRepository_.serialize< TaxTypes.TaxRateDTO[] >(rates, { populate: true }) @@ -182,7 +177,7 @@ export default class TaxModuleService< } @InjectTransactionManager("baseRepository_") - protected async update_( + protected async updateTaxRates_( idOrSelector: string | string[] | TaxTypes.FilterableTaxRateProps, data: TaxTypes.UpdateTaxRateDTO, @MedusaContext() sharedContext: Context = {} @@ -271,17 +266,17 @@ export default class TaxModuleService< return rates.map((r) => r.id) } - async upsert( + async upsertTaxRates( data: TaxTypes.UpsertTaxRateDTO[], sharedContext?: Context ): Promise - async upsert( + async upsertTaxRates( data: TaxTypes.UpsertTaxRateDTO, sharedContext?: Context ): Promise @InjectTransactionManager("baseRepository_") - async upsert( + async upsertTaxRates( data: TaxTypes.UpsertTaxRateDTO | TaxTypes.UpsertTaxRateDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -340,7 +335,7 @@ export default class TaxModuleService< .filter(Boolean) as TaxTypes.CreateTaxRateDTO[] if (rates.length !== 0) { - await this.create(rates, sharedContext) + await this.createTaxRates(rates, sharedContext) } return await this.baseRepository_.serialize( @@ -419,7 +414,7 @@ export default class TaxModuleService< const toReturn = await promiseAll( items.map(async (item) => { const regionIds = regions.map((r) => r.id) - const rateQuery = this.getTaxRateQueryForItem(item, regionIds) + const rateQuery = this.geTaxRateQueryForItem(item, regionIds) const candidateRates = await this.taxRateService_.list( rateQuery, { @@ -428,7 +423,7 @@ export default class TaxModuleService< sharedContext ) - const applicableRates = await this.getTaxRatesForItem( + const applicableRates = await this.geTaxRatesForItem( item, candidateRates ) @@ -580,10 +575,10 @@ export default class TaxModuleService< } } - private async getTaxRatesForItem( + private async geTaxRatesForItem( item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO, - rates: TTaxRate[] - ): Promise { + rates: TaxRate[] + ): Promise { if (!rates.length) { return [] } @@ -612,7 +607,7 @@ export default class TaxModuleService< return ratesToReturn } - private getTaxRateQueryForItem( + private geTaxRateQueryForItem( item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO, regionIds: string[] ) { @@ -644,7 +639,7 @@ export default class TaxModuleService< } private checkRuleMatches( - rate: TTaxRate, + rate: TaxRate, item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO ) { if (rate.rules.length === 0) { @@ -684,12 +679,10 @@ export default class TaxModuleService< } private prioritizeRates( - rates: TTaxRate[], + rates: TaxRate[], item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO ) { - const decoratedRates: (TTaxRate & { - priority_score: number - })[] = rates.map((rate) => { + const decoratedRates = rates.map((rate) => { const { isProductMatch, isProductTypeMatch, isShippingMatch } = this.checkRuleMatches(rate, item) @@ -715,7 +708,9 @@ export default class TaxModuleService< decoratedRate.priority_score = 6 } return decoratedRate - }) + }) as (TaxRate & { + priority_score: number + })[] return decoratedRates.sort( (a, b) => (a as any).priority_score - (b as any).priority_score diff --git a/packages/modules/user/integration-tests/__fixtures__/invite.ts b/packages/modules/user/integration-tests/__fixtures__/invite.ts deleted file mode 100644 index 6d44d23ca8..0000000000 --- a/packages/modules/user/integration-tests/__fixtures__/invite.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { SqlEntityManager } from "@mikro-orm/postgresql" -import { Invite } from "@models" -import { CreateInviteDTO } from "../../../types/dist" - -export const createInvites = async ( - manager: SqlEntityManager, - inviteData: (CreateInviteDTO & { id?: string })[] -) => { - const invites: Invite[] = [] - - for (const invite of inviteData) { - const inv = manager.create(Invite, invite) - invites.push(inv) - } - - await manager.persistAndFlush(invites) -} diff --git a/packages/modules/user/integration-tests/__fixtures__/user.ts b/packages/modules/user/integration-tests/__fixtures__/user.ts deleted file mode 100644 index c1922a2414..0000000000 --- a/packages/modules/user/integration-tests/__fixtures__/user.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { SqlEntityManager } from "@mikro-orm/postgresql" -import { User } from "@models" -import { CreateUserDTO } from "../../../types/dist" - -export const createUsers = async ( - manager: SqlEntityManager, - userData: (CreateUserDTO & { id?: string })[] -) => { - const users: User[] = [] - - for (const user of userData) { - const usr = manager.create(User, user) - users.push(usr) - } - - await manager.persistAndFlush(users) -} diff --git a/packages/modules/user/integration-tests/__tests__/services/module/invite.spec.ts b/packages/modules/user/integration-tests/__tests__/invite.spec.ts similarity index 87% rename from packages/modules/user/integration-tests/__tests__/services/module/invite.spec.ts rename to packages/modules/user/integration-tests/__tests__/invite.spec.ts index 7747455a2c..ce42e09e2f 100644 --- a/packages/modules/user/integration-tests/__tests__/services/module/invite.spec.ts +++ b/packages/modules/user/integration-tests/__tests__/invite.spec.ts @@ -4,9 +4,7 @@ import { UserEvents } from "@medusajs/utils" import { MockEventBusService, moduleIntegrationTestRunner, - SuiteOptions, } from "medusa-test-utils" -import { createInvites } from "../../../__fixtures__/invite" jest.setTimeout(30000) @@ -28,7 +26,7 @@ const defaultInviteData = [ }, ] -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.USER, moduleOptions: { jwt_secret: "test", @@ -36,10 +34,7 @@ moduleIntegrationTestRunner({ injectedDependencies: { eventBusModuleService: new MockEventBusService(), }, - testSuite: ({ - MikroOrmWrapper, - service, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("UserModuleService - Invite", () => { beforeEach(async () => { jest.clearAllMocks() @@ -47,8 +42,7 @@ moduleIntegrationTestRunner({ describe("listInvites", () => { it("should list invites", async () => { - await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData) - + await service.createInvites(defaultInviteData) const invites = await service.listInvites() expect(invites).toEqual([ @@ -62,7 +56,7 @@ moduleIntegrationTestRunner({ }) it("should list invites by id", async () => { - await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData) + await service.createInvites(defaultInviteData) const invites = await service.listInvites({ id: ["1"], }) @@ -77,7 +71,7 @@ moduleIntegrationTestRunner({ describe("listAndCountInvites", () => { it("should list and count invites", async () => { - await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData) + await service.createInvites(defaultInviteData) const [invites, count] = await service.listAndCountInvites() expect(count).toEqual(2) @@ -92,7 +86,7 @@ moduleIntegrationTestRunner({ }) it("should listAndCount invites by id", async () => { - await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData) + await service.createInvites(defaultInviteData) const [invites, count] = await service.listAndCountInvites({ id: "1", }) @@ -110,7 +104,7 @@ moduleIntegrationTestRunner({ const id = "1" it("should return an invite for the given id", async () => { - await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData) + await service.createInvites(defaultInviteData) const invite = await service.retrieveInvite(id) expect(invite).toEqual( @@ -139,7 +133,7 @@ moduleIntegrationTestRunner({ }) it("should return invite based on config select param", async () => { - await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData) + await service.createInvites(defaultInviteData) const invite = await service.retrieveInvite(id, { select: ["id"], }) @@ -166,7 +160,7 @@ moduleIntegrationTestRunner({ }) it("should emit invite updated events", async () => { - await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData) + await service.createInvites(defaultInviteData) jest.clearAllMocks() @@ -190,12 +184,12 @@ moduleIntegrationTestRunner({ describe("resendInvite", () => { it("should emit token generated event for invites", async () => { - await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData) + await service.createInvites(defaultInviteData) const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") await service.refreshInviteTokens(["1"]) - expect(eventBusSpy).toHaveBeenCalledTimes(1) + expect(eventBusSpy).toHaveBeenCalledTimes(2) expect(eventBusSpy).toHaveBeenCalledWith([ expect.objectContaining({ data: { id: "1" }, diff --git a/packages/modules/user/integration-tests/__tests__/services/module/user.spec.ts b/packages/modules/user/integration-tests/__tests__/user.spec.ts similarity index 75% rename from packages/modules/user/integration-tests/__tests__/services/module/user.spec.ts rename to packages/modules/user/integration-tests/__tests__/user.spec.ts index 9654dbae19..2ffa00ac76 100644 --- a/packages/modules/user/integration-tests/__tests__/services/module/user.spec.ts +++ b/packages/modules/user/integration-tests/__tests__/user.spec.ts @@ -4,9 +4,7 @@ import { UserEvents } from "@medusajs/utils" import { MockEventBusService, moduleIntegrationTestRunner, - SuiteOptions, } from "medusa-test-utils" -import { createUsers } from "../../../__fixtures__/user" jest.setTimeout(30000) @@ -21,7 +19,7 @@ const defaultUserData = [ }, ] -moduleIntegrationTestRunner({ +moduleIntegrationTestRunner({ moduleName: Modules.USER, moduleOptions: { jwt_secret: "test", @@ -29,11 +27,7 @@ moduleIntegrationTestRunner({ injectedDependencies: { eventBusModuleService: new MockEventBusService(), }, - testSuite: ({ - MikroOrmWrapper, - service, - medusaApp, - }: SuiteOptions) => { + testSuite: ({ service }) => { describe("UserModuleService - User", () => { afterEach(async () => { jest.clearAllMocks() @@ -41,9 +35,8 @@ moduleIntegrationTestRunner({ describe("list", () => { it("should list users", async () => { - await createUsers(MikroOrmWrapper.forkManager(), defaultUserData) - - const users = await service.list() + await service.createUsers(defaultUserData) + const users = await service.listUsers() expect(users).toEqual([ expect.objectContaining({ @@ -56,8 +49,8 @@ moduleIntegrationTestRunner({ }) it("should list users by id", async () => { - await createUsers(MikroOrmWrapper.forkManager(), defaultUserData) - const users = await service.list({ + await service.createUsers(defaultUserData) + const users = await service.listUsers({ id: ["1"], }) @@ -71,8 +64,8 @@ moduleIntegrationTestRunner({ describe("listAndCount", () => { it("should list and count users", async () => { - await createUsers(MikroOrmWrapper.forkManager(), defaultUserData) - const [users, count] = await service.listAndCount() + await service.createUsers(defaultUserData) + const [users, count] = await service.listAndCountUsers() expect(count).toEqual(2) expect(users).toEqual([ @@ -86,8 +79,8 @@ moduleIntegrationTestRunner({ }) it("should list and count users by id", async () => { - await createUsers(MikroOrmWrapper.forkManager(), defaultUserData) - const [Users, count] = await service.listAndCount({ + await service.createUsers(defaultUserData) + const [Users, count] = await service.listAndCountUsers({ id: "1", }) @@ -104,9 +97,9 @@ moduleIntegrationTestRunner({ const id = "1" it("should return an user for the given id", async () => { - await createUsers(MikroOrmWrapper.forkManager(), defaultUserData) + await service.createUsers(defaultUserData) - const user = await service.retrieve(id) + const user = await service.retrieveUser(id) expect(user).toEqual( expect.objectContaining({ @@ -116,7 +109,9 @@ moduleIntegrationTestRunner({ }) it("should throw an error when an user with the given id does not exist", async () => { - const error = await service.retrieve("does-not-exist").catch((e) => e) + const error = await service + .retrieveUser("does-not-exist") + .catch((e) => e) expect(error.message).toEqual( "User with id: does-not-exist was not found" @@ -125,16 +120,16 @@ moduleIntegrationTestRunner({ it("should throw an error when a userId is not provided", async () => { const error = await service - .retrieve(undefined as unknown as string) + .retrieveUser(undefined as unknown as string) .catch((e) => e) expect(error.message).toEqual("user - id must be defined") }) it("should return user based on config select param", async () => { - await createUsers(MikroOrmWrapper.forkManager(), defaultUserData) + await service.createUsers(defaultUserData) - const User = await service.retrieve(id, { + const User = await service.retrieveUser(id, { select: ["id"], }) @@ -150,11 +145,11 @@ moduleIntegrationTestRunner({ const id = "1" it("should delete the users given an id successfully", async () => { - await createUsers(MikroOrmWrapper.forkManager(), defaultUserData) + await service.createUsers(defaultUserData) - await service.delete([id]) + await service.deleteUsers([id]) - const users = await service.list({ + const users = await service.listUsers({ id: [id], }) @@ -165,7 +160,7 @@ moduleIntegrationTestRunner({ describe("update", () => { it("should throw an error when a id does not exist", async () => { const error = await service - .update([ + .updateUsers([ { id: "does-not-exist", }, @@ -179,11 +174,11 @@ moduleIntegrationTestRunner({ it("should emit user created events", async () => { const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") - await service.create(defaultUserData) + await service.createUsers(defaultUserData) jest.clearAllMocks() - await service.update([ + await service.updateUsers([ { id: "1", first_name: "John", @@ -202,9 +197,9 @@ moduleIntegrationTestRunner({ describe("create", () => { it("should create a user successfully", async () => { - await service.create(defaultUserData) + await service.createUsers(defaultUserData) - const [User, count] = await service.listAndCount({ + const [User, count] = await service.listAndCountUsers({ id: ["1"], }) @@ -218,7 +213,7 @@ moduleIntegrationTestRunner({ it("should emit user created events", async () => { const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") - await service.create(defaultUserData) + await service.createUsers(defaultUserData) expect(eventBusSpy).toHaveBeenCalledTimes(1) expect(eventBusSpy).toHaveBeenCalledWith([ diff --git a/packages/modules/user/package.json b/packages/modules/user/package.json index 82004d89b1..de5596d296 100644 --- a/packages/modules/user/package.json +++ b/packages/modules/user/package.json @@ -8,10 +8,7 @@ "dist" ], "engines": { - "node": ">=16" - }, - "bin": { - "medusa-user-seed": "dist/scripts/bin/run-seed.js" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/user/src/index.ts b/packages/modules/user/src/index.ts index dd414e1b19..2c9628a28d 100644 --- a/packages/modules/user/src/index.ts +++ b/packages/modules/user/src/index.ts @@ -1,3 +1,7 @@ -import { moduleDefinition } from "./module-definition" +import { UserModuleService } from "@services" +import { ModuleExports } from "@medusajs/types" +const moduleDefinition: ModuleExports = { + service: UserModuleService, +} export default moduleDefinition diff --git a/packages/modules/user/src/joiner-config.ts b/packages/modules/user/src/joiner-config.ts index 9dda3f6263..b1bbe5718c 100644 --- a/packages/modules/user/src/joiner-config.ts +++ b/packages/modules/user/src/joiner-config.ts @@ -1,41 +1,11 @@ -import { Invite, User } from "@models" -import { MapToConfig } from "@medusajs/utils" -import { ModuleJoinerConfig } from "@medusajs/types" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" import { Modules } from "@medusajs/modules-sdk" -export const LinkableKeys = { - user_id: User.name, - invite_id: Invite.name, -} +export const joinerConfig = defineJoinerConfig(Modules.USER) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.USER, - primaryKeys: ["id"], - linkableKeys: LinkableKeys, - alias: [ - { - name: ["user", "users"], - args: { - entity: User.name, - }, - }, - { - name: ["invite", "invites"], - args: { - entity: Invite.name, - methodSuffix: "Invites", - }, - }, - ], -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/user/src/module-definition.ts b/packages/modules/user/src/module-definition.ts deleted file mode 100644 index 74a1931795..0000000000 --- a/packages/modules/user/src/module-definition.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { UserModuleService } from "@services" -import { ModuleExports } from "@medusajs/types" - -const service = UserModuleService - -export const moduleDefinition: ModuleExports = { - service, -} diff --git a/packages/modules/user/src/repositories/index.ts b/packages/modules/user/src/repositories/index.ts deleted file mode 100644 index 147c9cc259..0000000000 --- a/packages/modules/user/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/user/src/scripts/bin/run-seed.ts b/packages/modules/user/src/scripts/bin/run-seed.ts deleted file mode 100644 index 8e5f2c778b..0000000000 --- a/packages/modules/user/src/scripts/bin/run-seed.ts +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env node - -import { EOL } from "os" -import { run } from "../seed" - -const args = process.argv -const path = args.pop() as string - -export default (async () => { - const { config } = await import("dotenv") - config() - if (!path) { - throw new Error( - `filePath is required.${EOL}Example: medusa-user-seed ` - ) - } - - await run({ path }) -})() diff --git a/packages/modules/user/src/scripts/seed.ts b/packages/modules/user/src/scripts/seed.ts deleted file mode 100644 index a226bcea6f..0000000000 --- a/packages/modules/user/src/scripts/seed.ts +++ /dev/null @@ -1,58 +0,0 @@ -import * as UserModels from "@models" - -import { DALUtils, ModulesSdkUtils } from "@medusajs/utils" -import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types" - -import { EOL } from "os" -import { EntitySchema } from "@mikro-orm/core" -import { Modules } from "@medusajs/modules-sdk" -import { resolve } from "path" - -export async function run({ - options, - logger, - path, -}: Partial< - Pick< - LoaderOptions, - "options" | "logger" - > -> & { - path: string -}) { - logger ??= console as unknown as Logger - - logger.info(`Loading seed data from ${path}...`) - - const { userData } = await import(resolve(process.cwd(), path)).catch((e) => { - logger?.error( - `Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: userData.${EOL}${e}` - ) - throw e - }) - - const dbData = ModulesSdkUtils.loadDatabaseConfig(Modules.USER, options)! - const entities = Object.values(UserModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - const orm = await DALUtils.mikroOrmCreateConnection( - dbData, - entities, - pathToMigrations - ) - - const manager = orm.em.fork() - - try { - logger.info("Seeding user data..") - - // TODO: implement user seed data - // await createUsers(manager, usersData) - } catch (e) { - logger.error( - `Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}` - ) - } - - await orm.close(true) -} diff --git a/packages/modules/user/src/services/index.ts b/packages/modules/user/src/services/index.ts index 6761aa1bb0..fa745e078b 100644 --- a/packages/modules/user/src/services/index.ts +++ b/packages/modules/user/src/services/index.ts @@ -1,2 +1 @@ export { default as UserModuleService } from "./user-module" -export { default as InviteService } from "./invite" diff --git a/packages/modules/user/src/services/invite.ts b/packages/modules/user/src/services/invite.ts deleted file mode 100644 index 52cf0fb437..0000000000 --- a/packages/modules/user/src/services/invite.ts +++ /dev/null @@ -1,184 +0,0 @@ -import * as crypto from "crypto" - -import { Context, DAL } from "@medusajs/types" -import { - arrayDifference, - InjectTransactionManager, - MedusaError, - ModulesSdkUtils, -} from "@medusajs/utils" -import jwt, { JwtPayload } from "jsonwebtoken" - -import { Invite } from "@models" -import { InviteServiceTypes } from "@types" - -type InjectedDependencies = { - inviteRepository: DAL.RepositoryService -} - -// 1 day -const DEFAULT_VALID_INVITE_DURATION = 60 * 60 * 24 * 1000 - -export default class InviteService< - TEntity extends Invite = Invite -> extends ModulesSdkUtils.MedusaInternalService( - Invite -) { - // eslint-disable-next-line max-len - protected readonly inviteRepository_: DAL.RepositoryService - protected options_: { jwt_secret: string; valid_duration: number } | undefined - - constructor(container: InjectedDependencies) { - super(container) - this.inviteRepository_ = container.inviteRepository - } - - public withModuleOptions(options: any) { - const service = new InviteService(this.__container__) - - service.options_ = options - - return service - } - - private getOption(key: string) { - if (!this.options_) { - throw new MedusaError( - MedusaError.Types.UNEXPECTED_STATE, - `Options are not configured for InviteService, call "withModuleOptions" and provide options` - ) - } - return this.options_[key] - } - - create( - data: InviteServiceTypes.CreateInviteDTO, - context?: Context - ): Promise - create( - data: InviteServiceTypes.CreateInviteDTO[], - context?: Context - ): Promise - - @InjectTransactionManager("inviteRepository_") - async create( - data: - | InviteServiceTypes.CreateInviteDTO - | InviteServiceTypes.CreateInviteDTO[], - context: Context = {} - ): Promise { - const data_ = Array.isArray(data) ? data : [data] - - const invites = await super.create(data_, context) - - const expiresIn: number = this.getValidDuration() - - const updates = invites.map((invite) => { - return { - id: invite.id, - expires_at: new Date().setMilliseconds( - new Date().getMilliseconds() + expiresIn - ), - token: this.generateToken({ id: invite.id }), - } - }) - - return await super.update(updates, context) - } - - @InjectTransactionManager("inviteRepository_") - async refreshInviteTokens( - inviteIds: string[], - context: Context = {} - ): Promise { - const [invites, count] = await super.listAndCount( - { id: inviteIds }, - {}, - context - ) - - if (count !== inviteIds.length) { - const missing = arrayDifference( - inviteIds, - invites.map((invite) => invite.id) - ) - - if (missing.length > 0) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - `The following invites do not exist: ${missing.join(", ")}` - ) - } - } - - const expiresIn: number = this.getValidDuration() - - const updates = invites.map((invite) => { - return { - id: invite.id, - expires_at: new Date().setMilliseconds( - new Date().getMilliseconds() + expiresIn - ), - token: this.generateToken({ id: invite.id }), - } - }) - - return await super.update(updates, context) - } - - @InjectTransactionManager("inviteRepository_") - async validateInviteToken( - token: string, - context?: Context - ): Promise { - const decoded = this.validateToken(token) - - const invite = await super.retrieve(decoded.payload.id, {}, context) - - if (invite.expires_at < new Date()) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - "The invite has expired" - ) - } - - return invite - } - - private generateToken(data: any): string { - const jwtSecret: string = this.getOption("jwt_secret") - const expiresIn: number = this.getValidDuration() / 1000 - - if (!jwtSecret) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - "No jwt_secret was provided in the UserModule's options. Please add one." - ) - } - - return jwt.sign(data, jwtSecret, { - jwtid: crypto.randomUUID(), - expiresIn, - }) - } - - private getValidDuration(): number { - return ( - parseInt(this.getOption("valid_duration")) || - DEFAULT_VALID_INVITE_DURATION - ) - } - - private validateToken(data: any): JwtPayload { - const jwtSecret = this.getOption("jwt_secret") - - if (!jwtSecret) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - "No jwt_secret was provided in the UserModule's options. Please add one." - ) - } - - return jwt.verify(data, jwtSecret, { complete: true }) - } -} diff --git a/packages/modules/user/src/services/user-module.ts b/packages/modules/user/src/services/user-module.ts index 6d243b76ae..1ffd068a65 100644 --- a/packages/modules/user/src/services/user-module.ts +++ b/packages/modules/user/src/services/user-module.ts @@ -8,40 +8,40 @@ import { UserTypes, } from "@medusajs/types" import { + arrayDifference, CommonEvents, EmitEvents, InjectManager, InjectTransactionManager, MedusaContext, - ModulesSdkUtils, + MedusaError, + MedusaService, UserEvents, } from "@medusajs/utils" +import jwt, { JwtPayload } from "jsonwebtoken" import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config" +import crypto from "node:crypto" import { Invite, User } from "@models" -import InviteService from "./invite" type InjectedDependencies = { baseRepository: DAL.RepositoryService userService: ModulesSdkTypes.IMedusaInternalService - inviteService: InviteService + inviteService: ModulesSdkTypes.IMedusaInternalService eventBusModuleService: IEventBusModuleService } -const generateMethodForModels = { Invite } - -export default class UserModuleService< - TUser extends User = User, - TInvite extends Invite = Invite - > - extends ModulesSdkUtils.MedusaService< - UserTypes.UserDTO, - { - Invite: { - dto: UserTypes.InviteDTO - } +// 1 day +const DEFAULT_VALID_INVITE_DURATION = 60 * 60 * 24 * 1000 +export default class UserModuleService + extends MedusaService<{ + User: { + dto: UserTypes.UserDTO } - >(User, generateMethodForModels, entityNameToLinkableKeysMap) + Invite: { + dto: UserTypes.InviteDTO + } + }>({ User, Invite }, entityNameToLinkableKeysMap) implements UserTypes.IUserModuleService { __joinerConfig(): ModuleJoinerConfig { @@ -50,8 +50,9 @@ export default class UserModuleService< protected baseRepository_: DAL.RepositoryService - protected readonly userService_: ModulesSdkTypes.IMedusaInternalService - protected readonly inviteService_: InviteService + protected readonly userService_: ModulesSdkTypes.IMedusaInternalService + protected readonly inviteService_: ModulesSdkTypes.IMedusaInternalService + protected readonly config: { jwtSecret: string; expiresIn: number } constructor( { userService, inviteService, baseRepository }: InjectedDependencies, @@ -62,9 +63,20 @@ export default class UserModuleService< this.baseRepository_ = baseRepository this.userService_ = userService - this.inviteService_ = inviteService.withModuleOptions( - this.moduleDeclaration - ) + this.inviteService_ = inviteService + this.config = { + jwtSecret: moduleDeclaration["jwt_secret"], + expiresIn: + parseInt(moduleDeclaration["valid_duration"]) || + DEFAULT_VALID_INVITE_DURATION, + } + + if (!this.config.jwtSecret) { + throw new MedusaError( + MedusaError.Types.INVALID_DATA, + "No jwt_secret was provided in the UserModule's options. Please add one." + ) + } } @InjectTransactionManager("baseRepository_") @@ -72,11 +84,22 @@ export default class UserModuleService< token: string, @MedusaContext() sharedContext: Context = {} ): Promise { - const invite = await this.inviteService_.validateInviteToken( - token, + const jwtSecret = this.moduleDeclaration["jwt_secret"] + const decoded: JwtPayload = jwt.verify(token, jwtSecret, { complete: true }) + + const invite = await this.inviteService_.retrieve( + decoded.payload.id, + {}, sharedContext ) + if (invite.expires_at < new Date()) { + throw new MedusaError( + MedusaError.Types.INVALID_DATA, + "The invite has expired" + ) + } + return await this.baseRepository_.serialize(invite, { populate: true, }) @@ -114,24 +137,52 @@ export default class UserModuleService< inviteIds: string[], @MedusaContext() sharedContext: Context = {} ) { - return await this.inviteService_.refreshInviteTokens( - inviteIds, + const [invites, count] = await this.inviteService_.listAndCount( + { id: inviteIds }, + {}, sharedContext ) + + if (count !== inviteIds.length) { + const missing = arrayDifference( + inviteIds, + invites.map((invite) => invite.id) + ) + + if (missing.length > 0) { + throw new MedusaError( + MedusaError.Types.INVALID_DATA, + `The following invites do not exist: ${missing.join(", ")}` + ) + } + } + + const updates = invites.map((invite) => { + return { + id: invite.id, + expires_at: new Date().setMilliseconds( + new Date().getMilliseconds() + this.config.expiresIn + ), + token: this.generateToken({ id: invite.id }), + } + }) + + return await this.inviteService_.update(updates, sharedContext) } - create( + // @ts-expect-error + createUsers( data: UserTypes.CreateUserDTO[], sharedContext?: Context ): Promise - create( + createUsers( data: UserTypes.CreateUserDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") @EmitEvents() - async create( + async createUsers( data: UserTypes.CreateUserDTO[] | UserTypes.CreateUserDTO, @MedusaContext() sharedContext: Context = {} ): Promise { @@ -159,18 +210,19 @@ export default class UserModuleService< return Array.isArray(data) ? serializedUsers : serializedUsers[0] } - update( + // @ts-expect-error + updateUsers( data: UserTypes.UpdateUserDTO[], sharedContext?: Context ): Promise - update( + updateUsers( data: UserTypes.UpdateUserDTO, sharedContext?: Context ): Promise @InjectManager("baseRepository_") @EmitEvents() - async update( + async updateUsers( data: UserTypes.UpdateUserDTO | UserTypes.UpdateUserDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { @@ -253,7 +305,7 @@ export default class UserModuleService< private async createInvites_( data: UserTypes.CreateInviteDTO[], @MedusaContext() sharedContext: Context = {} - ): Promise { + ): Promise { const toCreate = data.map((invite) => { return { ...invite, @@ -262,7 +314,19 @@ export default class UserModuleService< } }) - return await this.inviteService_.create(toCreate, sharedContext) + const created = await this.inviteService_.create(toCreate, sharedContext) + + const updates = created.map((invite) => { + return { + id: invite.id, + expires_at: new Date().setMilliseconds( + new Date().getMilliseconds() + this.config.expiresIn + ), + token: this.generateToken({ id: invite.id }), + } + }) + + return await this.inviteService_.update(updates, sharedContext) } // @ts-ignore @@ -307,4 +371,12 @@ export default class UserModuleService< return Array.isArray(data) ? serializedInvites : serializedInvites[0] } + + private generateToken(data: any): string { + const jwtSecret: string = this.moduleDeclaration["jwt_secret"] + return jwt.sign(data, jwtSecret, { + jwtid: crypto.randomUUID(), + expiresIn: this.config.expiresIn, + }) + } } diff --git a/packages/modules/workflow-engine-inmemory/integration-tests/__tests__/index.spec.ts b/packages/modules/workflow-engine-inmemory/integration-tests/__tests__/index.spec.ts index 5646a4fdcf..51f9d8d9bd 100644 --- a/packages/modules/workflow-engine-inmemory/integration-tests/__tests__/index.spec.ts +++ b/packages/modules/workflow-engine-inmemory/integration-tests/__tests__/index.spec.ts @@ -1,12 +1,7 @@ -import { MedusaApp } from "@medusajs/modules-sdk" +import { Modules, RemoteQueryFunction } from "@medusajs/modules-sdk" import { WorkflowManager } from "@medusajs/orchestration" -import { - Context, - IWorkflowEngineService, - RemoteJoinerQuery, -} from "@medusajs/types" +import { Context, IWorkflowEngineService } from "@medusajs/types" import { TransactionHandlerType } from "@medusajs/utils" -import { knex } from "knex" import { setTimeout as setTimeoutPromise } from "timers/promises" import "../__fixtures__" import { workflow2Step2Invoke, workflow2Step3Invoke } from "../__fixtures__" @@ -16,316 +11,284 @@ import { workflowEventGroupIdStep2Mock, } from "../__fixtures__/workflow_event_group_id" import { createScheduled } from "../__fixtures__/workflow_scheduled" -import { DB_URL, TestDatabase } from "../utils" - -const sharedPgConnection = knex({ - client: "pg", - searchPath: process.env.MEDUSA_WORKFLOW_ENGINE_DB_SCHEMA, - connection: { - connectionString: DB_URL, - debug: false, - }, -}) - -const afterEach_ = async () => { - await TestDatabase.clearTables(sharedPgConnection) -} +import { moduleIntegrationTestRunner } from "medusa-test-utils" jest.setTimeout(100000) -describe("Workflow Orchestrator module", function () { - let workflowOrcModule: IWorkflowEngineService - let query: ( - query: string | RemoteJoinerQuery | object, - variables?: Record - ) => Promise +moduleIntegrationTestRunner({ + moduleName: Modules.WORKFLOW_ENGINE, + resolve: __dirname + "/../..", + testSuite: ({ service: workflowOrcModule, medusaApp }) => { + describe("Workflow Orchestrator module", function () { + let query: RemoteQueryFunction - afterEach(afterEach_) - - beforeAll(async () => { - const { - runMigrations, - query: remoteQuery, - modules, - } = await MedusaApp({ - sharedResourcesConfig: { - database: { - connection: sharedPgConnection, - }, - }, - modulesConfig: { - workflows: { - resolve: __dirname + "/../..", - }, - }, - }) - - query = remoteQuery - - await runMigrations() - - workflowOrcModule = modules.workflows as unknown as IWorkflowEngineService - }) - - it("should execute an async workflow keeping track of the event group id provided in the context", async () => { - const eventGroupId = "event-group-id" - - await workflowOrcModule.run(eventGroupWorkflowId, { - input: {}, - context: { - eventGroupId, - transactionId: "transaction_id", - }, - throwOnError: true, - }) - - await workflowOrcModule.setStepSuccess({ - idempotencyKey: { - action: TransactionHandlerType.INVOKE, - stepId: "step_1_event_group_id_background", - workflowId: eventGroupWorkflowId, - transactionId: "transaction_id", - }, - stepResponse: { hey: "oh" }, - }) - - // Validate context event group id - expect(workflowEventGroupIdStep1Mock.mock.calls[0][1]).toEqual( - expect.objectContaining({ eventGroupId }) - ) - expect(workflowEventGroupIdStep2Mock.mock.calls[0][1]).toEqual( - expect.objectContaining({ eventGroupId }) - ) - }) - - it("should execute an async workflow keeping track of the event group id that has been auto generated", async () => { - await workflowOrcModule.run(eventGroupWorkflowId, { - input: {}, - context: { - transactionId: "transaction_id_2", - }, - throwOnError: true, - }) - - await workflowOrcModule.setStepSuccess({ - idempotencyKey: { - action: TransactionHandlerType.INVOKE, - stepId: "step_1_event_group_id_background", - workflowId: eventGroupWorkflowId, - transactionId: "transaction_id_2", - }, - stepResponse: { hey: "oh" }, - }) - - const generatedEventGroupId = (workflowEventGroupIdStep1Mock.mock - .calls[0][1] as unknown as Context)!.eventGroupId - - // Validate context event group id - expect(workflowEventGroupIdStep1Mock.mock.calls[0][1]).toEqual( - expect.objectContaining({ eventGroupId: generatedEventGroupId }) - ) - expect(workflowEventGroupIdStep2Mock.mock.calls[0][1]).toEqual( - expect.objectContaining({ eventGroupId: generatedEventGroupId }) - ) - }) - - describe("Testing basic workflow", function () { - it("should return a list of workflow executions and remove after completed when there is no retentionTime set", async () => { - await workflowOrcModule.run("workflow_1", { - input: { - value: "123", - }, - throwOnError: true, + beforeEach(() => { + query = medusaApp.query }) - let executionsList = await query({ - workflow_executions: { - fields: ["workflow_id", "transaction_id", "state"], - }, - }) + it("should execute an async workflow keeping track of the event group id provided in the context", async () => { + const eventGroupId = "event-group-id" - expect(executionsList).toHaveLength(1) - - const { result } = await workflowOrcModule.setStepSuccess({ - idempotencyKey: { - action: TransactionHandlerType.INVOKE, - stepId: "new_step_name", - workflowId: "workflow_1", - transactionId: executionsList[0].transaction_id, - }, - stepResponse: { uhuuuu: "yeaah!" }, - }) - - executionsList = await query({ - workflow_executions: { - fields: ["id"], - }, - }) - - expect(executionsList).toHaveLength(0) - expect(result).toEqual({ - done: { - inputFromSyncStep: "oh", - }, - }) - }) - - it("should return a list of workflow executions and keep it saved when there is a retentionTime set", async () => { - await workflowOrcModule.run("workflow_2", { - input: { - value: "123", - }, - throwOnError: true, - transactionId: "transaction_1", - }) - - let executionsList = await query({ - workflow_executions: { - fields: ["id"], - }, - }) - - expect(executionsList).toHaveLength(1) - - await workflowOrcModule.setStepSuccess({ - idempotencyKey: { - action: TransactionHandlerType.INVOKE, - stepId: "new_step_name", - workflowId: "workflow_2", - transactionId: "transaction_1", - }, - stepResponse: { uhuuuu: "yeaah!" }, - }) - - expect(workflow2Step2Invoke).toBeCalledTimes(2) - expect(workflow2Step2Invoke.mock.calls[0][0]).toEqual({ hey: "oh" }) - expect(workflow2Step2Invoke.mock.calls[1][0]).toEqual({ - hey: "async hello", - }) - - expect(workflow2Step3Invoke).toBeCalledTimes(1) - expect(workflow2Step3Invoke.mock.calls[0][0]).toEqual({ - uhuuuu: "yeaah!", - }) - - executionsList = await query({ - workflow_executions: { - fields: ["id"], - }, - }) - - expect(executionsList).toHaveLength(1) - }) - - it("should revert the entire transaction when a step timeout expires", async () => { - const { transaction } = await workflowOrcModule.run( - "workflow_step_timeout", - { + await workflowOrcModule.run(eventGroupWorkflowId, { input: {}, - throwOnError: false, - } - ) + context: { + eventGroupId, + transactionId: "transaction_id", + }, + throwOnError: true, + }) - expect(transaction.flow.state).toEqual("reverted") - }) + await workflowOrcModule.setStepSuccess({ + idempotencyKey: { + action: TransactionHandlerType.INVOKE, + stepId: "step_1_event_group_id_background", + workflowId: eventGroupWorkflowId, + transactionId: "transaction_id", + }, + stepResponse: { hey: "oh" }, + }) - it("should revert the entire transaction when the transaction timeout expires", async () => { - const { transaction } = await workflowOrcModule.run( - "workflow_transaction_timeout", - { + // Validate context event group id + expect(workflowEventGroupIdStep1Mock.mock.calls[0][1]).toEqual( + expect.objectContaining({ eventGroupId }) + ) + expect(workflowEventGroupIdStep2Mock.mock.calls[0][1]).toEqual( + expect.objectContaining({ eventGroupId }) + ) + }) + + it("should execute an async workflow keeping track of the event group id that has been auto generated", async () => { + await workflowOrcModule.run(eventGroupWorkflowId, { input: {}, - throwOnError: false, - } - ) + context: { + transactionId: "transaction_id_2", + }, + throwOnError: true, + }) - await setTimeoutPromise(200) + await workflowOrcModule.setStepSuccess({ + idempotencyKey: { + action: TransactionHandlerType.INVOKE, + stepId: "step_1_event_group_id_background", + workflowId: eventGroupWorkflowId, + transactionId: "transaction_id_2", + }, + stepResponse: { hey: "oh" }, + }) - expect(transaction.flow.state).toEqual("reverted") - }) + const generatedEventGroupId = (workflowEventGroupIdStep1Mock.mock + .calls[0][1] as unknown as Context)!.eventGroupId - it("should subscribe to a async workflow and receive the response when it finishes", (done) => { - const transactionId = "trx_123" - - const onFinish = jest.fn(() => { - done() + // Validate context event group id + expect(workflowEventGroupIdStep1Mock.mock.calls[0][1]).toEqual( + expect.objectContaining({ eventGroupId: generatedEventGroupId }) + ) + expect(workflowEventGroupIdStep2Mock.mock.calls[0][1]).toEqual( + expect.objectContaining({ eventGroupId: generatedEventGroupId }) + ) }) - void workflowOrcModule.subscribe({ - workflowId: "workflow_async_background", - transactionId, - subscriber: (event) => { - if (event.eventType === "onFinish") { - onFinish() - } - }, + describe("Testing basic workflow", function () { + it("should return a list of workflow executions and remove after completed when there is no retentionTime set", async () => { + await workflowOrcModule.run("workflow_1", { + input: { + value: "123", + }, + throwOnError: true, + }) + + let executionsList = await query({ + workflow_executions: { + fields: ["workflow_id", "transaction_id", "state"], + }, + }) + + expect(executionsList).toHaveLength(1) + + const { result } = await workflowOrcModule.setStepSuccess({ + idempotencyKey: { + action: TransactionHandlerType.INVOKE, + stepId: "new_step_name", + workflowId: "workflow_1", + transactionId: executionsList[0].transaction_id, + }, + stepResponse: { uhuuuu: "yeaah!" }, + }) + + executionsList = await query({ + workflow_executions: { + fields: ["id"], + }, + }) + + expect(executionsList).toHaveLength(0) + expect(result).toEqual({ + done: { + inputFromSyncStep: "oh", + }, + }) + }) + + it("should return a list of workflow executions and keep it saved when there is a retentionTime set", async () => { + await workflowOrcModule.run("workflow_2", { + input: { + value: "123", + }, + throwOnError: true, + transactionId: "transaction_1", + }) + + let executionsList = await query({ + workflow_executions: { + fields: ["id"], + }, + }) + + expect(executionsList).toHaveLength(1) + + await workflowOrcModule.setStepSuccess({ + idempotencyKey: { + action: TransactionHandlerType.INVOKE, + stepId: "new_step_name", + workflowId: "workflow_2", + transactionId: "transaction_1", + }, + stepResponse: { uhuuuu: "yeaah!" }, + }) + + expect(workflow2Step2Invoke).toBeCalledTimes(2) + expect(workflow2Step2Invoke.mock.calls[0][0]).toEqual({ hey: "oh" }) + expect(workflow2Step2Invoke.mock.calls[1][0]).toEqual({ + hey: "async hello", + }) + + expect(workflow2Step3Invoke).toBeCalledTimes(1) + expect(workflow2Step3Invoke.mock.calls[0][0]).toEqual({ + uhuuuu: "yeaah!", + }) + + executionsList = await query({ + workflow_executions: { + fields: ["id"], + }, + }) + + expect(executionsList).toHaveLength(1) + }) + + it("should revert the entire transaction when a step timeout expires", async () => { + const { transaction } = await workflowOrcModule.run( + "workflow_step_timeout", + { + input: {}, + throwOnError: false, + } + ) + + expect(transaction.flow.state).toEqual("reverted") + }) + + it("should revert the entire transaction when the transaction timeout expires", async () => { + const { transaction } = await workflowOrcModule.run( + "workflow_transaction_timeout", + { + input: {}, + throwOnError: false, + } + ) + + await setTimeoutPromise(200) + + expect(transaction.flow.state).toEqual("reverted") + }) + + it("should subscribe to a async workflow and receive the response when it finishes", (done) => { + const transactionId = "trx_123" + + const onFinish = jest.fn(() => { + done() + }) + + void workflowOrcModule.subscribe({ + workflowId: "workflow_async_background", + transactionId, + subscriber: (event) => { + if (event.eventType === "onFinish") { + onFinish() + } + }, + }) + + void workflowOrcModule.run("workflow_async_background", { + input: { + myInput: "123", + }, + transactionId, + throwOnError: false, + }) + + expect(onFinish).toHaveBeenCalledTimes(0) + }) }) - void workflowOrcModule.run("workflow_async_background", { - input: { - myInput: "123", - }, - transactionId, - throwOnError: false, + describe("Scheduled workflows", () => { + beforeAll(() => { + jest.useFakeTimers() + jest.spyOn(global, "setTimeout") + }) + + afterAll(() => { + jest.useRealTimers() + }) + + it("should execute a scheduled workflow", async () => { + const spy = createScheduled("standard") + + jest.clearAllMocks() + + await jest.runOnlyPendingTimersAsync() + expect(setTimeout).toHaveBeenCalledTimes(2) + expect(spy).toHaveBeenCalledTimes(1) + + await jest.runOnlyPendingTimersAsync() + expect(setTimeout).toHaveBeenCalledTimes(3) + expect(spy).toHaveBeenCalledTimes(2) + }) + + it("should stop executions after the set number of executions", async () => { + const spy = await createScheduled("num-executions", { + cron: "* * * * * *", + numberOfExecutions: 2, + }) + + await jest.runOnlyPendingTimersAsync() + expect(spy).toHaveBeenCalledTimes(1) + + await jest.runOnlyPendingTimersAsync() + expect(spy).toHaveBeenCalledTimes(2) + + await jest.runOnlyPendingTimersAsync() + expect(spy).toHaveBeenCalledTimes(2) + }) + + it("should remove scheduled workflow if workflow no longer exists", async () => { + const spy = await createScheduled("remove-scheduled", { + cron: "* * * * * *", + }) + const logSpy = jest.spyOn(console, "warn") + + await jest.runOnlyPendingTimersAsync() + expect(spy).toHaveBeenCalledTimes(1) + + WorkflowManager["workflows"].delete("remove-scheduled") + + await jest.runOnlyPendingTimersAsync() + expect(spy).toHaveBeenCalledTimes(1) + expect(logSpy).toHaveBeenCalledWith( + "Tried to execute a scheduled workflow with ID remove-scheduled that does not exist, removing it from the scheduler." + ) + }) }) - - expect(onFinish).toHaveBeenCalledTimes(0) }) - }) - - describe("Scheduled workflows", () => { - beforeAll(() => { - jest.useFakeTimers() - jest.spyOn(global, "setTimeout") - }) - - afterAll(() => { - jest.useRealTimers() - }) - - it("should execute a scheduled workflow", async () => { - const spy = createScheduled("standard") - - await jest.runOnlyPendingTimersAsync() - expect(setTimeout).toHaveBeenCalledTimes(2) - expect(spy).toHaveBeenCalledTimes(1) - - await jest.runOnlyPendingTimersAsync() - expect(setTimeout).toHaveBeenCalledTimes(3) - expect(spy).toHaveBeenCalledTimes(2) - }) - - it("should stop executions after the set number of executions", async () => { - const spy = await createScheduled("num-executions", { - cron: "* * * * * *", - numberOfExecutions: 2, - }) - - await jest.runOnlyPendingTimersAsync() - expect(spy).toHaveBeenCalledTimes(1) - - await jest.runOnlyPendingTimersAsync() - expect(spy).toHaveBeenCalledTimes(2) - - await jest.runOnlyPendingTimersAsync() - expect(spy).toHaveBeenCalledTimes(2) - }) - - it("should remove scheduled workflow if workflow no longer exists", async () => { - const spy = await createScheduled("remove-scheduled", { - cron: "* * * * * *", - }) - const logSpy = jest.spyOn(console, "warn") - - await jest.runOnlyPendingTimersAsync() - expect(spy).toHaveBeenCalledTimes(1) - - WorkflowManager["workflows"].delete("remove-scheduled") - - await jest.runOnlyPendingTimersAsync() - expect(spy).toHaveBeenCalledTimes(1) - expect(logSpy).toHaveBeenCalledWith( - "Tried to execute a scheduled workflow with ID remove-scheduled that does not exist, removing it from the scheduler." - ) - }) - }) + }, }) diff --git a/packages/modules/workflow-engine-inmemory/integration-tests/setup-env.js b/packages/modules/workflow-engine-inmemory/integration-tests/setup-env.js deleted file mode 100644 index 7de2d9de24..0000000000 --- a/packages/modules/workflow-engine-inmemory/integration-tests/setup-env.js +++ /dev/null @@ -1,6 +0,0 @@ -if (typeof process.env.DB_TEMP_NAME === "undefined") { - const tempName = parseInt(process.env.JEST_WORKER_ID || "1") - process.env.DB_TEMP_NAME = `medusa-workflow-engine-inmemory-${tempName}` -} - -process.env.MEDUSA_WORKFLOW_ENGINE_DB_SCHEMA = "public" diff --git a/packages/modules/workflow-engine-inmemory/integration-tests/setup.js b/packages/modules/workflow-engine-inmemory/integration-tests/setup.js deleted file mode 100644 index 43f99aab4a..0000000000 --- a/packages/modules/workflow-engine-inmemory/integration-tests/setup.js +++ /dev/null @@ -1,3 +0,0 @@ -import { JestUtils } from "medusa-test-utils" - -JestUtils.afterAllHookDropDatabase() diff --git a/packages/modules/workflow-engine-inmemory/integration-tests/utils/database.ts b/packages/modules/workflow-engine-inmemory/integration-tests/utils/database.ts deleted file mode 100644 index ed61b5e489..0000000000 --- a/packages/modules/workflow-engine-inmemory/integration-tests/utils/database.ts +++ /dev/null @@ -1,22 +0,0 @@ -import * as process from "process" - -const DB_HOST = process.env.DB_HOST ?? "localhost" -const DB_USERNAME = process.env.DB_USERNAME ?? "" -const DB_PASSWORD = process.env.DB_PASSWORD -const DB_NAME = process.env.DB_TEMP_NAME - -export const DB_URL = `postgres://${DB_USERNAME}${ - DB_PASSWORD ? `:${DB_PASSWORD}` : "" -}@${DB_HOST}/${DB_NAME}` - -interface TestDatabase { - clearTables(knex): Promise -} - -export const TestDatabase: TestDatabase = { - clearTables: async (knex) => { - await knex.raw(` - TRUNCATE TABLE workflow_execution CASCADE; - `) - }, -} diff --git a/packages/modules/workflow-engine-inmemory/integration-tests/utils/index.ts b/packages/modules/workflow-engine-inmemory/integration-tests/utils/index.ts deleted file mode 100644 index 6b917ed30e..0000000000 --- a/packages/modules/workflow-engine-inmemory/integration-tests/utils/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./database" diff --git a/packages/modules/workflow-engine-inmemory/jest.config.js b/packages/modules/workflow-engine-inmemory/jest.config.js index dce2002dae..0c652264ea 100644 --- a/packages/modules/workflow-engine-inmemory/jest.config.js +++ b/packages/modules/workflow-engine-inmemory/jest.config.js @@ -17,6 +17,4 @@ module.exports = { testEnvironment: `node`, moduleFileExtensions: [`js`, `ts`], modulePathIgnorePatterns: ["dist/"], - setupFiles: ["/integration-tests/setup-env.js"], - setupFilesAfterEnv: ["/integration-tests/setup.js"], } diff --git a/packages/modules/workflow-engine-inmemory/package.json b/packages/modules/workflow-engine-inmemory/package.json index 575b37ebe1..a41714667f 100644 --- a/packages/modules/workflow-engine-inmemory/package.json +++ b/packages/modules/workflow-engine-inmemory/package.json @@ -8,7 +8,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/workflow-engine-inmemory/src/joiner-config.ts b/packages/modules/workflow-engine-inmemory/src/joiner-config.ts index 7999e9c3ab..6c66786707 100644 --- a/packages/modules/workflow-engine-inmemory/src/joiner-config.ts +++ b/packages/modules/workflow-engine-inmemory/src/joiner-config.ts @@ -1,34 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import { WorkflowExecution } from "@models" -import moduleSchema from "./schema" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys = { - workflow_execution_id: WorkflowExecution.name, -} +export const joinerConfig = defineJoinerConfig(Modules.WORKFLOW_ENGINE) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.WORKFLOW_ENGINE, - primaryKeys: ["id"], - schema: moduleSchema, - linkableKeys: LinkableKeys, - alias: { - name: ["workflow_execution", "workflow_executions"], - args: { - entity: WorkflowExecution.name, - methodSuffix: "WorkflowExecution", - }, - }, -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/workflow-engine-inmemory/src/repositories/index.ts b/packages/modules/workflow-engine-inmemory/src/repositories/index.ts deleted file mode 100644 index 8def202608..0000000000 --- a/packages/modules/workflow-engine-inmemory/src/repositories/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" -export { WorkflowExecutionRepository } from "./workflow-execution" diff --git a/packages/modules/workflow-engine-inmemory/src/repositories/workflow-execution.ts b/packages/modules/workflow-engine-inmemory/src/repositories/workflow-execution.ts deleted file mode 100644 index 9e6553ec74..0000000000 --- a/packages/modules/workflow-engine-inmemory/src/repositories/workflow-execution.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { DALUtils } from "@medusajs/utils" -import { WorkflowExecution } from "@models" - -// eslint-disable-next-line max-len -export class WorkflowExecutionRepository extends DALUtils.mikroOrmBaseRepositoryFactory( - WorkflowExecution -) {} diff --git a/packages/modules/workflow-engine-inmemory/src/services/workflows-module.ts b/packages/modules/workflow-engine-inmemory/src/services/workflows-module.ts index 77a82257d6..8d21beea33 100644 --- a/packages/modules/workflow-engine-inmemory/src/services/workflows-module.ts +++ b/packages/modules/workflow-engine-inmemory/src/services/workflows-module.ts @@ -2,8 +2,8 @@ import { Context, DAL, FindConfig, - IWorkflowEngineService, InternalModuleDeclaration, + IWorkflowEngineService, ModuleJoinerConfig, ModulesSdkTypes, WorkflowsSdkTypes, @@ -93,7 +93,7 @@ export class WorkflowsModuleService implements IWorkflowEngineService { } @InjectManager("baseRepository_") - async listWorkflowExecution( + async listWorkflowExecutions( filters: WorkflowsSdkTypes.FilterableWorkflowExecutionProps = {}, config: FindConfig = {}, @MedusaContext() sharedContext: Context = {} @@ -128,7 +128,7 @@ export class WorkflowsModuleService implements IWorkflowEngineService { } @InjectManager("baseRepository_") - async listAndCountWorkflowExecution( + async listAndCountWorkflowExecutions( filters: WorkflowsSdkTypes.FilterableWorkflowExecutionProps = {}, config: FindConfig = {}, @MedusaContext() sharedContext: Context = {} diff --git a/packages/modules/workflow-engine-redis/package.json b/packages/modules/workflow-engine-redis/package.json index 1c9744c815..7f7da04b0d 100644 --- a/packages/modules/workflow-engine-redis/package.json +++ b/packages/modules/workflow-engine-redis/package.json @@ -8,7 +8,7 @@ "dist" ], "engines": { - "node": ">=16" + "node": ">=20" }, "repository": { "type": "git", diff --git a/packages/modules/workflow-engine-redis/src/joiner-config.ts b/packages/modules/workflow-engine-redis/src/joiner-config.ts index 7999e9c3ab..6c66786707 100644 --- a/packages/modules/workflow-engine-redis/src/joiner-config.ts +++ b/packages/modules/workflow-engine-redis/src/joiner-config.ts @@ -1,34 +1,11 @@ import { Modules } from "@medusajs/modules-sdk" -import { ModuleJoinerConfig } from "@medusajs/types" -import { MapToConfig } from "@medusajs/utils" -import { WorkflowExecution } from "@models" -import moduleSchema from "./schema" +import { + buildEntitiesNameToLinkableKeysMap, + defineJoinerConfig, + MapToConfig, +} from "@medusajs/utils" -export const LinkableKeys = { - workflow_execution_id: WorkflowExecution.name, -} +export const joinerConfig = defineJoinerConfig(Modules.WORKFLOW_ENGINE) -const entityLinkableKeysMap: MapToConfig = {} -Object.entries(LinkableKeys).forEach(([key, value]) => { - entityLinkableKeysMap[value] ??= [] - entityLinkableKeysMap[value].push({ - mapTo: key, - valueFrom: key.split("_").pop()!, - }) -}) - -export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap - -export const joinerConfig: ModuleJoinerConfig = { - serviceName: Modules.WORKFLOW_ENGINE, - primaryKeys: ["id"], - schema: moduleSchema, - linkableKeys: LinkableKeys, - alias: { - name: ["workflow_execution", "workflow_executions"], - args: { - entity: WorkflowExecution.name, - methodSuffix: "WorkflowExecution", - }, - }, -} +export const entityNameToLinkableKeysMap: MapToConfig = + buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys) diff --git a/packages/modules/workflow-engine-redis/src/repositories/index.ts b/packages/modules/workflow-engine-redis/src/repositories/index.ts deleted file mode 100644 index 8def202608..0000000000 --- a/packages/modules/workflow-engine-redis/src/repositories/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" -export { WorkflowExecutionRepository } from "./workflow-execution" diff --git a/packages/modules/workflow-engine-redis/src/repositories/workflow-execution.ts b/packages/modules/workflow-engine-redis/src/repositories/workflow-execution.ts deleted file mode 100644 index 9e6553ec74..0000000000 --- a/packages/modules/workflow-engine-redis/src/repositories/workflow-execution.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { DALUtils } from "@medusajs/utils" -import { WorkflowExecution } from "@models" - -// eslint-disable-next-line max-len -export class WorkflowExecutionRepository extends DALUtils.mikroOrmBaseRepositoryFactory( - WorkflowExecution -) {} diff --git a/packages/modules/workflow-engine-redis/src/services/workflows-module.ts b/packages/modules/workflow-engine-redis/src/services/workflows-module.ts index 3f6758a95b..ddd3d951be 100644 --- a/packages/modules/workflow-engine-redis/src/services/workflows-module.ts +++ b/packages/modules/workflow-engine-redis/src/services/workflows-module.ts @@ -2,8 +2,8 @@ import { Context, DAL, FindConfig, - IWorkflowEngineService, InternalModuleDeclaration, + IWorkflowEngineService, ModuleJoinerConfig, ModulesSdkTypes, WorkflowsSdkTypes, @@ -11,9 +11,9 @@ import { import { InjectManager, InjectSharedContext, + isString, MedusaContext, MedusaError, - isString, } from "@medusajs/utils" import type { ReturnWorkflow, @@ -107,7 +107,7 @@ export class WorkflowsModuleService implements IWorkflowEngineService { } @InjectManager("baseRepository_") - async listWorkflowExecution( + async listWorkflowExecutions( filters: WorkflowsSdkTypes.FilterableWorkflowExecutionProps = {}, config: FindConfig = {}, @MedusaContext() sharedContext: Context = {} @@ -142,7 +142,7 @@ export class WorkflowsModuleService implements IWorkflowEngineService { } @InjectManager("baseRepository_") - async listAndCountWorkflowExecution( + async listAndCountWorkflowExecutions( filters: WorkflowsSdkTypes.FilterableWorkflowExecutionProps = {}, config: FindConfig = {}, @MedusaContext() sharedContext: Context = {} diff --git a/www/apps/resources/app/commerce-modules/fulfillment/concepts/page.mdx b/www/apps/resources/app/commerce-modules/fulfillment/concepts/page.mdx index 39ef9c1799..2b5d15c6a3 100644 --- a/www/apps/resources/app/commerce-modules/fulfillment/concepts/page.mdx +++ b/www/apps/resources/app/commerce-modules/fulfillment/concepts/page.mdx @@ -13,7 +13,7 @@ A fulfillment set is a general form or way of fulfillment. For example, shipping A fulfillment set is represented by the [FulfillmentSet data model](/references/fulfillment/models/FulfillmentSet). All other configurations, options, and management features are related to a fulfillment set, in one way or another. ```ts -const fulfillmentSets = await fulfillmentModuleService.create( +const fulfillmentSets = await fulfillmentModuleService.createFulfillmentSets( [ { name: "Shipping", diff --git a/www/apps/resources/app/commerce-modules/fulfillment/page.mdx b/www/apps/resources/app/commerce-modules/fulfillment/page.mdx index 89cb3f818c..d5e9a60ae2 100644 --- a/www/apps/resources/app/commerce-modules/fulfillment/page.mdx +++ b/www/apps/resources/app/commerce-modules/fulfillment/page.mdx @@ -88,7 +88,7 @@ const shippingOption = Support various fulfillment forms, such as shipping or pick up. ```ts -const fulfillmentSets = await fulfillmentModuleService.create( +const fulfillmentSets = await fulfillmentModuleService.createFulfillmentSets( [ { name: "Shipping", diff --git a/www/apps/resources/references/fulfillment/IFulfillmentModuleService/methods/fulfillment.IFulfillmentModuleService.create/page.mdx b/www/apps/resources/references/fulfillment/IFulfillmentModuleService/methods/fulfillment.IFulfillmentModuleService.create/page.mdx index 339ee3627d..9db10b630a 100644 --- a/www/apps/resources/references/fulfillment/IFulfillmentModuleService/methods/fulfillment.IFulfillmentModuleService.create/page.mdx +++ b/www/apps/resources/references/fulfillment/IFulfillmentModuleService/methods/fulfillment.IFulfillmentModuleService.create/page.mdx @@ -17,7 +17,7 @@ This method creates fulfillment sets. ### Example ```ts -const fulfillmentSets = await fulfillmentModuleService.create( +const fulfillmentSets = await fulfillmentModuleService.createFulfillmentSets( [ { name: "Shipping", @@ -46,7 +46,7 @@ This method creates a fulfillment set. ### Example ```ts -const fulfillmentSet = await fulfillmentModuleService.create({ +const fulfillmentSet = await fulfillmentModuleService.createFulfillmentSets({ name: "Shipping", type: "default", }) diff --git a/yarn.lock b/yarn.lock index e3630c709b..d896ceb221 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4244,8 +4244,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-api-key-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -4304,8 +4302,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-auth-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -4361,8 +4357,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-cart-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -4407,8 +4401,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-currency-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -4434,8 +4426,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-customer-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -4622,8 +4612,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-fulfillment-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -4988,8 +4976,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-order-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5036,8 +5022,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-payment-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5063,8 +5047,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-pricing-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5093,8 +5075,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-product-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5120,8 +5100,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-promotion-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5147,8 +5125,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-region-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5174,8 +5150,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-sales-channel-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5226,8 +5200,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-store-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5253,8 +5225,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-tax-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft @@ -5414,8 +5384,6 @@ __metadata: ts-node: ^10.9.1 tsc-alias: ^1.8.6 typescript: ^5.1.6 - bin: - medusa-user-seed: dist/scripts/bin/run-seed.js languageName: unknown linkType: soft