Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/cozy-meals-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@labdigital/commercetools-mock": minor
---

Add basic support for discount codes in the cart repository
21 changes: 21 additions & 0 deletions src/repositories/cart/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import type {
ProductVariant,
} from "@commercetools/platform-sdk";
import type {
CartAddDiscountCodeAction,
CustomLineItem,
DirectDiscount,
} from "@commercetools/platform-sdk/dist/declarations/src/generated/models/cart";
Expand All @@ -61,6 +62,7 @@ import {
calculateCartTotalPrice,
calculateLineItemTotalPrice,
createCustomLineItemFromDraft,
createDiscountCodeInfoFromCode,
selectPrice,
} from "./helpers.ts";
import type { CartRepository } from "./index.ts";
Expand Down Expand Up @@ -280,6 +282,25 @@ export class CartUpdateHandler
// and prices on related Products have changed in the meanwhile.
}

addDiscountCode(
context: RepositoryContext,
resource: Writable<Cart>,
{ code }: CartAddDiscountCodeAction,
) {
const info = createDiscountCodeInfoFromCode(
context.projectKey,
this._storage,
code,
);
if (
!resource.discountCodes
.map((dc) => dc.discountCode.id)
.includes(info.discountCode.id)
) {
resource.discountCodes.push(info);
}
}
Comment on lines +285 to +302
Copy link

Copilot AI Dec 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The newly added addDiscountCode action lacks test coverage. While there is a test for creating a cart with discount codes, there's no test for the addDiscountCode update action itself. Consider adding a test that creates a cart and then uses the addDiscountCode action to verify the functionality works correctly.

Copilot uses AI. Check for mistakes.

removeDiscountCode(
context: RepositoryContext,
resource: Writable<Cart>,
Expand Down
29 changes: 29 additions & 0 deletions src/repositories/cart/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import type {
Cart,
CustomLineItem,
CustomLineItemDraft,
DiscountCodeInfo,
DiscountCodeNonApplicableError,
LineItem,
Price,
TaxCategory,
TaxCategoryReference,
} from "@commercetools/platform-sdk";
import { v4 as uuidv4 } from "uuid";
import { CommercetoolsError } from "#src/exceptions.ts";
import { calculateTaxedPrice } from "#src/lib/tax.ts";
import type { AbstractStorage } from "#src/storage/abstract.ts";
import {
Expand Down Expand Up @@ -121,3 +124,29 @@ export const createCustomLineItemFromDraft = (
taxedPricePortions: [],
};
};

export const createDiscountCodeInfoFromCode = (
projectKey: string,
storage: AbstractStorage,
code: string,
): DiscountCodeInfo => {
const discountCodes = storage.query(projectKey, "discount-code", {
where: `code="${code}"`,
});
// Does not validate anything besides existence of the DiscountCode object
if (discountCodes.count === 0) {
throw new CommercetoolsError<DiscountCodeNonApplicableError>({
code: "DiscountCodeNonApplicable",
message: `The discount code '${code}' was not found.`,
reason: "DoesNotExist",
discountCode: "nonexistent",
Copy link

Copilot AI Dec 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The discountCode field should contain the actual discount code that was not found, not the hardcoded string "nonexistent". This field should be set to the value of the code parameter to provide more useful error information to API consumers.

Suggested change
discountCode: "nonexistent",
discountCode: code,

Copilot uses AI. Check for mistakes.
});
}
return {
discountCode: {
typeId: "discount-code",
id: discountCodes.results[0].id,
},
state: "MatchesCart",
};
};
32 changes: 32 additions & 0 deletions src/repositories/cart/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -716,4 +716,36 @@ describe("createShippingInfo", () => {
expect(result.taxedPrice!.totalGross.centAmount).toBe(1204);
expect(result.taxedPrice!.totalNet.centAmount).toBe(995);
});

test("create cart with discount code", async () => {
const code = storage.add("dummy", "discount-code", {
...getBaseResourceProperties(),
code: "test-1234",
cartDiscounts: [],
isActive: true,
references: [],
groups: [],
});

const cart: CartDraft = {
country: "NL",
currency: "EUR",
discountCodes: ["test-1234"],
};

const ctx = { projectKey: "dummy", storeKey: "dummyStore" };

const result = repository.create(ctx, cart);
expect(result.id).toBeDefined();

expect(result.discountCodes).toEqual([
{
discountCode: {
typeId: "discount-code",
id: code.id,
},
state: "MatchesCart",
},
]);
});
Comment on lines +720 to +750
Copy link

Copilot AI Dec 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test only covers the happy path where the discount code exists. Consider adding a test case that verifies the error thrown when attempting to create a cart with a non-existent discount code to ensure proper error handling.

Copilot uses AI. Check for mistakes.
});
18 changes: 17 additions & 1 deletion src/repositories/cart/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {
BusinessUnit,
Cart,
CartDraft,
DiscountCodeInfo,
GeneralError,
InvalidOperationError,
LineItem,
Expand Down Expand Up @@ -29,6 +30,7 @@ import { CartUpdateHandler } from "./actions.ts";
import {
calculateCartTotalPrice,
createCustomLineItemFromDraft,
createDiscountCodeInfoFromCode,
selectPrice,
} from "./helpers.ts";

Expand Down Expand Up @@ -87,6 +89,20 @@ export class CartRepository extends AbstractResourceRepository<"cart"> {
),
) ?? [];

// Validate that discount codes exist
const discountCodeInfo: DiscountCodeInfo[] = [];
if (draft.discountCodes?.length) {
draft.discountCodes.forEach((code) => {
discountCodeInfo.push(
createDiscountCodeInfoFromCode(
context.projectKey,
this._storage,
code,
),
);
});
}
Comment on lines +92 to +104
Copy link

Copilot AI Dec 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When creating a cart with duplicate discount codes in the discountCodes array, the current implementation will create duplicate entries in the cart's discountCodes array. Consider deduplicating the discount codes during cart creation, similar to how the addDiscountCode action prevents duplicates.

Copilot uses AI. Check for mistakes.

const resource: Writable<Cart> = {
...getBaseResourceProperties(),
anonymousId: draft.anonymousId,
Expand All @@ -106,7 +122,7 @@ export class CartRepository extends AbstractResourceRepository<"cart"> {
customerEmail: draft.customerEmail,
customLineItems,
directDiscounts: [],
discountCodes: [],
discountCodes: discountCodeInfo,
inventoryMode: "None",
itemShippingAddresses: [],
lineItems,
Expand Down