Skip to content

Commit

Permalink
feat: add support for set product price action (#199)
Browse files Browse the repository at this point in the history
  • Loading branch information
leongraumans authored Aug 21, 2024
1 parent cb8cce6 commit be62944
Show file tree
Hide file tree
Showing 3 changed files with 160 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/purple-crews-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@labdigital/commercetools-mock": minor
---

add support for "setProductPriceCustomField" product update action
92 changes: 88 additions & 4 deletions src/repositories/product/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import type {
ProductSetMetaDescriptionAction,
ProductSetMetaKeywordsAction,
ProductSetMetaTitleAction,
ProductSetProductPriceCustomFieldAction,
ProductSetProductPriceCustomTypeAction,
ProductSetTaxCategoryAction,
ProductTransitionStateAction,
ProductUpdateAction,
Expand All @@ -35,8 +37,11 @@ import type {
} from "@commercetools/platform-sdk";
import { CommercetoolsError } from "~src/exceptions";
import type { Writable } from "~src/types";
import { AbstractUpdateHandler, RepositoryContext } from "../abstract";
import { getReferenceFromResourceIdentifier } from "../helpers";
import { AbstractUpdateHandler, type RepositoryContext } from "../abstract";
import {
createCustomFields,
getReferenceFromResourceIdentifier,
} from "../helpers";
import {
checkForStagedChanges,
getVariant,
Expand Down Expand Up @@ -853,6 +858,87 @@ export class ProductUpdateHandler
return resource;
}

setProductPriceCustomField(
context: RepositoryContext,
resource: Writable<Product>,
{ name, value, staged, priceId }: ProductSetProductPriceCustomFieldAction,
) {
const updatePriceCustomFields = (data: Writable<ProductData>) => {
const price = [data.masterVariant, ...(data.variants ?? [])]
.flatMap((variant) => variant.prices ?? [])
.find((price) => price.id === priceId);

if (!price) {
throw new Error(
`Price with id ${priceId} not found on product ${resource.id}`,
);
}
if (price.custom) {
if (value === null) {
delete price.custom.fields[name];
} else {
price.custom.fields[name] = value;
}
}
return data;
};

resource.masterData.staged = updatePriceCustomFields(
resource.masterData.staged,
);

const onlyStaged = staged !== undefined ? staged : true;
if (!onlyStaged) {
resource.masterData.current = updatePriceCustomFields(
resource.masterData.current,
);
}
checkForStagedChanges(resource);
return resource;
}

setProductPriceCustomType(
context: RepositoryContext,
resource: Writable<Product>,
{ type, fields, staged, priceId }: ProductSetProductPriceCustomTypeAction,
) {
const updatePriceCustomType = (data: Writable<ProductData>) => {
const price = [data.masterVariant, ...(data.variants ?? [])]
.flatMap((variant) => variant.prices ?? [])
.find((price) => price.id === priceId);

if (price) {
if (type) {
price.custom = createCustomFields(
{ type, fields },
context.projectKey,
this._storage,
);
} else {
price.custom = undefined;
}
} else {
throw new Error(
`Price with id ${priceId} not found on product ${resource.id}`,
);
}
return data;
};

resource.masterData.staged = updatePriceCustomType(
resource.masterData.staged,
);

const onlyStaged = staged !== undefined ? staged : true;
if (!onlyStaged) {
resource.masterData.current = updatePriceCustomType(
resource.masterData.current,
);
}
checkForStagedChanges(resource);
return resource;
}

setTaxCategory(
context: RepositoryContext,
resource: Writable<Product>,
Expand Down Expand Up @@ -919,8 +1005,6 @@ export class ProductUpdateHandler
}

// 'setPrices': () => {},
// 'setProductPriceCustomType': () => {},
// 'setProductPriceCustomField': () => {},
// 'setDiscountedPrice': () => {},
// 'setAttributeInAllVariants': () => {},
// 'setCategoryOrderHint': () => {},
Expand Down
67 changes: 67 additions & 0 deletions src/services/product.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import type {
StateDraft,
TaxCategory,
TaxCategoryDraft,
Type,
TypeDraft,
} from "@commercetools/platform-sdk";
import assert from "assert";
import supertest from "supertest";
Expand Down Expand Up @@ -78,6 +80,30 @@ const productState2Draft: StateDraft = {
},
};

const productPriceTypeDraft: TypeDraft = {
key: "product-price",
name: {
en: "ProductPriceType",
},
description: {
en: "Product Price Type",
},
resourceTypeIds: ["product-price"],
fieldDefinitions: [
{
name: "lastModifiedAt",
label: {
en: "Last modified at",
},
required: false,
type: {
name: "DateTime",
},
inputHint: "SingleLine",
},
],
};

const publishedProductDraft: ProductDraft = {
name: {
"nl-NL": "test published product",
Expand Down Expand Up @@ -250,6 +276,7 @@ let taxCategory1: TaxCategory;
let taxCategory2: TaxCategory;
let productState1: State;
let productState2: State;
let productPriceType: Type;

async function beforeAllProductTests(mock: CommercetoolsMock) {
let response;
Expand Down Expand Up @@ -308,6 +335,12 @@ async function beforeAllProductTests(mock: CommercetoolsMock) {

expect(response.status).toBe(201);
productState2 = response.body;

response = await supertest(mock.app)
.post("/dummy/types")
.send(productPriceTypeDraft);
expect(response.status).toBe(201);
productPriceType = response.body;
}

describe("Product", () => {
Expand Down Expand Up @@ -1418,4 +1451,38 @@ describe("Product update actions", () => {
id: productState2.id,
});
});

test("setProductPriceCustomField", async () => {
assert(productPublished, "product not created");
const priceId =
productPublished?.masterData.current.masterVariant.prices?.[0].id;
assert(priceId);

const response = await supertest(ctMock.app)
.post(`/dummy/products/${productPublished.id}`)
.send({
version: 1,
actions: [
{
action: "setProductPriceCustomType",
priceId,
type: {
typeId: "type",
key: productPriceType.key,
},
},
{
action: "setProductPriceCustomField",
name: "myCustomField",
value: "MyRandomValue",
priceId,
},
],
});
expect(response.status).toBe(200);
expect(
response.body.masterData.staged.masterVariant.prices?.[0].custom.fields
?.myCustomField,
).toBe("MyRandomValue");
});
});

0 comments on commit be62944

Please sign in to comment.