Home

mint @main - refs - log -
-
https://git.jolheiser.com/mint.git
Budget
tree log patch
use go tool for sqlc Signed-off-by: jolheiser <git@jolheiser.com>
Signature
-----BEGIN SSH SIGNATURE----- U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAgBTEvCQk6VqUAdN2RuH6bj1dNkY oOpbPWj+jw4ua1B1cAAAADZ2l0AAAAAAAAAAZzaGE1MTIAAABTAAAAC3NzaC1lZDI1NTE5 AAAAQAtNRG8ULMqXIS64bzwOa/DYPgBAECmkHuvsO/M4vPhUUD5H6Axxiwleg+Z3AZpBfo kAPU0/Oq1pbRnoIO71gA0= -----END SSH SIGNATURE-----
jolheiser <git@jolheiser.com>
3 months ago
11 changed files, 426 additions(+), 105 deletions(-)
.air.toml.gitignoredatabase/models.godatabase/sqlc/migrations/001_schema.up.sqldatabase/sqlc/queries/transactions.sqldatabase/sqlc/sqlc.godatabase/transactions.sql.goimport.goindex.htmlmain.gorouter.go
I .air.toml
 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
diff --git a/.air.toml b/.air.toml
new file mode 100644
index 0000000000000000000000000000000000000000..477b5f6d14d55df9fcc39a654d710b19cf3be5a0
--- /dev/null
+++ b/.air.toml
@@ -0,0 +1,25 @@
+root = "."
+testdata_dir = "testdata"
+tmp_dir = "tmp"
+
+[build]
+  bin = "./mint"
+  cmd = "go build"
+  delay = 1000
+  #exclude_file = ["internal/html/tailwind.go"]
+  exclude_regex = ["_test.go"]
+  exclude_unchanged = true
+  include_ext = ["go", "html", "sql"]
+  pre_cmd = ["go generate ./..."]
+
+[misc]
+  clean_on_exit = true
+
+[proxy]
+  app_port = 8080
+  enabled = true
+  proxy_port = 8081
+
+[screen]
+  clear_on_rebuild = true
+
I .gitignore
1
2
3
4
5
6
7
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..3d3f43b3532d18176467ad1970c71e686436c130
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/mint*
M database/models.go -> database/models.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
diff --git a/database/models.go b/database/models.go
index 2d7fc91cf703bf14521cf673885bd117ea53e670..8d0ddd72f0d35180623d1f79c44f6a187b7d2746 100644
--- a/database/models.go
+++ b/database/models.go
@@ -14,4 +14,6 @@ 	Title      string
 	Amount     int64
 	Date       time.Time
 	Recurrance string
+	Week       int64
+	IsIncome   bool
 }
M database/sqlc/migrations/001_schema.up.sql -> database/sqlc/migrations/001_schema.up.sql
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
diff --git a/database/sqlc/migrations/001_schema.up.sql b/database/sqlc/migrations/001_schema.up.sql
index 9adffc94e5619c9e81bbc1b0ba56d014e58774c5..e10f67049ff0fd5f336379efdbc4d7cafc96552c 100644
--- a/database/sqlc/migrations/001_schema.up.sql
+++ b/database/sqlc/migrations/001_schema.up.sql
@@ -3,5 +3,7 @@     id         INTEGER PRIMARY KEY,
     title      TEXT    NOT NULL,
     amount     INTEGER NOT NULL,
     date       DATE    NOT NULL,
-    recurrance TEXT    NOT NULL
+    recurrance TEXT    NOT NULL,
+    week       INTEGER NOT NULL,
+    is_income  BOOLEAN NOT NULL DEFAULT FALSE
 );
M database/sqlc/queries/transactions.sql -> database/sqlc/queries/transactions.sql
 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
diff --git a/database/sqlc/queries/transactions.sql b/database/sqlc/queries/transactions.sql
index 7f96a96debdb5d2b23ebf9d9b958668087119c10..f3bd56e9690f2397b052c6ff36694f17e119bece 100644
--- a/database/sqlc/queries/transactions.sql
+++ b/database/sqlc/queries/transactions.sql
@@ -4,19 +4,19 @@ WHERE id = ? LIMIT 1;
 
 -- name: ListTransactions :many
 SELECT * FROM transactions
