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/accept-untyped-money-draft.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@labdigital/commercetools-mock": patch
---

Accept Money without type where TypedMoneyDraft is expected
45 changes: 45 additions & 0 deletions scripts/generate-schemas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1253,4 +1253,49 @@ describe("patchSpec", () => {
type: "string",
});
});

it("makes the type of a TypedMoneyDraft optional", () => {
// Mirrors the spec: the required `type` sits on an allOf part.
const schemas: Record<string, OpenAPISchema> = {
Money: {
type: "object",
required: ["centAmount", "currencyCode"],
properties: {
centAmount: { type: "integer" },
currencyCode: { type: "string" },
},
},
MoneyType: {
type: "string",
enum: ["centPrecision", "highPrecision"],
},
TypedMoneyDraft: {
allOf: [
{ $ref: "#/components/schemas/Money" },
{
type: "object",
required: ["type"],
properties: {
centAmount: { type: "integer" },
currencyCode: { type: "string" },
type: { $ref: "#/components/schemas/MoneyType" },
},
},
],
},
};

patchSpec(schemas);

const result = generateObjectSchema(
schemas,
"TypedMoneyDraft",
schemas.TypedMoneyDraft,
);
expect(result).toContain("centAmount: z.number().int(),");
expect(result).toContain("currencyCode: z.string(),");
expect(result).toContain("type: MoneyTypeSchema.nullish(),");
// Money itself is shared with other schemas and stays untouched.
expect(schemas.Money.required).toEqual(["centAmount", "currencyCode"]);
});
});
29 changes: 27 additions & 2 deletions scripts/generate-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ const EXTRA_PROPERTIES: Record<string, Record<string, OpenAPIProperty>> = {
},
};

// ---------------------------------------------------------------------------
// Configuration: properties the spec requires but the API accepts without
// ---------------------------------------------------------------------------
// TypedMoneyDraft is documented with a required `type`, but the API accepts a
// plain Money wherever a TypedMoneyDraft is expected and treats it as
// centPrecision (e.g. the `money` of a fixed CartDiscountValueDraft).
const OPTIONAL_PROPERTIES: Record<string, string[]> = {
TypedMoneyDraft: ["type"],
};

