Skip to content

Feature/ecommerce template coupons #13322

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: feat/ecommerce-template
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
67 changes: 63 additions & 4 deletions packages/plugin-ecommerce/src/carts/beforeChange.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
import type { CollectionBeforeChangeHook } from 'payload'

import { getCouponDiscountValue } from '../utilities/getCouponDiscountValue.js'

type Props = {
couponsSlug: string
productsSlug: string
variantsSlug: string
}

export const beforeChangeCart: (args: Props) => CollectionBeforeChangeHook =
({ productsSlug, variantsSlug }) =>
({ couponsSlug, productsSlug, variantsSlug }) =>
async ({ data, req }) => {
// Update subtotal based on items in the cart
const payload = req.payload

if (data.items && Array.isArray(data.items)) {
const priceField = `priceIn${data.currency}`

let subtotal = 0
let totalItemsDiscount = 0
let totalCartDiscount = 0

for (const item of data.items) {
if (item.variant) {
Expand All @@ -27,7 +33,23 @@ export const beforeChangeCart: (args: Props) => CollectionBeforeChangeHook =
},
})

subtotal += variant[priceField] * item.quantity
const itemAmount = variant[priceField] * item.quantity
subtotal += itemAmount

if (Array.isArray(item.discount?.discountLines)) {
for (const discountLine of item.discount.discountLines) {
const coupon = await payload.findByID({
id: discountLine.coupon,
collection: couponsSlug,
})

discountLine.amount = discountLine.amount ?? 0
discountLine.amount += getCouponDiscountValue(itemAmount, coupon)
item.discount.amount += discountLine.amount

totalItemsDiscount += item.discount.amount
}
}
} else {
const id = typeof item.product === 'object' ? item.product.id : item.product

Expand All @@ -40,12 +62,49 @@ export const beforeChangeCart: (args: Props) => CollectionBeforeChangeHook =
},
})

subtotal += product[priceField] * item.quantity
const itemAmount = product[priceField] * item.quantity
subtotal += itemAmount

if (Array.isArray(item.discount?.discountLines)) {
for (const discountLine of item.discount.discountLines) {
const coupon = await payload.findByID({
id: discountLine.coupon,
collection: couponsSlug,
})

discountLine.amount = discountLine.amount ?? 0
discountLine.amount += getCouponDiscountValue(itemAmount, coupon)
if (!item.discount.total) {
item.discount.total = 0
}
item.discount.total += discountLine.amount
totalItemsDiscount += item.discount.total
}
}
}
}

for (const discountLine of data.discount?.discountLines ?? []) {
const coupon = await payload.findByID({
id: discountLine.coupon,
collection: couponsSlug,
})

discountLine.amount = getCouponDiscountValue(subtotal, coupon)
totalCartDiscount += discountLine.amount
}

data.subtotal = subtotal
data.discount = data.discount ?? {}
data.discount.cartAmount = totalCartDiscount
data.discount.lineItemsAmount = totalItemsDiscount
data.discount.totalAmount = totalCartDiscount + totalItemsDiscount
data.total = subtotal + data.discount.totalAmount
} else {
data.subtotal = 0
data.discount.cartAmount = 0
data.discount.lineItemsAmount = 0
data.discount.totalAmount = 0
data.total = 0
}
}
85 changes: 84 additions & 1 deletion packages/plugin-ecommerce/src/carts/cartsCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,25 @@ import { currencyField } from '../fields/currencyField.js'
import { beforeChangeCart } from './beforeChange.js'

type Props = {
/**
* Slug of the coupons collection, defaults to 'coupons'.
*/
couponsSlug?: string
currenciesConfig?: CurrenciesConfig
/**
* Slug of the customers collection, defaults to 'users'.
*/
customersSlug?: string
enableCoupons?: boolean
/**
* Enables support for variants in the cart.
* Defaults to false.
*/
enableVariants?: boolean
/**
* Enables support for coupons in the cart.
* Defaults to false.
*/
overrides?: { fields?: FieldsOverride } & Partial<Omit<CollectionConfig, 'fields'>>
/**
* Slug of the products collection, defaults to 'products'.
Expand All @@ -31,8 +40,10 @@ type Props = {

export const cartsCollection: (props?: Props) => CollectionConfig = (props) => {
const {
couponsSlug = 'coupons',
currenciesConfig,
customersSlug = 'users',
enableCoupons = false,
enableVariants = false,
overrides,
productsSlug = 'products',
Expand Down Expand Up @@ -82,6 +93,67 @@ export const cartsCollection: (props?: Props) => CollectionConfig = (props) => {
},
],
},

...(enableCoupons && currenciesConfig
? [
{
name: 'discount',
type: 'group',
fields: [
{
name: 'discountLines',
type: 'array',
fields: [
{
name: 'coupon',
type: 'relationship',
hasMany: false,
label: 'Coupon',
relationTo: couponsSlug,
},

amountField({
currenciesConfig,
overrides: {
name: 'amount',
label: ({ t }) =>
// @ts-expect-error - translations are not typed in plugins yet
t('plugin-ecommerce:subtotal'),
},
}),
],
},

amountField({
currenciesConfig,
overrides: {
name: 'totalAmount',
// @ts-expect-error - translations are not typed in plugins yet
label: ({ t }) => t('plugin-ecommerce:discount.amount'),
},
}),

amountField({
currenciesConfig,
overrides: {
name: 'cartAmount',
// @ts-expect-error - translations are not typed in plugins yet
label: ({ t }) => t('plugin-ecommerce:discount.amount'),
},
}),

amountField({
currenciesConfig,
overrides: {
name: 'lineItemsAmount',
// @ts-expect-error - translations are not typed in plugins yet
label: ({ t }) => t('plugin-ecommerce:discount.amount'),
},
}),
],
} as Field,
]
: []),
...(currenciesConfig
? [
currencyField({
Expand All @@ -96,9 +168,20 @@ export const cartsCollection: (props?: Props) => CollectionConfig = (props) => {
t('plugin-ecommerce:subtotal'),
},
}),
amountField({
currenciesConfig,
overrides: {
name: 'total',
label: ({ t }) =>
// @ts-expect-error - translations are not typed in plugins yet
t('plugin-ecommerce:total'),
},
}),
]
: []),
cartItemsField({
currenciesConfig,
enableCoupons,
enableVariants,
overrides: {
label: ({ t }) =>
Expand Down Expand Up @@ -135,7 +218,7 @@ export const cartsCollection: (props?: Props) => CollectionConfig = (props) => {
hooks: {
beforeChange: [
// This hook can be used to update the subtotal before saving the cart
beforeChangeCart({ productsSlug, variantsSlug }),
beforeChangeCart({ couponsSlug, productsSlug, variantsSlug }),
...(overrides?.hooks?.beforeChange || []),
],
...overrides?.hooks,
Expand Down
Loading
Loading