-WHERE date > ? AND date < ?;
+WHERE date BETWEEN ? AND ?;
 
 -- name: CreateTransaction :one
 INSERT INTO transactions (
-    title, amount, date, recurrance
+    title, amount, date, recurrance, week, is_income
 ) VALUES (
-    ?, ?, ?, ?
+    ?, ?, ?, ?, ?, ?
 )
 RETURNING *;
 
 -- name: UpdateTransaction :one
 UPDATE transactions
-SET title = ?, amount = ?, date = ?, recurrance = ?
+SET title = ?, amount = ?, date = ?, recurrance = ?, week = ?, is_income = ?
 WHERE id = ?
 RETURNING *;
 
M database/sqlc/sqlc.go -> database/sqlc/sqlc.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
diff --git a/database/sqlc/sqlc.go b/database/sqlc/sqlc.go
index 453ecc0c0ae67684749184d979cc8b9b93aaf567..fe7be91944ef0ae946fc3d555db8c4406d3acc95 100644
--- a/database/sqlc/sqlc.go
+++ b/database/sqlc/sqlc.go
@@ -1,4 +1,4 @@
-//go:generate sqlc generate
+//go:generate go tool sqlc generate
 package sqlc
 
 import (
M database/transactions.sql.go -> database/transactions.sql.go
  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
diff --git a/database/transactions.sql.go b/database/transactions.sql.go
index 3db2b494275d52bc29f333ac66ab726c11b2d175..f1aeea36704370894710e2216dcdf246b32b1442 100644
--- a/database/transactions.sql.go
+++ b/database/transactions.sql.go
@@ -12,11 +12,11 @@ )
 
 const createTransaction = `-- name: CreateTransaction :one
 INSERT INTO transactions (
-    title, amount, date, recurrance
+    title, amount, date, recurrance, week, is_income
 ) VALUES (
-    ?, ?, ?, ?
+    ?, ?, ?, ?, ?, ?
 )
-RETURNING id, title, amount, date, recurrance
+RETURNING id, title, amount, date, recurrance, week, is_income
 `
 
 type CreateTransactionParams struct {
@@ -24,6 +24,8 @@ 	Title      string
 	Amount     int64
 	Date       time.Time
 	Recurrance string
+	Week       int64
+	IsIncome   bool
 }
 
 func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionParams) (Transaction, error) {
@@ -32,6 +34,8 @@ 		arg.Title,
 		arg.Amount,
 		arg.Date,
 		arg.Recurrance,
+		arg.Week,
+		arg.IsIncome,
 	)
 	var i Transaction
 	err := row.Scan(
@@ -40,6 +44,8 @@ 		&i.Title,
 		&i.Amount,
 		&i.Date,
 		&i.Recurrance,
+		&i.Week,
+		&i.IsIncome,
 	)
 	return i, err
 }
@@ -55,7 +61,7 @@ 	return err
 }
 
 const getTransaction = `-- name: GetTransaction :one
-SELECT id, title, amount, date, recurrance from transactions
+SELECT id, title, amount, date, recurrance, week, is_income from transactions
 WHERE id = ? LIMIT 1
 `
 
@@ -68,22 +74,24 @@ 		&i.Title,
 		&i.Amount,
 		&i.Date,
 		&i.Recurrance,
+		&i.Week,
+		&i.IsIncome,
 	)
 	return i, err
 }
 
 const listTransactions = `-- name: ListTransactions :many
-SELECT id, title, amount, date, recurrance FROM transactions
-WHERE date > ? AND date < ?
+SELECT id, title, amount, date, recurrance, week, is_income FROM transactions
+WHERE date BETWEEN ? AND ?
 `
 
 type ListTransactionsParams struct {
-	Date   time.Time
-	Date_2 time.Time
+	FromDate time.Time
+	ToDate   time.Time
 }
 
 func (q *Queries) ListTransactions(ctx context.Context, arg ListTransactionsParams) ([]Transaction, error) {
-	rows, err := q.db.QueryContext(ctx, listTransactions, arg.Date, arg.Date_2)
+	rows, err := q.db.QueryContext(ctx, listTransactions, arg.FromDate, arg.ToDate)
 	if err != nil {
 		return nil, err
 	}
@@ -97,6 +105,8 @@ 			&i.Title,
 			&i.Amount,
 			&i.Date,
 			&i.Recurrance,
+			&i.Week,
+			&i.IsIncome,
 		); err != nil {
 			return nil, err
 		}
