-
Notifications
You must be signed in to change notification settings - Fork 0
/
complete_poi_interface.ts
393 lines (316 loc) · 12.7 KB
/
complete_poi_interface.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
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
async function main(workbook: ExcelScript.Workbook): Promise<void> {
//Interfaces
/************************************ Layer Interfaces **********************************************/
// Interface that matches the returned JSON structure for a layer
interface Layer {
code: string;
label: string;
icon: string;
sort: number;
filter: FilterObject;
}
// Interface for the filter object with a layer
interface FilterObject {
junction_type: string;
predicates: PredicatesArray[];
}
// Interface for the Predicates Array within the Filter Object
interface PredicatesArray {
operator: string;
property: string;
number_value: number | null;
boolean_value: boolean | null;
string_value: string | null;
}
/************************************** Individual POI Interfaces ****************************************/
// Interface that matches the sent JSON for a POI
interface poi {
id: string;
name: string;
categories: string[];
data: DataObject;
full_address: string;
location: LocationObject;
}
// Interface for the Data Object within a POI
interface DataObject {
details: string;
}
// Interface for the Location Object within a POI
interface LocationObject {
latitude: string;
longitude: string;
}
/********************************************* Layer Functions ***********************************************/
// Functions to create the spreadsheet
// Function to convert row data to layer array
function convertRowsToLayers(rowData: ExcelScript.Range): Layer {
const numberValue = rowData.getCell(0, 7).getValue().toString();
const booleanValue = rowData.getCell(0, 8).getValue().toString();
const stringValue = rowData.getCell(0, 9).getValue().toString();
const predicates: PredicatesArray[] = [];
if (numberValue !== "") {
predicates.push({
operator: rowData.getCell(0, 5).getValue().toString(),
property: rowData.getCell(0, 6).getValue().toString(),
number_value: Number(numberValue),
boolean_value: null, // Default value, as we are setting number_value
string_value: null
});
} else if (booleanValue !== "") {
predicates.push({
operator: rowData.getCell(0, 5).getValue().toString(),
property: rowData.getCell(0, 6).getValue().toString(),
number_value: null,
boolean_value: booleanValue.toLowerCase() === "true",
string_value: null
});
} else if (stringValue !== "") {
predicates.push({
operator: rowData.getCell(0, 5).getValue().toString(),
property: rowData.getCell(0, 6).getValue().toString(),
number_value: null,
boolean_value: null,
string_value: stringValue
});
}
const convertedLayer: Layer = {
code: rowData.getCell(0, 0).getValue().toString(),
label: rowData.getCell(0, 1).getValue().toString(),
icon: rowData.getCell(0, 2).getValue().toString(),
sort: Number(rowData.getCell(0, 3).getValue()),
filter: {
junction_type: rowData.getCell(0, 4).getValue().toString(),
predicates: predicates
}
};
return convertedLayer;
}
// fucntion to get active layers
async function getLayers(sheet: ExcelScript.Worksheet) {
try {
const myInit = {
method: "GET",
headers: {
"Authorization": "Key key=SCRUBBED",
"Content-Type": "application/json"
}
};
const response = await fetch('https://platform.driveaxleapp.com/api/v1/poi_layers/', myInit);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const layers: Layer[] = await response.json();
// Create an array to hold the returned values.
const rows: (string | boolean | number | null)[][] = [];
for (let each of layers) {
// Determine if the row was returned, for example, if each.code exists
const rowReturned = !!each.code;
// Iterate over each predicate in the predicates array
for (let predicate of each.filter.predicates) {
// Push data along with the indicator into the rows array
rows.push([
each.code,
each.label,
each.icon,
each.sort,
each.filter.junction_type,
predicate.operator,
predicate.property,
predicate.number_value,
predicate.boolean_value,
predicate.string_value,
rowReturned
]);
}
}
// Add the data to the current worksheet, starting at "A2".
const range = sheet.getRange('A2').getResizedRange(rows.length - 1, rows[0].length - 1);
range.setValue(rows);
// Set the content of the dropdown list.
let validationCriteria: ExcelScript.ListDataValidation = {
inCellDropDown: true,
source: dropdownValues
};
let validationRule: ExcelScript.DataValidationRule = {
list: validationCriteria
};
dataValidation.setRule(validationRule);
} catch (e) {
console.log("Error in getLayers: " + JSON.stringify(e));
}
}
// Function to Upload Active Layers
async function uploadLayers(sheet: ExcelScript.Worksheet) {
const rows = sheet.getUsedRange().getRowCount(); // Get the last row with data
// Collect data from each row
for (let i = 1; i < rows; i++) {
// see if the layer should be active
const activeOrNot = sheet.getRange().getRow(i).getCell(0, 10).getValue();
// if false delete the layer and continue
if (activeOrNot === false) {
// get layer code
const code = sheet.getRange().getRow(i).getCell(0, 0).getValue().toString();
console.log("code to delete: " + code);
// delete the layer
deletePOILayer(code);
// clear the range (the row)
sheet.getRange().getRow(i).delete(ExcelScript.DeleteShiftDirection.up);
continue;
}
else {
const row = sheet.getRange().getRow(i);
const layers = convertRowsToLayers(row);
const myInit = {
method: "PUT",
headers: {
"Authorization": "Key key=SCRUBBED",
"Content-Type": "application/json"
},
body: JSON.stringify(layers)
};
try {
const response = await fetch('https://platform.driveaxleapp.com/api/v1/poi_layers/', myInit);
if (!response.ok) {
let errorMessage = "Error: " + response.status;
if (response.body !== null) {
errorMessage += " " + await response.text();
}
console.log("error in upload Layers")
throw new Error(errorMessage);
} else {
console.log("it worked!");
}
} catch (e) {
console.log("Error in upload layers #2: " + e);
}
}
}
}
// function to delete POI Layers
async function deletePOILayer(code: string) {
const myInit = {
method: "DELETE",
headers: {
"Authorization": "Key key=SCRUBBED",
"Content-Type": "application/json"
}
};
const response = await fetch('https://platform.driveaxleapp.com/api/v1/poi_layers//' + code, myInit);
if (!response.ok) {
let errorMessage = "Error in delete layer: " + response.status;
if (response.body !== null) {
errorMessage += " " + await response.text();
}
console.log("error in delete layer #2");
throw new Error(errorMessage);
} else {
console.log("it worked! " + code + " deleted");
}
}
/************************************** Individual POI Functions ***************************************/
// Function to convert row data to poi object
function convertRowToPoi(rowData: ExcelScript.Range): poi {
try {
// Extract data from the row and create poi object
let poiObject: poi = {
id: rowData.getCell(0, 0).getValue().toString(),
name: rowData.getCell(0, 1).getValue().toString(),
categories: rowData.getCell(0, 2).getValue().toString().split(',').map(category => category.trim()),
full_address: rowData.getCell(0, 3).getValue().toString(),
// Initialize data and location objects
data: {
details: rowData.getCell(0, 4).getValue().toString()
},
location: {
latitude: rowData.getCell(0, 5).getValue().toString(),
longitude: rowData.getCell(0, 6).getValue().toString(),
}
};
return poiObject;
} catch (error) {
console.log("Error in convertRowToPoi:", error);
throw error; // Re-throw the error to propagate it further
}
}
// function to upload POIs
async function uploadPOIs(poiSpreadsheet: ExcelScript.Worksheet) {
try {
const usedRange = poiSpreadsheet.getRange().getUsedRange();
const rows = usedRange.getRowCount();
console.log("usedRange: " + usedRange);
console.log("rows: " + rows);
for (let i = 1; i < rows; i++) {
const poiRow = usedRange.getRow(i); // Get the range for the current row
const poiObject = convertRowToPoi(poiRow); // Convert row data to poi object
const myInit = {
method: "PUT",
headers: {
"Authorization": "Key key=SCRUBBED",
"Content-Type": "application/json"
},
body: JSON.stringify([poiObject]) // Convert poiArray to JSON string
};
console.log(JSON.stringify([poiObject])); // Log the poi array
const response = await fetch('https://platform.driveaxleapp.com/api/v1/pois', myInit);
if (!response.ok) {
let errorMessage = "Error: " + response.status;
if (response.body !== null) {
errorMessage += " " + await response.text();
}
throw new Error(errorMessage);
} else {
console.log("it worked!");
}
}
} catch (error) {
console.log("Error in uploadPOIs: " + error);
}
}
/********************************** Spreadsheet Setup ********************************/
// Check if the "Add POIs" worksheet exists.
const sheet = workbook.getWorksheet("Custom Layer Interface");
if (!sheet) {
console.log(`No worksheet named "Custom Layer Interface" in this workbook.`);
return;
}
// Check if the "Add POIs" worksheet exists.
const poiSpreadsheet = sheet.getRange("M2").getValue().toString();
const poisheet = workbook.getWorksheet(poiSpreadsheet);
if (!poisheet) {
console.log(`No worksheet named` + poiSpreadsheet + `in this workbook.`);
return;
}
let cellN2Value = sheet.getRange("N2").getValue();
/********************************** Spreadsheet Formatting ********************************/
const columnRange = sheet.getRange('A1:K1');
// set column headers
columnRange.setValues([["Code", "Label", "Icon", "Sort", "junction_type", "operator", "property", "number_value", "boolean_value", "string_value", "Active"]]);
// Bold the column headers
columnRange.getFormat().getFont().setBold(true);
// set update headers
sheet.getRange('M1:O1').setValues([["POI Spreadsheet", "Action", "Time Updated"]]);
// Bold the update headers
sheet.getRange('M1:O1').getFormat().getFont().setBold(true);
// Define the range where you want to apply the in-cell dropdown
let dropdownRange = sheet.getRange("N2");
const dataValidation = dropdownRange.getDataValidation();
// Set the values for the dropdown list
let dropdownValues = "Update,Refresh";
/********************************** Main ********************************/
// If the sheet is blank or cell N2 is set to "Refresh"
if (sheet.getRange("A1").getValue() === "" || cellN2Value === "Refresh") {
getLayers(sheet);
}
else if (cellN2Value === "Update") {
// upload edited layers
await uploadLayers(sheet);
}
// time of update
const timeReturned = new Date(Date.now()).toISOString();
sheet.getRange('O2').setValue(timeReturned);
// format cells
sheet.getUsedRange().getFormat().autofitColumns();
// Call the function to upload POIs
await uploadPOIs(poisheet);
}