Compare commits
255 Commits
0.4.3
...
ee59499bba
Author | SHA1 | Date | |
---|---|---|---|
ee59499bba | |||
67c79e252e | |||
3b1174225a | |||
92f56b1046 | |||
f068dd5009 | |||
ebc34d7031 | |||
03ea4a31ad | |||
8636d04b84 | |||
c63a8bc5d3 | |||
0aae7236ae | |||
91ed57f83d | |||
0817f18e33 | |||
704a520993 | |||
a48509e041 | |||
b812b19b34 | |||
0667e5a779 | |||
f47ede2060 | |||
91ac05b575 | |||
c30b33a070 | |||
4fa227c452 | |||
cfb1dbe276 | |||
8f99499c2f | |||
d22816dfd1 | |||
75a1839456 | |||
9fd70cd773 | |||
3b465f17cf | |||
f56d095016 | |||
741589dc71 | |||
44254ed4d0 | |||
777520e9df | |||
07c0c56d11 | |||
43a4647d74 | |||
c595f016b8 | |||
6702a775fb | |||
e4df2f0de5 | |||
ff06693f60 | |||
5c5429ab05 | |||
65424a2587 | |||
4563fcbbaf | |||
df7b691bdd | |||
f5274f69fc | |||
c50fc63303 | |||
88e1dbdfde | |||
0e84cdfa5f | |||
d29405bef3 | |||
46e665efc5 | |||
f3eb19ef91 | |||
2ca05b5d48 | |||
ed2eb53f93 | |||
8bf4fcfd42 | |||
38222c0777 | |||
f43feb66be | |||
49be1d5be6 | |||
8ec69e4b8f | |||
6b3026dc8e | |||
9b5119d3dd | |||
08f48a63ad | |||
c4fc80e47d | |||
23bd12147c | |||
3ca7bfeade | |||
249aa534c8 | |||
76ee88a1c6 | |||
bb664494f6 | |||
4f681d6d89 | |||
11df0fbff1 | |||
a2280e50ec | |||
ed321d3895 | |||
8fe91293e1 | |||
35690681cf | |||
54e591bc5e | |||
01c407d4f1 | |||
cef62574bb | |||
ae529665a3 | |||
2eba947d9d | |||
4d70f50683 | |||
9b67e700be | |||
cce9f29f17 | |||
eb2b31e622 | |||
967f1c71e5 | |||
585951d5e2 | |||
e7af03b702 | |||
a1ec7e9997 | |||
880ed731f8 | |||
a46ddded67 | |||
56485b8deb | |||
f67f6ff0d8 | |||
150a7d562b | |||
49d96be1e3 | |||
8df7968175 | |||
bd99f58ab4 | |||
9471c5b63b | |||
60d6967728 | |||
1913d9eaf0 | |||
8954cffb7a | |||
95eb302d26 | |||
93679c2932 | |||
cb8ce79107 | |||
80c0f0a231 | |||
d73eeb1b40 | |||
ce466e0031 | |||
684efffbdf | |||
cf39db52fb | |||
f0993fd9c3 | |||
5f6bea4ee2 | |||
4332a1537b | |||
2feefea737 | |||
2d9c380cf4 | |||
4a66d9fdfc | |||
967ea784dc | |||
23b7a4dbdd | |||
4798cb95b0 | |||
8eabf3d1c8 | |||
f0084b683e | |||
84c95d0c4e | |||
6576c994c9 | |||
a552983ac4 | |||
f99efe0e8e | |||
e1b6056d77 | |||
94329ac331 | |||
bfa67578cf | |||
eae196aa69 | |||
d2dd7d5280 | |||
f707197f42 | |||
66322ebd86 | |||
3ea90a5ebe | |||
d717ef1b4d | |||
61a534610f | |||
d8d713f841 | |||
7ac06012ec | |||
9af412a8bd | |||
3b61028576 | |||
87b78e7b67 | |||
6a71d9643c | |||
450324d29e | |||
6f4e286b7a | |||
324e13f5c5 | |||
0201b368d4 | |||
984a2aa296 | |||
d1a0296a58 | |||
d9efa9f4a1 | |||
b176ce26ba | |||
97de326527 | |||
a62ab543b0 | |||
244333adbc | |||
67ef4745a0 | |||
3856e8a8a5 | |||
db96fddde2 | |||
ecb801b2f2 | |||
fd6b77f154 | |||
442e87234c | |||
caf39fe5ea | |||
0dde94f855 | |||
34bbdf48b7 | |||
1e495a5e47 | |||
fc29b1409d | |||
8ecfd6b87a | |||
d89e702669 | |||
3795150508 | |||
67c013799d | |||
0038db90ac | |||
9759a7cc1e | |||
81c31a3d5f | |||
38e21786a7 | |||
971c3d3be5 | |||
946f14c1cc | |||
9ce0da0182 | |||
4c93e4635d | |||
f3a50c790b | |||
0c5f68ed80 | |||
7fdd8bd935 | |||
d4287f8aac | |||
6712af10d9 | |||
70edb382e1 | |||
390a042441 | |||
e8028dae34 | |||
fc249adc9e | |||
c186a14644 | |||
8a27303670 | |||
44e9bb6ec0 | |||
42d431ba8b | |||
3727061065 | |||
c7a8adb3ab | |||
29f534bf10 | |||
15381c84f6 | |||
a0cabbf4f7 | |||
f26ee8f472 | |||
4fb3c2a335 | |||
8899ff5772 | |||
347a0c9e50 | |||
66b8e1f69f | |||
5d1b49c896 | |||
42dc51fe9a | |||
1ca95f8768 | |||
a73f7c2934 | |||
489aa88c4b | |||
7b5b16c1b2 | |||
29cfeb6fa6 | |||
42baafd273 | |||
1e79f193be | |||
f0ec7fb30d | |||
034f4f2a90 | |||
51ece59866 | |||
bbfda6f402 | |||
2b3afbf448 | |||
a53c3d23a4 | |||
c899c21256 | |||
cccc948048 | |||
e8a0670a83 | |||
9638676b8f | |||
08bda8d14f | |||
d0ade0f2f1 | |||
466239ce11 | |||
d52e5c63d4 | |||
3dcb362372 | |||
67c9b53e91 | |||
7c08ddacb7 | |||
ecbb85aeaa | |||
3696bbde43 | |||
09a227d08d | |||
dae6185857 | |||
6dd8a3791f | |||
18149eef8b | |||
f0f97a2e77 | |||
71b2f8a9a3 | |||
8f666a0f26 | |||
2b9c76960e | |||
7fd057f9f6 | |||
a9be9367a9 | |||
bc75757ac7 | |||
a3e12df2e2 | |||
024c5e0a1c | |||
27372199f7 | |||
b3b878854e | |||
bbb12a788d | |||
7dfbef60a4 | |||
d8a96535dc | |||
ce26e76e8f | |||
6b3ac199fc | |||
4c6d21c2b4 | |||
faef975f1a | |||
bd686e0c00 | |||
4844889e0b | |||
2775578713 | |||
27dd6e923c | |||
2cf6b815bf | |||
81aacf339e | |||
16bcf516f6 | |||
52503a4c92 | |||
b4321395d9 | |||
d7058a49b0 | |||
eb9fc722aa | |||
511081298e | |||
422a74704b | |||
c4995bcbaf | |||
79fd95e152 |
22
.drone.yml
22
.drone.yml
@ -4,6 +4,11 @@ type: docker
|
|||||||
name: budgeteer
|
name: budgeteer
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
- name: submodules
|
||||||
|
image: alpine/git
|
||||||
|
commands:
|
||||||
|
- git submodule update --recursive --init
|
||||||
|
|
||||||
- name: Taskfile.dev PR
|
- name: Taskfile.dev PR
|
||||||
image: hub.javil.eu/budgeteer:dev
|
image: hub.javil.eu/budgeteer:dev
|
||||||
commands:
|
commands:
|
||||||
@ -18,9 +23,10 @@ steps:
|
|||||||
commands:
|
commands:
|
||||||
- task ci
|
- task ci
|
||||||
when:
|
when:
|
||||||
|
branch:
|
||||||
|
- master
|
||||||
event:
|
event:
|
||||||
exclude:
|
- push
|
||||||
- pull_request
|
|
||||||
|
|
||||||
- name: docker
|
- name: docker
|
||||||
image: plugins/docker
|
image: plugins/docker
|
||||||
@ -32,7 +38,7 @@ steps:
|
|||||||
from_secret: docker_password
|
from_secret: docker_password
|
||||||
repo: hub.javil.eu/budgeteer
|
repo: hub.javil.eu/budgeteer
|
||||||
context: build
|
context: build
|
||||||
dockerfile: build/Dockerfile
|
dockerfile: docker/Dockerfile
|
||||||
tags:
|
tags:
|
||||||
- latest
|
- latest
|
||||||
when:
|
when:
|
||||||
@ -51,11 +57,19 @@ steps:
|
|||||||
from_secret: docker_password
|
from_secret: docker_password
|
||||||
repo: hub.javil.eu/budgeteer
|
repo: hub.javil.eu/budgeteer
|
||||||
context: build
|
context: build
|
||||||
dockerfile: build/Dockerfile
|
dockerfile: docker/Dockerfile
|
||||||
auto_tag: true
|
auto_tag: true
|
||||||
when:
|
when:
|
||||||
event:
|
event:
|
||||||
- tag
|
- tag
|
||||||
|
|
||||||
|
services:
|
||||||
|
- name: db
|
||||||
|
image: postgres:alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: budgeteer
|
||||||
|
POSTGRES_PASSWORD: budgeteer
|
||||||
|
POSTGRES_DB: budgeteer_test
|
||||||
|
|
||||||
image_pull_secrets:
|
image_pull_secrets:
|
||||||
- hub.javil.eu
|
- hub.javil.eu
|
10
.earthignore
10
.earthignore
@ -1,10 +0,0 @@
|
|||||||
build/
|
|
||||||
.git/
|
|
||||||
docker-compose.yml
|
|
||||||
README.md
|
|
||||||
Earthfile
|
|
||||||
config.example.json
|
|
||||||
.gitignore
|
|
||||||
.vscode/
|
|
||||||
budgeteer
|
|
||||||
budgeteer.exe
|
|
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
[submodule "testdata"]
|
||||||
|
path = testdata
|
||||||
|
url = https://git.javil.eu/jacob1123/budgeteer-testdata.git
|
10
.vscode/settings.json
vendored
10
.vscode/settings.json
vendored
@ -1,9 +1,15 @@
|
|||||||
{
|
{
|
||||||
"files.exclude": {
|
"files.exclude": {
|
||||||
"**/node_modules": true,
|
"**/node_modules": true,
|
||||||
"**/vendor": true
|
"**/vendor": true,
|
||||||
|
"**/*.sql.go": true,
|
||||||
|
".task/": true,
|
||||||
|
"build/": true,
|
||||||
|
"web/dist/": true
|
||||||
},
|
},
|
||||||
"gopls": {
|
"gopls": {
|
||||||
"formatting.gofumpt": true,
|
"formatting.gofumpt": true,
|
||||||
}
|
},
|
||||||
|
"editor.detectIndentation": false,
|
||||||
|
"editor.tabSize": 2
|
||||||
}
|
}
|
@ -1,23 +0,0 @@
|
|||||||
pipeline:
|
|
||||||
build:
|
|
||||||
name: Taskfile.dev
|
|
||||||
image: hub.javil.eu/budgeteer:dev
|
|
||||||
pull: true
|
|
||||||
commands:
|
|
||||||
- task ci
|
|
||||||
|
|
||||||
docker:
|
|
||||||
image: plugins/docker
|
|
||||||
secrets: [ docker_username, docker_password ]
|
|
||||||
settings:
|
|
||||||
registry: hub.javil.eu
|
|
||||||
repo: hub.javil.eu/budgeteer
|
|
||||||
context: build
|
|
||||||
dockerfile: build/Dockerfile
|
|
||||||
tags:
|
|
||||||
- latest
|
|
||||||
when:
|
|
||||||
event: [push, tag, deployment]
|
|
||||||
|
|
||||||
image_pull_secrets:
|
|
||||||
- hub.javil.eu
|
|
21
Earthfile
21
Earthfile
@ -1,21 +0,0 @@
|
|||||||
FROM golang:1.17
|
|
||||||
WORKDIR /src
|
|
||||||
|
|
||||||
build:
|
|
||||||
COPY go.mod go.sum .
|
|
||||||
RUN go mod download
|
|
||||||
COPY . .
|
|
||||||
RUN --mount=type=cache,target=/root/.cache/go-build go build -o build/budgeteer ./cmd/budgeteer
|
|
||||||
SAVE ARTIFACT build/budgeteer /budgeteer AS LOCAL build/budgeteer
|
|
||||||
|
|
||||||
docker:
|
|
||||||
WORKDIR /app
|
|
||||||
COPY +build/budgeteer .
|
|
||||||
ENTRYPOINT ["/app/budgeteer"]
|
|
||||||
SAVE IMAGE hub.javil.eu/budgeteer:latest
|
|
||||||
|
|
||||||
run:
|
|
||||||
LOCALLY
|
|
||||||
WITH DOCKER --load=+docker
|
|
||||||
RUN docker-compose up -d
|
|
||||||
END
|
|
147
Taskfile.yml
147
Taskfile.yml
@ -5,30 +5,31 @@ vars:
|
|||||||
|
|
||||||
tasks:
|
tasks:
|
||||||
default:
|
default:
|
||||||
|
desc: Build budgeteer in production mode
|
||||||
|
deps: [frontend, go-mod, go-sqlc]
|
||||||
cmds:
|
cmds:
|
||||||
- task: build-prod
|
- task: backend
|
||||||
|
|
||||||
sqlc:
|
run:
|
||||||
desc: sqlc code generation
|
desc: Start budgeteer
|
||||||
sources:
|
deps: [backend, go-mod, go-sqlc]
|
||||||
- ./sqlc.yaml
|
|
||||||
- ./postgres/schema/*
|
|
||||||
- ./postgres/queries/*
|
|
||||||
generates:
|
|
||||||
- ./postgres/*.sql.go
|
|
||||||
cmds:
|
cmds:
|
||||||
- sqlc generate
|
- ./build/budgeteer{{exeExt}}
|
||||||
|
|
||||||
gomod:
|
dev:
|
||||||
desc: Go modules
|
desc: Build budgeteer in dev mode (without frontend)
|
||||||
sources:
|
deps: [go-mod, go-sqlc]
|
||||||
- ./go.mod
|
|
||||||
- ./go.sum
|
|
||||||
method: checksum
|
|
||||||
cmds:
|
cmds:
|
||||||
- go mod download
|
- task: backend
|
||||||
|
|
||||||
build:
|
ci:
|
||||||
|
desc: Run CI build
|
||||||
|
deps: [default, static]
|
||||||
|
|
||||||
|
static:
|
||||||
|
deps: [go-lint, go-vet, go-fmt, js-tsc, js-lint, cover]
|
||||||
|
|
||||||
|
backend:
|
||||||
desc: Build budgeteer
|
desc: Build budgeteer
|
||||||
sources:
|
sources:
|
||||||
- ./go.mod
|
- ./go.mod
|
||||||
@ -43,69 +44,99 @@ tasks:
|
|||||||
cmds:
|
cmds:
|
||||||
- go build -o ./build/budgeteer{{exeExt}} ./cmd/budgeteer
|
- go build -o ./build/budgeteer{{exeExt}} ./cmd/budgeteer
|
||||||
|
|
||||||
build-dev:
|
go-vet:
|
||||||
desc: Build budgeteer in dev mode
|
|
||||||
deps: [gomod, sqlc]
|
|
||||||
cmds:
|
cmds:
|
||||||
- go vet
|
- go vet
|
||||||
- go fmt
|
|
||||||
- golangci-lint run
|
|
||||||
- task: build
|
|
||||||
|
|
||||||
build-prod:
|
go-fmt:
|
||||||
desc: Build budgeteer in prod mode
|
|
||||||
deps: [gomod, sqlc, frontend]
|
|
||||||
cmds:
|
cmds:
|
||||||
- go vet
|
|
||||||
- go fmt
|
- go fmt
|
||||||
- golangci-lint run
|
|
||||||
- task: build
|
|
||||||
|
|
||||||
ci:
|
go-lint:
|
||||||
desc: Run CI build
|
|
||||||
cmds:
|
cmds:
|
||||||
- task: build-prod
|
- golangci-lint run
|
||||||
- go test ./...
|
|
||||||
|
go-sqlc:
|
||||||
|
desc: sqlc code generation
|
||||||
|
sources:
|
||||||
|
- ./sqlc.yaml
|
||||||
|
- ./postgres/schema/*
|
||||||
|
- ./postgres/queries/*
|
||||||
|
generates:
|
||||||
|
- ./postgres/*.sql.go
|
||||||
|
cmds:
|
||||||
|
- sqlc generate
|
||||||
|
|
||||||
|
go-mod:
|
||||||
|
desc: Go modules
|
||||||
|
sources:
|
||||||
|
- ./go.mod
|
||||||
|
- ./go.sum
|
||||||
|
method: checksum
|
||||||
|
cmds:
|
||||||
|
- go mod download
|
||||||
|
|
||||||
|
cover:
|
||||||
|
desc: Run test and analyze coverage
|
||||||
|
cmds:
|
||||||
|
- go test ./... -coverprofile=coverage.out -covermode=atomic
|
||||||
|
- go tool cover -html=coverage.out -o=coverage.html
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
desc: Build vue frontend
|
desc: Build vue frontend
|
||||||
dir: web
|
deps: [js-build]
|
||||||
sources:
|
sources:
|
||||||
- web/src/**/*
|
- web/src/**/*
|
||||||
generates:
|
generates:
|
||||||
- web/dist/**/*
|
- web/dist/**/*
|
||||||
|
|
||||||
|
frontend-dev:
|
||||||
|
desc: Run dev-server for frontend
|
||||||
|
dir: web
|
||||||
|
cmds:
|
||||||
|
- yarn run dev
|
||||||
|
|
||||||
|
js-build:
|
||||||
|
dir: web
|
||||||
|
deps: [js-mod]
|
||||||
cmds:
|
cmds:
|
||||||
- yarn
|
|
||||||
- yarn build
|
- yarn build
|
||||||
|
|
||||||
docker:
|
js-mod:
|
||||||
desc: Build budgeeter:latest
|
run: once
|
||||||
deps: [build-prod]
|
|
||||||
sources:
|
sources:
|
||||||
- ./build/budgeteer{{exeExt}}
|
- web/src/package.json
|
||||||
- ./build/Dockerfile
|
- web/src/yarn.lock
|
||||||
|
generates:
|
||||||
|
- web/node_modules/**/*
|
||||||
|
dir: web
|
||||||
cmds:
|
cmds:
|
||||||
- docker build -t {{.IMAGE_NAME}}:latest ./build
|
- yarn
|
||||||
- docker push {{.IMAGE_NAME}}:latest
|
|
||||||
|
js-tsc:
|
||||||
|
dir: web
|
||||||
|
deps: [js-mod]
|
||||||
|
cmds:
|
||||||
|
- yarn run vue-tsc --noEmit
|
||||||
|
|
||||||
|
js-lint:
|
||||||
|
dir: web
|
||||||
|
deps: [js-mod]
|
||||||
|
cmds:
|
||||||
|
- yarn run eslint "./src/**"
|
||||||
|
|
||||||
dev-docker:
|
dev-docker:
|
||||||
desc: Build budgeeter:dev
|
desc: Build budgeeter:dev
|
||||||
sources:
|
sources:
|
||||||
- ./docker/Dockerfile
|
- ./docker/Dockerfile.dev
|
||||||
- ./docker/build.sh
|
|
||||||
- ./web/package.json
|
- ./web/package.json
|
||||||
|
- ./web/yarn.lock
|
||||||
cmds:
|
cmds:
|
||||||
- docker build -t {{.IMAGE_NAME}}:dev . -f docker/Dockerfile
|
- docker build -t {{.IMAGE_NAME}}:dev . -f docker/Dockerfile.dev
|
||||||
- docker push {{.IMAGE_NAME}}:dev
|
- docker push {{.IMAGE_NAME}}:dev
|
||||||
|
|
||||||
run:
|
run-dev:
|
||||||
desc: Start budgeteer
|
desc: Run dev environment in docker
|
||||||
deps: [build-dev]
|
deps: [dev-docker]
|
||||||
cmds:
|
cmds:
|
||||||
- ./build/budgeteer{{exeExt}}
|
- docker-compose -f docker/docker-compose.dev.yml -p budgeteer up -d
|
||||||
|
|
||||||
rundocker:
|
|
||||||
desc: Start docker-compose
|
|
||||||
deps: [docker]
|
|
||||||
cmds:
|
|
||||||
- docker-compose up -d
|
|
@ -1,3 +0,0 @@
|
|||||||
FROM scratch
|
|
||||||
COPY ./budgeteer /app/budgeteer
|
|
||||||
ENTRYPOINT ["/app/budgeteer"]
|
|
@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -16,24 +17,27 @@ import (
|
|||||||
func main() {
|
func main() {
|
||||||
cfg, err := config.LoadConfig()
|
cfg, err := config.LoadConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Could not load config: %v", err)
|
log.Fatalf("load config: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
queries, err := postgres.Connect("pgx", cfg.DatabaseConnection)
|
queries, err := postgres.Connect("pgx", cfg.DatabaseConnection)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed connecting to DB: %v", err)
|
log.Fatalf("connect to database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
static, err := fs.Sub(web.Static, "dist")
|
static, err := fs.Sub(web.Static, "dist")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic("couldn't open static files")
|
panic("open static files")
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenVerifier, err := jwt.NewTokenVerifier(cfg.SessionSecret)
|
||||||
|
if err != nil {
|
||||||
|
panic(fmt.Errorf("create token verifier: %w", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
handler := &server.Handler{
|
handler := &server.Handler{
|
||||||
Service: queries,
|
Service: queries,
|
||||||
TokenVerifier: &jwt.TokenVerifier{
|
TokenVerifier: tokenVerifier,
|
||||||
Secret: cfg.SessionSecret,
|
|
||||||
},
|
|
||||||
CredentialsVerifier: &bcrypt.Verifier{},
|
CredentialsVerifier: &bcrypt.Verifier{},
|
||||||
StaticFS: http.FS(static),
|
StaticFS: http.FS(static),
|
||||||
}
|
}
|
||||||
|
@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"DatabaseHost": "localhost",
|
|
||||||
"DatabaseUser": "user",
|
|
||||||
"DatabasePassword": "thisismypassword",
|
|
||||||
"DatabaseName": "budgeteer"
|
|
||||||
}
|
|
@ -1,17 +1,3 @@
|
|||||||
FROM alpine as godeps
|
FROM scratch
|
||||||
RUN apk --no-cache add go
|
COPY ./budgeteer /app/budgeteer
|
||||||
RUN go install github.com/kyleconroy/sqlc/cmd/sqlc@latest
|
ENTRYPOINT ["/app/budgeteer"]
|
||||||
RUN go install github.com/go-task/task/v3/cmd/task@latest
|
|
||||||
RUN go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
|
|
||||||
|
|
||||||
FROM alpine
|
|
||||||
RUN apk --no-cache add go nodejs yarn bash curl git git-perl tmux
|
|
||||||
ADD docker/build.sh /
|
|
||||||
RUN yarn global add @vue/cli
|
|
||||||
ENV PATH="/root/.yarn/bin/:${PATH}"
|
|
||||||
WORKDIR /src/web
|
|
||||||
ADD web/package.json web/yarn.lock /src/web/
|
|
||||||
RUN yarn
|
|
||||||
WORKDIR /src
|
|
||||||
COPY --from=godeps /root/go/bin/task /root/go/bin/sqlc /root/go/bin/golangci-lint /usr/local/bin/
|
|
||||||
CMD /build.sh
|
|
||||||
|
15
docker/Dockerfile.dev
Normal file
15
docker/Dockerfile.dev
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
FROM alpine as godeps
|
||||||
|
RUN apk --no-cache add go
|
||||||
|
RUN go install github.com/kyleconroy/sqlc/cmd/sqlc@latest
|
||||||
|
RUN go install github.com/go-task/task/v3/cmd/task@latest
|
||||||
|
RUN go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
|
||||||
|
|
||||||
|
FROM alpine
|
||||||
|
RUN apk --no-cache add go nodejs yarn bash curl git git-perl
|
||||||
|
ENV PATH="/root/.yarn/bin/:${PATH}"
|
||||||
|
WORKDIR /src/web
|
||||||
|
ADD web/package.json web/yarn.lock /src/web/
|
||||||
|
WORKDIR /src
|
||||||
|
VOLUME /go
|
||||||
|
VOLUME /.cache
|
||||||
|
COPY --from=godeps /root/go/bin/task /root/go/bin/sqlc /root/go/bin/golangci-lint /usr/local/bin/
|
@ -1,26 +1,31 @@
|
|||||||
version: '3.7'
|
version: '3.7'
|
||||||
|
|
||||||
services:
|
services:
|
||||||
app:
|
backend:
|
||||||
image: hub.javil.eu/budgeteer:dev
|
image: hub.javil.eu/budgeteer:dev
|
||||||
container_name: budgeteer
|
command: task -w run
|
||||||
stdin_open: true # docker run -i
|
|
||||||
tty: true # docker run -t
|
|
||||||
ports:
|
ports:
|
||||||
- 1323:1323
|
- 1323:1323
|
||||||
- 3000:3000
|
|
||||||
user: '1000'
|
|
||||||
volumes:
|
volumes:
|
||||||
- ~/budgeteer:/src
|
- ~/budgeteer:/src
|
||||||
- ~/.gitconfig:/.gitconfig
|
- go-cache:/go
|
||||||
- ~/.go:/go
|
- yarn-cache:/.cache
|
||||||
- ~/.cache:/.cache
|
|
||||||
environment:
|
environment:
|
||||||
BUDGETEER_DB: postgres://budgeteer:budgeteer@db:5432/budgeteer
|
BUDGETEER_DB: postgres://budgeteer:budgeteer@db:5432/budgeteer
|
||||||
BUDGETEER_SESSION_SECRET: random string for JWT authorization
|
BUDGETEER_SESSION_SECRET: random string for JWT authorization
|
||||||
depends_on:
|
depends_on:
|
||||||
- db
|
- db
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
image: hub.javil.eu/budgeteer:dev
|
||||||
|
command: task frontend-dev
|
||||||
|
ports:
|
||||||
|
- 3000:3000
|
||||||
|
volumes:
|
||||||
|
- ~/budgeteer:/src
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
|
||||||
db:
|
db:
|
||||||
image: postgres:14
|
image: postgres:14
|
||||||
ports:
|
ports:
|
||||||
@ -41,3 +46,5 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
db:
|
db:
|
||||||
|
go-cache:
|
||||||
|
yarn-cache:
|
2
go.mod
2
go.mod
@ -11,7 +11,7 @@ require (
|
|||||||
golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa
|
golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa
|
||||||
)
|
)
|
||||||
|
|
||||||
require github.com/DATA-DOG/go-txdb v0.1.5 // indirect
|
require github.com/DATA-DOG/go-txdb v0.1.5
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||||
|
1
go.sum
1
go.sum
@ -74,6 +74,7 @@ github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+
|
|||||||
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
|
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
|
||||||
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
||||||
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||||
|
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
|
||||||
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||||
|
@ -12,32 +12,45 @@ import (
|
|||||||
|
|
||||||
// TokenVerifier verifies Tokens.
|
// TokenVerifier verifies Tokens.
|
||||||
type TokenVerifier struct {
|
type TokenVerifier struct {
|
||||||
Secret string
|
Expiration time.Duration
|
||||||
|
secret string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Token contains everything to authenticate a user.
|
const DefaultExpiration = time.Hour * time.Duration(72)
|
||||||
type Token struct {
|
|
||||||
username string
|
func NewTokenVerifier(secret string) (*TokenVerifier, error) {
|
||||||
name string
|
if secret == "" {
|
||||||
expiry float64
|
return nil, ErrEmptySecret
|
||||||
id uuid.UUID
|
}
|
||||||
|
|
||||||
|
return &TokenVerifier{
|
||||||
|
Expiration: DefaultExpiration,
|
||||||
|
secret: secret,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
var (
|
||||||
expiration = 72
|
ErrUnexpectedSigningMethod = fmt.Errorf("unexpected signing method")
|
||||||
|
ErrInvalidToken = fmt.Errorf("token is invalid")
|
||||||
|
ErrTokenExpired = fmt.Errorf("token has expired")
|
||||||
|
ErrEmptySecret = fmt.Errorf("secret is required")
|
||||||
)
|
)
|
||||||
|
|
||||||
// CreateToken creates a new token from username and name.
|
// CreateToken creates a new token from username and name.
|
||||||
func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
|
func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
|
||||||
|
if tv.secret == "" {
|
||||||
|
return "", ErrEmptySecret
|
||||||
|
}
|
||||||
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||||
"usr": user.Email,
|
"usr": user.Email,
|
||||||
"name": user.Name,
|
"name": user.Name,
|
||||||
"exp": time.Now().Add(time.Hour * expiration).Unix(),
|
"exp": time.Now().Add(tv.Expiration).Unix(),
|
||||||
"id": user.ID,
|
"id": user.ID,
|
||||||
})
|
})
|
||||||
|
|
||||||
// Generate encoded token and send it as response.
|
// Generate encoded token and send it as response.
|
||||||
t, err := token.SignedString([]byte(tv.Secret))
|
t, err := token.SignedString([]byte(tv.secret))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("create token: %w", err)
|
return "", fmt.Errorf("create token: %w", err)
|
||||||
}
|
}
|
||||||
@ -45,19 +58,17 @@ func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
|
|||||||
return t, nil
|
return t, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
// VerifyToken verifies a given string-token.
|
||||||
ErrUnexpectedSigningMethod = fmt.Errorf("unexpected signing method")
|
|
||||||
ErrInvalidToken = fmt.Errorf("token is invalid")
|
|
||||||
ErrTokenExpired = fmt.Errorf("token has expired")
|
|
||||||
)
|
|
||||||
|
|
||||||
// VerifyToken verifys a given string-token.
|
|
||||||
func (tv *TokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error) { //nolint:ireturn
|
func (tv *TokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error) { //nolint:ireturn
|
||||||
|
if tv.secret == "" {
|
||||||
|
return nil, ErrEmptySecret
|
||||||
|
}
|
||||||
|
|
||||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
return nil, fmt.Errorf("method '%v': %w", token.Header["alg"], ErrUnexpectedSigningMethod)
|
return nil, fmt.Errorf("method '%v': %w", token.Header["alg"], ErrUnexpectedSigningMethod)
|
||||||
}
|
}
|
||||||
return []byte(tv.Secret), nil
|
return []byte(tv.secret), nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("parse jwt: %w", err)
|
return nil, fmt.Errorf("parse jwt: %w", err)
|
||||||
@ -76,36 +87,3 @@ func (tv *TokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error
|
|||||||
}
|
}
|
||||||
return tkn, nil
|
return tkn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func verifyToken(token *jwt.Token) (jwt.MapClaims, error) {
|
|
||||||
if !token.Valid {
|
|
||||||
return nil, ErrInvalidToken
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, ok := token.Claims.(jwt.MapClaims)
|
|
||||||
if !ok {
|
|
||||||
return nil, ErrInvalidToken
|
|
||||||
}
|
|
||||||
|
|
||||||
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
|
|
||||||
return nil, ErrTokenExpired
|
|
||||||
}
|
|
||||||
|
|
||||||
return claims, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Token) GetName() string {
|
|
||||||
return t.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Token) GetUsername() string {
|
|
||||||
return t.username
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Token) GetExpiry() float64 {
|
|
||||||
return t.expiry
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Token) GetID() uuid.UUID {
|
|
||||||
return t.id
|
|
||||||
}
|
|
49
jwt/token.go
Normal file
49
jwt/token.go
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
package jwt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/dgrijalva/jwt-go"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Token contains everything to authenticate a user.
|
||||||
|
type Token struct {
|
||||||
|
username string
|
||||||
|
name string
|
||||||
|
expiry float64
|
||||||
|
id uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyToken(token *jwt.Token) (jwt.MapClaims, error) {
|
||||||
|
if !token.Valid {
|
||||||
|
return nil, ErrInvalidToken
|
||||||
|
}
|
||||||
|
|
||||||
|
claims, ok := token.Claims.(jwt.MapClaims)
|
||||||
|
if !ok {
|
||||||
|
return nil, ErrInvalidToken
|
||||||
|
}
|
||||||
|
|
||||||
|
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
|
||||||
|
return nil, ErrTokenExpired
|
||||||
|
}
|
||||||
|
|
||||||
|
return claims, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Token) GetName() string {
|
||||||
|
return t.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Token) GetUsername() string {
|
||||||
|
return t.username
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Token) GetExpiry() float64 {
|
||||||
|
return t.expiry
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Token) GetID() uuid.UUID {
|
||||||
|
return t.id
|
||||||
|
}
|
@ -1,10 +1,13 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: accounts.sql
|
// source: accounts.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
|
||||||
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
|
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
@ -14,7 +17,7 @@ const createAccount = `-- name: CreateAccount :one
|
|||||||
INSERT INTO accounts
|
INSERT INTO accounts
|
||||||
(name, budget_id)
|
(name, budget_id)
|
||||||
VALUES ($1, $2)
|
VALUES ($1, $2)
|
||||||
RETURNING id, budget_id, name, on_budget
|
RETURNING id, budget_id, name, on_budget, is_open, last_reconciled
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateAccountParams struct {
|
type CreateAccountParams struct {
|
||||||
@ -30,12 +33,14 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A
|
|||||||
&i.BudgetID,
|
&i.BudgetID,
|
||||||
&i.Name,
|
&i.Name,
|
||||||
&i.OnBudget,
|
&i.OnBudget,
|
||||||
|
&i.IsOpen,
|
||||||
|
&i.LastReconciled,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const getAccount = `-- name: GetAccount :one
|
const getAccount = `-- name: GetAccount :one
|
||||||
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget FROM accounts
|
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled FROM accounts
|
||||||
WHERE accounts.id = $1
|
WHERE accounts.id = $1
|
||||||
`
|
`
|
||||||
|
|
||||||
@ -47,13 +52,16 @@ func (q *Queries) GetAccount(ctx context.Context, id uuid.UUID) (Account, error)
|
|||||||
&i.BudgetID,
|
&i.BudgetID,
|
||||||
&i.Name,
|
&i.Name,
|
||||||
&i.OnBudget,
|
&i.OnBudget,
|
||||||
|
&i.IsOpen,
|
||||||
|
&i.LastReconciled,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const getAccounts = `-- name: GetAccounts :many
|
const getAccounts = `-- name: GetAccounts :many
|
||||||
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget FROM accounts
|
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled FROM accounts
|
||||||
WHERE accounts.budget_id = $1
|
WHERE accounts.budget_id = $1
|
||||||
|
AND accounts.is_open = TRUE
|
||||||
ORDER BY accounts.name
|
ORDER BY accounts.name
|
||||||
`
|
`
|
||||||
|
|
||||||
@ -71,6 +79,8 @@ func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Accoun
|
|||||||
&i.BudgetID,
|
&i.BudgetID,
|
||||||
&i.Name,
|
&i.Name,
|
||||||
&i.OnBudget,
|
&i.OnBudget,
|
||||||
|
&i.IsOpen,
|
||||||
|
&i.LastReconciled,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -86,19 +96,25 @@ func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Accoun
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getAccountsWithBalance = `-- name: GetAccountsWithBalance :many
|
const getAccountsWithBalance = `-- name: GetAccountsWithBalance :many
|
||||||
SELECT accounts.id, accounts.name, accounts.on_budget, SUM(transactions.amount)::decimal(12,2) as balance
|
SELECT accounts.id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled,
|
||||||
|
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW())::decimal(12,2) as working_balance,
|
||||||
|
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status IN ('Cleared', 'Reconciled'))::decimal(12,2) as cleared_balance,
|
||||||
|
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status = 'Reconciled')::decimal(12,2) as reconciled_balance
|
||||||
FROM accounts
|
FROM accounts
|
||||||
LEFT JOIN transactions ON transactions.account_id = accounts.id AND transactions.date < NOW()
|
|
||||||
WHERE accounts.budget_id = $1
|
WHERE accounts.budget_id = $1
|
||||||
GROUP BY accounts.id, accounts.name
|
AND accounts.is_open = TRUE
|
||||||
ORDER BY accounts.name
|
ORDER BY accounts.name
|
||||||
`
|
`
|
||||||
|
|
||||||
type GetAccountsWithBalanceRow struct {
|
type GetAccountsWithBalanceRow struct {
|
||||||
ID uuid.UUID
|
ID uuid.UUID
|
||||||
Name string
|
Name string
|
||||||
OnBudget bool
|
OnBudget bool
|
||||||
Balance numeric.Numeric
|
IsOpen bool
|
||||||
|
LastReconciled sql.NullTime
|
||||||
|
WorkingBalance numeric.Numeric
|
||||||
|
ClearedBalance numeric.Numeric
|
||||||
|
ReconciledBalance numeric.Numeric
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsWithBalanceRow, error) {
|
func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsWithBalanceRow, error) {
|
||||||
@ -114,7 +130,11 @@ func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID
|
|||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Name,
|
&i.Name,
|
||||||
&i.OnBudget,
|
&i.OnBudget,
|
||||||
&i.Balance,
|
&i.IsOpen,
|
||||||
|
&i.LastReconciled,
|
||||||
|
&i.WorkingBalance,
|
||||||
|
&i.ClearedBalance,
|
||||||
|
&i.ReconciledBalance,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -132,7 +152,8 @@ func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID
|
|||||||
const searchAccounts = `-- name: SearchAccounts :many
|
const searchAccounts = `-- name: SearchAccounts :many
|
||||||
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
|
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
|
||||||
WHERE accounts.budget_id = $1
|
WHERE accounts.budget_id = $1
|
||||||
AND accounts.name LIKE $2
|
AND accounts.is_open = TRUE
|
||||||
|
AND accounts.name ILIKE $2
|
||||||
ORDER BY accounts.name
|
ORDER BY accounts.name
|
||||||
`
|
`
|
||||||
|
|
||||||
@ -176,28 +197,48 @@ func (q *Queries) SearchAccounts(ctx context.Context, arg SearchAccountsParams)
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const setLastReconciled = `-- name: SetLastReconciled :exec
|
||||||
|
UPDATE accounts
|
||||||
|
SET last_reconciled = NOW()
|
||||||
|
WHERE accounts.id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) SetLastReconciled(ctx context.Context, id uuid.UUID) error {
|
||||||
|
_, err := q.db.ExecContext(ctx, setLastReconciled, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
const updateAccount = `-- name: UpdateAccount :one
|
const updateAccount = `-- name: UpdateAccount :one
|
||||||
UPDATE accounts
|
UPDATE accounts
|
||||||
SET name = $1,
|
SET name = $1,
|
||||||
on_budget = $2
|
on_budget = $2,
|
||||||
WHERE accounts.id = $3
|
is_open = $3
|
||||||
RETURNING id, budget_id, name, on_budget
|
WHERE accounts.id = $4
|
||||||
|
RETURNING id, budget_id, name, on_budget, is_open, last_reconciled
|
||||||
`
|
`
|
||||||
|
|
||||||
type UpdateAccountParams struct {
|
type UpdateAccountParams struct {
|
||||||
Name string
|
Name string
|
||||||
OnBudget bool
|
OnBudget bool
|
||||||
|
IsOpen bool
|
||||||
ID uuid.UUID
|
ID uuid.UUID
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) UpdateAccount(ctx context.Context, arg UpdateAccountParams) (Account, error) {
|
func (q *Queries) UpdateAccount(ctx context.Context, arg UpdateAccountParams) (Account, error) {
|
||||||
row := q.db.QueryRowContext(ctx, updateAccount, arg.Name, arg.OnBudget, arg.ID)
|
row := q.db.QueryRowContext(ctx, updateAccount,
|
||||||
|
arg.Name,
|
||||||
|
arg.OnBudget,
|
||||||
|
arg.IsOpen,
|
||||||
|
arg.ID,
|
||||||
|
)
|
||||||
var i Account
|
var i Account
|
||||||
err := row.Scan(
|
err := row.Scan(
|
||||||
&i.ID,
|
&i.ID,
|
||||||
&i.BudgetID,
|
&i.BudgetID,
|
||||||
&i.Name,
|
&i.Name,
|
||||||
&i.OnBudget,
|
&i.OnBudget,
|
||||||
|
&i.IsOpen,
|
||||||
|
&i.LastReconciled,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: assignments.sql
|
// source: assignments.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
@ -17,7 +19,7 @@ INSERT INTO assignments (
|
|||||||
) VALUES (
|
) VALUES (
|
||||||
$1, $2, $3
|
$1, $2, $3
|
||||||
)
|
)
|
||||||
RETURNING id, category_id, date, memo, amount
|
RETURNING category_id, date, memo, amount
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateAssignmentParams struct {
|
type CreateAssignmentParams struct {
|
||||||
@ -30,7 +32,6 @@ func (q *Queries) CreateAssignment(ctx context.Context, arg CreateAssignmentPara
|
|||||||
row := q.db.QueryRowContext(ctx, createAssignment, arg.Date, arg.Amount, arg.CategoryID)
|
row := q.db.QueryRowContext(ctx, createAssignment, arg.Date, arg.Amount, arg.CategoryID)
|
||||||
var i Assignment
|
var i Assignment
|
||||||
err := row.Scan(
|
err := row.Scan(
|
||||||
&i.ID,
|
|
||||||
&i.CategoryID,
|
&i.CategoryID,
|
||||||
&i.Date,
|
&i.Date,
|
||||||
&i.Memo,
|
&i.Memo,
|
||||||
@ -130,3 +131,41 @@ func (q *Queries) GetAssignmentsByMonthAndCategory(ctx context.Context, budgetID
|
|||||||
}
|
}
|
||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const updateAssignment = `-- name: UpdateAssignment :exec
|
||||||
|
INSERT INTO assignments (category_id, date, amount)
|
||||||
|
VALUES($1, $2, $3)
|
||||||
|
ON CONFLICT (category_id, date)
|
||||||
|
DO
|
||||||
|
UPDATE SET amount = $3
|
||||||
|
`
|
||||||
|
|
||||||
|
type UpdateAssignmentParams struct {
|
||||||
|
CategoryID uuid.UUID
|
||||||
|
Date time.Time
|
||||||
|
Amount numeric.Numeric
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) UpdateAssignment(ctx context.Context, arg UpdateAssignmentParams) error {
|
||||||
|
_, err := q.db.ExecContext(ctx, updateAssignment, arg.CategoryID, arg.Date, arg.Amount)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateAssignmentWithDifference = `-- name: UpdateAssignmentWithDifference :exec
|
||||||
|
INSERT INTO assignments (category_id, date, amount)
|
||||||
|
VALUES($1, $2, $3)
|
||||||
|
ON CONFLICT (category_id, date)
|
||||||
|
DO
|
||||||
|
UPDATE SET amount = assignments.amount + $3
|
||||||
|
`
|
||||||
|
|
||||||
|
type UpdateAssignmentWithDifferenceParams struct {
|
||||||
|
CategoryID uuid.UUID
|
||||||
|
Date time.Time
|
||||||
|
Amount numeric.Numeric
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) UpdateAssignmentWithDifference(ctx context.Context, arg UpdateAssignmentWithDifferenceParams) error {
|
||||||
|
_, err := q.db.ExecContext(ctx, updateAssignmentWithDifference, arg.CategoryID, arg.Date, arg.Amount)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: budgets.sql
|
// source: budgets.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
|
@ -59,5 +59,6 @@ func (s *Database) NewBudget(context context.Context, name string, userID uuid.U
|
|||||||
return nil, fmt.Errorf("commit: %w", err)
|
return nil, fmt.Errorf("commit: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
budget.IncomeCategoryID = cat.ID
|
||||||
return &budget, nil
|
return &budget, nil
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: categories.sql
|
// source: categories.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
@ -122,7 +124,8 @@ SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.
|
|||||||
FROM categories
|
FROM categories
|
||||||
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
|
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
|
||||||
WHERE category_groups.budget_id = $1
|
WHERE category_groups.budget_id = $1
|
||||||
AND categories.name LIKE $2
|
AND categories.name ILIKE $2
|
||||||
|
AND category_groups.name != 'Hidden Categories'
|
||||||
ORDER BY category_groups.name, categories.name
|
ORDER BY category_groups.name, categories.name
|
||||||
`
|
`
|
||||||
|
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: cumultative-balances.sql
|
// source: cumultative-balances.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
@ -13,21 +15,19 @@ import (
|
|||||||
|
|
||||||
const getCumultativeBalances = `-- name: GetCumultativeBalances :many
|
const getCumultativeBalances = `-- name: GetCumultativeBalances :many
|
||||||
SELECT COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id),
|
SELECT COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id),
|
||||||
COALESCE(ass.amount, 0)::decimal(12,2) as assignments, SUM(ass.amount) OVER (PARTITION BY ass.category_id ORDER BY ass.date)::decimal(12,2) as assignments_cum,
|
COALESCE(ass.amount, 0)::decimal(12,2) as assignments,
|
||||||
COALESCE(tra.amount, 0)::decimal(12,2) as transactions, SUM(tra.amount) OVER (PARTITION BY tra.category_id ORDER BY tra.date)::decimal(12,2) as transactions_cum
|
COALESCE(tra.amount, 0)::decimal(12,2) as transactions
|
||||||
FROM assignments_by_month as ass
|
FROM assignments_by_month as ass
|
||||||
FULL OUTER JOIN transactions_by_month as tra ON ass.date = tra.date AND ass.category_id = tra.category_id
|
FULL OUTER JOIN transactions_by_month as tra ON ass.date = tra.date AND ass.category_id = tra.category_id
|
||||||
WHERE (ass.budget_id IS NULL OR ass.budget_id = $1) AND (tra.budget_id IS NULL OR tra.budget_id = $1)
|
WHERE COALESCE(ass.budget_id, tra.budget_id) = $1
|
||||||
ORDER BY COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id)
|
ORDER BY COALESCE(ass.date, tra.date), COALESCE(ass.amount, tra.amount)
|
||||||
`
|
`
|
||||||
|
|
||||||
type GetCumultativeBalancesRow struct {
|
type GetCumultativeBalancesRow struct {
|
||||||
Date time.Time
|
Date time.Time
|
||||||
CategoryID uuid.UUID
|
CategoryID uuid.UUID
|
||||||
Assignments numeric.Numeric
|
Assignments numeric.Numeric
|
||||||
AssignmentsCum numeric.Numeric
|
Transactions numeric.Numeric
|
||||||
Transactions numeric.Numeric
|
|
||||||
TransactionsCum numeric.Numeric
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) GetCumultativeBalances(ctx context.Context, budgetID uuid.UUID) ([]GetCumultativeBalancesRow, error) {
|
func (q *Queries) GetCumultativeBalances(ctx context.Context, budgetID uuid.UUID) ([]GetCumultativeBalancesRow, error) {
|
||||||
@ -43,9 +43,7 @@ func (q *Queries) GetCumultativeBalances(ctx context.Context, budgetID uuid.UUID
|
|||||||
&i.Date,
|
&i.Date,
|
||||||
&i.CategoryID,
|
&i.CategoryID,
|
||||||
&i.Assignments,
|
&i.Assignments,
|
||||||
&i.AssignmentsCum,
|
|
||||||
&i.Transactions,
|
&i.Transactions,
|
||||||
&i.TransactionsCum,
|
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
|
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
|
|
||||||
@ -32,14 +34,15 @@ func (e *TransactionStatus) Scan(src interface{}) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Account struct {
|
type Account struct {
|
||||||
ID uuid.UUID
|
ID uuid.UUID
|
||||||
BudgetID uuid.UUID
|
BudgetID uuid.UUID
|
||||||
Name string
|
Name string
|
||||||
OnBudget bool
|
OnBudget bool
|
||||||
|
IsOpen bool
|
||||||
|
LastReconciled sql.NullTime
|
||||||
}
|
}
|
||||||
|
|
||||||
type Assignment struct {
|
type Assignment struct {
|
||||||
ID uuid.UUID
|
|
||||||
CategoryID uuid.UUID
|
CategoryID uuid.UUID
|
||||||
Date time.Time
|
Date time.Time
|
||||||
Memo sql.NullString
|
Memo sql.NullString
|
||||||
@ -72,6 +75,24 @@ type CategoryGroup struct {
|
|||||||
Name string
|
Name string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DisplayTransaction struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
Date time.Time
|
||||||
|
Memo string
|
||||||
|
Amount numeric.Numeric
|
||||||
|
GroupID uuid.NullUUID
|
||||||
|
Status TransactionStatus
|
||||||
|
Account string
|
||||||
|
PayeeID uuid.NullUUID
|
||||||
|
CategoryID uuid.NullUUID
|
||||||
|
Payee string
|
||||||
|
CategoryGroup string
|
||||||
|
Category string
|
||||||
|
TransferAccount string
|
||||||
|
BudgetID uuid.UUID
|
||||||
|
AccountID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
type Payee struct {
|
type Payee struct {
|
||||||
ID uuid.UUID
|
ID uuid.UUID
|
||||||
BudgetID uuid.UUID
|
BudgetID uuid.UUID
|
||||||
|
@ -25,6 +25,13 @@ func FromInt64WithExp(value int64, exp int32) Numeric {
|
|||||||
return Numeric{Numeric: pgtype.Numeric{Int: big.NewInt(value), Exp: exp, Status: pgtype.Present}}
|
return Numeric{Numeric: pgtype.Numeric{Int: big.NewInt(value), Exp: exp, Status: pgtype.Present}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (n *Numeric) SetZero() {
|
||||||
|
n.Exp = 0
|
||||||
|
n.Int = big.NewInt(0)
|
||||||
|
n.Status = pgtype.Present
|
||||||
|
n.NaN = false
|
||||||
|
}
|
||||||
|
|
||||||
func (n Numeric) GetFloat64() float64 {
|
func (n Numeric) GetFloat64() float64 {
|
||||||
if n.Status != pgtype.Present {
|
if n.Status != pgtype.Present {
|
||||||
return 0
|
return 0
|
||||||
@ -53,6 +60,13 @@ func (n Numeric) IsZero() bool {
|
|||||||
return float == 0
|
return float == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (n *Numeric) MatchExpI(exp int32) {
|
||||||
|
diffExp := n.Exp - exp
|
||||||
|
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
|
||||||
|
n.Exp = exp
|
||||||
|
n.Int = big.NewInt(0).Mul(n.Int, factor)
|
||||||
|
}
|
||||||
|
|
||||||
func (n Numeric) MatchExp(exp int32) Numeric {
|
func (n Numeric) MatchExp(exp int32) Numeric {
|
||||||
diffExp := n.Exp - exp
|
diffExp := n.Exp - exp
|
||||||
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
|
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
|
||||||
@ -64,6 +78,22 @@ func (n Numeric) MatchExp(exp int32) Numeric {
|
|||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (n *Numeric) SubI(other Numeric) *Numeric {
|
||||||
|
right := other
|
||||||
|
if n.Exp < other.Exp {
|
||||||
|
right = other.MatchExp(n.Exp)
|
||||||
|
} else if n.Exp > other.Exp {
|
||||||
|
n.MatchExpI(other.Exp)
|
||||||
|
}
|
||||||
|
|
||||||
|
if n.Exp == right.Exp {
|
||||||
|
n.Int = big.NewInt(0).Sub(n.Int, right.Int)
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
panic("Cannot subtract with different exponents")
|
||||||
|
}
|
||||||
|
|
||||||
func (n Numeric) Sub(other Numeric) Numeric {
|
func (n Numeric) Sub(other Numeric) Numeric {
|
||||||
left := n
|
left := n
|
||||||
right := other
|
right := other
|
||||||
@ -106,6 +136,22 @@ func (n Numeric) Add(other Numeric) Numeric {
|
|||||||
panic("Cannot add with different exponents")
|
panic("Cannot add with different exponents")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (n *Numeric) AddI(other Numeric) *Numeric {
|
||||||
|
right := other
|
||||||
|
if n.Exp < other.Exp {
|
||||||
|
right = other.MatchExp(n.Exp)
|
||||||
|
} else if n.Exp > other.Exp {
|
||||||
|
n.MatchExpI(other.Exp)
|
||||||
|
}
|
||||||
|
|
||||||
|
if n.Exp == right.Exp {
|
||||||
|
n.Int = big.NewInt(0).Add(n.Int, right.Int)
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
panic("Cannot add with different exponents")
|
||||||
|
}
|
||||||
|
|
||||||
func (n Numeric) String() string {
|
func (n Numeric) String() string {
|
||||||
if n.Int == nil || n.Int.Int64() == 0 {
|
if n.Int == nil || n.Int.Int64() == 0 {
|
||||||
return "0"
|
return "0"
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: payees.sql
|
// source: payees.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
@ -60,7 +62,7 @@ func (q *Queries) GetPayees(ctx context.Context, budgetID uuid.UUID) ([]Payee, e
|
|||||||
const searchPayees = `-- name: SearchPayees :many
|
const searchPayees = `-- name: SearchPayees :many
|
||||||
SELECT payees.id, payees.budget_id, payees.name, 'payee' as type FROM payees
|
SELECT payees.id, payees.budget_id, payees.name, 'payee' as type FROM payees
|
||||||
WHERE payees.budget_id = $1
|
WHERE payees.budget_id = $1
|
||||||
AND payees.name LIKE $2
|
AND payees.name ILIKE $2
|
||||||
ORDER BY payees.name
|
ORDER BY payees.name
|
||||||
`
|
`
|
||||||
|
|
||||||
|
@ -11,25 +11,35 @@ WHERE accounts.id = $1;
|
|||||||
-- name: GetAccounts :many
|
-- name: GetAccounts :many
|
||||||
SELECT accounts.* FROM accounts
|
SELECT accounts.* FROM accounts
|
||||||
WHERE accounts.budget_id = $1
|
WHERE accounts.budget_id = $1
|
||||||
|
AND accounts.is_open = TRUE
|
||||||
ORDER BY accounts.name;
|
ORDER BY accounts.name;
|
||||||
|
|
||||||
-- name: GetAccountsWithBalance :many
|
-- name: GetAccountsWithBalance :many
|
||||||
SELECT accounts.id, accounts.name, accounts.on_budget, SUM(transactions.amount)::decimal(12,2) as balance
|
SELECT accounts.id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled,
|
||||||
|
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW())::decimal(12,2) as working_balance,
|
||||||
|
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status IN ('Cleared', 'Reconciled'))::decimal(12,2) as cleared_balance,
|
||||||
|
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status = 'Reconciled')::decimal(12,2) as reconciled_balance
|
||||||
FROM accounts
|
FROM accounts
|
||||||
LEFT JOIN transactions ON transactions.account_id = accounts.id AND transactions.date < NOW()
|
|
||||||
WHERE accounts.budget_id = $1
|
WHERE accounts.budget_id = $1
|
||||||
GROUP BY accounts.id, accounts.name
|
AND accounts.is_open = TRUE
|
||||||
ORDER BY accounts.name;
|
ORDER BY accounts.name;
|
||||||
|
|
||||||
-- name: SearchAccounts :many
|
-- name: SearchAccounts :many
|
||||||
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
|
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
|
||||||
WHERE accounts.budget_id = @budget_id
|
WHERE accounts.budget_id = @budget_id
|
||||||
AND accounts.name LIKE @search
|
AND accounts.is_open = TRUE
|
||||||
|
AND accounts.name ILIKE @search
|
||||||
ORDER BY accounts.name;
|
ORDER BY accounts.name;
|
||||||
|
|
||||||
-- name: UpdateAccount :one
|
-- name: UpdateAccount :one
|
||||||
UPDATE accounts
|
UPDATE accounts
|
||||||
SET name = $1,
|
SET name = $1,
|
||||||
on_budget = $2
|
on_budget = $2,
|
||||||
WHERE accounts.id = $3
|
is_open = $3
|
||||||
RETURNING *;
|
WHERE accounts.id = $4
|
||||||
|
RETURNING *;
|
||||||
|
|
||||||
|
-- name: SetLastReconciled :exec
|
||||||
|
UPDATE accounts
|
||||||
|
SET last_reconciled = NOW()
|
||||||
|
WHERE accounts.id = $1;
|
@ -22,4 +22,18 @@ SELECT assignments.date, categories.name as category, category_groups.name as gr
|
|||||||
FROM assignments
|
FROM assignments
|
||||||
INNER JOIN categories ON categories.id = assignments.category_id
|
INNER JOIN categories ON categories.id = assignments.category_id
|
||||||
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
|
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
|
||||||
WHERE category_groups.budget_id = @budget_id;
|
WHERE category_groups.budget_id = @budget_id;
|
||||||
|
|
||||||
|
-- name: UpdateAssignment :exec
|
||||||
|
INSERT INTO assignments (category_id, date, amount)
|
||||||
|
VALUES($1, $2, $3)
|
||||||
|
ON CONFLICT (category_id, date)
|
||||||
|
DO
|
||||||
|
UPDATE SET amount = $3;
|
||||||
|
|
||||||
|
-- name: UpdateAssignmentWithDifference :exec
|
||||||
|
INSERT INTO assignments (category_id, date, amount)
|
||||||
|
VALUES($1, $2, $3)
|
||||||
|
ON CONFLICT (category_id, date)
|
||||||
|
DO
|
||||||
|
UPDATE SET amount = assignments.amount + $3;
|
@ -25,6 +25,7 @@ SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.
|
|||||||
FROM categories
|
FROM categories
|
||||||
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
|
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
|
||||||
WHERE category_groups.budget_id = @budget_id
|
WHERE category_groups.budget_id = @budget_id
|
||||||
AND categories.name LIKE @search
|
AND categories.name ILIKE @search
|
||||||
|
AND category_groups.name != 'Hidden Categories'
|
||||||
ORDER BY category_groups.name, categories.name;
|
ORDER BY category_groups.name, categories.name;
|
||||||
--ORDER BY levenshtein(payees.name, $2);
|
--ORDER BY levenshtein(payees.name, $2);
|
@ -1,8 +1,8 @@
|
|||||||
-- name: GetCumultativeBalances :many
|
-- name: GetCumultativeBalances :many
|
||||||
SELECT COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id),
|
SELECT COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id),
|
||||||
COALESCE(ass.amount, 0)::decimal(12,2) as assignments, SUM(ass.amount) OVER (PARTITION BY ass.category_id ORDER BY ass.date)::decimal(12,2) as assignments_cum,
|
COALESCE(ass.amount, 0)::decimal(12,2) as assignments,
|
||||||
COALESCE(tra.amount, 0)::decimal(12,2) as transactions, SUM(tra.amount) OVER (PARTITION BY tra.category_id ORDER BY tra.date)::decimal(12,2) as transactions_cum
|
COALESCE(tra.amount, 0)::decimal(12,2) as transactions
|
||||||
FROM assignments_by_month as ass
|
FROM assignments_by_month as ass
|
||||||
FULL OUTER JOIN transactions_by_month as tra ON ass.date = tra.date AND ass.category_id = tra.category_id
|
FULL OUTER JOIN transactions_by_month as tra ON ass.date = tra.date AND ass.category_id = tra.category_id
|
||||||
WHERE (ass.budget_id IS NULL OR ass.budget_id = @budget_id) AND (tra.budget_id IS NULL OR tra.budget_id = @budget_id)
|
WHERE COALESCE(ass.budget_id, tra.budget_id) = @budget_id
|
||||||
ORDER BY COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id);
|
ORDER BY COALESCE(ass.date, tra.date), COALESCE(ass.amount, tra.amount);
|
@ -12,6 +12,6 @@ ORDER BY name;
|
|||||||
-- name: SearchPayees :many
|
-- name: SearchPayees :many
|
||||||
SELECT payees.*, 'payee' as type FROM payees
|
SELECT payees.*, 'payee' as type FROM payees
|
||||||
WHERE payees.budget_id = @budget_id
|
WHERE payees.budget_id = @budget_id
|
||||||
AND payees.name LIKE @search
|
AND payees.name ILIKE @search
|
||||||
ORDER BY payees.name;
|
ORDER BY payees.name;
|
||||||
--ORDER BY levenshtein(payees.name, $2);
|
--ORDER BY levenshtein(payees.name, $2);
|
@ -1,70 +1,40 @@
|
|||||||
-- name: GetTransaction :one
|
-- name: GetTransaction :one
|
||||||
SELECT * FROM transactions
|
SELECT * FROM display_transactions
|
||||||
WHERE id = $1;
|
WHERE id = $1;
|
||||||
|
|
||||||
-- name: CreateTransaction :one
|
-- name: CreateTransaction :one
|
||||||
INSERT INTO transactions
|
INSERT INTO transactions
|
||||||
(date, memo, amount, account_id, payee_id, category_id, group_id, status)
|
(date, memo, amount, account_id, payee_id, category_id, group_id, status)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||||
RETURNING *;
|
RETURNING id;
|
||||||
|
|
||||||
-- name: UpdateTransaction :exec
|
-- name: UpdateTransaction :exec
|
||||||
UPDATE transactions
|
UPDATE transactions
|
||||||
SET date = $1,
|
SET date = $1,
|
||||||
memo = $2,
|
memo = $2,
|
||||||
amount = $3,
|
amount = $3,
|
||||||
payee_id = $4,
|
payee_id = $4,
|
||||||
category_id = $5
|
category_id = $5
|
||||||
WHERE id = $6;
|
WHERE id = $6;
|
||||||
|
|
||||||
|
-- name: SetTransactionReconciled :exec
|
||||||
|
UPDATE transactions
|
||||||
|
SET status = 'Reconciled'
|
||||||
|
WHERE id = $1;
|
||||||
|
|
||||||
-- name: DeleteTransaction :exec
|
-- name: DeleteTransaction :exec
|
||||||
DELETE FROM transactions
|
DELETE FROM transactions
|
||||||
WHERE id = $1;
|
WHERE id = $1;
|
||||||
|
|
||||||
-- name: GetAllTransactionsForBudget :many
|
-- name: GetAllTransactionsForBudget :many
|
||||||
SELECT transactions.id, transactions.date, transactions.memo,
|
SELECT t.*
|
||||||
transactions.amount, transactions.group_id, transactions.status,
|
FROM display_transactions AS t
|
||||||
accounts.name as account, transactions.payee_id, transactions.category_id,
|
WHERE t.budget_id = $1;
|
||||||
COALESCE(payees.name, '') as payee,
|
|
||||||
COALESCE(category_groups.name, '') as category_group,
|
|
||||||
COALESCE(categories.name, '') as category,
|
|
||||||
COALESCE((
|
|
||||||
SELECT CONCAT(otherAccounts.name)
|
|
||||||
FROM transactions otherTransactions
|
|
||||||
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
|
|
||||||
WHERE otherTransactions.group_id = transactions.group_id
|
|
||||||
AND otherTransactions.id != transactions.id
|
|
||||||
), '')::text as transfer_account
|
|
||||||
FROM transactions
|
|
||||||
INNER JOIN accounts ON accounts.id = transactions.account_id
|
|
||||||
LEFT JOIN payees ON payees.id = transactions.payee_id
|
|
||||||
LEFT JOIN categories ON categories.id = transactions.category_id
|
|
||||||
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
|
|
||||||
WHERE accounts.budget_id = $1
|
|
||||||
ORDER BY transactions.date DESC;
|
|
||||||
|
|
||||||
-- name: GetTransactionsForAccount :many
|
-- name: GetTransactionsForAccount :many
|
||||||
SELECT transactions.id, transactions.date, transactions.memo,
|
SELECT t.*
|
||||||
transactions.amount, transactions.group_id, transactions.status,
|
FROM display_transactions AS t
|
||||||
accounts.name as account, transactions.payee_id, transactions.category_id,
|
WHERE t.account_id = $1;
|
||||||
COALESCE(payees.name, '') as payee,
|
|
||||||
COALESCE(category_groups.name, '') as category_group,
|
|
||||||
COALESCE(categories.name, '') as category,
|
|
||||||
COALESCE((
|
|
||||||
SELECT CONCAT(otherAccounts.name)
|
|
||||||
FROM transactions otherTransactions
|
|
||||||
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
|
|
||||||
WHERE otherTransactions.group_id = transactions.group_id
|
|
||||||
AND otherTransactions.id != transactions.id
|
|
||||||
), '')::text as transfer_account
|
|
||||||
FROM transactions
|
|
||||||
INNER JOIN accounts ON accounts.id = transactions.account_id
|
|
||||||
LEFT JOIN payees ON payees.id = transactions.payee_id
|
|
||||||
LEFT JOIN categories ON categories.id = transactions.category_id
|
|
||||||
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
|
|
||||||
WHERE transactions.account_id = $1
|
|
||||||
ORDER BY transactions.date DESC
|
|
||||||
LIMIT 200;
|
|
||||||
|
|
||||||
-- name: DeleteAllTransactions :execrows
|
-- name: DeleteAllTransactions :execrows
|
||||||
DELETE FROM transactions
|
DELETE FROM transactions
|
||||||
@ -75,4 +45,29 @@ AND accounts.id = transactions.account_id;
|
|||||||
-- name: GetTransactionsByMonthAndCategory :many
|
-- name: GetTransactionsByMonthAndCategory :many
|
||||||
SELECT *
|
SELECT *
|
||||||
FROM transactions_by_month
|
FROM transactions_by_month
|
||||||
WHERE transactions_by_month.budget_id = @budget_id;
|
WHERE transactions_by_month.budget_id = @budget_id;
|
||||||
|
|
||||||
|
-- name: GetProblematicTransactions :many
|
||||||
|
SELECT transactions.*
|
||||||
|
FROM display_transactions AS transactions
|
||||||
|
LEFT JOIN accounts
|
||||||
|
ON transactions.account_id = accounts.id
|
||||||
|
LEFT JOIN transactions AS otherGroupTransaction
|
||||||
|
ON transactions.group_id = otherGroupTransaction.group_id
|
||||||
|
AND transactions.id != otherGroupTransaction.id
|
||||||
|
AND transactions.account_id != otherGroupTransaction.account_id
|
||||||
|
LEFT JOIn accounts AS otherGroupAccount
|
||||||
|
ON otherGroupTransaction.account_id = otherGroupAccount.id
|
||||||
|
WHERE transactions.category_id IS NULL
|
||||||
|
AND accounts.on_budget
|
||||||
|
AND (otherGroupAccount.id IS NULL OR NOT otherGroupAccount.on_budget)
|
||||||
|
AND accounts.budget_id = $1;
|
||||||
|
|
||||||
|
-- name: GetFilteredTransactions :many
|
||||||
|
SELECT transactions.*
|
||||||
|
FROM display_transactions AS transactions
|
||||||
|
WHERE (NOT @filter_category::boolean OR transactions.category_id = @category_id)
|
||||||
|
AND (NOT @filter_account::boolean OR transactions.account_id = @account_id)
|
||||||
|
AND (NOT @filter_payee::boolean OR transactions.payee_id = @payee_id)
|
||||||
|
AND transactions.date BETWEEN @from_date AND @to_date
|
||||||
|
AND transactions.budget_id = @budget_id;
|
25
postgres/schema/0015_transactions-view.sql
Normal file
25
postgres/schema/0015_transactions-view.sql
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
-- +goose Up
|
||||||
|
CREATE VIEW display_transactions AS
|
||||||
|
SELECT transactions.id, transactions.date, transactions.memo,
|
||||||
|
transactions.amount, transactions.group_id, transactions.status,
|
||||||
|
accounts.name as account, transactions.payee_id, transactions.category_id,
|
||||||
|
COALESCE(payees.name, '') as payee,
|
||||||
|
COALESCE(category_groups.name, '') as category_group,
|
||||||
|
COALESCE(categories.name, '') as category,
|
||||||
|
COALESCE((
|
||||||
|
SELECT CONCAT(otherAccounts.name)
|
||||||
|
FROM transactions otherTransactions
|
||||||
|
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
|
||||||
|
WHERE otherTransactions.group_id = transactions.group_id
|
||||||
|
AND otherTransactions.id != transactions.id
|
||||||
|
), '')::text as transfer_account,
|
||||||
|
accounts.budget_id, transactions.account_id
|
||||||
|
FROM transactions
|
||||||
|
INNER JOIN accounts ON accounts.id = transactions.account_id
|
||||||
|
LEFT JOIN payees ON payees.id = transactions.payee_id
|
||||||
|
LEFT JOIN categories ON categories.id = transactions.category_id
|
||||||
|
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
|
||||||
|
ORDER BY transactions.date DESC;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
DROP VIEW display_transactions;
|
5
postgres/schema/0016_closed-accounts.sql
Normal file
5
postgres/schema/0016_closed-accounts.sql
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
-- +goose Up
|
||||||
|
ALTER TABLE accounts ADD COLUMN is_open BOOLEAN NOT NULL DEFAULT TRUE;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
ALTER TABLE accounts DROP COLUMN is_open;
|
6
postgres/schema/0017_natural-key-assignments.sql
Normal file
6
postgres/schema/0017_natural-key-assignments.sql
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
-- +goose Up
|
||||||
|
ALTER TABLE assignments DROP id;
|
||||||
|
ALTER TABLE assignments ADD PRIMARY KEY (category_id, date);
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
ALTER TABLE assignments ADD COLUMN id uuid DEFAULT uuid_generate_v4() PRIMARY KEY;
|
12
postgres/schema/0018_reconciled-on.sql
Normal file
12
postgres/schema/0018_reconciled-on.sql
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
-- +goose Up
|
||||||
|
ALTER TABLE accounts ADD COLUMN last_reconciled date NULL;
|
||||||
|
UPDATE accounts
|
||||||
|
SET last_reconciled = (
|
||||||
|
SELECT MAX(transactions.date)
|
||||||
|
FROM transactions
|
||||||
|
WHERE transactions.account_id = accounts.id
|
||||||
|
AND transactions.status = 'Reconciled'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
ALTER TABLE accounts DROP COLUMN last_reconciled;
|
@ -0,0 +1,13 @@
|
|||||||
|
-- +goose Up
|
||||||
|
CREATE OR REPLACE VIEW transactions_by_month AS
|
||||||
|
SELECT date_trunc('month', transactions.date)::date as date, transactions.category_id, accounts.budget_id, SUM(amount) as amount
|
||||||
|
FROM transactions
|
||||||
|
INNER JOIN accounts ON accounts.id = transactions.account_id AND accounts.on_budget
|
||||||
|
GROUP BY date_trunc('month', transactions.date), transactions.category_id, accounts.budget_id;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
CREATE OR REPLACE VIEW transactions_by_month AS
|
||||||
|
SELECT date_trunc('month', transactions.date)::date as date, transactions.category_id, accounts.budget_id, SUM(amount) as amount
|
||||||
|
FROM transactions
|
||||||
|
INNER JOIN accounts ON accounts.id = transactions.account_id
|
||||||
|
GROUP BY date_trunc('month', transactions.date), transactions.category_id, accounts.budget_id;
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: transactions.sql
|
// source: transactions.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
@ -15,7 +17,7 @@ const createTransaction = `-- name: CreateTransaction :one
|
|||||||
INSERT INTO transactions
|
INSERT INTO transactions
|
||||||
(date, memo, amount, account_id, payee_id, category_id, group_id, status)
|
(date, memo, amount, account_id, payee_id, category_id, group_id, status)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||||
RETURNING id, date, memo, amount, account_id, category_id, payee_id, group_id, status
|
RETURNING id
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateTransactionParams struct {
|
type CreateTransactionParams struct {
|
||||||
@ -29,7 +31,7 @@ type CreateTransactionParams struct {
|
|||||||
Status TransactionStatus
|
Status TransactionStatus
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionParams) (Transaction, error) {
|
func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionParams) (uuid.UUID, error) {
|
||||||
row := q.db.QueryRowContext(ctx, createTransaction,
|
row := q.db.QueryRowContext(ctx, createTransaction,
|
||||||
arg.Date,
|
arg.Date,
|
||||||
arg.Memo,
|
arg.Memo,
|
||||||
@ -40,19 +42,9 @@ func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionPa
|
|||||||
arg.GroupID,
|
arg.GroupID,
|
||||||
arg.Status,
|
arg.Status,
|
||||||
)
|
)
|
||||||
var i Transaction
|
var id uuid.UUID
|
||||||
err := row.Scan(
|
err := row.Scan(&id)
|
||||||
&i.ID,
|
return id, err
|
||||||
&i.Date,
|
|
||||||
&i.Memo,
|
|
||||||
&i.Amount,
|
|
||||||
&i.AccountID,
|
|
||||||
&i.CategoryID,
|
|
||||||
&i.PayeeID,
|
|
||||||
&i.GroupID,
|
|
||||||
&i.Status,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const deleteAllTransactions = `-- name: DeleteAllTransactions :execrows
|
const deleteAllTransactions = `-- name: DeleteAllTransactions :execrows
|
||||||
@ -81,53 +73,20 @@ func (q *Queries) DeleteTransaction(ctx context.Context, id uuid.UUID) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getAllTransactionsForBudget = `-- name: GetAllTransactionsForBudget :many
|
const getAllTransactionsForBudget = `-- name: GetAllTransactionsForBudget :many
|
||||||
SELECT transactions.id, transactions.date, transactions.memo,
|
SELECT t.id, t.date, t.memo, t.amount, t.group_id, t.status, t.account, t.payee_id, t.category_id, t.payee, t.category_group, t.category, t.transfer_account, t.budget_id, t.account_id
|
||||||
transactions.amount, transactions.group_id, transactions.status,
|
FROM display_transactions AS t
|
||||||
accounts.name as account, transactions.payee_id, transactions.category_id,
|
WHERE t.budget_id = $1
|
||||||
COALESCE(payees.name, '') as payee,
|
|
||||||
COALESCE(category_groups.name, '') as category_group,
|
|
||||||
COALESCE(categories.name, '') as category,
|
|
||||||
COALESCE((
|
|
||||||
SELECT CONCAT(otherAccounts.name)
|
|
||||||
FROM transactions otherTransactions
|
|
||||||
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
|
|
||||||
WHERE otherTransactions.group_id = transactions.group_id
|
|
||||||
AND otherTransactions.id != transactions.id
|
|
||||||
), '')::text as transfer_account
|
|
||||||
FROM transactions
|
|
||||||
INNER JOIN accounts ON accounts.id = transactions.account_id
|
|
||||||
LEFT JOIN payees ON payees.id = transactions.payee_id
|
|
||||||
LEFT JOIN categories ON categories.id = transactions.category_id
|
|
||||||
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
|
|
||||||
WHERE accounts.budget_id = $1
|
|
||||||
ORDER BY transactions.date DESC
|
|
||||||
`
|
`
|
||||||
|
|
||||||
type GetAllTransactionsForBudgetRow struct {
|
func (q *Queries) GetAllTransactionsForBudget(ctx context.Context, budgetID uuid.UUID) ([]DisplayTransaction, error) {
|
||||||
ID uuid.UUID
|
|
||||||
Date time.Time
|
|
||||||
Memo string
|
|
||||||
Amount numeric.Numeric
|
|
||||||
GroupID uuid.NullUUID
|
|
||||||
Status TransactionStatus
|
|
||||||
Account string
|
|
||||||
PayeeID uuid.NullUUID
|
|
||||||
CategoryID uuid.NullUUID
|
|
||||||
Payee string
|
|
||||||
CategoryGroup string
|
|
||||||
Category string
|
|
||||||
TransferAccount string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) GetAllTransactionsForBudget(ctx context.Context, budgetID uuid.UUID) ([]GetAllTransactionsForBudgetRow, error) {
|
|
||||||
rows, err := q.db.QueryContext(ctx, getAllTransactionsForBudget, budgetID)
|
rows, err := q.db.QueryContext(ctx, getAllTransactionsForBudget, budgetID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
var items []GetAllTransactionsForBudgetRow
|
var items []DisplayTransaction
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var i GetAllTransactionsForBudgetRow
|
var i DisplayTransaction
|
||||||
if err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Date,
|
&i.Date,
|
||||||
@ -142,6 +101,135 @@ func (q *Queries) GetAllTransactionsForBudget(ctx context.Context, budgetID uuid
|
|||||||
&i.CategoryGroup,
|
&i.CategoryGroup,
|
||||||
&i.Category,
|
&i.Category,
|
||||||
&i.TransferAccount,
|
&i.TransferAccount,
|
||||||
|
&i.BudgetID,
|
||||||
|
&i.AccountID,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const getFilteredTransactions = `-- name: GetFilteredTransactions :many
|
||||||
|
SELECT transactions.id, transactions.date, transactions.memo, transactions.amount, transactions.group_id, transactions.status, transactions.account, transactions.payee_id, transactions.category_id, transactions.payee, transactions.category_group, transactions.category, transactions.transfer_account, transactions.budget_id, transactions.account_id
|
||||||
|
FROM display_transactions AS transactions
|
||||||
|
WHERE (NOT $1::boolean OR transactions.category_id = $2)
|
||||||
|
AND (NOT $3::boolean OR transactions.account_id = $4)
|
||||||
|
AND (NOT $5::boolean OR transactions.payee_id = $6)
|
||||||
|
AND transactions.date BETWEEN $7 AND $8
|
||||||
|
AND transactions.budget_id = $9
|
||||||
|
`
|
||||||
|
|
||||||
|
type GetFilteredTransactionsParams struct {
|
||||||
|
FilterCategory bool
|
||||||
|
CategoryID uuid.NullUUID
|
||||||
|
FilterAccount bool
|
||||||
|
AccountID uuid.UUID
|
||||||
|
FilterPayee bool
|
||||||
|
PayeeID uuid.NullUUID
|
||||||
|
FromDate time.Time
|
||||||
|
ToDate time.Time
|
||||||
|
BudgetID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) GetFilteredTransactions(ctx context.Context, arg GetFilteredTransactionsParams) ([]DisplayTransaction, error) {
|
||||||
|
rows, err := q.db.QueryContext(ctx, getFilteredTransactions,
|
||||||
|
arg.FilterCategory,
|
||||||
|
arg.CategoryID,
|
||||||
|
arg.FilterAccount,
|
||||||
|
arg.AccountID,
|
||||||
|
arg.FilterPayee,
|
||||||
|
arg.PayeeID,
|
||||||
|
arg.FromDate,
|
||||||
|
arg.ToDate,
|
||||||
|
arg.BudgetID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []DisplayTransaction
|
||||||
|
for rows.Next() {
|
||||||
|
var i DisplayTransaction
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.Date,
|
||||||
|
&i.Memo,
|
||||||
|
&i.Amount,
|
||||||
|
&i.GroupID,
|
||||||
|
&i.Status,
|
||||||
|
&i.Account,
|
||||||
|
&i.PayeeID,
|
||||||
|
&i.CategoryID,
|
||||||
|
&i.Payee,
|
||||||
|
&i.CategoryGroup,
|
||||||
|
&i.Category,
|
||||||
|
&i.TransferAccount,
|
||||||
|
&i.BudgetID,
|
||||||
|
&i.AccountID,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const getProblematicTransactions = `-- name: GetProblematicTransactions :many
|
||||||
|
SELECT transactions.id, transactions.date, transactions.memo, transactions.amount, transactions.group_id, transactions.status, transactions.account, transactions.payee_id, transactions.category_id, transactions.payee, transactions.category_group, transactions.category, transactions.transfer_account, transactions.budget_id, transactions.account_id
|
||||||
|
FROM display_transactions AS transactions
|
||||||
|
LEFT JOIN accounts
|
||||||
|
ON transactions.account_id = accounts.id
|
||||||
|
LEFT JOIN transactions AS otherGroupTransaction
|
||||||
|
ON transactions.group_id = otherGroupTransaction.group_id
|
||||||
|
AND transactions.id != otherGroupTransaction.id
|
||||||
|
AND transactions.account_id != otherGroupTransaction.account_id
|
||||||
|
LEFT JOIn accounts AS otherGroupAccount
|
||||||
|
ON otherGroupTransaction.account_id = otherGroupAccount.id
|
||||||
|
WHERE transactions.category_id IS NULL
|
||||||
|
AND accounts.on_budget
|
||||||
|
AND (otherGroupAccount.id IS NULL OR NOT otherGroupAccount.on_budget)
|
||||||
|
AND accounts.budget_id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) GetProblematicTransactions(ctx context.Context, budgetID uuid.UUID) ([]DisplayTransaction, error) {
|
||||||
|
rows, err := q.db.QueryContext(ctx, getProblematicTransactions, budgetID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []DisplayTransaction
|
||||||
|
for rows.Next() {
|
||||||
|
var i DisplayTransaction
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.Date,
|
||||||
|
&i.Memo,
|
||||||
|
&i.Amount,
|
||||||
|
&i.GroupID,
|
||||||
|
&i.Status,
|
||||||
|
&i.Account,
|
||||||
|
&i.PayeeID,
|
||||||
|
&i.CategoryID,
|
||||||
|
&i.Payee,
|
||||||
|
&i.CategoryGroup,
|
||||||
|
&i.Category,
|
||||||
|
&i.TransferAccount,
|
||||||
|
&i.BudgetID,
|
||||||
|
&i.AccountID,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -157,23 +245,29 @@ func (q *Queries) GetAllTransactionsForBudget(ctx context.Context, budgetID uuid
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getTransaction = `-- name: GetTransaction :one
|
const getTransaction = `-- name: GetTransaction :one
|
||||||
SELECT id, date, memo, amount, account_id, category_id, payee_id, group_id, status FROM transactions
|
SELECT id, date, memo, amount, group_id, status, account, payee_id, category_id, payee, category_group, category, transfer_account, budget_id, account_id FROM display_transactions
|
||||||
WHERE id = $1
|
WHERE id = $1
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) GetTransaction(ctx context.Context, id uuid.UUID) (Transaction, error) {
|
func (q *Queries) GetTransaction(ctx context.Context, id uuid.UUID) (DisplayTransaction, error) {
|
||||||
row := q.db.QueryRowContext(ctx, getTransaction, id)
|
row := q.db.QueryRowContext(ctx, getTransaction, id)
|
||||||
var i Transaction
|
var i DisplayTransaction
|
||||||
err := row.Scan(
|
err := row.Scan(
|
||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Date,
|
&i.Date,
|
||||||
&i.Memo,
|
&i.Memo,
|
||||||
&i.Amount,
|
&i.Amount,
|
||||||
&i.AccountID,
|
|
||||||
&i.CategoryID,
|
|
||||||
&i.PayeeID,
|
|
||||||
&i.GroupID,
|
&i.GroupID,
|
||||||
&i.Status,
|
&i.Status,
|
||||||
|
&i.Account,
|
||||||
|
&i.PayeeID,
|
||||||
|
&i.CategoryID,
|
||||||
|
&i.Payee,
|
||||||
|
&i.CategoryGroup,
|
||||||
|
&i.Category,
|
||||||
|
&i.TransferAccount,
|
||||||
|
&i.BudgetID,
|
||||||
|
&i.AccountID,
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
@ -213,54 +307,20 @@ func (q *Queries) GetTransactionsByMonthAndCategory(ctx context.Context, budgetI
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getTransactionsForAccount = `-- name: GetTransactionsForAccount :many
|
const getTransactionsForAccount = `-- name: GetTransactionsForAccount :many
|
||||||
SELECT transactions.id, transactions.date, transactions.memo,
|
SELECT t.id, t.date, t.memo, t.amount, t.group_id, t.status, t.account, t.payee_id, t.category_id, t.payee, t.category_group, t.category, t.transfer_account, t.budget_id, t.account_id
|
||||||
transactions.amount, transactions.group_id, transactions.status,
|
FROM display_transactions AS t
|
||||||
accounts.name as account, transactions.payee_id, transactions.category_id,
|
WHERE t.account_id = $1
|
||||||
COALESCE(payees.name, '') as payee,
|
|
||||||
COALESCE(category_groups.name, '') as category_group,
|
|
||||||
COALESCE(categories.name, '') as category,
|
|
||||||
COALESCE((
|
|
||||||
SELECT CONCAT(otherAccounts.name)
|
|
||||||
FROM transactions otherTransactions
|
|
||||||
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
|
|
||||||
WHERE otherTransactions.group_id = transactions.group_id
|
|
||||||
AND otherTransactions.id != transactions.id
|
|
||||||
), '')::text as transfer_account
|
|
||||||
FROM transactions
|
|
||||||
INNER JOIN accounts ON accounts.id = transactions.account_id
|
|
||||||
LEFT JOIN payees ON payees.id = transactions.payee_id
|
|
||||||
LEFT JOIN categories ON categories.id = transactions.category_id
|
|
||||||
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
|
|
||||||
WHERE transactions.account_id = $1
|
|
||||||
ORDER BY transactions.date DESC
|
|
||||||
LIMIT 200
|
|
||||||
`
|
`
|
||||||
|
|
||||||
type GetTransactionsForAccountRow struct {
|
func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.UUID) ([]DisplayTransaction, error) {
|
||||||
ID uuid.UUID
|
|
||||||
Date time.Time
|
|
||||||
Memo string
|
|
||||||
Amount numeric.Numeric
|
|
||||||
GroupID uuid.NullUUID
|
|
||||||
Status TransactionStatus
|
|
||||||
Account string
|
|
||||||
PayeeID uuid.NullUUID
|
|
||||||
CategoryID uuid.NullUUID
|
|
||||||
Payee string
|
|
||||||
CategoryGroup string
|
|
||||||
Category string
|
|
||||||
TransferAccount string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.UUID) ([]GetTransactionsForAccountRow, error) {
|
|
||||||
rows, err := q.db.QueryContext(ctx, getTransactionsForAccount, accountID)
|
rows, err := q.db.QueryContext(ctx, getTransactionsForAccount, accountID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
var items []GetTransactionsForAccountRow
|
var items []DisplayTransaction
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var i GetTransactionsForAccountRow
|
var i DisplayTransaction
|
||||||
if err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Date,
|
&i.Date,
|
||||||
@ -275,6 +335,8 @@ func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.
|
|||||||
&i.CategoryGroup,
|
&i.CategoryGroup,
|
||||||
&i.Category,
|
&i.Category,
|
||||||
&i.TransferAccount,
|
&i.TransferAccount,
|
||||||
|
&i.BudgetID,
|
||||||
|
&i.AccountID,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -289,13 +351,24 @@ func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const setTransactionReconciled = `-- name: SetTransactionReconciled :exec
|
||||||
|
UPDATE transactions
|
||||||
|
SET status = 'Reconciled'
|
||||||
|
WHERE id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) SetTransactionReconciled(ctx context.Context, id uuid.UUID) error {
|
||||||
|
_, err := q.db.ExecContext(ctx, setTransactionReconciled, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
const updateTransaction = `-- name: UpdateTransaction :exec
|
const updateTransaction = `-- name: UpdateTransaction :exec
|
||||||
UPDATE transactions
|
UPDATE transactions
|
||||||
SET date = $1,
|
SET date = $1,
|
||||||
memo = $2,
|
memo = $2,
|
||||||
amount = $3,
|
amount = $3,
|
||||||
payee_id = $4,
|
payee_id = $4,
|
||||||
category_id = $5
|
category_id = $5
|
||||||
WHERE id = $6
|
WHERE id = $6
|
||||||
`
|
`
|
||||||
|
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: user_budgets.sql
|
// source: user_budgets.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
// Code generated by sqlc. DO NOT EDIT.
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.13.0
|
||||||
// source: users.sql
|
// source: users.sql
|
||||||
|
|
||||||
package postgres
|
package postgres
|
||||||
|
@ -110,7 +110,7 @@ func (ynab *YNABExport) ExportTransactions(context context.Context, w io.Writer)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetTransactionRow(transaction GetAllTransactionsForBudgetRow) []string {
|
func GetTransactionRow(transaction DisplayTransaction) []string {
|
||||||
row := []string{
|
row := []string{
|
||||||
transaction.Account,
|
transaction.Account,
|
||||||
"", // Flag
|
"", // Flag
|
||||||
|
@ -91,12 +91,12 @@ func (ynab *YNABImport) ImportAssignments(context context.Context, r io.Reader)
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
assignment := CreateAssignmentParams{
|
assignment := UpdateAssignmentWithDifferenceParams{
|
||||||
Date: date,
|
Date: date,
|
||||||
CategoryID: category.UUID,
|
CategoryID: category.UUID,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
}
|
}
|
||||||
_, err = ynab.queries.CreateAssignment(context, assignment)
|
err = ynab.queries.UpdateAssignmentWithDifference(context, assignment)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("save assignment %v: %w", assignment, err)
|
return fmt.Errorf("save assignment %v: %w", assignment, err)
|
||||||
}
|
}
|
||||||
@ -226,7 +226,8 @@ func (ynab *YNABImport) GetTransaction(context context.Context, record []string)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ynab *YNABImport) ImportRegularTransaction(context context.Context, payeeName string,
|
func (ynab *YNABImport) ImportRegularTransaction(context context.Context, payeeName string,
|
||||||
transaction CreateTransactionParams) error {
|
transaction CreateTransactionParams,
|
||||||
|
) error {
|
||||||
payeeID, err := ynab.GetPayee(context, payeeName)
|
payeeID, err := ynab.GetPayee(context, payeeName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("get payee %s: %w", payeeName, err)
|
return fmt.Errorf("get payee %s: %w", payeeName, err)
|
||||||
@ -242,7 +243,8 @@ func (ynab *YNABImport) ImportRegularTransaction(context context.Context, payeeN
|
|||||||
|
|
||||||
func (ynab *YNABImport) ImportTransferTransaction(context context.Context, payeeName string,
|
func (ynab *YNABImport) ImportTransferTransaction(context context.Context, payeeName string,
|
||||||
transaction CreateTransactionParams, openTransfers *[]Transfer,
|
transaction CreateTransactionParams, openTransfers *[]Transfer,
|
||||||
account *Account, amount numeric.Numeric) error {
|
account *Account, amount numeric.Numeric,
|
||||||
|
) error {
|
||||||
transferToAccountName := payeeName[11:]
|
transferToAccountName := payeeName[11:]
|
||||||
transferToAccount, err := ynab.GetAccount(context, transferToAccountName)
|
transferToAccount, err := ynab.GetAccount(context, transferToAccountName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -1,13 +1,87 @@
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.javil.eu/jacob1123/budgeteer/postgres"
|
"git.javil.eu/jacob1123/budgeteer/postgres"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type FilterTransactionsRequest struct {
|
||||||
|
CategoryID string `json:"category_id"`
|
||||||
|
PayeeID string `json:"payee_id"`
|
||||||
|
AccountID string `json:"account_id"`
|
||||||
|
FromDate time.Time `json:"from_date"`
|
||||||
|
ToDate time.Time `json:"to_date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) filteredTransactions(c *gin.Context) {
|
||||||
|
budgetID := c.Param("budgetid")
|
||||||
|
budgetUUID, err := uuid.Parse(budgetID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var request FilterTransactionsRequest
|
||||||
|
err = c.BindJSON(&request)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
params := postgres.GetFilteredTransactionsParams{
|
||||||
|
BudgetID: budgetUUID,
|
||||||
|
FromDate: request.FromDate,
|
||||||
|
ToDate: request.ToDate,
|
||||||
|
}
|
||||||
|
params.CategoryID, params.FilterCategory = parseEmptyUUID(request.CategoryID)
|
||||||
|
accountID, filterAccount := parseEmptyUUID(request.AccountID)
|
||||||
|
params.AccountID, params.FilterAccount = accountID.UUID, filterAccount
|
||||||
|
params.PayeeID, params.FilterPayee = parseEmptyUUID(request.PayeeID)
|
||||||
|
|
||||||
|
transactions, err := h.Service.GetFilteredTransactions(c.Request.Context(), params)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, TransactionsResponse{nil, transactions})
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseEmptyUUID(value string) (uuid.NullUUID, bool) {
|
||||||
|
if value == "" {
|
||||||
|
return uuid.NullUUID{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
val, err := uuid.Parse(value)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.NullUUID{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return uuid.NullUUID{val, true}, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) problematicTransactions(c *gin.Context) {
|
||||||
|
budgetID := c.Param("budgetid")
|
||||||
|
budgetUUID, err := uuid.Parse(budgetID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
transactions, err := h.Service.GetProblematicTransactions(c.Request.Context(), budgetUUID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, TransactionsResponse{nil, transactions})
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) transactionsForAccount(c *gin.Context) {
|
func (h *Handler) transactionsForAccount(c *gin.Context) {
|
||||||
accountID := c.Param("accountid")
|
accountID := c.Param("accountid")
|
||||||
accountUUID, err := uuid.Parse(accountID)
|
accountUUID, err := uuid.Parse(accountID)
|
||||||
@ -28,17 +102,18 @@ func (h *Handler) transactionsForAccount(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, TransactionsResponse{account, transactions})
|
c.JSON(http.StatusOK, TransactionsResponse{&account, transactions})
|
||||||
}
|
}
|
||||||
|
|
||||||
type TransactionsResponse struct {
|
type TransactionsResponse struct {
|
||||||
Account postgres.Account
|
Account *postgres.Account
|
||||||
Transactions []postgres.GetTransactionsForAccountRow
|
Transactions []postgres.DisplayTransaction
|
||||||
}
|
}
|
||||||
|
|
||||||
type EditAccountRequest struct {
|
type EditAccountRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
OnBudget bool `json:"onBudget"`
|
OnBudget bool `json:"onBudget"`
|
||||||
|
IsOpen bool `json:"isOpen"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) editAccount(c *gin.Context) {
|
func (h *Handler) editAccount(c *gin.Context) {
|
||||||
@ -59,6 +134,7 @@ func (h *Handler) editAccount(c *gin.Context) {
|
|||||||
updateParams := postgres.UpdateAccountParams{
|
updateParams := postgres.UpdateAccountParams{
|
||||||
Name: request.Name,
|
Name: request.Name,
|
||||||
OnBudget: request.OnBudget,
|
OnBudget: request.OnBudget,
|
||||||
|
IsOpen: request.IsOpen,
|
||||||
ID: accountUUID,
|
ID: accountUUID,
|
||||||
}
|
}
|
||||||
account, err := h.Service.UpdateAccount(c.Request.Context(), updateParams)
|
account, err := h.Service.UpdateAccount(c.Request.Context(), updateParams)
|
||||||
@ -67,5 +143,5 @@ func (h *Handler) editAccount(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
h.returnBudgetingData(c, account.BudgetID)
|
h.getBudget(c, account.BudgetID)
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,6 @@ package server
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
@ -11,28 +10,21 @@ import (
|
|||||||
"git.javil.eu/jacob1123/budgeteer/bcrypt"
|
"git.javil.eu/jacob1123/budgeteer/bcrypt"
|
||||||
"git.javil.eu/jacob1123/budgeteer/jwt"
|
"git.javil.eu/jacob1123/budgeteer/jwt"
|
||||||
"git.javil.eu/jacob1123/budgeteer/postgres"
|
"git.javil.eu/jacob1123/budgeteer/postgres"
|
||||||
txdb "github.com/DATA-DOG/go-txdb"
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() { //nolint:gochecknoinits
|
func TestRegisterUser(t *testing.T) {
|
||||||
txdb.Register("pgtx", "pgx", "postgres://budgeteer_test:budgeteer_test@localhost:5432/budgeteer_test")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRegisterUser(t *testing.T) { //nolint:funlen
|
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
database, err := postgres.Connect("pgtx", "example")
|
database, err := postgres.Connect("pgtx", cfg.DatabaseConnection)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("could not connect to db: %s\n", err)
|
t.Errorf("connect to DB: %v", err)
|
||||||
t.Skip()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tokenVerifier, _ := jwt.NewTokenVerifier(cfg.SessionSecret)
|
||||||
h := Handler{
|
h := Handler{
|
||||||
Service: database,
|
Service: database,
|
||||||
TokenVerifier: &jwt.TokenVerifier{
|
TokenVerifier: tokenVerifier,
|
||||||
Secret: "this_is_my_demo_secret_for_unit_tests",
|
|
||||||
},
|
|
||||||
CredentialsVerifier: &bcrypt.Verifier{},
|
CredentialsVerifier: &bcrypt.Verifier{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,22 +59,4 @@ func TestRegisterUser(t *testing.T) { //nolint:funlen
|
|||||||
t.Error("Did not get a token")
|
t.Error("Did not get a token")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("GetTransactions", func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
context.Request, err = http.NewRequest(http.MethodGet, "/account/accountid/transactions", nil)
|
|
||||||
if recorder.Code != http.StatusOK {
|
|
||||||
t.Errorf("handler returned wrong status code: got %v want %v", recorder.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
var response TransactionsResponse
|
|
||||||
err = json.NewDecoder(recorder.Body).Decode(&response)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err.Error())
|
|
||||||
t.Error("Error retreiving list of transactions.")
|
|
||||||
}
|
|
||||||
if len(response.Transactions) == 0 {
|
|
||||||
t.Error("Did not get any transactions.")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
@ -64,49 +64,3 @@ func (h *Handler) clearBudget(c *gin.Context) {
|
|||||||
|
|
||||||
h.clearBudgetData(c, budgetUUID)
|
h.clearBudgetData(c, budgetUUID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) cleanNegativeBudget(c *gin.Context) {
|
|
||||||
/*budgetID := c.Param("budgetid")
|
|
||||||
budgetUUID, err := uuid.Parse(budgetID)
|
|
||||||
if err != nil {
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, "/login")
|
|
||||||
return
|
|
||||||
}*/
|
|
||||||
|
|
||||||
/*min_date, err := h.Service.GetFirstActivity(c.Request.Context(), budgetUUID)
|
|
||||||
date := getFirstOfMonthTime(min_date)
|
|
||||||
for {
|
|
||||||
nextDate := date.AddDate(0, 1, 0)
|
|
||||||
params := postgres.GetCategoriesWithBalanceParams{
|
|
||||||
BudgetID: budgetUUID,
|
|
||||||
ToDate: nextDate,
|
|
||||||
FromDate: date,
|
|
||||||
}
|
|
||||||
categories, err := h.Service.GetCategoriesWithBalance(c.Request.Context(), params)
|
|
||||||
if err != nil {
|
|
||||||
c.AbortWithError(http.StatusInternalServerError, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, category := range categories {
|
|
||||||
available := category.Available.GetFloat64()
|
|
||||||
if available >= 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var negativeAvailable postgres.Numeric
|
|
||||||
negativeAvailable.Set(-available)
|
|
||||||
createAssignment := postgres.CreateAssignmentParams{
|
|
||||||
Date: nextDate.AddDate(0, 0, -1),
|
|
||||||
Amount: negativeAvailable,
|
|
||||||
CategoryID: category.ID,
|
|
||||||
}
|
|
||||||
h.Service.CreateAssignment(c.Request.Context(), createAssignment)
|
|
||||||
}
|
|
||||||
|
|
||||||
if nextDate.Before(time.Now()) {
|
|
||||||
date = nextDate
|
|
||||||
} else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}*/
|
|
||||||
}
|
|
||||||
|
@ -9,6 +9,28 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func (h *Handler) autocompleteAccounts(c *gin.Context) {
|
||||||
|
budgetID := c.Param("budgetid")
|
||||||
|
budgetUUID, err := uuid.Parse(budgetID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"budgetid missing from URL"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
query := c.Request.URL.Query().Get("s")
|
||||||
|
searchParams := postgres.SearchAccountsParams{
|
||||||
|
BudgetID: budgetUUID,
|
||||||
|
Search: "%" + query + "%",
|
||||||
|
}
|
||||||
|
categories, err := h.Service.SearchAccounts(c.Request.Context(), searchParams)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, categories)
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) autocompleteCategories(c *gin.Context) {
|
func (h *Handler) autocompleteCategories(c *gin.Context) {
|
||||||
budgetID := c.Param("budgetid")
|
budgetID := c.Param("budgetid")
|
||||||
budgetUUID, err := uuid.Parse(budgetID)
|
budgetUUID, err := uuid.Parse(budgetID)
|
||||||
|
@ -1,10 +1,9 @@
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.javil.eu/jacob1123/budgeteer/postgres"
|
"git.javil.eu/jacob1123/budgeteer/postgres"
|
||||||
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
|
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
|
||||||
@ -12,20 +11,8 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
func getFirstOfMonth(year, month int, location *time.Location) time.Time {
|
|
||||||
return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, location)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getFirstOfMonthTime(date time.Time) time.Time {
|
|
||||||
var monthM time.Month
|
|
||||||
year, monthM, _ := date.Date()
|
|
||||||
month := int(monthM)
|
|
||||||
return getFirstOfMonth(year, month, date.Location())
|
|
||||||
}
|
|
||||||
|
|
||||||
type CategoryWithBalance struct {
|
type CategoryWithBalance struct {
|
||||||
*postgres.GetCategoriesRow
|
*postgres.GetCategoriesRow
|
||||||
Available numeric.Numeric
|
|
||||||
AvailableLastMonth numeric.Numeric
|
AvailableLastMonth numeric.Numeric
|
||||||
Activity numeric.Numeric
|
Activity numeric.Numeric
|
||||||
Assigned numeric.Numeric
|
Assigned numeric.Numeric
|
||||||
@ -34,34 +21,12 @@ type CategoryWithBalance struct {
|
|||||||
func NewCategoryWithBalance(category *postgres.GetCategoriesRow) CategoryWithBalance {
|
func NewCategoryWithBalance(category *postgres.GetCategoriesRow) CategoryWithBalance {
|
||||||
return CategoryWithBalance{
|
return CategoryWithBalance{
|
||||||
GetCategoriesRow: category,
|
GetCategoriesRow: category,
|
||||||
Available: numeric.Zero(),
|
|
||||||
AvailableLastMonth: numeric.Zero(),
|
AvailableLastMonth: numeric.Zero(),
|
||||||
Activity: numeric.Zero(),
|
Activity: numeric.Zero(),
|
||||||
Assigned: numeric.Zero(),
|
Assigned: numeric.Zero(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getDate(c *gin.Context) (time.Time, error) {
|
|
||||||
var year, month int
|
|
||||||
yearString := c.Param("year")
|
|
||||||
monthString := c.Param("month")
|
|
||||||
if yearString == "" && monthString == "" {
|
|
||||||
return getFirstOfMonthTime(time.Now()), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
year, err := strconv.Atoi(yearString)
|
|
||||||
if err != nil {
|
|
||||||
return time.Time{}, fmt.Errorf("parse year: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
month, err = strconv.Atoi(monthString)
|
|
||||||
if err != nil {
|
|
||||||
return time.Time{}, fmt.Errorf("parse month: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return getFirstOfMonth(year, month, time.Now().Location()), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) budgetingForMonth(c *gin.Context) {
|
func (h *Handler) budgetingForMonth(c *gin.Context) {
|
||||||
budgetID := c.Param("budgetid")
|
budgetID := c.Param("budgetid")
|
||||||
budgetUUID, err := uuid.Parse(budgetID)
|
budgetUUID, err := uuid.Parse(budgetID)
|
||||||
@ -76,59 +41,62 @@ func (h *Handler) budgetingForMonth(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
firstOfMonth, err := getDate(c)
|
month, err := getDate(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Redirect(http.StatusTemporaryRedirect, "/budget/"+budgetUUID.String())
|
c.Redirect(http.StatusTemporaryRedirect, "/budget/"+budget.ID.String())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
categories, err := h.Service.GetCategories(c.Request.Context(), budgetUUID)
|
data, err := h.getBudgetingViewForMonth(c.Request.Context(), budget, month)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.AbortWithError(http.StatusInternalServerError, err)
|
c.AbortWithError(http.StatusInternalServerError, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
firstOfNextMonth := firstOfMonth.AddDate(0, 1, 0)
|
|
||||||
cumultativeBalances, err := h.Service.GetCumultativeBalances(c.Request.Context(), budgetUUID)
|
|
||||||
if err != nil {
|
|
||||||
c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse{fmt.Sprintf("error loading balances: %s", err)})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
categoriesWithBalance, moneyUsed := h.calculateBalances(
|
|
||||||
budget, firstOfNextMonth, firstOfMonth, categories, cumultativeBalances)
|
|
||||||
|
|
||||||
availableBalance := h.getAvailableBalance(categories, budget, moneyUsed, cumultativeBalances, firstOfNextMonth)
|
|
||||||
|
|
||||||
data := struct {
|
|
||||||
Categories []CategoryWithBalance
|
|
||||||
AvailableBalance numeric.Numeric
|
|
||||||
}{categoriesWithBalance, availableBalance}
|
|
||||||
c.JSON(http.StatusOK, data)
|
c.JSON(http.StatusOK, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (*Handler) getAvailableBalance(categories []postgres.GetCategoriesRow, budget postgres.Budget,
|
func (h *Handler) getBudgetingViewForMonth(ctx context.Context, budget postgres.Budget, month Month) (BudgetingForMonthResponse, error) {
|
||||||
|
categories, err := h.Service.GetCategories(ctx, budget.ID)
|
||||||
|
if err != nil {
|
||||||
|
return BudgetingForMonthResponse{}, fmt.Errorf("error loading categories: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cumultativeBalances, err := h.Service.GetCumultativeBalances(ctx, budget.ID)
|
||||||
|
if err != nil {
|
||||||
|
return BudgetingForMonthResponse{}, fmt.Errorf("error loading balances: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
categoriesWithBalance, moneyUsed, overspentLastMonth := h.calculateBalances(budget, month, categories, cumultativeBalances)
|
||||||
|
availableBalance := h.getAvailableBalance(budget, month, moneyUsed, cumultativeBalances)
|
||||||
|
|
||||||
|
data := BudgetingForMonthResponse{categoriesWithBalance, availableBalance, overspentLastMonth}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type BudgetingForMonthResponse struct {
|
||||||
|
Categories []CategoryWithBalance
|
||||||
|
AvailableBalance numeric.Numeric
|
||||||
|
OverspentLastMonth numeric.Numeric
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Handler) getAvailableBalance(budget postgres.Budget, month Month,
|
||||||
moneyUsed numeric.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow,
|
moneyUsed numeric.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow,
|
||||||
firstOfNextMonth time.Time) numeric.Numeric {
|
) numeric.Numeric {
|
||||||
availableBalance := numeric.Zero()
|
availableBalance := moneyUsed
|
||||||
for _, cat := range categories {
|
|
||||||
if cat.ID != budget.IncomeCategoryID {
|
for _, bal := range cumultativeBalances {
|
||||||
|
if bal.CategoryID != budget.IncomeCategoryID {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
availableBalance = moneyUsed
|
|
||||||
|
|
||||||
for _, bal := range cumultativeBalances {
|
if month.InFuture(bal.Date) {
|
||||||
if bal.CategoryID != cat.ID {
|
continue
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if !bal.Date.Before(firstOfNextMonth) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
availableBalance = availableBalance.Add(bal.Transactions)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
availableBalance.AddI(bal.Transactions)
|
||||||
|
availableBalance.AddI(bal.Assignments) // should be zero, but who knows
|
||||||
}
|
}
|
||||||
|
|
||||||
return availableBalance
|
return availableBalance
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -137,7 +105,7 @@ type BudgetingResponse struct {
|
|||||||
Budget postgres.Budget
|
Budget postgres.Budget
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) budgeting(c *gin.Context) {
|
func (h *Handler) budget(c *gin.Context) {
|
||||||
budgetID := c.Param("budgetid")
|
budgetID := c.Param("budgetid")
|
||||||
budgetUUID, err := uuid.Parse(budgetID)
|
budgetUUID, err := uuid.Parse(budgetID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -145,10 +113,10 @@ func (h *Handler) budgeting(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
h.returnBudgetingData(c, budgetUUID)
|
h.getBudget(c, budgetUUID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) returnBudgetingData(c *gin.Context, budgetUUID uuid.UUID) {
|
func (h *Handler) getBudget(c *gin.Context, budgetUUID uuid.UUID) {
|
||||||
budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID)
|
budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.AbortWithError(http.StatusNotFound, err)
|
c.AbortWithError(http.StatusNotFound, err)
|
||||||
@ -166,57 +134,55 @@ func (h *Handler) returnBudgetingData(c *gin.Context, budgetUUID uuid.UUID) {
|
|||||||
c.JSON(http.StatusOK, data)
|
c.JSON(http.StatusOK, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) calculateBalances(budget postgres.Budget,
|
func (h *Handler) calculateBalances(budget postgres.Budget, month Month,
|
||||||
firstOfNextMonth time.Time, firstOfMonth time.Time, categories []postgres.GetCategoriesRow,
|
categories []postgres.GetCategoriesRow, cumultativeBalances []postgres.GetCumultativeBalancesRow,
|
||||||
cumultativeBalances []postgres.GetCumultativeBalancesRow) ([]CategoryWithBalance, numeric.Numeric) {
|
) ([]CategoryWithBalance, numeric.Numeric, numeric.Numeric) {
|
||||||
categoriesWithBalance := []CategoryWithBalance{}
|
categoriesWithBalance := []CategoryWithBalance{}
|
||||||
|
|
||||||
moneyUsed := numeric.Zero()
|
moneyUsed := numeric.Zero()
|
||||||
|
overspentLastMonth := numeric.Zero()
|
||||||
|
categories = append(categories, postgres.GetCategoriesRow{
|
||||||
|
Group: "Income",
|
||||||
|
Name: "No Category",
|
||||||
|
ID: uuid.UUID{},
|
||||||
|
})
|
||||||
for i := range categories {
|
for i := range categories {
|
||||||
cat := &categories[i]
|
cat := &categories[i]
|
||||||
// do not show hidden categories
|
|
||||||
categoryWithBalance := h.CalculateCategoryBalances(cat, cumultativeBalances,
|
|
||||||
firstOfNextMonth, &moneyUsed, firstOfMonth, budget)
|
|
||||||
|
|
||||||
if cat.ID == budget.IncomeCategoryID {
|
if cat.ID == budget.IncomeCategoryID {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
categoryWithBalance := NewCategoryWithBalance(cat)
|
||||||
|
for _, bal := range cumultativeBalances {
|
||||||
|
if bal.CategoryID != cat.ID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// skip everything in the future
|
||||||
|
if month.InFuture(bal.Date) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
moneyUsed.SubI(bal.Assignments)
|
||||||
|
if month.InPresent(bal.Date) {
|
||||||
|
categoryWithBalance.Activity = bal.Transactions
|
||||||
|
categoryWithBalance.Assigned = bal.Assignments
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
categoryWithBalance.AvailableLastMonth.AddI(bal.Assignments)
|
||||||
|
categoryWithBalance.AvailableLastMonth.AddI(bal.Transactions)
|
||||||
|
if !categoryWithBalance.AvailableLastMonth.IsPositive() {
|
||||||
|
moneyUsed.AddI(categoryWithBalance.AvailableLastMonth)
|
||||||
|
if month.Previous().InPresent(bal.Date) {
|
||||||
|
overspentLastMonth.AddI(categoryWithBalance.AvailableLastMonth)
|
||||||
|
}
|
||||||
|
categoryWithBalance.AvailableLastMonth = numeric.Zero()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
categoriesWithBalance = append(categoriesWithBalance, categoryWithBalance)
|
categoriesWithBalance = append(categoriesWithBalance, categoryWithBalance)
|
||||||
}
|
}
|
||||||
|
|
||||||
return categoriesWithBalance, moneyUsed
|
return categoriesWithBalance, moneyUsed, overspentLastMonth
|
||||||
}
|
|
||||||
|
|
||||||
func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow,
|
|
||||||
cumultativeBalances []postgres.GetCumultativeBalancesRow, firstOfNextMonth time.Time,
|
|
||||||
moneyUsed *numeric.Numeric, firstOfMonth time.Time, budget postgres.Budget) CategoryWithBalance {
|
|
||||||
categoryWithBalance := NewCategoryWithBalance(cat)
|
|
||||||
for _, bal := range cumultativeBalances {
|
|
||||||
if bal.CategoryID != cat.ID {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// skip everything in the future
|
|
||||||
if !bal.Date.Before(firstOfNextMonth) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
*moneyUsed = moneyUsed.Sub(bal.Assignments)
|
|
||||||
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Assignments)
|
|
||||||
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Transactions)
|
|
||||||
if !categoryWithBalance.Available.IsPositive() && bal.Date.Before(firstOfMonth) {
|
|
||||||
*moneyUsed = moneyUsed.Add(categoryWithBalance.Available)
|
|
||||||
categoryWithBalance.Available = numeric.Zero()
|
|
||||||
}
|
|
||||||
|
|
||||||
if bal.Date.Before(firstOfMonth) {
|
|
||||||
categoryWithBalance.AvailableLastMonth = categoryWithBalance.Available
|
|
||||||
} else if bal.Date.Before(firstOfNextMonth) {
|
|
||||||
categoryWithBalance.Activity = bal.Transactions
|
|
||||||
categoryWithBalance.Assigned = bal.Assignments
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return categoryWithBalance
|
|
||||||
}
|
}
|
||||||
|
55
server/category.go
Normal file
55
server/category.go
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/postgres"
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SetCategoryAssignmentRequest struct {
|
||||||
|
Assigned float64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) setCategoryAssignment(c *gin.Context) {
|
||||||
|
categoryID := c.Param("categoryid")
|
||||||
|
categoryUUID, err := uuid.Parse(categoryID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"categoryid missing from URL"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var request SetCategoryAssignmentRequest
|
||||||
|
err = c.BindJSON(&request)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("invalid payload: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
date, err := getDate(c)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("date invalid: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var amount numeric.Numeric
|
||||||
|
err = amount.Set(request.Assigned)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse amount: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updateArgs := postgres.UpdateAssignmentParams{
|
||||||
|
CategoryID: categoryUUID,
|
||||||
|
Date: date.FirstOfMonth(),
|
||||||
|
Amount: amount,
|
||||||
|
}
|
||||||
|
err = h.Service.UpdateAssignment(c.Request.Context(), updateArgs)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("update assignment: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
@ -1,25 +0,0 @@
|
|||||||
package server
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"git.javil.eu/jacob1123/budgeteer/postgres"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (h *Handler) dashboard(c *gin.Context) {
|
|
||||||
userID := MustGetToken(c).GetID()
|
|
||||||
budgets, err := h.Service.GetBudgetsForUser(c.Request.Context(), userID)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
d := DashboardData{
|
|
||||||
Budgets: budgets,
|
|
||||||
}
|
|
||||||
c.JSON(http.StatusOK, d)
|
|
||||||
}
|
|
||||||
|
|
||||||
type DashboardData struct {
|
|
||||||
Budgets []postgres.Budget
|
|
||||||
}
|
|
@ -36,6 +36,10 @@ type ErrorResponse struct {
|
|||||||
Message string
|
Message string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SuccessResponse struct {
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
// LoadRoutes initializes all the routes.
|
// LoadRoutes initializes all the routes.
|
||||||
func (h *Handler) LoadRoutes(router *gin.Engine) {
|
func (h *Handler) LoadRoutes(router *gin.Engine) {
|
||||||
router.Use(enableCachingForStaticFiles())
|
router.Use(enableCachingForStaticFiles())
|
||||||
@ -44,33 +48,37 @@ func (h *Handler) LoadRoutes(router *gin.Engine) {
|
|||||||
api := router.Group("/api/v1")
|
api := router.Group("/api/v1")
|
||||||
|
|
||||||
anonymous := api.Group("/user")
|
anonymous := api.Group("/user")
|
||||||
anonymous.GET("/login", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/login") })
|
|
||||||
anonymous.POST("/login", h.loginPost)
|
anonymous.POST("/login", h.loginPost)
|
||||||
anonymous.POST("/register", h.registerPost)
|
anonymous.POST("/register", h.registerPost)
|
||||||
|
|
||||||
authenticated := api.Group("")
|
authenticated := api.Group("")
|
||||||
authenticated.Use(h.verifyLoginWithForbidden)
|
{
|
||||||
authenticated.GET("/dashboard", h.dashboard)
|
authenticated.Use(h.verifyLoginWithForbidden)
|
||||||
authenticated.GET("/account/:accountid/transactions", h.transactionsForAccount)
|
authenticated.GET("/account/:accountid/transactions", h.transactionsForAccount)
|
||||||
authenticated.POST("/account/:accountid", h.editAccount)
|
authenticated.POST("/account/:accountid/reconcile", h.reconcileTransactions)
|
||||||
authenticated.GET("/admin/clear-database", h.clearDatabase)
|
authenticated.POST("/account/:accountid", h.editAccount)
|
||||||
|
authenticated.GET("/admin/clear-database", h.clearDatabase)
|
||||||
|
|
||||||
budget := authenticated.Group("/budget")
|
budget := authenticated.Group("/budget")
|
||||||
budget.POST("/new", h.newBudget)
|
budget.POST("/new", h.newBudget)
|
||||||
budget.GET("/:budgetid", h.budgeting)
|
budget.GET("/:budgetid", h.budget)
|
||||||
budget.GET("/:budgetid/:year/:month", h.budgetingForMonth)
|
budget.GET("/:budgetid/:year/:month", h.budgetingForMonth)
|
||||||
budget.GET("/:budgetid/autocomplete/payees", h.autocompletePayee)
|
budget.POST("/:budgetid/category/:categoryid/:year/:month", h.setCategoryAssignment)
|
||||||
budget.GET("/:budgetid/autocomplete/categories", h.autocompleteCategories)
|
budget.GET("/:budgetid/autocomplete/payees", h.autocompletePayee)
|
||||||
budget.DELETE("/:budgetid", h.deleteBudget)
|
budget.GET("/:budgetid/autocomplete/accounts", h.autocompleteAccounts)
|
||||||
budget.POST("/:budgetid/import/ynab", h.importYNAB)
|
budget.GET("/:budgetid/autocomplete/categories", h.autocompleteCategories)
|
||||||
budget.POST("/:budgetid/export/ynab/transactions", h.exportYNABTransactions)
|
budget.GET("/:budgetid/problematic-transactions", h.problematicTransactions)
|
||||||
budget.POST("/:budgetid/export/ynab/assignments", h.exportYNABAssignments)
|
budget.POST("/:budgetid/filtered-transactions", h.filteredTransactions)
|
||||||
budget.POST("/:budgetid/settings/clear", h.clearBudget)
|
budget.DELETE("/:budgetid", h.deleteBudget)
|
||||||
budget.POST("/:budgetid/settings/clean-negative", h.cleanNegativeBudget)
|
budget.POST("/:budgetid/import/ynab", h.importYNAB)
|
||||||
|
budget.POST("/:budgetid/export/ynab/transactions", h.exportYNABTransactions)
|
||||||
|
budget.POST("/:budgetid/export/ynab/assignments", h.exportYNABAssignments)
|
||||||
|
budget.POST("/:budgetid/settings/clear", h.clearBudget)
|
||||||
|
|
||||||
transaction := authenticated.Group("/transaction")
|
transaction := authenticated.Group("/transaction")
|
||||||
transaction.POST("/new", h.newTransaction)
|
transaction.POST("/new", h.newTransaction)
|
||||||
transaction.POST("/:transactionid", h.newTransaction)
|
transaction.POST("/:transactionid", h.updateTransaction)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) ServeStatic(c *gin.Context) {
|
func (h *Handler) ServeStatic(c *gin.Context) {
|
||||||
|
305
server/main_test.go
Normal file
305
server/main_test.go
Normal file
@ -0,0 +1,305 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/bcrypt"
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/config"
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/jwt"
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/postgres"
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/web"
|
||||||
|
|
||||||
|
txdb "github.com/DATA-DOG/go-txdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
var cfg = config.Config{ //nolint:gochecknoglobals
|
||||||
|
DatabaseConnection: "postgres://budgeteer:budgeteer@db:5432/budgeteer_test",
|
||||||
|
SessionSecret: "this_is_my_demo_secret_for_unit_tests",
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() { //nolint:gochecknoinits
|
||||||
|
_, err := postgres.Connect("pgx", cfg.DatabaseConnection)
|
||||||
|
if err != nil {
|
||||||
|
panic("failed connecting to DB for migrations: " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
txdb.Register("pgtx", "pgx", cfg.DatabaseConnection)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMain(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
queries, err := postgres.Connect("pgtx", cfg.DatabaseConnection)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("connect to DB: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
static, err := fs.Sub(web.Static, "dist")
|
||||||
|
if err != nil {
|
||||||
|
panic("couldn't open static files")
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenVerifier, err := jwt.NewTokenVerifier(cfg.SessionSecret)
|
||||||
|
if err != nil {
|
||||||
|
panic(fmt.Errorf("couldn't create token verifier: %w", err))
|
||||||
|
}
|
||||||
|
|
||||||
|
handler := &Handler{
|
||||||
|
Service: queries,
|
||||||
|
TokenVerifier: tokenVerifier,
|
||||||
|
CredentialsVerifier: &bcrypt.Verifier{},
|
||||||
|
StaticFS: http.FS(static),
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
createUserParams := postgres.CreateUserParams{
|
||||||
|
Email: "test@example.com",
|
||||||
|
Name: "test@example.com",
|
||||||
|
Password: "this is my dumb password",
|
||||||
|
}
|
||||||
|
user, err := handler.Service.CreateUser(ctx, createUserParams)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
t.Fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
budget, err := handler.Service.NewBudget(ctx, "My nice Budget", user.ID)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
t.Fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.DoYNABImport(ctx, t, budget)
|
||||||
|
|
||||||
|
loc := time.Now().Location()
|
||||||
|
|
||||||
|
AssertCategoriesAndAvailableEqual(ctx, t, loc, handler, budget)
|
||||||
|
|
||||||
|
AssertAccountsEqual(ctx, t, handler, budget)
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertAccountsEqual(ctx context.Context, t *testing.T, handler *Handler, budget *postgres.Budget) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
t.Run("account balances", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
resultDir := "../testdata/production-export/results"
|
||||||
|
files, err := os.ReadDir(resultDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("could not load results: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, file := range files {
|
||||||
|
if file.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
name := file.Name()[0 : len(file.Name())-5]
|
||||||
|
if name != "accounts" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
testCaseFile := filepath.Join(resultDir, file.Name())
|
||||||
|
handler.CheckAccountBalance(ctx, t, testCaseFile, budget)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h Handler) CheckAccountBalance(ctx context.Context, t *testing.T, testCaseFile string, budget *postgres.Budget) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
accounts, err := h.Service.GetAccountsWithBalance(ctx, budget.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("get accounts: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
testDataFile, err := os.Open(testCaseFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("could not load category test data: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var testData map[string]float64
|
||||||
|
dec := json.NewDecoder(testDataFile)
|
||||||
|
err = dec.Decode(&testData)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("could not decode category test data: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for accountName, accountBalance := range testData {
|
||||||
|
found := false
|
||||||
|
for _, account := range accounts {
|
||||||
|
if account.Name == accountName {
|
||||||
|
assertEqual(t, accountBalance, account.WorkingBalance.GetFloat64(), "balance for "+accountName)
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !found {
|
||||||
|
t.Errorf("account " + accountName + " was not found in result")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertCategoriesAndAvailableEqual(ctx context.Context, t *testing.T, loc *time.Location, handler *Handler, budget *postgres.Budget) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
t.Run("Categories and available balance", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
resultDir := "../testdata/production-export/results"
|
||||||
|
files, err := os.ReadDir(resultDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("could not load results: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, file := range files {
|
||||||
|
if file.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
name := file.Name()[0 : len(file.Name())-5]
|
||||||
|
parts := strings.Split(name, "-")
|
||||||
|
if len(parts) != 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
year, _ := strconv.Atoi(parts[0])
|
||||||
|
month, _ := strconv.Atoi(parts[1])
|
||||||
|
testCaseFile := filepath.Join(resultDir, file.Name())
|
||||||
|
handler.CheckAvailableBalance(ctx, t, testCaseFile, budget, Month{year, month})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type TestData struct {
|
||||||
|
AvailableBalance float64
|
||||||
|
Categories map[string]CategoryTestData
|
||||||
|
}
|
||||||
|
|
||||||
|
type CategoryTestData struct {
|
||||||
|
Available float64
|
||||||
|
Activity float64
|
||||||
|
Assigned float64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h Handler) CheckAvailableBalance(ctx context.Context, t *testing.T, testCaseFile string, budget *postgres.Budget, month Month) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
t.Run(month.String(), func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
data, err := h.getBudgetingViewForMonth(ctx, *budget, month)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("prepare budgeting: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
testDataFile, err := os.Open(testCaseFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("could not load category test data: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var testData TestData
|
||||||
|
dec := json.NewDecoder(testDataFile)
|
||||||
|
err = dec.Decode(&testData)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("could not decode category test data: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEqual(t, testData.AvailableBalance, data.AvailableBalance.GetFloat64(), "available balance")
|
||||||
|
|
||||||
|
for categoryName, categoryTestData := range testData.Categories {
|
||||||
|
found := false
|
||||||
|
for _, category := range data.Categories {
|
||||||
|
name := category.Group + " : " + category.Name
|
||||||
|
|
||||||
|
if name == categoryName {
|
||||||
|
assertEqual(t, categoryTestData.Activity, category.Activity.GetFloat64(), "activity for "+categoryName)
|
||||||
|
assertEqual(t, categoryTestData.Assigned, category.Assigned.GetFloat64(), "assigned for "+categoryName)
|
||||||
|
available := category.AvailableLastMonth
|
||||||
|
available.AddI(category.Activity).AddI(category.Assigned)
|
||||||
|
assertEqual(t, categoryTestData.Available, available.GetFloat64(), "available for "+categoryName)
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !found {
|
||||||
|
t.Errorf("category " + categoryName + " was not found in result")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertEqualBool(t *testing.T, expected, actual bool, message string) {
|
||||||
|
t.Helper()
|
||||||
|
if expected == actual {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Errorf("%s: expected %v, got %v", message, expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertEqual(t *testing.T, expected, actual float64, message string) {
|
||||||
|
t.Helper()
|
||||||
|
if expected == actual {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Errorf("%s: expected %f, got %f", message, expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h Handler) DoYNABImport(ctx context.Context, t *testing.T, budget *postgres.Budget) {
|
||||||
|
t.Helper()
|
||||||
|
budgetID := budget.ID
|
||||||
|
ynab, err := postgres.NewYNABImport(ctx, h.Service.Queries, budgetID)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
t.Fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
transactions, err := os.Open("../testdata/production-export/Register.tsv")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
t.Fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
assignments, err := os.Open("../testdata/production-export/Budget.tsv")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
t.Fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = ynab.ImportTransactions(ctx, transactions)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
t.Fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = ynab.ImportAssignments(ctx, assignments)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
t.Fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
71
server/month.go
Normal file
71
server/month.go
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Month struct {
|
||||||
|
Year int
|
||||||
|
Month int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFromTime(date time.Time) Month {
|
||||||
|
return Month{date.Year(), int(date.Month())}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Month) String() string {
|
||||||
|
return fmt.Sprintf("%d-%d", m.Year, m.Month)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Month) FirstOfMonth() time.Time {
|
||||||
|
return time.Date(m.Year, time.Month(m.Month), 1, 0, 0, 0, 0, time.Now().Location())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Month) Previous() Month {
|
||||||
|
if m.Month == int(time.January) {
|
||||||
|
return Month{Year: m.Year - 1, Month: int(time.December)}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Month{Year: m.Year, Month: m.Month - 1}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Month) Next() Month {
|
||||||
|
if m.Month == int(time.December) {
|
||||||
|
return Month{Year: m.Year + 1, Month: int(time.January)}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Month{Year: m.Year, Month: m.Month + 1}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Month) InFuture(date time.Time) bool {
|
||||||
|
if m.Year < date.Year() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.Year > date.Year() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return time.Month(m.Month) < date.Month()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Month) InPast(date time.Time) bool {
|
||||||
|
if m.Year > date.Year() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.Year < date.Year() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return time.Month(m.Month) > date.Month()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Month) InPresent(date time.Time) bool {
|
||||||
|
if date.Year() != m.Year {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return date.Month() == time.Month(m.Month)
|
||||||
|
}
|
46
server/month_test.go
Normal file
46
server/month_test.go
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package server_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TestCaseCompare struct {
|
||||||
|
Value server.Month
|
||||||
|
Date time.Time
|
||||||
|
InPast bool
|
||||||
|
InPresent bool
|
||||||
|
InFuture bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestComparisons(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
loc := time.Now().Location()
|
||||||
|
tests := []TestCaseCompare{
|
||||||
|
{server.Month{2022, 2}, time.Date(2022, 3, 1, 0, 0, 0, 0, loc), false, false, true},
|
||||||
|
{server.Month{2022, 3}, time.Date(2022, 3, 1, 0, 0, 0, 0, loc), false, true, false},
|
||||||
|
{server.Month{2022, 4}, time.Date(2022, 3, 1, 0, 0, 0, 0, loc), true, false, false},
|
||||||
|
{server.Month{2022, 2}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), false, false, true},
|
||||||
|
{server.Month{2022, 3}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), false, true, false},
|
||||||
|
{server.Month{2022, 4}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), true, false, false},
|
||||||
|
{server.Month{2021, 2}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), false, false, true},
|
||||||
|
{server.Month{2021, 3}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), false, false, true},
|
||||||
|
{server.Month{2021, 4}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), false, false, true},
|
||||||
|
{server.Month{2023, 2}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), true, false, false},
|
||||||
|
{server.Month{2023, 3}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), true, false, false},
|
||||||
|
{server.Month{2023, 4}, time.Date(2022, 3, 31, 0, 0, 0, 0, loc), true, false, false},
|
||||||
|
{server.Month{2021, 11}, time.Date(2021, 12, 1, 0, 0, 0, 0, loc), false, false, true},
|
||||||
|
}
|
||||||
|
for i := range tests { //nolint:paralleltest
|
||||||
|
test := tests[i]
|
||||||
|
t.Run(test.Date.Format("2006-01-02")+" is in of "+test.Value.String(), func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
server.AssertEqualBool(t, test.InPast, test.Value.InPast(test.Date), "in past")
|
||||||
|
server.AssertEqualBool(t, test.InPresent, test.Value.InPresent(test.Date), "in present")
|
||||||
|
server.AssertEqualBool(t, test.InFuture, test.Value.InFuture(test.Date), "in future")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
109
server/reconcile.go
Normal file
109
server/reconcile.go
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/postgres"
|
||||||
|
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ReconcileTransactionsRequest struct {
|
||||||
|
TransactionIDs []uuid.UUID `json:"transactionIds"`
|
||||||
|
ReconcilationTransactionAmount string `json:"reconciliationTransactionAmount"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReconcileTransactionsResponse struct {
|
||||||
|
Message string
|
||||||
|
ReconciliationTransaction *postgres.DisplayTransaction
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) reconcileTransactions(c *gin.Context) {
|
||||||
|
accountID := c.Param("accountid")
|
||||||
|
accountUUID, err := uuid.Parse(accountID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var request ReconcileTransactionsRequest
|
||||||
|
err = c.BindJSON(&request)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse request: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var amount numeric.Numeric
|
||||||
|
err = amount.Set(request.ReconcilationTransactionAmount)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse request: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := h.Service.BeginTx(c.Request.Context(), &sql.TxOptions{})
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("begin tx: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
db := h.Service.WithTx(tx)
|
||||||
|
for _, transactionID := range request.TransactionIDs {
|
||||||
|
err := db.SetTransactionReconciled(c.Request.Context(), transactionID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("update transaction: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reconciliationTransaction, err := h.CreateReconcilationTransaction(amount, accountUUID, db, c)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("insert new transaction: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = h.Service.SetLastReconciled(c.Request.Context(), accountUUID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("set last reconciled: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = tx.Commit()
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("commit: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, ReconcileTransactionsResponse{
|
||||||
|
Message: fmt.Sprintf("Set status for %d transactions", len(request.TransactionIDs)),
|
||||||
|
ReconciliationTransaction: reconciliationTransaction,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Handler) CreateReconcilationTransaction(amount numeric.Numeric, accountUUID uuid.UUID, db *postgres.Queries, c *gin.Context) (*postgres.DisplayTransaction, error) {
|
||||||
|
if amount.IsZero() {
|
||||||
|
return nil, nil //nolint: nilnil
|
||||||
|
}
|
||||||
|
|
||||||
|
createTransaction := postgres.CreateTransactionParams{
|
||||||
|
Date: time.Now(),
|
||||||
|
Memo: "Reconciliation Transaction",
|
||||||
|
Amount: amount,
|
||||||
|
AccountID: accountUUID,
|
||||||
|
Status: "Reconciled",
|
||||||
|
}
|
||||||
|
transactionUUID, err := db.CreateTransaction(c.Request.Context(), createTransaction)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("insert new transaction: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction, err := db.GetTransaction(c.Request.Context(), transactionUUID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("get created transaction: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &transaction, nil
|
||||||
|
}
|
@ -27,7 +27,7 @@ type NewTransactionPayload struct {
|
|||||||
State string `json:"state"`
|
State string `json:"state"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) newTransaction(c *gin.Context) {
|
func (h *Handler) updateTransaction(c *gin.Context) {
|
||||||
var payload NewTransactionPayload
|
var payload NewTransactionPayload
|
||||||
err := c.BindJSON(&payload)
|
err := c.BindJSON(&payload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -42,8 +42,26 @@ func (h *Handler) newTransaction(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
transactionID := c.Param("transactionid")
|
transactionID := c.Param("transactionid")
|
||||||
if transactionID != "" {
|
transactionUUID, err := uuid.Parse(transactionID)
|
||||||
h.UpdateTransaction(payload, amount, transactionID, c)
|
if err != nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"transactionid missing from URL"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.UpdateTransaction(payload, amount, transactionUUID, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) newTransaction(c *gin.Context) {
|
||||||
|
var payload NewTransactionPayload
|
||||||
|
err := c.BindJSON(&payload)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
amount, err := numeric.Parse(payload.Amount)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("amount: %w", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,11 +75,13 @@ func (h *Handler) newTransaction(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if payload.Payee.Type == "account" {
|
if payload.Payee.Type == "account" {
|
||||||
err := h.CreateTransferForOtherAccount(newTransaction, amount, payload, c)
|
groupID, err := h.CreateTransferForOtherAccount(newTransaction, amount, payload, c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.AbortWithError(http.StatusInternalServerError, err)
|
c.AbortWithError(http.StatusInternalServerError, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
newTransaction.GroupID = groupID
|
||||||
} else {
|
} else {
|
||||||
payeeID, err := GetPayeeID(c.Request.Context(), payload, h)
|
payeeID, err := GetPayeeID(c.Request.Context(), payload, h)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -70,16 +90,22 @@ func (h *Handler) newTransaction(c *gin.Context) {
|
|||||||
newTransaction.PayeeID = payeeID
|
newTransaction.PayeeID = payeeID
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
|
transactionUUID, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create transaction: %w", err))
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create transaction: %w", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
transaction, err := h.Service.GetTransaction(c.Request.Context(), transactionUUID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("get transaction: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, transaction)
|
c.JSON(http.StatusOK, transaction)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) UpdateTransaction(payload NewTransactionPayload, amount numeric.Numeric, transactionID string, c *gin.Context) {
|
func (h *Handler) UpdateTransaction(payload NewTransactionPayload, amount numeric.Numeric, transactionUUID uuid.UUID, c *gin.Context) {
|
||||||
transactionUUID := uuid.MustParse(transactionID)
|
|
||||||
if amount.IsZero() {
|
if amount.IsZero() {
|
||||||
err := h.Service.DeleteTransaction(c.Request.Context(), transactionUUID)
|
err := h.Service.DeleteTransaction(c.Request.Context(), transactionUUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -100,10 +126,19 @@ func (h *Handler) UpdateTransaction(payload NewTransactionPayload, amount numeri
|
|||||||
err := h.Service.UpdateTransaction(c.Request.Context(), editTransaction)
|
err := h.Service.UpdateTransaction(c.Request.Context(), editTransaction)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("edit transaction: %w", err))
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("edit transaction: %w", err))
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
transaction, err := h.Service.GetTransaction(c.Request.Context(), transactionUUID)
|
||||||
|
if err != nil {
|
||||||
|
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("get transaction: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, transaction)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) CreateTransferForOtherAccount(newTransaction postgres.CreateTransactionParams, amount numeric.Numeric, payload NewTransactionPayload, c *gin.Context) error {
|
func (h *Handler) CreateTransferForOtherAccount(newTransaction postgres.CreateTransactionParams, amount numeric.Numeric, payload NewTransactionPayload, c *gin.Context) (uuid.NullUUID, error) {
|
||||||
newTransaction.GroupID = uuid.NullUUID{UUID: uuid.New(), Valid: true}
|
newTransaction.GroupID = uuid.NullUUID{UUID: uuid.New(), Valid: true}
|
||||||
newTransaction.Amount = amount.Neg()
|
newTransaction.Amount = amount.Neg()
|
||||||
newTransaction.AccountID = payload.Payee.ID.UUID
|
newTransaction.AccountID = payload.Payee.ID.UUID
|
||||||
@ -113,9 +148,9 @@ func (h *Handler) CreateTransferForOtherAccount(newTransaction postgres.CreateTr
|
|||||||
|
|
||||||
_, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
|
_, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("create transfer transaction: %w", err)
|
return uuid.NullUUID{}, fmt.Errorf("create transfer transaction: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return newTransaction.GroupID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetPayeeID(context context.Context, payload NewTransactionPayload, h *Handler) (uuid.NullUUID, error) {
|
func GetPayeeID(context context.Context, payload NewTransactionPayload, h *Handler) (uuid.NullUUID, error) {
|
||||||
|
37
server/util.go
Normal file
37
server/util.go
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getDate(c *gin.Context) (Month, error) {
|
||||||
|
var year, month int
|
||||||
|
yearString := c.Param("year")
|
||||||
|
monthString := c.Param("month")
|
||||||
|
if yearString == "" && monthString == "" {
|
||||||
|
return getFirstOfMonthTime(time.Now()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
year, err := strconv.Atoi(yearString)
|
||||||
|
if err != nil {
|
||||||
|
return Month{}, fmt.Errorf("parse year: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
month, err = strconv.Atoi(monthString)
|
||||||
|
if err != nil {
|
||||||
|
return Month{}, fmt.Errorf("parse month: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Month{year, month}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getFirstOfMonthTime(date time.Time) Month {
|
||||||
|
var monthM time.Month
|
||||||
|
year, monthM, _ := date.Date()
|
||||||
|
month := int(monthM)
|
||||||
|
return Month{year, month}
|
||||||
|
}
|
1
testdata
Submodule
1
testdata
Submodule
Submodule testdata added at 8de369b17a
21
web/.eslintrc.js
Normal file
21
web/.eslintrc.js
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
module.exports = {
|
||||||
|
extends: [
|
||||||
|
// add more generic rulesets here, such as:
|
||||||
|
// 'eslint:recommended',
|
||||||
|
"plugin:vue/vue3-recommended",
|
||||||
|
// 'plugin:vue/recommended' // Use this if you are using Vue.js 2.x.
|
||||||
|
],
|
||||||
|
rules: {
|
||||||
|
// override/add rules settings here, such as:
|
||||||
|
'vue/max-attributes-per-line': 'off',
|
||||||
|
'vue/singleline-html-element-content-newline': 'off',
|
||||||
|
'vue/first-attribute-linebreak': 'off',
|
||||||
|
'vue/html-closing-bracket-newline': 'off',
|
||||||
|
// 'vue/no-unused-vars': 'error'
|
||||||
|
},
|
||||||
|
parser: "vue-eslint-parser",
|
||||||
|
parserOptions: {
|
||||||
|
parser: "@typescript-eslint/parser",
|
||||||
|
sourceType: "module",
|
||||||
|
},
|
||||||
|
};
|
0
web/dist/generate-directory-for-ci
vendored
Normal file
0
web/dist/generate-directory-for-ci
vendored
Normal file
@ -1,13 +1,14 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" href="/favicon.ico" />
|
<link rel="icon" href="/favicon.ico" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Vite App</title>
|
<title>Vite App</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body
|
||||||
<div id="app"></div>
|
class="bg-slate-200 text-slate-800 dark:bg-slate-800 dark:text-slate-200 box-border w-full">
|
||||||
<script type="module" src="/src/main.ts"></script>
|
<div id="app"></div>
|
||||||
</body>
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
@ -1,32 +1,41 @@
|
|||||||
{
|
{
|
||||||
"name": "web",
|
"name": "web",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"serve": "vite preview",
|
"serve": "vite preview",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@mdi/font": "5.9.55",
|
"@mdi/font": "5.9.55",
|
||||||
"@vueuse/core": "^7.6.1",
|
"@vueuse/core": "^7.6.1",
|
||||||
"autoprefixer": "^10.4.2",
|
"autoprefixer": "^10.4.2",
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"pinia": "^2.0.11",
|
"pinia": "^2.0.11",
|
||||||
"postcss": "^8.4.6",
|
"postcss": "^8.4.6",
|
||||||
"tailwindcss": "^3.0.18",
|
"tailwindcss": "^3.0.18",
|
||||||
"vue": "^3.2.25",
|
"vue": "^3.2.25",
|
||||||
"vue-router": "^4.0.12"
|
"vue-router": "^4.0.12"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/file-saver": "^2.0.5",
|
"@types/file-saver": "^2.0.5",
|
||||||
"@vitejs/plugin-vue": "^2.0.0",
|
"@typescript-eslint/parser": "^5.13.0",
|
||||||
"@vue/cli-plugin-babel": "5.0.0-beta.7",
|
"@vitejs/plugin-vue": "^2.0.0",
|
||||||
"@vue/cli-plugin-typescript": "~4.5.0",
|
"eslint": "^8.10.0",
|
||||||
"@vue/cli-service": "5.0.0-beta.7",
|
"eslint-plugin-vue": "^8.5.0",
|
||||||
"sass": "^1.38.0",
|
"prettier": "2.5.1",
|
||||||
"sass-loader": "^10.0.0",
|
"sass": "^1.38.0",
|
||||||
"vite": "^2.7.2",
|
"sass-loader": "^10.0.0",
|
||||||
"vue-cli-plugin-vuetify": "~2.4.5"
|
"typescript": "^4.5.5",
|
||||||
}
|
"vite": "^2.7.2",
|
||||||
|
"vue-tsc": "^0.32.0"
|
||||||
|
},
|
||||||
|
"prettier": {
|
||||||
|
"bracketSameLine": true,
|
||||||
|
"embeddedLanguageFormatting": "off",
|
||||||
|
"tabWidth": 4,
|
||||||
|
"useTabs": false
|
||||||
|
},
|
||||||
|
"eslintIgnore": ["index.css"]
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
plugins: {
|
plugins: {
|
||||||
tailwindcss: {},
|
tailwindcss: {},
|
||||||
autoprefixer: {},
|
autoprefixer: {},
|
||||||
},
|
},
|
||||||
}
|
};
|
||||||
|
8
web/src/@types/shims-vue.d.ts
vendored
8
web/src/@types/shims-vue.d.ts
vendored
@ -1,5 +1,5 @@
|
|||||||
declare module "*.vue" {
|
declare module "*.vue" {
|
||||||
import { defineComponent } from "vue";
|
import { defineComponent } from "vue";
|
||||||
const component: ReturnType<typeof defineComponent>;
|
const component: ReturnType<typeof defineComponent>;
|
||||||
export default component;
|
export default component;
|
||||||
}
|
}
|
||||||
|
@ -1,65 +1,17 @@
|
|||||||
<script lang="ts">
|
<script lang="ts" setup>
|
||||||
import { mapState } from "pinia";
|
import MainMenu from "./components/MainMenu.vue";
|
||||||
import { defineComponent } from "vue";
|
|
||||||
import { useBudgetsStore } from "./stores/budget";
|
|
||||||
import { useSessionStore } from "./stores/session";
|
|
||||||
import { useSettingsStore } from "./stores/settings";
|
|
||||||
|
|
||||||
export default defineComponent({
|
|
||||||
computed: {
|
|
||||||
...mapState(useBudgetsStore, ["CurrentBudgetName"]),
|
|
||||||
...mapState(useSettingsStore, ["Menu"]),
|
|
||||||
...mapState(useSessionStore, ["LoggedIn"]),
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
logout() {
|
|
||||||
useSessionStore().logout();
|
|
||||||
this.$router.push("/login");
|
|
||||||
},
|
|
||||||
toggleMenu() {
|
|
||||||
useSettingsStore().toggleMenu();
|
|
||||||
},
|
|
||||||
toggleMenuSize() {
|
|
||||||
useSettingsStore().toggleMenuSize();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="box-border w-full">
|
<div class="flex flex-col md:flex-row flex-1 h-screen">
|
||||||
<div class="flex bg-gray-400 p-4 m-2 rounded-lg">
|
<router-view name="sidebar" />
|
||||||
<span class="flex-1 font-bold text-5xl -my-3 hidden md:inline" @click="toggleMenuSize">≡</span>
|
|
||||||
<span class="flex-1 font-bold text-5xl -my-3 md:hidden" @click="toggleMenu">≡</span>
|
|
||||||
|
|
||||||
<span class="flex-1">{{ CurrentBudgetName }}</span>
|
<div class="flex-1 overflow-auto">
|
||||||
|
<MainMenu />
|
||||||
|
|
||||||
<div class="flex flex-1 flex-row justify-end -mx-4">
|
<div class="p-3 pl-6">
|
||||||
<router-link class="mx-4" v-if="LoggedIn" to="/dashboard">Dashboard</router-link>
|
<router-view />
|
||||||
<router-link class="mx-4" v-if="!LoggedIn" to="/login">Login</router-link>
|
</div>
|
||||||
<a class="mx-4" v-if="LoggedIn" @click="logout">Logout</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="flex flex-col md:flex-row flex-1">
|
|
||||||
<div
|
|
||||||
:class="[Menu.Expand ? 'md:w-72' : 'md:w-36', Menu.Show ? '' : 'hidden']"
|
|
||||||
class="md:block flex-shrink-0 w-full"
|
|
||||||
>
|
|
||||||
<router-view name="sidebar"></router-view>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="flex-1 p-6">
|
|
||||||
<router-view></router-view>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style>
|
|
||||||
#app {
|
|
||||||
font-family: Avenir, Helvetica, Arial, sans-serif;
|
|
||||||
-webkit-font-smoothing: antialiased;
|
|
||||||
-moz-osx-font-smoothing: grayscale;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import { useSessionStore } from "./stores/session";
|
import { useSessionStore } from "./stores/session";
|
||||||
|
|
||||||
export const BASE_URL = "/api/v1"
|
export const BASE_URL = "/api/v1";
|
||||||
|
|
||||||
export function GET(path: string) {
|
export function GET(path: string) {
|
||||||
const sessionStore = useSessionStore();
|
const sessionStore = useSessionStore();
|
||||||
return fetch(BASE_URL + path, {
|
return fetch(BASE_URL + path, {
|
||||||
headers: sessionStore.AuthHeaders,
|
headers: sessionStore.AuthHeaders,
|
||||||
})
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
export function POST(path: string, body: FormData | string | null) {
|
export function POST(path: string, body: FormData | string | null) {
|
||||||
const sessionStore = useSessionStore();
|
const sessionStore = useSessionStore();
|
||||||
@ -15,12 +15,12 @@ export function POST(path: string, body: FormData | string | null) {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: sessionStore.AuthHeaders,
|
headers: sessionStore.AuthHeaders,
|
||||||
body: body,
|
body: body,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
export function DELETE(path: string) {
|
export function DELETE(path: string) {
|
||||||
const sessionStore = useSessionStore();
|
const sessionStore = useSessionStore();
|
||||||
return fetch(BASE_URL + path, {
|
return fetch(BASE_URL + path, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: sessionStore.AuthHeaders,
|
headers: sessionStore.AuthHeaders,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
35
web/src/components/AccountWithReconciled.vue
Normal file
35
web/src/components/AccountWithReconciled.vue
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import { computed } from 'vue';
|
||||||
|
import { useBudgetsStore } from '../stores/budget';
|
||||||
|
import { Account } from '../stores/budget-account';
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
account: Account
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const budgetStore = useBudgetsStore();
|
||||||
|
const CurrentBudgetID = computed(() => budgetStore.CurrentBudgetID);
|
||||||
|
|
||||||
|
const days = 24 * 60 * 60 * 1000;
|
||||||
|
function daysSinceLastReconciled() {
|
||||||
|
const now = new Date().getTime();
|
||||||
|
const diff = new Date(now).getTime() - props.account.LastReconciled.Time.getTime();
|
||||||
|
return Math.floor(diff / days);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<span>
|
||||||
|
<router-link
|
||||||
|
:to="'/budget/' + CurrentBudgetID + '/account/' + account.ID"
|
||||||
|
>
|
||||||
|
{{ account.Name }}
|
||||||
|
</router-link>
|
||||||
|
<span
|
||||||
|
v-if="props.account.LastReconciled.Valid && daysSinceLastReconciled() > 7"
|
||||||
|
class="font-bold bg-gray-500 rounded-md text-sm px-2 mx-2 py-1 no-underline"
|
||||||
|
>
|
||||||
|
{{ daysSinceLastReconciled() }}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</template>
|
@ -2,6 +2,7 @@
|
|||||||
import { ref, watch } from "vue"
|
import { ref, watch } from "vue"
|
||||||
import { GET } from "../api";
|
import { GET } from "../api";
|
||||||
import { useBudgetsStore } from "../stores/budget";
|
import { useBudgetsStore } from "../stores/budget";
|
||||||
|
import Input from "./Input.vue";
|
||||||
|
|
||||||
export interface Suggestion {
|
export interface Suggestion {
|
||||||
ID: string
|
ID: string
|
||||||
@ -10,9 +11,9 @@ export interface Suggestion {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
text: String,
|
text: string,
|
||||||
id: String | undefined,
|
id: string | undefined,
|
||||||
model: String,
|
model: string,
|
||||||
type?: string | undefined,
|
type?: string | undefined,
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
@ -43,22 +44,25 @@ function load(text: String) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
function keypress(e: KeyboardEvent) {
|
function keypress(e: KeyboardEvent) {
|
||||||
if (e.key == "Enter") {
|
if (e.key != "Enter")
|
||||||
const selected = Suggestions.value[0];
|
return;
|
||||||
selectElement(selected);
|
|
||||||
const el = (<HTMLInputElement>e.target);
|
const selected = Suggestions.value[0];
|
||||||
const inputElements = Array.from(el.ownerDocument.querySelectorAll('input:not([disabled]):not([readonly])'));
|
selectElement(selected);
|
||||||
const currentIndex = inputElements.indexOf(el);
|
const el = (<HTMLInputElement>e.target);
|
||||||
const nextElement = inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0];
|
const inputElements = Array.from(el.ownerDocument.querySelectorAll('input:not([disabled]):not([readonly])'));
|
||||||
(<HTMLInputElement>nextElement).focus();
|
const currentIndex = inputElements.indexOf(el);
|
||||||
}
|
const nextElement = inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0];
|
||||||
|
(<HTMLInputElement>nextElement).focus();
|
||||||
};
|
};
|
||||||
|
|
||||||
function selectElement(element: Suggestion) {
|
function selectElement(element: Suggestion) {
|
||||||
emit('update:id', element.ID);
|
emit('update:id', element.ID);
|
||||||
emit('update:text', element.Name);
|
emit('update:text', element.Name);
|
||||||
emit('update:type', element.Type);
|
emit('update:type', element.Type);
|
||||||
Suggestions.value = [];
|
Suggestions.value = [];
|
||||||
};
|
};
|
||||||
|
|
||||||
function select(e: MouseEvent) {
|
function select(e: MouseEvent) {
|
||||||
const target = (<HTMLInputElement>e.target);
|
const target = (<HTMLInputElement>e.target);
|
||||||
const valueAttribute = target.attributes.getNamedItem("value");
|
const valueAttribute = target.attributes.getNamedItem("value");
|
||||||
@ -68,6 +72,7 @@ function select(e: MouseEvent) {
|
|||||||
const selected = Suggestions.value.filter(x => x.ID == selectedID)[0];
|
const selected = Suggestions.value.filter(x => x.ID == selectedID)[0];
|
||||||
selectElement(selected);
|
selectElement(selected);
|
||||||
};
|
};
|
||||||
|
|
||||||
function clear() {
|
function clear() {
|
||||||
emit('update:id', null);
|
emit('update:id', null);
|
||||||
emit('update:text', SearchQuery.value);
|
emit('update:text', SearchQuery.value);
|
||||||
@ -76,21 +81,30 @@ function clear() {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div>
|
<div>
|
||||||
<input
|
<Input
|
||||||
class="border-b-2 border-black"
|
v-if="id == undefined"
|
||||||
@keypress="keypress"
|
v-model="SearchQuery"
|
||||||
v-if="id == undefined"
|
type="text"
|
||||||
v-model="SearchQuery"
|
class="border-b-2 border-black block w-full border-b-2 border-black"
|
||||||
/>
|
@keypress="keypress"
|
||||||
<span @click="clear" v-if="id != undefined" class="bg-gray-300">{{ text }}</span>
|
/>
|
||||||
<div v-if="Suggestions.length > 0" class="absolute bg-gray-400 w-64 p-2">
|
<span
|
||||||
<span
|
v-if="id != undefined"
|
||||||
v-for="suggestion in Suggestions"
|
class="bg-gray-300 dark:bg-gray-700"
|
||||||
class="block"
|
@click="clear"
|
||||||
@click="select"
|
>{{ text }}</span>
|
||||||
:value="suggestion.ID"
|
<div
|
||||||
>{{ suggestion.Name }}</span>
|
v-if="Suggestions.length > 0"
|
||||||
</div>
|
class="absolute bg-gray-400 dark:bg-gray-600 w-64 p-2"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
v-for="suggestion in Suggestions"
|
||||||
|
:key="suggestion.ID"
|
||||||
|
class="block"
|
||||||
|
:value="suggestion.ID"
|
||||||
|
@click="select"
|
||||||
|
>{{ suggestion.Name }}</span>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</div>
|
||||||
|
</template>
|
||||||
|
@ -1,10 +0,0 @@
|
|||||||
<script lang="ts" setup>
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<button
|
|
||||||
class="px-4 py-2 text-base font-medium rounded-md shadow-sm focus:outline-none focus:ring-2"
|
|
||||||
>
|
|
||||||
<slot></slot>
|
|
||||||
</button>
|
|
||||||
</template>
|
|
@ -1,8 +0,0 @@
|
|||||||
<script lang="ts" setup>
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="flex flex-row items-center bg-gray-300 h-32 rounded-lg">
|
|
||||||
<slot></slot>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
15
web/src/components/Checkbox.vue
Normal file
15
web/src/components/Checkbox.vue
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
const props = defineProps<{modelValue?: boolean}>();
|
||||||
|
const emits = defineEmits<{
|
||||||
|
(e: "update:modelValue", value: boolean): void
|
||||||
|
}>();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
:checked="modelValue"
|
||||||
|
class="dark:bg-slate-900"
|
||||||
|
@change="emits('update:modelValue', ($event.target as HTMLInputElement)?.checked)"
|
||||||
|
>
|
||||||
|
</template>
|
@ -1,7 +1,11 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed } from 'vue';
|
import { computed } from 'vue';
|
||||||
|
|
||||||
const props = defineProps<{ value: number | undefined }>();
|
const props = defineProps<{
|
||||||
|
value: number | undefined
|
||||||
|
negativeClass?: string
|
||||||
|
positiveClass?: string
|
||||||
|
}>();
|
||||||
|
|
||||||
const internalValue = computed(() => Number(props.value ?? 0));
|
const internalValue = computed(() => Number(props.value ?? 0));
|
||||||
|
|
||||||
@ -11,5 +15,8 @@ const formattedValue = computed(() => internalValue.value.toLocaleString(undefin
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<span class="text-right" :class="internalValue < 0 ? 'negative' : ''">{{ formattedValue }} €</span>
|
<span
|
||||||
</template>
|
class="text-right"
|
||||||
|
:class="internalValue < 0 ? (negativeClass ?? 'negative') : positiveClass"
|
||||||
|
>{{ formattedValue }} €</span>
|
||||||
|
</template>
|
||||||
|
@ -1,8 +1,13 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
const props = defineProps(["modelValue"]);
|
import Input from './Input.vue';
|
||||||
|
const props = defineProps<{
|
||||||
|
modelValue?: Date
|
||||||
|
}>();
|
||||||
const emit = defineEmits(['update:modelValue']);
|
const emit = defineEmits(['update:modelValue']);
|
||||||
|
|
||||||
function dateToYYYYMMDD(d: Date) : string {
|
function dateToYYYYMMDD(d: Date | undefined) : string {
|
||||||
|
if(d == null)
|
||||||
|
return "";
|
||||||
// alternative implementations in https://stackoverflow.com/q/23593052/1850609
|
// alternative implementations in https://stackoverflow.com/q/23593052/1850609
|
||||||
//return new Date(d.getTime() - (d.getTimezoneOffset() * 60 * 1000)).toISOString().split('T')[0];
|
//return new Date(d.getTime() - (d.getTimezoneOffset() * 60 * 1000)).toISOString().split('T')[0];
|
||||||
return d.toISOString().split('T')[0];
|
return d.toISOString().split('T')[0];
|
||||||
@ -23,11 +28,11 @@ function selectAll(event: FocusEvent) {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<input
|
<Input
|
||||||
type="date"
|
|
||||||
ref="input"
|
ref="input"
|
||||||
v-bind:value="dateToYYYYMMDD(modelValue)"
|
type="date"
|
||||||
|
:value="dateToYYYYMMDD(modelValue)"
|
||||||
@input="updateValue"
|
@input="updateValue"
|
||||||
@focus="selectAll"
|
@focus="selectAll"
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
|
26
web/src/components/Input.vue
Normal file
26
web/src/components/Input.vue
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
const props = defineProps<{
|
||||||
|
modelValue?: number | string,
|
||||||
|
type: string,
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const emits = defineEmits<{
|
||||||
|
(e: "update:modelValue", value: number | string): void
|
||||||
|
}>();
|
||||||
|
|
||||||
|
function valueChanged(e: Event) {
|
||||||
|
const target = <HTMLInputElement>e.target;
|
||||||
|
switch (props.type) {
|
||||||
|
case "number":
|
||||||
|
emits('update:modelValue', target.valueAsNumber);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
emits('update:modelValue', target.value)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<input :value="modelValue" :type="type" class="dark:bg-slate-900" @input="valueChanged">
|
||||||
|
</template>
|
44
web/src/components/MainMenu.vue
Normal file
44
web/src/components/MainMenu.vue
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import { computed } from "vue";
|
||||||
|
import { useRouter } from "vue-router";
|
||||||
|
import { useBudgetsStore } from "../stores/budget";
|
||||||
|
import { useSessionStore } from "../stores/session";
|
||||||
|
import { useSettingsStore } from "../stores/settings";
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const CurrentBudgetName = computed(() => useBudgetsStore().CurrentBudgetName);
|
||||||
|
const LoggedIn = computed(() => useSessionStore().LoggedIn);
|
||||||
|
function logout() {
|
||||||
|
useSessionStore().logout();
|
||||||
|
router.push("/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleMenu() {
|
||||||
|
useSettingsStore().toggleMenu();
|
||||||
|
}
|
||||||
|
function toggleMenuSize() {
|
||||||
|
useSettingsStore().toggleMenuSize();
|
||||||
|
}
|
||||||
|
|
||||||
|
router.afterEach(function(to, from) {
|
||||||
|
useSettingsStore().Menu.Show = false;
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex bg-gray-400 dark:bg-gray-600 p-4 static top-0 left-0 w-full h-14">
|
||||||
|
<span class="flex-1 font-bold text-5xl -my-3 hidden md:inline" @click="toggleMenuSize">≡</span>
|
||||||
|
<span class="flex-1 font-bold text-5xl -my-3 md:hidden" @click="toggleMenu">≡</span>
|
||||||
|
<span class="flex-1">{{ CurrentBudgetName }}</span>
|
||||||
|
<div class="flex flex-1 flex-row justify-end -mx-4">
|
||||||
|
<router-link v-if="LoggedIn" class="mx-4" to="/dashboard">
|
||||||
|
Dashboard
|
||||||
|
</router-link>
|
||||||
|
<router-link v-if="!LoggedIn" class="mx-4" to="/login">
|
||||||
|
Login
|
||||||
|
</router-link>
|
||||||
|
<a v-if="LoggedIn" class="mx-4" @click="logout">Logout</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
@ -1,13 +1,13 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import Card from '../components/Card.vue';
|
import RowCard from './RowCard.vue';
|
||||||
import { ref } from "vue";
|
import { ref } from "vue";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
buttonText: string,
|
buttonText?: string,
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
(e: 'submit'): void,
|
(e: 'submit', event : {cancel:boolean}): boolean,
|
||||||
(e: 'open'): void,
|
(e: 'open'): void,
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
@ -20,39 +20,58 @@ function openDialog() {
|
|||||||
visible.value = true;
|
visible.value = true;
|
||||||
};
|
};
|
||||||
function submitDialog() {
|
function submitDialog() {
|
||||||
|
const e = {cancel: false};
|
||||||
|
emit("submit", e);
|
||||||
|
if(e.cancel)
|
||||||
|
return;
|
||||||
|
|
||||||
visible.value = false;
|
visible.value = false;
|
||||||
emit("submit");
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<button @click="openDialog">
|
<button @click="openDialog">
|
||||||
<slot name="placeholder">
|
<slot name="placeholder">
|
||||||
<Card>
|
<RowCard>
|
||||||
<p class="w-24 text-center text-6xl">+</p>
|
<p class="w-24 text-center text-6xl">
|
||||||
<span class="text-lg" dark>{{ buttonText }}</span>
|
+
|
||||||
</Card>
|
</p>
|
||||||
</slot>
|
<span
|
||||||
</button>
|
class="text-lg"
|
||||||
|
dark
|
||||||
|
>{{ buttonText }}</span>
|
||||||
|
</RowCard>
|
||||||
|
</slot>
|
||||||
|
</button>
|
||||||
|
<div
|
||||||
|
v-if="visible"
|
||||||
|
class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full"
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
v-if="visible"
|
class="relative md:top-20 md:mx-auto p-5 md:w-96 shadow-lg md:h-auto h-full rounded-md bg-white dark:bg-black"
|
||||||
class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full"
|
|
||||||
>
|
>
|
||||||
<div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
|
<div class="mt-3 text-center">
|
||||||
<div class="mt-3 text-center">
|
<h3
|
||||||
<h3 class="mt-3 text-lg leading-6 font-medium text-gray-900">{{ buttonText }}</h3>
|
class="mt-3 text-lg leading-6 font-medium text-gray-900 dark:text-gray-100"
|
||||||
<slot></slot>
|
>
|
||||||
<div class="grid grid-cols-2 gap-6">
|
{{ buttonText }}
|
||||||
<button
|
</h3>
|
||||||
@click="closeDialog"
|
<slot />
|
||||||
class="px-4 py-2 bg-red-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-300"
|
<div class="grid grid-cols-2 gap-6">
|
||||||
>Close</button>
|
<button
|
||||||
<button
|
class="px-4 py-2 bg-red-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-300"
|
||||||
@click="submitDialog"
|
@click="closeDialog"
|
||||||
class="px-4 py-2 bg-green-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-300"
|
>
|
||||||
>Save</button>
|
Close
|
||||||
</div>
|
</button>
|
||||||
</div>
|
<button
|
||||||
|
class="px-4 py-2 bg-green-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-300"
|
||||||
|
@click="submitDialog"
|
||||||
|
>
|
||||||
|
Save
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</div>
|
||||||
|
</template>
|
||||||
|
9
web/src/components/RowCard.vue
Normal file
9
web/src/components/RowCard.vue
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
<script lang="ts" setup></script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
class="flex flex-row items-center bg-gray-300 dark:bg-gray-700 rounded-lg"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
7
web/src/components/SimpleButton.vue
Normal file
7
web/src/components/SimpleButton.vue
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
<script lang="ts" setup></script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<button class="px-4 rounded-md shadow-sm focus:outline-none focus:ring-2">
|
||||||
|
<slot />
|
||||||
|
</button>
|
||||||
|
</template>
|
@ -3,58 +3,66 @@ import { computed, ref } from "vue";
|
|||||||
import Autocomplete from './Autocomplete.vue'
|
import Autocomplete from './Autocomplete.vue'
|
||||||
import { useAccountStore } from '../stores/budget-account'
|
import { useAccountStore } from '../stores/budget-account'
|
||||||
import DateInput from "./DateInput.vue";
|
import DateInput from "./DateInput.vue";
|
||||||
|
import { useTransactionsStore } from "../stores/transactions";
|
||||||
|
import Input from "./Input.vue";
|
||||||
|
import Button from "./SimpleButton.vue";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
transactionid: string
|
transactionid: string,
|
||||||
|
withAccount: boolean,
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const accountStore = useAccountStore();
|
const emit = defineEmits(["save"]);
|
||||||
const TX = accountStore.Transactions.get(props.transactionid)!;
|
|
||||||
|
const transactionsStore = useTransactionsStore();
|
||||||
|
const TX = transactionsStore.Transactions.get(props.transactionid)!;
|
||||||
const payeeType = ref<string|undefined>(undefined);
|
const payeeType = ref<string|undefined>(undefined);
|
||||||
|
|
||||||
const payload = computed(() => JSON.stringify({
|
const payload = computed(() => JSON.stringify({
|
||||||
date: TX.Date.toISOString().split("T")[0],
|
date: TX.Date.toISOString().split("T")[0],
|
||||||
payee: {
|
payee: {
|
||||||
Name: TX.Payee,
|
Name: TX.Payee,
|
||||||
ID: TX.PayeeID,
|
ID: TX.PayeeID,
|
||||||
Type: payeeType.value,
|
Type: payeeType.value,
|
||||||
},
|
},
|
||||||
categoryId: TX.CategoryID,
|
categoryId: TX.CategoryID,
|
||||||
memo: TX.Memo,
|
memo: TX.Memo,
|
||||||
amount: TX.Amount.toString(),
|
amount: TX.Amount.toString(),
|
||||||
state: "Uncleared"
|
state: "Uncleared"
|
||||||
}));
|
}));
|
||||||
|
|
||||||
function saveTransaction(e: MouseEvent) {
|
function saveTransaction(e: MouseEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
accountStore.editTransaction(TX.ID, payload.value);
|
transactionsStore.editTransaction(TX.ID, payload.value);
|
||||||
|
emit('save');
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<tr>
|
<tr>
|
||||||
<td style="width: 90px;" class="text-sm">
|
<td class="text-sm">
|
||||||
<DateInput class="border-b-2 border-black" v-model="TX.Date" />
|
<DateInput v-model="TX.Date" class="border-b-2 border-black" />
|
||||||
</td>
|
</td>
|
||||||
<td style="max-width: 150px;">
|
<td v-if="withAccount">
|
||||||
<Autocomplete v-model:text="TX.Payee" v-model:id="TX.PayeeID" v-model:type="payeeType" model="payees" />
|
<Autocomplete v-model:text="TX.Account" v-model:id="TX.AccountID" model="accounts" />
|
||||||
</td>
|
</td>
|
||||||
<td style="max-width: 200px;">
|
<td>
|
||||||
<Autocomplete v-model:text="TX.Category" v-model:id="TX.CategoryID" model="categories" />
|
<Autocomplete v-model:text="TX.Payee" v-model:id="TX.PayeeID" v-model:type="payeeType" model="payees" />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<input class="block w-full border-b-2 border-black" type="text" v-model="TX.Memo" />
|
<Autocomplete v-model:text="TX.Category" v-model:id="TX.CategoryID" model="categories" />
|
||||||
</td>
|
</td>
|
||||||
<td style="width: 80px;" class="text-right">
|
<td>
|
||||||
<input
|
<Input v-model="TX.Memo" class="block w-full border-b-2 border-black" type="text" />
|
||||||
class="text-right block w-full border-b-2 border-black"
|
</td>
|
||||||
type="currency"
|
<td class="text-right">
|
||||||
v-model="TX.Amount"
|
<Input v-model="TX.Amount" class="text-right block w-full border-b-2 border-black" type="currency" />
|
||||||
/>
|
</td>
|
||||||
</td>
|
<td>
|
||||||
<td style="width: 20px;">
|
<Button class="bg-blue-500" @click="saveTransaction">
|
||||||
<input type="submit" @click="saveTransaction" value="Save" />
|
Save
|
||||||
</td>
|
</Button>
|
||||||
<td style="width: 20px;"></td>
|
</td>
|
||||||
</tr>
|
<td />
|
||||||
</template>
|
</tr>
|
||||||
|
</template>
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, ref } from "vue";
|
import { computed, ref } from "vue";
|
||||||
import Autocomplete, { Suggestion } from '../components/Autocomplete.vue'
|
import Autocomplete from '../components/Autocomplete.vue'
|
||||||
import { Transaction, useAccountStore } from '../stores/budget-account'
|
import { Transaction, useTransactionsStore } from "../stores/transactions";
|
||||||
import DateInput from "./DateInput.vue";
|
import DateInput from "./DateInput.vue";
|
||||||
|
import Button from "./SimpleButton.vue";
|
||||||
|
import Input from "./Input.vue";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
budgetid: string
|
budgetid: string
|
||||||
@ -22,6 +24,9 @@ const TX = ref<Transaction>({
|
|||||||
ID: "",
|
ID: "",
|
||||||
Status: "Uncleared",
|
Status: "Uncleared",
|
||||||
TransferAccount: "",
|
TransferAccount: "",
|
||||||
|
Reconciled: false,
|
||||||
|
Account: "",
|
||||||
|
AccountID: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
const payeeType = ref<string|undefined>(undefined);
|
const payeeType = ref<string|undefined>(undefined);
|
||||||
@ -41,37 +46,68 @@ const payload = computed(() => JSON.stringify({
|
|||||||
state: "Uncleared"
|
state: "Uncleared"
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const accountStore = useAccountStore();
|
const transactionsStore = useTransactionsStore();
|
||||||
function saveTransaction(e: MouseEvent) {
|
function saveTransaction(e: MouseEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
accountStore.saveTransaction(payload.value);
|
Save();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Save() {
|
||||||
|
transactionsStore.saveTransaction(payload.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({Save});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<tr>
|
<tr>
|
||||||
<td style="width: 90px;" class="text-sm">
|
<label class="md:hidden">Date</label>
|
||||||
<DateInput class="border-b-2 border-black" v-model="TX.Date" />
|
<td class="text-sm">
|
||||||
</td>
|
<DateInput
|
||||||
<td style="max-width: 150px;">
|
v-model="TX.Date"
|
||||||
<Autocomplete v-model:text="TX.Payee" v-model:id="TX.PayeeID" v-model:type="payeeType" model="payees" />
|
class="block w-full border-b-2 border-black"
|
||||||
</td>
|
/>
|
||||||
<td style="max-width: 200px;">
|
</td>
|
||||||
<Autocomplete v-model:text="TX.Category" v-model:id="TX.CategoryID" model="categories" />
|
<label class="md:hidden">Payee</label>
|
||||||
</td>
|
<td>
|
||||||
<td>
|
<Autocomplete
|
||||||
<input class="block w-full border-b-2 border-black" type="text" v-model="TX.Memo" />
|
v-model:text="TX.Payee"
|
||||||
</td>
|
v-model:id="TX.PayeeID"
|
||||||
<td style="width: 80px;" class="text-right">
|
v-model:type="payeeType"
|
||||||
<input
|
model="payees"
|
||||||
class="text-right block w-full border-b-2 border-black"
|
/>
|
||||||
type="currency"
|
</td>
|
||||||
v-model="TX.Amount"
|
<label class="md:hidden">Category</label>
|
||||||
/>
|
<td>
|
||||||
</td>
|
<Autocomplete
|
||||||
<td style="width: 20px;">
|
v-model:text="TX.Category"
|
||||||
<input type="submit" @click="saveTransaction" value="Save" />
|
v-model:id="TX.CategoryID"
|
||||||
</td>
|
model="categories"
|
||||||
<td style="width: 20px;"></td>
|
/>
|
||||||
</tr>
|
</td>
|
||||||
</template>
|
<label class="md:hidden">Memo</label>
|
||||||
|
<td class="col-span-2">
|
||||||
|
<Input
|
||||||
|
v-model="TX.Memo"
|
||||||
|
class="block w-full border-b-2 border-black"
|
||||||
|
type="text"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<label class="md:hidden">Amount</label>
|
||||||
|
<td class="text-right">
|
||||||
|
<Input
|
||||||
|
v-model="TX.Amount"
|
||||||
|
class="text-right block w-full border-b-2 border-black"
|
||||||
|
type="currency"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td class="hidden md:table-cell">
|
||||||
|
<Button
|
||||||
|
class="bg-blue-500"
|
||||||
|
@click="saveTransaction"
|
||||||
|
>
|
||||||
|
Save
|
||||||
|
</Button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</template>
|
||||||
|
@ -1,44 +1,83 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, ref } from "vue";
|
import { computed, ref } from "vue";
|
||||||
import { useBudgetsStore } from "../stores/budget";
|
import { useBudgetsStore } from "../stores/budget";
|
||||||
import { Transaction } from "../stores/budget-account";
|
import { useTransactionsStore } from "../stores/transactions";
|
||||||
import Currency from "./Currency.vue";
|
import Currency from "./Currency.vue";
|
||||||
import TransactionEditRow from "./TransactionEditRow.vue";
|
import TransactionEditRow from "./TransactionEditRow.vue";
|
||||||
import { formatDate } from "../date";
|
import { formatDate } from "../date";
|
||||||
|
import { useAccountStore } from "../stores/budget-account";
|
||||||
|
import Checkbox from "./Checkbox.vue";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
transaction: Transaction,
|
transactionid: string,
|
||||||
index: number,
|
index: number,
|
||||||
|
withAccount: boolean,
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const edit = ref(false);
|
const edit = ref(false);
|
||||||
|
|
||||||
const CurrentBudgetID = computed(()=> useBudgetsStore().CurrentBudgetID);
|
const CurrentBudgetID = computed(() => useBudgetsStore().CurrentBudgetID);
|
||||||
|
const Reconciling = computed(() => useTransactionsStore().Reconciling);
|
||||||
|
|
||||||
|
const transactionsStore = useTransactionsStore();
|
||||||
|
const TX = transactionsStore.Transactions.get(props.transactionid)!;
|
||||||
|
|
||||||
|
function getStatusSymbol() {
|
||||||
|
if(TX.Status == "Reconciled")
|
||||||
|
return "✔";
|
||||||
|
|
||||||
|
if(TX.Status == "Uncleared")
|
||||||
|
return "*";
|
||||||
|
|
||||||
|
return "✘";
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<tr v-if="!edit" class="{{new Date(transaction.Date) > new Date() ? 'future' : ''}}"
|
<tr
|
||||||
:class="[index % 6 < 3 ? 'bg-gray-300' : 'bg-gray-100']">
|
v-if="!edit"
|
||||||
<!--:class="[index % 6 < 3 ? index % 6 === 1 ? 'bg-gray-400' : 'bg-gray-300' : index % 6 !== 4 ? 'bg-gray-100' : '']">-->
|
class="{{new Date(TX.Date) > new Date() ? 'future' : ''}}"
|
||||||
<td>{{ formatDate(transaction.Date) }}</td>
|
:class="[index % 2 < 1 ? 'md:bg-gray-300 dark:md:bg-gray-700' : 'md:bg-gray-100 dark:md:bg-gray-900']"
|
||||||
<td>{{ transaction.TransferAccount ? "Transfer : " + transaction.TransferAccount : transaction.Payee }}</td>
|
>
|
||||||
<td>
|
<td class="hidden md:block">
|
||||||
{{ transaction.CategoryGroup ? transaction.CategoryGroup + " : " + transaction.Category : "" }}
|
{{ formatDate(TX.Date) }}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td v-if="withAccount" class="pl-2 md:pl-0">
|
||||||
<a :href="'/budget/' + CurrentBudgetID + '/transaction/' + transaction.ID">
|
{{ TX.Account }}
|
||||||
{{ transaction.Memo }}
|
</td>
|
||||||
</a>
|
<td class="pl-2 md:pl-0">
|
||||||
</td>
|
{{ TX.TransferAccount ? "Transfer : " + TX.TransferAccount : TX.Payee }}
|
||||||
<td>
|
</td>
|
||||||
<Currency class="block" :value="transaction.Amount" />
|
<td>
|
||||||
</td>
|
{{ TX.CategoryGroup ? TX.CategoryGroup + " : " + TX.Category : "" }}
|
||||||
<td>
|
</td>
|
||||||
{{ transaction.Status == "Reconciled" ? "✔" : (transaction.Status == "Uncleared" ? "" : "*") }}
|
<td>
|
||||||
</td>
|
<a
|
||||||
<td class="text-right">{{ transaction.GroupID ? "☀" : "" }}<a @click="edit = true;">✎</a></td>
|
:href="'/budget/' + CurrentBudgetID + '/transaction/' + TX.ID"
|
||||||
</tr>
|
>{{ TX.Memo }}</a>
|
||||||
<TransactionEditRow v-if="edit" :transactionid="transaction.ID" />
|
</td>
|
||||||
|
<td>
|
||||||
|
<Currency
|
||||||
|
class="block"
|
||||||
|
:value="TX.Amount"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td class="text-right">
|
||||||
|
{{ TX.GroupID ? "☀" : "" }}
|
||||||
|
{{ getStatusSymbol() }}
|
||||||
|
<a @click="edit = true;">✎</a>
|
||||||
|
<Checkbox
|
||||||
|
v-if="Reconciling && TX.Status != 'Reconciled'"
|
||||||
|
v-model="TX.Reconciled"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<TransactionEditRow
|
||||||
|
v-if="edit"
|
||||||
|
:transactionid="TX.ID"
|
||||||
|
:with-account="withAccount"
|
||||||
|
@save="edit = false"
|
||||||
|
/>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
@ -46,4 +85,4 @@ td {
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
@ -1,7 +1,17 @@
|
|||||||
export function formatDate(date: Date): string {
|
export function formatDate(date: Date): string {
|
||||||
return date.toLocaleDateString(undefined, { // you can use undefined as first argument
|
return date.toLocaleDateString(undefined, {
|
||||||
|
// you can use undefined as first argument
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
month: "2-digit",
|
month: "2-digit",
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupBy<T, K extends keyof any>(list: T[], getKey: (item: T) => K) {
|
||||||
|
return list.reduce((previous, currentItem) => {
|
||||||
|
const group = getKey(currentItem);
|
||||||
|
if (!previous[group]) previous[group] = [];
|
||||||
|
previous[group].push(currentItem);
|
||||||
|
return previous;
|
||||||
|
}, {} as Record<K, T[]>);
|
||||||
}
|
}
|
@ -2,43 +2,84 @@
|
|||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import Modal from '../components/Modal.vue';
|
import Modal from '../components/Modal.vue';
|
||||||
import { useAccountStore } from '../stores/budget-account';
|
import { useAccountStore } from '../stores/budget-account';
|
||||||
|
import Input from '../components/Input.vue';
|
||||||
|
import Checkbox from '../components/Checkbox.vue';
|
||||||
|
import { useRouter } from 'vue-router';
|
||||||
|
import { useBudgetsStore } from '../stores/budget';
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
const accountStore = useAccountStore();
|
const accountStore = useAccountStore();
|
||||||
const CurrentAccount = computed(() => accountStore.CurrentAccount);
|
const CurrentAccount = computed(() => accountStore.CurrentAccount);
|
||||||
|
|
||||||
const accountName = ref("");
|
const accountName = ref("");
|
||||||
const accountOnBudget = ref(true);
|
const accountOnBudget = ref(true);
|
||||||
|
const accountOpen = ref(true);
|
||||||
|
const error = ref("");
|
||||||
|
|
||||||
function editAccount(e : any) {
|
function editAccount(e : {cancel:boolean}) : boolean {
|
||||||
accountStore.EditAccount(CurrentAccount.value?.ID ?? "", accountName.value, accountOnBudget.value);
|
if(CurrentAccount.value?.ClearedBalance != 0 && !accountOpen.value){
|
||||||
|
e.cancel = true;
|
||||||
|
error.value = "Cannot close account with balance";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
error.value = "";
|
||||||
|
accountStore.EditAccount(CurrentAccount.value?.ID ?? "", accountName.value, accountOnBudget.value, accountOpen.value);
|
||||||
|
|
||||||
|
// account closed, move to Budget
|
||||||
|
if(!accountOpen.value){
|
||||||
|
const currentBudgetID = useBudgetsStore().CurrentBudgetID;
|
||||||
|
router.replace('/budget/'+currentBudgetID+'/budgeting');
|
||||||
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEditAccount(e : any) {
|
function openEditAccount(e : any) {
|
||||||
accountName.value = CurrentAccount.value?.Name ?? "";
|
accountName.value = CurrentAccount.value?.Name ?? "";
|
||||||
accountOnBudget.value = CurrentAccount.value?.OnBudget ?? true;
|
accountOnBudget.value = CurrentAccount.value?.OnBudget ?? true;
|
||||||
|
accountOpen.value = CurrentAccount.value?.IsOpen ?? true;
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Modal button-text="Edit Account" @open="openEditAccount" @submit="editAccount">
|
<Modal
|
||||||
<template v-slot:placeholder>✎</template>
|
button-text="Edit Account"
|
||||||
<div class="mt-2 px-7 py-3">
|
@open="openEditAccount"
|
||||||
<input
|
@submit="editAccount"
|
||||||
class="border-2"
|
>
|
||||||
type="text"
|
<template #placeholder>
|
||||||
v-model="accountName"
|
<span class="ml-2">✎</span>
|
||||||
placeholder="Account name"
|
</template>
|
||||||
required
|
<div class="mt-2 px-7 py-3">
|
||||||
/>
|
<Input
|
||||||
</div>
|
v-model="accountName"
|
||||||
<div class="mt-2 px-7 py-3">
|
class="border-2 dark:border-gray-700"
|
||||||
<input
|
type="text"
|
||||||
class="border-2"
|
placeholder="Account name"
|
||||||
type="checkbox"
|
required
|
||||||
v-model="accountOnBudget"
|
/>
|
||||||
required
|
</div>
|
||||||
/>
|
<div class="mt-2 px-7 py-3">
|
||||||
<label>On Budget</label>
|
<Checkbox
|
||||||
</div>
|
v-model="accountOnBudget"
|
||||||
</Modal>
|
class="border-2"
|
||||||
</template>
|
required
|
||||||
|
/>
|
||||||
|
<label>On Budget</label>
|
||||||
|
</div>
|
||||||
|
<div class="mt-2 px-7 py-3">
|
||||||
|
<Checkbox
|
||||||
|
v-model="accountOpen"
|
||||||
|
class="border-2"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<label>Open</label>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="error != ''"
|
||||||
|
class="dark:text-red-300 text-red-700"
|
||||||
|
>
|
||||||
|
{{ error }}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</template>
|
||||||
|
@ -2,6 +2,7 @@
|
|||||||
import Modal from '../components/Modal.vue';
|
import Modal from '../components/Modal.vue';
|
||||||
import { ref } from "vue";
|
import { ref } from "vue";
|
||||||
import { useBudgetsStore } from '../stores/budget';
|
import { useBudgetsStore } from '../stores/budget';
|
||||||
|
import Input from '../components/Input.vue';
|
||||||
|
|
||||||
const budgetName = ref("");
|
const budgetName = ref("");
|
||||||
function saveBudget() {
|
function saveBudget() {
|
||||||
@ -10,9 +11,18 @@ function saveBudget() {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Modal button-text="New Budget" @submit="saveBudget">
|
<Modal
|
||||||
|
button-text="New Budget"
|
||||||
|
@submit="saveBudget"
|
||||||
|
>
|
||||||
<div class="mt-2 px-7 py-3">
|
<div class="mt-2 px-7 py-3">
|
||||||
<input class="border-2" type="text" v-model="budgetName" placeholder="Budget name" required />
|
<Input
|
||||||
|
v-model="budgetName"
|
||||||
|
class="border-2"
|
||||||
|
type="text"
|
||||||
|
placeholder="Budget name"
|
||||||
|
required
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
</template>
|
</template>
|
||||||
|
@ -3,9 +3,15 @@
|
|||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
|
||||||
h1 {
|
h1 {
|
||||||
font-size: 200%;
|
font-size: 200%;
|
||||||
}
|
}
|
||||||
|
|
||||||
a {
|
a {
|
||||||
text-decoration: underline;
|
text-decoration: underline;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#app {
|
||||||
|
font-family: Avenir, Helvetica, Arial, sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
@ -1,25 +1,79 @@
|
|||||||
import { createApp } from 'vue'
|
import { createApp } from "vue";
|
||||||
import App from './App.vue'
|
import App from "./App.vue";
|
||||||
import './index.css'
|
import "./index.css";
|
||||||
import router from './router'
|
import router from "./router";
|
||||||
import { createPinia } from 'pinia'
|
import { createPinia } from "pinia";
|
||||||
import { useBudgetsStore } from './stores/budget';
|
import { useBudgetsStore } from "./stores/budget";
|
||||||
import { useAccountStore } from './stores/budget-account'
|
import { useAccountStore } from "./stores/budget-account";
|
||||||
import PiniaLogger from './pinia-logger'
|
import PiniaLogger from "./pinia-logger";
|
||||||
|
import { useSessionStore } from "./stores/session";
|
||||||
|
|
||||||
const app = createApp(App)
|
const app = createApp(App);
|
||||||
app.use(router)
|
app.use(router);
|
||||||
|
|
||||||
const pinia = createPinia()
|
const pinia = createPinia();
|
||||||
pinia.use(PiniaLogger())
|
pinia.use(
|
||||||
app.use(pinia)
|
PiniaLogger({
|
||||||
app.mount('#app')
|
expanded: false,
|
||||||
|
showDuration: true,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
app.use(pinia);
|
||||||
|
app.mount("#app");
|
||||||
|
|
||||||
router.beforeEach(async (to, from, next) => {
|
router.beforeEach(async (to, from, next) => {
|
||||||
const budgetStore = useBudgetsStore();
|
const budgetStore = useBudgetsStore();
|
||||||
await budgetStore.SetCurrentBudget((<string>to.params.budgetid));
|
await budgetStore.SetCurrentBudget(<string>to.params.budgetid);
|
||||||
|
|
||||||
const accountStore = useAccountStore();
|
const accountStore = useAccountStore();
|
||||||
await accountStore.SetCurrentAccount((<string>to.params.budgetid), (<string>to.params.accountid));
|
await accountStore.SetCurrentAccount(
|
||||||
next();
|
<string>to.params.budgetid,
|
||||||
})
|
<string>to.params.accountid
|
||||||
|
);
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
router.beforeEach((to, from, next) => {
|
||||||
|
const sessionStore = useSessionStore();
|
||||||
|
const token = sessionStore.Session?.Token;
|
||||||
|
let loggedIn = false;
|
||||||
|
|
||||||
|
if (token != null) {
|
||||||
|
const jwt = parseJwt(token);
|
||||||
|
if (jwt.exp > Date.now() / 1000) loggedIn = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (to.matched.some((record) => record.meta.requiresAuth)) {
|
||||||
|
if (!loggedIn) {
|
||||||
|
next({ path: "/login" });
|
||||||
|
} else {
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
} else if (to.matched.some((record) => record.meta.hideForAuth)) {
|
||||||
|
if (loggedIn) {
|
||||||
|
next({ path: "/dashboard" });
|
||||||
|
} else {
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function parseJwt(token: string) {
|
||||||
|
var base64Url = token.split(".")[1];
|
||||||
|
var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
|
||||||
|
var jsonPayload = decodeURIComponent(
|
||||||
|
atob(base64)
|
||||||
|
.split("")
|
||||||
|
.map(function (c) {
|
||||||
|
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
|
||||||
|
})
|
||||||
|
.join("")
|
||||||
|
);
|
||||||
|
|
||||||
|
return JSON.parse(jsonPayload);
|
||||||
|
}
|
||||||
|
|
||||||
|
1646426130;
|
||||||
|
1646512855755;
|
||||||
|
@ -5,43 +5,166 @@ import TransactionRow from "../components/TransactionRow.vue";
|
|||||||
import TransactionInputRow from "../components/TransactionInputRow.vue";
|
import TransactionInputRow from "../components/TransactionInputRow.vue";
|
||||||
import { useAccountStore } from "../stores/budget-account";
|
import { useAccountStore } from "../stores/budget-account";
|
||||||
import EditAccount from "../dialogs/EditAccount.vue";
|
import EditAccount from "../dialogs/EditAccount.vue";
|
||||||
|
import Button from "../components/SimpleButton.vue";
|
||||||
|
import { useTransactionsStore } from "../stores/transactions";
|
||||||
|
import Modal from "../components/Modal.vue";
|
||||||
|
import Input from "../components/Input.vue";
|
||||||
|
import Checkbox from "../components/Checkbox.vue";
|
||||||
|
import { formatDate } from "../date";
|
||||||
|
|
||||||
const props = defineProps<{
|
defineProps<{
|
||||||
budgetid: string
|
budgetid: string
|
||||||
accountid: string
|
accountid: string
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const accountStore = useAccountStore();
|
const modalInputRow = ref<typeof TransactionInputRow | null>(null);
|
||||||
const CurrentAccount = computed(() => accountStore.CurrentAccount);
|
|
||||||
const TransactionsList = computed(() => accountStore.TransactionsList);
|
|
||||||
|
|
||||||
|
function submitModal() {
|
||||||
|
modalInputRow.value!.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
const accounts = useAccountStore();
|
||||||
|
const transactions = useTransactionsStore();
|
||||||
|
const TargetReconcilingBalance = ref(0);
|
||||||
|
|
||||||
|
function setReconciled(event: Event) {
|
||||||
|
const target = event.target as HTMLInputElement;
|
||||||
|
transactions.SetReconciledForAllTransactions(target.checked);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelReconcilation() {
|
||||||
|
transactions.SetReconciledForAllTransactions(false);
|
||||||
|
transactions.Reconciling = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitReconcilation() {
|
||||||
|
transactions.SubmitReconcilation(0);
|
||||||
|
transactions.Reconciling = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createReconcilationTransaction() {
|
||||||
|
const diff = TargetReconcilingBalance.value - transactions.ReconcilingBalance;
|
||||||
|
transactions.SubmitReconcilation(diff);
|
||||||
|
transactions.Reconciling = false;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<h1 class="inline">{{ CurrentAccount?.Name }}</h1>
|
<div class="grid grid-cols-[1fr_auto]">
|
||||||
<EditAccount />
|
<div>
|
||||||
|
<h1 class="inline">
|
||||||
|
{{ accounts.CurrentAccount?.Name }}
|
||||||
|
</h1>
|
||||||
|
<EditAccount />
|
||||||
|
</div>
|
||||||
|
|
||||||
<p>
|
<div
|
||||||
Current Balance:
|
class="text-right flex flex-wrap flex-col md:flex-row justify-end gap-2 max-w-sm"
|
||||||
<Currency :value="CurrentAccount?.Balance" />
|
>
|
||||||
</p>
|
<span class="rounded-lg p-1 whitespace-nowrap flex-1">
|
||||||
<table>
|
Working:
|
||||||
<tr class="font-bold">
|
<Currency :value="accounts.CurrentAccount?.WorkingBalance" />
|
||||||
<td style="width: 90px;">Date</td>
|
</span>
|
||||||
<td style="max-width: 150px;">Payee</td>
|
|
||||||
<td style="max-width: 200px;">Category</td>
|
<span class="rounded-lg p-1 whitespace-nowrap flex-1">
|
||||||
<td>Memo</td>
|
Cleared:
|
||||||
<td class="text-right">Amount</td>
|
<Currency :value="accounts.CurrentAccount?.ClearedBalance" />
|
||||||
<td style="width: 20px;"></td>
|
</span>
|
||||||
<td style="width: 40px;"></td>
|
|
||||||
</tr>
|
<span
|
||||||
<TransactionInputRow :budgetid="budgetid" :accountid="accountid" />
|
v-if="!transactions.Reconciling"
|
||||||
<TransactionRow
|
class="rounded-lg bg-blue-500 p-1 whitespace-nowrap flex-1"
|
||||||
v-for="(transaction, index) in TransactionsList"
|
@click="transactions.Reconciling = true"
|
||||||
:transaction="transaction"
|
>
|
||||||
:index="index"
|
Reconciled:
|
||||||
/>
|
<Currency :value="accounts.CurrentAccount?.ReconciledBalance" />
|
||||||
</table>
|
</span>
|
||||||
|
|
||||||
|
<span
|
||||||
|
v-if="transactions.Reconciling"
|
||||||
|
class="contents"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
class="bg-blue-500 p-1 whitespace-nowrap flex-1"
|
||||||
|
@click="submitReconcilation"
|
||||||
|
>
|
||||||
|
My current balance is
|
||||||
|
<Currency :value="transactions.ReconcilingBalance" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
class="bg-orange-500 p-1 whitespace-nowrap flex-1"
|
||||||
|
@click="createReconcilationTransaction"
|
||||||
|
>
|
||||||
|
No, it's:
|
||||||
|
<Input
|
||||||
|
v-model="TargetReconcilingBalance"
|
||||||
|
class="text-right w-20 bg-transparent dark:bg-transparent border-b-2"
|
||||||
|
type="number"
|
||||||
|
/>
|
||||||
|
(Difference
|
||||||
|
<Currency
|
||||||
|
:value="transactions.ReconcilingBalance - TargetReconcilingBalance"
|
||||||
|
/>)
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
class="bg-red-500 p-1 flex-1"
|
||||||
|
@click="cancelReconcilation"
|
||||||
|
>Cancel</Button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr class="font-bold">
|
||||||
|
<td class="hidden md:block" style="width: 90px;">Date</td>
|
||||||
|
<td style="max-width: 150px;">Payee</td>
|
||||||
|
<td style="max-width: 200px;">Category</td>
|
||||||
|
<td>Memo</td>
|
||||||
|
<td class="text-right">Amount</td>
|
||||||
|
<td style="width: 80px;">
|
||||||
|
<Checkbox v-if="transactions.Reconciling" @input="setReconciled" />
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<TransactionInputRow
|
||||||
|
class="hidden md:table-row"
|
||||||
|
:budgetid="budgetid"
|
||||||
|
:accountid="accountid"
|
||||||
|
/>
|
||||||
|
<template v-for="(dayTransactions, key, index) in transactions.TransactionsByDate" :key="key">
|
||||||
|
<tr class="table-row md:hidden">
|
||||||
|
<td class="py-2" colspan="5">
|
||||||
|
<span class="bg-gray-400 dark:bg-slate-600 rounded-lg p-1 px-2 w-full block">
|
||||||
|
{{ key }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<TransactionRow
|
||||||
|
v-for="transaction in dayTransactions"
|
||||||
|
:key="transaction.ID"
|
||||||
|
:index="index"
|
||||||
|
:transactionid="transaction.ID"
|
||||||
|
:with-account="false"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</table>
|
||||||
|
<div class="md:hidden">
|
||||||
|
<Modal @submit="submitModal">
|
||||||
|
<template #placeholder>
|
||||||
|
<Button
|
||||||
|
class="fixed right-4 bottom-4 font-bold text-lg bg-blue-500 py-2"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
<TransactionInputRow
|
||||||
|
ref="modalInputRow"
|
||||||
|
class="flex flex-col w-full h-full top-0"
|
||||||
|
:budgetid="budgetid"
|
||||||
|
:accountid="accountid"
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
@ -52,4 +175,4 @@ table {
|
|||||||
.negative {
|
.negative {
|
||||||
color: red;
|
color: red;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
@ -8,9 +8,9 @@ onMounted(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<h1>Danger Zone</h1>
|
<h1>Danger Zone</h1>
|
||||||
<div class="budget-item">
|
<div class="budget-item">
|
||||||
<button>Clear database</button>
|
<button>Clear database</button>
|
||||||
<p>This removes all data and starts from scratch. Not undoable!</p>
|
<p>This removes all data and starts from scratch. Not undoable!</p>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
125
web/src/pages/AllAccounts.vue
Normal file
125
web/src/pages/AllAccounts.vue
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import { computed, ref, onMounted, watch } from "vue"
|
||||||
|
import Currency from "../components/Currency.vue";
|
||||||
|
import TransactionRow from "../components/TransactionRow.vue";
|
||||||
|
import TransactionInputRow from "../components/TransactionInputRow.vue";
|
||||||
|
import { useAccountStore } from "../stores/budget-account";
|
||||||
|
import EditAccount from "../dialogs/EditAccount.vue";
|
||||||
|
import Button from "../components/SimpleButton.vue";
|
||||||
|
import { useTransactionsStore } from "../stores/transactions";
|
||||||
|
import Modal from "../components/Modal.vue";
|
||||||
|
import Input from "../components/Input.vue";
|
||||||
|
import Checkbox from "../components/Checkbox.vue";
|
||||||
|
import { formatDate } from "../date";
|
||||||
|
import DateInput from "../components/DateInput.vue";
|
||||||
|
import Autocomplete from '../components/Autocomplete.vue'
|
||||||
|
|
||||||
|
defineProps<{
|
||||||
|
budgetid: string
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const modalInputRow = ref<typeof TransactionInputRow | null>(null);
|
||||||
|
|
||||||
|
function submitModal() {
|
||||||
|
modalInputRow.value!.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
const accounts = useAccountStore();
|
||||||
|
const transactions = useTransactionsStore();
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
transactions.GetProblematicTransactions();
|
||||||
|
})
|
||||||
|
|
||||||
|
const filters = ref({
|
||||||
|
Account: null,
|
||||||
|
AccountID: null,
|
||||||
|
Payee: null,
|
||||||
|
PayeeID: null,
|
||||||
|
Category: null,
|
||||||
|
CategoryID: null,
|
||||||
|
FromDate: new Date(1900, 0, 2, 0, 0, 0),
|
||||||
|
ToDate: new Date(2999,11,32,0,0,0),
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(() => filters.value.AccountID
|
||||||
|
+ filters.value.PayeeID
|
||||||
|
+ filters.value.CategoryID
|
||||||
|
+ filters.value.FromDate?.toISOString()
|
||||||
|
+ filters.value.ToDate?.toISOString(), function() {
|
||||||
|
console.log(filters.value.FromDate)
|
||||||
|
if(!hasFilters.value)
|
||||||
|
return;
|
||||||
|
transactions.GetFilteredTransactions(
|
||||||
|
filters.value.AccountID,
|
||||||
|
filters.value.CategoryID,
|
||||||
|
filters.value.PayeeID,
|
||||||
|
filters.value.FromDate?.toISOString(),
|
||||||
|
filters.value.ToDate?.toISOString(),
|
||||||
|
);
|
||||||
|
})
|
||||||
|
|
||||||
|
const hasFilters = computed(() =>
|
||||||
|
filters.value.AccountID != null
|
||||||
|
|| filters.value.PayeeID != null
|
||||||
|
|| filters.value.CategoryID != null
|
||||||
|
|| (filters.value.FromDate != null && filters.value.FromDate.getYear() > 1900)
|
||||||
|
|| (filters.value.ToDate != null && filters.value.ToDate.getYear() < 2999))
|
||||||
|
const transactionsList = computed(() => {
|
||||||
|
if (hasFilters.value){
|
||||||
|
return transactions.FilteredTransactionsList;
|
||||||
|
}
|
||||||
|
return transactions.ProblematicTransactionsList;
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="grid grid-cols-[1fr_auto]">
|
||||||
|
<div>
|
||||||
|
<h1 class="inline">
|
||||||
|
{{ hasFilters ? "Filtered" : "Problematic" }} Transactions
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-2 w-96">
|
||||||
|
Account:
|
||||||
|
<Autocomplete v-model:text="filters.Account" v-model:id="filters.AccountID" model="accounts" class="inline-block" /><br>
|
||||||
|
Payee:
|
||||||
|
<Autocomplete v-model:text="filters.Payee" v-model:id="filters.PayeeID" model="payees" class="inline-block" /><br>
|
||||||
|
Category:
|
||||||
|
<Autocomplete v-model:text="filters.Category" v-model:id="filters.CategoryID" model="categories" class="inline-block" /><br>
|
||||||
|
From Date:
|
||||||
|
<DateInput v-model="filters.FromDate" class="inline-block" /><br>
|
||||||
|
To Date:
|
||||||
|
<DateInput v-model="filters.ToDate" class="inline-block" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr class="font-bold">
|
||||||
|
<td class="hidden md:block" style="width: 90px;">Date</td>
|
||||||
|
<td style="max-width: 200px;">Account</td>
|
||||||
|
<td style="max-width: 150px;">Payee</td>
|
||||||
|
<td style="max-width: 200px;">Category</td>
|
||||||
|
<td>Memo</td>
|
||||||
|
<td class="text-right">Amount</td>
|
||||||
|
</tr>
|
||||||
|
<TransactionRow
|
||||||
|
v-for="(transaction, index) in transactionsList"
|
||||||
|
:key="transaction.ID"
|
||||||
|
:with-account="true"
|
||||||
|
:transactionid="transaction.ID"
|
||||||
|
:index="index"
|
||||||
|
/>
|
||||||
|
</table>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
table-layout: fixed;
|
||||||
|
}
|
||||||
|
.negative {
|
||||||
|
color: red;
|
||||||
|
}
|
||||||
|
</style>
|
@ -1,11 +1,14 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed } from "vue";
|
import { computed } from "vue";
|
||||||
import Currency from "../components/Currency.vue"
|
import Currency from "../components/Currency.vue";
|
||||||
import { useBudgetsStore } from "../stores/budget"
|
import { useBudgetsStore } from "../stores/budget";
|
||||||
import { useAccountStore } from "../stores/budget-account"
|
import { Account, useAccountStore } from "../stores/budget-account";
|
||||||
import { useSettingsStore } from "../stores/settings"
|
import { useSettingsStore } from "../stores/settings";
|
||||||
|
import AccountWithReconciled from "../components/AccountWithReconciled.vue";
|
||||||
|
|
||||||
const ExpandMenu = computed(() => useSettingsStore().Menu.Expand);
|
const settings = useSettingsStore();
|
||||||
|
const ExpandMenu = computed(() => settings.Menu.Expand);
|
||||||
|
const ShowMenu = computed(() => settings.Menu.Show);
|
||||||
|
|
||||||
const budgetStore = useBudgetsStore();
|
const budgetStore = useBudgetsStore();
|
||||||
const CurrentBudgetName = computed(() => budgetStore.CurrentBudgetName);
|
const CurrentBudgetName = computed(() => budgetStore.CurrentBudgetName);
|
||||||
@ -16,51 +19,66 @@ const OnBudgetAccounts = computed(() => accountStore.OnBudgetAccounts);
|
|||||||
const OffBudgetAccounts = computed(() => accountStore.OffBudgetAccounts);
|
const OffBudgetAccounts = computed(() => accountStore.OffBudgetAccounts);
|
||||||
const OnBudgetAccountsBalance = computed(() => accountStore.OnBudgetAccountsBalance);
|
const OnBudgetAccountsBalance = computed(() => accountStore.OnBudgetAccountsBalance);
|
||||||
const OffBudgetAccountsBalance = computed(() => accountStore.OffBudgetAccountsBalance);
|
const OffBudgetAccountsBalance = computed(() => accountStore.OffBudgetAccountsBalance);
|
||||||
|
|
||||||
|
function toggleMenu() {
|
||||||
|
useSettingsStore().toggleMenu();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col">
|
<div :class="[ExpandMenu ? 'md:w-72' : 'md:w-36', ShowMenu ? '' : 'hidden']"
|
||||||
<span class="m-1 p-1 px-3 text-xl">
|
class="md:block flex-shrink-0 w-full bg-gray-500 border-r-4 border-black">
|
||||||
<router-link to="/dashboard">⌂</router-link>
|
<div class="flex flex-col">
|
||||||
{{CurrentBudgetName}}
|
<div class="m-2 md:px-3 p-1">
|
||||||
</span>
|
<span class="font-bold-my-3 md:hidden font-bold text-5xl pr-3" @click="toggleMenu">≡</span>
|
||||||
<span class="bg-orange-200 rounded-lg m-1 p-1 px-3 flex flex-col">
|
<span class="h-10 overflow-hidden" :class="[ExpandMenu ? 'text-2xl' : 'text-md']">
|
||||||
<router-link :to="'/budget/'+CurrentBudgetID+'/budgeting'">Budget</router-link><br />
|
<router-link to="/dashboard" class="text-5xl">⌂</router-link>
|
||||||
<!--<router-link :to="'/budget/'+CurrentBudgetID+'/reports'">Reports</router-link>-->
|
{{ CurrentBudgetName }}
|
||||||
<!--<router-link :to="'/budget/'+CurrentBudgetID+'/all-accounts'">All Accounts</router-link>-->
|
</span>
|
||||||
</span>
|
</div>
|
||||||
<li class="bg-orange-200 rounded-lg m-1 p-1 px-3">
|
<span class="bg-gray-100 dark:bg-gray-700 p-2 px-3 flex flex-col">
|
||||||
|
<router-link :to="'/budget/' + CurrentBudgetID + '/budgeting'">Budget</router-link>
|
||||||
|
<br>
|
||||||
|
<!--<router-link :to="'/budget/'+CurrentBudgetID+'/reports'">Reports</router-link>-->
|
||||||
|
<router-link :to="'/budget/'+CurrentBudgetID+'/problematic-transactions'">Transactions</router-link>
|
||||||
|
</span>
|
||||||
|
<li class="bg-slate-200 dark:bg-slate-700 my-2 p-2 px-3">
|
||||||
|
<div class="flex flex-row justify-between font-bold">
|
||||||
|
<span>On-Budget Accounts</span>
|
||||||
|
<Currency :class="ExpandMenu ? 'md:inline' : 'md:hidden'" class="whitespace-nowrap" :value="OnBudgetAccountsBalance" />
|
||||||
|
</div>
|
||||||
|
<div v-for="account in OnBudgetAccounts" :key="account.ID" class="flex flex-row justify-between">
|
||||||
|
<AccountWithReconciled class="whitespace-nowrap overflow-hidden mr-4" :account="account" />
|
||||||
|
<Currency :class="ExpandMenu ? 'md:inline' : 'md:hidden'" class="whitespace-nowrap" :value="account.ClearedBalance" />
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li class="bg-slate-200 dark:bg-slate-700 my-2 p-2 px-3">
|
||||||
|
<div class="flex flex-row justify-between font-bold">
|
||||||
|
<span>Off-Budget Accounts</span>
|
||||||
|
<Currency :class="ExpandMenu ? 'md:inline' : 'md:hidden'" class="whitespace-nowrap" :value="OffBudgetAccountsBalance" />
|
||||||
|
</div>
|
||||||
|
<div v-for="account in OffBudgetAccounts" :key="account.ID" class="flex flex-row justify-between">
|
||||||
|
<AccountWithReconciled class="whitespace-nowrap overflow-hidden mr-4" :account="account" />
|
||||||
|
<Currency :class="ExpandMenu ? 'md:inline' : 'md:hidden'" class="whitespace-nowrap" :value="account.ClearedBalance" />
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<!--
|
||||||
|
<li class="bg-slate-100 dark:bg-slate-800 my-2 p-2 px-3">
|
||||||
<div class="flex flex-row justify-between font-bold">
|
<div class="flex flex-row justify-between font-bold">
|
||||||
<span>On-Budget Accounts</span>
|
<span>Closed Accounts</span>
|
||||||
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="OnBudgetAccountsBalance" />
|
|
||||||
</div>
|
</div>
|
||||||
<div v-for="account in OnBudgetAccounts" class="flex flex-row justify-between">
|
|
||||||
<router-link :to="'/budget/'+CurrentBudgetID+'/account/'+account.ID">{{account.Name}}</router-link>
|
|
||||||
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="account.Balance" />
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
<li class="bg-red-200 rounded-lg m-1 p-1 px-3">
|
|
||||||
<div class="flex flex-row justify-between font-bold">
|
|
||||||
<span>Off-Budget Accounts</span>
|
|
||||||
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="OffBudgetAccountsBalance" />
|
|
||||||
</div>
|
|
||||||
<div v-for="account in OffBudgetAccounts" class="flex flex-row justify-between">
|
|
||||||
<router-link :to="'/budget/'+CurrentBudgetID+'/account/'+account.ID">{{account.Name}}</router-link>
|
|
||||||
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="account.Balance" />
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
<li class="bg-red-200 rounded-lg m-1 p-1 px-3">
|
|
||||||
Closed Accounts
|
|
||||||
</li>
|
|
||||||
<!--<li>
|
|
||||||
<router-link :to="'/budget/'+CurrentBudgetID+'/accounts'">Edit accounts</router-link>
|
|
||||||
</li>-->
|
|
||||||
<li class="bg-red-200 rounded-lg m-1 p-1 px-3">
|
|
||||||
+ Add Account
|
+ Add Account
|
||||||
</li>
|
</li>
|
||||||
<li class="bg-red-200 rounded-lg m-1 p-1 px-3">
|
-->
|
||||||
<router-link :to="'/budget/'+CurrentBudgetID+'/settings'">Budget-Settings</router-link>
|
<!--<li>
|
||||||
</li>
|
<router-link :to="'/budget/'+CurrentBudgetID+'/accounts'">Edit accounts</router-link>
|
||||||
<!--<li><router-link to="/admin">Admin</router-link></li>-->
|
</li>-->
|
||||||
</div>
|
<li class="bg-red-100 dark:bg-slate-600 my-2 p-2 px-3">
|
||||||
</template>
|
<router-link :to="'/budget/' + CurrentBudgetID + '/settings'">
|
||||||
|
Budget-Settings
|
||||||
|
</router-link>
|
||||||
|
</li>
|
||||||
|
<!--<li><router-link to="/admin">Admin</router-link></li>-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
@ -1,9 +1,11 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, defineProps, onMounted, ref, watchEffect } from "vue";
|
import { computed, onMounted, ref, watchEffect } from "vue";
|
||||||
import Currency from "../components/Currency.vue";
|
import Currency from "../components/Currency.vue";
|
||||||
import { useBudgetsStore } from "../stores/budget";
|
import { useBudgetsStore } from "../stores/budget";
|
||||||
import { useAccountStore } from "../stores/budget-account";
|
import { Category, useAccountStore } from "../stores/budget-account";
|
||||||
import { useSessionStore } from "../stores/session";
|
import { useSessionStore } from "../stores/session";
|
||||||
|
import Input from "../components/Input.vue";
|
||||||
|
import { POST } from "../api";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
budgetid: string,
|
budgetid: string,
|
||||||
@ -17,7 +19,7 @@ const CurrentBudgetID = computed(() => budgetsStore.CurrentBudgetID);
|
|||||||
const accountStore = useAccountStore();
|
const accountStore = useAccountStore();
|
||||||
const categoriesForMonth = accountStore.CategoriesForMonthAndGroup;
|
const categoriesForMonth = accountStore.CategoriesForMonthAndGroup;
|
||||||
|
|
||||||
function GetCategories(group : string) {
|
function GetCategories(group: string) {
|
||||||
return [...categoriesForMonth(selected.value.Year, selected.value.Month, group)];
|
return [...categoriesForMonth(selected.value.Year, selected.value.Month, group)];
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -28,20 +30,20 @@ const GroupsForMonth = computed(() => {
|
|||||||
|
|
||||||
|
|
||||||
const previous = computed(() => ({
|
const previous = computed(() => ({
|
||||||
Year: new Date(selected.value.Year, selected.value.Month - 1, 1).getFullYear(),
|
Year: new Date(selected.value.Year, selected.value.Month - 1, 1).getFullYear(),
|
||||||
Month: new Date(selected.value.Year, selected.value.Month - 1, 1).getMonth(),
|
Month: new Date(selected.value.Year, selected.value.Month - 1, 1).getMonth(),
|
||||||
}));
|
}));
|
||||||
const current = computed(() => ({
|
const current = computed(() => ({
|
||||||
Year: new Date().getFullYear(),
|
Year: new Date().getFullYear(),
|
||||||
Month: new Date().getMonth(),
|
Month: new Date().getMonth(),
|
||||||
}));
|
}));
|
||||||
const selected = computed(() => ({
|
const selected = computed(() => ({
|
||||||
Year: Number(props.year) ?? current.value.Year,
|
Year: Number(props.year) ?? current.value.Year,
|
||||||
Month: Number(props.month ?? current.value.Month)
|
Month: Number(props.month ?? current.value.Month)
|
||||||
}));
|
}));
|
||||||
const next = computed(() => ({
|
const next = computed(() => ({
|
||||||
Year: new Date(selected.value.Year, Number(props.month) + 1, 1).getFullYear(),
|
Year: new Date(selected.value.Year, Number(props.month) + 1, 1).getFullYear(),
|
||||||
Month: new Date(selected.value.Year, Number(props.month) + 1, 1).getMonth(),
|
Month: new Date(selected.value.Year, Number(props.month) + 1, 1).getMonth(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
watchEffect(() => {
|
watchEffect(() => {
|
||||||
@ -56,58 +58,162 @@ onMounted(() => {
|
|||||||
|
|
||||||
const expandedGroups = ref<Map<string, boolean>>(new Map<string, boolean>())
|
const expandedGroups = ref<Map<string, boolean>>(new Map<string, boolean>())
|
||||||
|
|
||||||
function toggleGroup(group : {Name : string, Expand: boolean}) {
|
function toggleGroup(group: { Name: string, Expand: boolean }) {
|
||||||
console.log(expandedGroups.value);
|
|
||||||
expandedGroups.value.set(group.Name, !(expandedGroups.value.get(group.Name) ?? group.Expand))
|
expandedGroups.value.set(group.Name, !(expandedGroups.value.get(group.Name) ?? group.Expand))
|
||||||
}
|
}
|
||||||
|
|
||||||
function getGroupState(group : {Name : string, Expand: boolean}) : boolean {
|
function getGroupState(group: { Name: string, Expand: boolean }): boolean {
|
||||||
return expandedGroups.value.get(group.Name) ?? group.Expand;
|
return expandedGroups.value.get(group.Name) ?? group.Expand;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function assignedChanged(e : Event, category : Category){
|
||||||
|
const target = e.target as HTMLInputElement;
|
||||||
|
const value = target.valueAsNumber;
|
||||||
|
POST("/budget/"+CurrentBudgetID.value+"/category/" + category.ID + "/" + selected.value.Year + "/" + (selected.value.Month+1),
|
||||||
|
JSON.stringify({Assigned: category.Assigned}));
|
||||||
|
}
|
||||||
|
|
||||||
|
const budgeted = computed(() => accountStore.GetBudgeted(selected.value.Year, selected.value.Month))
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<h1>Budget for {{ selected.Month + 1 }}/{{ selected.Year }}</h1>
|
<h1>Budget for {{ selected.Month + 1 }}/{{ selected.Year }}</h1>
|
||||||
<div>
|
<table class="inline-block">
|
||||||
<router-link
|
<tr>
|
||||||
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + previous.Year + '/' + previous.Month"
|
<td>
|
||||||
>Previous Month</router-link>-
|
Available last month:
|
||||||
<router-link
|
</td>
|
||||||
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + current.Year + '/' + current.Month"
|
<td class="text-right">
|
||||||
>Current Month</router-link>-
|
<Currency :value="accountStore.Available-accountStore.OverspentLastMonth+budgeted.Assigned+budgeted.Deassigned" />
|
||||||
<router-link
|
</td>
|
||||||
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + next.Year + '/' + next.Month"
|
</tr>
|
||||||
>Next Month</router-link>
|
<tr>
|
||||||
</div>
|
<td>
|
||||||
<table class="container col-lg-12" id="content">
|
Overspent last month:
|
||||||
<tr>
|
</td>
|
||||||
<th>Category</th>
|
<td class="text-right">
|
||||||
<th></th>
|
<Currency :value="accountStore.OverspentLastMonth" />
|
||||||
<th></th>
|
</td>
|
||||||
<th>Leftover</th>
|
</tr>
|
||||||
<th>Assigned</th>
|
<tr>
|
||||||
<th>Activity</th>
|
<td>
|
||||||
<th>Available</th>
|
Budgeted this month:
|
||||||
</tr>
|
</td>
|
||||||
<tbody v-for="group in GroupsForMonth">
|
<td class="text-right">
|
||||||
<a class="text-lg font-bold" @click="toggleGroup(group)">{{ (getGroupState(group) ? "−" : "+") + " " + group.Name }}</a>
|
<Currency :value="budgeted.Assigned+budgeted.Deassigned" />
|
||||||
<tr v-for="category in GetCategories(group.Name)" v-if="getGroupState(group)">
|
</td>
|
||||||
<td>{{ category.Name }}</td>
|
<td class="text-sm pl-2">
|
||||||
<td></td>
|
= <Currency :value="budgeted.Assigned" /> - <Currency :value="-budgeted.Deassigned" />
|
||||||
<td></td>
|
</td>
|
||||||
<td class="text-right">
|
</tr>
|
||||||
<Currency :value="category.AvailableLastMonth" />
|
<tr class="font-bold">
|
||||||
</td>
|
<td class="py-2">
|
||||||
<td class="text-right">
|
Available balance:
|
||||||
<Currency :value="category.Assigned" />
|
</td>
|
||||||
</td>
|
<td class="text-right">
|
||||||
<td class="text-right">
|
<Currency :value="accountStore.Available" />
|
||||||
<Currency :value="category.Activity" />
|
</td>
|
||||||
</td>
|
</tr>
|
||||||
<td class="text-right">
|
<tr>
|
||||||
<Currency :value="category.Available" />
|
<td>
|
||||||
</td>
|
Activity:
|
||||||
</tr>
|
</td>
|
||||||
</tbody>
|
<td class="text-right">
|
||||||
</table>
|
<Currency :value="budgeted.Income + budgeted.Spent" />
|
||||||
|
</td>
|
||||||
|
<td class="text-sm pl-2">
|
||||||
|
= <Currency :value="budgeted.Income" /> - <Currency :value="-1 * budgeted.Spent" />
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
<div>
|
||||||
|
<router-link
|
||||||
|
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + previous.Year + '/' + previous.Month"
|
||||||
|
>
|
||||||
|
<<
|
||||||
|
</router-link>
|
||||||
|
<router-link
|
||||||
|
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + current.Year + '/' + current.Month"
|
||||||
|
>
|
||||||
|
Current Month
|
||||||
|
</router-link>
|
||||||
|
<router-link
|
||||||
|
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + next.Year + '/' + next.Month"
|
||||||
|
>
|
||||||
|
>>
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="content"
|
||||||
|
class="container col-lg-12 grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-5"
|
||||||
|
>
|
||||||
|
<span class="hidden sm:block" />
|
||||||
|
<span class="hidden lg:block text-right">Leftover</span>
|
||||||
|
<span class="hidden sm:block text-right">Assigned</span>
|
||||||
|
<span class="hidden sm:block text-right">Activity</span>
|
||||||
|
<span class="hidden sm:block text-right">Available</span>
|
||||||
|
<template
|
||||||
|
v-for="group in GroupsForMonth"
|
||||||
|
:key="group.Name"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="text-lg font-bold mt-2"
|
||||||
|
@click="toggleGroup(group)"
|
||||||
|
>{{ (getGroupState(group) ? "−" : "+") + " " + group.Name }}</span>
|
||||||
|
<Currency
|
||||||
|
:value="group.AvailableLastMonth"
|
||||||
|
class="hidden lg:block mt-2"
|
||||||
|
positive-class="text-slate-500"
|
||||||
|
negative-class="text-red-700 dark:text-red-400"
|
||||||
|
/>
|
||||||
|
<Currency
|
||||||
|
:value="group.Assigned"
|
||||||
|
class="hidden sm:block mx-2 mt-2 text-right"
|
||||||
|
positive-class="text-slate-500"
|
||||||
|
negative-class="text-red-700 dark:text-red-400"
|
||||||
|
/>
|
||||||
|
<Currency
|
||||||
|
:value="group.Activity"
|
||||||
|
class="hidden sm:block mt-2"
|
||||||
|
positive-class="text-slate-500"
|
||||||
|
negative-class="text-red-700 dark:text-red-400"
|
||||||
|
/>
|
||||||
|
<Currency
|
||||||
|
:value="group.Available"
|
||||||
|
class="mt-2"
|
||||||
|
positive-class="text-slate-500"
|
||||||
|
negative-class="text-red-700 dark:text-red-400"
|
||||||
|
/>
|
||||||
|
<template
|
||||||
|
v-for="category in GetCategories(group.Name)"
|
||||||
|
:key="category.ID"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-if="getGroupState(group)"
|
||||||
|
class="contents"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="whitespace-nowrap overflow-hidden"
|
||||||
|
>{{ category.Name }}</span>
|
||||||
|
<Currency
|
||||||
|
:value="category.AvailableLastMonth"
|
||||||
|
class="hidden lg:block"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
v-model="category.Assigned"
|
||||||
|
type="number"
|
||||||
|
class="hidden sm:block mx-2 text-right"
|
||||||
|
@input="(evt) => assignedChanged(evt, category)"
|
||||||
|
/>
|
||||||
|
<Currency
|
||||||
|
:value="category.Activity"
|
||||||
|
class="hidden sm:block"
|
||||||
|
/>
|
||||||
|
<Currency
|
||||||
|
:value="accountStore.GetCategoryAvailable(category)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import NewBudget from '../dialogs/NewBudget.vue';
|
import NewBudget from '../dialogs/NewBudget.vue';
|
||||||
import Card from '../components/Card.vue';
|
import RowCard from '../components/RowCard.vue';
|
||||||
import { useSessionStore } from '../stores/session';
|
import { useSessionStore } from '../stores/session';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@ -11,15 +11,22 @@ const BudgetsList = useSessionStore().BudgetsList;
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<h1>Budgets</h1>
|
<h1>Budgets</h1>
|
||||||
<div class="grid md:grid-cols-2 gap-6">
|
<div class="grid md:grid-cols-2 gap-6">
|
||||||
<Card v-for="budget in BudgetsList">
|
<RowCard
|
||||||
<router-link v-bind:to="'/budget/'+budget.ID+'/budgeting'" class="contents">
|
v-for="budget in BudgetsList"
|
||||||
<!--<svg class="w-24"></svg>-->
|
:key="budget.ID"
|
||||||
<p class="w-24 text-center text-6xl"></p>
|
>
|
||||||
<span class="text-lg">{{budget.Name}}{{budget.ID == budgetid ? " *" : ""}}</span>
|
<router-link
|
||||||
</router-link>
|
:to="'/budget/'+budget.ID+'/budgeting'"
|
||||||
</Card>
|
class="contents"
|
||||||
<NewBudget />
|
>
|
||||||
</div>
|
<!--<svg class="w-24"></svg>-->
|
||||||
|
<p class="w-24 text-center text-6xl" />
|
||||||
|
<span class="text-lg">{{ budget.Name
|
||||||
|
}}{{ budget.ID == budgetid ? " *" : "" }}</span>
|
||||||
|
</router-link>
|
||||||
|
</RowCard>
|
||||||
|
<NewBudget />
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
@ -1,13 +0,0 @@
|
|||||||
<script lang="ts" setup>
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div>
|
|
||||||
<div class="font-bold" id="content">
|
|
||||||
Willkommen bei Budgeteer, der neuen App für's Budget!
|
|
||||||
</div>
|
|
||||||
<div class="container col-md-4" id="login">
|
|
||||||
<router-link to="/login">Login</router-link> or <router-link to="/login">register</router-link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
@ -2,6 +2,7 @@
|
|||||||
import { onMounted, ref } from "vue";
|
import { onMounted, ref } from "vue";
|
||||||
import { useRouter } from "vue-router";
|
import { useRouter } from "vue-router";
|
||||||
import { useSessionStore } from "../stores/session";
|
import { useSessionStore } from "../stores/session";
|
||||||
|
import Input from "../components/Input.vue";
|
||||||
|
|
||||||
const error = ref("");
|
const error = ref("");
|
||||||
const login = ref({ user: "", password: "" });
|
const login = ref({ user: "", password: "" });
|
||||||
@ -27,18 +28,32 @@ function formSubmit(e: MouseEvent) {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div>
|
<div>
|
||||||
<input type="text" v-model="login.user"
|
<Input
|
||||||
placeholder="Username"
|
v-model="login.user"
|
||||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
type="text"
|
||||||
<input type="password" v-model="login.password"
|
placeholder="Username"
|
||||||
placeholder="Password"
|
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
|
||||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
/>
|
||||||
</div>
|
<Input
|
||||||
<div>{{ error }}</div>
|
v-model="login.password"
|
||||||
<button type="submit" @click="formSubmit" class="bg-blue-300 rounded-lg p-2 w-48">Login</button>
|
type="password"
|
||||||
<p>
|
placeholder="Password"
|
||||||
New user?
|
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
|
||||||
<router-link to="/register">Register</router-link> instead!
|
/>
|
||||||
</p>
|
</div>
|
||||||
</template>
|
<div>{{ error }}</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="bg-blue-300 rounded-lg p-2 w-48"
|
||||||
|
@click="formSubmit"
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</button>
|
||||||
|
<p>
|
||||||
|
New user?
|
||||||
|
<router-link to="/register">
|
||||||
|
Register
|
||||||
|
</router-link> instead!
|
||||||
|
</p>
|
||||||
|
</template>
|
||||||
|
@ -1,47 +1,65 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { onMounted, ref } from "vue";
|
import { onMounted, ref } from "vue";
|
||||||
import { useRouter } from "vue-router";
|
import { useRouter } from "vue-router";
|
||||||
import { useSessionStore } from "../stores/session";
|
import { useSessionStore } from "../stores/session";
|
||||||
|
import Input from "../components/Input.vue";
|
||||||
const error = ref("");
|
|
||||||
const login = ref({ email: "", password: "", name: "" });
|
const error = ref("");
|
||||||
const router = useRouter(); // has to be called in setup
|
const login = ref({ email: "", password: "", name: "" });
|
||||||
|
const router = useRouter(); // has to be called in setup
|
||||||
onMounted(() => {
|
|
||||||
useSessionStore().setTitle("Login");
|
onMounted(() => {
|
||||||
});
|
useSessionStore().setTitle("Login");
|
||||||
|
});
|
||||||
function formSubmit(e: MouseEvent) {
|
|
||||||
e.preventDefault();
|
function formSubmit(e: MouseEvent) {
|
||||||
useSessionStore().register(login.value)
|
e.preventDefault();
|
||||||
.then(x => {
|
useSessionStore().register(login.value)
|
||||||
error.value = "";
|
.then(x => {
|
||||||
router.replace("/dashboard");
|
error.value = "";
|
||||||
return x;
|
router.replace("/dashboard");
|
||||||
})
|
return x;
|
||||||
.catch(x => error.value = "The entered credentials are invalid!");
|
})
|
||||||
|
.catch(x => error.value = "The entered credentials are invalid!");
|
||||||
// TODO display invalidCredentials
|
|
||||||
// TODO redirect to dashboard on success
|
// TODO display invalidCredentials
|
||||||
}
|
// TODO redirect to dashboard on success
|
||||||
</script>
|
}
|
||||||
|
</script>
|
||||||
<template>
|
|
||||||
<div>
|
<template>
|
||||||
<input type="text" v-model="login.name"
|
<div>
|
||||||
placeholder="Name"
|
<Input
|
||||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
v-model="login.name"
|
||||||
<input type="text" v-model="login.email"
|
type="text"
|
||||||
placeholder="Email"
|
placeholder="Name"
|
||||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
|
||||||
<input type="password" v-model="login.password"
|
/>
|
||||||
placeholder="Password"
|
<Input
|
||||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
v-model="login.email"
|
||||||
</div>
|
type="text"
|
||||||
<div>{{ error }}</div>
|
placeholder="Email"
|
||||||
<button type="submit" @click="formSubmit" class="bg-blue-300 rounded-lg p-2 w-48">Register</button>
|
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
|
||||||
<p>
|
/>
|
||||||
Existing user?
|
<Input
|
||||||
<router-link to="/login">Login</router-link> instead!
|
v-model="login.password"
|
||||||
</p>
|
type="password"
|
||||||
</template>
|
placeholder="Password"
|
||||||
|
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>{{ error }}</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="bg-blue-300 rounded-lg p-2 w-48"
|
||||||
|
@click="formSubmit"
|
||||||
|
>
|
||||||
|
Register
|
||||||
|
</button>
|
||||||
|
<p>
|
||||||
|
Existing user?
|
||||||
|
<router-link to="/login">
|
||||||
|
Login
|
||||||
|
</router-link> instead!
|
||||||
|
</p>
|
||||||
|
</template>
|
||||||
|
@ -4,9 +4,12 @@ import { useRouter } from "vue-router";
|
|||||||
import { DELETE, POST } from "../api";
|
import { DELETE, POST } from "../api";
|
||||||
import { useBudgetsStore } from "../stores/budget";
|
import { useBudgetsStore } from "../stores/budget";
|
||||||
import { useSessionStore } from "../stores/session";
|
import { useSessionStore } from "../stores/session";
|
||||||
import Card from "../components/Card.vue";
|
import RowCard from "../components/RowCard.vue";
|
||||||
import Button from "../components/Button.vue";
|
import Button from "../components/SimpleButton.vue";
|
||||||
import { saveAs } from 'file-saver';
|
import { saveAs } from 'file-saver';
|
||||||
|
import Input from "../components/Input.vue";
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
const transactionsFile = ref<File | undefined>(undefined);
|
const transactionsFile = ref<File | undefined>(undefined);
|
||||||
const assignmentsFile = ref<File | undefined>(undefined);
|
const assignmentsFile = ref<File | undefined>(undefined);
|
||||||
@ -38,14 +41,11 @@ function deleteBudget() {
|
|||||||
|
|
||||||
const budgetStore = useSessionStore();
|
const budgetStore = useSessionStore();
|
||||||
budgetStore.Budgets.delete(CurrentBudgetID.value);
|
budgetStore.Budgets.delete(CurrentBudgetID.value);
|
||||||
useRouter().push("/")
|
router.push("/dashboard")
|
||||||
};
|
};
|
||||||
function clearBudget() {
|
function clearBudget() {
|
||||||
POST("/budget/" + CurrentBudgetID.value + "/settings/clear", null)
|
POST("/budget/" + CurrentBudgetID.value + "/settings/clear", null)
|
||||||
};
|
};
|
||||||
function cleanNegative() {
|
|
||||||
// <a href="/budget/{{.Budget.ID}}/settings/clean-negative">Fix all historic negative category-balances</a>
|
|
||||||
};
|
|
||||||
function ynabImport() {
|
function ynabImport() {
|
||||||
if (transactionsFile.value == undefined || assignmentsFile.value == undefined)
|
if (transactionsFile.value == undefined || assignmentsFile.value == undefined)
|
||||||
return
|
return
|
||||||
@ -71,55 +71,90 @@ function ynabExport() {
|
|||||||
saveAs(blob, timeStamp + " " + CurrentBudgetName.value + " - Transactions.tsv");
|
saveAs(blob, timeStamp + " " + CurrentBudgetName.value + " - Transactions.tsv");
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div>
|
<div>
|
||||||
<h1>Danger Zone</h1>
|
<h1>Danger Zone</h1>
|
||||||
<div class="grid md:grid-cols-2 gap-6">
|
<div class="grid md:grid-cols-2 gap-6">
|
||||||
<Card class="flex-col p-3">
|
<RowCard class="flex-col p-3">
|
||||||
<h2 class="text-lg font-bold">Clear Budget</h2>
|
<h2 class="text-lg font-bold">
|
||||||
<p>This removes transactions and assignments to start from scratch. Accounts and categories are kept. Not undoable!</p>
|
Clear Budget
|
||||||
|
</h2>
|
||||||
|
<p>
|
||||||
|
This removes transactions and assignments to start from
|
||||||
|
scratch. Accounts and categories are kept. Not undoable!
|
||||||
|
</p>
|
||||||
|
|
||||||
<Button class="bg-red-500" @click="clearBudget">Clear budget</Button>
|
<Button
|
||||||
</Card>
|
class="bg-red-500 py-2"
|
||||||
<Card class="flex-col p-3">
|
@click="clearBudget"
|
||||||
<h2 class="text-lg font-bold">Delete Budget</h2>
|
>
|
||||||
<p>This deletes the whole bugdet including all transactions, assignments, accounts and categories. Not undoable!</p>
|
Clear budget
|
||||||
<Button class="bg-red-500" @click="deleteBudget">Delete budget</button>
|
</Button>
|
||||||
</Card>
|
</RowCard>
|
||||||
<Card class="flex-col p-3">
|
<RowCard class="flex-col p-3">
|
||||||
<h2 class="text-lg font-bold">Fix all historic negative category-balances</h2>
|
<h2 class="text-lg font-bold">
|
||||||
<p>This restores YNABs functionality, that would substract any overspent categories' balances from next months inflows.</p>
|
Delete Budget
|
||||||
<Button class="bg-orange-500" @click="cleanNegative">Fix negative</button>
|
</h2>
|
||||||
</Card>
|
<p>
|
||||||
<Card class="flex-col p-3">
|
This deletes the whole bugdet including all transactions,
|
||||||
<h2 class="text-lg font-bold">Import YNAB Budget</h2>
|
assignments, accounts and categories. Not undoable!
|
||||||
|
</p>
|
||||||
<div class="flex flex-row">
|
<Button
|
||||||
<div>
|
class="bg-red-500 py-2"
|
||||||
<label for="transactions_file">
|
@click="deleteBudget"
|
||||||
Transaktionen:
|
>
|
||||||
<input type="file" @change="gotTransactions" accept="text/*" />
|
Delete budget
|
||||||
</label>
|
</Button>
|
||||||
<br />
|
</RowCard>
|
||||||
<label for="assignments_file">
|
<RowCard class="flex-col p-3">
|
||||||
Budget:
|
<h2 class="text-lg font-bold">
|
||||||
<input type="file" @change="gotAssignments" accept="text/*" />
|
Import YNAB Budget
|
||||||
</label>
|
</h2>
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button class="bg-blue-500" :disabled="filesIncomplete" @click="ynabImport">Importieren</Button>
|
<div>
|
||||||
</div>
|
<label for="transactions_file">
|
||||||
</Card>
|
Transaktionen:
|
||||||
<Card class="flex-col p-3">
|
<input
|
||||||
<h2 class="text-lg font-bold">Export as YNAB TSV</h2>
|
type="file"
|
||||||
|
accept="text/*"
|
||||||
<div class="flex flex-row">
|
@change="gotTransactions"
|
||||||
<Button class="bg-blue-500" @click="ynabExport">Export</Button>
|
>
|
||||||
</div>
|
</label>
|
||||||
</Card>
|
<br>
|
||||||
|
<label for="assignments_file">
|
||||||
|
Budget:
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept="text/*"
|
||||||
|
@change="gotAssignments"
|
||||||
|
>
|
||||||
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
class="bg-blue-500 py-2"
|
||||||
|
:disabled="filesIncomplete"
|
||||||
|
@click="ynabImport"
|
||||||
|
>
|
||||||
|
Importieren
|
||||||
|
</Button>
|
||||||
|
</RowCard>
|
||||||
|
<RowCard class="flex-col p-3">
|
||||||
|
<h2 class="text-lg font-bold">
|
||||||
|
Export as YNAB TSV
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div class="flex flex-row">
|
||||||
|
<Button
|
||||||
|
class="bg-blue-500 py-2"
|
||||||
|
@click="ynabExport"
|
||||||
|
>
|
||||||
|
Export
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</RowCard>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</div>
|
||||||
|
</template>
|
||||||
|
24
web/src/pages/WelcomePage.vue
Normal file
24
web/src/pages/WelcomePage.vue
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<div
|
||||||
|
id="content"
|
||||||
|
class="font-bold"
|
||||||
|
>
|
||||||
|
Willkommen bei Budgeteer, der neuen App für's Budget!
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="login"
|
||||||
|
class="container col-md-4"
|
||||||
|
>
|
||||||
|
<router-link to="/login">
|
||||||
|
Login
|
||||||
|
</router-link> or
|
||||||
|
<router-link to="/login">
|
||||||
|
register
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
@ -1,82 +1,107 @@
|
|||||||
import { PiniaPluginContext, StoreGeneric, _ActionsTree, _StoreOnActionListenerContext } from 'pinia';
|
import {
|
||||||
|
PiniaPluginContext,
|
||||||
|
StoreGeneric,
|
||||||
|
_ActionsTree,
|
||||||
|
_StoreOnActionListenerContext,
|
||||||
|
} from "pinia";
|
||||||
|
|
||||||
const cloneDeep = <T>(obj: T): T => {
|
const cloneDeep = <T>(obj: T): T => {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(JSON.stringify(obj));
|
return JSON.parse(JSON.stringify(obj));
|
||||||
} catch {
|
} catch {
|
||||||
return { ...obj };
|
return { ...obj };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const formatTime = (date = new Date()) => {
|
const formatTime = (date = new Date()) => {
|
||||||
const hours = date.getHours().toString().padStart(2, '0');
|
const hours = date.getHours().toString().padStart(2, "0");
|
||||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
const minutes = date.getMinutes().toString().padStart(2, "0");
|
||||||
const seconds = date.getSeconds().toString().padStart(2, '0');
|
const seconds = date.getSeconds().toString().padStart(2, "0");
|
||||||
const milliseconds = date.getMilliseconds().toString();
|
|
||||||
|
|
||||||
return `${hours}:${minutes}:${seconds}:${milliseconds}`;
|
return `${hours}:${minutes}:${seconds}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface PiniaLoggerOptions {
|
export interface PiniaLoggerOptions {
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
expanded?: boolean;
|
expanded?: boolean;
|
||||||
showDuration?: boolean
|
showDuration?: boolean;
|
||||||
showStoreName?: boolean;
|
showStoreName?: boolean;
|
||||||
logErrors?: boolean;
|
logErrors?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PiniaActionListenerContext = _StoreOnActionListenerContext<StoreGeneric, string, _ActionsTree>;
|
export type PiniaActionListenerContext = _StoreOnActionListenerContext<
|
||||||
|
StoreGeneric,
|
||||||
|
string,
|
||||||
|
_ActionsTree
|
||||||
|
>;
|
||||||
|
|
||||||
const defaultOptions: PiniaLoggerOptions = {
|
const defaultOptions: PiniaLoggerOptions = {
|
||||||
logErrors: true,
|
logErrors: true,
|
||||||
disabled: false,
|
disabled: false,
|
||||||
expanded: true,
|
expanded: true,
|
||||||
showStoreName: true,
|
showStoreName: true,
|
||||||
showDuration: false,
|
showDuration: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PiniaLogger = (config = defaultOptions) => (ctx: PiniaPluginContext) => {
|
export const PiniaLogger =
|
||||||
const options = {
|
(config = defaultOptions) =>
|
||||||
...defaultOptions,
|
(ctx: PiniaPluginContext) => {
|
||||||
...config,
|
const options = {
|
||||||
};
|
...defaultOptions,
|
||||||
|
...config,
|
||||||
|
};
|
||||||
|
|
||||||
if (options.disabled) return;
|
if (options.disabled) return;
|
||||||
|
|
||||||
|
ctx.store.$onAction((action: PiniaActionListenerContext) => {
|
||||||
|
const startTime = Date.now();
|
||||||
|
const prevState = cloneDeep(ctx.store.$state);
|
||||||
|
|
||||||
ctx.store.$onAction((action: PiniaActionListenerContext) => {
|
const log = (isError?: boolean, error?: any) => {
|
||||||
const startTime = Date.now();
|
const endTime = Date.now();
|
||||||
const prevState = cloneDeep(ctx.store.$state);
|
const duration = endTime - startTime + "ms";
|
||||||
|
const nextState = cloneDeep(ctx.store.$state);
|
||||||
|
const storeName = action.store.$id;
|
||||||
|
const title = `${formatTime()} action 🍍 ${
|
||||||
|
options.showStoreName ? `[${storeName}] ` : ""
|
||||||
|
}${action.name} ${
|
||||||
|
isError ? `failed after ` : ""
|
||||||
|
}in ${duration}`;
|
||||||
|
|
||||||
const log = (isError?: boolean, error?: any) => {
|
console[options.expanded ? "group" : "groupCollapsed"](
|
||||||
const endTime = Date.now();
|
`%c${title}`,
|
||||||
const duration = endTime - startTime + 'ms';
|
`font-weight: bold; ${isError ? "color: #ed4981;" : ""}`
|
||||||
const nextState = cloneDeep(ctx.store.$state);
|
);
|
||||||
const storeName = action.store.$id;
|
console.log(
|
||||||
const title = `action 🍍 ${options.showStoreName ? `[${storeName}] ` : ''}${action.name} ${isError ? `failed after ${duration} ` : ''}@ ${formatTime()}`;
|
"%cprev state",
|
||||||
|
"font-weight: bold; color: grey;",
|
||||||
|
prevState
|
||||||
|
);
|
||||||
|
console.log("%caction", "font-weight: bold; color: #69B7FF;", {
|
||||||
|
type: action.name,
|
||||||
|
args:
|
||||||
|
action.args.length > 0 ? { ...action.args } : undefined,
|
||||||
|
...(options.showStoreName && { store: action.store.$id }),
|
||||||
|
...(options.showDuration && { duration }),
|
||||||
|
...(isError && { error }),
|
||||||
|
});
|
||||||
|
console.log(
|
||||||
|
"%cnext state",
|
||||||
|
"font-weight: bold; color: #4caf50;",
|
||||||
|
nextState
|
||||||
|
);
|
||||||
|
console.groupEnd();
|
||||||
|
};
|
||||||
|
|
||||||
console[options.expanded ? 'group' : 'groupCollapsed'](`%c${title}`, `font-weight: bold; ${isError ? 'color: #ed4981;' : ''}`);
|
action.after(() => {
|
||||||
console.log('%cprev state', 'font-weight: bold; color: grey;', prevState);
|
log();
|
||||||
console.log('%caction', 'font-weight: bold; color: #69B7FF;', {
|
});
|
||||||
type: action.name,
|
|
||||||
args: action.args.length > 0 ? { ...action.args } : undefined,
|
if (options.logErrors) {
|
||||||
...(options.showStoreName && { store: action.store.$id }),
|
action.onError((error) => {
|
||||||
...(options.showDuration && { duration }),
|
log(true, error);
|
||||||
...(isError && { error }),
|
});
|
||||||
});
|
}
|
||||||
console.log('%cnext state', 'font-weight: bold; color: #4caf50;', nextState);
|
});
|
||||||
console.groupEnd();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
action.after(() => {
|
export default PiniaLogger;
|
||||||
log();
|
|
||||||
});
|
|
||||||
|
|
||||||
if (options.logErrors) {
|
|
||||||
action.onError((error) => {
|
|
||||||
log(true, error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export default PiniaLogger;
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user