Policy Engine API
API reference for @guardrail-sim/policy-engine
Policy Engine API
Complete API reference for the @guardrail-sim/policy-engine package.
PolicyEngine
The main class for policy evaluation.
import { PolicyEngine, defaultPolicy } from '@guardrail-sim/policy-engine';
const engine = new PolicyEngine(defaultPolicy);Constructor
new PolicyEngine(policy: Policy)Creates a new policy engine instance with the given policy.
evaluate
Evaluate a discount request against the policy.
async evaluate(order: Order, proposedDiscount: number): Promise<EvaluationResult>Parameters:
- order: Order details including value, quantity, margin, and customer segment
- proposedDiscount: Discount as decimal (0.15 = 15%)
Returns: EvaluationResult with approval status, violations, and calculated margin.
Example:
const result = await engine.evaluate(
{ order_value: 5000, quantity: 100, product_margin: 0.4 },
0.12
);
if (result.approved) {
console.log(`Approved! Margin: ${result.calculated_margin}`);
} else {
console.log('Violations:', result.violations);
}getPolicy
Get the current policy.
getPolicy(): PolicycalculateAllocations
Calculate how a discount should be allocated across line items.
function calculateAllocations(
discountAmount: number,
lineItems: LineItem[],
method?: 'across' | 'each'
): Allocation[];Parameters:
- discountAmount: Total discount amount
- lineItems: Array of line items with subtotals
- method: Allocation method ('across' proportionally, 'each' evenly)
Returns: Array of allocations per line item.
Example:
import { calculateAllocations } from '@guardrail-sim/policy-engine';
const allocations = calculateAllocations(
100, // $100 discount
[
{ item_id: 'A', subtotal: 300 },
{ item_id: 'B', subtotal: 200 },
],
'across'
);
// [{ item_id: 'A', amount: 60 }, { item_id: 'B', amount: 40 }]calculateMaxDiscount
Calculate the maximum allowed discount for an order.
function calculateMaxDiscount(order: Order, options?: { policy?: Policy }): number;Returns: Maximum discount as decimal.
defaultPolicy
Pre-configured policy with standard B2B pricing rules.
import { defaultPolicy } from '@guardrail-sim/policy-engine';Includes:
- margin_floor: 15% minimum margin
- max_discount: 25% maximum discount
- volume_tier: 10% base, 15% for orders >= 100 units
getUCPErrorCode
Map a policy violation to a UCP-compatible error code.
function getUCPErrorCode(violationRule: string): UCPErrorCode;Example:
import { getUCPErrorCode } from '@guardrail-sim/policy-engine';
const code = getUCPErrorCode('margin_floor');
// 'discount_code_invalid'VIOLATION_TO_UCP_ERROR
Mapping of violation rules to UCP error codes.
const VIOLATION_TO_UCP_ERROR: Record<string, UCPErrorCode> = {
max_discount: 'discount_code_invalid',
margin_floor: 'discount_code_invalid',
volume_tier: 'discount_code_user_ineligible',
stacking_not_allowed: 'discount_code_combination_disallowed',
discount_expired: 'discount_code_expired',
login_required: 'discount_code_user_not_logged_in',
// ...
};