-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
448 lines (378 loc) · 14.7 KB
/
Copy pathindex.js
File metadata and controls
448 lines (378 loc) · 14.7 KB
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
"use strict";
document.addEventListener('DOMContentLoaded', function () {
// Import Input (IBAN)
const fileInput = document.getElementById('file-input');
const fileLabel = document.getElementById('file-label');
const fileDropArea = document.getElementById('file-drop-area');
fileDropArea.addEventListener('click', () => {
fileInput.click();
});
fileInput.addEventListener('change', () => {
if (fileInput.files.length > 0) {
fileLabel.textContent = fileInput.files.length + " Datei(en) ausgewählt";
} else {
fileLabel.textContent = '.csv,.pdf,.html';
}
});
fileDropArea.addEventListener('dragover', (e) => {
e.preventDefault();
});
fileDropArea.addEventListener('drop', (e) => {
e.preventDefault();
const files = e.dataTransfer.files;
if (files.length > 0) {
fileInput.files = files;
fileLabel.textContent = files.length + " Datei(en) ausgewählt";
}
});
// Import Input (Settings)
const settingsInput = document.getElementById('settings-input');
const settingsLabel = document.getElementById('settings-label');
const settingsDropArea = document.getElementById('settings-drop-area');
settingsDropArea.addEventListener('click', () => {
settingsInput.click();
});
settingsInput.addEventListener('change', () => {
if (settingsInput.files.length > 0) {
settingsLabel.textContent = settingsInput.files[0].name;
} else {
settingsLabel.textContent = '.json';
}
});
settingsDropArea.addEventListener('dragover', (e) => {
e.preventDefault();
});
settingsDropArea.addEventListener('drop', (e) => {
e.preventDefault();
const files = e.dataTransfer.files;
if (files.length > 0) {
settingsInput.files = files;
settingsLabel.textContent = files[0].name;
}
});
// Metadata-Select
document.getElementById('read-setting').addEventListener('change', function () {
document.getElementById('set-setting').value = "";
});
});
// ----------------------------------------------------------------------------
// -- DOM Functions -----------------------------------------------------------
// ----------------------------------------------------------------------------
/**
* Prepares and configures a modal dialog for adding or editing data based on the provided mode.
* This function handles both "group" and "IBAN" modes, dynamically loading data and updating the modal's content.
*
* @param {string} modal_id - The ID of the modal element to be prepared.
* @param {Event} event - The event object triggered by the user interaction.
* @param {string} [force_id] - Optional parameter to force a specific mode or ID, overriding the event's dataset.
*
* @returns {void}
*/
function prepareAddModal(modal_id, event, force_id) {
const mode = modal_id.split('-')[1];
const text_input = document.getElementById(mode + "-input");
const link_open = document.querySelector("#" + modal_id + " footer a:last-child");
const iban_stats = document.getElementById('iban-stats');
if (force_id || (event && event.currentTarget.dataset[mode])) {
// Load and fill
const id = force_id || event.currentTarget.dataset[mode];
text_input.value = id;
link_open.href = '/' + encodeURIComponent(id);
link_open.classList.remove('hide');
if (mode == "group") {
// Get Group Info; Activate Checkboxes for Ibans in Group
const iban_checkboxes = document.querySelectorAll("#" + modal_id + " fieldset input");
apiGet("getMeta/" + id, {}, function (response, error) {
const ibans = response['ibans'] || [];
iban_checkboxes.forEach(box => {
if (ibans.includes(box.value)) {
// Activate IBAN as Groupmember
box.checked = true;
}
});
});
return;
}
// Modal is Add-IBAN
const stat_points = iban_stats.getElementsByTagName('b');
apiGet('stats/' + id, {}, function (repsonse, error) {
// Get basic Stats
if (error) {
alert(error);
return;
}
stat_points[0].innerHTML = repsonse.count;
stat_points[1].innerHTML = formatUnixToDate(repsonse.min);
stat_points[2].innerHTML = formatUnixToDate(repsonse.max);
iban_stats.classList.remove('hide');
})
return;
}
// Clean
text_input.value = "";
link_open.classList.add('hide');
iban_stats.classList.add('hide');
}
/**
* Gets a value for a Metadate into a textarea.
* The key is selected via the select input element 'read-setting'
* and written to 'set-setting'.
*/
function loadSetting() {
const setting_uuid = document.getElementById('read-setting').value;
const result_text = document.getElementById('set-setting');
if (!setting_uuid) {
alert('Kein Name einer Einstellung angegeben!');
return;
}
apiGet('getMeta/' + setting_uuid, {}, function (responseText, error) {
if (error) {
showAjaxError(error, responseText);
} else {
result_text.value = formatResultText(responseText);
}
});
}
/**
* Sets a value for a Metadate.
* The key is selected via the select input element 'read-setting'
* and the value is taken from 'set-setting'.
*/
function saveSetting() {
const setting_uuid = document.getElementById('read-setting').value;
const result_text = document.getElementById('set-setting');
if (!setting_uuid || !result_text.value) {
alert('Kein Name einer Einstellung oder Wert angegeben!');
return;
}
let payload;
let meta_type;
try {
payload = JSON.parse(result_text.value);
if (!payload['metatype']) {
throw new ValueError("No metatype provided!");
}
meta_type = payload['metatype'];
} catch (error) {
alert('Could not parse settingsvalue!' + error);
return;
}
apiSubmit('saveMeta/' + meta_type, payload, function (response, error) {
if (error) {
showAjaxError(error, response);
} else {
alert('Einstellungen gespeichert (' + response.inserted + ')');
result_text.value = '';
}
}, false);
}
/**
* Delete a value from Metadate by uuid.
* The key is selected via the select input element 'read-setting'.
*/
function deleteSetting() {
const setting_uuid = document.getElementById('read-setting').value;
if (!setting_uuid) {
alert('Kein Name einer Einstellung angegeben!');
return;
}
apiSubmit('deleteMeta/' + setting_uuid, {}, function (response, error) {
if (error) {
showAjaxError(error, response);
} else {
alert('Einstellung gelöscht !');
window.location.reload();
}
}, false, 'DELETE');
}
// ----------------------------------------------------------------------------
// -- API Functions -----------------------------------------------------------
// ----------------------------------------------------------------------------
/**
* Sends a file to the server for upload.
* The file is selected via the file input element 'settings-input'.
*/
function importSettings() {
const settings_type = document.getElementById('settings-type').value;
const fileInput = document.getElementById('settings-input');
if (fileInput.files.length === 0) {
alert('Please select a file to upload.');
return;
}
const params = { file: 'settings-input' }; // The value of 'file' corresponds to the input element's ID
apiSubmit('upload/metadata/' + settings_type, params, function (response, error) {
if (error) {
showAjaxError(error, response);
} else {
alert('Es wurden ' + response.inserted + ' Einträge aus der Datei importiert.');
window.location.href = '/';
}
}, true);
}
/**
* Sends transactions in a file or a batch of files to the server for upload.
* The file is selected via the file input element 'file-input' (multiple)
* but every entry is send step-by-step to get results per call directly.
* Therefore this methods differ from the global `apiSubmit()` function.
*/
function uploadIban() {
const iban = document.getElementById('iban-input').value;
if (!iban) {
alert("Keine IBAN angegeben!");
return;
}
const bank_id = document.getElementById('bank-type').value
const fileInput = document.getElementById('file-input');
if (fileInput.files.length === 0) {
alert('Es wurde keine Datei ausgewählt.');
return;
}
const upload_modal = document.getElementById('upload-list');
// Prepare List entry for clone in loop
const open_btn = document.querySelector('#upload-list footer a');
open_btn.setAttribute('disabled', 'true');
const list_table = document.querySelector('#upload-list table');
list_table.innerHTML = "";
const list_tr = document.createElement('tr');
const cell1 = document.createElement('td');
const cell2 = document.createElement('td');
const span = document.createElement('span');
span.setAttribute('aria-busy', "true");
cell2.appendChild(span);
list_tr.appendChild(cell1);
list_tr.appendChild(cell2);
// Use Promises to wait until all uploads finish
// Show Upload Modal once
document.querySelector('#add-iban header button').click();
openModal(upload_modal, { 'currentTarget': { 'dataset': {} } });
const uploadPromises = [];
for (let i = 0; i < fileInput.files.length; i++) {
// DOM
const tr = list_tr.cloneNode(true);
const td2 = tr.querySelector('td:last-child');
const td1 = tr.querySelector('td:first-child');
const file = fileInput.files[i];
let file_name = file.name.slice(-30);
if (file.name.length > 30) {
file_name = '...' + file_name;
}
td1.innerHTML = file_name + '<br><small> </small>';
list_table.appendChild(tr);
// Form
const fileFormData = new FormData();
fileFormData.append('bank', bank_id);
fileFormData.append('file-batch', file);
// Wrap each ajax call in a Promise
const p = new Promise((resolve) => {
const ajax = createAjax(function (response, error) {
let result = '';
let parsed = response || '{}';
if (error) {
console.warn(file.name, error, response);
td2.setAttribute('aria-busy', 'false');
td2.classList.add('error');
td2.innerHTML = '×';
result = parsed.error || 'Fehler beim Import';
resolve({ success: false, file: file.name, result: result });
} else {
td2.setAttribute('aria-busy', 'false');
td2.innerHTML = '✔';
result = (parsed.inserted !== undefined) ? (parsed.inserted + ' Transaktionen importiert') : 'OK';
resolve({ success: true, file: file.name, result: result });
}
td1.querySelector('small').innerHTML = result;
});
ajax.open("POST", "/api/upload/" + iban, true);
ajax.send(fileFormData);
});
uploadPromises.push(p);
}
// After all uploads finish, update modal link and re-enable button
Promise.all(uploadPromises).then((results) => {
upload_modal.querySelector('footer a').href = '/' + iban;
open_btn.removeAttribute('disabled');
});
}
/**
* Saves a group with the specified name and associated IBANs.
*
* This function retrieves the group name from an input field and the selected IBANs
* from checkboxes. It then sends the data to the server using the `apiSubmit` function.
* If the operation is successful, the page is reloaded; otherwise, an error message is displayed.
*/
function saveGroup() {
const groupname = document.getElementById("group-input").value;
if (!groupname) {
alert("Keine Gruppe angegeben!");
return;
}
const checkboxes = document.querySelectorAll('input[name="iban-checkbox"]:checked');
const selectedIbans = Array.from(checkboxes).map(checkbox => checkbox.value);
const params = {'ibans': selectedIbans}
apiSubmit('addgroup/' + groupname, params, function (responseText, error) {
if (error) {
showAjaxError(error, responseText);
} else {
alert('Gruppe gespeichert!');
window.location.reload();
}
}, false);
return selectedIbans;
}
/**
* Deletes the database for the given IBAN or the Config for a Groupname
*/
function deleteDB(delete_group) {
let collection;
if (delete_group) {
collection = document.getElementById('group-input').value;
} else {
collection = document.getElementById('iban-input').value;
}
if (!collection) {
alert("Keine IBAN/Gruppe angegeben!");
return;
}
apiGet('deleteDatabase/'+ collection, {}, function (response, error) {
if (error) {
showAjaxError(error, response);
} else {
alert(response.deleted + ' IBAN(s) / Gruppe(n) gelöscht');
window.location.reload();
}
}, 'DELETE');
}
/**
* Re-Parse all transactions in an IBAN-Database with the current settings.
*/
function reParse() {
const iban = document.getElementById('iban-input').value;
if (!iban) {
alert("Keine IBAN angegeben!");
return;
}
// Prepare Result PopUp
const popup = document.getElementById('reparse-iban');
const button = popup.querySelector('footer a');
const progress = popup.querySelector('progress');
const updated = popup.querySelector('p > span');
button.setAttribute('disabled', 'true');
openModal(popup, { 'currentTarget': { 'dataset': {} } });
apiSubmitStreaming('/reparse/' + iban, {},
function(response, error) {
if (error) {
errorPopUp('Neuparse fehlgeschlagen', error, response);
} else {
updated.innerHTML = response.updated || 0;
progress.value = response.processed || 0;
progress.max = response.count || 0;
}
},
function(response) {
updated.innerHTML = response.updated || 0;
progress.value = response.processed || 0;
progress.max = response.count || 0;
button.removeAttribute('disabled');
}
);
}