diff --git a/.changeset/product-recommendation-rules.md b/.changeset/product-recommendation-rules.md new file mode 100644 index 0000000..56dc0d3 --- /dev/null +++ b/.changeset/product-recommendation-rules.md @@ -0,0 +1,7 @@ +--- +'@epilot/pricing': minor +--- + +Add `extractProductRecommendationRuleRelations` and `validateProductRecommendationRules` (plus `ProductRecommendationRule`, `ProductRecommendationOfferGroup` and `ProductRecommendationOfferItem` types) to derive the `source_products`/`source_prices`/`offer_products`/`offer_prices` relations of a `product_recommendation` entity from its rule table and validate it before saving. + +The rule table types (`ProductRecommendationRule`, `ProductRecommendationOfferGroup`) come from the pricing API spec via `@epilot/sdk/pricing` and are re-exported; `ProductRecommendationOfferItem` is derived from them. The `@epilot/sdk` peer dependency is raised to `^2.20.115`, the first version that ships these types. diff --git a/package.json b/package.json index e768924..548891c 100644 --- a/package.json +++ b/package.json @@ -67,13 +67,13 @@ "dinero.js": "^1.9.1" }, "peerDependencies": { - "@epilot/sdk": "^2.19.3", + "@epilot/sdk": "^2.20.115", "i18next": "^25.1.2" }, "devDependencies": { "@changesets/cli": "^2.30.0", "@epilot/eslint-config": "^3.0.5", - "@epilot/sdk": "^2.19.3", + "@epilot/sdk": "^2.20.115", "@types/dinero.js": "^1.9.4", "@vitest/coverage-v8": "^1.6.1", "concurrently": "^9.1.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2f4b9ca..8bb3ba5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -19,8 +19,8 @@ importers: specifier: ^3.0.5 version: 3.0.5(eslint@9.28.0)(typescript@5.8.3) '@epilot/sdk': - specifier: ^2.19.3 - version: 2.19.3(@material-ui/core@4.12.4(@types/react@17.0.93)(react-dom@17.0.2(react@17.0.2))(react@17.0.2))(axios@1.9.0)(js-yaml@4.1.1)(openapi-client-axios@7.8.0(axios@1.9.0)(js-yaml@4.1.1)) + specifier: ^2.20.115 + version: 2.20.115(@material-ui/core@4.12.4(@types/react@17.0.93)(react-dom@17.0.2(react@17.0.2))(react@17.0.2))(axios@1.9.0)(js-yaml@4.1.1)(openapi-client-axios@7.8.0(axios@1.9.0)(js-yaml@4.1.1)) '@types/dinero.js': specifier: ^1.9.4 version: 1.9.4 @@ -177,8 +177,8 @@ packages: peerDependencies: axios: ^1.0.0 || >=0.25.0 <1.0.0 - '@epilot/sdk@2.19.3': - resolution: {integrity: sha512-j4+98+obHJ2vmHklDR3SvL589j8yE/vyStGF6h8m07rGIQs6UWpXBOUU0N8OGnzWCPItGJ7JXmU1pI6s/mIHXg==} + '@epilot/sdk@2.20.115': + resolution: {integrity: sha512-74Rn12kFx39KwI+pA3wHkP79jHJymaSLZ7IVVvUMmKlBd9suuOhDjy0BOUoEIUKCsbiYS2P/CU9sPDOaDalcDw==} hasBin: true peerDependencies: axios: ^1.0.0 @@ -2985,7 +2985,7 @@ snapshots: - js-yaml optional: true - '@epilot/sdk@2.19.3(@material-ui/core@4.12.4(@types/react@17.0.93)(react-dom@17.0.2(react@17.0.2))(react@17.0.2))(axios@1.9.0)(js-yaml@4.1.1)(openapi-client-axios@7.8.0(axios@1.9.0)(js-yaml@4.1.1))': + '@epilot/sdk@2.20.115(@material-ui/core@4.12.4(@types/react@17.0.93)(react-dom@17.0.2(react@17.0.2))(react@17.0.2))(axios@1.9.0)(js-yaml@4.1.1)(openapi-client-axios@7.8.0(axios@1.9.0)(js-yaml@4.1.1))': dependencies: axios: 1.9.0 openapi-client-axios: 7.8.0(axios@1.9.0)(js-yaml@4.1.1) diff --git a/src/exports.test.ts b/src/exports.test.ts index 34e202d..a062fc3 100644 --- a/src/exports.test.ts +++ b/src/exports.test.ts @@ -39,6 +39,8 @@ const expectedNamedExports = [ 'computePriceDiff', 'isVariablePrice', 'isVariablePriceItem', + 'extractProductRecommendationRuleRelations', + 'validateProductRecommendationRules', ]; /** diff --git a/src/index.ts b/src/index.ts index 9d2ef9e..3fd0ad5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -42,3 +42,14 @@ export { getTaxValue } from './taxes/get-tax-value'; export { getAmountWithTax } from './taxes/get-amount-with-tax'; export { computePriceDiff } from './prices/compute-price-diff'; export type { PriceDiff, PriceDiffFormat, PriceDiffOptions } from './prices/compute-price-diff'; +export { extractProductRecommendationRuleRelations } from './product-recommendations/extract-rule-relations'; +export { validateProductRecommendationRules } from './product-recommendations/validate-rules'; +export type { + ProductRecommendationRule, + ProductRecommendationOfferGroup, + ProductRecommendationOfferItem, + ProductRecommendationRelationAttributeValue, + ProductRecommendationRuleRelations, + ProductRecommendationRuleValidationError, + ProductRecommendationRuleValidationErrorCode, +} from './product-recommendations/types'; diff --git a/src/product-recommendations/extract-rule-relations.test.ts b/src/product-recommendations/extract-rule-relations.test.ts new file mode 100644 index 0000000..37d8398 --- /dev/null +++ b/src/product-recommendations/extract-rule-relations.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from 'vitest'; +import { extractProductRecommendationRuleRelations } from './extract-rule-relations'; +import type { ProductRecommendationRule } from './types'; + +const empty = { $relation: [] }; + +describe('extractProductRecommendationRuleRelations', () => { + it('returns empty relations when there are no rules', () => { + const expected = { source_products: empty, source_prices: empty, offer_products: empty, offer_prices: empty }; + + expect(extractProductRecommendationRuleRelations()).toStrictEqual(expected); + expect(extractProductRecommendationRuleRelations([])).toStrictEqual(expected); + }); + + it('extracts source and offer relations de-duplicated in order of first appearance', () => { + const rules: ProductRecommendationRule[] = [ + { + id: 'r1', + source: { product_id: 'prod-a', price_id: 'price-a1' }, + offer_groups: [ + { + id: 'g1', + items: [ + { product_id: 'prod-x', price_id: 'price-x1' }, + { product_id: 'prod-y', price_id: 'price-y1', highlight_config: { badge: 'Best' } }, + ], + }, + { id: 'g2', target_id: 't1', items: [{ product_id: 'prod-x', price_id: 'price-x2' }] }, + ], + }, + { + id: 'r2', + source: { product_id: 'prod-a', price_id: 'price-a2' }, + offer_groups: [{ id: 'g3', items: [{ product_id: 'prod-y', price_id: 'price-y1' }] }], + }, + { + id: 'r3', + source: null, + offer_groups: [{ id: 'g4', items: [{ product_id: 'prod-z', price_id: 'price-x1' }] }], + }, + ]; + + expect(extractProductRecommendationRuleRelations(rules)).toStrictEqual({ + source_products: { $relation: [{ entity_id: 'prod-a', _schema: 'product' }] }, + source_prices: { + $relation: [ + { entity_id: 'price-a1', _schema: 'price' }, + { entity_id: 'price-a2', _schema: 'price' }, + ], + }, + offer_products: { + $relation: [ + { entity_id: 'prod-x', _schema: 'product' }, + { entity_id: 'prod-y', _schema: 'product' }, + { entity_id: 'prod-z', _schema: 'product' }, + ], + }, + offer_prices: { + $relation: [ + { entity_id: 'price-x1', _schema: 'price' }, + { entity_id: 'price-y1', _schema: 'price' }, + { entity_id: 'price-x2', _schema: 'price' }, + ], + }, + }); + }); + + it('returns empty source relations for a fallback-only table', () => { + const rules: ProductRecommendationRule[] = [ + { id: 'r1', source: null, offer_groups: [{ id: 'g1', items: [{ product_id: 'prod-x', price_id: 'price-x' }] }] }, + ]; + + const result = extractProductRecommendationRuleRelations(rules); + + expect(result.source_products).toStrictEqual(empty); + expect(result.source_prices).toStrictEqual(empty); + expect(result.offer_products.$relation).toStrictEqual([{ entity_id: 'prod-x', _schema: 'product' }]); + expect(result.offer_prices.$relation).toStrictEqual([{ entity_id: 'price-x', _schema: 'price' }]); + }); + + it('skips missing ids and empty offer groups', () => { + const rules = [ + { + id: 'r1', + source: { product_id: 'prod-a', price_id: '' }, + offer_groups: [ + { id: 'g1', items: [] }, + { id: 'g2', items: [{ product_id: '', price_id: 'price-x' }] }, + ], + }, + { id: 'r2', source: null, offer_groups: [] }, + ] as ProductRecommendationRule[]; + + expect(extractProductRecommendationRuleRelations(rules)).toStrictEqual({ + source_products: { $relation: [{ entity_id: 'prod-a', _schema: 'product' }] }, + source_prices: empty, + offer_products: empty, + offer_prices: { $relation: [{ entity_id: 'price-x', _schema: 'price' }] }, + }); + }); +}); diff --git a/src/product-recommendations/extract-rule-relations.ts b/src/product-recommendations/extract-rule-relations.ts new file mode 100644 index 0000000..819856f --- /dev/null +++ b/src/product-recommendations/extract-rule-relations.ts @@ -0,0 +1,58 @@ +import type { + ProductRecommendationRelationAttributeValue, + ProductRecommendationRule, + ProductRecommendationRuleRelations, +} from './types'; + +const createRelationCollector = (schema: 'product' | 'price') => { + const seen = new Set(); + const value: ProductRecommendationRelationAttributeValue = { $relation: [] }; + + return { + add: (entityId?: string | null) => { + if (!entityId || seen.has(entityId)) { + return; + } + seen.add(entityId); + value.$relation.push({ entity_id: entityId, _schema: schema }); + }, + value, + }; +}; + +/** + * Derives the relation attributes of a `product_recommendation` entity from its rule table, + * the same way `extractPricingEntitiesBySlug` derives product/price relations from line items. + * + * Relations are de-duplicated and keep the order of first appearance. Missing ids are skipped. + * + * @param rules the rule table of the product recommendation + * @returns `source_products`, `source_prices`, `offer_products` and `offer_prices` relation attribute values + */ +export const extractProductRecommendationRuleRelations = ( + rules?: ProductRecommendationRule[], +): ProductRecommendationRuleRelations => { + const sourceProducts = createRelationCollector('product'); + const sourcePrices = createRelationCollector('price'); + const offerProducts = createRelationCollector('product'); + const offerPrices = createRelationCollector('price'); + + for (const rule of rules ?? []) { + sourceProducts.add(rule?.source?.product_id); + sourcePrices.add(rule?.source?.price_id); + + for (const group of rule?.offer_groups ?? []) { + for (const item of group?.items ?? []) { + offerProducts.add(item?.product_id); + offerPrices.add(item?.price_id); + } + } + } + + return { + source_products: sourceProducts.value, + source_prices: sourcePrices.value, + offer_products: offerProducts.value, + offer_prices: offerPrices.value, + }; +}; diff --git a/src/product-recommendations/types.ts b/src/product-recommendations/types.ts new file mode 100644 index 0000000..a31eece --- /dev/null +++ b/src/product-recommendations/types.ts @@ -0,0 +1,53 @@ +import type { ProductRecommendationOfferGroup, ProductRecommendationRule } from '@epilot/sdk/pricing'; + +/** + * The rule table types come from the pricing API spec (`@epilot/sdk/pricing`): + * - `ProductRecommendationRule`: a row; customers on the `source` product + price are offered the items of + * the `offer_groups`. `source: null` marks the fallback rule ("any other product"). + * - `ProductRecommendationOfferGroup`: the API's `Offer` plus an `id`; `target_id` absent = everyone on the + * rule's source tariff. + */ +export type { ProductRecommendationOfferGroup, ProductRecommendationRule }; + +/** + * A product + price offered to customers matched by a product recommendation rule (incl. its `highlight_config`). + */ +export type ProductRecommendationOfferItem = ProductRecommendationOfferGroup['items'][number]; + +/** + * A has_many relation attribute value. + */ +export type ProductRecommendationRelationAttributeValue = { + $relation: { entity_id: string; _schema: 'product' | 'price' }[]; +}; + +/** + * The relation attributes of a `product_recommendation` entity derived from its rules. + */ +export type ProductRecommendationRuleRelations = { + /** Products of all rule sources. */ + source_products: ProductRecommendationRelationAttributeValue; + /** Prices of all rule sources. */ + source_prices: ProductRecommendationRelationAttributeValue; + /** Products of all offer items. */ + offer_products: ProductRecommendationRelationAttributeValue; + /** Prices of all offer items. */ + offer_prices: ProductRecommendationRelationAttributeValue; +}; + +export type ProductRecommendationRuleValidationErrorCode = + | 'RULES_REQUIRED' + | 'RULE_SOURCE_REQUIRED' + | 'DUPLICATE_SOURCE' + | 'MULTIPLE_FALLBACKS' + | 'OFFERS_REQUIRED' + | 'OFFER_IS_OWN_SOURCE' + | 'DUPLICATE_RULE_ID'; + +export type ProductRecommendationRuleValidationError = { + code: ProductRecommendationRuleValidationErrorCode; + rule_id?: string; + offer_group_id?: string; + item_index?: number; + message: string; +}; diff --git a/src/product-recommendations/validate-rules.test.ts b/src/product-recommendations/validate-rules.test.ts new file mode 100644 index 0000000..198b70f --- /dev/null +++ b/src/product-recommendations/validate-rules.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it } from 'vitest'; +import type { ProductRecommendationRule } from './types'; +import { validateProductRecommendationRules } from './validate-rules'; + +const offer = (id = 'g1', productId = 'prod-x', priceId = 'price-x') => ({ + id, + items: [{ product_id: productId, price_id: priceId }], +}); + +const rule = ( + id: string, + source: ProductRecommendationRule['source'], + offerGroups = [offer(`${id}-g1`)], +): ProductRecommendationRule => ({ id, source, offer_groups: offerGroups }); + +const codes = (rules?: ProductRecommendationRule[]) => validateProductRecommendationRules(rules).map((e) => e.code); + +describe('validateProductRecommendationRules', () => { + it('returns no errors for a valid rule table', () => { + const rules = [ + rule('r1', { product_id: 'prod-a', price_id: 'price-a' }), + rule('r2', { product_id: 'prod-a', price_id: 'price-b' }, [offer('g2'), { ...offer('g3'), target_id: 't1' }]), + rule('r3', null), + ]; + + expect(validateProductRecommendationRules(rules)).toStrictEqual([]); + }); + + it('accepts a fallback-only rule table', () => { + expect(validateProductRecommendationRules([rule('r1', null)])).toStrictEqual([]); + }); + + it.each([undefined, []])('requires at least one rule (%s)', (rules) => { + expect(validateProductRecommendationRules(rules)).toStrictEqual([ + { code: 'RULES_REQUIRED', message: 'Add at least one rule.' }, + ]); + }); + + it.each([ + { product_id: 'prod-a', price_id: '' }, + { product_id: '', price_id: 'price-a' }, + ])('requires a complete source %o', (source) => { + expect(validateProductRecommendationRules([rule('r1', source)])).toStrictEqual([ + expect.objectContaining({ code: 'RULE_SOURCE_REQUIRED', rule_id: 'r1' }), + ]); + }); + + it('rejects duplicate sources on the later rule', () => { + const rules = [ + rule('r1', { product_id: 'prod-a', price_id: 'price-a' }), + rule('r2', { product_id: 'prod-a', price_id: 'price-a' }), + ]; + + expect(validateProductRecommendationRules(rules)).toStrictEqual([ + expect.objectContaining({ code: 'DUPLICATE_SOURCE', rule_id: 'r2', message: expect.stringContaining('"r1"') }), + ]); + }); + + it('allows the same source product with different prices', () => { + const rules = [ + rule('r1', { product_id: 'prod-a', price_id: 'price-a' }), + rule('r2', { product_id: 'prod-a', price_id: 'price-b' }), + ]; + + expect(codes(rules)).toStrictEqual([]); + }); + + it('allows only one fallback', () => { + const rules = [rule('r1', null), rule('r2', null), rule('r3', null)]; + + expect(validateProductRecommendationRules(rules)).toStrictEqual([ + expect.objectContaining({ code: 'MULTIPLE_FALLBACKS', rule_id: 'r2' }), + expect.objectContaining({ code: 'MULTIPLE_FALLBACKS', rule_id: 'r3' }), + ]); + }); + + it('requires offer groups', () => { + expect(validateProductRecommendationRules([rule('r1', null, [])])).toStrictEqual([ + expect.objectContaining({ code: 'OFFERS_REQUIRED', rule_id: 'r1' }), + ]); + }); + + it('requires items in every offer group', () => { + const rules = [rule('r1', null, [offer('g1'), { id: 'g2', items: [] }])]; + + expect(validateProductRecommendationRules(rules)).toStrictEqual([ + expect.objectContaining({ code: 'OFFERS_REQUIRED', rule_id: 'r1', offer_group_id: 'g2' }), + ]); + }); + + it('requires a product and a price on every offer item', () => { + const rules = [ + rule('r1', null, [ + { + id: 'g1', + items: [ + { product_id: 'prod-x', price_id: 'price-x' }, + { product_id: 'prod-y', price_id: '' }, + ], + }, + ]), + ]; + + expect(validateProductRecommendationRules(rules)).toStrictEqual([ + expect.objectContaining({ code: 'OFFERS_REQUIRED', rule_id: 'r1', offer_group_id: 'g1', item_index: 1 }), + ]); + }); + + it('rejects a rule offering its own source', () => { + const rules = [ + rule('r1', { product_id: 'prod-a', price_id: 'price-a' }, [ + { id: 'g1', items: [{ product_id: 'prod-a', price_id: 'price-b' }] }, + { + id: 'g2', + items: [ + { product_id: 'prod-x', price_id: 'price-x' }, + { product_id: 'prod-a', price_id: 'price-a' }, + ], + }, + ]), + ]; + + expect(validateProductRecommendationRules(rules)).toStrictEqual([ + expect.objectContaining({ code: 'OFFER_IS_OWN_SOURCE', rule_id: 'r1', offer_group_id: 'g2', item_index: 1 }), + ]); + }); + + it('rejects duplicate rule ids', () => { + const rules = [ + rule('r1', { product_id: 'prod-a', price_id: 'price-a' }), + rule('r1', { product_id: 'prod-b', price_id: 'price-b' }), + ]; + + expect(validateProductRecommendationRules(rules)).toStrictEqual([ + expect.objectContaining({ code: 'DUPLICATE_RULE_ID', rule_id: 'r1' }), + ]); + }); + + it('reports every problem in one pass', () => { + const rules = [ + rule('r1', { product_id: 'prod-a', price_id: 'price-a' }, [offer('g1', 'prod-a', 'price-a')]), + rule('r1', { product_id: 'prod-a', price_id: 'price-a' }, []), + rule('r2', null), + rule('r3', null, [{ id: 'g9', items: [] }]), + ]; + + expect(codes(rules)).toStrictEqual([ + 'OFFER_IS_OWN_SOURCE', + 'DUPLICATE_RULE_ID', + 'DUPLICATE_SOURCE', + 'OFFERS_REQUIRED', + 'MULTIPLE_FALLBACKS', + 'OFFERS_REQUIRED', + ]); + }); +}); diff --git a/src/product-recommendations/validate-rules.ts b/src/product-recommendations/validate-rules.ts new file mode 100644 index 0000000..127bc31 --- /dev/null +++ b/src/product-recommendations/validate-rules.ts @@ -0,0 +1,118 @@ +import type { ProductRecommendationRule, ProductRecommendationRuleValidationError } from './types'; + +const toSourceKey = (productId: string, priceId: string) => `${productId}:${priceId}`; + +/** + * Validates the rule table of a `product_recommendation` entity. + * + * Pure and synchronous: it only checks the structure of the rules. Checking that referenced + * products and prices exist and are not archived or deleted is the caller's job. + * + * Error codes: + * - `RULES_REQUIRED`: there are no rules + * - `DUPLICATE_RULE_ID`: two rules share the same id + * - `RULE_SOURCE_REQUIRED`: a source has a product but no price, or a price but no product (a fallback rule is `source: null`) + * - `MULTIPLE_FALLBACKS`: more than one rule has `source: null` + * - `DUPLICATE_SOURCE`: two rules have the same source product + price + * - `OFFERS_REQUIRED`: a rule has no offer groups, an offer group has no items, or an offer item lacks a product or price + * - `OFFER_IS_OWN_SOURCE`: a rule offers its own source product + price + * + * @param rules the rule table of the product recommendation + * @returns the validation errors; an empty array means the rules are valid + */ +export const validateProductRecommendationRules = ( + rules?: ProductRecommendationRule[], +): ProductRecommendationRuleValidationError[] => { + if (!rules?.length) { + return [{ code: 'RULES_REQUIRED', message: 'Add at least one rule.' }]; + } + + const errors: ProductRecommendationRuleValidationError[] = []; + const seenRuleIds = new Set(); + const ruleIdBySource = new Map(); + let fallbackRuleId: string | undefined; + + for (const rule of rules) { + const ruleId = rule.id; + + if (seenRuleIds.has(ruleId)) { + errors.push({ + code: 'DUPLICATE_RULE_ID', + rule_id: ruleId, + message: `Rule id "${ruleId}" is used more than once.`, + }); + } + seenRuleIds.add(ruleId); + + const source = rule.source; + let sourceKey: string | undefined; + + if (!source) { + if (fallbackRuleId !== undefined) { + errors.push({ code: 'MULTIPLE_FALLBACKS', rule_id: ruleId, message: 'Only one fallback rule is allowed.' }); + } else { + fallbackRuleId = ruleId; + } + } else if (!source.product_id || !source.price_id) { + errors.push({ + code: 'RULE_SOURCE_REQUIRED', + rule_id: ruleId, + message: 'Select both a source product and a source price.', + }); + } else { + sourceKey = toSourceKey(source.product_id, source.price_id); + const firstRuleId = ruleIdBySource.get(sourceKey); + if (firstRuleId !== undefined) { + errors.push({ + code: 'DUPLICATE_SOURCE', + rule_id: ruleId, + message: `This source product and price is already used by rule "${firstRuleId}".`, + }); + } else { + ruleIdBySource.set(sourceKey, ruleId); + } + } + + const offerGroups = rule.offer_groups ?? []; + if (!offerGroups.length) { + errors.push({ code: 'OFFERS_REQUIRED', rule_id: ruleId, message: 'Add at least one offer.' }); + } + + for (const group of offerGroups) { + const items = group?.items ?? []; + if (!items.length) { + errors.push({ + code: 'OFFERS_REQUIRED', + rule_id: ruleId, + offer_group_id: group?.id, + message: 'Add at least one offer to this group.', + }); + } + + items.forEach((item, itemIndex) => { + if (!item?.product_id || !item?.price_id) { + errors.push({ + code: 'OFFERS_REQUIRED', + rule_id: ruleId, + offer_group_id: group?.id, + item_index: itemIndex, + message: 'Select both a product and a price for this offer.', + }); + return; + } + + if (sourceKey && toSourceKey(item.product_id, item.price_id) === sourceKey) { + errors.push({ + code: 'OFFER_IS_OWN_SOURCE', + rule_id: ruleId, + offer_group_id: group?.id, + item_index: itemIndex, + message: 'A rule cannot offer its own source product and price.', + }); + } + }); + } + } + + return errors; +};