-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
374 lines (245 loc) · 12.2 KB
/
index.html
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
<html lang="en">
<head>
<title>Archivist mapping files generator</title>
<script src="https://cdn.sheetjs.com/xlsx-0.20.2/package/dist/xlsx.full.min.js"></script>
<script src="jszip.min.js"></script>
<style>
.paddedDiv {
margin: 20px
}
.leftPaddedDiv {
margin-left: 40px
}
</style>
</head>
<body>
<div style="font-size:20px; padding:5px">
<h1>Generate text mappings files</h1>
<div style="display:flex">
<div style="flex-direction:column">
<div class="paddedDiv">
<label for="inputFileSelector">Select an input Excel (.xlsx) file from which Archivist text mapping files will
be generated.</label>
</div>
<div class="paddedDiv" style="display:flex;flex-direction:row">
<input id="inputFileSelector" type="file" />
<div style="margin-left:20px" id="createMappingsButton"></div>
</div>
</div>
</div>
<div class="paddedDiv" id="fileLinks"></div>
<div class="paddedDiv" id="downloadAllFiles"></div>
<div class="paddedDiv" id="statusMessage"></div>
<div class="leftPaddedDiv" id="statusMessageDetails"></div>
</div>
<script>
var zip;
function getUniqueArrayValues(arrayData) {
return [...new Set(arrayData)]
}
function addLinkToNewDiv(linkURL, linkText, downloadedFilename, pageDivId) {
const link = document.createElement("a");
const div = document.createElement("div");
div.id = pageDivId
link.href = linkURL
link.text = linkText
link.download = downloadedFilename
document.getElementById("fileLinks").appendChild(div)
document.getElementById(pageDivId).appendChild(link)
}
function addLinkToExistingDiv(linkURL, linkText, downloadedFilename, divId, linkLabel) {
const link = document.createElement("a");
link.href = linkURL
link.text = linkText
link.download = downloadedFilename
const labelDiv = document.createElement("div");
labelDiv.id = `${divId}-label`
labelDiv.innerHTML = linkLabel
const linkDiv = document.createElement("div");
linkDiv.id = `${divId}-link`
linkDiv.setAttribute("class", "paddedDiv")
linkDiv.appendChild(link)
document.getElementById(divId).appendChild(labelDiv)
document.getElementById(divId).appendChild(linkDiv)
}
function columnNamesToLowerCase(worksheetDataByRows) {
const rowValues = []
worksheetDataByRows.forEach(worksheetRow => {
// We need to create a new object to hold the row data so we can ensure the
// field names of the object are all lower case...
var rowData = {}
Object.keys(worksheetRow).forEach(fieldName => rowData[fieldName.toLowerCase()] = worksheetRow[fieldName])
rowValues.push(rowData)
})
return rowValues
}
function createBlobURL(worksheetDataByRows, columns, fileName, suffix = {}) {
var fileData = ""
worksheetDataByRows.forEach(worksheetRow => {
const rowValues = []
columns.map(columnName => rowValues.push(worksheetRow[columnName.toLowerCase()]
+ (!!suffix[columnName] ? suffix[columnName] : "")))
const lowerCaseRowValues = rowValues.map(rowValue => rowValue.trim().toLowerCase())
if (!(lowerCaseRowValues.includes("n/a")
|| lowerCaseRowValues.includes("na")
|| lowerCaseRowValues.includes("derived")
|| lowerCaseRowValues.includes("undefined")
|| lowerCaseRowValues.includes("")))
fileData = fileData + rowValues.join("\t") + "\n"
})
var formBlob = new Blob([fileData], { type: 'text/plain' });
if (formBlob.size > 0)
zip.file(fileName, fileData);
const downloadLink = window.URL.createObjectURL(formBlob);
return formBlob.size > 0 ? downloadLink : null
}
const inputElement = document.getElementById("inputFileSelector");
inputElement.addEventListener("change", addConvertButton, false);
function addConvertButton() {
const fileList = this.files;
const createMappingsButtonDiv = document.getElementById("createMappingsButton");
const createMappingsButtonObject = document.createElement("button");
createMappingsButtonObject.textContent = "Create mappings"
createMappingsButtonObject.setAttribute('aria-label', 'Create mapping files')
createMappingsButtonObject.addEventListener("click", () => handleFiles(fileList), false);
createMappingsButtonDiv.innerHTML = ""
document.getElementById("fileLinks").innerHTML = ""
document.getElementById("downloadAllFiles").innerHTML = ""
document.getElementById("statusMessage").textContent = ""
document.getElementById("statusMessageDetails").textContent = ""
zip = new JSZip();
createMappingsButtonDiv.appendChild(createMappingsButtonObject)
}
function handleFiles(fileList) {
const reader = new FileReader()
reader.onload = (function (event) {
document.getElementById("fileLinks").innerHTML = ""
document.getElementById("downloadAllFiles").innerHTML = ""
try {
const workBook = XLSX.read(reader.result, { nullError: true })['Sheets'];
// Get QV and TV mappings worksheet...
const qvTvWorksheet = workBook[Object.keys(workBook).find(key => key.toLowerCase() === 'qv and tv mappings')]
const qvTvWorksheetOrderedByRows = columnNamesToLowerCase(
XLSX.utils.sheet_to_json(qvTvWorksheet, { defval: "" }))
var datasetPrefixes = (getUniqueArrayValues(qvTvWorksheetOrderedByRows.map(
worksheetRow => worksheetRow['dataset prefix']).filter(datasetPrefixCell =>
(!!datasetPrefixCell && !(datasetPrefixCell.toLowerCase().includes("n/a")
|| datasetPrefixCell.toLowerCase().includes("na")
|| datasetPrefixCell.toLowerCase().includes("derived") || !datasetPrefixCell.trim()))
)))
var questionnairePrefixes = (getUniqueArrayValues(qvTvWorksheetOrderedByRows.map(
worksheetRow => worksheetRow['questionnaire prefix']).filter(questionnairePrefixCell =>
(!!questionnairePrefixCell && !(questionnairePrefixCell.toLowerCase().includes("n/a")
|| questionnairePrefixCell.toLowerCase().includes("na")
|| questionnairePrefixCell.toLowerCase().includes("derived") || !questionnairePrefixCell.trim()))
)))
var qvLinkURL;
var tvLinkURL;
var tqLinkURL;
questionnairePrefixes.forEach(questionnairePrefix => {
qvLinkURL = createBlobURL(qvTvWorksheetOrderedByRows.filter(
worksheetRow => worksheetRow['questionnaire prefix'] == questionnairePrefix),
['questionnaire prefix', 'question name', 'dataset prefix', 'variable name'],
`${questionnairePrefix}_qv.txt`,
{ 'questionnaire prefix': '_ccs01' })
!!qvLinkURL && addLinkToNewDiv(qvLinkURL,
`${questionnairePrefix}_qv.txt`,
`${questionnairePrefix}_qv.txt`,
`qv${questionnairePrefix.replaceAll("_", "-")}`)
})
datasetPrefixes.forEach(datasetPrefix => {
tvLinkURL = createBlobURL(qvTvWorksheetOrderedByRows.filter(
worksheetRow => worksheetRow['dataset prefix'] == datasetPrefix),
['dataset prefix', 'variable name', 'topic id'],
`${datasetPrefix}_tv.txt`)
!!tvLinkURL && addLinkToNewDiv(tvLinkURL,
`${datasetPrefix}_tv.txt`,
`${datasetPrefix}_tv.txt`,
`tv${datasetPrefix.replaceAll("_", "-")}`)
})
simplifiedData = []
qvTvWorksheetOrderedByRows.forEach(worksheetRow => {
if (worksheetRow['question name']?.includes("$")) {
indexOfDollarSign = worksheetRow['question name'].indexOf("$")
worksheetRow['question name'] = (worksheetRow['question name'].slice(0, indexOfDollarSign))
}
if (simplifiedData.filter(dataRow => dataRow['question name'] == worksheetRow['question name']
&& dataRow['topic id'] == worksheetRow['topic id']).length == 0)
simplifiedData.push(worksheetRow)
})
questionnairePrefixes.forEach(questionnairePrefix => {
tqLinkURL = createBlobURL(simplifiedData.filter(
dataRow => dataRow['questionnaire prefix'] == questionnairePrefix),
['questionnaire prefix', 'question name', 'topic id'],
`${questionnairePrefix}_tq.txt`,
{ 'questionnaire prefix': '_ccs01' })
!!tqLinkURL && addLinkToNewDiv(tqLinkURL,
`${questionnairePrefix}_tq.txt`,
`${questionnairePrefix}_tq.txt`,
`tq${questionnairePrefix.replaceAll("_", "-")}`)
})
// Get DV mappings worksheet...
const dvWorksheet = workBook[Object.keys(workBook).find(key => key.toLowerCase() === 'dv')]
const dvWorksheetOrderedByRows = columnNamesToLowerCase(
XLSX.utils.sheet_to_json(dvWorksheet, { defval: "" }))
datasetPrefixes = (getUniqueArrayValues(dvWorksheetOrderedByRows.map(
worksheetRow => worksheetRow['derived dataset prefix']).filter(datasetPrefixCell =>
(!!datasetPrefixCell
&& !(datasetPrefixCell.toLowerCase().includes("n/a")
|| datasetPrefixCell.toLowerCase().includes("na")
|| datasetPrefixCell.toLowerCase().includes("derived") || !datasetPrefixCell.trim()))
)))
var dvLinkURL;
datasetPrefixes.forEach(datasetPrefix => {
dvLinkURL = createBlobURL(dvWorksheetOrderedByRows.filter(
worksheetRow => worksheetRow['derived dataset prefix'] == datasetPrefix), ["derived dataset prefix",
"derived variable name",
"source dataset prefix",
"source variable name"
],
`${datasetPrefix}_dv.txt`)
dvLinkURL && addLinkToNewDiv(dvLinkURL,
`${datasetPrefix}_dv.txt`,
`${datasetPrefix}_dv.txt`,
`dv${datasetPrefix.replaceAll("_", "-")}`)
})
if (!qvLinkURL || !tvLinkURL || !tqLinkURL || !dvLinkURL)
document.getElementById("statusMessage").innerHTML += `Please check that uploaded input has a valid structure:`
if (!qvLinkURL)
document.getElementById("statusMessageDetails").innerHTML += `- Unable to create qv mappings file.<br>`
if (!tvLinkURL)
document.getElementById("statusMessageDetails").innerHTML += `- Unable to create tv mappings file.<br>`
if (!tqLinkURL)
document.getElementById("statusMessageDetails").innerHTML += `- Unable to create tq mappings file.<br>`
if (!dvLinkURL)
document.getElementById("statusMessageDetails").innerHTML += `- Unable to create dv mappings file.<br>`
} catch (error) {
document.getElementById("statusMessage").innerHTML = `Error processing selected input file. Error generated
by application: ${error}
<p>
Check that the file is correctly formatted, see <a target="_blank" href="https://github.com/CLOSER-Cohorts/archivist-utilities/blob/main/README.md">
https://github.com/CLOSER-Cohorts/archivist-utilities/blob/main/README.md
</a> for instructions on the required format for the input file.
`
}
if (Object.keys(zip.files).length > 0) {
zip.generateAsync({ type: "blob" })
.then(function (content) {
const downloadLink = window.URL.createObjectURL(content);
addLinkToExistingDiv(downloadLink,
"allMappings.zip",
"allMappings.zip",
"downloadAllFiles",
"Click the link below to download all the generated mapping files.")
});
}
else {
document.getElementById("downloadAllFiles")
.innerHTML = "Insufficient data in input spreadsheet to generate any mapping files."
}
})
reader.readAsArrayBuffer(fileList[0])
}
</script>
</body>
</html>