Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,37 +1,21 @@
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework"
import { ContainerRegistrationKeys, MedusaError, PromotionActions } from "@medusajs/framework/utils"
import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
import { ContainerRegistrationKeys, PromotionActions } from "@medusajs/framework/utils"
import { StoreAddCartPromotionsType } from "@medusajs/medusa/api/store/carts/validators"
import { updateCartPromotionsWorkflow } from "@medusajs/medusa/core-flows"
import { fetchSellerByAuthActorId } from "@mercurjs/framework"
import { validateSellerPromotions } from "../../../../../modules/seller"
import { updateCartPromotionsInSellerContextWorkflow } from "../../../../../workflows/promotions/workflows/update-cart-promotions-in-seller-context"

export const POST = async (
req: AuthenticatedMedusaRequest<StoreAddCartPromotionsType>,
req: MedusaRequest,
res: MedusaResponse
) => {
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
const { promo_codes } = req.validatedBody as StoreAddCartPromotionsType;

const seller = await fetchSellerByAuthActorId(
req.auth_context?.actor_id,
req.scope
)

const validatePromotions = await validateSellerPromotions(
req.validatedBody.promo_codes,
req.scope,
seller.id
)

if (!validatePromotions.valid) {
throw new MedusaError(MedusaError.Types.INVALID_DATA, 'Some of the promotion codes are invalid')
}

await updateCartPromotionsWorkflow.run({
await updateCartPromotionsInSellerContextWorkflow(req.scope).run({
input: {
cart_id: req.params.id,
promo_codes: req.validatedBody.promo_codes,
promo_codes: promo_codes,
action:
req.validatedBody.promo_codes.length > 0
promo_codes.length > 0
? PromotionActions.ADD
: PromotionActions.REPLACE,
},
Expand Down
13 changes: 12 additions & 1 deletion packages/modules/b2c-core/src/api/store/carts/middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
validateAndTransformQuery
} from '@medusajs/framework'
import * as QueryConfig from '@medusajs/medusa/api/store/carts/query-config'
import { StoreGetCartsCart } from '@medusajs/medusa/api/store/carts/validators'
import { StoreAddCartPromotions, StoreGetCartsCart } from '@medusajs/medusa/api/store/carts/validators'
import { StoreAddCartShippingMethods } from '@medusajs/medusa/api/store/carts/validators'

import { StoreDeleteCartShippingMethods } from './validators'
Expand All @@ -31,5 +31,16 @@ export const storeCartsMiddlewares: MiddlewareRoute[] = [
QueryConfig.retrieveTransformQueryConfig
)
]
},
{
method: ['POST'],
matcher: '/store/carts/:id/promotions',
middlewares: [
validateAndTransformBody(StoreAddCartPromotions),
validateAndTransformQuery(
StoreGetCartsCart,
QueryConfig.retrieveTransformQueryConfig
)
]
}
]
31 changes: 0 additions & 31 deletions packages/modules/b2c-core/src/modules/seller/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,34 +126,3 @@ export async function selectCustomersChartData(

return result as unknown as { date: Date; count: string }[]
}

export async function validateSellerPromotions(
promo_codes: string[],
container: MedusaContainer,
seller_id: string
): Promise<{ valid: boolean; invalidCodes: string[] }> {
const knex = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)

const sellerPromotionCodes = await knex
.select('promotion.code')
.from('seller_seller_promotion_promotion')
.leftJoin(
'promotion',
'seller_seller_promotion_promotion.promotion_id',
'promotion.id'
)
.where('seller_seller_promotion_promotion.seller_id', seller_id)
.whereIn('promotion.code', promo_codes)
.whereNull('promotion.deleted_at')

const foundCodes = sellerPromotionCodes.map((row) => row.code)

const invalidCodes = promo_codes.filter(
(code) => !foundCodes.includes(code)
)

return {
valid: invalidCodes.length === 0,
invalidCodes
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
export const cartFieldsForPromoApply = [
"id",
"email",
"currency_code",
"quantity",
"subtotal",
"item_total",
"total",
"item_subtotal",
"shipping_subtotal",
"region_id",
"metadata",
"completed_at",
"sales_channel_id",
"region.*",
"items.*",
"items.product.id",
"items.product.is_giftcard",
"items.product.collection_id",
"items.product.categories.id",
"items.product.tags.id",
"items.product.type_id",
"items.product.seller.id",
"items.variant.id",
"items.variant.product.id",
"items.variant.weight",
"items.variant.length",
"items.variant.height",
"items.variant.width",
"items.variant.material",
"items.adjustments.*",
"items.tax_lines.*",
"shipping_address.*",
"shipping_methods.*",
"shipping_methods.adjustments.*",
"shipping_methods.tax_lines.*",
"shipping_methods.shipping_option.shipping_option_type_id",
"customer.*",
"customer.groups.*",
"promotions.id",
"promotions.code",
"payment_collection.id",
"payment_collection.raw_amount",
"payment_collection.amount",
"payment_collection.currency_code",
"payment_collection.payment_sessions.id",
]
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CreatePromotionDTO, LinkDefinition } from "@medusajs/framework/types";
import { CreatePromotionDTO, CreatePromotionRuleDTO, LinkDefinition } from "@medusajs/framework/types";
import { Modules } from "@medusajs/framework/utils";
import {
createPromotionsWorkflow,
Expand Down Expand Up @@ -30,9 +30,24 @@ export const createVendorPromotionWorkflow = createWorkflow(
}))
);

const promotionWithVendorRule = transform(input, ({ promotion, seller_id }) => ({
...promotion,
application_method: {
...promotion.application_method,
target_rules: [
...(promotion.application_method?.target_rules || []),
{
attribute: "items.product.seller.id",
operator: "eq",
values: [seller_id],
} as CreatePromotionRuleDTO,
],
},
}));

const promotions = createPromotionsWorkflow.runAsStep({
input: {
promotionsData: [input.promotion],
promotionsData: [promotionWithVendorRule],
},
});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createWorkflow, WorkflowData, transform } from "@medusajs/framework/workflows-sdk"
import { UpdateCartPromotionsWorkflowInput, useQueryGraphStep, updateCartPromotionsWorkflow } from "@medusajs/medusa/core-flows"
import { cartFieldsForPromoApply } from "../utils/cart-fields-for-promo-apply"

export const updateCartPromotionsInSellerContextWorkflow = createWorkflow(
{
name: "update-cart-promotions-in-seller-context",
idempotent: false,
},
(input: WorkflowData<UpdateCartPromotionsWorkflowInput>) => {
const { data: fetchedCart } = useQueryGraphStep({
entity: "cart",
fields: cartFieldsForPromoApply,
filters: { id: input.cart_id },
options: { isList: false },
}).config({ name: "fetch-cart-with-seller" })

const enrichedInput = transform({ input, fetchedCart }, ({ input, fetchedCart }) => ({
...input,
cart: fetchedCart,
}))

return updateCartPromotionsWorkflow.runAsStep({
input: enrichedInput,
})
}
)