Skip to content

Commit

Permalink
Merge pull request #6771 from reactioncommerce/feat/add-additional-co…
Browse files Browse the repository at this point in the history
…upon-validation

feat: add additional coupon validation
  • Loading branch information
vanpho93 committed Feb 7, 2023
2 parents 65e9795 + 729b4a5 commit 193751c
Show file tree
Hide file tree
Showing 9 changed files with 336 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ export default async function createStandardCoupon(context, input) {

for (const existsPromotion of promotions) {
if (existsPromotion.startDate <= promotion.startDate && existsPromotion.endDate >= promotion.endDate) {
throw new ReactionError("invalid-params", `A coupon code ${code} already exists in this promotion window`);
throw new ReactionError(
"invalid-params",
// eslint-disable-next-line max-len
"A promotion with this coupon code is already set to be active during part of this promotion window. Please either adjust your coupon code or your Promotion Start and End Dates"
);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ test("throws error when coupon code already exists in promotion window", async (
try {
await createStandardCoupon(mockContext, input);
} catch (error) {
expect(error.message).toEqual("A coupon code CODE already exists in this promotion window");
// eslint-disable-next-line max-len
expect(error.message).toEqual("A promotion with this coupon code is already set to be active during part of this promotion window. Please either adjust your coupon code or your Promotion Start and End Dates");
}
});

Expand Down
2 changes: 2 additions & 0 deletions packages/api-plugin-promotions-coupons/src/mutations/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import applyCouponToCart from "./applyCouponToCart.js";
import createStandardCoupon from "./createStandardCoupon.js";
import updateStandardCoupon from "./updateStandardCoupon.js";
import removeCouponFromCart from "./removeCouponFromCart.js";

export default {
applyCouponToCart,
createStandardCoupon,
updateStandardCoupon,
removeCouponFromCart
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import _ from "lodash";
import SimpleSchema from "simpl-schema";
import ReactionError from "@reactioncommerce/reaction-error";
import { Coupon } from "../simpleSchemas.js";

const inputSchema = new SimpleSchema({
_id: String,
shopId: String,
name: {
type: String,
optional: true
},
code: {
type: String,
optional: true
},
canUseInStore: {
type: Boolean,
optional: true
},
maxUsageTimesPerUser: {
type: Number,
optional: true
},
maxUsageTimes: {
type: Number,
optional: true
}
});

/**
* @method updateStandardCoupon
* @summary Update a standard coupon mutation
* @param {Object} context - The application context
* @param {Object} input - The coupon input to create
* @returns {Promise<Object>} with updated coupon result
*/
export default async function updateStandardCoupon(context, input) {
inputSchema.validate(input);

const { collections: { Coupons, Promotions } } = context;
const { shopId, _id: couponId } = input;

const coupon = await Coupons.findOne({ _id: couponId, shopId });
if (!coupon) throw new ReactionError("not-found", "Coupon not found");

const promotion = await Promotions.findOne({ _id: coupon.promotionId, shopId });
if (!promotion) throw new ReactionError("not-found", "Promotion not found");

const now = new Date();
if (promotion.startDate <= now) {
throw new ReactionError("invalid-params", "Cannot update a coupon for a promotion that has already started");
}

if (input.code && coupon.code !== input.code) {
const existsCoupons = await Coupons.find({ code: input.code, shopId, _id: { $ne: coupon._id } }).toArray();
if (existsCoupons.length > 0) {
const promotionIds = _.map(existsCoupons, "promotionId");
const promotions = await Promotions.find({ _id: { $in: promotionIds } }).toArray();
for (const existsPromotion of promotions) {
if (existsPromotion.startDate <= promotion.startDate && existsPromotion.endDate >= promotion.endDate) {
throw new ReactionError(
"invalid-params",
// eslint-disable-next-line max-len
"A promotion with this coupon code is already set to be active during part of this promotion window. Please either adjust your coupon code or your Promotion Start and End Dates"
);
}
}
}
}

const modifiedCoupon = _.merge(coupon, input);
modifiedCoupon.updatedAt = now;

Coupon.clean(modifiedCoupon, { mutate: true });
Coupon.validate(modifiedCoupon);

const modifier = { $set: modifiedCoupon };
const results = await Coupons.findOneAndUpdate({ _id: couponId, shopId }, modifier, { returnDocument: "after" });

const { modifiedCount, value } = results;
return { success: !!modifiedCount, coupon: value };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import _ from "lodash";
import mockContext from "@reactioncommerce/api-utils/tests/mockContext.js";
import updateStandardCoupon from "./updateStandardCoupon.js";

const now = new Date();
const mockCoupon = {
_id: "123",
code: "CODE",
promotionId: "123",
shopId: "123",
canUseInStore: false,
usedCount: 0,
createdAt: now,
updatedAt: now,
maxUsageTimes: 10,
maxUsageTimesPerUser: 1
};

test("throws if validation check fails", async () => {
const input = { code: "CODE" };

try {
await updateStandardCoupon(mockContext, input);
} catch (error) {
expect(error.error).toEqual("validation-error");
}
});

test("throws error when coupon does not exist", async () => {
const input = { code: "CODE", _id: "123", shopId: "123", canUseInStore: true };
mockContext.collections = {
Coupons: {
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(null))
}
};
try {
await updateStandardCoupon(mockContext, input);
} catch (error) {
expect(error.message).toEqual("Coupon not found");
}
});

test("throws error when promotion does not exist", async () => {
const input = { code: "CODE", shopId: "123", _id: "123" };
const coupon = _.cloneDeep(mockCoupon);
mockContext.collections = {
Coupons: {
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(coupon))
},
Promotions: {
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(null))
}
};

try {
await updateStandardCoupon(mockContext, input);
} catch (error) {
expect(error.message).toEqual("Promotion not found");
}
});

test("throws error when the related promotion is in promotion window", async () => {
const input = { code: "CODE", shopId: "123", _id: "123" };
const promotion = { _id: "123", startDate: now, endDate: now };
const coupon = _.cloneDeep(mockCoupon);
mockContext.collections = {
Coupons: {
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(coupon))
},
Promotions: {
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(promotion))
}
};

try {
await updateStandardCoupon(mockContext, input);
} catch (error) {
expect(error.message).toEqual("Cannot update a coupon for a promotion that has already started");
}
});

