Framework
Take a rule such as “send large orders for review.” The engine first needs the facts about the order, then a condition that can evaluate those facts, and finally an action with an observable outcome. Each part has a different place in the implementation.
The Business Rules module follows Open Mercato's modular architecture pattern, with clear separation between data, services, UI, and API layers.
packages/core/src/modules/business_rules/
├── index.ts # Module metadata
├── acl.ts # RBAC feature definitions
├── di.ts # Dependency injection registrations
├── data/
│ ├── entities.ts # MikroORM entities (4)
│ ├── validators.ts # Zod schemas
│ └── extensions.ts # Entity extensions
├── lib/
│ ├── expression-evaluator.ts # Condition evaluation
│ ├── rule-evaluator.ts # Rule discovery and evaluation
│ ├── action-executor.ts # Action execution
│ ├── rule-engine.ts # Orchestration layer
│ ├── value-resolver.ts # Field and special value resolution
│ └── payload-validation.ts # Server-side validation
├── components/
│ ├── ConditionBuilder.tsx # Visual condition builder
│ ├── ActionBuilder.tsx # Visual action builder
│ └── formConfig.tsx # Form configuration
├── backend/ # Admin UI pages (8)
├── api/ # REST API endpoints (13)
├── migrations/ # Database migrations (3)
├── i18n/ # Translations (EN, PL)
└── __tests__/ # Test suites
The engine uses pure functions over classes for core logic:
Benefits:
Example:
// Pure function - no state, no side effects
export function evaluateExpression(
expression: ConditionExpression,
data: Record<string, any>
): boolean {
// Logic here
return result
}
Conditions and actions are stored as JSONB in PostgreSQL:
Why JSONB:
Trade-offs:
The Business Rules module is self-contained:
This follows Open Mercato's modular architecture principles.
BusinessRule:
RuleExecutionLog:
RuleSet:
RuleSetMember:
Critical indexes for performance:
-- Rule discovery
CREATE INDEX idx_business_rules_entity_event
ON business_rules(entity_type, event_type, enabled);
-- Priority ordering
CREATE INDEX idx_business_rules_priority
ON business_rules(priority DESC, created_at);
-- Tenant isolation
CREATE INDEX idx_business_rules_tenant
ON business_rules(tenant_id, organization_id);
-- Log querying
CREATE INDEX idx_rule_execution_logs_rule
ON rule_execution_logs(rule_id, executed_at DESC);
CREATE INDEX idx_rule_execution_logs_entity
ON rule_execution_logs(entity_type, entity_id, executed_at DESC);
Purpose: Evaluate condition expressions against entity data
Key Functions:
evaluateExpression() - Recursive condition evaluationapplyOperator() - Execute comparison operatorsgetNestedValue() - Resolve field paths with dot notationOperators Implemented (15):
=, ==, !=>, >=, <, <=IN, NOT_IN, CONTAINS, NOT_CONTAINSSTARTS_WITH, ENDS_WITH, MATCHESIS_EMPTY, IS_NOT_EMPTYExample:
const condition = {
operator: 'AND',
rules: [
{ field: 'status', operator: '=', value: 'ACTIVE' },
{ field: 'total', operator: '>', value: 1000 }
]
}
const result = evaluateExpression(condition, {
status: 'ACTIVE',
total: 1500
}) // Returns: true
Purpose: Discover and evaluate applicable rules
Key Functions:
evaluate() - Find and evaluate all applicable rulesevaluateSingleRule() - Evaluate one ruleRule Discovery Algorithm:
Purpose: Execute actions when rule conditions pass/fail
Key Functions:
executeActions() - Execute array of actionsexecuteAction() - Execute single action{{field}} syntaxAction Handlers: Each action type has a dedicated handler function:
async function handleLogAction(action: Action, context: ExecutionContext) {
const { level, message } = action.config
const interpolated = interpolateMessage(message, context.data)
logger.log(level, interpolated)
}
Purpose: High-level orchestration of rule execution
Key Functions:
executeRules() - Main entry point for rule executionfindApplicableRules() - Discover rules to executelogRuleExecution() - Record execution audit trailExecution Flow:
graph TD
A[Execute Request] --> B[Find Applicable Rules]
B --> C[Sort by Priority]
C --> D{For Each Rule}
D --> E[Evaluate Conditions]
E --> F{Conditions Pass?}
F -->|Yes| G[Execute Success Actions]
F -->|No| H[Execute Failure Actions]
G --> I[Log Execution]
H --> I
I --> J{Is GUARD?}
J -->|Yes & Failed| K[Block Operation]
J -->|No or Passed| D
K --> L[Return Blocked]
D -->|Done| M[Return Allowed]
classDef focus fill:#e0f29c,stroke:#34402d,color:#172011,stroke-width:2px
class F focus
Purpose: Resolve field paths and special values
Key Functions:
getNestedValue() - Access nested properties with dot notationresolveSpecialValue() - Replace special {{tokens}} with dynamic valuesSupported Tokens:
{{today}}, {{now}}, {{yesterday}}, {{tomorrow}}{{user.id}}, {{user.email}}, {{user.name}}{{entity.id}}, {{entity.tenantId}}, {{entity.organizationId}}Purpose: Server-side safety checks
Validations:
Prevents:
All queries automatically scoped by tenant_id and organization_id:
const rules = await em.find(BusinessRule, {
entityType,
tenantId, // Injected from auth context
organizationId, // Injected from auth context
enabled: true,
deletedAt: null
})
Keep both tenant and organization scope in any custom query or extension.
Execution logs sanitize sensitive fields (13 patterns):
const SENSITIVE_PATTERNS = [
/password/i, /secret/i, /token/i, /api[_-]?key/i,
/credit[_-]?card/i, /ssn/i, /social[_-]?security/i,
/bank[_-]?account/i, /routing[_-]?number/i,
/pin/i, /cvv/i, /security[_-]?code/i, /private[_-]?key/i
]
Fields matching these patterns are replaced with [REDACTED] in logs.
Every operation checks required features:
// API handler
export const metadata = {
requireAuth: true,
requireFeatures: ['business_rules.rules.create']
}
Features enforced:
business_rules.rules.viewbusiness_rules.rules.createbusiness_rules.rules.editbusiness_rules.rules.deletebusiness_rules.rules.executebusiness_rules.logs.viewStrategic indexes for common query patterns:
Rule data is not cached by default because:
For high-throughput scenarios, consider:
Pure function tests:
describe('evaluateExpression', () => {
it('evaluates simple equality', () => {
const expr = { field: 'status', operator: '=', value: 'ACTIVE' }
const data = { status: 'ACTIVE' }
expect(evaluateExpression(expr, data)).toBe(true)
})
})
Integration tests with ORM:
describe('RuleEngine', () => {
let orm: MikroORM
let em: EntityManager
beforeAll(async () => {
orm = await createTestORM()
em = orm.em.fork()
})
it('executes applicable rules', async () => {
const rule = createTestRule()
await em.persist(rule).flush()
const result = await executeRules({ entityType: 'Order', data: {} })
expect(result.executedRules).toHaveLength(1)
})
})
The engine is designed for extensibility:
Add new comparison operators:
// In expression-evaluator.ts
function applyOperator(field: any, operator: string, value: any): boolean {
switch (operator) {
// Existing operators...
case 'CUSTOM_OP':
return customLogic(field, value)
default:
throw new Error(`Unknown operator: ${operator}`)
}
}
Implement new action types:
// In action-executor.ts
async function executeAction(action: Action, context: ExecutionContext) {
switch (action.type) {
// Existing actions...
case 'CUSTOM_ACTION':
return await handleCustomAction(action, context)
default:
throw new Error(`Unknown action type: ${action.type}`)
}
}
Extend value resolution:
// In value-resolver.ts
function resolveSpecialValue(token: string, context: ExecutionContext): any {
switch (token) {
// Existing tokens...
case '{{custom.value}}':
return getCustomValue(context)
default:
return token
}
}
The module includes 3 migrations:
Migration files: packages/core/src/modules/business_rules/migrations/
Apply migrations:
yarn db:migrate
Every rule execution is logged:
Track these metrics for health monitoring:
Structured logging at key points:
Keep Services Pure: Core evaluation logic should be pure functions
Validate Input: Use Zod schemas for all external data
Handle Errors Gracefully: Rule errors shouldn't crash the system
Test Thoroughly: Unit test all operators and actions
Document Extensions: When adding operators/actions, update docs
Monitor Performance: Track execution times and optimize slow rules
Secure by Default: Always check tenant scope, never expose cross-tenant data