/
RulesetsFactory.ts
306 lines (274 loc) · 11.5 KB
/
RulesetsFactory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Core
*/
import { Guid, Id64, Id64String } from "@itwin/core-bentley";
import { Field, PropertiesField } from "./content/Fields";
import { Item } from "./content/Item";
import { PrimitiveTypeDescription, PropertyValueFormat } from "./content/TypeDescription";
import { DisplayValue, Value } from "./content/Value";
import { ClassInfo, InstanceKey, RelationshipPath } from "./EC";
import { MultiSchemaClassesSpecification, SingleSchemaClassSpecification } from "./rules/ClassSpecifications";
import { ContentSpecificationTypes } from "./rules/content/ContentSpecification";
import { RelatedInstanceSpecification } from "./rules/RelatedInstanceSpecification";
import { RelationshipDirection } from "./rules/RelationshipDirection";
import { RuleTypes } from "./rules/Rule";
import { Ruleset } from "./rules/Ruleset";
/**
* A factory class that can be used to create presentation rulesets targeted towards
* specific use cases.
*
* @public
*/
export class RulesetsFactory {
private createSimilarInstancesRulesetInfo(field: Field, record: Item) {
if (!field.isPropertiesField()) {
throw new Error("Can only create 'similar instances' ruleset for properties-based records");
}
if (field.type.valueFormat !== PropertyValueFormat.Primitive) {
throw new Error("Can only create 'similar instances' ruleset for primitive properties");
}
if (field.properties.length === 0) {
throw new Error("Invalid properties' field with no properties");
}
if (record.isFieldMerged(field.name)) {
throw new Error("Can't create 'similar instances' ruleset for merged values");
}
if (!record.classInfo) {
throw new Error("Can't create 'similar instances' for records based on multiple different ECClass instances");
}
const propertyName = getPropertyName(field);
const propertyValue = getPropertyValue(record, field);
const relatedInstanceInfo = createRelatedInstanceSpecInfo(field);
const relatedClass = relatedInstanceInfo?.class;
const ruleset: Ruleset = {
id: `SimilarInstances/${propertyName}/${Guid.createValue()}`,
rules: [],
};
ruleset.rules.push({
ruleType: RuleTypes.Content,
specifications: [
{
specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses,
classes: createMultiClassSpecification(record.classInfo),
relatedInstances: relatedInstanceInfo ? [relatedInstanceInfo.spec] : [],
instanceFilter: createInstanceFilter(relatedInstanceInfo?.spec, field.type, propertyName, propertyValue.raw),
},
],
});
return { ruleset, relatedClass, propertyName, propertyValue };
}
/**
* Create a ruleset with content rules for getting instances are of the
* same ECClass and have the same property value as the provided `record`.
* @param field A field identifying which property of the record we should use
* @param record A record whose similar instances should be found
* @param computeDisplayValue Optional callback function to calculate display value that's
* used in ruleset's description. If not provided, display value from record is used instead.
*/
public async createSimilarInstancesRuleset(
field: Field,
record: Item,
computeDisplayValue?: ComputeDisplayValueCallback,
): Promise<{ ruleset: Ruleset; description: string }> {
const info = this.createSimilarInstancesRulesetInfo(field, record);
const description = await createDescriptionAsync(record, info.relatedClass, field, info.propertyValue, computeDisplayValue);
return { ruleset: info.ruleset, description };
}
}
/**
* Definition of a function for calculating a display value.
* @public
*/
export type ComputeDisplayValueCallback = (type: string, value: PrimitivePropertyValue, displayValue: string) => Promise<string>;
interface PrimitiveValueDef {
raw: PrimitivePropertyValue;
display: string;
}
/**
* Value of a primitive property.
* @public
*/
export type PrimitivePropertyValue = string | number | boolean | Point | InstanceKey | undefined;
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
type Point = { x: number; y: number; z?: number };
const toString = (displayValue: Value | DisplayValue): string => {
if (!displayValue) {
return "NULL";
}
return displayValue.toString();
};
const createDescription = (record: Item, relatedClass: ClassInfo | undefined, field: Field, value: string): string => {
const classInfo = relatedClass ?? record.classInfo!;
return `[${classInfo.label}].[${field.label}] = ${value}`;
};
const createDescriptionAsync = async (
record: Item,
relatedClass: ClassInfo | undefined,
field: Field,
value: PrimitiveValueDef,
computeDisplayValue?: ComputeDisplayValueCallback,
): Promise<string> => {
const displayValue = computeDisplayValue ? await computeDisplayValue(field.type.typeName, value.raw, value.display) : toString(value.display);
return createDescription(record, relatedClass, field, displayValue);
};
const getPropertyName = (field: PropertiesField) => {
let name = field.properties[0].property.name;
if (field.type.typeName === "navigation") {
name += ".Id";
}
return name;
};
const isPrimitivePropertyValue = (value: Value): value is PrimitivePropertyValue => {
if (Value.isPrimitive(value)) {
return true;
}
if (Value.isMap(value)) {
if (typeof value.x === "number" && typeof value.y === "number" && (value.z === undefined || typeof value.z === "number")) {
return true;
}
if (typeof value.className === "string" && typeof value.id === "string") {
return true;
}
}
return false;
};
const getPropertyValue = (record: Item, field: Field): PrimitiveValueDef => {
const fieldNamesStack = [];
let currField: Field | undefined = field;
while (currField) {
fieldNamesStack.push(currField.name);
currField = currField.parent;
}
let currFieldName = fieldNamesStack.pop();
let displayValue: DisplayValue = record.displayValues[currFieldName!];
let value: Value = record.values[currFieldName!];
currFieldName = fieldNamesStack.pop();
while (currFieldName) {
if (!Value.isNestedContent(value) || value.length === 0) {
throw new Error("Invalid record value");
}
if (value.length > 1) {
throw new Error("Can't create 'similar instances' for records related through many part of *-to-many relationship");
}
if (value[0].mergedFieldNames.indexOf(currFieldName) !== -1) {
throw new Error("Can't create 'similar instances' ruleset for merged values");
}
displayValue = value[0].displayValues[currFieldName];
value = value[0].values[currFieldName];
currFieldName = fieldNamesStack.pop();
}
if (!isPrimitivePropertyValue(value)) {
throw new Error("Can only create 'similar instances' ruleset for primitive values");
}
return { raw: value, display: toString(displayValue) };
};
const createInstanceFilter = (
relatedInstanceSpec: Readonly<RelatedInstanceSpecification> | undefined,
propertyType: PrimitiveTypeDescription,
propertyName: string,
propertyValue: PrimitivePropertyValue,
): string => {
const alias = relatedInstanceSpec ? relatedInstanceSpec.alias : "this";
return createComparison(propertyType, `${alias}.${propertyName}`, "=", propertyValue);
};
type Operator = "=" | "!=" | ">" | ">=" | "<" | "<=";
const createComparison = (type: PrimitiveTypeDescription, name: string, operator: Operator, value: PrimitivePropertyValue): string => {
let compareValue = "";
switch (typeof value) {
case "undefined":
compareValue = "NULL";
break;
case "string":
compareValue = `"${value.replace(/"/g, `""`)}"`;
break;
case "boolean":
compareValue = value ? "TRUE" : "FALSE";
break;
case "number":
compareValue = value.toString();
break;
}
if (type.typeName === "navigation" && typeof value === "object" && Id64.isId64((value as InstanceKey).id)) {
// note: this is temporary until we support hex ids in instance filters
compareValue = hexToDec((value as InstanceKey).id);
}
if (type.typeName === "point2d" || type.typeName === "point3d") {
if (typeof value !== "object") {
throw new Error("Expecting point values to be supplied as objects");
}
const dimensionType: PrimitiveTypeDescription = {
valueFormat: PropertyValueFormat.Primitive,
typeName: "double",
};
const pointValue = value as Point;
let comparison = `${createComparison(dimensionType, `${name}.x`, operator, pointValue.x)}`;
comparison += ` AND ${createComparison(dimensionType, `${name}.y`, operator, pointValue.y)}`;
if (type.typeName === "point3d" && pointValue.z !== undefined) {
comparison += ` AND ${createComparison(dimensionType, `${name}.z`, operator, pointValue.z)}`;
}
return comparison;
}
if (type.typeName === "double") {
return `CompareDoubles(${name}, ${compareValue}) ${operator} 0`;
}
if (type.typeName === "dateTime") {
return `CompareDateTimes(${name}, ${compareValue}) ${operator} 0`;
}
return `${name} ${operator} ${compareValue}`;
};
const createMultiClassSpecification = (classInfo: Readonly<ClassInfo>): MultiSchemaClassesSpecification => {
const [schemaName, className] = classInfo.name.split(":");
return { schemaName, classNames: [className], arePolymorphic: true };
};
const createSingleClassSpecification = (classInfo: Readonly<ClassInfo>): SingleSchemaClassSpecification => {
const [schemaName, className] = classInfo.name.split(":");
return { schemaName, className };
};
const createRelatedInstanceSpec = (
pathFromSelectToPropertyClass: RelationshipPath,
index: number,
): { spec: RelatedInstanceSpecification; class: ClassInfo } => ({
spec: {
relationshipPath: pathFromSelectToPropertyClass.map((step) => ({
relationship: createSingleClassSpecification(step.relationshipInfo),
direction: step.isForwardRelationship ? RelationshipDirection.Forward : RelationshipDirection.Backward,
targetClass: createSingleClassSpecification(step.targetClassInfo),
})),
isRequired: true,
alias: `related_${index}`,
},
class: pathFromSelectToPropertyClass[pathFromSelectToPropertyClass.length - 1].targetClassInfo,
});
const createPathFromSelectToPropertyClass = (field: PropertiesField): RelationshipPath => {
let currField: Field = field;
const pathFromPropertyToSelectClass: RelationshipPath = [];
while (currField.parent) {
pathFromPropertyToSelectClass.push(...currField.parent.pathToPrimaryClass);
currField = currField.parent;
}
return RelationshipPath.reverse(pathFromPropertyToSelectClass);
};
const createRelatedInstanceSpecInfo = (field: PropertiesField): { spec: RelatedInstanceSpecification; class: ClassInfo } | undefined => {
const path = createPathFromSelectToPropertyClass(field);
return path.length ? createRelatedInstanceSpec(path, 0) : undefined;
};
const hexToDec = (id: Id64String) => {
const digits = [0];
for (let i = 2; i < id.length; ++i) {
let carry = parseInt(id.charAt(i), 16);
for (let j = 0; j < digits.length; ++j) {
digits[j] = digits[j] * 16 + carry;
carry = (digits[j] / 10) | 0;
digits[j] %= 10;
}
while (carry > 0) {
digits.push(carry % 10);
carry = (carry / 10) | 0;
}
}
return digits.reverse().join("");
};