onroute-policy-engine 0.8.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,7 +31,7 @@ jobs:
31
31
  run: npm install # Installs project dependencies
32
32
 
33
33
  - name: Lint code
34
- run: npx eslint . --config .eslintrc.cjs # Run ESLint with the specified config
34
+ run: npx eslint "{src,apps,libs,test}/**/*.ts" # Run ESLint with the specified config
35
35
 
36
36
 
37
37
  # https://github.com/marketplace/actions/aqua-security-trivy
@@ -3,5 +3,6 @@ export declare enum ValidationResultCode {
3
3
  FieldValidationError = "field-validation-error",
4
4
  ConfigurationInvalid = "configuration-invalid",
5
5
  GeneralResult = "general-result",
6
- CostValue = "cost-value"
6
+ CostValue = "cost-value",
7
+ IsLcvCarrier = "lcv-carrier"
7
8
  }
@@ -8,4 +8,5 @@ var ValidationResultCode;
8
8
  ValidationResultCode["ConfigurationInvalid"] = "configuration-invalid";
9
9
  ValidationResultCode["GeneralResult"] = "general-result";
10
10
  ValidationResultCode["CostValue"] = "cost-value";
11
+ ValidationResultCode["IsLcvCarrier"] = "lcv-carrier";
11
12
  })(ValidationResultCode || (exports.ValidationResultCode = ValidationResultCode = {}));
@@ -56,11 +56,33 @@ function addRuntimeFacts(engine, policy) {
56
56
  isValid = policy.isConfigurationValid(permitType, commodity, fullVehicleConfiguration);
57
57
  }
58
58
  catch (e) {
59
- console.log(`Error validating vehicle configuration: '{e.message}'`);
59
+ console.log(`Error validating vehicle configuration: '${e.message}'`);
60
60
  isValid = false;
61
61
  }
62
62
  return isValid;
63
63
  });
64
+ /**
65
+ * Add runtime fact to get the list of allowed vehicles taking into
66
+ * consideration a client special authorization lcv flag.
67
+ */
68
+ engine.addFact(enum_1.PolicyFacts.AllowedVehicles.toString(), async function (params, almanac) {
69
+ let allowedVehicles = [];
70
+ const permitTypeId = (await almanac.factValue(enum_1.PermitAppInfo.PermitType));
71
+ const permitType = policy.getPermitTypeDefinition(permitTypeId);
72
+ if (permitType) {
73
+ if (permitType.allowedVehicles &&
74
+ permitType.allowedVehicles.length > 0) {
75
+ allowedVehicles = permitType.allowedVehicles;
76
+ // Filter out long combination vehcles if necessary
77
+ if (!policy.specialAuthorizations ||
78
+ !policy.specialAuthorizations.lcv) {
79
+ allowedVehicles =
80
+ policy.filterOutLongCombinationVehicles(allowedVehicles);
81
+ }
82
+ }
83
+ }
84
+ return allowedVehicles;
85
+ });
64
86
  /**
65
87
  * Add runtime fact for a fixed permit cost, the cost supplied
66
88
  * as a parameter.
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getRulesEngines = getRulesEngines;
4
4
  const json_rules_engine_1 = require("json-rules-engine");
5
5
  const custom_operators_1 = require("../rule-operator/custom-operators");
6
- const enum_1 = require("onroute-policy-engine/enum");
7
6
  /**
8
7
  * Gets a json-rules-engine with all onRouteBC custom operators added,
9
8
  * and all policy rules that apply to all permit types added.
@@ -60,16 +59,6 @@ function getRulesEngines(policy) {
60
59
  };
61
60
  engine.addRule(costRule);
62
61
  });
63
- let allowedVehicles;
64
- if (permitType.allowedVehicles && permitType.allowedVehicles.length > 0) {
65
- allowedVehicles = permitType.allowedVehicles;
66
- }
67
- else {
68
- // If no allowed vehicles are specified, none are permitted
69
- allowedVehicles = [];
70
- }
71
- // Each permit type should have a list of allowed vehicles configured.
72
- engine.addFact(enum_1.PolicyFacts.AllowedVehicles.toString(), allowedVehicles);
73
62
  engineMap.set(permitType.id, engine);
74
63
  });
75
64
  return engineMap;
@@ -0,0 +1,8 @@
1
+ import { VehicleTypes } from '../types';
2
+ /**
3
+ * Filters out all LCV vehicles from a supplied list of vehicle IDs.
4
+ * @param vehicleList List of vehicle IDs to filter
5
+ * @param vehicleTypes Configured vehicle types from policy configuration
6
+ * @returns
7
+ */
8
+ export declare function filterOutLcv(vehicleList: Array<string>, vehicleTypes: VehicleTypes): Array<string>;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.filterOutLcv = filterOutLcv;
4
+ /**
5
+ * Filters out all LCV vehicles from a supplied list of vehicle IDs.
6
+ * @param vehicleList List of vehicle IDs to filter
7
+ * @param vehicleTypes Configured vehicle types from policy configuration
8
+ * @returns
9
+ */
10
+ function filterOutLcv(vehicleList, vehicleTypes) {
11
+ const allVehicleTypes = vehicleTypes.powerUnitTypes.concat(vehicleTypes.trailerTypes);
12
+ const filteredList = vehicleList.filter((v) => {
13
+ const vType = allVehicleTypes.find((vt) => vt.id === v);
14
+ if (vType) {
15
+ if (vType.isLcv) {
16
+ return false;
17
+ }
18
+ else {
19
+ return true;
20
+ }
21
+ }
22
+ else {
23
+ console.log(`No configured vehicle type matching '${v}'`);
24
+ return false;
25
+ }
26
+ });
27
+ return filteredList;
28
+ }
@@ -1,10 +1,16 @@
1
1
  import { PolicyDefinition, PermitType, Commodity, SizeDimension, AxleConfiguration, BridgeCalculationResult } from 'onroute-policy-engine/types';
