Compare commits
124 Commits
Author | SHA1 | Date | |
---|---|---|---|
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 |
@ -32,7 +32,7 @@ steps:
|
||||
from_secret: docker_password
|
||||
repo: hub.javil.eu/budgeteer
|
||||
context: build
|
||||
dockerfile: build/Dockerfile
|
||||
dockerfile: docker/Dockerfile
|
||||
tags:
|
||||
- latest
|
||||
when:
|
||||
@ -51,7 +51,7 @@ steps:
|
||||
from_secret: docker_password
|
||||
repo: hub.javil.eu/budgeteer
|
||||
context: build
|
||||
dockerfile: build/Dockerfile
|
||||
dockerfile: docker/Dockerfile
|
||||
auto_tag: true
|
||||
when:
|
||||
event:
|
||||
|
10
.earthignore
10
.earthignore
@ -1,10 +0,0 @@
|
||||
build/
|
||||
.git/
|
||||
docker-compose.yml
|
||||
README.md
|
||||
Earthfile
|
||||
config.example.json
|
||||
.gitignore
|
||||
.vscode/
|
||||
budgeteer
|
||||
budgeteer.exe
|
6
.vscode/settings.json
vendored
6
.vscode/settings.json
vendored
@ -1,7 +1,11 @@
|
||||
{
|
||||
"files.exclude": {
|
||||
"**/node_modules": true,
|
||||
"**/vendor": true
|
||||
"**/vendor": true,
|
||||
"**/*.sql.go": true,
|
||||
".task/": true,
|
||||
"build/": true,
|
||||
"web/dist/": true
|
||||
},
|
||||
"gopls": {
|
||||
"formatting.gofumpt": true,
|
||||
|
@ -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
|
@ -77,6 +77,8 @@ tasks:
|
||||
cmds:
|
||||
- yarn
|
||||
- yarn build
|
||||
- yarn run vue-tsc --noEmit
|
||||
- yarn run eslint "./src/**"
|
||||
|
||||
docker:
|
||||
desc: Build budgeeter:latest
|
||||
@ -95,7 +97,7 @@ tasks:
|
||||
- ./docker/build.sh
|
||||
- ./web/package.json
|
||||
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
|
||||
|
||||
run:
|
||||
|
@ -1,3 +0,0 @@
|
||||
FROM scratch
|
||||
COPY ./budgeteer /app/budgeteer
|
||||
ENTRYPOINT ["/app/budgeteer"]
|
@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
@ -29,11 +30,14 @@ func main() {
|
||||
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 := &server.Handler{
|
||||
Service: queries,
|
||||
TokenVerifier: &jwt.TokenVerifier{
|
||||
Secret: cfg.SessionSecret,
|
||||
},
|
||||
Service: queries,
|
||||
TokenVerifier: tokenVerifier,
|
||||
CredentialsVerifier: &bcrypt.Verifier{},
|
||||
StaticFS: http.FS(static),
|
||||
}
|
||||
|
@ -1,6 +0,0 @@
|
||||
{
|
||||
"DatabaseHost": "localhost",
|
||||
"DatabaseUser": "user",
|
||||
"DatabasePassword": "thisismypassword",
|
||||
"DatabaseName": "budgeteer"
|
||||
}
|
@ -1,17 +1,3 @@
|
||||
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 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
|
||||
FROM scratch
|
||||
COPY ./budgeteer /app/budgeteer
|
||||
ENTRYPOINT ["/app/budgeteer"]
|
||||
|
17
docker/Dockerfile.dev
Normal file
17
docker/Dockerfile.dev
Normal file
@ -0,0 +1,17 @@
|
||||
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 tmux
|
||||
ADD docker/dev.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 /dev.sh
|
2
go.mod
2
go.mod
@ -11,7 +11,7 @@ require (
|
||||
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 (
|
||||
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/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.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
|
||||
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/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
|
@ -12,32 +12,45 @@ import (
|
||||
|
||||
// TokenVerifier verifies Tokens.
|
||||
type TokenVerifier struct {
|
||||
Secret string
|
||||
Expiration time.Duration
|
||||
secret string
|
||||
}
|
||||
|
||||
// Token contains everything to authenticate a user.
|
||||
type Token struct {
|
||||
username string
|
||||
name string
|
||||
expiry float64
|
||||
id uuid.UUID
|
||||
const DefaultExpiration = time.Hour * time.Duration(72)
|
||||
|
||||
func NewTokenVerifier(secret string) (*TokenVerifier, error) {
|
||||
if secret == "" {
|
||||
return nil, ErrEmptySecret
|
||||
}
|
||||
|
||||
return &TokenVerifier{
|
||||
Expiration: DefaultExpiration,
|
||||
secret: secret,
|
||||
}, nil
|
||||
}
|
||||
|
||||
const (
|
||||
expiration = 72
|
||||
var (
|
||||
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.
|
||||
func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
|
||||
if tv.secret == "" {
|
||||
return "", ErrEmptySecret
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"usr": user.Email,
|
||||
"name": user.Name,
|
||||
"exp": time.Now().Add(time.Hour * expiration).Unix(),
|
||||
"exp": time.Now().Add(tv.Expiration).Unix(),
|
||||
"id": user.ID,
|
||||
})
|
||||
|
||||
// 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 {
|
||||
return "", fmt.Errorf("create token: %w", err)
|
||||
}
|
||||
@ -45,19 +58,17 @@ func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUnexpectedSigningMethod = fmt.Errorf("unexpected signing method")
|
||||
ErrInvalidToken = fmt.Errorf("token is invalid")
|
||||
ErrTokenExpired = fmt.Errorf("token has expired")
|
||||
)
|
||||
|
||||
// VerifyToken verifys a given string-token.
|
||||
// VerifyToken verifies a given string-token.
|
||||
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) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("method '%v': %w", token.Header["alg"], ErrUnexpectedSigningMethod)
|
||||
}
|
||||
return []byte(tv.Secret), nil
|
||||
return []byte(tv.secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse jwt: %w", err)
|
||||
@ -76,36 +87,3 @@ func (tv *TokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error
|
||||
}
|
||||
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
|
||||
}
|
@ -5,6 +5,7 @@ package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
|
||||
"github.com/google/uuid"
|
||||
@ -14,7 +15,7 @@ const createAccount = `-- name: CreateAccount :one
|
||||
INSERT INTO accounts
|
||||
(name, budget_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, budget_id, name, on_budget
|
||||
RETURNING id, budget_id, name, on_budget, is_open, last_reconciled
|
||||
`
|
||||
|
||||
type CreateAccountParams struct {
|
||||
@ -30,12 +31,14 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A
|
||||
&i.BudgetID,
|
||||
&i.Name,
|
||||
&i.OnBudget,
|
||||
&i.IsOpen,
|
||||
&i.LastReconciled,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
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
|
||||
`
|
||||
|
||||
@ -47,13 +50,16 @@ func (q *Queries) GetAccount(ctx context.Context, id uuid.UUID) (Account, error)
|
||||
&i.BudgetID,
|
||||
&i.Name,
|
||||
&i.OnBudget,
|
||||
&i.IsOpen,
|
||||
&i.LastReconciled,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
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
|
||||
AND accounts.is_open = TRUE
|
||||
ORDER BY accounts.name
|
||||
`
|
||||
|
||||
@ -71,6 +77,8 @@ func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Accoun
|
||||
&i.BudgetID,
|
||||
&i.Name,
|
||||
&i.OnBudget,
|
||||
&i.IsOpen,
|
||||
&i.LastReconciled,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -86,12 +94,13 @@ func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Accoun
|
||||
}
|
||||
|
||||
const getAccountsWithBalance = `-- name: GetAccountsWithBalance :many
|
||||
SELECT accounts.id, accounts.name, accounts.on_budget,
|
||||
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
|
||||
WHERE accounts.budget_id = $1
|
||||
AND accounts.is_open = TRUE
|
||||
ORDER BY accounts.name
|
||||
`
|
||||
|
||||
@ -99,6 +108,8 @@ type GetAccountsWithBalanceRow struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
OnBudget bool
|
||||
IsOpen bool
|
||||
LastReconciled sql.NullTime
|
||||
WorkingBalance numeric.Numeric
|
||||
ClearedBalance numeric.Numeric
|
||||
ReconciledBalance numeric.Numeric
|
||||
@ -117,6 +128,8 @@ func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
&i.OnBudget,
|
||||
&i.IsOpen,
|
||||
&i.LastReconciled,
|
||||
&i.WorkingBalance,
|
||||
&i.ClearedBalance,
|
||||
&i.ReconciledBalance,
|
||||
@ -137,7 +150,8 @@ func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID
|
||||
const searchAccounts = `-- name: SearchAccounts :many
|
||||
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
|
||||
WHERE accounts.budget_id = $1
|
||||
AND accounts.name LIKE $2
|
||||
AND accounts.is_open = TRUE
|
||||
AND accounts.name ILIKE $2
|
||||
ORDER BY accounts.name
|
||||
`
|
||||
|
||||
@ -181,28 +195,48 @@ func (q *Queries) SearchAccounts(ctx context.Context, arg SearchAccountsParams)
|
||||
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
|
||||
UPDATE accounts
|
||||
SET name = $1,
|
||||
on_budget = $2
|
||||
WHERE accounts.id = $3
|
||||
RETURNING id, budget_id, name, on_budget
|
||||
on_budget = $2,
|
||||
is_open = $3
|
||||
WHERE accounts.id = $4
|
||||
RETURNING id, budget_id, name, on_budget, is_open, last_reconciled
|
||||
`
|
||||
|
||||
type UpdateAccountParams struct {
|
||||
Name string
|
||||
OnBudget bool
|
||||
IsOpen bool
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
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
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.BudgetID,
|
||||
&i.Name,
|
||||
&i.OnBudget,
|
||||
&i.IsOpen,
|
||||
&i.LastReconciled,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ INSERT INTO assignments (
|
||||
) VALUES (
|
||||
$1, $2, $3
|
||||
)
|
||||
RETURNING id, category_id, date, memo, amount
|
||||
RETURNING category_id, date, memo, amount
|
||||
`
|
||||
|
||||
type CreateAssignmentParams struct {
|
||||
@ -30,7 +30,6 @@ func (q *Queries) CreateAssignment(ctx context.Context, arg CreateAssignmentPara
|
||||
row := q.db.QueryRowContext(ctx, createAssignment, arg.Date, arg.Amount, arg.CategoryID)
|
||||
var i Assignment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.CategoryID,
|
||||
&i.Date,
|
||||
&i.Memo,
|
||||
@ -130,3 +129,41 @@ func (q *Queries) GetAssignmentsByMonthAndCategory(ctx context.Context, budgetID
|
||||
}
|
||||
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
|
||||
}
|
||||
|
@ -122,7 +122,8 @@ SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.
|
||||
FROM categories
|
||||
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
|
||||
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
|
||||
`
|
||||
|
||||
|
@ -32,14 +32,15 @@ func (e *TransactionStatus) Scan(src interface{}) error {
|
||||
}
|
||||
|
||||
type Account struct {
|
||||
ID uuid.UUID
|
||||
BudgetID uuid.UUID
|
||||
Name string
|
||||
OnBudget bool
|
||||
ID uuid.UUID
|
||||
BudgetID uuid.UUID
|
||||
Name string
|
||||
OnBudget bool
|
||||
IsOpen bool
|
||||
LastReconciled sql.NullTime
|
||||
}
|
||||
|
||||
type Assignment struct {
|
||||
ID uuid.UUID
|
||||
CategoryID uuid.UUID
|
||||
Date time.Time
|
||||
Memo sql.NullString
|
||||
|
@ -53,6 +53,13 @@ func (n Numeric) IsZero() bool {
|
||||
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 {
|
||||
diffExp := n.Exp - exp
|
||||
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil) //nolint:gomnd
|
||||
@ -64,6 +71,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 {
|
||||
left := n
|
||||
right := other
|
||||
@ -106,6 +129,22 @@ func (n Numeric) Add(other Numeric) Numeric {
|
||||
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 {
|
||||
if n.Int == nil || n.Int.Int64() == 0 {
|
||||
return "0"
|
||||
|
@ -60,7 +60,7 @@ func (q *Queries) GetPayees(ctx context.Context, budgetID uuid.UUID) ([]Payee, e
|
||||
const searchPayees = `-- name: SearchPayees :many
|
||||
SELECT payees.id, payees.budget_id, payees.name, 'payee' as type FROM payees
|
||||
WHERE payees.budget_id = $1
|
||||
AND payees.name LIKE $2
|
||||
AND payees.name ILIKE $2
|
||||
ORDER BY payees.name
|
||||
`
|
||||
|
||||
|
@ -11,26 +11,35 @@ WHERE accounts.id = $1;
|
||||
-- name: GetAccounts :many
|
||||
SELECT accounts.* FROM accounts
|
||||
WHERE accounts.budget_id = $1
|
||||
AND accounts.is_open = TRUE
|
||||
ORDER BY accounts.name;
|
||||
|
||||
-- name: GetAccountsWithBalance :many
|
||||
SELECT accounts.id, accounts.name, accounts.on_budget,
|
||||
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
|
||||
WHERE accounts.budget_id = $1
|
||||
AND accounts.is_open = TRUE
|
||||
ORDER BY accounts.name;
|
||||
|
||||
-- name: SearchAccounts :many
|
||||
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
|
||||
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;
|
||||
|
||||
-- name: UpdateAccount :one
|
||||
UPDATE accounts
|
||||
SET name = $1,
|
||||
on_budget = $2
|
||||
WHERE accounts.id = $3
|
||||
on_budget = $2,
|
||||
is_open = $3
|
||||
WHERE accounts.id = $4
|
||||
RETURNING *;
|
||||
|
||||
-- name: SetLastReconciled :exec
|
||||
UPDATE accounts
|
||||
SET last_reconciled = NOW()
|
||||
WHERE accounts.id = $1;
|
@ -23,3 +23,17 @@ FROM assignments
|
||||
INNER JOIN categories ON categories.id = assignments.category_id
|
||||
INNER JOIN category_groups ON categories.category_group_id = category_groups.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
|
||||
INNER JOIN category_groups ON categories.category_group_id = category_groups.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 levenshtein(payees.name, $2);
|
@ -12,6 +12,6 @@ ORDER BY name;
|
||||
-- name: SearchPayees :many
|
||||
SELECT payees.*, 'payee' as type FROM payees
|
||||
WHERE payees.budget_id = @budget_id
|
||||
AND payees.name LIKE @search
|
||||
AND payees.name ILIKE @search
|
||||
ORDER BY payees.name;
|
||||
--ORDER BY levenshtein(payees.name, $2);
|
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;
|
@ -91,12 +91,12 @@ func (ynab *YNABImport) ImportAssignments(context context.Context, r io.Reader)
|
||||
continue
|
||||
}
|
||||
|
||||
assignment := CreateAssignmentParams{
|
||||
assignment := UpdateAssignmentWithDifferenceParams{
|
||||
Date: date,
|
||||
CategoryID: category.UUID,
|
||||
Amount: amount,
|
||||
}
|
||||
_, err = ynab.queries.CreateAssignment(context, assignment)
|
||||
err = ynab.queries.UpdateAssignmentWithDifference(context, assignment)
|
||||
if err != nil {
|
||||
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,
|
||||
transaction CreateTransactionParams) error {
|
||||
transaction CreateTransactionParams,
|
||||
) error {
|
||||
payeeID, err := ynab.GetPayee(context, payeeName)
|
||||
if err != nil {
|
||||
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,
|
||||
transaction CreateTransactionParams, openTransfers *[]Transfer,
|
||||
account *Account, amount numeric.Numeric) error {
|
||||
account *Account, amount numeric.Numeric,
|
||||
) error {
|
||||
transferToAccountName := payeeName[11:]
|
||||
transferToAccount, err := ynab.GetAccount(context, transferToAccountName)
|
||||
if err != nil {
|
||||
|
@ -39,6 +39,7 @@ type TransactionsResponse struct {
|
||||
type EditAccountRequest struct {
|
||||
Name string `json:"name"`
|
||||
OnBudget bool `json:"onBudget"`
|
||||
IsOpen bool `json:"isOpen"`
|
||||
}
|
||||
|
||||
func (h *Handler) editAccount(c *gin.Context) {
|
||||
@ -59,6 +60,7 @@ func (h *Handler) editAccount(c *gin.Context) {
|
||||
updateParams := postgres.UpdateAccountParams{
|
||||
Name: request.Name,
|
||||
OnBudget: request.OnBudget,
|
||||
IsOpen: request.IsOpen,
|
||||
ID: accountUUID,
|
||||
}
|
||||
account, err := h.Service.UpdateAccount(c.Request.Context(), updateParams)
|
||||
|
@ -28,11 +28,10 @@ func TestRegisterUser(t *testing.T) { //nolint:funlen
|
||||
return
|
||||
}
|
||||
|
||||
tokenVerifier, _ := jwt.NewTokenVerifier("this_is_my_demo_secret_for_unit_tests")
|
||||
h := Handler{
|
||||
Service: database,
|
||||
TokenVerifier: &jwt.TokenVerifier{
|
||||
Secret: "this_is_my_demo_secret_for_unit_tests",
|
||||
},
|
||||
Service: database,
|
||||
TokenVerifier: tokenVerifier,
|
||||
CredentialsVerifier: &bcrypt.Verifier{},
|
||||
}
|
||||
|
||||
|
@ -3,7 +3,6 @@ package server
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.javil.eu/jacob1123/budgeteer/postgres"
|
||||
@ -41,27 +40,6 @@ func NewCategoryWithBalance(category *postgres.GetCategoriesRow) CategoryWithBal
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
budgetID := c.Param("budgetid")
|
||||
budgetUUID, err := uuid.Parse(budgetID)
|
||||
@ -97,8 +75,16 @@ func (h *Handler) budgetingForMonth(c *gin.Context) {
|
||||
|
||||
categoriesWithBalance, moneyUsed := h.calculateBalances(
|
||||
budget, firstOfNextMonth, firstOfMonth, categories, cumultativeBalances)
|
||||
availableBalance := h.getAvailableBalance(budget, moneyUsed, cumultativeBalances, firstOfNextMonth)
|
||||
for i := range categoriesWithBalance {
|
||||
cat := &categoriesWithBalance[i]
|
||||
if cat.ID != budget.IncomeCategoryID {
|
||||
continue
|
||||
}
|
||||
|
||||
availableBalance := h.getAvailableBalance(categories, budget, moneyUsed, cumultativeBalances, firstOfNextMonth)
|
||||
cat.Available = availableBalance
|
||||
cat.AvailableLastMonth = availableBalance
|
||||
}
|
||||
|
||||
data := struct {
|
||||
Categories []CategoryWithBalance
|
||||
@ -107,27 +93,22 @@ func (h *Handler) budgetingForMonth(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, data)
|
||||
}
|
||||
|
||||
func (*Handler) getAvailableBalance(categories []postgres.GetCategoriesRow, budget postgres.Budget,
|
||||
func (*Handler) getAvailableBalance(budget postgres.Budget,
|
||||
moneyUsed numeric.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow,
|
||||
firstOfNextMonth time.Time) numeric.Numeric {
|
||||
availableBalance := numeric.Zero()
|
||||
for _, cat := range categories {
|
||||
if cat.ID != budget.IncomeCategoryID {
|
||||
availableBalance := moneyUsed
|
||||
|
||||
for _, bal := range cumultativeBalances {
|
||||
if bal.CategoryID != budget.IncomeCategoryID {
|
||||
continue
|
||||
}
|
||||
availableBalance = moneyUsed
|
||||
|
||||
for _, bal := range cumultativeBalances {
|
||||
if bal.CategoryID != cat.ID {
|
||||
continue
|
||||
}
|
||||
|
||||
if !bal.Date.Before(firstOfNextMonth) {
|
||||
continue
|
||||
}
|
||||
|
||||
availableBalance = availableBalance.Add(bal.Transactions)
|
||||
if !bal.Date.Before(firstOfNextMonth) {
|
||||
continue
|
||||
}
|
||||
|
||||
availableBalance.AddI(bal.Transactions)
|
||||
availableBalance.AddI(bal.Assignments)
|
||||
}
|
||||
return availableBalance
|
||||
}
|
||||
@ -171,21 +152,18 @@ func (h *Handler) calculateBalances(budget postgres.Budget,
|
||||
cumultativeBalances []postgres.GetCumultativeBalancesRow) ([]CategoryWithBalance, numeric.Numeric) {
|
||||
categoriesWithBalance := []CategoryWithBalance{}
|
||||
|
||||
moneyUsed := numeric.Zero()
|
||||
moneyUsed2 := numeric.Zero()
|
||||
moneyUsed := &moneyUsed2
|
||||
for i := range categories {
|
||||
cat := &categories[i]
|
||||
// do not show hidden categories
|
||||
categoryWithBalance := h.CalculateCategoryBalances(cat, cumultativeBalances,
|
||||
firstOfNextMonth, &moneyUsed, firstOfMonth, budget)
|
||||
|
||||
if cat.ID == budget.IncomeCategoryID {
|
||||
continue
|
||||
}
|
||||
firstOfNextMonth, moneyUsed, firstOfMonth, budget)
|
||||
|
||||
categoriesWithBalance = append(categoriesWithBalance, categoryWithBalance)
|
||||
}
|
||||
|
||||
return categoriesWithBalance, moneyUsed
|
||||
return categoriesWithBalance, *moneyUsed
|
||||
}
|
||||
|
||||
func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow,
|
||||
@ -202,11 +180,11 @@ func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow,
|
||||
continue
|
||||
}
|
||||
|
||||
*moneyUsed = moneyUsed.Sub(bal.Assignments)
|
||||
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Assignments)
|
||||
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Transactions)
|
||||
moneyUsed.SubI(bal.Assignments)
|
||||
categoryWithBalance.Available.AddI(bal.Assignments)
|
||||
categoryWithBalance.Available.AddI(bal.Transactions)
|
||||
if !categoryWithBalance.Available.IsPositive() && bal.Date.Before(firstOfMonth) {
|
||||
*moneyUsed = moneyUsed.Add(categoryWithBalance.Available)
|
||||
moneyUsed.AddI(categoryWithBalance.Available)
|
||||
categoryWithBalance.Available = numeric.Zero()
|
||||
}
|
||||
|
||||
|
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 string
|
||||
}
|
||||
|
||||
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,
|
||||
Amount: amount,
|
||||
}
|
||||
err = h.Service.UpdateAssignment(c.Request.Context(), updateArgs)
|
||||
if err != nil {
|
||||
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("update assignment: %w", err))
|
||||
return
|
||||
}
|
||||
}
|
@ -64,6 +64,7 @@ func (h *Handler) LoadRoutes(router *gin.Engine) {
|
||||
budget.POST("/new", h.newBudget)
|
||||
budget.GET("/:budgetid", h.budgeting)
|
||||
budget.GET("/:budgetid/:year/:month", h.budgetingForMonth)
|
||||
budget.POST("/:budgetid/category/:categoryid/:year/:month", h.setCategoryAssignment)
|
||||
budget.GET("/:budgetid/autocomplete/payees", h.autocompletePayee)
|
||||
budget.GET("/:budgetid/autocomplete/categories", h.autocompleteCategories)
|
||||
budget.DELETE("/:budgetid", h.deleteBudget)
|
||||
|
@ -65,6 +65,12 @@ func (h *Handler) reconcileTransactions(c *gin.Context) {
|
||||
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))
|
||||
|
30
server/util.go
Normal file
30
server/util.go
Normal file
@ -0,0 +1,30 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
17
web/.eslintrc.js
Normal file
17
web/.eslintrc.js
Normal file
@ -0,0 +1,17 @@
|
||||
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/no-unused-vars': 'error'
|
||||
},
|
||||
parser: "vue-eslint-parser",
|
||||
parserOptions: {
|
||||
parser: "@typescript-eslint/parser",
|
||||
sourceType: "module",
|
||||
},
|
||||
};
|
@ -1,13 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite App</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite App</title>
|
||||
</head>
|
||||
<body
|
||||
class="bg-slate-200 text-slate-800 dark:bg-slate-800 dark:text-slate-200 box-border w-full">
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
@ -1,32 +1,44 @@
|
||||
{
|
||||
"name": "web",
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"serve": "vite preview",
|
||||
"build": "vite build",
|
||||
"dev": "vite",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mdi/font": "5.9.55",
|
||||
"@vueuse/core": "^7.6.1",
|
||||
"autoprefixer": "^10.4.2",
|
||||
"file-saver": "^2.0.5",
|
||||
"pinia": "^2.0.11",
|
||||
"postcss": "^8.4.6",
|
||||
"tailwindcss": "^3.0.18",
|
||||
"vue": "^3.2.25",
|
||||
"vue-router": "^4.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/file-saver": "^2.0.5",
|
||||
"@vitejs/plugin-vue": "^2.0.0",
|
||||
"@vue/cli-plugin-babel": "5.0.0-beta.7",
|
||||
"@vue/cli-plugin-typescript": "~4.5.0",
|
||||
"@vue/cli-service": "5.0.0-beta.7",
|
||||
"sass": "^1.38.0",
|
||||
"sass-loader": "^10.0.0",
|
||||
"vite": "^2.7.2",
|
||||
"vue-cli-plugin-vuetify": "~2.4.5"
|
||||
}
|
||||
"name": "web",
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"serve": "vite preview",
|
||||
"build": "vite build",
|
||||
"dev": "vite",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mdi/font": "5.9.55",
|
||||
"@vueuse/core": "^7.6.1",
|
||||
"autoprefixer": "^10.4.2",
|
||||
"file-saver": "^2.0.5",
|
||||
"pinia": "^2.0.11",
|
||||
"postcss": "^8.4.6",
|
||||
"tailwindcss": "^3.0.18",
|
||||
"vue": "^3.2.25",
|
||||
"vue-router": "^4.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/file-saver": "^2.0.5",
|
||||
"@typescript-eslint/parser": "^5.13.0",
|
||||
"@vitejs/plugin-vue": "^2.0.0",
|
||||
"@vue/cli-plugin-babel": "5.0.0-beta.7",
|
||||
"@vue/cli-plugin-typescript": "~4.5.0",
|
||||
"@vue/cli-service": "5.0.0-beta.7",
|
||||
"eslint": "^8.10.0",
|
||||
"eslint-plugin-vue": "^8.5.0",
|
||||
"prettier": "2.5.1",
|
||||
"sass": "^1.38.0",
|
||||
"sass-loader": "^10.0.0",
|
||||
"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 = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
|
6
web/src/@types/shims-vue.d.ts
vendored
6
web/src/@types/shims-vue.d.ts
vendored
@ -1,5 +1,5 @@
|
||||
declare module "*.vue" {
|
||||
import { defineComponent } from "vue";
|
||||
const component: ReturnType<typeof defineComponent>;
|
||||
export default component;
|
||||
import { defineComponent } from "vue";
|
||||
const component: ReturnType<typeof defineComponent>;
|
||||
export default component;
|
||||
}
|
@ -8,7 +8,6 @@ import { useSettingsStore } from "./stores/settings";
|
||||
export default defineComponent({
|
||||
computed: {
|
||||
...mapState(useBudgetsStore, ["CurrentBudgetName"]),
|
||||
...mapState(useSettingsStore, ["Menu"]),
|
||||
...mapState(useSessionStore, ["LoggedIn"]),
|
||||
},
|
||||
methods: {
|
||||
@ -27,39 +26,50 @@ export default defineComponent({
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="box-border w-full">
|
||||
<div class="flex bg-gray-400 p-4 m-2 rounded-lg">
|
||||
<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>
|
||||
<div class="flex flex-col md:flex-row flex-1 h-screen">
|
||||
<router-view name="sidebar" />
|
||||
|
||||
<span class="flex-1">{{ CurrentBudgetName }}</span>
|
||||
<div class="flex-1 overflow-auto">
|
||||
<div
|
||||
class="flex bg-gray-400 dark:bg-gray-600 p-4 fixed md: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>
|
||||
|
||||
<div class="flex flex-1 flex-row justify-end -mx-4">
|
||||
<router-link class="mx-4" v-if="LoggedIn" to="/dashboard">Dashboard</router-link>
|
||||
<router-link class="mx-4" v-if="!LoggedIn" to="/login">Login</router-link>
|
||||
<a class="mx-4" v-if="LoggedIn" @click="logout">Logout</a>
|
||||
</div>
|
||||
<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>
|
||||
|
||||
<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 class="p-3 pl-6">
|
||||
<router-view />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</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";
|
||||
|
||||
export const BASE_URL = "/api/v1"
|
||||
export const BASE_URL = "/api/v1";
|
||||
|
||||
export function GET(path: string) {
|
||||
const sessionStore = useSessionStore();
|
||||
return fetch(BASE_URL + path, {
|
||||
headers: sessionStore.AuthHeaders,
|
||||
})
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function POST(path: string, body: FormData | string | null) {
|
||||
const sessionStore = useSessionStore();
|
||||
@ -15,12 +15,12 @@ export function POST(path: string, body: FormData | string | null) {
|
||||
method: "POST",
|
||||
headers: sessionStore.AuthHeaders,
|
||||
body: body,
|
||||
})
|
||||
});
|
||||
}
|
||||
export function DELETE(path: string) {
|
||||
const sessionStore = useSessionStore();
|
||||
return fetch(BASE_URL + path, {
|
||||
method: "DELETE",
|
||||
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 { GET } from "../api";
|
||||
import { useBudgetsStore } from "../stores/budget";
|
||||
import Input from "./Input.vue";
|
||||
|
||||
export interface Suggestion {
|
||||
ID: string
|
||||
@ -10,9 +11,9 @@ export interface Suggestion {
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
text: String,
|
||||
id: String | undefined,
|
||||
model: String,
|
||||
text: string,
|
||||
id: string | undefined,
|
||||
model: string,
|
||||
type?: string | undefined,
|
||||
}>();
|
||||
|
||||
@ -43,22 +44,25 @@ function load(text: String) {
|
||||
});
|
||||
};
|
||||
function keypress(e: KeyboardEvent) {
|
||||
if (e.key == "Enter") {
|
||||
const selected = Suggestions.value[0];
|
||||
selectElement(selected);
|
||||
const el = (<HTMLInputElement>e.target);
|
||||
const inputElements = Array.from(el.ownerDocument.querySelectorAll('input:not([disabled]):not([readonly])'));
|
||||
const currentIndex = inputElements.indexOf(el);
|
||||
const nextElement = inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0];
|
||||
(<HTMLInputElement>nextElement).focus();
|
||||
}
|
||||
if (e.key != "Enter")
|
||||
return;
|
||||
|
||||
const selected = Suggestions.value[0];
|
||||
selectElement(selected);
|
||||
const el = (<HTMLInputElement>e.target);
|
||||
const inputElements = Array.from(el.ownerDocument.querySelectorAll('input:not([disabled]):not([readonly])'));
|
||||
const currentIndex = inputElements.indexOf(el);
|
||||
const nextElement = inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0];
|
||||
(<HTMLInputElement>nextElement).focus();
|
||||
};
|
||||
|
||||
function selectElement(element: Suggestion) {
|
||||
emit('update:id', element.ID);
|
||||
emit('update:text', element.Name);
|
||||
emit('update:type', element.Type);
|
||||
Suggestions.value = [];
|
||||
};
|
||||
|
||||
function select(e: MouseEvent) {
|
||||
const target = (<HTMLInputElement>e.target);
|
||||
const valueAttribute = target.attributes.getNamedItem("value");
|
||||
@ -68,6 +72,7 @@ function select(e: MouseEvent) {
|
||||
const selected = Suggestions.value.filter(x => x.ID == selectedID)[0];
|
||||
selectElement(selected);
|
||||
};
|
||||
|
||||
function clear() {
|
||||
emit('update:id', null);
|
||||
emit('update:text', SearchQuery.value);
|
||||
@ -76,21 +81,30 @@ function clear() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<input
|
||||
class="border-b-2 border-black"
|
||||
@keypress="keypress"
|
||||
v-if="id == undefined"
|
||||
v-model="SearchQuery"
|
||||
/>
|
||||
<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
|
||||
v-for="suggestion in Suggestions"
|
||||
class="block"
|
||||
@click="select"
|
||||
:value="suggestion.ID"
|
||||
>{{ suggestion.Name }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<Input
|
||||
v-if="id == undefined"
|
||||
v-model="SearchQuery"
|
||||
type="text"
|
||||
class="border-b-2 border-black"
|
||||
@keypress="keypress"
|
||||
/>
|
||||
<span
|
||||
v-if="id != undefined"
|
||||
class="bg-gray-300 dark:bg-gray-700"
|
||||
@click="clear"
|
||||
>{{ text }}</span>
|
||||
<div
|
||||
v-if="Suggestions.length > 0"
|
||||
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>
|
@ -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>
|
||||
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));
|
||||
|
||||
@ -11,5 +15,8 @@ const formattedValue = computed(() => internalValue.value.toLocaleString(undefin
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="text-right" :class="internalValue < 0 ? 'negative' : ''">{{ formattedValue }} €</span>
|
||||
<span
|
||||
class="text-right"
|
||||
:class="internalValue < 0 ? (negativeClass ?? 'negative') : positiveClass"
|
||||
>{{ formattedValue }} €</span>
|
||||
</template>
|
@ -1,8 +1,13 @@
|
||||
<script lang="ts" setup>
|
||||
const props = defineProps(["modelValue"]);
|
||||
import Input from './Input.vue';
|
||||
const props = defineProps<{
|
||||
modelValue?: Date
|
||||
}>();
|
||||
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
|
||||
//return new Date(d.getTime() - (d.getTimezoneOffset() * 60 * 1000)).toISOString().split('T')[0];
|
||||
return d.toISOString().split('T')[0];
|
||||
@ -23,10 +28,10 @@ function selectAll(event: FocusEvent) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input
|
||||
type="date"
|
||||
<Input
|
||||
ref="input"
|
||||
v-bind:value="dateToYYYYMMDD(modelValue)"
|
||||
type="date"
|
||||
:value="dateToYYYYMMDD(modelValue)"
|
||||
@input="updateValue"
|
||||
@focus="selectAll"
|
||||
/>
|
||||
|
17
web/src/components/Input.vue
Normal file
17
web/src/components/Input.vue
Normal file
@ -0,0 +1,17 @@
|
||||
<script lang="ts" setup>
|
||||
const props = defineProps<{
|
||||
modelValue?: number | string
|
||||
}>();
|
||||
|
||||
const emits = defineEmits<{
|
||||
(e: "update:modelValue", value: number | string): void
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<input
|
||||
:value="modelValue"
|
||||
class="dark:bg-slate-900"
|
||||
@input="emits('update:modelValue', ($event.target as HTMLInputElement)?.value)"
|
||||
>
|
||||
</template>
|
@ -1,13 +1,13 @@
|
||||
<script lang="ts" setup>
|
||||
import Card from '../components/Card.vue';
|
||||
import RowCard from './RowCard.vue';
|
||||
import { ref } from "vue";
|
||||
|
||||
const props = defineProps<{
|
||||
buttonText: string,
|
||||
buttonText?: string,
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'submit'): void,
|
||||
(e: 'submit', event : {cancel:boolean}): boolean,
|
||||
(e: 'open'): void,
|
||||
}>();
|
||||
|
||||
@ -20,39 +20,58 @@ function openDialog() {
|
||||
visible.value = true;
|
||||
};
|
||||
function submitDialog() {
|
||||
const e = {cancel: false};
|
||||
emit("submit", e);
|
||||
if(e.cancel)
|
||||
return;
|
||||
|
||||
visible.value = false;
|
||||
emit("submit");
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button @click="openDialog">
|
||||
<slot name="placeholder">
|
||||
<Card>
|
||||
<p class="w-24 text-center text-6xl">+</p>
|
||||
<span class="text-lg" dark>{{ buttonText }}</span>
|
||||
</Card>
|
||||
</slot>
|
||||
</button>
|
||||
<button @click="openDialog">
|
||||
<slot name="placeholder">
|
||||
<RowCard>
|
||||
<p class="w-24 text-center text-6xl">
|
||||
+
|
||||
</p>
|
||||
<span
|
||||
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
|
||||
v-if="visible"
|
||||
class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full"
|
||||
class="relative top-20 mx-auto p-5 w-96 shadow-lg rounded-md bg-white dark:bg-black"
|
||||
>
|
||||
<div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
|
||||
<div class="mt-3 text-center">
|
||||
<h3 class="mt-3 text-lg leading-6 font-medium text-gray-900">{{ buttonText }}</h3>
|
||||
<slot></slot>
|
||||
<div class="grid grid-cols-2 gap-6">
|
||||
<button
|
||||
@click="closeDialog"
|
||||
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"
|
||||
>Close</button>
|
||||
<button
|
||||
@click="submitDialog"
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3 text-center">
|
||||
<h3
|
||||
class="mt-3 text-lg leading-6 font-medium text-gray-900 dark:text-gray-100"
|
||||
>
|
||||
{{ buttonText }}
|
||||
</h3>
|
||||
<slot />
|
||||
<div class="grid grid-cols-2 gap-6">
|
||||
<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="closeDialog"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
<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>
|
||||
</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,6 +3,9 @@ import { computed, ref } from "vue";
|
||||
import Autocomplete from './Autocomplete.vue'
|
||||
import { useAccountStore } from '../stores/budget-account'
|
||||
import DateInput from "./DateInput.vue";
|
||||
import { useTransactionsStore } from "../stores/transactions";
|
||||
import Input from "./Input.vue";
|
||||
import Button from "./SimpleButton.vue";
|
||||
|
||||
const props = defineProps<{
|
||||
transactionid: string
|
||||
@ -10,8 +13,8 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits(["save"]);
|
||||
|
||||
const accountStore = useAccountStore();
|
||||
const TX = accountStore.Transactions.get(props.transactionid)!;
|
||||
const transactionsStore = useTransactionsStore();
|
||||
const TX = transactionsStore.Transactions.get(props.transactionid)!;
|
||||
const payeeType = ref<string|undefined>(undefined);
|
||||
|
||||
const payload = computed(() => JSON.stringify({
|
||||
@ -29,35 +32,56 @@ const payload = computed(() => JSON.stringify({
|
||||
|
||||
function saveTransaction(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
accountStore.editTransaction(TX.ID, payload.value);
|
||||
transactionsStore.editTransaction(TX.ID, payload.value);
|
||||
emit('save');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<tr>
|
||||
<td style="width: 90px;" class="text-sm">
|
||||
<DateInput class="border-b-2 border-black" v-model="TX.Date" />
|
||||
</td>
|
||||
<td style="max-width: 150px;">
|
||||
<Autocomplete v-model:text="TX.Payee" v-model:id="TX.PayeeID" v-model:type="payeeType" model="payees" />
|
||||
</td>
|
||||
<td style="max-width: 200px;">
|
||||
<Autocomplete v-model:text="TX.Category" v-model:id="TX.CategoryID" model="categories" />
|
||||
</td>
|
||||
<td>
|
||||
<input class="block w-full border-b-2 border-black" type="text" v-model="TX.Memo" />
|
||||
</td>
|
||||
<td style="width: 80px;" class="text-right">
|
||||
<input
|
||||
class="text-right block w-full border-b-2 border-black"
|
||||
type="currency"
|
||||
v-model="TX.Amount"
|
||||
/>
|
||||
</td>
|
||||
<td style="width: 20px;">
|
||||
<input type="submit" @click="saveTransaction" value="Save" />
|
||||
</td>
|
||||
<td style="width: 20px;"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-sm">
|
||||
<DateInput
|
||||
v-model="TX.Date"
|
||||
class="border-b-2 border-black"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<Autocomplete
|
||||
v-model:text="TX.Payee"
|
||||
v-model:id="TX.PayeeID"
|
||||
v-model:type="payeeType"
|
||||
model="payees"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<Autocomplete
|
||||
v-model:text="TX.Category"
|
||||
v-model:id="TX.CategoryID"
|
||||
model="categories"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<Input
|
||||
v-model="TX.Memo"
|
||||
class="block w-full border-b-2 border-black"
|
||||
type="text"
|
||||
/>
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<Input
|
||||
v-model="TX.Amount"
|
||||
class="text-right block w-full border-b-2 border-black"
|
||||
type="currency"
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<Button
|
||||
class="bg-blue-500"
|
||||
@click="saveTransaction"
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
</td>
|
||||
<td />
|
||||
</tr>
|
||||
</template>
|
@ -1,8 +1,10 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref } from "vue";
|
||||
import Autocomplete, { Suggestion } from '../components/Autocomplete.vue'
|
||||
import { Transaction, useAccountStore } from '../stores/budget-account'
|
||||
import Autocomplete from '../components/Autocomplete.vue'
|
||||
import { Transaction, useTransactionsStore } from "../stores/transactions";
|
||||
import DateInput from "./DateInput.vue";
|
||||
import Button from "./SimpleButton.vue";
|
||||
import Input from "./Input.vue";
|
||||
|
||||
const props = defineProps<{
|
||||
budgetid: string
|
||||
@ -22,6 +24,7 @@ const TX = ref<Transaction>({
|
||||
ID: "",
|
||||
Status: "Uncleared",
|
||||
TransferAccount: "",
|
||||
Reconciled: false
|
||||
});
|
||||
|
||||
const payeeType = ref<string|undefined>(undefined);
|
||||
@ -41,37 +44,67 @@ const payload = computed(() => JSON.stringify({
|
||||
state: "Uncleared"
|
||||
}));
|
||||
|
||||
const accountStore = useAccountStore();
|
||||
const transactionsStore = useTransactionsStore();
|
||||
function saveTransaction(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
accountStore.saveTransaction(payload.value);
|
||||
Save();
|
||||
}
|
||||
|
||||
function Save() {
|
||||
transactionsStore.saveTransaction(payload.value);
|
||||
}
|
||||
|
||||
defineExpose({Save});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<tr>
|
||||
<td style="width: 90px;" class="text-sm">
|
||||
<DateInput class="border-b-2 border-black" v-model="TX.Date" />
|
||||
</td>
|
||||
<td style="max-width: 150px;">
|
||||
<Autocomplete v-model:text="TX.Payee" v-model:id="TX.PayeeID" v-model:type="payeeType" model="payees" />
|
||||
</td>
|
||||
<td style="max-width: 200px;">
|
||||
<Autocomplete v-model:text="TX.Category" v-model:id="TX.CategoryID" model="categories" />
|
||||
</td>
|
||||
<td>
|
||||
<input class="block w-full border-b-2 border-black" type="text" v-model="TX.Memo" />
|
||||
</td>
|
||||
<td style="width: 80px;" class="text-right">
|
||||
<input
|
||||
class="text-right block w-full border-b-2 border-black"
|
||||
type="currency"
|
||||
v-model="TX.Amount"
|
||||
/>
|
||||
</td>
|
||||
<td style="width: 20px;">
|
||||
<input type="submit" @click="saveTransaction" value="Save" />
|
||||
</td>
|
||||
<td style="width: 20px;"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<label class="md:hidden">Date</label>
|
||||
<td class="text-sm">
|
||||
<DateInput
|
||||
v-model="TX.Date"
|
||||
class="border-b-2 border-black"
|
||||
/>
|
||||
</td>
|
||||
<label class="md:hidden">Payee</label>
|
||||
<td>
|
||||
<Autocomplete
|
||||
v-model:text="TX.Payee"
|
||||
v-model:id="TX.PayeeID"
|
||||
v-model:type="payeeType"
|
||||
model="payees"
|
||||
/>
|
||||
</td>
|
||||
<label class="md:hidden">Category</label>
|
||||
<td>
|
||||
<Autocomplete
|
||||
v-model:text="TX.Category"
|
||||
v-model:id="TX.CategoryID"
|
||||
model="categories"
|
||||
/>
|
||||
</td>
|
||||
<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,50 +1,100 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref } from "vue";
|
||||
import { useBudgetsStore } from "../stores/budget";
|
||||
import { Transaction, useAccountStore } from "../stores/budget-account";
|
||||
import { useTransactionsStore } from "../stores/transactions";
|
||||
import Currency from "./Currency.vue";
|
||||
import TransactionEditRow from "./TransactionEditRow.vue";
|
||||
import { formatDate } from "../date";
|
||||
import { useAccountStore } from "../stores/budget-account";
|
||||
import Input from "./Input.vue";
|
||||
import Checkbox from "./Checkbox.vue";
|
||||
|
||||
const props = defineProps<{
|
||||
transaction: Transaction,
|
||||
transactionid: string,
|
||||
index: number,
|
||||
}>();
|
||||
|
||||
const edit = ref(false);
|
||||
|
||||
const CurrentBudgetID = computed(() => useBudgetsStore().CurrentBudgetID);
|
||||
const Reconciling = computed(() => useAccountStore().Reconciling);
|
||||
const Reconciling = computed(() => useTransactionsStore().Reconciling);
|
||||
|
||||
const transactionsStore = useTransactionsStore();
|
||||
const TX = transactionsStore.Transactions.get(props.transactionid)!;
|
||||
|
||||
function dateChanged() {
|
||||
const currentAccount = useAccountStore().CurrentAccount;
|
||||
if (currentAccount == null)
|
||||
return true;
|
||||
const transactionIndex = currentAccount.Transactions.indexOf(props.transactionid);
|
||||
if(transactionIndex<=0)
|
||||
return true;
|
||||
|
||||
const previousTransactionId = currentAccount.Transactions[transactionIndex-1];
|
||||
const previousTransaction = transactionsStore.Transactions.get(previousTransactionId);
|
||||
return TX.Date.getTime() != previousTransaction?.Date.getTime();
|
||||
}
|
||||
|
||||
function getStatusSymbol() {
|
||||
if(TX.Status == "Reconciled")
|
||||
return "✔";
|
||||
|
||||
if(TX.Status == "Uncleared")
|
||||
return "*";
|
||||
|
||||
return "✘";
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<tr
|
||||
v-if="!edit"
|
||||
class="{{new Date(transaction.Date) > new Date() ? 'future' : ''}}"
|
||||
:class="[index % 6 < 3 ? 'bg-gray-300' : 'bg-gray-100']"
|
||||
>
|
||||
<!--:class="[index % 6 < 3 ? index % 6 === 1 ? 'bg-gray-400' : 'bg-gray-300' : index % 6 !== 4 ? 'bg-gray-100' : '']">-->
|
||||
<td>{{ formatDate(transaction.Date) }}</td>
|
||||
<td>{{ transaction.TransferAccount ? "Transfer : " + transaction.TransferAccount : transaction.Payee }}</td>
|
||||
<td>{{ transaction.CategoryGroup ? transaction.CategoryGroup + " : " + transaction.Category : "" }}</td>
|
||||
<td>
|
||||
<a
|
||||
:href="'/budget/' + CurrentBudgetID + '/transaction/' + transaction.ID"
|
||||
>{{ transaction.Memo }}</a>
|
||||
</td>
|
||||
<td>
|
||||
<Currency class="block" :value="transaction.Amount" />
|
||||
</td>
|
||||
<td>{{ transaction.Status == "Reconciled" ? "✔" : (transaction.Status == "Uncleared" ? "" : "*") }}</td>
|
||||
<td class="text-right">
|
||||
{{ transaction.GroupID ? "☀" : "" }}
|
||||
<a @click="edit = true;">✎</a>
|
||||
</td>
|
||||
<td v-if="Reconciling && transaction.Status != 'Reconciled'">
|
||||
<input type="checkbox" v-model="transaction.Reconciled" />
|
||||
</td>
|
||||
</tr>
|
||||
<TransactionEditRow v-if="edit" :transactionid="transaction.ID" @save="edit = false" />
|
||||
<tr v-if="dateChanged()" 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">
|
||||
{{ formatDate(TX.Date) }}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr
|
||||
v-if="!edit"
|
||||
class="{{new Date(TX.Date) > new Date() ? 'future' : ''}}"
|
||||
:class="[index % 6 < 3 ? 'md:bg-gray-300 dark:md:bg-gray-700' : 'md:bg-gray-100 dark:md:bg-gray-900']"
|
||||
>
|
||||
<!--:class="[index % 6 < 3 ? index % 6 === 1 ? 'bg-gray-400' : 'bg-gray-300' : index % 6 !== 4 ? 'bg-gray-100' : '']">-->
|
||||
<td class="hidden md:block">
|
||||
{{ formatDate(TX.Date) }}
|
||||
</td>
|
||||
<td class="pl-2 md:pl-0">
|
||||
{{ TX.TransferAccount ? "Transfer : " + TX.TransferAccount : TX.Payee }}
|
||||
</td>
|
||||
<td>
|
||||
{{ TX.CategoryGroup ? TX.CategoryGroup + " : " + TX.Category : "" }}
|
||||
</td>
|
||||
<td>
|
||||
<a
|
||||
:href="'/budget/' + CurrentBudgetID + '/transaction/' + TX.ID"
|
||||
>{{ TX.Memo }}</a>
|
||||
</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"
|
||||
@save="edit = false"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
|
@ -1,5 +1,6 @@
|
||||
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",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
|
@ -2,43 +2,84 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import Modal from '../components/Modal.vue';
|
||||
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 CurrentAccount = computed(() => accountStore.CurrentAccount);
|
||||
|
||||
const accountName = ref("");
|
||||
const accountOnBudget = ref(true);
|
||||
const accountOpen = ref(true);
|
||||
const error = ref("");
|
||||
|
||||
function editAccount(e : any) {
|
||||
accountStore.EditAccount(CurrentAccount.value?.ID ?? "", accountName.value, accountOnBudget.value);
|
||||
function editAccount(e : {cancel:boolean}) : boolean {
|
||||
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) {
|
||||
accountName.value = CurrentAccount.value?.Name ?? "";
|
||||
accountOnBudget.value = CurrentAccount.value?.OnBudget ?? true;
|
||||
accountOpen.value = CurrentAccount.value?.IsOpen ?? true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal button-text="Edit Account" @open="openEditAccount" @submit="editAccount">
|
||||
<template v-slot:placeholder>✎</template>
|
||||
<div class="mt-2 px-7 py-3">
|
||||
<input
|
||||
class="border-2"
|
||||
type="text"
|
||||
v-model="accountName"
|
||||
placeholder="Account name"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="mt-2 px-7 py-3">
|
||||
<input
|
||||
class="border-2"
|
||||
type="checkbox"
|
||||
v-model="accountOnBudget"
|
||||
required
|
||||
/>
|
||||
<label>On Budget</label>
|
||||
</div>
|
||||
</Modal>
|
||||
<Modal
|
||||
button-text="Edit Account"
|
||||
@open="openEditAccount"
|
||||
@submit="editAccount"
|
||||
>
|
||||
<template #placeholder>
|
||||
<span class="ml-2">✎</span>
|
||||
</template>
|
||||
<div class="mt-2 px-7 py-3">
|
||||
<Input
|
||||
v-model="accountName"
|
||||
class="border-2 dark:border-gray-700"
|
||||
type="text"
|
||||
placeholder="Account name"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="mt-2 px-7 py-3">
|
||||
<Checkbox
|
||||
v-model="accountOnBudget"
|
||||
class="border-2"
|
||||
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 { ref } from "vue";
|
||||
import { useBudgetsStore } from '../stores/budget';
|
||||
import Input from '../components/Input.vue';
|
||||
|
||||
const budgetName = ref("");
|
||||
function saveBudget() {
|
||||
@ -10,9 +11,18 @@ function saveBudget() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal button-text="New Budget" @submit="saveBudget">
|
||||
<Modal
|
||||
button-text="New Budget"
|
||||
@submit="saveBudget"
|
||||
>
|
||||
<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>
|
||||
</Modal>
|
||||
</template>
|
@ -3,9 +3,15 @@
|
||||
@tailwind utilities;
|
||||
|
||||
h1 {
|
||||
font-size: 200%;
|
||||
font-size: 200%;
|
||||
}
|
||||
|
||||
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 App from './App.vue'
|
||||
import './index.css'
|
||||
import router from './router'
|
||||
import { createPinia } from 'pinia'
|
||||
import { useBudgetsStore } from './stores/budget';
|
||||
import { useAccountStore } from './stores/budget-account'
|
||||
import PiniaLogger from './pinia-logger'
|
||||
import { createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import "./index.css";
|
||||
import router from "./router";
|
||||
import { createPinia } from "pinia";
|
||||
import { useBudgetsStore } from "./stores/budget";
|
||||
import { useAccountStore } from "./stores/budget-account";
|
||||
import PiniaLogger from "./pinia-logger";
|
||||
import { useSessionStore } from "./stores/session";
|
||||
|
||||
const app = createApp(App)
|
||||
app.use(router)
|
||||
const app = createApp(App);
|
||||
app.use(router);
|
||||
|
||||
const pinia = createPinia()
|
||||
pinia.use(PiniaLogger())
|
||||
app.use(pinia)
|
||||
app.mount('#app')
|
||||
const pinia = createPinia();
|
||||
pinia.use(
|
||||
PiniaLogger({
|
||||
expanded: false,
|
||||
showDuration: true,
|
||||
})
|
||||
);
|
||||
app.use(pinia);
|
||||
app.mount("#app");
|
||||
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
const budgetStore = useBudgetsStore();
|
||||
await budgetStore.SetCurrentBudget((<string>to.params.budgetid));
|
||||
const budgetStore = useBudgetsStore();
|
||||
await budgetStore.SetCurrentBudget(<string>to.params.budgetid);
|
||||
|
||||
const accountStore = useAccountStore();
|
||||
await accountStore.SetCurrentAccount((<string>to.params.budgetid), (<string>to.params.accountid));
|
||||
next();
|
||||
})
|
||||
const accountStore = useAccountStore();
|
||||
await accountStore.SetCurrentAccount(
|
||||
<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,97 +5,169 @@ 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/Button.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";
|
||||
|
||||
defineProps<{
|
||||
budgetid: string
|
||||
accountid: string
|
||||
}>()
|
||||
|
||||
const modalInputRow = ref<typeof TransactionInputRow | null>(null);
|
||||
|
||||
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;
|
||||
accounts.SetReconciledForAllTransactions(target.checked);
|
||||
transactions.SetReconciledForAllTransactions(target.checked);
|
||||
}
|
||||
|
||||
function cancelReconcilation() {
|
||||
accounts.SetReconciledForAllTransactions(false);
|
||||
accounts.Reconciling = false;
|
||||
transactions.SetReconciledForAllTransactions(false);
|
||||
transactions.Reconciling = false;
|
||||
}
|
||||
|
||||
function submitReconcilation() {
|
||||
accounts.SubmitReconcilation(0);
|
||||
accounts.Reconciling = false;
|
||||
transactions.SubmitReconcilation(0);
|
||||
transactions.Reconciling = false;
|
||||
}
|
||||
|
||||
function createReconcilationTransaction() {
|
||||
const diff = TargetReconcilingBalance.value - accounts.ReconcilingBalance ;
|
||||
accounts.SubmitReconcilation(diff);
|
||||
accounts.Reconciling = false;
|
||||
const diff = TargetReconcilingBalance.value - transactions.ReconcilingBalance;
|
||||
transactions.SubmitReconcilation(diff);
|
||||
transactions.Reconciling = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1 class="inline">{{ accounts.CurrentAccount?.Name }}</h1>
|
||||
<EditAccount />
|
||||
<br />
|
||||
<div class="grid grid-cols-[1fr_auto]">
|
||||
<div>
|
||||
<h1 class="inline">
|
||||
{{ accounts.CurrentAccount?.Name }}
|
||||
</h1>
|
||||
<EditAccount />
|
||||
</div>
|
||||
|
||||
<span>
|
||||
Current Balance:
|
||||
<div
|
||||
class="text-right flex flex-wrap flex-col md:flex-row justify-end gap-2 max-w-sm"
|
||||
>
|
||||
<span class="rounded-lg p-1 whitespace-nowrap flex-1">
|
||||
Working:
|
||||
<Currency :value="accounts.CurrentAccount?.WorkingBalance" />
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<span>
|
||||
Cleared Balance:
|
||||
<span class="rounded-lg p-1 whitespace-nowrap flex-1">
|
||||
Cleared:
|
||||
<Currency :value="accounts.CurrentAccount?.ClearedBalance" />
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<span v-if="accounts.Reconciling" class="border-2 block bg-gray-200 rounded-lg p-2">
|
||||
Is <Currency :value="accounts.ReconcilingBalance" /> your current balance?
|
||||
<Button
|
||||
class="bg-blue-500 mx-3"
|
||||
@click="submitReconcilation">Yes!</Button>
|
||||
<br />
|
||||
|
||||
No, it's: <input class="text-right" type="number" v-model="TargetReconcilingBalance" />
|
||||
Difference: <Currency :value="accounts.ReconcilingBalance - TargetReconcilingBalance" />
|
||||
<Button
|
||||
class="bg-orange-500 mx-3"
|
||||
v-if="Math.abs(accounts.ReconcilingBalance - TargetReconcilingBalance) > 0.01"
|
||||
@click="createReconcilationTransaction"
|
||||
>Create reconciling Transaction</Button>
|
||||
<Button
|
||||
class="bg-red-500 mx-3"
|
||||
@click="cancelReconcilation"
|
||||
>Cancel</Button>
|
||||
</span>
|
||||
<span v-if="!accounts.Reconciling">
|
||||
Reconciled Balance:
|
||||
<span
|
||||
v-if="!transactions.Reconciling"
|
||||
class="rounded-lg bg-blue-500 p-1 whitespace-nowrap flex-1"
|
||||
@click="transactions.Reconciling = true"
|
||||
>
|
||||
Reconciled:
|
||||
<Currency :value="accounts.CurrentAccount?.ReconciledBalance" />
|
||||
<Button class="bg-blue-500" @click="accounts.Reconciling = true" v-if="!accounts.Reconciling">Reconcile</Button>
|
||||
</span>
|
||||
<table>
|
||||
<tr class="font-bold">
|
||||
<td 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: 20px;"></td>
|
||||
<td style="width: 40px;"></td>
|
||||
<td style="width: 20px;" v-if="accounts.Reconciling">
|
||||
<input type="checkbox" @input="setReconciled" />
|
||||
</td>
|
||||
</tr>
|
||||
<TransactionInputRow :budgetid="budgetid" :accountid="accountid" />
|
||||
<TransactionRow
|
||||
v-for="(transaction, index) in accounts.TransactionsList" :key="transaction.ID"
|
||||
:transaction="transaction"
|
||||
:index="index"
|
||||
</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"
|
||||
/>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
<TransactionInputRow
|
||||
class="hidden md:table-row"
|
||||
:budgetid="budgetid"
|
||||
:accountid="accountid"
|
||||
/>
|
||||
<TransactionRow
|
||||
v-for="(transaction, index) in transactions.TransactionsList"
|
||||
:key="transaction.ID"
|
||||
:transactionid="transaction.ID"
|
||||
:index="index"
|
||||
/>
|
||||
</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="grid grid-cols-2"
|
||||
:budgetid="budgetid"
|
||||
:accountid="accountid"
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
|
@ -8,9 +8,9 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Danger Zone</h1>
|
||||
<div class="budget-item">
|
||||
<button>Clear database</button>
|
||||
<p>This removes all data and starts from scratch. Not undoable!</p>
|
||||
</div>
|
||||
<h1>Danger Zone</h1>
|
||||
<div class="budget-item">
|
||||
<button>Clear database</button>
|
||||
<p>This removes all data and starts from scratch. Not undoable!</p>
|
||||
</div>
|
||||
</template>
|
@ -1,11 +1,14 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed } from "vue";
|
||||
import Currency from "../components/Currency.vue"
|
||||
import { useBudgetsStore } from "../stores/budget"
|
||||
import { useAccountStore } from "../stores/budget-account"
|
||||
import { useSettingsStore } from "../stores/settings"
|
||||
import Currency from "../components/Currency.vue";
|
||||
import { useBudgetsStore } from "../stores/budget";
|
||||
import { Account, useAccountStore } from "../stores/budget-account";
|
||||
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 CurrentBudgetName = computed(() => budgetStore.CurrentBudgetName);
|
||||
@ -19,48 +22,84 @@ const OffBudgetAccountsBalance = computed(() => accountStore.OffBudgetAccountsBa
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col">
|
||||
<span class="m-1 p-1 px-3 text-xl">
|
||||
<router-link to="/dashboard">⌂</router-link>
|
||||
{{CurrentBudgetName}}
|
||||
</span>
|
||||
<span class="bg-orange-200 rounded-lg m-1 p-1 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+'/all-accounts'">All Accounts</router-link>-->
|
||||
</span>
|
||||
<li class="bg-orange-200 rounded-lg m-1 p-1 px-3">
|
||||
<div
|
||||
:class="[ExpandMenu ? 'md:w-72' : 'md:w-36', ShowMenu ? '' : 'hidden']"
|
||||
class="md:block flex-shrink-0 w-full bg-gray-500 border-r-4 border-black"
|
||||
>
|
||||
<div class="flex flex-col mt-14 md:mt-0">
|
||||
<span
|
||||
class="m-2 p-1 px-3 h-10 overflow-hidden"
|
||||
:class="[ExpandMenu ? 'text-2xl' : 'text-md']"
|
||||
>
|
||||
<router-link
|
||||
to="/dashboard"
|
||||
style="font-size: 150%"
|
||||
>⌂</router-link>
|
||||
{{ CurrentBudgetName }}
|
||||
</span>
|
||||
<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+'/all-accounts'">All Accounts</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'"
|
||||
:value="OnBudgetAccountsBalance"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-for="account in OnBudgetAccounts"
|
||||
:key="account.ID"
|
||||
class="flex flex-row justify-between"
|
||||
>
|
||||
<AccountWithReconciled :account="account" />
|
||||
<Currency
|
||||
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
|
||||
: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'"
|
||||
:value="OffBudgetAccountsBalance"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-for="account in OffBudgetAccounts"
|
||||
:key="account.ID"
|
||||
class="flex flex-row justify-between"
|
||||
>
|
||||
<AccountWithReconciled :account="account" />
|
||||
<Currency
|
||||
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
|
||||
: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">
|
||||
<span>On-Budget Accounts</span>
|
||||
<Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="OnBudgetAccountsBalance" />
|
||||
<span>Closed Accounts</span>
|
||||
</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.ClearedBalance" />
|
||||
</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.ClearedBalance" />
|
||||
</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
|
||||
</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="/admin">Admin</router-link></li>-->
|
||||
-->
|
||||
<!--<li>
|
||||
<router-link :to="'/budget/'+CurrentBudgetID+'/accounts'">Edit accounts</router-link>
|
||||
</li>-->
|
||||
<li class="bg-red-100 dark:bg-slate-600 my-2 p-2 px-3">
|
||||
<router-link :to="'/budget/' + CurrentBudgetID + '/settings'">
|
||||
Budget-Settings
|
||||
</router-link>
|
||||
</li>
|
||||
<!--<li><router-link to="/admin">Admin</router-link></li>-->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
@ -2,8 +2,10 @@
|
||||
import { computed, defineProps, onMounted, ref, watchEffect } from "vue";
|
||||
import Currency from "../components/Currency.vue";
|
||||
import { useBudgetsStore } from "../stores/budget";
|
||||
import { useAccountStore } from "../stores/budget-account";
|
||||
import { Category, useAccountStore } from "../stores/budget-account";
|
||||
import { useSessionStore } from "../stores/session";
|
||||
import Input from "../components/Input.vue";
|
||||
import { POST } from "../api";
|
||||
|
||||
const props = defineProps<{
|
||||
budgetid: string,
|
||||
@ -17,7 +19,7 @@ const CurrentBudgetID = computed(() => budgetsStore.CurrentBudgetID);
|
||||
const accountStore = useAccountStore();
|
||||
const categoriesForMonth = accountStore.CategoriesForMonthAndGroup;
|
||||
|
||||
function GetCategories(group : string) {
|
||||
function GetCategories(group: string) {
|
||||
return [...categoriesForMonth(selected.value.Year, selected.value.Month, group)];
|
||||
};
|
||||
|
||||
@ -28,20 +30,20 @@ const GroupsForMonth = computed(() => {
|
||||
|
||||
|
||||
const previous = computed(() => ({
|
||||
Year: new Date(selected.value.Year, selected.value.Month - 1, 1).getFullYear(),
|
||||
Month: new Date(selected.value.Year, selected.value.Month - 1, 1).getMonth(),
|
||||
Year: new Date(selected.value.Year, selected.value.Month - 1, 1).getFullYear(),
|
||||
Month: new Date(selected.value.Year, selected.value.Month - 1, 1).getMonth(),
|
||||
}));
|
||||
const current = computed(() => ({
|
||||
Year: new Date().getFullYear(),
|
||||
Month: new Date().getMonth(),
|
||||
Year: new Date().getFullYear(),
|
||||
Month: new Date().getMonth(),
|
||||
}));
|
||||
const selected = computed(() => ({
|
||||
Year: Number(props.year) ?? current.value.Year,
|
||||
Month: Number(props.month ?? current.value.Month)
|
||||
Year: Number(props.year) ?? current.value.Year,
|
||||
Month: Number(props.month ?? current.value.Month)
|
||||
}));
|
||||
const next = computed(() => ({
|
||||
Year: new Date(selected.value.Year, Number(props.month) + 1, 1).getFullYear(),
|
||||
Month: new Date(selected.value.Year, Number(props.month) + 1, 1).getMonth(),
|
||||
Year: new Date(selected.value.Year, Number(props.month) + 1, 1).getFullYear(),
|
||||
Month: new Date(selected.value.Year, Number(props.month) + 1, 1).getMonth(),
|
||||
}));
|
||||
|
||||
watchEffect(() => {
|
||||
@ -56,58 +58,116 @@ onMounted(() => {
|
||||
|
||||
const expandedGroups = ref<Map<string, boolean>>(new Map<string, boolean>())
|
||||
|
||||
function toggleGroup(group : {Name : string, Expand: boolean}) {
|
||||
console.log(expandedGroups.value);
|
||||
function toggleGroup(group: { Name: string, Expand: boolean }) {
|
||||
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;
|
||||
}
|
||||
|
||||
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}));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Budget for {{ selected.Month + 1 }}/{{ selected.Year }}</h1>
|
||||
<div>
|
||||
<router-link
|
||||
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + previous.Year + '/' + previous.Month"
|
||||
>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"
|
||||
>Next Month</router-link>
|
||||
</div>
|
||||
<table class="container col-lg-12" id="content">
|
||||
<tr>
|
||||
<th>Category</th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
<th>Leftover</th>
|
||||
<th>Assigned</th>
|
||||
<th>Activity</th>
|
||||
<th>Available</th>
|
||||
</tr>
|
||||
<tbody v-for="group in GroupsForMonth">
|
||||
<a class="text-lg font-bold" @click="toggleGroup(group)">{{ (getGroupState(group) ? "−" : "+") + " " + group.Name }}</a>
|
||||
<tr v-for="category in GetCategories(group.Name)" v-if="getGroupState(group)">
|
||||
<td>{{ category.Name }}</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td class="text-right">
|
||||
<Currency :value="category.AvailableLastMonth" />
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<Currency :value="category.Assigned" />
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<Currency :value="category.Activity" />
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<Currency :value="category.Available" />
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<h1>Budget for {{ selected.Month + 1 }}/{{ selected.Year }}</h1>
|
||||
<span>Available balance:
|
||||
<Currency
|
||||
:value="accountStore.GetIncomeAvailable(selected.Year, selected.Month)"
|
||||
/></span>
|
||||
<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>
|
||||
|
@ -1,6 +1,6 @@
|
||||
<script lang="ts" setup>
|
||||
import NewBudget from '../dialogs/NewBudget.vue';
|
||||
import Card from '../components/Card.vue';
|
||||
import RowCard from '../components/RowCard.vue';
|
||||
import { useSessionStore } from '../stores/session';
|
||||
|
||||
const props = defineProps<{
|
||||
@ -11,15 +11,22 @@ const BudgetsList = useSessionStore().BudgetsList;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Budgets</h1>
|
||||
<div class="grid md:grid-cols-2 gap-6">
|
||||
<Card v-for="budget in BudgetsList">
|
||||
<router-link v-bind:to="'/budget/'+budget.ID+'/budgeting'" class="contents">
|
||||
<!--<svg class="w-24"></svg>-->
|
||||
<p class="w-24 text-center text-6xl"></p>
|
||||
<span class="text-lg">{{budget.Name}}{{budget.ID == budgetid ? " *" : ""}}</span>
|
||||
</router-link>
|
||||
</Card>
|
||||
<NewBudget />
|
||||
</div>
|
||||
<h1>Budgets</h1>
|
||||
<div class="grid md:grid-cols-2 gap-6">
|
||||
<RowCard
|
||||
v-for="budget in BudgetsList"
|
||||
:key="budget.ID"
|
||||
>
|
||||
<router-link
|
||||
:to="'/budget/'+budget.ID+'/budgeting'"
|
||||
class="contents"
|
||||
>
|
||||
<!--<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>
|
||||
|
@ -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 { useRouter } from "vue-router";
|
||||
import { useSessionStore } from "../stores/session";
|
||||
import Input from "../components/Input.vue";
|
||||
|
||||
const error = ref("");
|
||||
const login = ref({ user: "", password: "" });
|
||||
@ -27,18 +28,32 @@ function formSubmit(e: MouseEvent) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<input type="text" v-model="login.user"
|
||||
placeholder="Username"
|
||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
||||
<input type="password" v-model="login.password"
|
||||
placeholder="Password"
|
||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
||||
</div>
|
||||
<div>{{ error }}</div>
|
||||
<button type="submit" @click="formSubmit" class="bg-blue-300 rounded-lg p-2 w-48">Login</button>
|
||||
<p>
|
||||
New user?
|
||||
<router-link to="/register">Register</router-link> instead!
|
||||
</p>
|
||||
<div>
|
||||
<Input
|
||||
v-model="login.user"
|
||||
type="text"
|
||||
placeholder="Username"
|
||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
|
||||
/>
|
||||
<Input
|
||||
v-model="login.password"
|
||||
type="password"
|
||||
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"
|
||||
>
|
||||
Login
|
||||
</button>
|
||||
<p>
|
||||
New user?
|
||||
<router-link to="/register">
|
||||
Register
|
||||
</router-link> instead!
|
||||
</p>
|
||||
</template>
|
@ -2,6 +2,7 @@
|
||||
import { onMounted, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useSessionStore } from "../stores/session";
|
||||
import Input from "../components/Input.vue";
|
||||
|
||||
const error = ref("");
|
||||
const login = ref({ email: "", password: "", name: "" });
|
||||
@ -27,21 +28,38 @@ function formSubmit(e: MouseEvent) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<input type="text" v-model="login.name"
|
||||
placeholder="Name"
|
||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
||||
<input type="text" v-model="login.email"
|
||||
placeholder="Email"
|
||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
||||
<input type="password" v-model="login.password"
|
||||
placeholder="Password"
|
||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48" />
|
||||
</div>
|
||||
<div>{{ error }}</div>
|
||||
<button type="submit" @click="formSubmit" class="bg-blue-300 rounded-lg p-2 w-48">Register</button>
|
||||
<p>
|
||||
Existing user?
|
||||
<router-link to="/login">Login</router-link> instead!
|
||||
</p>
|
||||
<div>
|
||||
<Input
|
||||
v-model="login.name"
|
||||
type="text"
|
||||
placeholder="Name"
|
||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
|
||||
/>
|
||||
<Input
|
||||
v-model="login.email"
|
||||
type="text"
|
||||
placeholder="Email"
|
||||
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
|
||||
/>
|
||||
<Input
|
||||
v-model="login.password"
|
||||
type="password"
|
||||
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,10 @@ import { useRouter } from "vue-router";
|
||||
import { DELETE, POST } from "../api";
|
||||
import { useBudgetsStore } from "../stores/budget";
|
||||
import { useSessionStore } from "../stores/session";
|
||||
import Card from "../components/Card.vue";
|
||||
import Button from "../components/Button.vue";
|
||||
import RowCard from "../components/RowCard.vue";
|
||||
import Button from "../components/SimpleButton.vue";
|
||||
import { saveAs } from 'file-saver';
|
||||
import Input from "../components/Input.vue";
|
||||
|
||||
const transactionsFile = ref<File | undefined>(undefined);
|
||||
const assignmentsFile = ref<File | undefined>(undefined);
|
||||
@ -71,55 +72,105 @@ function ynabExport() {
|
||||
saveAs(blob, timeStamp + " " + CurrentBudgetName.value + " - Transactions.tsv");
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1>Danger Zone</h1>
|
||||
<div class="grid md:grid-cols-2 gap-6">
|
||||
<Card class="flex-col p-3">
|
||||
<h2 class="text-lg font-bold">Clear Budget</h2>
|
||||
<p>This removes transactions and assignments to start from scratch. Accounts and categories are kept. Not undoable!</p>
|
||||
<div>
|
||||
<h1>Danger Zone</h1>
|
||||
<div class="grid md:grid-cols-2 gap-6">
|
||||
<RowCard class="flex-col p-3">
|
||||
<h2 class="text-lg font-bold">
|
||||
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>
|
||||
</Card>
|
||||
<Card class="flex-col p-3">
|
||||
<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>
|
||||
<Button class="bg-red-500" @click="deleteBudget">Delete budget</button>
|
||||
</Card>
|
||||
<Card class="flex-col p-3">
|
||||
<h2 class="text-lg font-bold">Fix all historic negative category-balances</h2>
|
||||
<p>This restores YNABs functionality, that would substract any overspent categories' balances from next months inflows.</p>
|
||||
<Button class="bg-orange-500" @click="cleanNegative">Fix negative</button>
|
||||
</Card>
|
||||
<Card class="flex-col p-3">
|
||||
<h2 class="text-lg font-bold">Import YNAB Budget</h2>
|
||||
<Button
|
||||
class="bg-red-500 py-2"
|
||||
@click="clearBudget"
|
||||
>
|
||||
Clear budget
|
||||
</Button>
|
||||
</RowCard>
|
||||
<RowCard class="flex-col p-3">
|
||||
<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>
|
||||
<Button
|
||||
class="bg-red-500 py-2"
|
||||
@click="deleteBudget"
|
||||
>
|
||||
Delete budget
|
||||
</Button>
|
||||
</RowCard>
|
||||
<RowCard class="flex-col p-3">
|
||||
<h2 class="text-lg font-bold">
|
||||
Fix all historic negative category-balances
|
||||
</h2>
|
||||
<p>
|
||||
This restores YNABs functionality, that would substract any
|
||||
overspent categories' balances from next months inflows.
|
||||
</p>
|
||||
<Button
|
||||
class="bg-orange-500 py-2"
|
||||
@click="cleanNegative"
|
||||
>
|
||||
Fix negative
|
||||
</Button>
|
||||
</RowCard>
|
||||
<RowCard class="flex-col p-3">
|
||||
<h2 class="text-lg font-bold">
|
||||
Import YNAB Budget
|
||||
</h2>
|
||||
|
||||
<div class="flex flex-row">
|
||||
<div>
|
||||
<label for="transactions_file">
|
||||
Transaktionen:
|
||||
<input type="file" @change="gotTransactions" accept="text/*" />
|
||||
</label>
|
||||
<br />
|
||||
<label for="assignments_file">
|
||||
Budget:
|
||||
<input type="file" @change="gotAssignments" accept="text/*" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<Button class="bg-blue-500" :disabled="filesIncomplete" @click="ynabImport">Importieren</Button>
|
||||
</div>
|
||||
</Card>
|
||||
<Card 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" @click="ynabExport">Export</Button>
|
||||
</div>
|
||||
</Card>
|
||||
<div>
|
||||
<label for="transactions_file">
|
||||
Transaktionen:
|
||||
<input
|
||||
type="file"
|
||||
accept="text/*"
|
||||
@change="gotTransactions"
|
||||
>
|
||||
</label>
|
||||
<br>
|
||||
<label for="assignments_file">
|
||||
Budget:
|
||||
<input
|
||||
type="file"
|
||||
accept="text/*"
|
||||
@change="gotAssignments"
|
||||
>
|
||||
</label>
|
||||
</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>
|
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 => {
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
} catch {
|
||||
return { ...obj };
|
||||
}
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
} catch {
|
||||
return { ...obj };
|
||||
}
|
||||
};
|
||||
const formatTime = (date = new Date()) => {
|
||||
const hours = date.getHours().toString().padStart(2, '0');
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0');
|
||||
const seconds = date.getSeconds().toString().padStart(2, '0');
|
||||
const milliseconds = date.getMilliseconds().toString();
|
||||
const hours = date.getHours().toString().padStart(2, "0");
|
||||
const minutes = date.getMinutes().toString().padStart(2, "0");
|
||||
const seconds = date.getSeconds().toString().padStart(2, "0");
|
||||
|
||||
return `${hours}:${minutes}:${seconds}:${milliseconds}`;
|
||||
return `${hours}:${minutes}:${seconds}`;
|
||||
};
|
||||
|
||||
export interface PiniaLoggerOptions {
|
||||
disabled?: boolean;
|
||||
expanded?: boolean;
|
||||
showDuration?: boolean
|
||||
showStoreName?: boolean;
|
||||
logErrors?: boolean;
|
||||
disabled?: boolean;
|
||||
expanded?: boolean;
|
||||
showDuration?: boolean;
|
||||
showStoreName?: boolean;
|
||||
logErrors?: boolean;
|
||||
}
|
||||
|
||||
export type PiniaActionListenerContext = _StoreOnActionListenerContext<StoreGeneric, string, _ActionsTree>;
|
||||
export type PiniaActionListenerContext = _StoreOnActionListenerContext<
|
||||
StoreGeneric,
|
||||
string,
|
||||
_ActionsTree
|
||||
>;
|
||||
|
||||
const defaultOptions: PiniaLoggerOptions = {
|
||||
logErrors: true,
|
||||
disabled: false,
|
||||
expanded: true,
|
||||
showStoreName: true,
|
||||
showDuration: false,
|
||||
logErrors: true,
|
||||
disabled: false,
|
||||
expanded: true,
|
||||
showStoreName: true,
|
||||
showDuration: false,
|
||||
};
|
||||
|
||||
export const PiniaLogger = (config = defaultOptions) => (ctx: PiniaPluginContext) => {
|
||||
const options = {
|
||||
...defaultOptions,
|
||||
...config,
|
||||
};
|
||||
export const PiniaLogger =
|
||||
(config = defaultOptions) =>
|
||||
(ctx: PiniaPluginContext) => {
|
||||
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 startTime = Date.now();
|
||||
const prevState = cloneDeep(ctx.store.$state);
|
||||
const log = (isError?: boolean, error?: any) => {
|
||||
const endTime = Date.now();
|
||||
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) => {
|
||||
const endTime = Date.now();
|
||||
const duration = endTime - startTime + 'ms';
|
||||
const nextState = cloneDeep(ctx.store.$state);
|
||||
const storeName = action.store.$id;
|
||||
const title = `action 🍍 ${options.showStoreName ? `[${storeName}] ` : ''}${action.name} ${isError ? `failed after ${duration} ` : ''}@ ${formatTime()}`;
|
||||
console[options.expanded ? "group" : "groupCollapsed"](
|
||||
`%c${title}`,
|
||||
`font-weight: bold; ${isError ? "color: #ed4981;" : ""}`
|
||||
);
|
||||
console.log(
|
||||
"%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;' : ''}`);
|
||||
console.log('%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();
|
||||
action.after(() => {
|
||||
log();
|
||||
});
|
||||
|
||||
if (options.logErrors) {
|
||||
action.onError((error) => {
|
||||
log(true, error);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
action.after(() => {
|
||||
log();
|
||||
});
|
||||
|
||||
if (options.logErrors) {
|
||||
action.onError((error) => {
|
||||
log(true, error);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export default PiniaLogger;
|
@ -1,29 +1,75 @@
|
||||
import { createRouter, createWebHistory, RouteLocationNormalized } from 'vue-router'
|
||||
import Dashboard from '../pages/Dashboard.vue';
|
||||
import Login from '../pages/Login.vue';
|
||||
import Index from '../pages/Index.vue';
|
||||
import Register from '../pages/Register.vue';
|
||||
import Account from '@/pages/Account.vue';
|
||||
import Settings from '../pages/Settings.vue';
|
||||
import Budgeting from '../pages/Budgeting.vue';
|
||||
import BudgetSidebar from '../pages/BudgetSidebar.vue';
|
||||
import {
|
||||
createRouter,
|
||||
createWebHistory,
|
||||
RouteLocationNormalized,
|
||||
} from "vue-router";
|
||||
import Account from "@/pages/Account.vue";
|
||||
import Budgeting from "../pages/Budgeting.vue";
|
||||
import BudgetSidebar from "../pages/BudgetSidebar.vue";
|
||||
import Dashboard from "../pages/Dashboard.vue";
|
||||
import Login from "../pages/Login.vue";
|
||||
import Register from "../pages/Register.vue";
|
||||
import Settings from "../pages/Settings.vue";
|
||||
import WelcomePage from "../pages/WelcomePage.vue";
|
||||
|
||||
const routes = [
|
||||
{ path: "/", name: "Index", component: Index },
|
||||
{ path: "/dashboard", name: "Dashboard", component: Dashboard },
|
||||
{ path: "/login", name: "Login", component: Login },
|
||||
{ path: "/register", name: "Register", component: Register },
|
||||
{ path: "/budget/:budgetid/budgeting", name: "Budget", redirect: (to : RouteLocationNormalized) =>
|
||||
'/budget/' + to.params.budgetid + '/budgeting/' + new Date().getFullYear() + '/' + new Date().getMonth()
|
||||
},
|
||||
{ path: "/budget/:budgetid/budgeting/:year/:month", name: "Budget with date", components: { default: Budgeting, sidebar: BudgetSidebar }, props: true },
|
||||
{ path: "/budget/:budgetid/Settings", name: "Budget Settings", components: { default: Settings, sidebar: BudgetSidebar }, props: true },
|
||||
{ path: "/budget/:budgetid/account/:accountid", name: "Account", components: { default: Account, sidebar: BudgetSidebar }, props: true },
|
||||
]
|
||||
{ path: "/", name: "Index", component: WelcomePage },
|
||||
{
|
||||
path: "/dashboard",
|
||||
name: "Dashboard",
|
||||
component: Dashboard,
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: "/login",
|
||||
name: "Login",
|
||||
component: Login,
|
||||
meta: { hideForAuth: true },
|
||||
},
|
||||
{
|
||||
path: "/register",
|
||||
name: "Register",
|
||||
component: Register,
|
||||
meta: { hideForAuth: true },
|
||||
},
|
||||
{
|
||||
path: "/budget/:budgetid/budgeting",
|
||||
name: "Budget",
|
||||
redirect: (to: RouteLocationNormalized) =>
|
||||
"/budget/" +
|
||||
to.params.budgetid +
|
||||
"/budgeting/" +
|
||||
new Date().getFullYear() +
|
||||
"/" +
|
||||
new Date().getMonth(),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: "/budget/:budgetid/budgeting/:year/:month",
|
||||
name: "Budget with date",
|
||||
components: { default: Budgeting, sidebar: BudgetSidebar },
|
||||
props: true,
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: "/budget/:budgetid/Settings",
|
||||
name: "Budget Settings",
|
||||
components: { default: Settings, sidebar: BudgetSidebar },
|
||||
props: true,
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: "/budget/:budgetid/account/:accountid",
|
||||
name: "Account",
|
||||
components: { default: Account, sidebar: BudgetSidebar },
|
||||
props: true,
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
})
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
});
|
||||
|
||||
export default router
|
||||
export default router;
|
||||
|
@ -1,52 +1,41 @@
|
||||
import { defineStore } from "pinia"
|
||||
import { defineStore } from "pinia";
|
||||
import { GET, POST } from "../api";
|
||||
import { useBudgetsStore } from "./budget";
|
||||
import { useSessionStore } from "./session";
|
||||
import { useTransactionsStore } from "./transactions";
|
||||
|
||||
interface State {
|
||||
Accounts: Map<string, Account>
|
||||
CurrentAccountID: string | null
|
||||
Categories: Map<string, Category>
|
||||
Months: Map<number, Map<number, Map<string, Category>>>
|
||||
Transactions: Map<string, Transaction>
|
||||
Assignments: []
|
||||
Reconciling: boolean
|
||||
}
|
||||
|
||||
export interface Transaction {
|
||||
ID: string
|
||||
Date: Date
|
||||
TransferAccount: string
|
||||
CategoryGroup: string
|
||||
Category: string
|
||||
CategoryID: string | undefined
|
||||
Memo: string
|
||||
Status: string
|
||||
GroupID: string
|
||||
Payee: string
|
||||
PayeeID: string | undefined
|
||||
Amount: number
|
||||
Reconciled: boolean
|
||||
Accounts: Map<string, Account>;
|
||||
CurrentAccountID: string | null;
|
||||
Categories: Map<string, Category>;
|
||||
Months: Map<number, Map<number, Map<string, Category>>>;
|
||||
Assignments: [];
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
ID: string
|
||||
Name: string
|
||||
OnBudget: boolean
|
||||
ClearedBalance: number
|
||||
WorkingBalance: number
|
||||
ReconciledBalance: number
|
||||
Transactions: string[]
|
||||
ID: string;
|
||||
Name: string;
|
||||
OnBudget: boolean;
|
||||
IsOpen: boolean;
|
||||
ClearedBalance: number;
|
||||
WorkingBalance: number;
|
||||
ReconciledBalance: number;
|
||||
Transactions: string[];
|
||||
LastReconciled: NullDate;
|
||||
}
|
||||
|
||||
interface NullDate {
|
||||
Valid: boolean;
|
||||
Time: Date;
|
||||
}
|
||||
|
||||
export interface Category {
|
||||
ID: string
|
||||
Group: string
|
||||
Name: string
|
||||
AvailableLastMonth: number
|
||||
Assigned: number
|
||||
Activity: number
|
||||
Available: number
|
||||
ID: string;
|
||||
Group: string;
|
||||
Name: string;
|
||||
AvailableLastMonth: number;
|
||||
Assigned: number;
|
||||
Activity: number;
|
||||
}
|
||||
|
||||
export const useAccountStore = defineStore("budget/account", {
|
||||
@ -55,9 +44,7 @@ export const useAccountStore = defineStore("budget/account", {
|
||||
CurrentAccountID: null,
|
||||
Months: new Map<number, Map<number, Map<string, Category>>>(),
|
||||
Categories: new Map<string, Category>(),
|
||||
Transactions: new Map<string, Transaction>(),
|
||||
Assignments: [],
|
||||
Reconciling: false,
|
||||
}),
|
||||
getters: {
|
||||
AccountsList(state) {
|
||||
@ -66,7 +53,33 @@ export const useAccountStore = defineStore("budget/account", {
|
||||
AllCategoriesForMonth: (state) => (year: number, month: number) => {
|
||||
const yearMap = state.Months.get(year);
|
||||
const monthMap = yearMap?.get(month);
|
||||
return [...monthMap?.values() || []];
|
||||
return [...(monthMap?.values() || [])];
|
||||
},
|
||||
GetCategoryAvailable(state) {
|
||||
return (category: Category): number => {
|
||||
return (
|
||||
category.AvailableLastMonth +
|
||||
Number(category.Assigned) +
|
||||
category.Activity
|
||||
);
|
||||
};
|
||||
},
|
||||
GetIncomeCategoryID(state) {
|
||||
const budget = useBudgetsStore();
|
||||
return budget.CurrentBudget?.IncomeCategoryID;
|
||||
},
|
||||
GetIncomeAvailable(state) {
|
||||
return (year: number, month: number) => {
|
||||
const IncomeCategoryID = this.GetIncomeCategoryID;
|
||||
if (IncomeCategoryID == null) return 0;
|
||||
|
||||
const categories = this.AllCategoriesForMonth(year, month);
|
||||
const category = categories.filter(
|
||||
(x) => x.ID == IncomeCategoryID
|
||||
)[0];
|
||||
if (category == null) return 0;
|
||||
return category.AvailableLastMonth;
|
||||
};
|
||||
},
|
||||
CategoryGroupsForMonth(state) {
|
||||
return (year: number, month: number) => {
|
||||
@ -74,96 +87,137 @@ export const useAccountStore = defineStore("budget/account", {
|
||||
const categoryGroups = [];
|
||||
let prev = undefined;
|
||||
for (const category of categories) {
|
||||
if (category.Group != prev)
|
||||
categoryGroups.push({
|
||||
if (category.ID == this.GetIncomeCategoryID) continue;
|
||||
|
||||
if (prev == undefined || category.Group != prev.Name) {
|
||||
prev = {
|
||||
Name: category.Group,
|
||||
Expand: category.Group != "Hidden Categories",
|
||||
Available: this.GetCategoryAvailable(category),
|
||||
AvailableLastMonth: category.AvailableLastMonth,
|
||||
Activity: category.Activity,
|
||||
Assigned: category.Assigned,
|
||||
};
|
||||
categoryGroups.push({
|
||||
...prev,
|
||||
Expand: prev.Name != "Hidden Categories",
|
||||
});
|
||||
prev = category.Group;
|
||||
} else {
|
||||
categoryGroups[categoryGroups.length - 1].Available +=
|
||||
this.GetCategoryAvailable(category);
|
||||
categoryGroups[
|
||||
categoryGroups.length - 1
|
||||
].AvailableLastMonth += category.AvailableLastMonth;
|
||||
categoryGroups[categoryGroups.length - 1].Activity +=
|
||||
category.Activity;
|
||||
categoryGroups[categoryGroups.length - 1].Assigned +=
|
||||
category.Assigned;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return categoryGroups;
|
||||
}
|
||||
};
|
||||
},
|
||||
CategoriesForMonthAndGroup(state) {
|
||||
return (year: number, month: number, group: string) => {
|
||||
const categories = this.AllCategoriesForMonth(year, month);
|
||||
return categories.filter(x => x.Group == group);
|
||||
}
|
||||
return categories.filter((x) => x.Group == group);
|
||||
};
|
||||
},
|
||||
GetAccount(state) {
|
||||
return (accountid: string) => {
|
||||
return this.Accounts.get(accountid);
|
||||
};
|
||||
},
|
||||
CurrentAccount(state): Account | undefined {
|
||||
if (state.CurrentAccountID == null)
|
||||
return undefined;
|
||||
if (state.CurrentAccountID == null) return undefined;
|
||||
|
||||
return state.Accounts.get(state.CurrentAccountID);
|
||||
},
|
||||
ReconcilingBalance(state): number {
|
||||
let reconciledBalance = this.CurrentAccount!.ReconciledBalance;
|
||||
for (const transaction of this.TransactionsList) {
|
||||
if (transaction.Reconciled)
|
||||
reconciledBalance += transaction.Amount;
|
||||
}
|
||||
return reconciledBalance;
|
||||
return this.GetAccount(state.CurrentAccountID);
|
||||
},
|
||||
OnBudgetAccounts(state) {
|
||||
return [...state.Accounts.values()].filter(x => x.OnBudget);
|
||||
return [...state.Accounts.values()].filter((x) => x.OnBudget);
|
||||
},
|
||||
OnBudgetAccountsBalance(state): number {
|
||||
return this.OnBudgetAccounts.reduce((prev, curr) => prev + Number(curr.ClearedBalance), 0);
|
||||
return this.OnBudgetAccounts.reduce(
|
||||
(prev, curr) => prev + Number(curr.ClearedBalance),
|
||||
0
|
||||
);
|
||||
},
|
||||
OffBudgetAccounts(state) {
|
||||
return [...state.Accounts.values()].filter(x => !x.OnBudget);
|
||||
return [...state.Accounts.values()].filter((x) => !x.OnBudget);
|
||||
},
|
||||
OffBudgetAccountsBalance(state): number {
|
||||
return this.OffBudgetAccounts.reduce((prev, curr) => prev + Number(curr.ClearedBalance), 0);
|
||||
},
|
||||
TransactionsList(state): Transaction[] {
|
||||
return this.CurrentAccount!.Transactions.map(x => {
|
||||
return this.Transactions.get(x)!
|
||||
});
|
||||
return this.OffBudgetAccounts.reduce(
|
||||
(prev, curr) => prev + Number(curr.ClearedBalance),
|
||||
0
|
||||
);
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
async SetCurrentAccount(budgetid: string, accountid: string) {
|
||||
if (budgetid == null)
|
||||
return
|
||||
if (budgetid == null) return;
|
||||
|
||||
this.CurrentAccountID = accountid;
|
||||
const account = this.CurrentAccount;
|
||||
if (account == undefined)
|
||||
return
|
||||
|
||||
if (accountid == null) return;
|
||||
const account = this.GetAccount(accountid)!;
|
||||
useSessionStore().setTitle(account.Name);
|
||||
await this.FetchAccount(account);
|
||||
},
|
||||
AddTransaction(account: Account, transaction: any) {
|
||||
transaction.Date = new Date(transaction.Date);
|
||||
this.Transactions.set(transaction.ID, transaction);
|
||||
},
|
||||
async FetchAccount(account: Account) {
|
||||
const result = await GET("/account/" + account.ID + "/transactions");
|
||||
const result = await GET(
|
||||
"/account/" + account.ID + "/transactions"
|
||||
);
|
||||
const response = await result.json();
|
||||
account.Transactions = [];
|
||||
for (const transaction of response.Transactions) {
|
||||
this.AddTransaction(account, transaction);
|
||||
account.Transactions.push(transaction.ID);
|
||||
}
|
||||
const transactionsStore = useTransactionsStore();
|
||||
const transactions = transactionsStore.AddTransactions(
|
||||
response.Transactions
|
||||
);
|
||||
account.Transactions = transactions;
|
||||
},
|
||||
async FetchMonthBudget(budgetid: string, year: number, month: number) {
|
||||
const result = await GET("/budget/" + budgetid + "/" + year + "/" + month);
|
||||
const result = await GET(
|
||||
"/budget/" + budgetid + "/" + year + "/" + (month + 1)
|
||||
);
|
||||
const response = await result.json();
|
||||
if (response.Categories == undefined || response.Categories.length <= 0)
|
||||
if (
|
||||
response.Categories == undefined ||
|
||||
response.Categories.length <= 0
|
||||
)
|
||||
return;
|
||||
this.addCategoriesForMonth(year, month, response.Categories);
|
||||
},
|
||||
async EditAccount(accountid: string, name: string, onBudget: boolean) {
|
||||
const result = await POST("/account/" + accountid, JSON.stringify({ name: name, onBudget: onBudget }));
|
||||
async EditAccount(
|
||||
accountid: string,
|
||||
name: string,
|
||||
onBudget: boolean,
|
||||
isOpen: boolean
|
||||
) {
|
||||
const result = await POST(
|
||||
"/account/" + accountid,
|
||||
JSON.stringify({
|
||||
name: name,
|
||||
onBudget: onBudget,
|
||||
isOpen: isOpen,
|
||||
})
|
||||
);
|
||||
const response = await result.json();
|
||||
useBudgetsStore().MergeBudgetingData(response);
|
||||
|
||||
if (!isOpen) {
|
||||
this.Accounts.delete(accountid);
|
||||
}
|
||||
},
|
||||
addCategoriesForMonth(year: number, month: number, categories: Category[]): void {
|
||||
addCategoriesForMonth(
|
||||
year: number,
|
||||
month: number,
|
||||
categories: Category[]
|
||||
): void {
|
||||
this.$patch((state) => {
|
||||
const yearMap = state.Months.get(year) || new Map<number, Map<string, Category>>();
|
||||
const monthMap = yearMap.get(month) || new Map<string, Category>();
|
||||
const yearMap =
|
||||
state.Months.get(year) ||
|
||||
new Map<number, Map<string, Category>>();
|
||||
const monthMap =
|
||||
yearMap.get(month) || new Map<string, Category>();
|
||||
for (const category of categories) {
|
||||
monthMap.set(category.ID, category);
|
||||
}
|
||||
@ -172,48 +226,8 @@ export const useAccountStore = defineStore("budget/account", {
|
||||
state.Months.set(year, yearMap);
|
||||
});
|
||||
},
|
||||
SetReconciledForAllTransactions(value: boolean) {
|
||||
for (const transaction of this.TransactionsList) {
|
||||
if (transaction.Status == "Reconciled")
|
||||
continue;
|
||||
|
||||
transaction.Reconciled = value;
|
||||
}
|
||||
},
|
||||
async SubmitReconcilation(reconciliationTransactionAmount: number) {
|
||||
const account = this.CurrentAccount!;
|
||||
const reconciledTransactions = this.TransactionsList.filter(x => x.Reconciled);
|
||||
for (const transaction of reconciledTransactions) {
|
||||
account.ReconciledBalance += transaction.Amount;
|
||||
transaction.Status = "Reconciled";
|
||||
transaction.Reconciled = false;
|
||||
}
|
||||
const result = await POST("/account/" + this.CurrentAccountID + "/reconcile", JSON.stringify({
|
||||
transactionIDs: reconciledTransactions.map(x => x.ID),
|
||||
reconciliationTransactionAmount: reconciliationTransactionAmount.toString(),
|
||||
}));
|
||||
const response = await result.json();
|
||||
const recTrans = response.ReconciliationTransaction;
|
||||
if (recTrans) {
|
||||
this.AddTransaction(account, recTrans);
|
||||
account.Transactions.unshift(recTrans.ID);
|
||||
}
|
||||
console.log("Reconcile: " + response.message);
|
||||
},
|
||||
logout() {
|
||||
this.$reset()
|
||||
this.$reset();
|
||||
},
|
||||
async saveTransaction(payload: string) {
|
||||
const result = await POST("/transaction/new", payload);
|
||||
const response = await result.json();
|
||||
this.AddTransaction(this.CurrentAccount!, response);
|
||||
this.CurrentAccount?.Transactions.unshift(response.ID);
|
||||
},
|
||||
async editTransaction(transactionid: string, payload: string) {
|
||||
const result = await POST("/transaction/" + transactionid, payload);
|
||||
const response = await result.json();
|
||||
this.AddTransaction(this.CurrentAccount!, response);
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
},
|
||||
});
|
||||
|
@ -4,17 +4,16 @@ import { useAccountStore } from "./budget-account";
|
||||
import { Budget, useSessionStore } from "./session";
|
||||
|
||||
interface State {
|
||||
CurrentBudgetID: string | null,
|
||||
CurrentBudgetID: string | null;
|
||||
}
|
||||
|
||||
export const useBudgetsStore = defineStore('budget', {
|
||||
export const useBudgetsStore = defineStore("budget", {
|
||||
state: (): State => ({
|
||||
CurrentBudgetID: null,
|
||||
}),
|
||||
getters: {
|
||||
CurrentBudget(): Budget | undefined {
|
||||
if (this.CurrentBudgetID == null)
|
||||
return undefined;
|
||||
if (this.CurrentBudgetID == null) return undefined;
|
||||
|
||||
const sessionStore = useSessionStore();
|
||||
return sessionStore.Budgets.get(this.CurrentBudgetID);
|
||||
@ -27,7 +26,7 @@ export const useBudgetsStore = defineStore('budget', {
|
||||
ImportYNAB(formData: FormData) {
|
||||
return POST(
|
||||
"/budget/" + this.CurrentBudgetID + "/import/ynab",
|
||||
formData,
|
||||
formData
|
||||
);
|
||||
},
|
||||
async NewBudget(budgetName: string): Promise<void> {
|
||||
@ -43,8 +42,7 @@ export const useBudgetsStore = defineStore('budget', {
|
||||
async SetCurrentBudget(budgetid: string): Promise<void> {
|
||||
this.CurrentBudgetID = budgetid;
|
||||
|
||||
if (budgetid == null)
|
||||
return
|
||||
if (budgetid == null) return;
|
||||
|
||||
await this.FetchBudget(budgetid);
|
||||
},
|
||||
@ -53,13 +51,20 @@ export const useBudgetsStore = defineStore('budget', {
|
||||
const response = await result.json();
|
||||
this.MergeBudgetingData(response);
|
||||
},
|
||||
MergeBudgetingData(response : any) {
|
||||
MergeBudgetingData(response: any) {
|
||||
const accounts = useAccountStore();
|
||||
for (const account of response.Accounts || []) {
|
||||
useAccountStore().Accounts.set(account.ID, account);
|
||||
const existingAccount = accounts.Accounts.get(account.ID);
|
||||
account.Transactions = existingAccount?.Transactions ?? [];
|
||||
if (account.LastReconciled.Valid)
|
||||
account.LastReconciled.Time = new Date(
|
||||
account.LastReconciled.Time
|
||||
);
|
||||
accounts.Accounts.set(account.ID, account);
|
||||
}
|
||||
for (const category of response.Categories || []) {
|
||||
useAccountStore().Categories.set(category.ID, category);
|
||||
accounts.Categories.set(category.ID, category);
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
},
|
||||
});
|
||||
|
@ -1,42 +1,52 @@
|
||||
import { StorageSerializers, useStorage } from '@vueuse/core';
|
||||
import { defineStore } from 'pinia'
|
||||
import { POST } from '../api';
|
||||
import { StorageSerializers, useStorage } from "@vueuse/core";
|
||||
import { defineStore } from "pinia";
|
||||
import { POST } from "../api";
|
||||
|
||||
interface State {
|
||||
Session: Session | null
|
||||
Budgets: Map<string, Budget>,
|
||||
Session: Session | null;
|
||||
Budgets: Map<string, Budget>;
|
||||
}
|
||||
|
||||
interface Session {
|
||||
Token: string
|
||||
User: string
|
||||
Token: string;
|
||||
User: string;
|
||||
}
|
||||
|
||||
export interface Budget {
|
||||
ID: string
|
||||
Name: string
|
||||
AvailableBalance: number
|
||||
ID: string;
|
||||
Name: string;
|
||||
AvailableBalance: number;
|
||||
IncomeCategoryID: string;
|
||||
}
|
||||
|
||||
export const useSessionStore = defineStore('session', {
|
||||
export const useSessionStore = defineStore("session", {
|
||||
state: () => ({
|
||||
Session: useStorage<Session | null>('session', null, undefined, { serializer: StorageSerializers.object }),
|
||||
Budgets: useStorage<Map<string, Budget>>('budgets', new Map<string, Budget>(), undefined, { serializer: StorageSerializers.map }),
|
||||
Session: useStorage<Session | null>("session", null, undefined, {
|
||||
serializer: StorageSerializers.object,
|
||||
}),
|
||||
Budgets: useStorage<Map<string, Budget>>(
|
||||
"budgets",
|
||||
new Map<string, Budget>(),
|
||||
undefined,
|
||||
{ serializer: StorageSerializers.map }
|
||||
),
|
||||
}),
|
||||
getters: {
|
||||
BudgetsList: (state) => [ ...state.Budgets.values() ],
|
||||
AuthHeaders: (state) => ({'Authorization': 'Bearer ' + state.Session?.Token}),
|
||||
BudgetsList: (state) => [...state.Budgets.values()],
|
||||
AuthHeaders: (state) => ({
|
||||
Authorization: "Bearer " + state.Session?.Token,
|
||||
}),
|
||||
LoggedIn: (state) => state.Session != null,
|
||||
},
|
||||
actions: {
|
||||
setTitle(title : string) {
|
||||
setTitle(title: string) {
|
||||
document.title = "Budgeteer - " + title;
|
||||
},
|
||||
loginSuccess(x : any) {
|
||||
loginSuccess(x: any) {
|
||||
this.Session = {
|
||||
User: x.User,
|
||||
Token: x.Token,
|
||||
}
|
||||
};
|
||||
for (const budget of x.Budgets) {
|
||||
this.Budgets.set(budget.ID, budget);
|
||||
}
|
||||
@ -47,8 +57,11 @@ export const useSessionStore = defineStore('session', {
|
||||
this.loginSuccess(result);
|
||||
return result;
|
||||
},
|
||||
async register(login : any) {
|
||||
const response = await POST("/user/register", JSON.stringify(login));
|
||||
async register(login: any) {
|
||||
const response = await POST(
|
||||
"/user/register",
|
||||
JSON.stringify(login)
|
||||
);
|
||||
const result = await response.json();
|
||||
this.loginSuccess(result);
|
||||
return result;
|
||||
@ -57,5 +70,5 @@ export const useSessionStore = defineStore('session', {
|
||||
this.Session = null;
|
||||
this.Budgets.clear();
|
||||
},
|
||||
}
|
||||
})
|
||||
},
|
||||
});
|
||||
|
@ -2,17 +2,17 @@ import { useStorage } from "@vueuse/core";
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
interface State {
|
||||
Menu: MenuSettings
|
||||
Menu: MenuSettings;
|
||||
}
|
||||
|
||||
interface MenuSettings {
|
||||
Show: boolean | null,
|
||||
Expand: boolean | null,
|
||||
Show: boolean | null;
|
||||
Expand: boolean | null;
|
||||
}
|
||||
|
||||
export const useSettingsStore = defineStore('settings', {
|
||||
export const useSettingsStore = defineStore("settings", {
|
||||
state: () => ({
|
||||
Menu: useStorage<MenuSettings>('settings', {
|
||||
Menu: useStorage<MenuSettings>("settings", {
|
||||
Show: null,
|
||||
Expand: false,
|
||||
}),
|
||||
@ -24,5 +24,5 @@ export const useSettingsStore = defineStore('settings', {
|
||||
toggleMenuSize() {
|
||||
this.Menu.Expand = !this.Menu.Expand;
|
||||
},
|
||||
}
|
||||
},
|
||||
});
|
110
web/src/stores/transactions.ts
Normal file
110
web/src/stores/transactions.ts
Normal file
@ -0,0 +1,110 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { POST } from "../api";
|
||||
import { useAccountStore } from "./budget-account";
|
||||
|
||||
interface State {
|
||||
Transactions: Map<string, Transaction>;
|
||||
Reconciling: boolean;
|
||||
}
|
||||
|
||||
export interface Transaction {
|
||||
ID: string;
|
||||
Date: Date;
|
||||
TransferAccount: string;
|
||||
CategoryGroup: string;
|
||||
Category: string;
|
||||
CategoryID: string | undefined;
|
||||
Memo: string;
|
||||
Status: string;
|
||||
GroupID: string;
|
||||
Payee: string;
|
||||
PayeeID: string | undefined;
|
||||
Amount: number;
|
||||
Reconciled: boolean;
|
||||
}
|
||||
|
||||
export const useTransactionsStore = defineStore("budget/transactions", {
|
||||
state: (): State => ({
|
||||
Transactions: new Map<string, Transaction>(),
|
||||
Reconciling: false,
|
||||
}),
|
||||
getters: {
|
||||
ReconcilingBalance(state): number {
|
||||
const accountsStore = useAccountStore();
|
||||
let reconciledBalance =
|
||||
accountsStore.CurrentAccount!.ReconciledBalance;
|
||||
for (const transaction of this.TransactionsList) {
|
||||
if (transaction.Reconciled)
|
||||
reconciledBalance += transaction.Amount;
|
||||
}
|
||||
return reconciledBalance;
|
||||
},
|
||||
TransactionsList(state): Transaction[] {
|
||||
const accountsStore = useAccountStore();
|
||||
return accountsStore.CurrentAccount!.Transactions.map((x) => {
|
||||
return this.Transactions.get(x)!;
|
||||
});
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
AddTransactions(transactions: Array<Transaction>) {
|
||||
const transactionIds = [] as Array<string>;
|
||||
this.$patch(() => {
|
||||
for (const transaction of transactions) {
|
||||
transaction.Date = new Date(transaction.Date);
|
||||
this.Transactions.set(transaction.ID, transaction);
|
||||
transactionIds.push(transaction.ID);
|
||||
}
|
||||
});
|
||||
return transactionIds;
|
||||
},
|
||||
SetReconciledForAllTransactions(value: boolean) {
|
||||
for (const transaction of this.TransactionsList) {
|
||||
if (transaction.Status == "Reconciled") continue;
|
||||
|
||||
transaction.Reconciled = value;
|
||||
}
|
||||
},
|
||||
async SubmitReconcilation(reconciliationTransactionAmount: number) {
|
||||
const accountsStore = useAccountStore();
|
||||
const account = accountsStore.CurrentAccount!;
|
||||
const reconciledTransactions = this.TransactionsList.filter(
|
||||
(x) => x.Reconciled
|
||||
);
|
||||
for (const transaction of reconciledTransactions) {
|
||||
account.ReconciledBalance += transaction.Amount;
|
||||
transaction.Status = "Reconciled";
|
||||
transaction.Reconciled = false;
|
||||
}
|
||||
const result = await POST(
|
||||
"/account/" + accountsStore.CurrentAccountID + "/reconcile",
|
||||
JSON.stringify({
|
||||
transactionIDs: reconciledTransactions.map((x) => x.ID),
|
||||
reconciliationTransactionAmount:
|
||||
reconciliationTransactionAmount.toString(),
|
||||
})
|
||||
);
|
||||
const response = await result.json();
|
||||
const recTrans = response.ReconciliationTransaction;
|
||||
if (recTrans) {
|
||||
this.AddTransactions([recTrans]);
|
||||
account.Transactions.unshift(recTrans.ID);
|
||||
}
|
||||
},
|
||||
logout() {
|
||||
this.$reset();
|
||||
},
|
||||
async saveTransaction(payload: string) {
|
||||
const accountsStore = useAccountStore();
|
||||
const result = await POST("/transaction/new", payload);
|
||||
const response = (await result.json()) as Transaction;
|
||||
this.AddTransactions([response]);
|
||||
accountsStore.CurrentAccount?.Transactions.unshift(response.ID);
|
||||
},
|
||||
async editTransaction(transactionid: string, payload: string) {
|
||||
const result = await POST("/transaction/" + transactionid, payload);
|
||||
const response = (await result.json()) as Transaction;
|
||||
this.AddTransactions([response]);
|
||||
},
|
||||
},
|
||||
});
|
@ -1,10 +1,7 @@
|
||||
module.exports = {
|
||||
content: [
|
||||
"./index.html",
|
||||
"./src/**/*.{vue,js,ts,jsx,tsx}"
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
content: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
|
@ -1,10 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
// this enables stricter inference for data properties on `this`
|
||||
"strict": true,
|
||||
"jsx": "preserve",
|
||||
"moduleResolution": "node"
|
||||
}
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
// this enables stricter inference for data properties on `this`
|
||||
"strict": true,
|
||||
"jsx": "preserve",
|
||||
"moduleResolution": "node"
|
||||
}
|
||||
}
|
@ -1,30 +1,30 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { defineConfig } from "vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
|
||||
import path from 'path'
|
||||
import path from "path";
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
|
||||
],
|
||||
define: { 'process.env': {} },
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, 'src'),
|
||||
plugins: [
|
||||
vue(),
|
||||
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
|
||||
],
|
||||
define: { "process.env": {} },
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "src"),
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://10.0.0.162:1323/',
|
||||
changeOrigin: true
|
||||
}
|
||||
}
|
||||
}
|
||||
/* remove the need to specify .vue files https://vitejs.dev/config/#resolve-extensions
|
||||
server: {
|
||||
host: "0.0.0.0",
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://10.0.0.162:1323/",
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
/* remove the need to specify .vue files https://vitejs.dev/config/#resolve-extensions
|
||||
resolve: {
|
||||
extensions: [
|
||||
'.js',
|
||||
@ -37,4 +37,4 @@ export default defineConfig({
|
||||
]
|
||||
},
|
||||
*/
|
||||
})
|
||||
});
|
||||
|
889
web/yarn.lock
889
web/yarn.lock
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user