-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutilitynetwork.js
505 lines (398 loc) · 23.6 KB
/
utilitynetwork.js
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
'use strict';
//Author : Hussein Nasser
//Date : Jan-23-2018
//Twitter: @hnasr
const emptyTraceConfiguration = {"includeContainers":false,"includeContent":false,"includeStructures":false,"includeBarriers":true,"validateConsistency":false,"domainNetworkName":"","tierName":"","targetTierName":"","subnetworkName":"","diagramTemplateName":"","shortestPathNetworkAttributeName":"","filterBitsetNetworkAttributeName":"","traversabilityScope":"junctionsAndEdges","conditionBarriers":[],"functionBarriers":[],"arcadeExpressionBarrier":"","filterBarriers":[],"filterFunctionBarriers":[],"filterScope":"junctionsAndEdges","functions":[],"nearestNeighbor":{"count":-1,"costNetworkAttributeName":"","nearestCategories":[],"nearestAssets":[]},"outputFilters":[],"outputConditions":[],"propagators":[]}
class UtilityNetwork {
constructor(token, featureServiceUrl)
{
this.featureServiceUrl = featureServiceUrl;
this.token = token;
}
///first function one should call after creating an instance of a utility network
load ()
{
let thisObj = this;
return new Promise (function (resolve, reject)
{
//run async mode
(async function () {
//pull the feature service definition
let featureServiceJsonResult = await makeRequest({method: 'POST', url: thisObj.featureServiceUrl, params: {f : "json", token: thisObj.token}});
thisObj.featureServiceJson = featureServiceJsonResult
//check to see if the feature service has a UN
if (thisObj.featureServiceJson.controllerDatasetLayers != undefined)
{
thisObj.layerId = thisObj.featureServiceJson.controllerDatasetLayers.utilityNetworkLayerId;
let queryDataElementUrl = thisObj.featureServiceUrl + "/queryDataElements";
let layers = "[" + thisObj.layerId + "]"
let postJson = {
token: thisObj.token,
layers: layers,
f: "json"
}
//pull the data element definition of the utility network now that we have the utility network layer
let undataElement = await makeRequest({method: 'POST', url: queryDataElementUrl, params: postJson });
//request the un layer defition which has different set of information
let unLayerUrl = thisObj.featureServiceUrl + "/" + thisObj.layerId;
postJson = {
token: thisObj.token,
f: "json"
}
let unLayerDef = await makeRequest({method: 'POST', url: unLayerUrl, params: postJson });
thisObj.dataElement = undataElement.layerDataElements[0].dataElement;
thisObj.layerDefinition = unLayerDef
//thisObj.subnetLineLayerId = thisObj.getSubnetLineLayerId();
resolve(thisObj);
}
else
reject("No Utility Network found in this feature service");
})();
})
}
//return the domainNetwork object.
getDomainNetwork(domainNetworkName)
{
for (let domainNetwork of this.dataElement.domainNetworks)
if (domainNetwork.domainNetworkName === domainNetworkName) return domainNetwork;
}
//return the tier
getTier(domainNetworkName, tierName)
{
for (let tier of this.getDomainNetwork(domainNetworkName).tiers)
if (tier.name === tierName)
return tier;
}
//query the subnetwokrs table
getSubnetworks(domainNetworkName, tierName)
{
let subnetworkTableUrl = this.featureServiceUrl + "/" + this.layerDefinition.systemLayers.subnetworksTableId + "/query";
let postJson = {
token: this.token,
where: "DOMAINNETWORKNAME = '" + domainNetworkName + "' AND TIERNAME = '" + tierName + "'",
outFields: "SUBNETWORKNAME",
orderByFields: "SUBNETWORKNAME",
returnDistinctValues: true,
f: "json"
}
return makeRequest({method: 'POST', url: subnetworkTableUrl, params: postJson});
}
//query that projects to webmercator.
query(layerId, where, obj, objectids)
{
let webMercSpatialReference = {
"wkid": 102100,
"latestWkid": 3857,
"xyTolerance": 0.001,
"zTolerance": 0.001,
"mTolerance": 0.001,
"falseX": -20037700,
"falseY": -30241100,
"xyUnits": 148923141.92838538,
"falseZ": -100000,
"zUnits": 10000,
"falseM": -100000,
"mUnits": 10000
}
let queryJson = {
f: "json",
token: this.token,
outFields: "*",
where: where,
outSR: JSON.stringify(webMercSpatialReference)
}
if (objectids != undefined)
queryJson.objectIds = objectids;
queryJson.layerId = layerId
return new Promise((resolve, reject) => {
makeRequest({method: 'POST', params: queryJson, url: this.featureServiceUrl + "/" + layerId + "/query"}).then(rowsJson=> {
rowsJson.obj = obj;
resolve(rowsJson);
}).catch(rej => reject("failed to query"));
});
}
//get the terminal configuration using the id
getTerminalConfiguration(terminalConfigurationId)
{
return this.dataElement.terminalConfigurations.find(tc => tc.terminalConfigurationId === terminalConfigurationId);
}
//get the subenetline layer
getSubnetLineLayerId(domainNetworkName)
{
//esriUNFCUTSubnetLine
let domainNetworks = this.dataElement.domainNetworks;
for (let i = 0; i < domainNetworks.length; i ++)
{
let domainNetwork = domainNetworks[i];
if (domainNetwork.domainNetworkName === domainNetworkName) {
//only search edgeSources since subnetline is a line
for (let j = 0; j < domainNetwork.edgeSources.length; j ++)
if (domainNetwork.edgeSources[j].utilityNetworkFeatureClassUsageType === "esriUNFCUTSubnetLine")
return domainNetwork.edgeSources[j].layerId;
}
}
}
//return the asset type
getAssetType(layerId, assetGroupCode, assetTypeCode)
{
let domainNetworks = this.dataElement.domainNetworks;
let layerObj = undefined;
for (let i = 0; i < domainNetworks.length; i ++)
{
let domainNetwork = domainNetworks[i];
for (let j = 0; j < domainNetwork.junctionSources.length; j ++)
if (domainNetwork.junctionSources[j].layerId == layerId)
{
let assetGroup = domainNetwork.junctionSources[j].assetGroups.find( ag => ag.assetGroupCode === assetGroupCode);
if (assetGroup instanceof Object)
{
let assetType = assetGroup.assetTypes.find(at => at.assetTypeCode === assetTypeCode);
assetType.assetGroupName = assetGroup.assetGroupName;
assetType.utilityNetworkFeatureClassUsageType = domainNetwork.junctionSources[j].utilityNetworkFeatureClassUsageType;
if(assetType instanceof Object) return assetType;
}
}
for (let j = 0; j < domainNetwork.edgeSources.length; j ++)
if (domainNetwork.edgeSources[j].layerId == layerId)
{
let assetGroup = domainNetwork.edgeSources[j].assetGroups.find( ag => ag.assetGroupCode === assetGroupCode);
if (assetGroup instanceof Object)
{
let assetType = assetGroup.assetTypes.find(at => at.assetTypeCode === assetTypeCode);
assetType.assetGroupName = assetGroup.assetGroupName;
assetType.utilityNetworkFeatureClassUsageType = domainNetwork.edgeSources[j].utilityNetworkFeatureClassUsageType;
if(assetType instanceof Object) return assetType;
}
}
}
return undefined;
}
//return layer by type
getLayer(utilityNetworkUsageType) {
let domainNetworks = this.dataElement.domainNetworks;
let layers = []
for (let i = 0; i < domainNetworks.length; i ++)
{
let domainNetwork = domainNetworks[i];
for (let j = 0; j < domainNetwork.junctionSources.length; j ++)
if (domainNetwork.junctionSources[j].utilityNetworkFeatureClassUsageType === utilityNetworkUsageType)
layers.push(domainNetwork.junctionSources[j].layerId);
}
for (let i = 0; i < domainNetworks.length; i ++)
{
let domainNetwork = domainNetworks[i];
for (let j = 0; j < domainNetwork.edgeSources.length; j ++)
if (domainNetwork.edgeSources[j].utilityNetworkFeatureClassUsageType === utilityNetworkUsageType)
layers.push(domainNetwork.edgeSources[j].layerId)
}
return layers;
}
//return the first device layer
getDeviceLayers() {
return this.getLayer("esriUNFCUTDevice");
}
//return the first junction layer
getJunctionLayers() {
return this.getLayer("esriUNFCUTJunction");
}
//return the first Line layer
getLineLayers() {
return this.getLayer("esriUNFCUTLine");
}
//determines if the layerid is a line or point...
isLayerEdge(layerId) {
let domainNetworks = this.dataElement.domainNetworks;
for (let i = 0; i < domainNetworks.length; i ++)
{
let domainNetwork = domainNetworks[i];
for (let j = 0; j < domainNetwork.edgeSources.length; j ++)
if (domainNetwork.edgeSources[j].layerId === layerId)
return true;
}
return false;
}
//get layer id from Source Id used to map sourceid to layer id
getLayerIdfromSourceId(sourceId)
{
let domainNetworks = this.dataElement.domainNetworks;
let layerObj = undefined;
for (let i = 0; i < domainNetworks.length; i ++)
{
let domainNetwork = domainNetworks[i];
for (let j = 0; j < domainNetwork.junctionSources.length; j ++)
if (domainNetwork.junctionSources[j].sourceId == sourceId)
{
layerObj = {type: domainNetwork.junctionSources[j].shapeType, layerId: domainNetwork.junctionSources[j].layerId}
break;
}
for (let j = 0; j < domainNetwork.edgeSources.length; j ++)
if (domainNetwork.edgeSources[j].sourceId == sourceId)
{
layerObj = {type: domainNetwork.edgeSources[j].shapeType, layerId: domainNetwork.edgeSources[j].layerId}
break;
}
}
if (layerObj != undefined)
layerObj.type = layerObj.type.replace("esriGeometry", "").toLowerCase();
return layerObj;
}
//receives an array of starting locations and transforms it for the rest params..
//an array of [{"traceLocationType":"startingPoint", assetGroupCode: 5, assetTypeCode:5, layerId: 5, "globalId":"{00B313AC-FBC4-4FF4-9D7A-6BF40F4D4CAD}"}]
buildTraceLocations (traceLocationsParam) {
let traceLocations = [];
//terminalId percentAlong: 0
//line starting point [{"traceLocationType":"startingPoint","globalId":"{00B313AC-FBC4-4FF4-9D7A-6BF40F4D4CAD}","percentAlong":0.84695770913918678}]
traceLocationsParam.forEach(s=> {
//if layerid doesn't exists get it from the sourceid..
if (s.layerId === undefined) s.layerId = this.getLayerIdfromSourceId(s.networkSourceId);
if (this.isLayerEdge(s.layerId) === true)
traceLocations.push({traceLocationType: s.traceLocationType, globalId:s.globalId , percentAlong: 0.5 } ) //add the starting point to themiddle of the line temporary
else {
//if its a junction, check if a terminalid is passed if not then get the terminal configuration and add all possible terminals temrporary..
if (s.terminalId === undefined && s.terminalId != -1) {
let at = this.getAssetType(s.layerId, s.assetGroupCode, s.assetTypeCode);
let tc = this.getTerminalConfiguration(at.terminalConfigurationId)
tc.terminals.forEach(t => traceLocations.push({traceLocationType: s.traceLocationType, globalId:s.globalId , terminalId: t.terminalId } ))
}
else
{
traceLocations.push({traceLocationType: s.traceLocationType, globalId:s.globalId , terminalId: s.terminalId } )
}
}
}
);
return traceLocations;
}
//if it is an error we return true assuming we couldn't trace if no elements exists for this feature.. or any other..
isInIsland (traceLocationsParam) {
return new Promise( (resolve, reject) => {
//this trace configuration stops when it finds a single controller.
let traceConfiguration = {"includeContainers":false,"includeContent":false,"includeStructures":false,"includeBarriers":true,"validateConsistency":false,"domainNetworkName":"","tierName":"","targetTierName":"","subnetworkName":"","diagramTemplateName":"","shortestPathNetworkAttributeName":"","filterBitsetNetworkAttributeName":"","traversabilityScope":"junctions","conditionBarriers":[{"name":"Is subnetwork controller","type":"networkAttribute","operator":"equal","value":1,"combineUsingOr":false,"isSpecificValue":true}],"functionBarriers":[{"functionType":"add","networkAttributeName":"Is subnetwork controller","operator":"equal","value":1,"useLocalValues":false}],"arcadeExpressionBarrier":"","filterBarriers":[{"name":"Is subnetwork controller","type":"networkAttribute","operator":"equal","value":1,"combineUsingOr":false,"isSpecificValue":true}],"filterFunctionBarriers":[],"filterScope":"junctions","functions":[],"nearestNeighbor":{"count":-1,"costNetworkAttributeName":"","nearestCategories":[],"nearestAssets":[]},"outputFilters":[],"outputConditions":[{"name":"Is subnetwork controller","type":"networkAttribute","operator":"equal","value":1,"combineUsingOr":false,"isSpecificValue":true},{"name":"Category","type":"category","operator":"equal","value":"Subnetwork Controller","combineUsingOr":false,"isSpecificValue":true}],"propagators":[]}
this.Trace(traceLocationsParam, "connected", traceConfiguration)
.then (results => {
if (results.traceResults.success === false)
{
console.log ("Error tracing " + JSON.stringify(traceLocationsParam));
reject(true);
}
else
resolve(results.traceResults.elements.length === 0)
})
.catch (er => {
console.log ("Error tracing " + JSON.stringify(traceLocationsParam));
reject(true);});
})
}
//run connected Trace
connectedTrace(traceLocationsParam, traceConfiguration)
{
return this.Trace(traceLocationsParam, "connected", traceConfiguration);
}
//generic trace function
Trace (traceLocationsParam, traceType, traceConfiguration, forceFail=true) {
let traceLocations = this.buildTraceLocations (traceLocationsParam);
return new Promise((resolve, reject) => {
if (traceConfiguration === undefined)
traceConfiguration = emptyTraceConfiguration; //{"includeContainers":false,"includeContent":false,"includeStructures":false,"includeBarriers":true,"validateConsistency":false,"domainNetworkName":"","tierName":"","targetTierName":"","subnetworkName":"","diagramTemplateName":"","shortestPathNetworkAttributeName":"","filterBitsetNetworkAttributeName":"","traversabilityScope":"junctionsAndEdges","conditionBarriers":[],"functionBarriers":[],"arcadeExpressionBarrier":"","filterBarriers":[],"filterFunctionBarriers":[],"filterScope":"junctionsAndEdges","functions":[],"nearestNeighbor":{"count":-1,"costNetworkAttributeName":"","nearestCategories":[],"nearestAssets":[]},"outputFilters":[],"outputConditions":[],"propagators":[]}
//serviceJson load each layer..
let ar = this.featureServiceUrl.split("/");
ar[ar.length-1]="UtilityNetworkServer";
let traceUrl = ar.join("/") + "/trace"
let traceJson = {
f: "json",
token: this.token,
traceType : traceType,
traceLocations: JSON.stringify(traceLocations),
traceConfiguration: JSON.stringify(traceConfiguration)
}
let un = this;
makeRequest({method:'POST', params: traceJson, url: traceUrl })
.then(featuresJson=> featuresJson.success === false && forceFail === true ? reject(JSON.stringify(featuresJson)) : resolve( featuresJson))
.catch(e=> reject("failed to execute trace. " + e));
});
}
subnetworkControllerTrace (traceLocationsParam, domainNetworkName, tierName, subnetworkName, traceConfiguration) {
if (traceConfiguration === undefined)
{
let tier = this.getTier(domainNetworkName, tierName);
let subnetworkDef = tier.updateSubnetworkTraceConfiguration;
subnetworkDef.subnetworkName = subnetworkName;
//disable consistency
subnetworkDef.validateConsistency = false;
traceConfiguration = subnetworkDef;
//if no trace configuration passed to override use the tier subnetwork definition
}
return this.Trace(traceLocationsParam, "subnetworkController", traceConfiguration,false);
}
upstreamTrace (traceLocationsParam, domainNetworkName, tierName, subnetworkName, traceConfiguration) {
if (traceConfiguration === undefined)
{
let tier = this.getTier(domainNetworkName, tierName);
let subnetworkDef = tier.updateSubnetworkTraceConfiguration;
subnetworkDef.subnetworkName = subnetworkName;
//disable consistency
subnetworkDef.validateConsistency = false;
traceConfiguration = subnetworkDef;
//if no trace configuration passed to override use the tier subnetwork definition
}
return this.Trace(traceLocationsParam, "upstream", traceConfiguration);
}
downstreamTrace (traceLocationsParam, domainNetworkName, tierName, subnetworkName, traceConfiguration) {
if (traceConfiguration === undefined)
{
let tier = this.getTier(domainNetworkName, tierName);
let subnetworkDef = tier.updateSubnetworkTraceConfiguration;
subnetworkDef.subnetworkName = subnetworkName;
//disable consistency
subnetworkDef.validateConsistency = false;
traceConfiguration = subnetworkDef;
//if no trace configuration passed to override use the tier subnetwork definition
}
return this.Trace(traceLocationsParam, "downstream", traceConfiguration);
}
//run subnetwork Trace
subnetworkTrace(traceLocationsParam, domainNetworkName, tierName, subnetworkName, traceConfiguration)
{
if (traceConfiguration === undefined)
{
let tier = this.getTier(domainNetworkName, tierName);
let subnetworkDef = tier.updateSubnetworkTraceConfiguration;
subnetworkDef.subnetworkName = subnetworkName;
//disable consistency
subnetworkDef.validateConsistency = false;
traceConfiguration = subnetworkDef;
//if no trace configuration passed to override use the tier subnetwork definition
}
return this.Trace(traceLocationsParam, "subnetwork", traceConfiguration);
}
}
//Makes a request
function makeRequest (opts) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(opts.method, opts.url);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
let jsonRes = xhr.response;
if (typeof jsonRes !== "object") jsonRes = JSON.parse(xhr.response);
resolve(jsonRes);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
//xhr.onerror = err => reject({status: this.status, statusText: xhr.statusText}) ;
xhr.onerror = err => reject(err) ;
if (opts.headers)
Object.keys(opts.headers).forEach( key => xhr.setRequestHeader(key, opts.headers[key]) )
let params = opts.params;
// We'll need to stringify if we've been given an object
// If we have a string, this is skipped.
if (params && typeof params === 'object')
params = Object.keys(params).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key])).join('&');
xhr.send(params);
});
}