2
2
  import { Engine } from 'json-rules-engine';
3
3
  import { ValidationResults } from './validation-results';
4
+ import { SpecialAuthorizations } from './types/special-authorizations';
4
5
  /** Class representing commercial vehicle policy. */
5
6
  export declare class Policy {
6
7
  /** Object representation of policy definition and rules. */
7
8
  policyDefinition: PolicyDefinition;
9
+ /**
10
+ * Special authorizations granted to a client, used
11
+ * to adjust validations and allowed vehicles for permit types.
12
+ */
13
+ specialAuthorizations?: SpecialAuthorizations | null;
8
14
  /**
9
15
  * Map of json-rules-engine instances, one for each
10
16
  * permit type defined in the permit definition. Keyed
@@ -15,7 +21,13 @@ export declare class Policy {
15
21
  * Creates a new Policy object.
16
22
  * @param definition Policy definition to validate permits against
17
23
  */
18
- constructor(definition: PolicyDefinition);
24
+ constructor(definition: PolicyDefinition, authorizations?: SpecialAuthorizations);
25
+ /**
26
+ * Sets a client's special authorizations to modify the policy validations
27
+ * and permittable vehicles for permit types.
28
+ * @param authorizations Special authorizations for a client
29
+ */
30
+ setSpecialAuthorizations(authorizations: SpecialAuthorizations | null): void;
19
31
  /**
20
32
  * Validates a permit application against the policy definition.
21
33
  * @param permit The permit application to validate against policy
@@ -32,6 +44,13 @@ export declare class Policy {
32
44
  * @returns Map of geographic region IDs to region names.
33
45
  */
34
46
  getGeographicRegions(): Map<string, string>;
47
+ /**
48
+ * Filters out all long combination vehicles from the list of supplied
49
+ * vehicle IDs, based on policy configuration.
50
+ * @param vehicleList List of vehicles to filter
51
+ * @returns Filtered list of vehicles without LCVs
52
+ */
53
+ filterOutLongCombinationVehicles(vehicleList: Array<string>): Array<string>;
35
54
  /**
36
55
  * Gets a list of all configured commodities in the policy definition.
37
56
  * @param permitTypeId Return only commodities valid for this permit type.
@@ -1,4 +1,7 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.Policy = void 0;
4
7
  const lists_helper_1 = require("./helper/lists.helper");
@@ -8,22 +11,50 @@ const validation_result_1 = require("./validation-result");
8
11
  const facts_helper_1 = require("./helper/facts.helper");
9
12
  const enum_1 = require("onroute-policy-engine/enum");
10
13
  const bridge_calculation_helper_1 = require("./helper/bridge-calculation.helper");
14
+ const version_1 = require("./version");
15
+ const valid_1 = __importDefault(require("semver/functions/valid"));
16
+ const lt_1 = __importDefault(require("semver/functions/lt"));
17
+ const major_1 = __importDefault(require("semver/functions/major"));
18
+ const vehicles_helper_1 = require("./helper/vehicles.helper");
11
19
  /** Class representing commercial vehicle policy. */
12
20
  class Policy {
13
21
  /**
14
22
  * Creates a new Policy object.
15
23
  * @param definition Policy definition to validate permits against
16
24
  */
17
- constructor(definition) {
25
+ constructor(definition, authorizations) {
26
+ // Check compatibility of the policy engine with the policy config
27
+ if (!(0, valid_1.default)(version_1.version)) {
28
+ throw new Error(`Cannot determine the version of the policy engine for compatibility: invalid semver: ${version_1.version}`);
29
+ }
30
+ else if (!(0, valid_1.default)(definition.minPEVersion)) {
31
+ throw new Error(`Cannot determine the minimum PE version for the configuration: invalid semver: ${definition.minPEVersion}`);
32
+ }
33
+ else if ((0, lt_1.default)(version_1.version, definition.minPEVersion)) {
34
+ throw new Error(`Current policy engine version is less than minimum version required for policy config: ${version_1.version} > ${definition.minPEVersion}`);
35
+ }
36
+ else if ((0, major_1.default)(version_1.version) > (0, major_1.default)(definition.minPEVersion)) {
37
+ throw new Error(`Current policy config minimum version is at least one major version behind policy engine: major(${definition.minPEVersion}) < major(${version_1.version}))`);
38
+ }
18
39
  this.policyDefinition = definition;
40
+ this.specialAuthorizations = authorizations;
19
41
  this.rulesEngines = (0, rules_engine_helper_1.getRulesEngines)(this);
20
42
  }
43
+ /**
44
+ * Sets a client's special authorizations to modify the policy validations
45
+ * and permittable vehicles for permit types.
46
+ * @param authorizations Special authorizations for a client
47
+ */
48
+ setSpecialAuthorizations(authorizations) {
49
+ this.specialAuthorizations = authorizations;
50
+ }
21
51
  /**
22
52
  * Validates a permit application against the policy definition.
23
53
  * @param permit The permit application to validate against policy
24
54
  * @returns Results of the validation of the permit application
25
55
  */
26
56
  async validate(permit) {
57
+ var _a;
27
58
  const engine = this.rulesEngines.get(permit.permitType);
28
59
  if (!engine) {
29
60
  // If the permit type being validated has no configuration in the
@@ -40,7 +71,12 @@ class Policy {
40
71
  // Run the json-rules-engine against the permit facts
41
72
  const engineResult = await engine.run(permit);
42
73
  // Wrap the json-rules-engine result in a ValidationResult object
43
- return new validation_results_1.ValidationResults(engineResult);
74
+ const validationResults = new validation_results_1.ValidationResults(engineResult);
75
+ // Include an informational message if the client is an LCV carrier
76
+ if ((_a = this.specialAuthorizations) === null || _a === void 0 ? void 0 : _a.lcv) {
77
+ validationResults.information.push(new validation_result_1.ValidationResult(enum_1.ValidationResultType.Information, enum_1.ValidationResultCode.IsLcvCarrier, `Policy validation allowing long combination vahicle permitting for client '${this.specialAuthorizations.clientNumber}'`));
78
+ }
79
+ return validationResults;
44
80
  }
45
81
  }
46
82
  /**
@@ -59,6 +95,15 @@ class Policy {
59
95
  const geographicRegions = (0, lists_helper_1.extractIdentifiedObjects)(this.policyDefinition.geographicRegions);
60
96
  return geographicRegions;
61
97
  }
98
+ /**
99
+ * Filters out all long combination vehicles from the list of supplied
100
+ * vehicle IDs, based on policy configuration.
101
+ * @param vehicleList List of vehicles to filter
102
+ * @returns Filtered list of vehicles without LCVs
103
+ */
104
+ filterOutLongCombinationVehicles(vehicleList) {
105
+ return (0, vehicles_helper_1.filterOutLcv)(vehicleList, this.policyDefinition.vehicleTypes);
106
+ }
62
107
  /**
63
108
  * Gets a list of all configured commodities in the policy definition.
64
109
  * @param permitTypeId Return only commodities valid for this permit type.
@@ -123,7 +168,7 @@ class Policy {
123
168
  * vehicle, and a string common name for the vehicle.
124
169
  */
125
170
  getPermittableVehicleTypes(permitTypeId, commodityId) {
126
- var _a, _b, _c, _d;
171
+ var _a, _b, _c, _d, _e;
127
172
  if (!permitTypeId || !commodityId) {
128
173
  throw new Error('Missing permitTypeId and/or commodityId');
129
174
  }
@@ -150,16 +195,31 @@ class Policy {
150
195
  if (!commodity) {
151
196
  throw new Error(`Commodity id '${commodityId}' is not correctly configured in the policy definition`);
152
197
  }
153
- const puTypeIdsOS = (_b = (_a = commodity.size) === null || _a === void 0 ? void 0 : _a.powerUnits) === null || _b === void 0 ? void 0 : _b.map((p) => p.type);
154
- const trTypeIdsOS = [];
198
+ let puTypeIdsOS = (_b = (_a = commodity.size) === null || _a === void 0 ? void 0 : _a.powerUnits) === null || _b === void 0 ? void 0 : _b.map((p) => p.type);
199
+ let trTypeIdsOS = [];
155
200
  (_d = (_c = commodity.size) === null || _c === void 0 ? void 0 : _c.powerUnits) === null || _d === void 0 ? void 0 : _d.forEach((pu) => {
156
201
  const trForPu = pu.trailers.map((t) => t.type);
157
202
  if (trForPu)
158
- trTypeIdsOS.concat(trForPu);
203
+ trTypeIdsOS === null || trTypeIdsOS === void 0 ? void 0 : trTypeIdsOS.concat(trForPu);
159
204
  });
160
205
  // TODO: implement along with overweight permits. Stub for now.
161
- const puTypeIdsOW = [];
162
- const trTypeIdsOW = [];
206
+ let puTypeIdsOW = [];
207
+ let trTypeIdsOW = [];
208
+ // Remove long combination vehicles if needed
209
+ if (!((_e = this.specialAuthorizations) === null || _e === void 0 ? void 0 : _e.lcv)) {
210
+ if (puTypeIdsOS) {
211
+ puTypeIdsOS = this.filterOutLongCombinationVehicles(puTypeIdsOS);
212
+ }
213
+ if (trTypeIdsOS) {
214
+ trTypeIdsOS = this.filterOutLongCombinationVehicles(trTypeIdsOS);
215
+ }
216
+ if (puTypeIdsOW) {
217
+ puTypeIdsOW = this.filterOutLongCombinationVehicles(puTypeIdsOW);
218
+ }
219
+ if (trTypeIdsOW) {
220
+ trTypeIdsOW = this.filterOutLongCombinationVehicles(trTypeIdsOW);
221
+ }
222
+ }
163
223
  const puTypesOS = (0, lists_helper_1.extractIdentifiedObjects)(this.policyDefinition.vehicleTypes.powerUnitTypes, puTypeIdsOS);
164
224
  const trTypesOS = (0, lists_helper_1.extractIdentifiedObjects)(this.policyDefinition.vehicleTypes.trailerTypes, trTypeIdsOS);
165
225
  const puTypesOW = (0, lists_helper_1.extractIdentifiedObjects)(this.policyDefinition.vehicleTypes.powerUnitTypes, puTypeIdsOW);
@@ -217,7 +277,7 @@ class Policy {
217
277
  * trailers in a single return value (if applicable).
218
278
  */
219
279
  getNextPermittableVehicles(permitTypeId, commodityId, currentConfiguration) {
220
- var _a, _b, _c, _d;
280
+ var _a, _b, _c, _d, _e;
221
281
  if (!permitTypeId || !commodityId || !currentConfiguration) {
222
282
  throw new Error('Missing permitTypeId and/or commodityId and/or currentConfiguration');
223
283
  }
@@ -285,6 +345,12 @@ class Policy {
285
345
  }
286
346
  }
287
347
  }
348
+ // Remove long combination vehicles if required
349
+ if (!((_e = this.specialAuthorizations) === null || _e === void 0 ? void 0 : _e.lcv)) {
350
+ if (vehicleTypeIds) {
351
+ vehicleTypeIds = this.filterOutLongCombinationVehicles(vehicleTypeIds);
352
+ }
353
+ }
288
354
  vehicleTypes = (0, lists_helper_1.extractIdentifiedObjects)(allVehicles, vehicleTypeIds);
289
355
  return vehicleTypes;
290
356
  }
@@ -327,6 +393,15 @@ class Policy {
327
393
  // invalid as a complete configuration.
328
394
  return validatePartial;
329
395
  }
396
+ if (!this.specialAuthorizations || !this.specialAuthorizations.lcv) {
397
+ // No provision for allowing long combination vehicles
398
+ const filteredConfiguration = this.filterOutLongCombinationVehicles(currentConfiguration);
399
+ if (filteredConfiguration.length !== currentConfiguration.length) {
400
+ // There is an LCV in the configuration, but we are not allowing
401
+ // LCV permitting. Return false.
402
+ return false;
403
+ }
404
+ }
330
405
  const powerUnit = (_b = (_a = commodity.size) === null || _a === void 0 ? void 0 : _a.powerUnits) === null || _b === void 0 ? void 0 : _b.find((p) => p.type == currentConfiguration[0]);
331
406
  if (!powerUnit) {
332
407
  // The power unit is not allowed for the commodity
@@ -13,6 +13,7 @@ export { Matrix, RangeMatrix } from './range-matrix';
13
13
  export { RegionSizeOverride } from './region-size-override';
14
14
  export { SelfIssuable } from './self-issuable';
15
15
  export { SizeDimension } from './size-dimension';
16
+ export { SpecialAuthorizations } from './special-authorizations';
16
17
  export { VehicleCategory, PowerUnitCategory, TrailerCategory, VehicleCategories, } from './vehicle-category';
17
18
  export { VehicleType, PowerUnitType, TrailerType, VehicleTypes, } from './vehicle-type';
18
19
  export { Vehicle, VehicleSizeConfiguration, TrailerSize, PowerUnitWeight, TrailerWeight, } from './vehicle';
@@ -1,7 +1,7 @@
1
1
  import { GeographicRegion, PermitType, DefaultWeightDimensions, VehicleTypes, Commodity, SizeDimension, VehicleCategories, RangeMatrix, BridgeCalculationConstants } from 'onroute-policy-engine/types';
2
2
  import { RuleProperties } from 'json-rules-engine';
3
3
  export type PolicyDefinition = {
4
- version: string;
4
+ minPEVersion: string;
5
5
  geographicRegions: Array<GeographicRegion>;
6
6
  permitTypes: Array<PermitType>;
7
7
  commonRules: Array<RuleProperties>;
@@ -0,0 +1,5 @@
1
+ export type SpecialAuthorizations = {
2
+ clientNumber: string;
3
+ lcv?: boolean;
4
+ noFee?: boolean;
5
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -3,6 +3,7 @@ export type VehicleType = IdentifiedObject & {
3
3
  category: string;
4
4
  defaultSizeDimensions?: SizeDimension;
5
5
  ignoreForSizeDimensions?: boolean;
6
+ isLcv?: boolean;
6
7
  };
7
8
  export type PowerUnitType = VehicleType & {
8
9
  defaultWeightDimensions?: Array<PowerUnitWeightDimension>;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "v0.8.1";
1
+ export declare const version = "v1.1.0";
package/dist/version.js CHANGED
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.version = void 0;
4
4
  // Generated by genversion.
5
- exports.version = 'v0.8.1';
5
+ exports.version = 'v1.1.0';
@@ -0,0 +1,46 @@
1
+ import typescriptEslint from "@typescript-eslint/eslint-plugin";
2
+ import globals from "globals";
3
+ import tsParser from "@typescript-eslint/parser";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import js from "@eslint/js";
7
+ import { FlatCompat } from "@eslint/eslintrc";
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+ const compat = new FlatCompat({
12
+ baseDirectory: __dirname,
13
+ recommendedConfig: js.configs.recommended,
14
+ allConfig: js.configs.all
15
+ });
16
+
17
+ export default [{
18
+ ignores: ["**/.eslintrc.cjs", "**/node_modules/", "**/dist/", "**/.eslintrc.cjs"],
19
+ }, ...compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"), {
20
+ plugins: {
21
+ "@typescript-eslint": typescriptEslint,
22
+ },
23
+
24
+ languageOptions: {
25
+ globals: {
26
+ ...globals.node,
27
+ ...globals.jest,
28
+ },
29
+
30
+ parser: tsParser,
31
+ ecmaVersion: 5,
32
+ sourceType: "module",
33
+
34
+ parserOptions: {
35
+ project: ["./tsconfig.json"],
36
+ tsconfigRootDir: __dirname,
37
+ },
38
+ },
39
+
40
+ rules: {
41
+ "@typescript-eslint/no-explicit-any": "off",
42
+ },
43
+ },
44
+ {
45
+ ignores: ["node_modules/*", "dist/*"]
46
+ }];
package/package.json CHANGED
@@ -38,22 +38,24 @@
38
38
  "license": "Apache-2.0",
39
39
  "homepage": "https://github.com/bcgov/onroutebc-policy-engine#readme",
40
40
  "devDependencies": {
41
- "@iwsio/json-csv-core": "^1.1.7",
42
- "@types/jest": "^29.5.12",
43
- "@typescript-eslint/eslint-plugin": "^7.5.0",
44
- "csv": "^6.3.10",
45
- "eslint": "^8.57.0",
41
+ "@iwsio/json-csv-core": "^1.2.0",
42
+ "@types/jest": "^29.5.14",
43
+ "@types/semver": "^7.5.8",
44
+ "@typescript-eslint/eslint-plugin": "^8.17.0",
45
+ "csv": "^6.3.11",
46
+ "eslint": "^9.16.0",
46
47
  "eslint-config-prettier": "^9.1.0",
47
48
  "genversion": "^3.2.0",
48
49
  "jest": "^29.7.0",
49
- "prettier": "^3.2.5",
50
- "rimraf": "^5.0.7",
51
- "ts-jest": "^29.1.2",
52
- "typescript": "^5.4.3"
50
+ "prettier": "^3.4.2",
51
+ "rimraf": "^6.0.1",
52
+ "ts-jest": "^29.2.5",
53
+ "typescript": "^5.7.2"
53
54
  },
54
55
  "dependencies": {
55
- "dayjs": "^1.11.10",
56
- "json-rules-engine": "^6.5.0"
56
+ "dayjs": "^1.11.13",
57
+ "json-rules-engine": "^7.2.1",
58
+ "semver": "^7.6.3"
57
59
  },
58
60
  "jest": {
59
61
  "moduleFileExtensions": [
@@ -87,5 +89,5 @@
87
89
  ],
88
90
  "testEnvironment": "node"
89
91
  },
90
- "version": "v0.8.1"
92
+ "version": "v1.1.0"
91
93
  }