test("throws error when coupon code already exists in promotion window", async () => {
const input = { code: "NEW_CODE", shopId: "123", _id: "123" };
const promotion = {
_id: "123",
startDate: new Date(now.getTime() + 1000 * 60 * 60 * 24 * 1),
endDate: new Date(now.getTime() + 1000 * 60 * 60 * 24 * 7)
};
const existsPromotion = {
_id: "1234",
startDate: now,
endDate: new Date(now.getTime() + 1000 * 60 * 60 * 24 * 10)
};
const coupon = _.cloneDeep(mockCoupon);
mockContext.collections = {
Coupons: {
find: jest.fn().mockReturnValue({
toArray: jest.fn().mockResolvedValueOnce(Promise.resolve([coupon]))
}),
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(coupon))
},
Promotions: {
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(promotion)),
find: jest.fn().mockReturnValue({
toArray: jest.fn().mockResolvedValueOnce(Promise.resolve([existsPromotion]))
})
}
};

try {
await updateStandardCoupon(mockContext, input);
} catch (error) {
// eslint-disable-next-line max-len
expect(error.message).toEqual("A promotion with this coupon code is already set to be active during part of this promotion window. Please either adjust your coupon code or your Promotion Start and End Dates");
}
});

test("should update coupon and return the updated results", async () => {
const input = { name: "test", code: "CODE", shopId: "123", _id: "123", canUseInStore: true };
const promotion = { _id: "123", endDate: now };
const coupon = _.cloneDeep(mockCoupon);
mockContext.collections = {
Coupons: {
find: jest.fn().mockReturnValue({
toArray: jest.fn().mockResolvedValueOnce([])
}),
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(coupon)),
findOneAndUpdate: jest.fn().mockResolvedValueOnce(Promise.resolve({ modifiedCount: 1, value: { _id: "123" } }))
},
Promotions: {
findOne: jest.fn().mockResolvedValueOnce(Promise.resolve(promotion))
}
};

const result = await updateStandardCoupon(mockContext, input);

expect(mockContext.collections.Coupons.findOneAndUpdate).toHaveBeenCalledTimes(1);
expect(mockContext.collections.Coupons.findOne).toHaveBeenCalledTimes(1);

expect(result).toEqual({
success: true,
coupon: {
_id: "123"
}
});
});
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import applyCouponToCart from "./applyCouponToCart.js";
import createStandardCoupon from "./createStandardCoupon.js";
import updateStandardCoupon from "./updateStandardCoupon.js";
import removeCouponFromCart from "./removeCouponFromCart.js";

