-
Notifications
You must be signed in to change notification settings - Fork 0
/
export-wizard.ts
559 lines (476 loc) · 23.2 KB
/
export-wizard.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
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import { Modal, App, Setting, Notice } from "obsidian";
import { ExportData } from "./export-data";
import { WizardPage } from "./export-wizard-page"
import { CustomNotice } from "./custom-notice";
import * as utils from "./utils"
import * as dbQueries from "db-queries";
import moment from "moment"; // A namespace-style import cannot be called or constructed, and will cause a failure at runtime.
export class ExportWizardModal extends Modal {
_dbConfig: dbQueries.DBConfig;
private _resolvePromise: (value: string | null) => void; // Function to resolve the Promise
private _result: string | null = null; // To store the result
private _wasCancelled: boolean = true; // Tracks if the modal was cancelled
private _currentStep: number = 0;
private _animalID: string;
private _exportData: ExportData[] = [];
private _missingSitesIDs: number[] = [];
private _missingSiteIDsIndex: number = 0;
private _projects: string[] = [];
private _locations: string[] = [];
constructor(app: App, dbConfig: dbQueries.DBConfig, animalID: string, exportData: ExportData[]) {
super(app);
this._dbConfig = dbConfig;
this._animalID = animalID;
this._exportData = exportData;
}
// Method to open the modal and return a Promise
openWithPromise(): Promise<string | null> {
return new Promise((resolve) => {
this._resolvePromise = resolve; // Store the resolve function
this.open();
});
}
async onOpen() {
try {
await this.renderCurrentStep();
if (!this._animalID) {
this._result = "Animal ID is required.";
this._resolvePromise(this._result);
this.close();
return;
}
if (!this._exportData || this._exportData.length === 0) {
this._result = "Export data is required.";
this._resolvePromise(this._result);
this.close();
return;
}
// Get current IDs
const currentStackIDs = this._exportData.filter((row) => !!row.stackID).map((row) => row.stackID as number);
const currentExpIDs = this._exportData.filter((row) => !!row.expID).map((row) => row.expID as number);
const currentSiteIDs = this._exportData.filter((row) => !!row.siteID).map((row) => row.siteID as number);
if ((!currentStackIDs || currentStackIDs.length === 0)
|| (!currentExpIDs || currentExpIDs.length === 0)
|| (!currentSiteIDs || currentSiteIDs.length === 0)
) {
this._result = "StackIDs, ExpIDs and SiteIDs must be available in export data.";
this._resolvePromise(this._result);
this.close();
return;
}
// Use a Set to ensure unique site IDs
const distinctStackIDs = Array.from(new Set(currentStackIDs));
const distinctExpIDs = Array.from(new Set(currentExpIDs));
const distinctSiteIDs = Array.from(new Set(currentSiteIDs));
this._missingSitesIDs = await dbQueries.queryMissingSites(this._dbConfig, distinctSiteIDs);
console.log(`Distinct SiteIDs: ${distinctSiteIDs}`);
console.log(`Missing SiteIDs: ${this._missingSitesIDs}`);
const validationResult = await this.ValidateExportData(distinctStackIDs, distinctExpIDs, distinctSiteIDs);
if (validationResult) {
this._result = validationResult;
this._resolvePromise(this._result);
this.close();
return;
}
if (this._missingSitesIDs.length > 0) {
this._currentStep++;
}
else {
this._currentStep += 2;
}
// Allow setting custom CSS for styling (e.g. height)
const { contentEl, modalEl } = this;
modalEl.classList.add("export-wizard-modal");
// Clear previous content
contentEl.empty();
this.renderCurrentStep();
}
catch (err) {
this._result = err.message;
this._resolvePromise(this._result);
this.close();
return;
}
}
async ValidateExportData(stackIDs: number[], expIDs: number[], siteIDs: number[]): Promise<string> { //Promise<string | null>
const messages: string[] = [];
// Check, if provided stackIDs, expIDs and siteIDs (which already exist) are belonging to this animal
const invalidStackIDs = await dbQueries.queryInvalidStacksForAnimal(this._dbConfig, this._animalID, stackIDs);
const invalidExpIDs = await dbQueries.queryInvalidExperimentsForAnimal(this._dbConfig, this._animalID, expIDs);
const invalidSiteIDs = await dbQueries.queryInvalidSitesForAnimal(this._dbConfig, this._animalID, siteIDs);
if ((invalidStackIDs && invalidStackIDs.length > 0)
|| (invalidExpIDs && invalidExpIDs.length > 0)
|| (invalidSiteIDs && invalidSiteIDs.length > 0)
) {
messages.push("Some StackIDs, ExpIDs or SiteIDs are belonging to different animal.");
if (invalidStackIDs && invalidStackIDs.length > 0) {
messages.push(`StackIDs: ${invalidStackIDs.join(", ")}`);
}
if (invalidExpIDs && invalidExpIDs.length > 0) {
messages.push(`ExpIDs: ${invalidExpIDs.join(", ")}`);
}
if (invalidSiteIDs && invalidSiteIDs.length > 0) {
messages.push(`SiteIDs: ${invalidSiteIDs.join(", ")}`);
}
}
// Check, if for each missing Site there is corresponding Stack & Experiment with same ID
if (this._missingSitesIDs && this._missingSitesIDs.length > 0) {
const missingStackExpIDs: number[] = [];
this._missingSitesIDs.forEach(siteID => {
if (this._exportData.filter((row) => row.siteID == siteID && row.stackID == siteID && row.expID == siteID).length === 0) {
missingStackExpIDs.push(siteID);
}
});
if (missingStackExpIDs.length > 0) {
messages.push(`Following new SiteIDs don't have matching StackID / ExpID: ${missingStackExpIDs.join(", ")}`);
}
}
return messages.join("\n");
}
async renderCurrentStep() {
const { contentEl } = this;
contentEl.empty(); // Clear content for new step
switch (this._currentStep) {
case 0:
this.renderStepInitialValidation();
break;
case 1:
this.renderStepNewSite();
break;
case 2:
this.renderStepFinish();
break;
default:
this._resolvePromise(this._result);
this.close();
return;
}
}
private async renderStepInitialValidation() {
const { contentEl } = this;
const titleEl = contentEl.createEl("h3", { text: `Export ${this._animalID}` });
titleEl.classList.add("export-wizard-title");
contentEl.createEl("p", { text: "Validating data..." });
}
private async renderStepNewSite() {
if (this._missingSitesIDs.length == 0) {
throw new Error("Error in renderStepNewSite: _missingSitesIDs is empty.");
}
if (this._missingSiteIDsIndex > 0 && this._missingSiteIDsIndex + 1 > this._missingSitesIDs.length) {
throw new Error(`Error in renderStepNewSite: _missingSiteIDsIndex is out of range (index = ${this._missingSiteIDsIndex}, max. range = ${this._missingSitesIDs.length - 1}).`);
}
// Get projects & locations (used during site creation)
if (this._projects.length == 0) {
this._projects = await dbQueries.queryProjects(this._dbConfig);
}
if (this._locations.length == 0) {
this._locations = await dbQueries.queryLocations(this._dbConfig);
}
// Get the current site (based on _missingSiteIDsIndex)
const currSiteID = this._missingSitesIDs[this._missingSiteIDsIndex];
const { contentEl } = this;
const page = new NewSiteWizardPage(contentEl, this._animalID, currSiteID, this._missingSiteIDsIndex, this._missingSitesIDs.length, this._projects, this._locations);
page.onSuccess(async (result) => {
try {
await dbQueries.addNewSite(this._dbConfig, currSiteID, this._animalID, result.project, result.location, result.depth);
new CustomNotice(`New Site ${currSiteID} added successfully.`, "success-notice");
this._missingSiteIDsIndex++;
if (!(this._missingSiteIDsIndex + 1 <= this._missingSitesIDs.length)) {
this._currentStep++;
}
await this.renderCurrentStep();
}
catch(err) {
new CustomNotice(err.message, "error-notice");
}
});
}
private async renderStepFinish() {
const { contentEl, modalEl } = this;
modalEl.classList.add("finish-wizard-page");
const page = new FinishWizardPage(contentEl, this._animalID, this._exportData);
page.onSuccess(async (result) => {
try {
if (this._exportData && this._exportData.length > 0) {
for (const data of this._exportData) {
// Experiment
const dataExp = { ExpID: data.expID, SiteID: data.siteID };
const countExp = await dbQueries.executeNonQuery(this._dbConfig, "UPDATE dbo.Experiments SET SiteID = @SiteID WHERE ExpID = @ExpID;", dataExp);
if (countExp == 0) {
// If there was no update, then Experiment not yet exists
await dbQueries.executeNonQuery(this._dbConfig, "INSERT INTO dbo.Experiments (ExpID, SiteID) VALUES (@ExpID, @SiteID);", dataExp);
new CustomNotice(`New Experiment ${data.expID} added successfully.`, "success-notice");
}
else {
new CustomNotice(`Experiment ${data.expID} updated successfully.`, "success-notice");
}
// Stack
const stackDate = new Date(data.logDateTime!.getFullYear(), data.logDateTime!.getMonth(), data.logDateTime!.getDate());
const stackTime = moment(data.logDateTime!).format("HH:mm:ss");
const dataStack = { StackID: data.stackID, ExpID: data.expID, StackDate: stackDate, StackTime: stackTime, Comment: data.comment };
const countStack = await dbQueries.executeNonQuery(this._dbConfig, "UPDATE dbo.Stacks SET ExpID = @ExpID, StackDate = @StackDate, StackTime = @StackTime, Comment = @Comment WHERE StackID = @StackID;", dataStack);
if (countStack == 0) {
// If there was no update, then Stack not yet exists
await dbQueries.executeNonQuery(this._dbConfig, "INSERT INTO dbo.Stacks (StackID, ExpID, StackDate, StackTime, Comment) VALUES (@StackID, @ExpID, @StackDate, @StackTime, @Comment);", dataStack);
new CustomNotice(`New Stack ${data.stackID} added successfully.`, "success-notice");
}
else {
new CustomNotice(`Stack ${data.stackID} updated successfully.`, "success-notice");
}
};
this._wasCancelled = false;
this.close();
}
}
catch(err) {
new CustomNotice(err.message, "error-notice");
}
});
page.onCancelled(async () => {
this.close();
});
}
onClose() {
const { contentEl } = this;
contentEl.empty(); // Clean up modal
// Check cancellation
if (this._wasCancelled) {
console.log("Modal was cancelled (Close button or Esc key).");
this._result = "User cancelled the export.";
}
this._resolvePromise(this._result); // Resolve the Promise with the result
}
}
class NewSiteWizardPage extends WizardPage {
private _projectType: string = "existing";
private _locationType: string = "existing";
private _projects: string[] = [];
private _locations: string[] = [];
private _currentSiteID: number;
private _currentProjectName: string = "";
private _currentLocationName: string = "";
private _currentDepthString: string = "";
private _projectContainer: HTMLElement;
private _locationContainer: HTMLElement;
private _depthContainer: HTMLElement;
constructor(parentEl: HTMLElement, animalID: string, currentSiteID: number, currentSitesIndex: number, totalSitesCount: number, existingProjects: string[], existingLocations: string[]) {
super(parentEl, animalID);
this._projects = existingProjects;
this._locations = existingLocations;
this._currentSiteID = currentSiteID;
this.renderPageContent(currentSitesIndex, totalSitesCount);
}
private renderPageContent(currentSitesIndex: number, totalSitesCount: number) {
const { _containerEl: containerEl } = this;
// Header
const titleEl = containerEl.createEl("h3", { text: `Create New Site: ${this._currentSiteID}` });
titleEl.classList.add("export-wizard-title");
const descriptionEl = containerEl.createEl("p", {
text: `Step ${currentSitesIndex + 1} of ${totalSitesCount} - Please provide project and location details.`,
});
// Project Section
this._projectContainer = containerEl.createDiv({ cls: "project-container" });
this.renderProjectSection();
// Location Section
this._locationContainer = containerEl.createDiv({ cls: "location-container" });
this.renderLocationSection();
// Depth Section
this._depthContainer = containerEl.createDiv({ cls: "depth-container" });
this.renderDepthSection();
// Call the parent renderPage to display content and buttons
this.renderPage(
[titleEl, descriptionEl, this._projectContainer, this._locationContainer, this._depthContainer], // Content elements
false, // Never show "Back" button for new sites as data is saved when clicking on "Next" (currentSitesIndex > 0)
true // Show "Next" button
);
}
// Render Project Section
private renderProjectSection() {
this._projectContainer.empty(); // Clear previous content
this._projectContainer.createEl("h4", { text: "Project" });
// Create a container for the dropdown
const dropdownContainer = this._projectContainer.createDiv({ cls: "project-type-container" });
// Create the dropdown element
const dropdown = dropdownContainer.createEl("select", { cls: "project-type-dropdown" });
// Add dropdown options
const options = [
{ value: "existing", label: "Existing" },
{ value: "new", label: "New" },
];
options.forEach((option) => {
const opt = dropdown.createEl("option", { text: option.label, value: option.value });
if (option.value === this._projectType) {
opt.selected = true;
}
});
// Handle dropdown change
dropdown.addEventListener("change", (event: Event) => {
const target = event.target as HTMLSelectElement;
this._projectType = target.value;
console.log(`Project type selected: ${this._projectType}`);
this.renderProjectInputs(); // Re-render inputs below
});
this.renderProjectInputs();
}
private renderProjectInputs() {
let inputContainer = this._projectContainer.querySelector(".project-inputs") as HTMLElement;
if (!inputContainer) {
inputContainer = this._projectContainer.createDiv({ cls: "project-inputs" });
}
inputContainer.empty(); // Clear previous inputs
if (this._projectType === "existing") {
new Setting(inputContainer)
.setName("Select Existing Project")
.addDropdown((dropdown) => {
this._projects.forEach((project) => dropdown.addOption(project, project));
dropdown.setValue(this._currentProjectName);
dropdown.selectEl.classList.add("project-selection-dropdown");
dropdown.onChange((value) => {
this._currentProjectName = value;
console.log(`Selected Existing Project: ${value}`);
});
});
} else {
new Setting(inputContainer)
.setName("New Project Name")
.addText((text) => {
text.setPlaceholder("Enter project name...")
.setValue(this._currentProjectName)
.onChange((value) => {
this._currentProjectName = value;
console.log(`New Project Name: ${value}`);
});
text.inputEl.classList.add("project-selection-textbox");
});
}
}
// Render Location Section
private renderLocationSection() {
this._locationContainer.empty(); // Clear previous content
this._locationContainer.createEl("h4", { text: "Location" });
// Create a container for the dropdown
const dropdownContainer = this._locationContainer.createDiv({ cls: "location-type-container" });
// Create the dropdown element
const dropdown = dropdownContainer.createEl("select", { cls: "location-type-dropdown" });
// Add dropdown options
const options = [
{ value: "existing", label: "Existing" },
{ value: "new", label: "New" },
];
options.forEach((option) => {
const opt = dropdown.createEl("option", { text: option.label, value: option.value });
if (option.value === this._locationType) {
opt.selected = true;
}
});
// Handle dropdown change
dropdown.addEventListener("change", (event: Event) => {
const target = event.target as HTMLSelectElement;
this._locationType = target.value;
console.log(`Location type selected: ${this._locationType}`);
this.renderLocationInputs(); // Re-render inputs below
});
this.renderLocationInputs();
}
private renderLocationInputs() {
let inputContainer = this._locationContainer.querySelector(".location-inputs") as HTMLElement;
if (!inputContainer) {
inputContainer = this._locationContainer.createDiv({ cls: "location-inputs" });
}
inputContainer.empty(); // Clear previous inputs
if (this._locationType === "existing") {
new Setting(inputContainer)
.setName("Select Existing Location")
.addDropdown((dropdown) => {
this._locations.forEach((location) => dropdown.addOption(location, location));
dropdown.setValue(this._currentLocationName);
dropdown.selectEl.classList.add("location-selection-dropdown");
dropdown.onChange((value) => {
this._currentLocationName = value;
console.log(`Selected Existing Location: ${value}`);
});
});
} else {
new Setting(inputContainer)
.setName("New Location Name")
.addText((text) => {
text.setPlaceholder("Enter location name...")
.setValue(this._currentLocationName)
.onChange((value) => {
this._currentLocationName = value;
console.log(`New Location Name: ${value}`);
});
text.inputEl.classList.add("location-selection-textbox");
});
}
}
private renderDepthSection() {
this._depthContainer.empty(); // Clear previous content
this._depthContainer.createEl("h4", { text: "Depth" });
new Setting(this._depthContainer)
.setName("Depth")
.setDesc("optional")
.addText((text) => {
text.setPlaceholder("Enter depth...")
.setValue(this._currentDepthString)
.onChange((value) => {
this._currentDepthString = value;
});
text.inputEl.classList.add("depth-selection-textbox");
});
}
protected onBack(): void {
console.log("Back button clicked - cancellation.");
this.triggerCancelled();
}
protected async onNext(): Promise<void> {
// Validation logic
if (!this._currentProjectName || !this._currentLocationName) {
new CustomNotice("Please provide Project and Location!", "warning-notice");
return;
}
let currentDepth: number | null = null;
if (this._currentDepthString) {
if (utils.isInteger(this._currentDepthString)) {
currentDepth = Number(this._currentDepthString);
console.log(`Depth: ${currentDepth}`);
}
else {
new CustomNotice("Please provide valid integer for Depth!", "warning-notice");
return
}
}
console.log("Proceeding to the next step...");
console.log(`Project: ${this._currentProjectName}, Location: ${this._currentLocationName}, Depth: ${currentDepth}`);
this.triggerSuccess({
project: this._currentProjectName,
location: this._currentLocationName,
depth: currentDepth,
});
}
}
class FinishWizardPage extends WizardPage {
private _exportData: ExportData[] = [];
constructor(parentEl: HTMLElement, animalID: string, exportData: ExportData[]) {
super(parentEl, animalID, "Cancel", "Finish");
this._exportData = exportData;
this.renderPageContent();
}
private renderPageContent() {
const { _containerEl: containerEl } = this;
containerEl.empty(); // Clear previous content
const titleEl = containerEl.createEl("h4", { text: "Please click on Finish button." });
titleEl.classList.add("export-wizard-title");
const descriptionEl = containerEl.createEl("p", { text: `The number of rows exported will be ${this._exportData.length}.` });
// Call the parent renderPage to display content and buttons
this.renderPage([titleEl, descriptionEl], true, true);
}
protected onBack(): void {
console.log("Back button clicked - cancellation.");
this.triggerCancelled();
}
protected async onNext(): Promise<void> {
// Just trigger success - export is handled in callback.
this.triggerSuccess();
}
}