// ---------------------------------------------------------------------------
// Configuration: which draft schemas to generate
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -177,8 +187,9 @@ export interface OpenAPIProperty {
// Spec patching
// ---------------------------------------------------------------------------
/**
* Adds the EXTRA_PROPERTIES to the parsed spec, so the rest of the generator
* sees them as regular properties of their schema.
* Adds the EXTRA_PROPERTIES to the parsed spec and drops the
* OPTIONAL_PROPERTIES from its required lists, so the rest of the generator
* sees them as regular (optional) properties of their schema.
*/
export function patchSpec(schemas: Record<string, OpenAPISchema>) {
for (const [name, properties] of Object.entries(EXTRA_PROPERTIES)) {
Expand All @@ -196,6 +207,20 @@ export function patchSpec(schemas: Record<string, OpenAPISchema>) {
schema.properties = { ...schema.properties, [propName]: propDef };
}
}

for (const [name, propNames] of Object.entries(OPTIONAL_PROPERTIES)) {
const schema = schemas[name];
if (!schema) {
console.warn(` Warning: cannot patch ${name}, not found in spec`);
continue;
}

// `required` can sit on the schema itself or on any of its allOf parts.
for (const part of [schema, ...(schema.allOf ?? [])]) {
if (!part.required) continue;
part.required = part.required.filter((r) => !propNames.includes(r));
}
}
}

// ---------------------------------------------------------------------------
Expand Down
3 changes: 3 additions & 0 deletions src/repositories/standalone-price.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ export class StandAlonePriceRepository extends AbstractResourceRepository<"stand
: undefined,
validFrom: draft.validFrom,
validUntil: draft.validUntil,
staged: draft.staged
? { value: createTypedMoney(draft.staged.value) }
: undefined,
};
return await this.saveNew(context, resource);
}
Expand Down
2 changes: 1 addition & 1 deletion src/schemas/generated/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -870,7 +870,7 @@ export const CartDiscountValueAbsoluteDraftSchema = z.object({
export const TypedMoneyDraftSchema = z.object({
centAmount: z.number().int(),
currencyCode: CurrencyCodeSchema,
type: MoneyTypeSchema,
type: MoneyTypeSchema.nullish(),
fractionDigits: z.number().int().nullish(),
});

Expand Down
138 changes: 138 additions & 0 deletions src/services/draft-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,144 @@ describe("Draft validation (strict mode)", () => {
);
});
});
// The API accepts a plain Money wherever a TypedMoneyDraft is expected and
// treats it as centPrecision.
describe("TypedMoneyDraft", () => {
const cartDiscountDraft = (value: unknown) => ({
cartPredicate: "1=1",
description: {},
isActive: true,
name: { en: "fixed name" },
requiresDiscountCode: false,
sortOrder: "0.9",
stackingMode: "Stacking",
stores: [],
target: { type: "shipping" },
value,
});

test("accepts a fixed cart discount value with plain money", async () => {
const response = await ctMock.app.inject({
method: "POST",
url: "/dummy/cart-discounts",
payload: cartDiscountDraft({
type: "fixed",
money: [
{ centAmount: 1000, currencyCode: "USD" },
{ centAmount: 2000, currencyCode: "EUR" },
],
}),
});
expect(response.statusCode).toBe(201);
expect(response.json().value).toEqual({
type: "fixed",
money: [
{
type: "centPrecision",
centAmount: 1000,
currencyCode: "USD",
fractionDigits: 2,
},
{
type: "centPrecision",
centAmount: 2000,
currencyCode: "EUR",
fractionDigits: 2,
},
],
});
});

test("accepts an absolute cart discount value with plain money", async () => {
const response = await ctMock.app.inject({
method: "POST",
url: "/dummy/cart-discounts",
payload: cartDiscountDraft({
type: "absolute",
money: [{ centAmount: 500, currencyCode: "JPY" }],
}),
});
expect(response.statusCode).toBe(201);
expect(response.json().value).toEqual({
type: "absolute",
money: [
{
type: "centPrecision",
centAmount: 500,
currencyCode: "JPY",
fractionDigits: 0,
},
],
});
});

test("still accepts typed money on a fixed cart discount value", async () => {
const response = await ctMock.app.inject({
method: "POST",
url: "/dummy/cart-discounts",
payload: cartDiscountDraft({
type: "fixed",
money: [
{
type: "highPrecision",
centAmount: 1235,
currencyCode: "EUR",
preciseAmount: 12345,
fractionDigits: 3,
},
],
}),
});
expect(response.statusCode).toBe(201);
expect(response.json().value.money).toEqual([
{
type: "highPrecision",
centAmount: 1235,
currencyCode: "EUR",
fractionDigits: 3,
preciseAmount: 12345,
},
]);
});

test("rejects an unknown money type", async () => {
const response = await ctMock.app.inject({
method: "POST",
url: "/dummy/cart-discounts",
payload: cartDiscountDraft({
type: "fixed",
money: [{ type: "foo", centAmount: 1000, currencyCode: "USD" }],
}),
});
expect(response.statusCode).toBe(400);
const body = response.json();
expect(body.errors[0].code).toBe("InvalidJsonInput");
expect(body.errors[0].detailedErrorMessage).toContain(
"value.money.0.type",
);
});

test("accepts a staged standalone price with plain money", async () => {
const response = await ctMock.app.inject({
method: "POST",
url: "/dummy/standalone-prices",
payload: {
sku: "typed-money-draft",
value: { centAmount: 100, currencyCode: "EUR" },
staged: { value: { centAmount: 90, currencyCode: "EUR" } },
},
});
expect(response.statusCode).toBe(201);
expect(response.json().staged).toEqual({
value: {
type: "centPrecision",
centAmount: 90,
currencyCode: "EUR",
fractionDigits: 2,
},
});
});
});
});

describe("Draft validation (non-strict mode - default)", () => {
Expand Down
Loading