@@ -113,9 +123,9 @@ }
 
 const updateTransaction = `-- name: UpdateTransaction :one
 UPDATE transactions
-SET title = ?, amount = ?, date = ?, recurrance = ?
+SET title = ?, amount = ?, date = ?, recurrance = ?, week = ?, is_income = ?
 WHERE id = ?
-RETURNING id, title, amount, date, recurrance
+RETURNING id, title, amount, date, recurrance, week, is_income
 `
 
 type UpdateTransactionParams struct {
@@ -123,6 +133,8 @@ 	Title      string
 	Amount     int64
 	Date       time.Time
 	Recurrance string
+	Week       int64
+	IsIncome   bool
 	ID         int64
 }
 
@@ -132,6 +144,8 @@ 		arg.Title,
 		arg.Amount,
 		arg.Date,
 		arg.Recurrance,
+		arg.Week,
+		arg.IsIncome,
 		arg.ID,
 	)
 	var i Transaction
@@ -141,6 +155,8 @@ 		&i.Title,
 		&i.Amount,
 		&i.Date,
 		&i.Recurrance,
+		&i.Week,
+		&i.IsIncome,
 	)
 	return i, err
 }
I import.go
 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
diff --git a/import.go b/import.go
new file mode 100644
index 0000000000000000000000000000000000000000..3a933349e80af98913e54b09fd752cb81028ba26
--- /dev/null
+++ b/import.go
@@ -0,0 +1,69 @@
+//go:build import
+
+package main
+
+import (
+	"context"
+	"database/sql"
+	"encoding/json"
+	"errors"
+	"flag"
+	"fmt"
+	"os"
+	"time"
+
+	"github.com/golang-migrate/migrate/v4"
+	"go.jolheiser.com/mint/database"
+	"go.jolheiser.com/mint/database/sqlc/migrations"
+)
+
+type budget struct {
+	Title  string
+	Amount float64
+	Date   time.Time
+}
+
+func main() {
+	b := flag.String("budget", "budget.json", "Path to existing budget")
+	d := flag.String("database", "mint.sqlite3", "Path to database file")
+	flag.Parse()
+
+	data, err := os.ReadFile(*b)
+	if err != nil {
+		panic(err)
+	}
+
+	dsn := fmt.Sprintf("file:%s", *d)
+	sdb, err := sql.Open("sqlite", dsn)
+	if err != nil {
+		panic(err)
+	}
+
+	migrator, err := migrations.New(sdb)
+	if err != nil {
+		panic(err)
+	}
+
+	if err := migrator.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
+		panic(err)
+	}
+
+	db := database.New(sdb)
+
+	var transactions []budget
+	if err := json.Unmarshal(data, &transactions); err != nil {
+		panic(err)
+	}
+
+	for _, t := range transactions {
+		if _, err := db.CreateTransaction(context.Background(), database.CreateTransactionParams{
+			Title:      t.Title,
+			Amount:     int64(t.Amount * 100),
+			Date:       t.Date,
+			Recurrance: "month",
+		}); err != nil {
+			panic(err)
+		}
+	}
+	fmt.Println("Import complete")
+}
M index.html -> index.html
  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
diff --git a/index.html b/index.html
index f5d49a66afd414539f1b220cbb6f2d4cb8d2ae31..a759bf1a1bc64da41fb7dd82270f9e03c98554b9 100644
--- a/index.html
+++ b/index.html
@@ -9,7 +9,6 @@   <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
   <script>
     let MINT_DEBUG = true;
     const now = new Date();