export default {
applyCouponToCart,
createStandardCoupon,
updateStandardCoupon,
removeCouponFromCart
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @method updateStandardCoupon
* @summary Update a standard coupon mutation
* @param {Object} _ unused
* @param {Object} args.input - The input arguments
* @param {Object} args.input.shopId - The shop ID
* @param {Object} args.input.couponId - The coupon ID
* @param {Object} args.input.promotionId - The promotion ID
* @param {Object} context - The application context
* @returns {Promise<Object>} with updated coupon result
*/
export default async function updateStandardCoupon(_, { input }, context) {
const { shopId } = input;

await context.validatePermissions("reaction:legacy:promotions", "update", { shopId });

const updatedCouponResult = await context.mutations.updateStandardCoupon(context, input);
return updatedCouponResult;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import mockContext from "@reactioncommerce/api-utils/tests/mockContext.js";
import updateStandardCoupon from "./updateStandardCoupon.js";

test("throws if permission check fails", async () => {
const input = { name: "Test coupon", code: "CODE" };
mockContext.validatePermissions.mockResolvedValue(Promise.reject(new Error("Access Denied")));

try {
await updateStandardCoupon(null, { input }, mockContext);
} catch (error) {
expect(error.message).toEqual("Access Denied");
}
});

test("calls mutations.updateStandardCoupon and returns the result", async () => {
const input = { name: "Test coupon", code: "CODE", couponId: "testId" };
const result = { _id: "123" };
mockContext.validatePermissions.mockResolvedValue(Promise.resolve());
mockContext.mutations = {
updateStandardCoupon: jest.fn().mockName("mutations.updateStandardCoupon").mockReturnValueOnce(Promise.resolve(result))
};

const createdCoupon = await updateStandardCoupon(null, { input }, mockContext);

expect(createdCoupon).toEqual(result);
});
51 changes: 51 additions & 0 deletions packages/api-plugin-promotions-coupons/src/schemas/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,51 @@ input CreateStandardCouponInput {
maxUsageTimes: Int
}

"Input for the updateStandardCoupon mutation"
input UpdateStandardCouponInput {
"The coupon ID"
_id: ID!

"The shop ID"
shopId: ID!

"The coupon name"
name: String

"The coupon code"
code: String

"Can use this coupon in the store"
canUseInStore: Boolean

"The number of times this coupon can be used per user"
maxUsageTimesPerUser: Int

"The number of times this coupon can be used"
maxUsageTimes: Int
}

"The input for the createStandardCoupon mutation"
input CreateStandardCouponInput {
"The shop ID"
shopId: ID!

"The promotion ID"
promotionId: ID!

"The coupon code"
code: String!

"Can use this coupon in the store"
canUseInStore: Boolean!

"The number of times this coupon can be used per user"
maxUsageTimesPerUser: Int

"The number of times this coupon can be used"
maxUsageTimes: Int
}

input CouponQueryInput {
"The unique ID of the coupon"
_id: String!
Expand Down Expand Up @@ -211,6 +256,12 @@ extend type Mutation {
input: CreateStandardCouponInput
): StandardCouponPayload

"Update a standard coupon mutation"
updateStandardCoupon(
"The updateStandardCoupon mutation input"
input: UpdateStandardCouponInput
): StandardCouponPayload

"Remove a coupon from a cart"
removeCouponFromCart(
"The removeCouponFromCart mutation input"
Expand Down

0 comments on commit 193751c

Please sign in to comment.