aboutsummaryrefslogtreecommitdiff
path: root/src/components/FileUploads.svelte
blob: 46327482fbadc52000491d7f6377c43188b8c00e (plain)
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
<script lang="ts">
  import { Label } from "@smui/button";
  import IconButton from "@smui/icon-button";
  import Snackbar, { Actions } from "@smui/snackbar";
  import UploadButton from "./helpers/UploadButton.svelte";
  import Card from "./helpers/Card.svelte";
  import {
    parseDatabaseFile,
    parseLabScheduleFile,
    parseOfficeHoursFile,
    parsePTFile,
    readQuestionnaire,
  } from "../logic/EditorActions";
  import { labStore, ptStore } from "../stores";

  let ptSchedules: FileList | null;
  let labSchedule: FileList | null;
  let dbFile: FileList | null;
  let questionnaire_file: FileList | null;
  let officehoursFiles: FileList | null;
  let snackbar: Snackbar;
  let snackbarText;

  $: {
    if (ptSchedules?.length) {
      const promises = [...ptSchedules].map((file) => parsePTFile(file));
      Promise.allSettled(promises)
        .then((results) =>
          results.flatMap((result) => {
            if (result.status === "fulfilled") {
              // TODO uploading a new schedule to a PT just updates the previous value. This means that if we re-upload a PT that already exists (and who has labs assigned), then the new version of this PT will not have those labs (good), but all those labs will still be marked as assigned in `lab.assigned`. Maybe call a `pt.delete` function if the PT already exists when attempting to add.
              ptStore.update((val) => val.set(result.value.id, result.value));
              return [];
            } else {
              return [result];
            }
          })
        )
        .then((failed) => {
          if (failed.length) {
            snackbarText = `Failed to add ${failed.length} PTs. See console for details.`;
            snackbar.open();
          }
        })
        .finally(() => {
          snackbarText = "Successfully imported Peer Teacher/s!";
          snackbar.open();
        });
    }
  }

  $: {
    if (labSchedule?.length) {
      parseLabScheduleFile(labSchedule[0])
        .then((labs) => {
          labStore.update(() => new Map(labs.map((lab) => [lab.id, lab])));
        })
        .catch(() => {
          snackbarText =
            "Failed to import lab schedule. See console for details.";
          snackbar.open();
        })
        .finally(() => {
          snackbarText = "Successfully imported Lab/s!";
          snackbar.open();
        });
    }
  }

  $: {
    if (dbFile?.length) {
      parseDatabaseFile(dbFile[0])
        .then((database) => {
          labStore.set(database.labs);
          ptStore.set(database.peerTeachers);
        })
        .catch(() => {
          snackbarText = "Failed to import database. See console for details.";
          snackbar.open();
        })
        .finally(() => {
          snackbarText = "Successfully imported database!";
          snackbar.open();
        });
    }
  }

  $: {
    if (questionnaire_file?.length) {
      readQuestionnaire(questionnaire_file[0]);
    }
  }

  $: {
    if (officehoursFiles?.length) {
      parseOfficeHoursFile(officehoursFiles[0]);
    }
  }

  function dbStringify(): string {
    const peerTeachers = [...$ptStore.values()];
    const labs = [...$labStore.values()];
    const database = {
      labs: labs,
      peerTeachers: peerTeachers,
    };

    const dbObj = JSON.stringify(database, (_, value) => {
      // Need to manually convert the PeerTeacher objects'
      // `labs` set to an array because `JSON.stringify` doesn't
      // support "stringing" it out of the box
      if (typeof value === "object" && value instanceof Set) {
        return [...value];
      }
      return value;
    });

    return dbObj;
  }

  function exportDB() {
    const dbObj = dbStringify();
    const blob = new Blob([dbObj], { type: "text/json" });
    const anchor = document.createElement("a");
    const url = window.URL.createObjectURL(blob);
    anchor.href = url;
    anchor.download = "pt-db.json";
    anchor.style.display = "none";
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
    window.URL.revokeObjectURL(url);
  }

  function exportDB2LocalStorage() {
    const db = dbStringify();
    localStorage.setItem("db", db);
  }
</script>

<div class="flex grid m-10 grid-cols-2 gap-2 w-[70%] ">
  <Card title="Data Base" desc="">
    <UploadButton
      color="btn-info"
      accept="application/json"
      multiple={true}
      bind:files={dbFile}
    />
    <button class="btn btn-warning" on:click={exportDB}>Download</button>
    <button class="btn btn-ghost" on:click={exportDB2LocalStorage}
      >LocalStorage</button
    >
  </Card>

  <Card title="Peer Teachers" desc="">
    <label class="btn btn-info">
      Schedules
      <input type="file" accept="text/plain" bind:files={ptSchedules} hidden />
    </label>
    <label class="btn btn-secondary">
      Straw Poll
      <input
        type="file"
        accept="text/csv"
        bind:files={officehoursFiles}
        hidden
      />
    </label>
    <label class="btn btn-error">
      Questionnaire
      <input
        type="file"
        accept="text/csv"
        bind:files={questionnaire_file}
        hidden
      />
    </label>
  </Card>

  <Card
    title="Labs"
    desc="Upload one or more Labs as json file. Acquired from Howdy"
  >
    <UploadButton
      color="btn-success"
      accept="application/json"
      multiple={true}
      bind:files={labSchedule}
    />
  </Card>
</div>

<!-- https://github.com/saadeghi/daisyui/issues/221 -->
<!-- Snackbar is a work in progress for Daisyui. Until then, keep smui -->
<Snackbar bind:this={snackbar} labelText={snackbarText}>
  <Label />
  <Actions>
    <IconButton class="material-icons" title="Dismiss">close</IconButton>
  </Actions>
</Snackbar>