-    let events = [{id: '1', title: 'A bill! ($200)', start: now, allDay: true, extendedProps: {title: 'A bill!', amount: 200, recurring: true}}, {id: '3', title: 'Subscription! ($10)', start: now, allDay: true, extendedProps: {title: 'Subscription!', amount: 10, recurring: true}}, {id: '2', title: 'Another bill! ($150)', start: new Date(now.getTime() + (1000 * 60 * 60 * 24 * 2)), allDay: true, extendedProps: {title: 'Another bill!', amount: 150, recurring: false}}];
     let calendar;
 
     document.addEventListener('DOMContentLoaded', function () {
@@ -20,43 +19,60 @@         dayMaxEventRows: true,
         headerToolbar: {
           left: 'prev,next today',
           center: 'title',
-          right: ''
+          right: 'dayGridWeek,dayGridMonth,dayGridYear'
         },
         selectable: true,
         select: (info) => {
           if (MINT_DEBUG) console.log(info);
           const days = Math.floor(Math.abs(info.end - info.start) / (1000 * 60 * 60 * 24));
           if (days == 1) {
-            toast('add transaction', 'info');
             input(info.start);
             return;
           }
-          toast('show mini stats for range', 'info');
           const events = calendar.getEvents().filter((event) => {
             const start = event.start;
             const end = event.end || event.start;
             return start < info.end && end >= info.start
           });
           if (MINT_DEBUG) console.log(events);
-          const sum = events.reduce((acc, event) => acc + event.extendedProps.amount, 0);
-          toast(`\$${sum / 100}`, 'success')
+          const sum = events.filter((event) => !event.extendedProps.income).reduce((acc, event) => acc + event.extendedProps.amount, 0);
+          toast(`\$${sum / 100}`, 'info')
+        },
+        eventStartEditable: true,
+        eventDrop: (info) => {
+          const event = info.event;
+          const props = event.extendedProps;
+          fetch("/transaction", {
+            method: "PATCH",
+            body: JSON.stringify({
+              id: event.id,
+              start: event.start,
+              extendedProps: {
+                title: props.title,
+                amount: props.amount,
+                recurrance: props.recurrance,
+                week: props.week,
+                income: props.income
+              }
+            })
+          }).then(() => calendar.refetchEvents());
         },
         eventClick: (info) => {
           const event = info.event;
           const props = event.extendedProps;
-          input(event.start, event.id, props.title, props.amount / 100, props.recurring);
+          input(event.start, event.id, props.title, props.amount / 100, props.recurrance, props.income);
         },
         eventClassNames: (info) => {
           const classes = ['cursor-pointer'];
           if (toDate(info.event.start) < toDate(now)) classes.push("bg-gray-500!", "border-gray-500!");
           return classes;
         },
-        events: "/data",
+        events: "/events",
       });
       calendar.render();
     });
 
