summaryrefslogtreecommitdiffstats
path: root/apps/projects/src/app/pages/views/entry-form/index.svelte
blob: cb974ed5a9999cbe4a0dbd8911b82faac98cf112 (plain) (blame)
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
<script lang="ts">
    import {TimeEntryDto} from "$shared/lib/models/TimeEntryDto";
    import {Temporal} from "@js-temporal/polyfill";
    import {createEventDispatcher, onMount, onDestroy} from "svelte";
    import DateTimePart from "./sections/date-time.svelte";
    import LabelsPart from "./sections/labels.svelte";
    import CategoryPart from "./sections/category.svelte";
    import Button from "$shared/components/button.svelte";
    import {Textarea} from "$shared/components/form";
    import Alert from "$shared/components/alert.svelte";
    import {is_guid} from "$shared/lib/helpers";
    import {create_entry_async, edit_entry_async} from "$app/lib/stores/entries";

    const dispatch = createEventDispatcher();

    let formError = "";
    let formIsLoading = false;
    let description = "";
    let descriptionError = "";
    let dateTimePart;
    let labelsPart;
    let categoryPart;
    let entryId;

    onMount(() => {
        formIsLoading = true;

        Promise.all([categoryPart.load_categories(), labelsPart.load_labels()]).then(() => {
            formIsLoading = false;
        });

        window.addEventListener("keydown", handle_window_keydown);
    });

    onDestroy(() => {
        window.removeEventListener("keydown", handle_window_keydown);
    });

    function handle_window_keydown(event) {
        if (event.ctrlKey && event.code === "Enter") {
            submit_form();
        }
    }

    function validate_form() {
        return dateTimePart.is_valid() && categoryPart.is_valid() && description_is_valid();
    }

    function description_is_valid() {
        if (!description) {
            descriptionError = "Description is required";
        } else {
            descriptionError = "";
        }

        return description;
    }

    function get_payload() {
        const response = {} as TimeEntryDto;
        const values = get_values();
        if (!is_guid(values.id)) {
            delete values.id;
        } else {
            response.id = values.id;
        }

        const currentTimeZone = Temporal.Now.zonedDateTimeISO().offset;
        response.start = values.date + "T" + values.fromTimeValue + currentTimeZone.toString();
        response.stop = values.date + "T" + values.toTimeValue + currentTimeZone.toString();

        response.category = {
            id: values.category.id,
        };

        const selectedLabels = values.labels;
        if (selectedLabels?.length > 0 ?? false) {
            response.labels = selectedLabels;
        }

        const descriptionContent = description?.trim();
        if (descriptionContent?.length > 0 ?? false) {
            response.description = descriptionContent;
        }

        return response;
    }

    async function submit_form() {
        formError = "";
        if (validate_form()) {
            const payload = get_payload() as TimeEntryDto;
            formIsLoading = true;
            if (is_guid(payload.id)) {
                const response = await edit_entry_async(payload);
                if (response.ok) {
                    functions.reset();
                    dispatch("updated", response.data);
                } else {
                    formError = "An error occured while updating the entry, try again soon";
                    formIsLoading = false;
                }
            } else {
                const response = await create_entry_async(payload);
                if (response.ok) {
                    functions.reset();
                    dispatch("created");
                } else {
                    formError = "An error occured while creating the entry, try again soon";
                    formIsLoading = false;
                }
            }
        }
    }

    function get_values() {
        return {
            id: entryId,
            toTimeValue: dateTimePart.get_to_time_value(),
            fromTimeValue: dateTimePart.get_from_time_value(),
            date: dateTimePart.get_date(),
            category: categoryPart.get_selected(),
            labels: labelsPart.get_selected(),
            description: description,
        };
    }

    export const functions = {
        set_values(values) {
            entryId = values.id;
            dateTimePart.set_values(values);
            labelsPart.select_labels(values?.labels.map((c) => c.id) ?? []);
            categoryPart.select_category(values?.category?.id);
            description = values.description;
        },
        set_time(value: {to: Temporal.PlainTime, from: Temporal.PlainTime}) {
            dateTimePart.set_times(value);
        },
        set_description(value: string) {
            if (description) description = description + "\n\n" + value;
            else description = value;
        },
        reset() {
            formIsLoading = false;
            entryId = "";
            labelsPart.reset();
            categoryPart.reset();
            dateTimePart.reset(true);
            description = "";
            formError = "";
        },
    };
</script>

<form on:submit|preventDefault={submit_form}
      on:reset={() => functions.reset()}>
    <div class="margin-y-sm">
        <Alert visible={formError !== ""}
               message={formError}
               type="error"/>
    </div>

    <div class="margin-bottom-sm">
        <DateTimePart bind:functions={dateTimePart}/>
    </div>

    <div class="margin-bottom-sm">
        <CategoryPart bind:functions={categoryPart}/>
    </div>

    <div class="margin-bottom-sm">
        <LabelsPart bind:functions={labelsPart}/>
    </div>

    <div class="margin-bottom-sm">
        <Textarea class="width-100%"
                  id="description"
                  label="Description"
                  errorText="{descriptionError}"
                  bind:value={description}></Textarea>
    </div>

    <div class="flex flex-row justify-end gap-x-xs">
        {#if entryId}
            <Button text="Reset"
                    on:click={() => functions.reset()}
                    variant="subtle"
            />
        {/if}
        <Button loading={formIsLoading}
                type="submit"
                variant="primary"
                text={entryId ? "Save" : "Create"}
        />
    </div>
</form>