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
7 changes: 7 additions & 0 deletions .changeset/product-recommendation-rules.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ const expectedNamedExports = [
'computePriceDiff',
'isVariablePrice',
'isVariablePriceItem',
'extractProductRecommendationRuleRelations',
'validateProductRecommendationRules',
];

/**
Expand Down
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
101 changes: 101 additions & 0 deletions src/product-recommendations/extract-rule-relations.test.ts
Original file line number Diff line number Diff line change
@@ -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' }] },
});
});
});
58 changes: 58 additions & 0 deletions src/product-recommendations/extract-rule-relations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type {
ProductRecommendationRelationAttributeValue,
ProductRecommendationRule,
ProductRecommendationRuleRelations,
} from './types';

const createRelationCollector = (schema: 'product' | 'price') => {
const seen = new Set<string>();
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,
};
};
53 changes: 53 additions & 0 deletions src/product-recommendations/types.ts
Original file line number Diff line number Diff line change
@@ -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;
};
Loading
Loading