-    function input(time, id = '', title = 'New Transaction', amount = 0, recurring = true) {
+    function input(time, id = '', title = 'New Transaction', amount = 0, recurrance = "month", income = false) {
       const weekDay = time.getDay();
       const monthDay = time.getDate();
       Swal.fire({
@@ -66,19 +82,20 @@           <div class="grid grid-cols-1 gap-x-4 gap-y-3 items-center text-left">
             <input type="hidden" name="id" value="${id}"/>
             <input type="hidden" name="date" value="${time.toISOString()}"/>
             <label class="font-semibold">Amount: $<input class="border rounded w-30 mx-px p-1" type="number" name="amount" value="${amount}"/></label>
-            <label class="font-semibold">Recurring? <input class="border rounded w-4 h-4" type="checkbox" name="recurring" ${recurring ? "checked" : ""}/></label>
-            <div id="recurringOptions" class="${recurring ? "" : "hidden"}">
-              <label><input type="radio" name="recurrance"/> Monthly on the ${ordinal(monthDay)}</label>
+            <label class="font-semibold">Recurring? <input class="border rounded w-4 h-4" type="checkbox" name="recurring" ${recurrance !== "" ? "checked" : ""}/></label>
+            <div id="recurringOptions" class="${recurrance !== "" ? "" : "hidden"}">
+              <label><input type="radio" name="recurrance" ${recurrance === "month" ? "checked" : ""} value="month"/> Monthly on the ${ordinal(monthDay)}</label>
               <br/>
-              <label><input type="radio" name="recurrance"/> Every <input class="border rounded w-15 p-1" type="number" min="1" max="4" value="1"/> weeks on ${dayOfWeek(weekDay)}</label>
+              <label><input type="radio" name="recurrance" ${recurrance.endsWith("week") ? "checked" : ""} value="week"/> Every <input name="week" class="border rounded w-15 p-1" type="number" min="1" max="4" value="${recurrance.endsWith("week") ? recurrance.substring(0, 1) : "1"}"/> weeks on ${dayOfWeek(weekDay)}</label>
             </div>
+            <label class="font-semibold">Income? <input class="border rounded w-4 h-4" type="checkbox" name="income" ${income ? "checked" : ""}/></label>
           </div>
         `,
         allowOutsideClick: false,
         showCloseButton: true,
         reverseButtons: true,
         confirmButtonText: 'Save',
-        showDenyButton: true,
+        showDenyButton: id !== '',
         denyButtonText: 'Delete',
         customClass: {
           confirmButton: 'ml-[15rem]!'
@@ -90,6 +107,12 @@           $recurring.addEventListener('change', () => {
             $recurring.checked ? $opts.classList.remove('hidden') : $opts.classList.add('hidden');
           });
         },
+        preDeny: () => {
+          const $popup = Swal.getPopup();
+          return {
+            id: $popup.querySelector("[name='id']").value
+          };
+        },
         preConfirm: () => {
           const $popup = Swal.getPopup();
           return {
@@ -97,27 +120,22 @@             id: $popup.querySelector("[name='id']").value,
             date: new Date($popup.querySelector("[name='date']").value),
             title: $popup.querySelector("[name='title']").value,
             amount: parseFloat($popup.querySelector("[name='amount']").value),
-            recurring: $popup.querySelector("[name='recurring']").checked
-          }
+            recurrance: $popup.querySelector("[name='recurring']").checked ? $popup.querySelector("[name='recurrance']:checked").value : '',
+            week: $popup.querySelector("[name='week']").value,
+            income: $popup.querySelector("[name='income']").checked
+          };
         },
       }).then((result) => {
-        if (!result.isConfirmed) return;
         const value = result.value;
-        if (MINT_DEBUG) console.log(value);
-        if (value.id !== "") {
-          // FIXME
-          const event = events.find((e) => e.id === value.id);
-          event.title = `${value.title} (\$${value.amount})`;
-          event.extendedProps.title = value.title;
-          event.extendedProps.amount = value.amount;
-          event.extendedProps.recurring = value.recurring;
-          calendar.getEventById(id).remove();
-          calendar.addEvent(event);
-          if (MINT_DEBUG) console.log('Event Modified:', event);
-          return;
+        if (result.isDenied) {
+          fetch("/transaction", {
+            method: "DELETE",
+            body: JSON.stringify(value)
+          }).then(() => calendar.refetchEvents());
+          return
         }
-        // FIXME
-        value.id = `${events.length + 1}`
+        if (!result.isConfirmed) return;
+        if (MINT_DEBUG) console.log(value);
         const event = {
           id: value.id,
           title: `${value.title} (\$${value.amount})`,
@@ -125,12 +143,24 @@           start: new Date(value.date),
           allDay: true,
           extendedProps: {
             title: value.title,
-            amount: value.amount,
-            recurring: value.recurring
+            amount: value.amount * 100,
+            recurrance: value.recurrance,
+            week: value.week,
+            income: value.income
           }
         };
-        events.push(event);
-        calendar.addEvent(event);
+        if (event.id !== "") {
+          fetch("/transaction", {
+            method: "PATCH",
+            body: JSON.stringify(event)
+          }).then(() => calendar.refetchEvents());
+          if (MINT_DEBUG) console.log('Event Modified:', event);
+          return;
+        }
+        fetch("/transaction", {
+          method: "POST",
+          body: JSON.stringify(event)
+        }).then(() => calendar.refetchEvents());
         if (MINT_DEBUG) console.log('Event Added:', event);
       });
     }
M main.go -> main.go
  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
diff --git a/main.go b/main.go
index 69842ae02be9b4c9501bda13cf083968d9172f70..8b101e3605bf03fae6a71e3f7bfe562b7fec015a 100644
--- a/main.go
+++ b/main.go
@@ -1,8 +1,9 @@
 package main
 
 import (
+	"database/sql"
 	_ "embed"
-	"encoding/json"
+	"errors"
 	"flag"
 	"fmt"
 	"html/template"
@@ -10,30 +11,21 @@ 	"log/slog"
 	"net/http"
 	"os"
 	"os/signal"
-	"strconv"
 	"strings"
-	"time"
 
+	"github.com/golang-migrate/migrate/v4"
 	"github.com/peterbourgon/ff/v3"
 	"go.jolheiser.com/ffjsonnet"
+	"go.jolheiser.com/mint/database"
+	"go.jolheiser.com/mint/database/sqlc/migrations"
 )
 
 var (
 	//go:embed index.html
 	_indexTmpl string
 	indexTmpl  = template.Must(template.New("").Parse(_indexTmpl))
-	//go:embed budget.json
-	_json []byte
 )
 
-type Event struct {
-	ID            string         `json:"id"`
-	AllDay        bool           `json:"allDay"`
-	Start         time.Time      `json:"start"`
-	Title         string         `json:"title"`
-	ExtendedProps map[string]any `json:"extendedProps"`
-}
-
 type Args struct {
 	Port     int
 	Database string
@@ -63,12 +55,14 @@ 			args.LogLevel = slog.LevelWarn
 		case "error":
 			args.LogLevel = slog.LevelError
 		default:
-			return fmt.Errorf("unknown log level %q: valid settings are debug, info, warn, or error")
+			return fmt.Errorf("unknown log level %q: valid settings are debug, info, warn, or error", s)
 		}
 		return nil
 	}
 	fs.Func("log-level", "Logging level [debug, info, warn, error]", logFn)
-	fs.Func("l", "--log-level", logFn)
+	fs.BoolFunc("v", "--log-level debug", func(_ string) error {
+		return logFn("debug")
+	})
 	fs.String("config", "mint.jsonnet", "Config file")
 
 	if err := ff.Parse(fs, os.Args[1:],
@@ -80,50 +74,33 @@ 	); err != nil {
 		return fmt.Errorf("could not parse CLI arguments: %w", err)
 	}
 
-	logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
+	logOpts := &slog.HandlerOptions{Level: args.LogLevel}
+	logger := slog.New(slog.NewTextHandler(os.Stderr, logOpts))
 	if args.JSON {
-		logger = slog.New(slog.NewJSONHandler(os.Stderr, nil))
+		logger = slog.New(slog.NewJSONHandler(os.Stderr, logOpts))
 	}
 	slog.SetDefault(logger)
-	slog.SetLogLoggerLevel(args.LogLevel)
+
+	dsn := fmt.Sprintf("file:%s", args.Database)
+	sdb, err := sql.Open("sqlite", dsn)
+	if err != nil {
+		return fmt.Errorf("could not open database: %w", err)
+	}
+
+	migrator, err := migrations.New(sdb)
+	if err != nil {
+		return fmt.Errorf("could not init migrations: %w", err)
+	}
+
+	if err := migrator.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
+		return fmt.Errorf("could not migrate database: %w", err)
+	}
 
-	mux := http.NewServeMux()
-	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
-		indexTmpl.Execute(w, nil)
-	})
-	mux.HandleFunc("/data", func(w http.ResponseWriter, r *http.Request) {
-		var budget []struct {
-			Title  string
-			Amount float64
-			Date   time.Time
-		}
-		if err := json.Unmarshal(_json, &budget); err != nil {
-			slog.Error("could not unmarshal budget", slog.Any("err", err))
-		}
-		var events []Event
-		var id int
-		for _, b := range budget {
-			events = append(events, Event{
-				ID:     strconv.Itoa(id),
-				AllDay: true,
-				Start:  b.Date,
-				Title:  fmt.Sprintf("%s ($%.2f)", b.Title, b.Amount),
-				ExtendedProps: map[string]any{
-					"title":     b.Title,
-					"amount":    int(b.Amount * 100),
-					"recurring": true,
-				},
-			})
-			id++
-		}
-		w.Header().Set("Content-Type", "application/json")
-		if err := json.NewEncoder(w).Encode(events); err != nil {
-			slog.Error("could not marshal budget data", slog.Any("err", err))
-		}
-	})
+	db := database.New(sdb)
+	mux := mux(db)
 
 	go func() {
-		addr := fmt.Sprintf(":%d", *portFlag)
+		addr := fmt.Sprintf(":%d", args.Port)
 		slog.Debug(fmt.Sprintf("Listening at http://localhost%s", addr))
 		if err := http.ListenAndServe(addr, mux); err != nil {
 			panic(err)
I router.go
  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
diff --git a/router.go b/router.go
new file mode 100644
index 0000000000000000000000000000000000000000..e93778855baa213ba35e80b7ee4953f5a9e358fc
--- /dev/null
+++ b/router.go
@@ -0,0 +1,199 @@
+package main
+
+import (
+	"encoding/json"
+	"fmt"
+	"log/slog"
+	"net/http"
+	"strconv"
+	"strings"
+	"time"
+
+	"go.jolheiser.com/mint/database"
+)
+
+const (
+	blue   = "#3788d8"
+	yellow = "#d4a574"
+	green  = "#a8d5ba"
+	white  = "#fff"
+	black  = "#000"
+)
+
+type Event struct {
+	ID              string        `json:"id"`
+	AllDay          bool          `json:"allDay"`
+	Start           time.Time     `json:"start"`
+	Title           string        `json:"title"`
+	ExtendedProps   ExtendedProps `json:"extendedProps"`
+	BackgroundColor string        `json:"backgroundColor"`
+	BorderColor     string        `json:"borderColor"`
+	TextColor       string        `json:"textColor"`
+}
+
+type ExtendedProps struct {
+	Title      string `json:"title"`
+	Amount     int64  `json:"amount"`
+	Recurrance string `json:"recurrance"`
+	Week       int    `json:"week,string"`
+	Income     bool   `json:"income"`
+}
+
+type router struct {
+	db *database.Queries
+}
+
+func (rt router) index(w http.ResponseWriter, r *http.Request) {
+	indexTmpl.Execute(w, nil)
+}
+
+func (rt router) events(w http.ResponseWriter, r *http.Request) {
+	start, err := time.Parse(time.RFC3339, r.URL.Query().Get("start"))
+	if err != nil {
+		start = time.Time{}
+	}
+	end, err := time.Parse(time.RFC3339, r.URL.Query().Get("end"))
+	if err != nil {
+		end = time.Now()
+	}
+	slog.Debug("retrieving transactions", slog.Time("start", start), slog.Time("end", end))
+	txs, err := rt.db.ListTransactions(r.Context(), database.ListTransactionsParams{
+		FromDate: start,
+		ToDate:   end,
+	})
+	if err != nil {
+		slog.Error("could not list transactions", slog.Any("err", err))
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+		return
+	}
+
+	events := make([]Event, 0)
+	for _, b := range txs {
+		recurrance := b.Recurrance != ""
+
+		bg, border, text := blue, blue, white
+		if b.IsIncome {
+			bg, border, text = green, green, black
+		}
+		if !recurrance {
+			border = yellow
+		}
+		events = append(events, Event{
+			ID:     strconv.FormatInt(b.ID, 10),
+			AllDay: true,
+			Start:  b.Date,
+			Title:  fmt.Sprintf("%s ($%.2f)", b.Title, float64(b.Amount)/100),
+			ExtendedProps: ExtendedProps{
+				Title:      b.Title,
+				Amount:     b.Amount,
+				Recurrance: b.Recurrance,
+				Income:     b.IsIncome,
+			},
+			BackgroundColor: bg,
+			BorderColor:     border,
+			TextColor:       text,
+		})
+	}
+	w.Header().Set("Content-Type", "application/json")
+	if err := json.NewEncoder(w).Encode(events); err != nil {
+		slog.Error("could not marshal budget data", slog.Any("err", err))
+	}
+}
+
+func (rt router) transaction(w http.ResponseWriter, r *http.Request) {
+	var e Event
+	if err := json.NewDecoder(r.Body).Decode(&e); err != nil {
+		slog.Error("could not decode event", slog.Any("err", err))
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+		return
+	}
+
+	recurrance := e.ExtendedProps.Recurrance
+	if recurrance == "week" && e.ExtendedProps.Week != 0 {
+		recurrance = fmt.Sprintf("%dweek", e.ExtendedProps.Week)
+	}
+
+	var t database.Transaction
+	var err error
+	switch r.Method {
+	case http.MethodPost:
+		t, err = rt.db.CreateTransaction(r.Context(), database.CreateTransactionParams{
+			Title:      e.ExtendedProps.Title,
+			Amount:     e.ExtendedProps.Amount,
+			Date:       e.Start,
+			Recurrance: recurrance,
+			IsIncome:   e.ExtendedProps.Income,
+		})
+	case http.MethodPatch:
+		id, err := strconv.ParseInt(e.ID, 10, 64)
+		if err != nil {
+			slog.Error("invalid ID for updating transaction", slog.Any("err", err), slog.String("id", e.ID))
+			http.Error(w, err.Error(), http.StatusBadRequest)
+			return
+		}
+		t, err = rt.db.UpdateTransaction(r.Context(), database.UpdateTransactionParams{
+			Title:      e.ExtendedProps.Title,
+			Amount:     e.ExtendedProps.Amount,
+			Date:       e.Start,
+			Recurrance: recurrance,
+			IsIncome:   e.ExtendedProps.Income,
+			ID:         id,
+		})
+	case http.MethodDelete:
+		id, err := strconv.ParseInt(e.ID, 10, 64)
+		if err != nil {
+			slog.Error("invalid ID for deleting transaction", slog.Any("err", err), slog.String("id", e.ID))
+			http.Error(w, err.Error(), http.StatusBadRequest)
+			return
+		}
+		err = rt.db.DeleteTransaction(r.Context(), id)
+	default:
+		http.Error(w, "invalid method", http.StatusMethodNotAllowed)
+		return
+	}
+
+	if err != nil {
+		slog.Error("could not process transaction", slog.Any("err", err))
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+		return
+	}
+
+	var week int64
+	recurrance = t.Recurrance
+	if strings.HasSuffix(recurrance, "week") {
+		parts := []string{recurrance[:1], recurrance[1:]}
+		week, err = strconv.ParseInt(parts[0], 10, 64)
+		if err != nil {
+			slog.Error("could not parse weeks", slog.Any("err", err))
+			http.Error(w, err.Error(), http.StatusInternalServerError)
+			return
+		}
+		recurrance = parts[1]
+	}
+
+	w.Header().Set("Content-Type", "application/json")
+	json.NewEncoder(w).Encode(Event{
+		ID:     strconv.FormatInt(t.ID, 10),
+		AllDay: true,
+		Start:  t.Date,
+		Title:  fmt.Sprintf("%s ($%.2f)", t.Title, float64(t.Amount)/100),
+		ExtendedProps: ExtendedProps{
+			Title:      t.Title,
+			Amount:     t.Amount,
+			Recurrance: recurrance,
+			Week:       int(week),
+			Income:     t.IsIncome,
+		},
+	})
+}
+
+func mux(db *database.Queries) *http.ServeMux {
+	router := router{
+		db: db,
+	}
+	mux := http.NewServeMux()
+	mux.HandleFunc("/", router.index)
+	mux.HandleFunc("/events", router.events)
+	mux.HandleFunc("/transaction", router.transaction)
+	return mux
+}