feat(medusa, link-modules): sales channel <> cart link (#5459)
* feat: sales channel joiner config * feat: product sales channel link config, SC list method * feat: migration * fix: refactor list SC * refactor: SC repo api * chore: changeset * feat: add dedicated FF * wip: cart<>sc link and migration * chore: changeset * fix: update migration with the cart table constraints * feat: populate the pivot table * chore: remove relation from joiner config * fix: constraint name * fix: filter out link relations when calling internal services * feat: product<> sc join entity * fix: update case * fix: add FF on in the repository, fix tests * fix: assign id when FF is on * fix: target table * feat: product service - fetch SC with RQ * feat: admin list products & SC with isolated product domain * feat: get admin product * feat: store endpoints * fix: remove duplicate import * fix: remove "name" prop * feat: typeorm entity changes * feat: pivot table, entity, on cart create changes * feat: update carts' SC * feat: cart - getValidatedSalesChannel with RQ * feat: refactor * wip: changes to create cart workflow * fix: remove join table entity due to migrations failing * fix: product seeder if FF is on * feat: attach SC handler and test * fix: env * feat: workflow compensation, cart service retrieve with RQ * fix: remote joiner implode map * chore: update changesets * fix: remove methods from SC service/repo * feat: use remote link in handlers * fix: remove SC service calls * fix: link params * fix: migration add constraint to make link upsert pass * refactor: workflow product handlers to handle remote links * fix: condition * fix: use correct method * fix: build * wip: update FF * fix: update FF in the handlers * chore: migrate to medusav2 FF * chore: uncomment test * fix: product factory * fix: unlinking SC and product * fix: use module name variable * refactor: cleanup query definitions * fix: add constraint * wip: migrate FF * fix: comments * feat: cart entity callbacks, fix tests * fix: only create SC in test * wip: services updates, changes to models * chore: rename prop * fix: add hook * fix: address comments * fix: temp sc filtering * fix: use RQ to filter by SC * fix: relations on retrieve * feat: migration sync data, remove FF * fix: revert order of queries * fix: alter migration, relations in service * fix: revert id * fix: migrations * fix: make expand work * fix: remote link method call * fix: try making tests work without id in the pivot table * test: use remote link * test: relations changes * fix: preserve channel id column * fix: seeder and factory * fix: remove sales_channels from response * feat: support feature flag arrays * fix: cover everything with correct FF * fix: remove verbose * fix: unit and plugin tests * chore: comments * fix: reenable workflow handler, add comments, split cart create workflow tests * chore: reenable link in the create mehod, update changesets * fix: address feedback * fix: revert migration * fix: change the migration to follow link module * fix: migration syntax * fix: merge conflicts * fix: typo * feat: remove store sales channel foreign key * fix: merge migrations * fix: FF keys * refactor: cart service * refactor: FF missing key * fix: comments * fix: address PR comments * fix: new changesets * fix: revert flag router changes * chore: refactor `isFeatureEnabled` --------- Co-authored-by: Carlos R. L. Rodrigues <rodrigolr@gmail.com> Co-authored-by: Riqwan Thamir <rmthamir@gmail.com>
This commit is contained in:
28 files changed
+662
-89
No files matched your search
@@ -16,6 +16,7 @@ import { StorePostCartsCartShippingMethodReq } from "./add-shipping-method"
|
||||
import { StorePostCartsCartPaymentSessionReq } from "./set-payment-session"
|
||||
import { StorePostCartsCartLineItemsItemReq } from "./update-line-item"
|
||||
import { StorePostCartsCartPaymentSessionUpdateReq } from "./update-payment-session"
|
||||
import { MedusaV2Flag } from "@medusajs/utils"
|
||||
|
||||
const route = Router()
|
||||
|
||||
@@ -26,7 +27,11 @@ export default (app, container) => {
|
||||
app.use("/carts", route)
|
||||
|
||||
if (featureFlagRouter.isFeatureEnabled(SalesChannelFeatureFlag.key)) {
|
||||
defaultStoreCartRelations.push("sales_channel")
|
||||
if (featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
|
||||
defaultStoreCartRelations.push("sales_channels")
|
||||
} else {
|
||||
defaultStoreCartRelations.push("sales_channel")
|
||||
}
|
||||
}
|
||||
|
||||
// Inject plugin routes
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { ModuleJoinerConfig } from "@medusajs/types"
|
||||
|
||||
import { Cart } from "../models"
|
||||
|
||||
export default {
|
||||
serviceName: "cartService",
|
||||
primaryKeys: ["id"],
|
||||
linkableKeys: { cart_id: "Cart" },
|
||||
alias: [
|
||||
{
|
||||
name: "cart",
|
||||
},
|
||||
],
|
||||
alias: {
|
||||
name: ["cart", "carts"],
|
||||
args: { entity: Cart.name },
|
||||
},
|
||||
relationships: [
|
||||
{
|
||||
serviceName: Modules.PRODUCT,
|
||||
|
||||
@@ -32,7 +32,7 @@ export class addTableProductShippingProfile1680857773273
|
||||
DROP INDEX IF EXISTS "idx_product_shipping_profile_product_id";
|
||||
DROP INDEX IF EXISTS "idx_product_shipping_profile_profile_id";
|
||||
|
||||
ALTER TABLE "product" ADD COLUMN IF NOT EXISTS "profile_id";
|
||||
ALTER TABLE "product" ADD COLUMN IF NOT EXISTS "profile_id" CHARACTER VARYING;
|
||||
|
||||
UPDATE "product" SET "profile_id" = "product_shipping_profile"."profile_id"
|
||||
FROM "product_shipping_profile"
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { MigrationInterface, QueryRunner } from "typeorm"
|
||||
import { MedusaV2Flag } from "@medusajs/utils"
|
||||
|
||||
import SalesChannelFeatureFlag from "../loaders/feature-flags/sales-channels"
|
||||
|
||||
export const featureFlag = [SalesChannelFeatureFlag.key, MedusaV2Flag.key]
|
||||
|
||||
export class CartSalesChannelsLink1698160215000 implements MigrationInterface {
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
CREATE TABLE IF NOT EXISTS "cart_sales_channel"
|
||||
(
|
||||
"id" character varying NOT NULL,
|
||||
"cart_id" character varying NOT NULL,
|
||||
"sales_channel_id" character varying NOT NULL,
|
||||
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
"deleted_at" TIMESTAMP WITH TIME ZONE,
|
||||
CONSTRAINT "cart_sales_channel_pk" PRIMARY KEY ("cart_id", "sales_channel_id"),
|
||||
CONSTRAINT "cart_sales_channel_cart_id_unique" UNIQUE ("cart_id")
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "IDX_id_cart_sales_channel" ON "cart_sales_channel" ("id");
|
||||
|
||||
insert into "cart_sales_channel" (id, cart_id, sales_channel_id)
|
||||
(select 'cartsc_' || substr(md5(random()::text), 0, 27), id, sales_channel_id from "cart" WHERE sales_channel_id IS NOT NULL);
|
||||
|
||||
ALTER TABLE IF EXISTS "cart" DROP CONSTRAINT IF EXISTS "FK_a2bd3c26f42e754b9249ba78fd6";
|
||||
|
||||
ALTER TABLE IF EXISTS "store" DROP CONSTRAINT IF EXISTS "FK_61b0f48cccbb5f41c750bac7286";
|
||||
`)
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
UPDATE "cart" SET "sales_channel_id" = "cart_sales_channel"."sales_channel_id"
|
||||
FROM "cart_sales_channel"
|
||||
WHERE "cart"."id" = "cart_sales_channel"."cart_id";
|
||||
|
||||
DROP TABLE IF EXISTS "cart_sales_channel";
|
||||
|
||||
ALTER TABLE IF EXISTS "cart" ADD CONSTRAINT "FK_a2bd3c26f42e754b9249ba78fd6" FOREIGN KEY ("sales_channel_id") REFERENCES "sales_channel"("id") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
|
||||
ALTER TABLE IF EXISTS "store" ADD CONSTRAINT "FK_61b0f48cccbb5f41c750bac7286" FOREIGN KEY ("default_sales_channel_id") REFERENCES "sales_channel"("id") ON DELETE NO ACTION ON UPDATE NO ACTION;
|
||||
`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { BeforeInsert, Column, Index, PrimaryColumn } from "typeorm"
|
||||
import { MedusaV2Flag, SalesChannelFeatureFlag } from "@medusajs/utils"
|
||||
|
||||
import { generateEntityId } from "../utils"
|
||||
import { SoftDeletableEntity } from "../interfaces"
|
||||
import { FeatureFlagEntity } from "../utils/feature-flag-decorators"
|
||||
|
||||
@FeatureFlagEntity([MedusaV2Flag.key, SalesChannelFeatureFlag.key])
|
||||
export class CartSalesChannel extends SoftDeletableEntity {
|
||||
@Column()
|
||||
id: string
|
||||
|
||||
@Index("cart_sales_channel_cart_id_unique", {
|
||||
unique: true,
|
||||
})
|
||||
@PrimaryColumn()
|
||||
cart_id: string
|
||||
|
||||
@PrimaryColumn()
|
||||
sales_channel_id: string
|
||||
|
||||
/**
|
||||
* @apiIgnore
|
||||
*/
|
||||
@BeforeInsert()
|
||||
private beforeInsert(): void {
|
||||
this.id = generateEntityId(this.id, "cartsc")
|
||||
}
|
||||
}
|
||||
@@ -233,6 +233,7 @@
|
||||
import {
|
||||
AfterLoad,
|
||||
BeforeInsert,
|
||||
BeforeUpdate,
|
||||
Column,
|
||||
Entity,
|
||||
Index,
|
||||
@@ -241,13 +242,10 @@ import {
|
||||
ManyToMany,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
OneToOne
|
||||
OneToOne,
|
||||
} from "typeorm"
|
||||
import { MedusaV2Flag, SalesChannelFeatureFlag } from "@medusajs/utils"
|
||||
import { DbAwareColumn, resolveDbType } from "../utils/db-aware-column"
|
||||
import {
|
||||
FeatureFlagColumn,
|
||||
FeatureFlagDecorators,
|
||||
} from "../utils/feature-flag-decorators"
|
||||
|
||||
import { SoftDeletableEntity } from "../interfaces/models/soft-deletable-entity"
|
||||
import { generateEntityId } from "../utils/generate-entity-id"
|
||||
@@ -261,6 +259,10 @@ import { PaymentSession } from "./payment-session"
|
||||
import { Region } from "./region"
|
||||
import { SalesChannel } from "./sales-channel"
|
||||
import { ShippingMethod } from "./shipping-method"
|
||||
import {
|
||||
FeatureFlagColumn,
|
||||
FeatureFlagDecorators,
|
||||
} from "../utils/feature-flag-decorators"
|
||||
|
||||
export enum CartType {
|
||||
DEFAULT = "default",
|
||||
@@ -387,15 +389,37 @@ export class Cart extends SoftDeletableEntity {
|
||||
@DbAwareColumn({ type: "jsonb", nullable: true })
|
||||
metadata: Record<string, unknown>
|
||||
|
||||
@FeatureFlagColumn("sales_channels", { type: "varchar", nullable: true })
|
||||
@FeatureFlagColumn(SalesChannelFeatureFlag.key, {
|
||||
type: "varchar",
|
||||
nullable: true,
|
||||
})
|
||||
sales_channel_id: string | null
|
||||
|
||||
@FeatureFlagDecorators("sales_channels", [
|
||||
@FeatureFlagDecorators(SalesChannelFeatureFlag.key, [
|
||||
ManyToOne(() => SalesChannel),
|
||||
JoinColumn({ name: "sales_channel_id" }),
|
||||
])
|
||||
sales_channel: SalesChannel
|
||||
|
||||
@FeatureFlagDecorators(
|
||||
[MedusaV2Flag.key, SalesChannelFeatureFlag.key],
|
||||
[
|
||||
ManyToMany(() => SalesChannel, { cascade: ["remove", "soft-remove"] }),
|
||||
JoinTable({
|
||||
name: "cart_sales_channel",
|
||||
joinColumn: {
|
||||
name: "cart_id",
|
||||
referencedColumnName: "id",
|
||||
},
|
||||
inverseJoinColumn: {
|
||||
name: "sales_channel_id",
|
||||
referencedColumnName: "id",
|
||||
},
|
||||
}),
|
||||
]
|
||||
)
|
||||
sales_channels?: SalesChannel[]
|
||||
|
||||
shipping_total?: number
|
||||
discount_total?: number
|
||||
raw_discount_total?: number
|
||||
@@ -412,18 +436,41 @@ export class Cart extends SoftDeletableEntity {
|
||||
/**
|
||||
* @apiIgnore
|
||||
*/
|
||||
@AfterLoad()
|
||||
private afterLoad(): void {
|
||||
if (this.payment_sessions) {
|
||||
this.payment_session = this.payment_sessions.find((p) => p.is_selected)!
|
||||
@BeforeInsert()
|
||||
private beforeInsert(): void {
|
||||
this.id = generateEntityId(this.id, "cart")
|
||||
|
||||
if (this.sales_channel_id || this.sales_channel) {
|
||||
this.sales_channels = [
|
||||
{ id: this.sales_channel_id || this.sales_channel?.id },
|
||||
] as SalesChannel[]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @apiIgnore
|
||||
*/
|
||||
@BeforeInsert()
|
||||
private beforeInsert(): void {
|
||||
this.id = generateEntityId(this.id, "cart")
|
||||
@BeforeUpdate()
|
||||
private beforeUpdate(): void {
|
||||
if (this.sales_channel_id || this.sales_channel) {
|
||||
this.sales_channels = [
|
||||
{ id: this.sales_channel_id || this.sales_channel?.id },
|
||||
] as SalesChannel[]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @apiIgnore
|
||||
*/
|
||||
@AfterLoad()
|
||||
private afterLoad(): void {
|
||||
if (this.payment_sessions) {
|
||||
this.payment_session = this.payment_sessions.find((p) => p.is_selected)!
|
||||
}
|
||||
if (this.sales_channels) {
|
||||
this.sales_channel = this.sales_channels?.[0]
|
||||
this.sales_channel_id = this.sales_channel?.id
|
||||
delete this.sales_channels
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
import { BeforeInsert, Column, JoinTable, ManyToMany, OneToMany } from "typeorm"
|
||||
|
||||
import { FeatureFlagEntity } from "../utils/feature-flag-decorators"
|
||||
import { MedusaV2Flag } from "@medusajs/utils"
|
||||
import {
|
||||
FeatureFlagDecorators,
|
||||
FeatureFlagEntity,
|
||||
} from "../utils/feature-flag-decorators"
|
||||
import { SoftDeletableEntity } from "../interfaces"
|
||||
import { DbAwareColumn, generateEntityId } from "../utils"
|
||||
import { SalesChannelLocation } from "./sales-channel-location"
|
||||
import { Product } from "./product"
|
||||
import { Cart } from "./cart"
|
||||
|
||||
@FeatureFlagEntity("sales_channels")
|
||||
export class SalesChannel extends SoftDeletableEntity {
|
||||
@@ -34,6 +39,22 @@ export class SalesChannel extends SoftDeletableEntity {
|
||||
})
|
||||
products: Product[]
|
||||
|
||||
@FeatureFlagDecorators(MedusaV2Flag.key, [
|
||||
ManyToMany(() => Cart),
|
||||
JoinTable({
|
||||
name: "cart_sales_channel",
|
||||
joinColumn: {
|
||||
name: "sales_channel_id",
|
||||
referencedColumnName: "id",
|
||||
},
|
||||
inverseJoinColumn: {
|
||||
name: "cart_id",
|
||||
referencedColumnName: "id",
|
||||
},
|
||||
}),
|
||||
])
|
||||
carts: Cart[]
|
||||
|
||||
@OneToMany(
|
||||
() => SalesChannelLocation,
|
||||
(scLocation) => scLocation.sales_channel,
|
||||
|
||||
@@ -2668,6 +2668,7 @@ describe("CartService", () => {
|
||||
.register("newTotalsService", asClass(NewTotalsService))
|
||||
.register("cartService", asClass(CartService))
|
||||
.register("remoteQuery", asValue(null))
|
||||
.register("remoteLink", asValue(null))
|
||||
.register("pricingModuleService", asValue(undefined))
|
||||
.register("pricingService", asClass(PricingService))
|
||||
|
||||
|
||||
@@ -68,6 +68,8 @@ import { PaymentSessionRepository } from "../repositories/payment-session"
|
||||
import { ShippingMethodRepository } from "../repositories/shipping-method"
|
||||
import { PaymentSessionInput } from "../types/payment"
|
||||
import { validateEmail } from "../utils/is-email"
|
||||
import { RemoteQueryFunction } from "@medusajs/types"
|
||||
import { RemoteLink } from "@medusajs/modules-sdk"
|
||||
|
||||
type InjectedDependencies = {
|
||||
manager: EntityManager
|
||||
@@ -98,6 +100,8 @@ type InjectedDependencies = {
|
||||
priceSelectionStrategy: IPriceSelectionStrategy
|
||||
productVariantInventoryService: ProductVariantInventoryService
|
||||
pricingService: PricingService
|
||||
remoteQuery: RemoteQueryFunction
|
||||
remoteLink: RemoteLink
|
||||
}
|
||||
|
||||
type TotalsConfig = {
|
||||
@@ -139,6 +143,8 @@ class CartService extends TransactionBaseService {
|
||||
protected readonly priceSelectionStrategy_: IPriceSelectionStrategy
|
||||
protected readonly lineItemAdjustmentService_: LineItemAdjustmentService
|
||||
protected readonly featureFlagRouter_: FlagRouter
|
||||
protected remoteQuery_: RemoteQueryFunction
|
||||
protected remoteLink_: RemoteLink
|
||||
// eslint-disable-next-line max-len
|
||||
protected readonly productVariantInventoryService_: ProductVariantInventoryService
|
||||
protected readonly pricingService_: PricingService
|
||||
@@ -169,6 +175,8 @@ class CartService extends TransactionBaseService {
|
||||
salesChannelService,
|
||||
featureFlagRouter,
|
||||
storeService,
|
||||
remoteQuery,
|
||||
remoteLink,
|
||||
productVariantInventoryService,
|
||||
pricingService,
|
||||
}: InjectedDependencies) {
|
||||
@@ -202,6 +210,8 @@ class CartService extends TransactionBaseService {
|
||||
this.storeService_ = storeService
|
||||
this.productVariantInventoryService_ = productVariantInventoryService
|
||||
this.pricingService_ = pricingService
|
||||
this.remoteQuery_ = remoteQuery
|
||||
this.remoteLink_ = remoteLink
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -216,6 +226,7 @@ class CartService extends TransactionBaseService {
|
||||
const cartRepo = this.activeManager_.withRepository(this.cartRepository_)
|
||||
|
||||
const query = buildQuery(selector, config)
|
||||
|
||||
return await cartRepo.find(query)
|
||||
}
|
||||
|
||||
@@ -357,7 +368,10 @@ class CartService extends TransactionBaseService {
|
||||
}
|
||||
|
||||
if (
|
||||
this.featureFlagRouter_.isFeatureEnabled(SalesChannelFeatureFlag.key)
|
||||
this.featureFlagRouter_.isFeatureEnabled(
|
||||
SalesChannelFeatureFlag.key
|
||||
) &&
|
||||
!this.featureFlagRouter_.isFeatureEnabled(MedusaV2Flag.key)
|
||||
) {
|
||||
rawCart.sales_channel_id = (
|
||||
await this.getValidatedSalesChannel(data.sales_channel_id)
|
||||
@@ -365,8 +379,7 @@ class CartService extends TransactionBaseService {
|
||||
}
|
||||
|
||||
if (data.customer_id || data.customer) {
|
||||
const customer =
|
||||
(data.customer ??
|
||||
const customer = (data.customer ??
|
||||
(data.customer_id &&
|
||||
(await this.customerService_
|
||||
.withTransaction(transactionManager)
|
||||
@@ -476,6 +489,27 @@ class CartService extends TransactionBaseService {
|
||||
|
||||
const createdCart = cartRepo.create(rawCart)
|
||||
const cart = await cartRepo.save(createdCart)
|
||||
|
||||
if (
|
||||
this.featureFlagRouter_.isFeatureEnabled([
|
||||
SalesChannelFeatureFlag.key,
|
||||
MedusaV2Flag.key,
|
||||
])
|
||||
) {
|
||||
const salesChannel = await this.getValidatedSalesChannel(
|
||||
data.sales_channel_id
|
||||
)
|
||||
|
||||
await this.remoteLink_.create({
|
||||
cartService: {
|
||||
cart_id: cart.id,
|
||||
},
|
||||
salesChannelService: {
|
||||
sales_channel_id: salesChannel.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
await this.eventBus_
|
||||
.withTransaction(transactionManager)
|
||||
.emit(CartService.Events.CREATED, {
|
||||
@@ -491,9 +525,20 @@ class CartService extends TransactionBaseService {
|
||||
): Promise<SalesChannel | never> {
|
||||
let salesChannel: SalesChannel
|
||||
if (isDefined(salesChannelId)) {
|
||||
salesChannel = await this.salesChannelService_
|
||||
.withTransaction(this.activeManager_)
|
||||
.retrieve(salesChannelId)
|
||||
if (this.featureFlagRouter_.isFeatureEnabled(MedusaV2Flag.key)) {
|
||||
const query = {
|
||||
sales_channel: {
|
||||
__args: {
|
||||
id: salesChannelId,
|
||||
},
|
||||
},
|
||||
}
|
||||
;[salesChannel] = await this.remoteQuery_(query)
|
||||
} else {
|
||||
salesChannel = await this.salesChannelService_
|
||||
.withTransaction(this.activeManager_)
|
||||
.retrieve(salesChannelId)
|
||||
}
|
||||
} else {
|
||||
salesChannel = (
|
||||
await this.storeService_.withTransaction(this.activeManager_).retrieve({
|
||||
@@ -584,7 +629,7 @@ class CartService extends TransactionBaseService {
|
||||
* Returns true if all products in the cart can be fulfilled with the current
|
||||
* shipping methods.
|
||||
* @param shippingMethods - the set of shipping methods to check from
|
||||
* @param lineItem - the line item
|
||||
* @param lineItemShippingProfiledId - the line item
|
||||
* @return boolean representing whether shipping method is validated
|
||||
*/
|
||||
protected validateLineItemShipping_(
|
||||
@@ -655,17 +700,22 @@ class CartService extends TransactionBaseService {
|
||||
lineItem: LineItem,
|
||||
config = { validateSalesChannels: true }
|
||||
): Promise<void> {
|
||||
const select: (keyof Cart)[] = ["id"]
|
||||
const fields: (keyof Cart)[] = ["id"]
|
||||
const relations: (keyof Cart)[] = ["shipping_methods"]
|
||||
|
||||
if (this.featureFlagRouter_.isFeatureEnabled("sales_channels")) {
|
||||
select.push("sales_channel_id")
|
||||
if (this.featureFlagRouter_.isFeatureEnabled(MedusaV2Flag.key)) {
|
||||
relations.push("sales_channels")
|
||||
} else {
|
||||
fields.push("sales_channel_id")
|
||||
}
|
||||
}
|
||||
|
||||
return await this.atomicPhase_(
|
||||
async (transactionManager: EntityManager) => {
|
||||
let cart = await this.retrieve(cartId, {
|
||||
select,
|
||||
relations: ["shipping_methods"],
|
||||
select: fields,
|
||||
relations,
|
||||
})
|
||||
|
||||
if (this.featureFlagRouter_.isFeatureEnabled("sales_channels")) {
|
||||
@@ -797,17 +847,22 @@ class CartService extends TransactionBaseService {
|
||||
): Promise<void> {
|
||||
const items: LineItem[] = Array.isArray(lineItems) ? lineItems : [lineItems]
|
||||
|
||||
const select: (keyof Cart)[] = ["id", "customer_id", "region_id"]
|
||||
const fields: (keyof Cart)[] = ["id", "customer_id", "region_id"]
|
||||
const relations: (keyof Cart)[] = ["shipping_methods"]
|
||||
|
||||
if (this.featureFlagRouter_.isFeatureEnabled("sales_channels")) {
|
||||
select.push("sales_channel_id")
|
||||
if (this.featureFlagRouter_.isFeatureEnabled(MedusaV2Flag.key)) {
|
||||
relations.push("sales_channels")
|
||||
} else {
|
||||
fields.push("sales_channel_id")
|
||||
}
|
||||
}
|
||||
|
||||
return await this.atomicPhase_(
|
||||
async (transactionManager: EntityManager) => {
|
||||
let cart = await this.retrieve(cartId, {
|
||||
select,
|
||||
relations: ["shipping_methods"],
|
||||
select: fields,
|
||||
relations,
|
||||
})
|
||||
|
||||
if (this.featureFlagRouter_.isFeatureEnabled("sales_channels")) {
|
||||
@@ -994,7 +1049,7 @@ class CartService extends TransactionBaseService {
|
||||
* Updates a cart's existing line item.
|
||||
* @param cartId - the id of the cart to update
|
||||
* @param lineItemId - the id of the line item to update.
|
||||
* @param lineItemUpdate - the line item to update. Must include an id field.
|
||||
* @param update - the line item to update. Must include an id field.
|
||||
* @return the result of the update operation
|
||||
*/
|
||||
async updateLineItem(
|
||||
@@ -1223,8 +1278,39 @@ class CartService extends TransactionBaseService {
|
||||
isDefined(data.sales_channel_id) &&
|
||||
data.sales_channel_id != cart.sales_channel_id
|
||||
) {
|
||||
const salesChannel = await this.getValidatedSalesChannel(
|
||||
data.sales_channel_id
|
||||
)
|
||||
|
||||
await this.onSalesChannelChange(cart, data.sales_channel_id)
|
||||
cart.sales_channel_id = data.sales_channel_id
|
||||
|
||||
/**
|
||||
* TODO: remove this once update cart workflow is build
|
||||
* since this will be handled in a handler by the workflow
|
||||
*/
|
||||
if (this.featureFlagRouter_.isFeatureEnabled(MedusaV2Flag.key)) {
|
||||
if (cart.sales_channel_id) {
|
||||
await this.remoteLink_.dismiss({
|
||||
cartService: {
|
||||
cart_id: cart.id,
|
||||
},
|
||||
salesChannelService: {
|
||||
sales_channel_id: cart.sales_channel_id,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
await this.remoteLink_.create({
|
||||
cartService: {
|
||||
cart_id: cart.id,
|
||||
},
|
||||
salesChannelService: {
|
||||
sales_channel_id: salesChannel.id,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
cart.sales_channel_id = salesChannel.id
|
||||
}
|
||||
}
|
||||
|
||||
if (isDefined(data.discounts) && data.discounts.length) {
|
||||
@@ -2247,15 +2333,15 @@ class CartService extends TransactionBaseService {
|
||||
const lineItemServiceTx =
|
||||
this.lineItemService_.withTransaction(transactionManager)
|
||||
|
||||
let productShippinProfileMap = new Map<string, string>()
|
||||
let productShippingProfileMap = new Map<string, string>()
|
||||
|
||||
if (this.featureFlagRouter_.isFeatureEnabled(MedusaV2Flag.key)) {
|
||||
productShippinProfileMap =
|
||||
productShippingProfileMap =
|
||||
await this.shippingProfileService_.getMapProfileIdsByProductIds(
|
||||
cart.items.map((item) => item.variant.product_id)
|
||||
)
|
||||
} else {
|
||||
productShippinProfileMap = new Map<string, string>(
|
||||
productShippingProfileMap = new Map<string, string>(
|
||||
cart.items.map((item) => [
|
||||
item.variant?.product?.id,
|
||||
item.variant?.product?.profile_id,
|
||||
@@ -2268,7 +2354,7 @@ class CartService extends TransactionBaseService {
|
||||
return lineItemServiceTx.update(item.id, {
|
||||
has_shipping: this.validateLineItemShipping_(
|
||||
methods,
|
||||
productShippinProfileMap.get(item.variant?.product_id)!
|
||||
productShippingProfileMap.get(item.variant?.product_id)!
|
||||
),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -76,7 +76,7 @@ class SalesChannelLocationService extends TransactionBaseService {
|
||||
.retrieve(salesChannelId)
|
||||
|
||||
if (this.stockLocationService_) {
|
||||
// trhows error if not found
|
||||
// throws error if not found
|
||||
await this.stockLocationService_.retrieve(locationId, undefined, {
|
||||
transactionManager: this.activeManager_,
|
||||
})
|
||||
@@ -124,7 +124,7 @@ class SalesChannelLocationService extends TransactionBaseService {
|
||||
|
||||
/**
|
||||
* Lists the sales channels associated with a stock location.
|
||||
* @param {string} salesChannelId - The ID of the stock location.
|
||||
* @param {string} locationId - The ID of the stock location.
|
||||
* @returns {Promise<string[]>} A promise that resolves with an array of sales channel IDs.
|
||||
*/
|
||||
async listSalesChannelIds(locationId: string): Promise<string[]> {
|
||||
|
||||
@@ -34,7 +34,7 @@ export function FeatureFlagColumn(
|
||||
}
|
||||
|
||||
export function FeatureFlagDecorators(
|
||||
featureFlag: string,
|
||||
featureFlag: string | string[],
|
||||
decorators: PropertyDecorator[]
|
||||
): PropertyDecorator {
|
||||
return function (target, propertyName) {
|
||||
@@ -68,7 +68,7 @@ export function FeatureFlagClassDecorators(
|
||||
}
|
||||
|
||||
export function FeatureFlagEntity(
|
||||
featureFlag: string,
|
||||
featureFlag: string | string[],
|
||||
name?: string,
|
||||
options?: EntityOptions
|
||||
): ClassDecorator {
|
||||
|
||||
@@ -17,6 +17,18 @@ export function remoteQueryFetchData(container: MedusaContainer) {
|
||||
...RemoteQuery.getAllFieldsAndRelations(expand),
|
||||
}
|
||||
|
||||
const expandRelations = Object.keys(expand.expands ?? {})
|
||||
|
||||
// filter out links from relations because TypeORM will throw if the relation doesn't exist
|
||||
|
||||
options.relations = options.relations.filter(
|
||||
(relation) => !expandRelations.some((ex) => relation.startsWith(ex))
|
||||
)
|
||||
|
||||
options.select = options.relations.filter(
|
||||
(field) => !expandRelations.some((ex) => field.startsWith(ex))
|
||||
)
|
||||
|
||||
if (ids) {
|
||||
filters[keyField] = ids
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user