aboutsummaryrefslogtreecommitdiff
path: root/fe/src/lib/forms/AddForm.svelte
blob: f85cce61c5105bdb58b653239743036ad2b26e4a (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
<script lang='ts'>
    import { createEventDispatcher } from "svelte";
    import { token, user } from "../../stores/auth";
    import type { Statistic } from "../../types";
    import { apiURL } from "../../utils";

    export let open: boolean;

    const dispatch = createEventDispatcher();

    const statistic: Statistic = newStatistic();

    function newStatistic(): Statistic {
        let now = new Date(),
            month,
            day,
            year;

        month = `${now.getMonth() + 1}`;
        day = `${now.getDate()}`;
        year = now.getFullYear();
        if (month.length < 2) month = "0" + month;
        if (day.length < 2) day = "0" + day;

        const date = [year, month, day].join("-");

        return {
            user_id: $user!.uuid,
            date,
            quantity: 1
        };
    }

    function closeDialog() {
        dispatch("close");
    }

    async function handleSubmitStat()
    {
        const { date, quantity } = statistic;
        await fetch(apiURL("stats"), {
            method: "POST",
            headers: {
                Authorization: `Bearer ${$token}`
            },
            body: JSON.stringify({
                date: new Date(date),
                user_id: 2,
                quantity
            })
        });
        dispatch("submit");
    }

</script>

<dialog {open} on:submit={handleSubmitStat}>
    <h2>Add Water</h2>
    <form method="dialog">
        <div class="form input group">
            <label for="date">Date:</label>
            <input bind:value={statistic.date} id="date" name="date" type="date" />
        </div>
        <div class="form input group">
            <label for="quantity">Quantity:</label>
            <input
                bind:value={statistic.quantity}
                id="quantity"
                name="quantity"
                type="number"
                min="0"
                autocomplete="off"
            />
        </div>
        <button on:click={closeDialog}>Cancel</button>
        <button type="submit">Submit</button>
    </form>
</dialog>