3 Commits

Author SHA1 Message Date
8fbdd78cb3 Add Transaction to list after saving
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2022-02-15 09:14:06 +00:00
b3ff5cf055 Extract component for new Transaction 2022-02-15 09:14:06 +00:00
a09511061f Handle new Payees 2022-02-15 09:14:06 +00:00
114 changed files with 2278 additions and 5369 deletions

View File

@@ -4,23 +4,11 @@ type: docker
name: budgeteer name: budgeteer
steps: steps:
- name: Taskfile.dev PR
image: hub.javil.eu/budgeteer:dev
commands:
- task ci
when:
event:
- pull_request
- name: Taskfile.dev - name: Taskfile.dev
image: hub.javil.eu/budgeteer:dev image: hub.javil.eu/budgeteer:dev
pull: always pull: true
commands: commands:
- task ci - task
when:
event:
exclude:
- pull_request
- name: docker - name: docker
image: plugins/docker image: plugins/docker
@@ -32,30 +20,14 @@ steps:
from_secret: docker_password from_secret: docker_password
repo: hub.javil.eu/budgeteer repo: hub.javil.eu/budgeteer
context: build context: build
dockerfile: docker/Dockerfile dockerfile: build/Dockerfile
tags: tags:
- latest - latest
when: when:
branch:
- master
event: event:
- push exclude:
- pull_request
- name: docker tag
image: plugins/docker
settings:
registry: hub.javil.eu
username:
from_secret: docker_user
password:
from_secret: docker_password
repo: hub.javil.eu/budgeteer
context: build
dockerfile: docker/Dockerfile
auto_tag: true
when:
event:
- tag
image_pull_secrets: image_pull_secrets:
- hub.javil.eu - hub.javil.eu

10
.earthignore Normal file
View File

@@ -0,0 +1,10 @@
build/
.git/
docker-compose.yml
README.md
Earthfile
config.example.json
.gitignore
.vscode/
budgeteer
budgeteer.exe

View File

@@ -1,27 +0,0 @@
linters:
enable-all: true
disable:
- golint
- scopelint
- maligned
- interfacer
- wsl
- forbidigo
- nlreturn
- testpackage
- ifshort
- exhaustivestruct
- gci # not working, shows errors on freshly formatted file
- varnamelen
- lll
linters-settings:
errcheck:
exclude-functions:
- io/ioutil.ReadFile
- io.Copy(*bytes.Buffer)
- (*github.com/gin-gonic/gin.Context).AbortWithError
- (*github.com/gin-gonic/gin.Context).AbortWithError
- io.Copy(os.Stdout)
varnamelen:
ignore-decls:
- c *gin.Context

View File

@@ -1,13 +1,6 @@
{ {
"files.exclude": { "files.exclude": {
"**/node_modules": true, "**/node_modules": true,
"**/vendor": true, "**/vendor": true
"**/*.sql.go": true,
".task/": true,
"build/": true,
"web/dist/": true
},
"gopls": {
"formatting.gofumpt": true,
} }
} }

23
.woodpecker.yml Normal file
View File

@@ -0,0 +1,23 @@
pipeline:
build:
name: Taskfile.dev
image: hub.javil.eu/budgeteer:dev
pull: true
commands:
- task
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 Normal file
View File

@@ -0,0 +1,21 @@
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

View File

@@ -33,7 +33,12 @@ tasks:
sources: sources:
- ./go.mod - ./go.mod
- ./go.sum - ./go.sum
- ./**/*.go - ./cmd/budgeteer/*.go
- ./*.go
- ./config/*.go
- ./http/*.go
- ./jwt/*.go
- ./postgres/*.go
- ./web/dist/**/* - ./web/dist/**/*
- ./postgres/schema/* - ./postgres/schema/*
generates: generates:
@@ -47,26 +52,14 @@ tasks:
desc: Build budgeteer in dev mode desc: Build budgeteer in dev mode
deps: [gomod, sqlc] deps: [gomod, sqlc]
cmds: cmds:
- go vet
- go fmt
- golangci-lint run
- task: build - task: build
build-prod: build-prod:
desc: Build budgeteer in prod mode desc: Build budgeteer in prod mode
deps: [gomod, sqlc, frontend] deps: [gomod, sqlc, frontend]
cmds: cmds:
- go vet
- go fmt
- golangci-lint run
- task: build - task: build
ci:
desc: Run CI build
cmds:
- task: build-prod
- go test ./...
frontend: frontend:
desc: Build vue frontend desc: Build vue frontend
dir: web dir: web
@@ -77,8 +70,6 @@ tasks:
cmds: cmds:
- yarn - yarn
- yarn build - yarn build
- yarn run vue-tsc --noEmit
- yarn run eslint "./src/**"
docker: docker:
desc: Build budgeeter:latest desc: Build budgeeter:latest
@@ -94,10 +85,8 @@ tasks:
desc: Build budgeeter:dev desc: Build budgeeter:dev
sources: sources:
- ./docker/Dockerfile - ./docker/Dockerfile
- ./docker/build.sh
- ./web/package.json
cmds: cmds:
- docker build -t {{.IMAGE_NAME}}:dev . -f docker/Dockerfile.dev - docker build -t {{.IMAGE_NAME}}:dev . -f docker/Dockerfile
- docker push {{.IMAGE_NAME}}:dev - docker push {{.IMAGE_NAME}}:dev
run: run:

View File

@@ -1,30 +1,23 @@
package bcrypt package bcrypt
import ( import "golang.org/x/crypto/bcrypt"
"fmt"
"golang.org/x/crypto/bcrypt" // Verifier verifys passwords using Bcrypt
) type Verifier struct {
cost int
// Verifier verifys passwords using Bcrypt.
type Verifier struct{}
// Verify verifys a Password.
func (bv *Verifier) Verify(password string, hashOnDB string) error {
err := bcrypt.CompareHashAndPassword([]byte(hashOnDB), []byte(password))
if err != nil {
return fmt.Errorf("verify password: %w", err)
}
return nil
} }
// Hash calculates a hash to be stored on the database. // Verify verifys a Password
func (bv *Verifier) Verify(password string, hashOnDb string) error {
return bcrypt.CompareHashAndPassword([]byte(hashOnDb), []byte(password))
}
// Hash calculates a hash to be stored on the database
func (bv *Verifier) Hash(password string) (string, error) { func (bv *Verifier) Hash(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) hash, err := bcrypt.GenerateFromPassword([]byte(password), bv.cost)
if err != nil { if err != nil {
return "", fmt.Errorf("hash password: %w", err) return "", err
} }
return string(hash), nil return string(hash[:]), nil
} }

3
build/Dockerfile Normal file
View File

@@ -0,0 +1,3 @@
FROM scratch
COPY ./budgeteer /app/budgeteer
ENTRYPOINT ["/app/budgeteer"]

View File

@@ -1,17 +1,13 @@
package main package main
import ( import (
"fmt"
"io/fs"
"log" "log"
"net/http"
"git.javil.eu/jacob1123/budgeteer/bcrypt" "git.javil.eu/jacob1123/budgeteer/bcrypt"
"git.javil.eu/jacob1123/budgeteer/config" "git.javil.eu/jacob1123/budgeteer/config"
"git.javil.eu/jacob1123/budgeteer/http"
"git.javil.eu/jacob1123/budgeteer/jwt" "git.javil.eu/jacob1123/budgeteer/jwt"
"git.javil.eu/jacob1123/budgeteer/postgres" "git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/server"
"git.javil.eu/jacob1123/budgeteer/web"
) )
func main() { func main() {
@@ -20,27 +16,16 @@ func main() {
log.Fatalf("Could not load config: %v", err) log.Fatalf("Could not load config: %v", err)
} }
queries, err := postgres.Connect("pgx", cfg.DatabaseConnection) q, err := postgres.Connect("pgx", cfg.DatabaseConnection)
if err != nil { if err != nil {
log.Fatalf("Failed connecting to DB: %v", err) log.Fatalf("Failed connecting to DB: %v", err)
} }
static, err := fs.Sub(web.Static, "dist") h := &http.Handler{
if err != nil { Service: q,
panic("couldn't open static files") TokenVerifier: &jwt.TokenVerifier{},
}
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: tokenVerifier,
CredentialsVerifier: &bcrypt.Verifier{}, CredentialsVerifier: &bcrypt.Verifier{},
StaticFS: http.FS(static),
} }
handler.Serve() h.Serve()
} }

6
config.example.json Normal file
View File

@@ -0,0 +1,6 @@
{
"DatabaseHost": "localhost",
"DatabaseUser": "user",
"DatabasePassword": "thisismypassword",
"DatabaseName": "budgeteer"
}

View File

@@ -4,17 +4,15 @@ import (
"os" "os"
) )
// Config contains all needed configurations. // Config contains all needed configurations
type Config struct { type Config struct {
DatabaseConnection string DatabaseConnection string
SessionSecret string
} }
// LoadConfig from path. // LoadConfig from path
func LoadConfig() (*Config, error) { func LoadConfig() (*Config, error) {
configuration := Config{ configuration := Config{
DatabaseConnection: os.Getenv("BUDGETEER_DB"), DatabaseConnection: os.Getenv("BUDGETEER_DB"),
SessionSecret: os.Getenv("BUDGETEER_SESSION_SECRET"),
} }
return &configuration, nil return &configuration, nil

View File

@@ -17,7 +17,6 @@ services:
- ~/.cache:/.cache - ~/.cache:/.cache
environment: environment:
BUDGETEER_DB: postgres://budgeteer:budgeteer@db:5432/budgeteer BUDGETEER_DB: postgres://budgeteer:budgeteer@db:5432/budgeteer
BUDGETEER_SESSION_SECRET: random string for JWT authorization
depends_on: depends_on:
- db - db

View File

@@ -1,3 +1,16 @@
FROM scratch FROM alpine as godeps
COPY ./budgeteer /app/budgeteer RUN apk add go
ENTRYPOINT ["/app/budgeteer"] RUN go install github.com/kyleconroy/sqlc/cmd/sqlc@latest
RUN go install github.com/go-task/task/v3/cmd/task@latest
FROM alpine
RUN apk add go
RUN apk add nodejs yarn bash curl git git-perl tmux
ADD docker/build.sh /
COPY --from=godeps /root/go/bin/task /root/go/bin/sqlc /usr/local/bin/
RUN yarn global add @vue/cli
ENV PATH="/root/.yarn/bin/:${PATH}"
WORKDIR /src
ADD web/package.json /src/web/
RUN yarn
CMD /build.sh

View File

@@ -1,17 +0,0 @@
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
View File

@@ -11,7 +11,7 @@ require (
golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa
) )
require github.com/DATA-DOG/go-txdb v0.1.5 require github.com/DATA-DOG/go-txdb v0.1.5 // indirect
require ( require (
github.com/gin-contrib/sse v0.1.0 // indirect github.com/gin-contrib/sse v0.1.0 // indirect

1
go.sum
View File

@@ -74,7 +74,6 @@ github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=

37
http/account.go Normal file
View File

@@ -0,0 +1,37 @@
package http
import (
"net/http"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func (h *Handler) transactionsForAccount(c *gin.Context) {
accountID := c.Param("accountid")
accountUUID, err := uuid.Parse(accountID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
account, err := h.Service.GetAccount(c.Request.Context(), accountUUID)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
transactions, err := h.Service.GetTransactionsForAccount(c.Request.Context(), accountUUID)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
c.JSON(http.StatusOK, TransactionsResponse{account, transactions})
}
type TransactionsResponse struct {
Account postgres.Account
Transactions []postgres.GetTransactionsForAccountRow
}

View File

@@ -1,8 +1,7 @@
package server package http
import ( import (
"encoding/json" "encoding/json"
"fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
@@ -11,53 +10,47 @@ import (
"git.javil.eu/jacob1123/budgeteer/bcrypt" "git.javil.eu/jacob1123/budgeteer/bcrypt"
"git.javil.eu/jacob1123/budgeteer/jwt" "git.javil.eu/jacob1123/budgeteer/jwt"
"git.javil.eu/jacob1123/budgeteer/postgres" "git.javil.eu/jacob1123/budgeteer/postgres"
txdb "github.com/DATA-DOG/go-txdb"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
txdb "github.com/DATA-DOG/go-txdb"
) )
func init() { //nolint:gochecknoinits func init() {
txdb.Register("pgtx", "pgx", "postgres://budgeteer_test:budgeteer_test@localhost:5432/budgeteer_test") txdb.Register("pgtx", "pgx", "postgres://budgeteer_test:budgeteer_test@localhost:5432/budgeteer_test")
} }
func TestRegisterUser(t *testing.T) { //nolint:funlen func TestListTimezonesHandler(t *testing.T) {
t.Parallel() db, err := postgres.Connect("pgtx", "example")
database, err := postgres.Connect("pgtx", "example")
if err != nil { if err != nil {
fmt.Printf("could not connect to db: %s\n", err) t.Errorf("could not connect to db: %s", err)
t.Skip()
return return
} }
tokenVerifier, _ := jwt.NewTokenVerifier("this_is_my_demo_secret_for_unit_tests")
h := Handler{ h := Handler{
Service: database, Service: db,
TokenVerifier: tokenVerifier, TokenVerifier: &jwt.TokenVerifier{},
CredentialsVerifier: &bcrypt.Verifier{}, CredentialsVerifier: &bcrypt.Verifier{},
} }
recorder := httptest.NewRecorder() rr := httptest.NewRecorder()
context, engine := gin.CreateTestContext(recorder) c, engine := gin.CreateTestContext(rr)
h.LoadRoutes(engine) h.LoadRoutes(engine)
t.Run("RegisterUser", func(t *testing.T) { t.Run("RegisterUser", func(t *testing.T) {
t.Parallel() c.Request, err = http.NewRequest(http.MethodPost, "/api/v1/user/register", strings.NewReader(`{"password":"pass","email":"info@example.com","name":"Test"}`))
context.Request, err = http.NewRequest(
http.MethodPost,
"/api/v1/user/register",
strings.NewReader(`{"password":"pass","email":"info@example.com","name":"Test"}`))
if err != nil { if err != nil {
t.Errorf("error creating request: %s", err) t.Errorf("error creating request: %s", err)
return return
} }
h.registerPost(context) h.registerPost(c)
if recorder.Code != http.StatusOK { if rr.Code != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", recorder.Code, http.StatusOK) t.Errorf("handler returned wrong status code: got %v want %v", rr.Code, http.StatusOK)
} }
var response LoginResponse var response LoginResponse
err = json.NewDecoder(recorder.Body).Decode(&response) err = json.NewDecoder(rr.Body).Decode(&response)
if err != nil { if err != nil {
t.Error(err.Error()) t.Error(err.Error())
t.Error("Error registering") t.Error("Error registering")
@@ -68,14 +61,13 @@ func TestRegisterUser(t *testing.T) { //nolint:funlen
}) })
t.Run("GetTransactions", func(t *testing.T) { t.Run("GetTransactions", func(t *testing.T) {
t.Parallel() c.Request, err = http.NewRequest(http.MethodGet, "/account/accountid/transactions", nil)
context.Request, err = http.NewRequest(http.MethodGet, "/account/accountid/transactions", nil) if rr.Code != http.StatusOK {
if recorder.Code != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", rr.Code, http.StatusOK)
t.Errorf("handler returned wrong status code: got %v want %v", recorder.Code, http.StatusOK)
} }
var response TransactionsResponse var response TransactionsResponse
err = json.NewDecoder(recorder.Body).Decode(&response) err = json.NewDecoder(rr.Body).Decode(&response)
if err != nil { if err != nil {
t.Error(err.Error()) t.Error(err.Error())
t.Error("Error retreiving list of transactions.") t.Error("Error retreiving list of transactions.")

View File

@@ -1,4 +1,4 @@
package server package http
import ( import (
"fmt" "fmt"

54
http/autocomplete.go Normal file
View File

@@ -0,0 +1,54 @@
package http
import (
"fmt"
"net/http"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func (h *Handler) autocompleteCategories(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("budgetid missing from URL"))
return
}
query := c.Request.URL.Query().Get("s")
searchParams := postgres.SearchCategoriesParams{
BudgetID: budgetUUID,
Search: "%" + query + "%",
}
categories, err := h.Service.SearchCategories(c.Request.Context(), searchParams)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, categories)
}
func (h *Handler) autocompletePayee(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("budgetid missing from URL"))
return
}
query := c.Request.URL.Query().Get("s")
searchParams := postgres.SearchPayeesParams{
BudgetID: budgetUUID,
Search: query + "%",
}
payees, err := h.Service.SearchPayees(c.Request.Context(), searchParams)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, payees)
}

View File

@@ -1,8 +1,10 @@
package server package http
import ( import (
"fmt"
"net/http" "net/http"
"git.javil.eu/jacob1123/budgeteer"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -12,17 +14,18 @@ type newBudgetInformation struct {
func (h *Handler) newBudget(c *gin.Context) { func (h *Handler) newBudget(c *gin.Context) {
var newBudget newBudgetInformation var newBudget newBudgetInformation
if err := c.BindJSON(&newBudget); err != nil { err := c.BindJSON(&newBudget)
if err != nil {
c.AbortWithError(http.StatusNotAcceptable, err) c.AbortWithError(http.StatusNotAcceptable, err)
return return
} }
if newBudget.Name == "" { if newBudget.Name == "" {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"budget name is required"}) c.AbortWithError(http.StatusNotAcceptable, fmt.Errorf("Budget name is needed"))
return return
} }
userID := MustGetToken(c).GetID() userID := c.MustGet("token").(budgeteer.Token).GetID()
budget, err := h.Service.NewBudget(c.Request.Context(), newBudget.Name, userID) budget, err := h.Service.NewBudget(c.Request.Context(), newBudget.Name, userID)
if err != nil { if err != nil {
c.AbortWithError(http.StatusInternalServerError, err) c.AbortWithError(http.StatusInternalServerError, err)

216
http/budgeting.go Normal file
View File

@@ -0,0 +1,216 @@
package http
import (
"fmt"
"net/http"
"strconv"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func getFirstOfMonth(year, month int, location *time.Location) time.Time {
return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, location)
}
func getFirstOfMonthTime(date time.Time) time.Time {
var monthM time.Month
year, monthM, _ := date.Date()
month := int(monthM)
return getFirstOfMonth(year, month, date.Location())
}
type CategoryWithBalance struct {
*postgres.GetCategoriesRow
Available postgres.Numeric
AvailableLastMonth postgres.Numeric
Activity postgres.Numeric
Assigned postgres.Numeric
}
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)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("budgetid missing from URL"))
return
}
budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
firstOfMonth, err := getDate(c)
if err != nil {
c.Redirect(http.StatusTemporaryRedirect, "/budget/"+budgetUUID.String())
return
}
categories, err := h.Service.GetCategories(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
firstOfNextMonth := firstOfMonth.AddDate(0, 1, 0)
cumultativeBalances, err := h.Service.GetCumultativeBalances(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("load balances: %w", err))
return
}
// skip everything in the future
categoriesWithBalance, moneyUsed, err := h.calculateBalances(c, budget, firstOfNextMonth, firstOfMonth, categories, cumultativeBalances)
if err != nil {
return
}
availableBalance := postgres.NewZeroNumeric()
for _, cat := range categories {
if cat.ID != 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)
}
}
data := struct {
Categories []CategoryWithBalance
AvailableBalance postgres.Numeric
}{categoriesWithBalance, availableBalance}
c.JSON(http.StatusOK, data)
}
func (h *Handler) budgeting(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("budgetid missing from URL"))
return
}
budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
accounts, err := h.Service.GetAccountsWithBalance(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
data := struct {
Accounts []postgres.GetAccountsWithBalanceRow
Budget postgres.Budget
}{accounts, budget}
c.JSON(http.StatusOK, data)
}
func (h *Handler) calculateBalances(c *gin.Context, budget postgres.Budget, firstOfNextMonth time.Time, firstOfMonth time.Time, categories []postgres.GetCategoriesRow, cumultativeBalances []postgres.GetCumultativeBalancesRow) ([]CategoryWithBalance, postgres.Numeric, error) {
categoriesWithBalance := []CategoryWithBalance{}
hiddenCategory := CategoryWithBalance{
GetCategoriesRow: &postgres.GetCategoriesRow{
Name: "",
Group: "Hidden Categories",
},
Available: postgres.NewZeroNumeric(),
AvailableLastMonth: postgres.NewZeroNumeric(),
Activity: postgres.NewZeroNumeric(),
Assigned: postgres.NewZeroNumeric(),
}
moneyUsed := postgres.NewZeroNumeric()
for i := range categories {
cat := &categories[i]
categoryWithBalance := CategoryWithBalance{
GetCategoriesRow: cat,
Available: postgres.NewZeroNumeric(),
AvailableLastMonth: postgres.NewZeroNumeric(),
Activity: postgres.NewZeroNumeric(),
Assigned: postgres.NewZeroNumeric(),
}
for _, bal := range cumultativeBalances {
if bal.CategoryID != cat.ID {
continue
}
if !bal.Date.Before(firstOfNextMonth) {
continue
}
moneyUsed = moneyUsed.Sub(bal.Assignments)
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Assignments)
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Transactions)
if !categoryWithBalance.Available.IsPositive() && bal.Date.Before(firstOfMonth) {
moneyUsed = moneyUsed.Add(categoryWithBalance.Available)
categoryWithBalance.Available = postgres.NewZeroNumeric()
}
if bal.Date.Before(firstOfMonth) {
categoryWithBalance.AvailableLastMonth = categoryWithBalance.Available
} else if bal.Date.Before(firstOfNextMonth) {
categoryWithBalance.Activity = bal.Transactions
categoryWithBalance.Assigned = bal.Assignments
}
}
// do not show hidden categories
if cat.Group == "Hidden Categories" {
hiddenCategory.Available = hiddenCategory.Available.Add(categoryWithBalance.Available)
hiddenCategory.AvailableLastMonth = hiddenCategory.AvailableLastMonth.Add(categoryWithBalance.AvailableLastMonth)
hiddenCategory.Activity = hiddenCategory.Activity.Add(categoryWithBalance.Activity)
hiddenCategory.Assigned = hiddenCategory.Assigned.Add(categoryWithBalance.Assigned)
continue
}
if cat.ID == budget.IncomeCategoryID {
continue
}
categoriesWithBalance = append(categoriesWithBalance, categoryWithBalance)
}
categoriesWithBalance = append(categoriesWithBalance, hiddenCategory)
return categoriesWithBalance, moneyUsed, nil
}

View File

@@ -1,14 +1,15 @@
package server package http
import ( import (
"net/http" "net/http"
"git.javil.eu/jacob1123/budgeteer"
"git.javil.eu/jacob1123/budgeteer/postgres" "git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func (h *Handler) dashboard(c *gin.Context) { func (h *Handler) dashboard(c *gin.Context) {
userID := MustGetToken(c).GetID() userID := c.MustGet("token").(budgeteer.Token).GetID()
budgets, err := h.Service.GetBudgetsForUser(c.Request.Context(), userID) budgets, err := h.Service.GetBudgetsForUser(c.Request.Context(), userID)
if err != nil { if err != nil {
return return

View File

@@ -1,4 +1,4 @@
package server package http
import ( import (
"errors" "errors"
@@ -11,10 +11,12 @@ import (
"git.javil.eu/jacob1123/budgeteer" "git.javil.eu/jacob1123/budgeteer"
"git.javil.eu/jacob1123/budgeteer/bcrypt" "git.javil.eu/jacob1123/budgeteer/bcrypt"
"git.javil.eu/jacob1123/budgeteer/postgres" "git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/web"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// Handler handles incoming requests. // Handler handles incoming requests
type Handler struct { type Handler struct {
Service *postgres.Database Service *postgres.Database
TokenVerifier budgeteer.TokenVerifier TokenVerifier budgeteer.TokenVerifier
@@ -22,63 +24,63 @@ type Handler struct {
StaticFS http.FileSystem StaticFS http.FileSystem
} }
// Serve starts the http server. const (
expiration = 72
)
// Serve starts the http server
func (h *Handler) Serve() { func (h *Handler) Serve() {
router := gin.Default() router := gin.Default()
h.LoadRoutes(router) h.LoadRoutes(router)
router.Run(":1323")
if err := router.Run(":1323"); err != nil {
panic(err)
}
} }
type ErrorResponse struct { // LoadRoutes initializes all the routes
Message string
}
type SuccessResponse struct {
Message string
}
// LoadRoutes initializes all the routes.
func (h *Handler) LoadRoutes(router *gin.Engine) { func (h *Handler) LoadRoutes(router *gin.Engine) {
static, err := fs.Sub(web.Static, "dist")
if err != nil {
panic("couldn't open static files")
}
h.StaticFS = http.FS(static)
router.Use(enableCachingForStaticFiles()) router.Use(enableCachingForStaticFiles())
router.NoRoute(h.ServeStatic) router.NoRoute(h.ServeStatic)
withLogin := router.Group("")
withLogin.Use(h.verifyLoginWithRedirect)
withBudget := router.Group("")
withBudget.Use(h.verifyLoginWithForbidden)
withBudget.GET("/budget/:budgetid/:year/:month", h.budgeting)
withBudget.GET("/budget/:budgetid/settings/clean-negative", h.cleanNegativeBudget)
api := router.Group("/api/v1") api := router.Group("/api/v1")
anonymous := api.Group("/user") unauthenticated := api.Group("/user")
anonymous.GET("/login", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/login") }) unauthenticated.GET("/login", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/login") })
anonymous.POST("/login", h.loginPost) unauthenticated.POST("/login", h.loginPost)
anonymous.POST("/register", h.registerPost) unauthenticated.POST("/register", h.registerPost)
authenticated := api.Group("") authenticated := api.Group("")
authenticated.Use(h.verifyLoginWithForbidden) authenticated.Use(h.verifyLoginWithForbidden)
authenticated.GET("/dashboard", h.dashboard) authenticated.GET("/dashboard", h.dashboard)
authenticated.GET("/account/:accountid/transactions", h.transactionsForAccount) authenticated.GET("/account/:accountid/transactions", h.transactionsForAccount)
authenticated.POST("/account/:accountid/reconcile", h.reconcileTransactions)
authenticated.POST("/account/:accountid", h.editAccount)
authenticated.GET("/admin/clear-database", h.clearDatabase) authenticated.GET("/admin/clear-database", h.clearDatabase)
authenticated.GET("/budget/:budgetid", h.budgeting)
authenticated.GET("/budget/:budgetid/:year/:month", h.budgetingForMonth)
authenticated.GET("/budget/:budgetid/autocomplete/payees", h.autocompletePayee)
authenticated.GET("/budget/:budgetid/autocomplete/categories", h.autocompleteCategories)
authenticated.DELETE("/budget/:budgetid", h.deleteBudget)
authenticated.POST("/budget/:budgetid/import/ynab", h.importYNAB)
authenticated.POST("/budget/:budgetid/settings/clear", h.clearBudget)
budget := authenticated.Group("/budget") budget := authenticated.Group("/budget")
budget.POST("/new", h.newBudget) budget.POST("/new", h.newBudget)
budget.GET("/:budgetid", h.budgeting)
budget.GET("/:budgetid/: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)
budget.POST("/:budgetid/import/ynab", h.importYNAB)
budget.POST("/:budgetid/export/ynab/transactions", h.exportYNABTransactions)
budget.POST("/:budgetid/export/ynab/assignments", h.exportYNABAssignments)
budget.POST("/:budgetid/settings/clear", h.clearBudget)
budget.POST("/:budgetid/settings/clean-negative", h.cleanNegativeBudget)
transaction := authenticated.Group("/transaction") transaction := authenticated.Group("/transaction")
transaction.POST("/new", h.newTransaction) transaction.POST("/new", h.newTransaction)
transaction.POST("/:transactionid", h.newTransaction) transaction.POST("/:transactionid", h.newTransaction)
} }
func (h *Handler) ServeStatic(c *gin.Context) { func (h *Handler) ServeStatic(c *gin.Context) {
h.ServeStaticFile(c, c.Request.URL.Path) h.ServeStaticFile(c, c.Request.URL.Path)
} }
@@ -106,11 +108,7 @@ func (h *Handler) ServeStaticFile(c *gin.Context, fullPath string) {
return return
} }
if file, ok := file.(io.ReadSeeker); ok { http.ServeContent(c.Writer, c.Request, stat.Name(), stat.ModTime(), file.(io.ReadSeeker))
http.ServeContent(c.Writer, c.Request, stat.Name(), stat.ModTime(), file)
} else {
panic("File does not implement ReadSeeker")
}
} }
func enableCachingForStaticFiles() gin.HandlerFunc { func enableCachingForStaticFiles() gin.HandlerFunc {

View File

@@ -1,36 +1,29 @@
package server package http
import ( import (
"encoding/json" "encoding/json"
"fmt"
"strings" "strings"
"time" "time"
) )
type JSONDate time.Time type JSONDate time.Time
// UnmarshalJSON parses the JSONDate from a JSON input. // Implement Marshaler and Unmarshaler interface
func (j *JSONDate) UnmarshalJSON(b []byte) error { func (j *JSONDate) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), "\"") s := strings.Trim(string(b), "\"")
t, err := time.Parse("2006-01-02", s) t, err := time.Parse("2006-01-02", s)
if err != nil { if err != nil {
return fmt.Errorf("parse date: %w", err) return err
} }
*j = JSONDate(t) *j = JSONDate(t)
return nil return nil
} }
// MarshalJSON converts the JSONDate to a JSON in ISO format.
func (j JSONDate) MarshalJSON() ([]byte, error) { func (j JSONDate) MarshalJSON() ([]byte, error) {
result, err := json.Marshal(time.Time(j)) return json.Marshal(time.Time(j))
if err != nil {
return nil, fmt.Errorf("marshal date: %w", err)
}
return result, nil
} }
// Format formats the time using the regular time.Time mechanics.. // Maybe a Format function for printing your date
func (j JSONDate) Format(s string) string { func (j JSONDate) Format(s string) string {
t := time.Time(j) t := time.Time(j)
return t.Format(s) return t.Format(s)

View File

@@ -1,4 +1,4 @@
package server package http
import ( import (
"context" "context"
@@ -8,34 +8,18 @@ import (
"git.javil.eu/jacob1123/budgeteer" "git.javil.eu/jacob1123/budgeteer"
"git.javil.eu/jacob1123/budgeteer/postgres" "git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/google/uuid"
) )
const ( func (h *Handler) verifyLogin(c *gin.Context) (budgeteer.Token, error) {
HeaderName = "Authorization" tokenString := c.GetHeader("Authorization")
Bearer = "Bearer " if len(tokenString) < 8 {
ParamName = "token" return nil, fmt.Errorf("no authorization header supplied")
)
func MustGetToken(c *gin.Context) budgeteer.Token { //nolint:ireturn
token := c.MustGet(ParamName)
if token, ok := token.(budgeteer.Token); ok {
return token
}
panic("Token is not a valid Token")
}
func (h *Handler) verifyLogin(c *gin.Context) (budgeteer.Token, *ErrorResponse) { //nolint:ireturn
tokenString := c.GetHeader(HeaderName)
if len(tokenString) <= len(Bearer) {
return nil, &ErrorResponse{"no authorization header supplied"}
} }
tokenString = tokenString[7:] tokenString = tokenString[7:]
token, err := h.TokenVerifier.VerifyToken(tokenString) token, err := h.TokenVerifier.VerifyToken(tokenString)
if err != nil { if err != nil {
return nil, &ErrorResponse{fmt.Sprintf("verify token '%s': %s", tokenString, err)} return nil, fmt.Errorf("verify token '%s': %w", tokenString, err)
} }
return token, nil return token, nil
@@ -44,12 +28,24 @@ func (h *Handler) verifyLogin(c *gin.Context) (budgeteer.Token, *ErrorResponse)
func (h *Handler) verifyLoginWithForbidden(c *gin.Context) { func (h *Handler) verifyLoginWithForbidden(c *gin.Context) {
token, err := h.verifyLogin(c) token, err := h.verifyLogin(c)
if err != nil { if err != nil {
// c.Header("WWW-Authenticate", "Bearer") //c.Header("WWW-Authenticate", "Bearer")
c.AbortWithStatusJSON(http.StatusForbidden, err) c.AbortWithError(http.StatusForbidden, err)
return return
} }
c.Set(ParamName, token) c.Set("token", token)
c.Next()
}
func (h *Handler) verifyLoginWithRedirect(c *gin.Context) {
token, err := h.verifyLogin(c)
if err != nil {
c.Redirect(http.StatusTemporaryRedirect, "/login")
c.Abort()
return
}
c.Set("token", token)
c.Next() c.Next()
} }
@@ -76,19 +72,19 @@ func (h *Handler) loginPost(c *gin.Context) {
return return
} }
token, err := h.TokenVerifier.CreateToken(&user) t, err := h.TokenVerifier.CreateToken(&user)
if err != nil { if err != nil {
c.AbortWithError(http.StatusUnauthorized, err) c.AbortWithError(http.StatusUnauthorized, err)
} }
go h.UpdateLastLogin(user.ID) go h.Service.UpdateLastLogin(context.Background(), user.ID)
budgets, err := h.Service.GetBudgetsForUser(c.Request.Context(), user.ID) budgets, err := h.Service.GetBudgetsForUser(c.Request.Context(), user.ID)
if err != nil { if err != nil {
return return
} }
c.JSON(http.StatusOK, LoginResponse{token, user, budgets}) c.JSON(http.StatusOK, LoginResponse{t, user, budgets})
} }
type LoginResponse struct { type LoginResponse struct {
@@ -105,20 +101,16 @@ type registerInformation struct {
func (h *Handler) registerPost(c *gin.Context) { func (h *Handler) registerPost(c *gin.Context) {
var register registerInformation var register registerInformation
err := c.BindJSON(&register) c.BindJSON(&register)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"error parsing body"})
return
}
if register.Email == "" || register.Password == "" || register.Name == "" { if register.Email == "" || register.Password == "" || register.Name == "" {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"e-mail, password and name are required"}) c.AbortWithError(http.StatusBadRequest, fmt.Errorf("e-mail, password and name are required"))
return return
} }
_, err = h.Service.GetUserByUsername(c.Request.Context(), register.Email) _, err := h.Service.GetUserByUsername(c.Request.Context(), register.Email)
if err == nil { if err == nil {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"email is already taken"}) c.AbortWithError(http.StatusBadRequest, fmt.Errorf("email is already taken"))
return return
} }
@@ -138,24 +130,17 @@ func (h *Handler) registerPost(c *gin.Context) {
c.AbortWithError(http.StatusInternalServerError, err) c.AbortWithError(http.StatusInternalServerError, err)
} }
token, err := h.TokenVerifier.CreateToken(&user) t, err := h.TokenVerifier.CreateToken(&user)
if err != nil { if err != nil {
c.AbortWithError(http.StatusUnauthorized, err) c.AbortWithError(http.StatusUnauthorized, err)
} }
go h.UpdateLastLogin(user.ID) go h.Service.UpdateLastLogin(context.Background(), user.ID)
budgets, err := h.Service.GetBudgetsForUser(c.Request.Context(), user.ID) budgets, err := h.Service.GetBudgetsForUser(c.Request.Context(), user.ID)
if err != nil { if err != nil {
return return
} }
c.JSON(http.StatusOK, LoginResponse{token, user, budgets}) c.JSON(http.StatusOK, LoginResponse{t, user, budgets})
}
func (h *Handler) UpdateLastLogin(userID uuid.UUID) {
_, err := h.Service.UpdateLastLogin(context.Background(), userID)
if err != nil {
fmt.Printf("Error updating last login: %s", err)
}
} }

105
http/transaction.go Normal file
View File

@@ -0,0 +1,105 @@
package http
import (
"fmt"
"net/http"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type NewTransactionPayload struct {
Date JSONDate `json:"date"`
Payee struct {
ID uuid.NullUUID
Name string
} `json:"payee"`
Category struct {
ID uuid.NullUUID
Name string
} `json:"category"`
Memo string `json:"memo"`
Amount string `json:"amount"`
BudgetID uuid.UUID `json:"budget_id"`
AccountID uuid.UUID `json:"account_id"`
State string `json:"state"`
}
func (h *Handler) newTransaction(c *gin.Context) {
var payload NewTransactionPayload
err := c.BindJSON(&payload)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
amount := postgres.Numeric{}
amount.Set(payload.Amount)
/*transactionUUID, err := getNullUUIDFromParam(c, "transactionid")
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("parse transaction id: %w", err))
return
}*/
payeeID := payload.Payee.ID
if !payeeID.Valid && payload.Payee.Name != "" {
newPayee := postgres.CreatePayeeParams{
Name: payload.Payee.Name,
BudgetID: payload.BudgetID,
}
payee, err := h.Service.CreatePayee(c.Request.Context(), newPayee)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create payee: %w", err))
}
payeeID = uuid.NullUUID{
UUID: payee.ID,
Valid: true,
}
}
//if !transactionUUID.Valid {
new := postgres.CreateTransactionParams{
Memo: payload.Memo,
Date: time.Time(payload.Date),
Amount: amount,
AccountID: payload.AccountID,
PayeeID: payeeID, //TODO handle new payee
CategoryID: payload.Category.ID, //TODO handle new category
Status: postgres.TransactionStatus(payload.State),
}
transaction, err := h.Service.CreateTransaction(c.Request.Context(), new)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create transaction: %w", err))
return
}
c.JSON(http.StatusOK, transaction)
// }
/*
_, delete := c.GetPostForm("delete")
if delete {
err = h.Service.DeleteTransaction(c.Request.Context(), transactionUUID.UUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("delete transaction: %w", err))
}
return
}
update := postgres.UpdateTransactionParams{
ID: transactionUUID.UUID,
Memo: payload.Memo,
Date: time.Time(payload.Date),
Amount: amount,
AccountID: transactionAccountID,
PayeeID: payload.Payee.ID, //TODO handle new payee
CategoryID: payload.Category.ID, //TODO handle new category
}
err = h.Service.UpdateTransaction(c.Request.Context(), update)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("update transaction: %w", err))
}*/
}

56
http/util.go Normal file
View File

@@ -0,0 +1,56 @@
package http
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func getUUID(c *gin.Context, name string) (uuid.UUID, error) {
value, succ := c.GetPostForm(name)
if !succ {
return uuid.UUID{}, fmt.Errorf("not set")
}
id, err := uuid.Parse(value)
if err != nil {
return uuid.UUID{}, fmt.Errorf("not a valid uuid: %w", err)
}
return id, nil
}
func getNullUUIDFromParam(c *gin.Context, name string) (uuid.NullUUID, error) {
value := c.Param(name)
if value == "" {
return uuid.NullUUID{}, nil
}
id, err := uuid.Parse(value)
if err != nil {
return uuid.NullUUID{}, fmt.Errorf("not a valid uuid: %w", err)
}
return uuid.NullUUID{
UUID: id,
Valid: true,
}, nil
}
func getNullUUIDFromForm(c *gin.Context, name string) (uuid.NullUUID, error) {
value, succ := c.GetPostForm(name)
if !succ || value == "" {
return uuid.NullUUID{}, nil
}
id, err := uuid.Parse(value)
if err != nil {
return uuid.NullUUID{}, fmt.Errorf("not a valid uuid: %w", err)
}
return uuid.NullUUID{
UUID: id,
Valid: true,
}, nil
}

66
http/ynab-import.go Normal file
View File

@@ -0,0 +1,66 @@
package http
import (
"fmt"
"net/http"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func (h *Handler) importYNAB(c *gin.Context) {
budgetID, succ := c.Params.Get("budgetid")
if !succ {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("no budget_id specified"))
return
}
budgetUUID, err := uuid.Parse(budgetID)
if !succ {
c.AbortWithError(http.StatusBadRequest, err)
return
}
ynab, err := postgres.NewYNABImport(c.Request.Context(), h.Service.Queries, budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
transactionsFile, err := c.FormFile("transactions")
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
transactions, err := transactionsFile.Open()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
err = ynab.ImportTransactions(transactions)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
assignmentsFile, err := c.FormFile("assignments")
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
assignments, err := assignmentsFile.Open()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
err = ynab.ImportAssignments(assignments)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}

105
jwt/login.go Normal file
View File

@@ -0,0 +1,105 @@
package jwt
import (
"fmt"
"time"
"git.javil.eu/jacob1123/budgeteer"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
)
// TokenVerifier verifies Tokens
type TokenVerifier struct {
}
// Token contains everything to authenticate a user
type Token struct {
username string
name string
expiry float64
id uuid.UUID
}
const (
expiration = 72
secret = "uditapbzuditagscwxuqdflgzpbu´ßiaefnlmzeßtrubiadern"
)
// CreateToken creates a new token from username and name
func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"usr": user.Email,
"name": user.Name,
"exp": time.Now().Add(time.Hour * expiration).Unix(),
"id": user.ID,
})
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(secret))
if err != nil {
return "", err
}
return t, nil
}
// VerifyToken verifys a given string-token
func (tv *TokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return nil, fmt.Errorf("parse jwt: %w", err)
}
claims, err := verifyToken(token)
if err != nil {
return nil, fmt.Errorf("verify jwt: %w", err)
}
tkn := &Token{
username: claims["usr"].(string),
name: claims["name"].(string),
expiry: claims["exp"].(float64),
id: uuid.MustParse(claims["id"].(string)),
}
return tkn, nil
}
func verifyToken(token *jwt.Token) (jwt.MapClaims, error) {
if !token.Valid {
return nil, fmt.Errorf("Token is not valid")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("Claims are not of Type MapClaims")
}
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
return nil, fmt.Errorf("Claims have expired")
}
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
}

View File

@@ -1,89 +0,0 @@
package jwt
import (
"fmt"
"time"
"git.javil.eu/jacob1123/budgeteer"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
)
// TokenVerifier verifies Tokens.
type TokenVerifier struct {
Expiration time.Duration
secret string
}
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
}
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(tv.Expiration).Unix(),
"id": user.ID,
})
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(tv.secret))
if err != nil {
return "", fmt.Errorf("create token: %w", err)
}
return t, nil
}
// 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
})
if err != nil {
return nil, fmt.Errorf("parse jwt: %w", err)
}
claims, err := verifyToken(token)
if err != nil {
return nil, fmt.Errorf("verify jwt: %w", err)
}
tkn := &Token{ //nolint:forcetypeassert
username: claims["usr"].(string),
name: claims["name"].(string),
expiry: claims["exp"].(float64),
id: uuid.MustParse(claims["id"].(string)),
}
return tkn, nil
}

View File

@@ -1,49 +0,0 @@
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
}

View File

@@ -5,9 +5,7 @@ package postgres
import ( import (
"context" "context"
"database/sql"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -15,7 +13,7 @@ const createAccount = `-- name: CreateAccount :one
INSERT INTO accounts INSERT INTO accounts
(name, budget_id) (name, budget_id)
VALUES ($1, $2) VALUES ($1, $2)
RETURNING id, budget_id, name, on_budget, is_open, last_reconciled RETURNING id, budget_id, name, on_budget
` `
type CreateAccountParams struct { type CreateAccountParams struct {
@@ -31,14 +29,12 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A
&i.BudgetID, &i.BudgetID,
&i.Name, &i.Name,
&i.OnBudget, &i.OnBudget,
&i.IsOpen,
&i.LastReconciled,
) )
return i, err return i, err
} }
const getAccount = `-- name: GetAccount :one const getAccount = `-- name: GetAccount :one
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled FROM accounts SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget FROM accounts
WHERE accounts.id = $1 WHERE accounts.id = $1
` `
@@ -50,16 +46,13 @@ func (q *Queries) GetAccount(ctx context.Context, id uuid.UUID) (Account, error)
&i.BudgetID, &i.BudgetID,
&i.Name, &i.Name,
&i.OnBudget, &i.OnBudget,
&i.IsOpen,
&i.LastReconciled,
) )
return i, err return i, err
} }
const getAccounts = `-- name: GetAccounts :many const getAccounts = `-- name: GetAccounts :many
SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled FROM accounts SELECT accounts.id, accounts.budget_id, accounts.name, accounts.on_budget FROM accounts
WHERE accounts.budget_id = $1 WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE
ORDER BY accounts.name ORDER BY accounts.name
` `
@@ -77,8 +70,6 @@ func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Accoun
&i.BudgetID, &i.BudgetID,
&i.Name, &i.Name,
&i.OnBudget, &i.OnBudget,
&i.IsOpen,
&i.LastReconciled,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -94,13 +85,11 @@ func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Accoun
} }
const getAccountsWithBalance = `-- name: GetAccountsWithBalance :many const getAccountsWithBalance = `-- name: GetAccountsWithBalance :many
SELECT accounts.id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled, SELECT accounts.id, accounts.name, accounts.on_budget, SUM(transactions.amount)::decimal(12,2) as balance
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW())::decimal(12,2) as working_balance,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status IN ('Cleared', 'Reconciled'))::decimal(12,2) as cleared_balance,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status = 'Reconciled')::decimal(12,2) as reconciled_balance
FROM accounts FROM accounts
LEFT JOIN transactions ON transactions.account_id = accounts.id AND transactions.date < NOW()
WHERE accounts.budget_id = $1 WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE GROUP BY accounts.id, accounts.name
ORDER BY accounts.name ORDER BY accounts.name
` `
@@ -108,11 +97,7 @@ type GetAccountsWithBalanceRow struct {
ID uuid.UUID ID uuid.UUID
Name string Name string
OnBudget bool OnBudget bool
IsOpen bool Balance Numeric
LastReconciled sql.NullTime
WorkingBalance numeric.Numeric
ClearedBalance numeric.Numeric
ReconciledBalance numeric.Numeric
} }
func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsWithBalanceRow, error) { func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsWithBalanceRow, error) {
@@ -128,11 +113,7 @@ func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID
&i.ID, &i.ID,
&i.Name, &i.Name,
&i.OnBudget, &i.OnBudget,
&i.IsOpen, &i.Balance,
&i.LastReconciled,
&i.WorkingBalance,
&i.ClearedBalance,
&i.ReconciledBalance,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -146,97 +127,3 @@ func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID
} }
return items, nil return items, nil
} }
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.is_open = TRUE
AND accounts.name ILIKE $2
ORDER BY accounts.name
`
type SearchAccountsParams struct {
BudgetID uuid.UUID
Search string
}
type SearchAccountsRow struct {
ID uuid.UUID
BudgetID uuid.UUID
Name string
Type interface{}
}
func (q *Queries) SearchAccounts(ctx context.Context, arg SearchAccountsParams) ([]SearchAccountsRow, error) {
rows, err := q.db.QueryContext(ctx, searchAccounts, arg.BudgetID, arg.Search)
if err != nil {
return nil, err
}
defer rows.Close()
var items []SearchAccountsRow
for rows.Next() {
var i SearchAccountsRow
if err := rows.Scan(
&i.ID,
&i.BudgetID,
&i.Name,
&i.Type,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const 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,
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.IsOpen,
arg.ID,
)
var i Account
err := row.Scan(
&i.ID,
&i.BudgetID,
&i.Name,
&i.OnBudget,
&i.IsOpen,
&i.LastReconciled,
)
return i, err
}

View File

@@ -7,7 +7,6 @@ import (
"context" "context"
"time" "time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -17,12 +16,12 @@ INSERT INTO assignments (
) VALUES ( ) VALUES (
$1, $2, $3 $1, $2, $3
) )
RETURNING category_id, date, memo, amount RETURNING id, category_id, date, memo, amount
` `
type CreateAssignmentParams struct { type CreateAssignmentParams struct {
Date time.Time Date time.Time
Amount numeric.Numeric Amount Numeric
CategoryID uuid.UUID CategoryID uuid.UUID
} }
@@ -30,6 +29,7 @@ func (q *Queries) CreateAssignment(ctx context.Context, arg CreateAssignmentPara
row := q.db.QueryRowContext(ctx, createAssignment, arg.Date, arg.Amount, arg.CategoryID) row := q.db.QueryRowContext(ctx, createAssignment, arg.Date, arg.Amount, arg.CategoryID)
var i Assignment var i Assignment
err := row.Scan( err := row.Scan(
&i.ID,
&i.CategoryID, &i.CategoryID,
&i.Date, &i.Date,
&i.Memo, &i.Memo,
@@ -53,49 +53,6 @@ func (q *Queries) DeleteAllAssignments(ctx context.Context, budgetID uuid.UUID)
return result.RowsAffected() return result.RowsAffected()
} }
const getAllAssignments = `-- name: GetAllAssignments :many
SELECT assignments.date, categories.name as category, category_groups.name as group, assignments.amount
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 = $1
`
type GetAllAssignmentsRow struct {
Date time.Time
Category string
Group string
Amount numeric.Numeric
}
func (q *Queries) GetAllAssignments(ctx context.Context, budgetID uuid.UUID) ([]GetAllAssignmentsRow, error) {
rows, err := q.db.QueryContext(ctx, getAllAssignments, budgetID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAllAssignmentsRow
for rows.Next() {
var i GetAllAssignmentsRow
if err := rows.Scan(
&i.Date,
&i.Category,
&i.Group,
&i.Amount,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getAssignmentsByMonthAndCategory = `-- name: GetAssignmentsByMonthAndCategory :many const getAssignmentsByMonthAndCategory = `-- name: GetAssignmentsByMonthAndCategory :many
SELECT date, category_id, budget_id, amount SELECT date, category_id, budget_id, amount
FROM assignments_by_month FROM assignments_by_month
@@ -129,41 +86,3 @@ func (q *Queries) GetAssignmentsByMonthAndCategory(ctx context.Context, budgetID
} }
return items, nil return items, nil
} }
const updateAssignment = `-- name: UpdateAssignment :exec
INSERT INTO assignments (category_id, date, amount)
VALUES($1, $2, $3)
ON CONFLICT (category_id, date)
DO
UPDATE SET amount = $3
`
type UpdateAssignmentParams struct {
CategoryID uuid.UUID
Date time.Time
Amount numeric.Numeric
}
func (q *Queries) UpdateAssignment(ctx context.Context, arg UpdateAssignmentParams) error {
_, err := q.db.ExecContext(ctx, updateAssignment, arg.CategoryID, arg.Date, arg.Amount)
return err
}
const updateAssignmentWithDifference = `-- name: UpdateAssignmentWithDifference :exec
INSERT INTO assignments (category_id, date, amount)
VALUES($1, $2, $3)
ON CONFLICT (category_id, date)
DO
UPDATE SET amount = assignments.amount + $3
`
type UpdateAssignmentWithDifferenceParams struct {
CategoryID uuid.UUID
Date time.Time
Amount numeric.Numeric
}
func (q *Queries) UpdateAssignmentWithDifference(ctx context.Context, arg UpdateAssignmentWithDifferenceParams) error {
_, err := q.db.ExecContext(ctx, updateAssignmentWithDifference, arg.CategoryID, arg.Date, arg.Amount)
return err
}

View File

@@ -8,15 +8,11 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
) )
// NewBudget creates a budget and adds it to the current user. // NewBudget creates a budget and adds it to the current user
func (s *Database) NewBudget(context context.Context, name string, userID uuid.UUID) (*Budget, error) { func (s *Database) NewBudget(context context.Context, name string, userID uuid.UUID) (*Budget, error) {
tx, err := s.BeginTx(context, &sql.TxOptions{}) tx, err := s.BeginTx(context, &sql.TxOptions{})
if err != nil { q := s.WithTx(tx)
return nil, fmt.Errorf("begin transaction: %w", err) budget, err := q.CreateBudget(context, CreateBudgetParams{
}
transaction := s.WithTx(tx)
budget, err := transaction.CreateBudget(context, CreateBudgetParams{
Name: name, Name: name,
IncomeCategoryID: uuid.New(), IncomeCategoryID: uuid.New(),
}) })
@@ -25,12 +21,12 @@ func (s *Database) NewBudget(context context.Context, name string, userID uuid.U
} }
ub := LinkBudgetToUserParams{UserID: userID, BudgetID: budget.ID} ub := LinkBudgetToUserParams{UserID: userID, BudgetID: budget.ID}
_, err = transaction.LinkBudgetToUser(context, ub) _, err = q.LinkBudgetToUser(context, ub)
if err != nil { if err != nil {
return nil, fmt.Errorf("link budget to user: %w", err) return nil, fmt.Errorf("link budget to user: %w", err)
} }
group, err := transaction.CreateCategoryGroup(context, CreateCategoryGroupParams{ group, err := q.CreateCategoryGroup(context, CreateCategoryGroupParams{
Name: "Inflow", Name: "Inflow",
BudgetID: budget.ID, BudgetID: budget.ID,
}) })
@@ -38,7 +34,7 @@ func (s *Database) NewBudget(context context.Context, name string, userID uuid.U
return nil, fmt.Errorf("create inflow category_group: %w", err) return nil, fmt.Errorf("create inflow category_group: %w", err)
} }
cat, err := transaction.CreateCategory(context, CreateCategoryParams{ cat, err := q.CreateCategory(context, CreateCategoryParams{
Name: "Ready to Assign", Name: "Ready to Assign",
CategoryGroupID: group.ID, CategoryGroupID: group.ID,
}) })
@@ -46,7 +42,7 @@ func (s *Database) NewBudget(context context.Context, name string, userID uuid.U
return nil, fmt.Errorf("create ready to assign category: %w", err) return nil, fmt.Errorf("create ready to assign category: %w", err)
} }
err = transaction.SetInflowCategory(context, SetInflowCategoryParams{ err = q.SetInflowCategory(context, SetInflowCategoryParams{
IncomeCategoryID: cat.ID, IncomeCategoryID: cat.ID,
ID: budget.ID, ID: budget.ID,
}) })
@@ -54,10 +50,7 @@ func (s *Database) NewBudget(context context.Context, name string, userID uuid.U
return nil, fmt.Errorf("set inflow category: %w", err) return nil, fmt.Errorf("set inflow category: %w", err)
} }
err = tx.Commit() tx.Commit()
if err != nil {
return nil, fmt.Errorf("commit: %w", err)
}
return &budget, nil return &budget, nil
} }

View File

@@ -118,12 +118,10 @@ func (q *Queries) GetCategoryGroups(ctx context.Context, budgetID uuid.UUID) ([]
} }
const searchCategories = `-- name: SearchCategories :many const searchCategories = `-- name: SearchCategories :many
SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.id, 'category' as type SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.id FROM categories
FROM categories
INNER JOIN category_groups ON categories.category_group_id = category_groups.id INNER JOIN category_groups ON categories.category_group_id = category_groups.id
WHERE category_groups.budget_id = $1 WHERE category_groups.budget_id = $1
AND categories.name ILIKE $2 AND categories.name LIKE $2
AND category_groups.name != 'Hidden Categories'
ORDER BY category_groups.name, categories.name ORDER BY category_groups.name, categories.name
` `
@@ -135,7 +133,6 @@ type SearchCategoriesParams struct {
type SearchCategoriesRow struct { type SearchCategoriesRow struct {
Name interface{} Name interface{}
ID uuid.UUID ID uuid.UUID
Type interface{}
} }
func (q *Queries) SearchCategories(ctx context.Context, arg SearchCategoriesParams) ([]SearchCategoriesRow, error) { func (q *Queries) SearchCategories(ctx context.Context, arg SearchCategoriesParams) ([]SearchCategoriesRow, error) {
@@ -147,7 +144,7 @@ func (q *Queries) SearchCategories(ctx context.Context, arg SearchCategoriesPara
var items []SearchCategoriesRow var items []SearchCategoriesRow
for rows.Next() { for rows.Next() {
var i SearchCategoriesRow var i SearchCategoriesRow
if err := rows.Scan(&i.Name, &i.ID, &i.Type); err != nil { if err := rows.Scan(&i.Name, &i.ID); err != nil {
return nil, err return nil, err
} }
items = append(items, i) items = append(items, i)

View File

@@ -5,7 +5,7 @@ import (
"embed" "embed"
"fmt" "fmt"
_ "github.com/jackc/pgx/v4/stdlib" // needed for pg connection _ "github.com/jackc/pgx/v4/stdlib"
"github.com/pressly/goose/v3" "github.com/pressly/goose/v3"
) )
@@ -17,7 +17,7 @@ type Database struct {
*sql.DB *sql.DB
} }
// Connect connects to a database. // Connect to a database
func Connect(typ string, connString string) (*Database, error) { func Connect(typ string, connString string) (*Database, error) {
conn, err := sql.Open(typ, connString) conn, err := sql.Open(typ, connString)
if err != nil { if err != nil {

View File

@@ -7,7 +7,6 @@ import (
"context" "context"
"time" "time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -24,10 +23,10 @@ ORDER BY COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id
type GetCumultativeBalancesRow struct { type GetCumultativeBalancesRow struct {
Date time.Time Date time.Time
CategoryID uuid.UUID CategoryID uuid.UUID
Assignments numeric.Numeric Assignments Numeric
AssignmentsCum numeric.Numeric AssignmentsCum Numeric
Transactions numeric.Numeric Transactions Numeric
TransactionsCum numeric.Numeric TransactionsCum Numeric
} }
func (q *Queries) GetCumultativeBalances(ctx context.Context, budgetID uuid.UUID) ([]GetCumultativeBalancesRow, error) { func (q *Queries) GetCumultativeBalances(ctx context.Context, budgetID uuid.UUID) ([]GetCumultativeBalancesRow, error) {

View File

@@ -7,7 +7,6 @@ import (
"fmt" "fmt"
"time" "time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -36,15 +35,14 @@ type Account struct {
BudgetID uuid.UUID BudgetID uuid.UUID
Name string Name string
OnBudget bool OnBudget bool
IsOpen bool
LastReconciled sql.NullTime
} }
type Assignment struct { type Assignment struct {
ID uuid.UUID
CategoryID uuid.UUID CategoryID uuid.UUID
Date time.Time Date time.Time
Memo sql.NullString Memo sql.NullString
Amount numeric.Numeric Amount Numeric
} }
type AssignmentsByMonth struct { type AssignmentsByMonth struct {
@@ -73,24 +71,6 @@ type CategoryGroup struct {
Name string Name string
} }
type DisplayTransaction struct {
ID uuid.UUID
Date time.Time
Memo string
Amount numeric.Numeric
GroupID uuid.NullUUID
Status TransactionStatus
Account string
PayeeID uuid.NullUUID
CategoryID uuid.NullUUID
Payee string
CategoryGroup string
Category string
TransferAccount string
BudgetID uuid.UUID
AccountID uuid.UUID
}
type Payee struct { type Payee struct {
ID uuid.UUID ID uuid.UUID
BudgetID uuid.UUID BudgetID uuid.UUID
@@ -101,7 +81,7 @@ type Transaction struct {
ID uuid.UUID ID uuid.UUID
Date time.Time Date time.Time
Memo string Memo string
Amount numeric.Numeric Amount Numeric
AccountID uuid.UUID AccountID uuid.UUID
CategoryID uuid.NullUUID CategoryID uuid.NullUUID
PayeeID uuid.NullUUID PayeeID uuid.NullUUID

129
postgres/numeric.go Normal file
View File

@@ -0,0 +1,129 @@
package postgres
import (
"fmt"
"math/big"
"github.com/jackc/pgtype"
)
type Numeric struct {
pgtype.Numeric
}
func NewZeroNumeric() Numeric {
return Numeric{pgtype.Numeric{Exp: 0, Int: big.NewInt(0), Status: pgtype.Present, NaN: false}}
}
func (n Numeric) GetFloat64() float64 {
if n.Status != pgtype.Present {
return 0
}
var balance float64
err := n.AssignTo(&balance)
if err != nil {
panic(err)
}
return balance
}
func (n Numeric) IsPositive() bool {
if n.Status != pgtype.Present {
return true
}
float := n.GetFloat64()
return float >= 0
}
func (n Numeric) IsZero() bool {
if n.Status != pgtype.Present {
return true
}
float := n.GetFloat64()
return float == 0
}
func (n Numeric) MatchExp(exp int32) Numeric {
diffExp := n.Exp - exp
factor := big.NewInt(0).Exp(big.NewInt(10), big.NewInt(int64(diffExp)), nil)
return Numeric{pgtype.Numeric{
Exp: exp,
Int: big.NewInt(0).Mul(n.Int, factor),
Status: n.Status,
NaN: n.NaN,
}}
}
func (n Numeric) Sub(o Numeric) Numeric {
left := n
right := o
if n.Exp < o.Exp {
right = o.MatchExp(n.Exp)
} else if n.Exp > o.Exp {
left = n.MatchExp(o.Exp)
}
if left.Exp == right.Exp {
return Numeric{pgtype.Numeric{
Exp: left.Exp,
Int: big.NewInt(0).Sub(left.Int, right.Int),
}}
}
panic("Cannot subtract with different exponents")
}
func (n Numeric) Add(o Numeric) Numeric {
left := n
right := o
if n.Exp < o.Exp {
right = o.MatchExp(n.Exp)
} else if n.Exp > o.Exp {
left = n.MatchExp(o.Exp)
}
if left.Exp == right.Exp {
return Numeric{pgtype.Numeric{
Exp: left.Exp,
Int: big.NewInt(0).Add(left.Int, right.Int),
}}
}
panic("Cannot add with different exponents")
}
func (n Numeric) MarshalJSON() ([]byte, error) {
if n.Int.Int64() == 0 {
return []byte("\"0\""), nil
}
s := fmt.Sprintf("%d", n.Int)
bytes := []byte(s)
exp := n.Exp
for exp > 0 {
bytes = append(bytes, byte('0'))
exp--
}
if exp == 0 {
return bytes, nil
}
length := int32(len(bytes))
var bytesWithSeparator []byte
exp = -exp
for length <= exp {
bytes = append(bytes, byte('0'))
length++
}
split := length - exp
bytesWithSeparator = append(bytesWithSeparator, bytes[:split]...)
if split == 1 && n.Int.Int64() < 0 {
bytesWithSeparator = append(bytesWithSeparator, byte('0'))
}
bytesWithSeparator = append(bytesWithSeparator, byte('.'))
bytesWithSeparator = append(bytesWithSeparator, bytes[split:]...)
return bytesWithSeparator, nil
}

View File

@@ -1,265 +0,0 @@
package numeric
import (
"fmt"
"math/big"
"strings"
"unicode/utf8"
"github.com/jackc/pgtype"
)
type Numeric struct {
pgtype.Numeric
}
func Zero() Numeric {
return Numeric{pgtype.Numeric{Exp: 0, Int: big.NewInt(0), Status: pgtype.Present, NaN: false}}
}
func FromInt64(value int64) Numeric {
return Numeric{Numeric: pgtype.Numeric{Int: big.NewInt(value), Status: pgtype.Present}}
}
func FromInt64WithExp(value int64, exp int32) Numeric {
return Numeric{Numeric: pgtype.Numeric{Int: big.NewInt(value), Exp: exp, Status: pgtype.Present}}
}
func (n Numeric) GetFloat64() float64 {
if n.Status != pgtype.Present {
return 0
}
var balance float64
err := n.AssignTo(&balance)
if err != nil {
panic(err)
}
return balance
}
func (n Numeric) IsPositive() bool {
if n.Status != pgtype.Present {
return true
}
float := n.GetFloat64()
return float >= 0
}
func (n Numeric) IsZero() bool {
if n.Status != pgtype.Present {
return true
}
float := n.GetFloat64()
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
return Numeric{pgtype.Numeric{
Exp: exp,
Int: big.NewInt(0).Mul(n.Int, factor),
Status: n.Status,
NaN: n.NaN,
}}
}
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
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
left = n.MatchExp(other.Exp)
}
if left.Exp == right.Exp {
return Numeric{pgtype.Numeric{
Exp: left.Exp,
Int: big.NewInt(0).Sub(left.Int, right.Int),
}}
}
panic("Cannot subtract with different exponents")
}
func (n Numeric) Neg() Numeric {
return Numeric{pgtype.Numeric{Exp: n.Exp, Int: big.NewInt(-1 * n.Int.Int64()), Status: n.Status}}
}
func (n Numeric) Add(other Numeric) Numeric {
left := n
right := other
if n.Exp < other.Exp {
right = other.MatchExp(n.Exp)
} else if n.Exp > other.Exp {
left = n.MatchExp(other.Exp)
}
if left.Exp == right.Exp {
return Numeric{pgtype.Numeric{
Exp: left.Exp,
Int: big.NewInt(0).Add(left.Int, right.Int),
}}
}
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"
}
s := fmt.Sprintf("%d", n.Int)
bytes := []byte(s)
exp := n.Exp
for exp > 0 {
bytes = append(bytes, byte('0'))
exp--
}
if exp == 0 {
return string(bytes)
}
length := int32(len(bytes))
var bytesWithSeparator []byte
exp = -exp
for length <= exp {
if n.Int.Int64() < 0 {
bytes = append([]byte{bytes[0], byte('0')}, bytes[1:]...)
} else {
bytes = append([]byte{byte('0')}, bytes...)
}
length++
}
split := length - exp
bytesWithSeparator = append(bytesWithSeparator, bytes[:split]...)
if split == 1 && n.Int.Int64() < 0 {
bytesWithSeparator = append(bytesWithSeparator, byte('0'))
}
bytesWithSeparator = append(bytesWithSeparator, byte('.'))
bytesWithSeparator = append(bytesWithSeparator, bytes[split:]...)
return string(bytesWithSeparator)
}
func (n Numeric) MarshalJSON() ([]byte, error) {
if n.Int == nil || n.Int.Int64() == 0 {
return []byte("0"), nil
}
s := fmt.Sprintf("%d", n.Int)
bytes := []byte(s)
exp := n.Exp
for exp > 0 {
bytes = append(bytes, byte('0'))
exp--
}
if exp == 0 {
return bytes, nil
}
length := int32(len(bytes))
var bytesWithSeparator []byte
exp = -exp
for length <= exp {
if n.Int.Int64() < 0 {
bytes = append([]byte{bytes[0], byte('0')}, bytes[1:]...)
} else {
bytes = append([]byte{byte('0')}, bytes...)
}
length++
}
split := length - exp
bytesWithSeparator = append(bytesWithSeparator, bytes[:split]...)
if split == 1 && n.Int.Int64() < 0 {
bytesWithSeparator = append(bytesWithSeparator, byte('0'))
}
bytesWithSeparator = append(bytesWithSeparator, byte('.'))
bytesWithSeparator = append(bytesWithSeparator, bytes[split:]...)
return bytesWithSeparator, nil
}
func MustParse(text string) Numeric {
num, err := Parse(text)
if err != nil {
panic(err)
}
return num
}
func Parse(text string) (Numeric, error) {
// Unify decimal separator
text = strings.Replace(text, ",", ".", 1)
num := Numeric{}
err := num.Set(text)
if err != nil {
return num, fmt.Errorf("parse numeric %s: %w", text, err)
}
return num, nil
}
func ParseCurrency(text string) (Numeric, error) {
// Remove trailing currency
text = trimLastChar(text)
return Parse(text)
}
func trimLastChar(s string) string {
r, size := utf8.DecodeLastRuneInString(s)
if r == utf8.RuneError && (size == 0 || size == 1) {
size = 0
}
return s[:len(s)-size]
}

View File

@@ -1,118 +0,0 @@
package numeric_test
import (
"testing"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
)
type TestCaseMarshalJSON struct {
Value numeric.Numeric
Result string
}
func TestMarshalJSON(t *testing.T) {
t.Parallel()
tests := []TestCaseMarshalJSON{
{numeric.Zero(), `0`},
{numeric.MustParse("1.23"), "1.23"},
{numeric.MustParse("1,24"), "1.24"},
{numeric.MustParse("1"), "1"},
{numeric.MustParse("10"), "10"},
{numeric.MustParse("100"), "100"},
{numeric.MustParse("1000"), "1000"},
{numeric.MustParse("0.1"), "0.1"},
{numeric.MustParse("0.01"), "0.01"},
{numeric.MustParse("0.001"), "0.001"},
{numeric.MustParse("0.0001"), "0.0001"},
{numeric.MustParse("-1"), "-1"},
{numeric.MustParse("-10"), "-10"},
{numeric.MustParse("-100"), "-100"},
{numeric.MustParse("-1000"), "-1000"},
{numeric.MustParse("-0.1"), "-0.1"},
{numeric.MustParse("-0.01"), "-0.01"},
{numeric.MustParse("-0.001"), "-0.001"},
{numeric.MustParse("-0.0001"), "-0.0001"},
{numeric.MustParse("123456789.12345"), "123456789.12345"},
{numeric.MustParse("123456789.12345"), "123456789.12345"},
{numeric.MustParse("-1.23"), "-1.23"},
{numeric.MustParse("-1,24"), "-1.24"},
{numeric.MustParse("-123456789.12345"), "-123456789.12345"},
}
for i := range tests {
test := tests[i]
t.Run(test.Result, func(t *testing.T) {
t.Parallel()
z := test.Value
result, err := z.MarshalJSON()
if err != nil {
t.Error(err)
return
}
if string(result) != test.Result {
t.Errorf("Expected %s, got %s", test.Result, string(result))
return
}
})
}
}
type TestCaseParse struct {
Result numeric.Numeric
Value string
}
func TestParse(t *testing.T) {
t.Parallel()
tests := []TestCaseParse{
{numeric.FromInt64WithExp(0, 0), `0`},
{numeric.FromInt64WithExp(1, 0), `1`},
{numeric.FromInt64WithExp(1, 1), `10`},
{numeric.FromInt64WithExp(1, 2), `100`},
{numeric.FromInt64WithExp(1, 3), `1000`},
{numeric.FromInt64WithExp(1, -1), `0.1`},
{numeric.FromInt64WithExp(1, -2), `0.01`},
{numeric.FromInt64WithExp(1, -3), `0.001`},
{numeric.FromInt64WithExp(1, -4), `0.0001`},
{numeric.FromInt64WithExp(-1, 0), `-1`},
{numeric.FromInt64WithExp(-1, 1), `-10`},
{numeric.FromInt64WithExp(-1, 2), `-100`},
{numeric.FromInt64WithExp(-1, 3), `-1000`},
{numeric.FromInt64WithExp(-1, -1), `-0.1`},
{numeric.FromInt64WithExp(-1, -2), `-0.01`},
{numeric.FromInt64WithExp(-1, -3), `-0.001`},
{numeric.FromInt64WithExp(-1, -4), `-0.0001`},
{numeric.FromInt64WithExp(123, -2), "1.23"},
{numeric.FromInt64WithExp(124, -2), "1,24"},
{numeric.FromInt64WithExp(12345678912345, -5), "123456789.12345"},
{numeric.FromInt64WithExp(0, 0), `-0`},
{numeric.FromInt64WithExp(-1, 0), `-1`},
{numeric.FromInt64WithExp(-1, 1), `-10`},
{numeric.FromInt64WithExp(-1, 2), `-100`},
{numeric.FromInt64WithExp(-123, -2), "-1.23"},
{numeric.FromInt64WithExp(-124, -2), "-1,24"},
{numeric.FromInt64WithExp(-12345678912345, -5), "-123456789.12345"},
}
for i := range tests {
test := tests[i]
t.Run(test.Value, func(t *testing.T) {
t.Parallel()
result, err := numeric.Parse(test.Value)
if err != nil {
t.Error(err)
return
}
if test.Result.Int.Int64() != result.Int.Int64() {
t.Errorf("Expected int %d, got %d", test.Result.Int, result.Int)
return
}
if test.Result.Exp != result.Exp {
t.Errorf("Expected exp %d, got %d", test.Result.Exp, result.Exp)
return
}
})
}
}

View File

@@ -58,9 +58,9 @@ func (q *Queries) GetPayees(ctx context.Context, budgetID uuid.UUID) ([]Payee, e
} }
const searchPayees = `-- name: SearchPayees :many const searchPayees = `-- name: SearchPayees :many
SELECT payees.id, payees.budget_id, payees.name, 'payee' as type FROM payees SELECT payees.id, payees.budget_id, payees.name FROM payees
WHERE payees.budget_id = $1 WHERE payees.budget_id = $1
AND payees.name ILIKE $2 AND payees.name LIKE $2
ORDER BY payees.name ORDER BY payees.name
` `
@@ -69,28 +69,16 @@ type SearchPayeesParams struct {
Search string Search string
} }
type SearchPayeesRow struct { func (q *Queries) SearchPayees(ctx context.Context, arg SearchPayeesParams) ([]Payee, error) {
ID uuid.UUID
BudgetID uuid.UUID
Name string
Type interface{}
}
func (q *Queries) SearchPayees(ctx context.Context, arg SearchPayeesParams) ([]SearchPayeesRow, error) {
rows, err := q.db.QueryContext(ctx, searchPayees, arg.BudgetID, arg.Search) rows, err := q.db.QueryContext(ctx, searchPayees, arg.BudgetID, arg.Search)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
var items []SearchPayeesRow var items []Payee
for rows.Next() { for rows.Next() {
var i SearchPayeesRow var i Payee
if err := rows.Scan( if err := rows.Scan(&i.ID, &i.BudgetID, &i.Name); err != nil {
&i.ID,
&i.BudgetID,
&i.Name,
&i.Type,
); err != nil {
return nil, err return nil, err
} }
items = append(items, i) items = append(items, i)

View File

@@ -11,35 +11,12 @@ WHERE accounts.id = $1;
-- name: GetAccounts :many -- name: GetAccounts :many
SELECT accounts.* FROM accounts SELECT accounts.* FROM accounts
WHERE accounts.budget_id = $1 WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE
ORDER BY accounts.name; ORDER BY accounts.name;
-- name: GetAccountsWithBalance :many -- name: GetAccountsWithBalance :many
SELECT accounts.id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled, SELECT accounts.id, accounts.name, accounts.on_budget, SUM(transactions.amount)::decimal(12,2) as balance
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW())::decimal(12,2) as working_balance,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status IN ('Cleared', 'Reconciled'))::decimal(12,2) as cleared_balance,
(SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status = 'Reconciled')::decimal(12,2) as reconciled_balance
FROM accounts FROM accounts
LEFT JOIN transactions ON transactions.account_id = accounts.id AND transactions.date < NOW()
WHERE accounts.budget_id = $1 WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE GROUP BY accounts.id, accounts.name
ORDER BY accounts.name; 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.is_open = TRUE
AND accounts.name ILIKE @search
ORDER BY accounts.name;
-- name: UpdateAccount :one
UPDATE accounts
SET name = $1,
on_budget = $2,
is_open = $3
WHERE accounts.id = $4
RETURNING *;
-- name: SetLastReconciled :exec
UPDATE accounts
SET last_reconciled = NOW()
WHERE accounts.id = $1;

View File

@@ -16,24 +16,3 @@ WHERE categories.id = assignments.category_id AND category_groups.budget_id = @b
SELECT * SELECT *
FROM assignments_by_month FROM assignments_by_month
WHERE assignments_by_month.budget_id = @budget_id; WHERE assignments_by_month.budget_id = @budget_id;
-- name: GetAllAssignments :many
SELECT assignments.date, categories.name as category, category_groups.name as group, assignments.amount
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;

View File

@@ -21,11 +21,9 @@ WHERE category_groups.budget_id = $1
ORDER BY category_groups.name, categories.name; ORDER BY category_groups.name, categories.name;
-- name: SearchCategories :many -- name: SearchCategories :many
SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.id, 'category' as type SELECT CONCAT(category_groups.name, ' : ', categories.name) as name, categories.id FROM categories
FROM categories
INNER JOIN category_groups ON categories.category_group_id = category_groups.id INNER JOIN category_groups ON categories.category_group_id = category_groups.id
WHERE category_groups.budget_id = @budget_id WHERE category_groups.budget_id = @budget_id
AND categories.name ILIKE @search AND categories.name LIKE @search
AND category_groups.name != 'Hidden Categories'
ORDER BY category_groups.name, categories.name; ORDER BY category_groups.name, categories.name;
--ORDER BY levenshtein(payees.name, $2); --ORDER BY levenshtein(payees.name, $2);

View File

@@ -10,8 +10,8 @@ WHERE payees.budget_id = $1
ORDER BY name; ORDER BY name;
-- name: SearchPayees :many -- name: SearchPayees :many
SELECT payees.*, 'payee' as type FROM payees SELECT payees.* FROM payees
WHERE payees.budget_id = @budget_id WHERE payees.budget_id = @budget_id
AND payees.name ILIKE @search AND payees.name LIKE @search
ORDER BY payees.name; ORDER BY payees.name;
--ORDER BY levenshtein(payees.name, $2); --ORDER BY levenshtein(payees.name, $2);

View File

@@ -1,40 +1,60 @@
-- name: GetTransaction :one -- name: GetTransaction :one
SELECT * FROM display_transactions SELECT * FROM transactions
WHERE id = $1; WHERE id = $1;
-- name: CreateTransaction :one -- name: CreateTransaction :one
INSERT INTO transactions INSERT INTO transactions
(date, memo, amount, account_id, payee_id, category_id, group_id, status) (date, memo, amount, account_id, payee_id, category_id, group_id, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id; RETURNING *;
-- name: UpdateTransaction :exec -- name: UpdateTransaction :exec
UPDATE transactions UPDATE transactions
SET date = $1, SET date = $1,
memo = $2, memo = $2,
amount = $3, amount = $3,
payee_id = $4, account_id = $4,
category_id = $5 payee_id = $5,
WHERE id = $6; category_id = $6
WHERE id = $7;
-- name: SetTransactionReconciled :exec
UPDATE transactions
SET status = 'Reconciled'
WHERE id = $1;
-- name: DeleteTransaction :exec -- name: DeleteTransaction :exec
DELETE FROM transactions DELETE FROM transactions
WHERE id = $1; WHERE id = $1;
-- name: GetAllTransactionsForBudget :many -- name: GetTransactionsForBudget :many
SELECT t.* SELECT transactions.id, transactions.date, transactions.memo, transactions.amount, transactions.group_id, transactions.status,
FROM display_transactions AS t accounts.name as account, COALESCE(payees.name, '') as payee, COALESCE(category_groups.name, '') as category_group, COALESCE(categories.name, '') as category
WHERE t.budget_id = $1; FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
WHERE accounts.budget_id = $1
ORDER BY transactions.date DESC
LIMIT 200;
-- name: GetTransactionsForAccount :many -- name: GetTransactionsForAccount :many
SELECT t.* SELECT transactions.id, transactions.date, transactions.memo,
FROM display_transactions AS t transactions.amount, transactions.group_id, transactions.status,
WHERE t.account_id = $1 accounts.name as account,
COALESCE(payees.name, '') as payee,
COALESCE(category_groups.name, '') as category_group,
COALESCE(categories.name, '') as category,
(
SELECT CONCAT(otherAccounts.name)
FROM transactions otherTransactions
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
WHERE otherTransactions.group_id = transactions.group_id
AND otherTransactions.id != transactions.id
) as transfer_account
FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
WHERE transactions.account_id = $1
ORDER BY transactions.date DESC
LIMIT 200; LIMIT 200;
-- name: DeleteAllTransactions :execrows -- name: DeleteAllTransactions :execrows

View File

@@ -1,25 +0,0 @@
-- +goose Up
CREATE VIEW display_transactions AS
SELECT transactions.id, transactions.date, transactions.memo,
transactions.amount, transactions.group_id, transactions.status,
accounts.name as account, transactions.payee_id, transactions.category_id,
COALESCE(payees.name, '') as payee,
COALESCE(category_groups.name, '') as category_group,
COALESCE(categories.name, '') as category,
COALESCE((
SELECT CONCAT(otherAccounts.name)
FROM transactions otherTransactions
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
WHERE otherTransactions.group_id = transactions.group_id
AND otherTransactions.id != transactions.id
), '')::text as transfer_account,
accounts.budget_id, transactions.account_id
FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
ORDER BY transactions.date DESC;
-- +goose Down
DROP VIEW display_transactions;

View File

@@ -1,5 +0,0 @@
-- +goose Up
ALTER TABLE accounts ADD COLUMN is_open BOOLEAN NOT NULL DEFAULT TRUE;
-- +goose Down
ALTER TABLE accounts DROP COLUMN is_open;

View File

@@ -1,6 +0,0 @@
-- +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;

View File

@@ -1,12 +0,0 @@
-- +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;

View File

@@ -7,7 +7,6 @@ import (
"context" "context"
"time" "time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -15,13 +14,13 @@ const createTransaction = `-- name: CreateTransaction :one
INSERT INTO transactions INSERT INTO transactions
(date, memo, amount, account_id, payee_id, category_id, group_id, status) (date, memo, amount, account_id, payee_id, category_id, group_id, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id RETURNING id, date, memo, amount, account_id, category_id, payee_id, group_id, status
` `
type CreateTransactionParams struct { type CreateTransactionParams struct {
Date time.Time Date time.Time
Memo string Memo string
Amount numeric.Numeric Amount Numeric
AccountID uuid.UUID AccountID uuid.UUID
PayeeID uuid.NullUUID PayeeID uuid.NullUUID
CategoryID uuid.NullUUID CategoryID uuid.NullUUID
@@ -29,7 +28,7 @@ type CreateTransactionParams struct {
Status TransactionStatus Status TransactionStatus
} }
func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionParams) (uuid.UUID, error) { func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionParams) (Transaction, error) {
row := q.db.QueryRowContext(ctx, createTransaction, row := q.db.QueryRowContext(ctx, createTransaction,
arg.Date, arg.Date,
arg.Memo, arg.Memo,
@@ -40,9 +39,19 @@ func (q *Queries) CreateTransaction(ctx context.Context, arg CreateTransactionPa
arg.GroupID, arg.GroupID,
arg.Status, arg.Status,
) )
var id uuid.UUID var i Transaction
err := row.Scan(&id) err := row.Scan(
return id, err &i.ID,
&i.Date,
&i.Memo,
&i.Amount,
&i.AccountID,
&i.CategoryID,
&i.PayeeID,
&i.GroupID,
&i.Status,
)
return i, err
} }
const deleteAllTransactions = `-- name: DeleteAllTransactions :execrows const deleteAllTransactions = `-- name: DeleteAllTransactions :execrows
@@ -70,75 +79,24 @@ func (q *Queries) DeleteTransaction(ctx context.Context, id uuid.UUID) error {
return err return err
} }
const getAllTransactionsForBudget = `-- name: GetAllTransactionsForBudget :many
SELECT t.id, t.date, t.memo, t.amount, t.group_id, t.status, t.account, t.payee_id, t.category_id, t.payee, t.category_group, t.category, t.transfer_account, t.budget_id, t.account_id
FROM display_transactions AS t
WHERE t.budget_id = $1
`
func (q *Queries) GetAllTransactionsForBudget(ctx context.Context, budgetID uuid.UUID) ([]DisplayTransaction, error) {
rows, err := q.db.QueryContext(ctx, getAllTransactionsForBudget, budgetID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []DisplayTransaction
for rows.Next() {
var i DisplayTransaction
if err := rows.Scan(
&i.ID,
&i.Date,
&i.Memo,
&i.Amount,
&i.GroupID,
&i.Status,
&i.Account,
&i.PayeeID,
&i.CategoryID,
&i.Payee,
&i.CategoryGroup,
&i.Category,
&i.TransferAccount,
&i.BudgetID,
&i.AccountID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getTransaction = `-- name: GetTransaction :one const getTransaction = `-- name: GetTransaction :one
SELECT id, date, memo, amount, group_id, status, account, payee_id, category_id, payee, category_group, category, transfer_account, budget_id, account_id FROM display_transactions SELECT id, date, memo, amount, account_id, category_id, payee_id, group_id, status FROM transactions
WHERE id = $1 WHERE id = $1
` `
func (q *Queries) GetTransaction(ctx context.Context, id uuid.UUID) (DisplayTransaction, error) { func (q *Queries) GetTransaction(ctx context.Context, id uuid.UUID) (Transaction, error) {
row := q.db.QueryRowContext(ctx, getTransaction, id) row := q.db.QueryRowContext(ctx, getTransaction, id)
var i DisplayTransaction var i Transaction
err := row.Scan( err := row.Scan(
&i.ID, &i.ID,
&i.Date, &i.Date,
&i.Memo, &i.Memo,
&i.Amount, &i.Amount,
&i.AccountID,
&i.CategoryID,
&i.PayeeID,
&i.GroupID, &i.GroupID,
&i.Status, &i.Status,
&i.Account,
&i.PayeeID,
&i.CategoryID,
&i.Payee,
&i.CategoryGroup,
&i.Category,
&i.TransferAccount,
&i.BudgetID,
&i.AccountID,
) )
return i, err return i, err
} }
@@ -178,21 +136,52 @@ func (q *Queries) GetTransactionsByMonthAndCategory(ctx context.Context, budgetI
} }
const getTransactionsForAccount = `-- name: GetTransactionsForAccount :many const getTransactionsForAccount = `-- name: GetTransactionsForAccount :many
SELECT t.id, t.date, t.memo, t.amount, t.group_id, t.status, t.account, t.payee_id, t.category_id, t.payee, t.category_group, t.category, t.transfer_account, t.budget_id, t.account_id SELECT transactions.id, transactions.date, transactions.memo,
FROM display_transactions AS t transactions.amount, transactions.group_id, transactions.status,
WHERE t.account_id = $1 accounts.name as account,
COALESCE(payees.name, '') as payee,
COALESCE(category_groups.name, '') as category_group,
COALESCE(categories.name, '') as category,
(
SELECT CONCAT(otherAccounts.name)
FROM transactions otherTransactions
LEFT JOIN accounts otherAccounts ON otherAccounts.id = otherTransactions.account_id
WHERE otherTransactions.group_id = transactions.group_id
AND otherTransactions.id != transactions.id
) as transfer_account
FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
WHERE transactions.account_id = $1
ORDER BY transactions.date DESC
LIMIT 200 LIMIT 200
` `
func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.UUID) ([]DisplayTransaction, error) { type GetTransactionsForAccountRow struct {
ID uuid.UUID
Date time.Time
Memo string
Amount Numeric
GroupID uuid.NullUUID
Status TransactionStatus
Account string
Payee string
CategoryGroup string
Category string
TransferAccount interface{}
}
func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.UUID) ([]GetTransactionsForAccountRow, error) {
rows, err := q.db.QueryContext(ctx, getTransactionsForAccount, accountID) rows, err := q.db.QueryContext(ctx, getTransactionsForAccount, accountID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
var items []DisplayTransaction var items []GetTransactionsForAccountRow
for rows.Next() { for rows.Next() {
var i DisplayTransaction var i GetTransactionsForAccountRow
if err := rows.Scan( if err := rows.Scan(
&i.ID, &i.ID,
&i.Date, &i.Date,
@@ -201,14 +190,10 @@ func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.
&i.GroupID, &i.GroupID,
&i.Status, &i.Status,
&i.Account, &i.Account,
&i.PayeeID,
&i.CategoryID,
&i.Payee, &i.Payee,
&i.CategoryGroup, &i.CategoryGroup,
&i.Category, &i.Category,
&i.TransferAccount, &i.TransferAccount,
&i.BudgetID,
&i.AccountID,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -223,15 +208,64 @@ func (q *Queries) GetTransactionsForAccount(ctx context.Context, accountID uuid.
return items, nil return items, nil
} }
const setTransactionReconciled = `-- name: SetTransactionReconciled :exec const getTransactionsForBudget = `-- name: GetTransactionsForBudget :many
UPDATE transactions SELECT transactions.id, transactions.date, transactions.memo, transactions.amount, transactions.group_id, transactions.status,
SET status = 'Reconciled' accounts.name as account, COALESCE(payees.name, '') as payee, COALESCE(category_groups.name, '') as category_group, COALESCE(categories.name, '') as category
WHERE id = $1 FROM transactions
INNER JOIN accounts ON accounts.id = transactions.account_id
LEFT JOIN payees ON payees.id = transactions.payee_id
LEFT JOIN categories ON categories.id = transactions.category_id
LEFT JOIN category_groups ON category_groups.id = categories.category_group_id
WHERE accounts.budget_id = $1
ORDER BY transactions.date DESC
LIMIT 200
` `
func (q *Queries) SetTransactionReconciled(ctx context.Context, id uuid.UUID) error { type GetTransactionsForBudgetRow struct {
_, err := q.db.ExecContext(ctx, setTransactionReconciled, id) ID uuid.UUID
return err Date time.Time
Memo string
Amount Numeric
GroupID uuid.NullUUID
Status TransactionStatus
Account string
Payee string
CategoryGroup string
Category string
}
func (q *Queries) GetTransactionsForBudget(ctx context.Context, budgetID uuid.UUID) ([]GetTransactionsForBudgetRow, error) {
rows, err := q.db.QueryContext(ctx, getTransactionsForBudget, budgetID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetTransactionsForBudgetRow
for rows.Next() {
var i GetTransactionsForBudgetRow
if err := rows.Scan(
&i.ID,
&i.Date,
&i.Memo,
&i.Amount,
&i.GroupID,
&i.Status,
&i.Account,
&i.Payee,
&i.CategoryGroup,
&i.Category,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
} }
const updateTransaction = `-- name: UpdateTransaction :exec const updateTransaction = `-- name: UpdateTransaction :exec
@@ -239,15 +273,17 @@ UPDATE transactions
SET date = $1, SET date = $1,
memo = $2, memo = $2,
amount = $3, amount = $3,
payee_id = $4, account_id = $4,
category_id = $5 payee_id = $5,
WHERE id = $6 category_id = $6
WHERE id = $7
` `
type UpdateTransactionParams struct { type UpdateTransactionParams struct {
Date time.Time Date time.Time
Memo string Memo string
Amount numeric.Numeric Amount Numeric
AccountID uuid.UUID
PayeeID uuid.NullUUID PayeeID uuid.NullUUID
CategoryID uuid.NullUUID CategoryID uuid.NullUUID
ID uuid.UUID ID uuid.UUID
@@ -258,6 +294,7 @@ func (q *Queries) UpdateTransaction(ctx context.Context, arg UpdateTransactionPa
arg.Date, arg.Date,
arg.Memo, arg.Memo,
arg.Amount, arg.Amount,
arg.AccountID,
arg.PayeeID, arg.PayeeID,
arg.CategoryID, arg.CategoryID,
arg.ID, arg.ID,

View File

@@ -1,144 +0,0 @@
package postgres
import (
"context"
"encoding/csv"
"fmt"
"io"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
type YNABExport struct {
queries *Queries
budgetID uuid.UUID
}
func NewYNABExport(context context.Context, queries *Queries, budgetID uuid.UUID) (*YNABExport, error) {
return &YNABExport{
queries: queries,
budgetID: budgetID,
}, nil
}
// ImportAssignments expects a TSV-file as exported by YNAB in the following format:
// "Month" "Category Group/Category" "Category Group" "Category" "Budgeted" "Activity" "Available"
// "Apr 2019" "Income: Next Month" "Income" "Next Month" 0,00€ 0,00€ 0,00€
//
// Activity and Available are not imported, since they are determined by the transactions and historic assignments.
func (ynab *YNABExport) ExportAssignments(context context.Context, w io.Writer) error {
csv := csv.NewWriter(w)
csv.Comma = '\t'
assignments, err := ynab.queries.GetAllAssignments(context, ynab.budgetID)
if err != nil {
return fmt.Errorf("load assignments: %w", err)
}
count := 0
for _, assignment := range assignments {
row := []string{
assignment.Date.Format("Jan 2006"),
assignment.Group + ": " + assignment.Category,
assignment.Group,
assignment.Category,
assignment.Amount.String() + "€",
numeric.Zero().String() + "€",
numeric.Zero().String() + "€",
}
err := csv.Write(row)
if err != nil {
return fmt.Errorf("write assignment: %w", err)
}
count++
}
csv.Flush()
fmt.Printf("Exported %d assignments\n", count)
return nil
}
// ImportTransactions expects a TSV-file as exported by YNAB in the following format:
// "Account" "Flag" "Date" "Payee" "Category Group/Category" "Category Group" "Category" "Memo" "Outflow" "Inflow" "Cleared"
// "Cash" "" "11.12.2021" "Transfer : Checking" "" "" "" "Brought to bank" 500,00€ 0,00€ "Cleared".
func (ynab *YNABExport) ExportTransactions(context context.Context, w io.Writer) error {
csv := csv.NewWriter(w)
csv.Comma = '\t'
transactions, err := ynab.queries.GetAllTransactionsForBudget(context, ynab.budgetID)
if err != nil {
return fmt.Errorf("load transactions: %w", err)
}
header := []string{
"Account",
"Flag",
"Date",
"Payee",
"Category Group/Category",
"Category Group",
"Category",
"Memo",
"Outflow",
"Inflow",
"Cleared",
}
err = csv.Write(header)
if err != nil {
return fmt.Errorf("write transaction: %w", err)
}
count := 0
for _, transaction := range transactions {
row := GetTransactionRow(transaction)
err := csv.Write(row)
if err != nil {
return fmt.Errorf("write transaction: %w", err)
}
count++
}
csv.Flush()
fmt.Printf("Exported %d transactions\n", count)
return nil
}
func GetTransactionRow(transaction DisplayTransaction) []string {
row := []string{
transaction.Account,
"", // Flag
transaction.Date.Format("02.01.2006"),
}
if transaction.TransferAccount != "" {
row = append(row, "Transfer : "+transaction.TransferAccount)
} else {
row = append(row, transaction.Payee)
}
if transaction.CategoryGroup != "" && transaction.Category != "" {
row = append(row,
transaction.CategoryGroup+": "+transaction.Category,
transaction.CategoryGroup,
transaction.Category)
} else {
row = append(row, "", "", "")
}
row = append(row, transaction.Memo)
if transaction.Amount.IsPositive() {
row = append(row, numeric.Zero().String()+"€", transaction.Amount.String()+"€")
} else {
row = append(row, transaction.Amount.String()[1:]+"€", numeric.Zero().String()+"€")
}
return append(row, string(transaction.Status))
}

View File

@@ -7,12 +7,13 @@ import (
"io" "io"
"strings" "strings"
"time" "time"
"unicode/utf8"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid" "github.com/google/uuid"
) )
type YNABImport struct { type YNABImport struct {
Context context.Context
accounts []Account accounts []Account
payees []Payee payees []Payee
categories []GetCategoriesRow categories []GetCategoriesRow
@@ -21,84 +22,87 @@ type YNABImport struct {
budgetID uuid.UUID budgetID uuid.UUID
} }
func NewYNABImport(context context.Context, queries *Queries, budgetID uuid.UUID) (*YNABImport, error) { func NewYNABImport(context context.Context, q *Queries, budgetID uuid.UUID) (*YNABImport, error) {
accounts, err := queries.GetAccounts(context, budgetID) accounts, err := q.GetAccounts(context, budgetID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
payees, err := queries.GetPayees(context, budgetID) payees, err := q.GetPayees(context, budgetID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
categories, err := queries.GetCategories(context, budgetID) categories, err := q.GetCategories(context, budgetID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
categoryGroups, err := queries.GetCategoryGroups(context, budgetID) categoryGroups, err := q.GetCategoryGroups(context, budgetID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &YNABImport{ return &YNABImport{
Context: context,
accounts: accounts, accounts: accounts,
payees: payees, payees: payees,
categories: categories, categories: categories,
categoryGroups: categoryGroups, categoryGroups: categoryGroups,
queries: queries, queries: q,
budgetID: budgetID, budgetID: budgetID,
}, nil }, nil
} }
// ImportAssignments expects a TSV-file as exported by YNAB in the following format: // ImportAssignments expects a TSV-file as exported by YNAB in the following format:
// "Month" "Category Group/Category" "Category Group" "Category" "Budgeted" "Activity" "Available" //"Month" "Category Group/Category" "Category Group" "Category" "Budgeted" "Activity" "Available"
// "Apr 2019" "Income: Next Month" "Income" "Next Month" 0,00€ 0,00€ 0,00€ //"Apr 2019" "Income: Next Month" "Income" "Next Month" 0,00€ 0,00€ 0,00€
// //
// Activity and Available are not imported, since they are determined by the transactions and historic assignments. // Activity and Available are not imported, since they are determined by the transactions and historic assignments
func (ynab *YNABImport) ImportAssignments(context context.Context, r io.Reader) error { func (ynab *YNABImport) ImportAssignments(r io.Reader) error {
csv := csv.NewReader(r) csv := csv.NewReader(r)
csv.Comma = '\t' csv.Comma = '\t'
csv.LazyQuotes = true csv.LazyQuotes = true
csvData, err := csv.ReadAll() csvData, err := csv.ReadAll()
if err != nil { if err != nil {
return fmt.Errorf("read from tsv: %w", err) return fmt.Errorf("could not read from tsv: %w", err)
} }
count := 0 count := 0
for _, record := range csvData[1:] { for _, record := range csvData[1:] {
dateString := record[0] dateString := record[0]
date, err := time.Parse("Jan 2006", dateString) date, err := time.Parse("Jan 2006", dateString)
if err != nil { if err != nil {
return fmt.Errorf("parse date %s: %w", dateString, err) return fmt.Errorf("could not parse date %s: %w", dateString, err)
} }
categoryGroup, categoryName := record[2], record[3] // also in 1 joined by : categoryGroup, categoryName := record[2], record[3] //also in 1 joined by :
category, err := ynab.GetCategory(context, categoryGroup, categoryName) category, err := ynab.GetCategory(categoryGroup, categoryName)
if err != nil { if err != nil {
return fmt.Errorf("get category %s/%s: %w", categoryGroup, categoryName, err) return fmt.Errorf("could not get category %s/%s: %w", categoryGroup, categoryName, err)
} }
amountString := record[4] amountString := record[4]
amount, err := GetAmount(amountString, "0,00€") amount, err := GetAmount(amountString, "0,00€")
if err != nil { if err != nil {
return fmt.Errorf("parse amount %s: %w", amountString, err) return fmt.Errorf("could not parse amount %s: %w", amountString, err)
} }
if amount.Int.Int64() == 0 { if amount.Int.Int64() == 0 {
continue continue
} }
assignment := UpdateAssignmentWithDifferenceParams{ assignment := CreateAssignmentParams{
Date: date, Date: date,
CategoryID: category.UUID, CategoryID: category.UUID,
Amount: amount, Amount: amount,
} }
err = ynab.queries.UpdateAssignmentWithDifference(context, assignment) _, err = ynab.queries.CreateAssignment(ynab.Context, assignment)
if err != nil { if err != nil {
return fmt.Errorf("save assignment %v: %w", assignment, err) return fmt.Errorf("could not save assignment %v: %w", assignment, err)
} }
count++ count++
@@ -117,80 +121,39 @@ type Transfer struct {
} }
// ImportTransactions expects a TSV-file as exported by YNAB in the following format: // ImportTransactions expects a TSV-file as exported by YNAB in the following format:
// "Account" "Flag" "Date" "Payee" "Category Group/Category" "Category Group" "Category" "Memo" "Outflow" "Inflow" "Cleared"
// "Cash" "" "11.12.2021" "Transfer : Checking" "" "" "" "Brought to bank" 500,00€ 0,00€ "Cleared". func (ynab *YNABImport) ImportTransactions(r io.Reader) error {
func (ynab *YNABImport) ImportTransactions(context context.Context, r io.Reader) error {
csv := csv.NewReader(r) csv := csv.NewReader(r)
csv.Comma = '\t' csv.Comma = '\t'
csv.LazyQuotes = true csv.LazyQuotes = true
csvData, err := csv.ReadAll() csvData, err := csv.ReadAll()
if err != nil { if err != nil {
return fmt.Errorf("read from tsv: %w", err) return fmt.Errorf("could not read from tsv: %w", err)
} }
var openTransfers []Transfer var openTransfers []Transfer
count := 0 count := 0
for _, record := range csvData[1:] { for _, record := range csvData[1:] {
transaction, err := ynab.GetTransaction(context, record)
if err != nil {
return err
}
payeeName := record[3]
// Transaction is a transfer
if strings.HasPrefix(payeeName, "Transfer : ") {
err = ynab.ImportTransferTransaction(context, payeeName, transaction.CreateTransactionParams,
&openTransfers, transaction.Account, transaction.Amount)
} else {
err = ynab.ImportRegularTransaction(context, payeeName, transaction.CreateTransactionParams)
}
if err != nil {
return err
}
count++
}
for _, openTransfer := range openTransfers {
fmt.Printf("Saving unmatched transfer from %s to %s on %s over %f as regular transaction\n",
openTransfer.FromAccount, openTransfer.ToAccount, openTransfer.Date, openTransfer.Amount.GetFloat64())
_, err = ynab.queries.CreateTransaction(context, openTransfer.CreateTransactionParams)
if err != nil {
return fmt.Errorf("save transaction %v: %w", openTransfer.CreateTransactionParams, err)
}
}
fmt.Printf("Imported %d transactions\n", count)
return nil
}
type NewTransaction struct {
CreateTransactionParams
Account *Account
}
func (ynab *YNABImport) GetTransaction(context context.Context, record []string) (NewTransaction, error) {
accountName := record[0] accountName := record[0]
account, err := ynab.GetAccount(context, accountName) account, err := ynab.GetAccount(accountName)
if err != nil { if err != nil {
return NewTransaction{}, fmt.Errorf("get account %s: %w", accountName, err) return fmt.Errorf("could not get account %s: %w", accountName, err)
} }
// flag := record[1] //flag := record[1]
dateString := record[2] dateString := record[2]
date, err := time.Parse("02.01.2006", dateString) date, err := time.Parse("02.01.2006", dateString)
if err != nil { if err != nil {
return NewTransaction{}, fmt.Errorf("parse date %s: %w", dateString, err) return fmt.Errorf("could not parse date %s: %w", dateString, err)
} }
categoryGroup, categoryName := record[5], record[6] // also in 4 joined by : categoryGroup, categoryName := record[5], record[6] //also in 4 joined by :
category, err := ynab.GetCategory(context, categoryGroup, categoryName) category, err := ynab.GetCategory(categoryGroup, categoryName)
if err != nil { if err != nil {
return NewTransaction{}, fmt.Errorf("get category %s/%s: %w", categoryGroup, categoryName, err) return fmt.Errorf("could not get category %s/%s: %w", categoryGroup, categoryName, err)
} }
memo := record[7] memo := record[7]
@@ -199,7 +162,7 @@ func (ynab *YNABImport) GetTransaction(context context.Context, record []string)
inflow := record[9] inflow := record[9]
amount, err := GetAmount(inflow, outflow) amount, err := GetAmount(inflow, outflow)
if err != nil { if err != nil {
return NewTransaction{}, fmt.Errorf("parse amount from (%s/%s): %w", inflow, outflow, err) return fmt.Errorf("could not parse amount from (%s/%s): %w", inflow, outflow, err)
} }
statusEnum := TransactionStatusUncleared statusEnum := TransactionStatusUncleared
@@ -212,54 +175,33 @@ func (ynab *YNABImport) GetTransaction(context context.Context, record []string)
case "Uncleared": case "Uncleared":
} }
return NewTransaction{ transaction := CreateTransactionParams{
CreateTransactionParams: CreateTransactionParams{
Date: date, Date: date,
Memo: memo, Memo: memo,
AccountID: account.ID, AccountID: account.ID,
CategoryID: category, CategoryID: category,
Amount: amount, Amount: amount,
Status: statusEnum, Status: statusEnum,
},
Account: account,
}, nil
}
func (ynab *YNABImport) ImportRegularTransaction(context context.Context, payeeName string,
transaction CreateTransactionParams,
) error {
payeeID, err := ynab.GetPayee(context, payeeName)
if err != nil {
return fmt.Errorf("get payee %s: %w", payeeName, err)
} }
transaction.PayeeID = payeeID
_, err = ynab.queries.CreateTransaction(context, transaction) payeeName := record[3]
if err != nil { if strings.HasPrefix(payeeName, "Transfer : ") {
return fmt.Errorf("save transaction %v: %w", transaction, err) // Transaction is a transfer to
}
return nil
}
func (ynab *YNABImport) ImportTransferTransaction(context context.Context, payeeName string,
transaction CreateTransactionParams, openTransfers *[]Transfer,
account *Account, amount numeric.Numeric,
) error {
transferToAccountName := payeeName[11:] transferToAccountName := payeeName[11:]
transferToAccount, err := ynab.GetAccount(context, transferToAccountName) transferToAccount, err := ynab.GetAccount(transferToAccountName)
if err != nil { if err != nil {
return fmt.Errorf("get transfer account %s: %w", transferToAccountName, err) return fmt.Errorf("Could not get transfer account %s: %w", transferToAccountName, err)
} }
transfer := Transfer{ transfer := Transfer{
transaction, transaction,
transferToAccount, transferToAccount,
account.Name, accountName,
transferToAccountName, transferToAccountName,
} }
found := false found := false
for i, openTransfer := range *openTransfers { for i, openTransfer := range openTransfers {
if openTransfer.TransferToAccount.ID != transfer.AccountID { if openTransfer.TransferToAccount.ID != transfer.AccountID {
continue continue
} }
@@ -271,58 +213,96 @@ func (ynab *YNABImport) ImportTransferTransaction(context context.Context, payee
} }
fmt.Printf("Matched transfers from %s to %s over %f\n", account.Name, transferToAccount.Name, amount.GetFloat64()) fmt.Printf("Matched transfers from %s to %s over %f\n", account.Name, transferToAccount.Name, amount.GetFloat64())
transfers := *openTransfers openTransfers[i] = openTransfers[len(openTransfers)-1]
transfers[i] = transfers[len(transfers)-1] openTransfers = openTransfers[:len(openTransfers)-1]
*openTransfers = transfers[:len(transfers)-1]
found = true found = true
groupID := uuid.New() groupID := uuid.New()
transfer.GroupID = uuid.NullUUID{UUID: groupID, Valid: true} transfer.GroupID = uuid.NullUUID{UUID: groupID, Valid: true}
openTransfer.GroupID = uuid.NullUUID{UUID: groupID, Valid: true} openTransfer.GroupID = uuid.NullUUID{UUID: groupID, Valid: true}
_, err = ynab.queries.CreateTransaction(context, transfer.CreateTransactionParams) _, err = ynab.queries.CreateTransaction(ynab.Context, transfer.CreateTransactionParams)
if err != nil { if err != nil {
return fmt.Errorf("save transaction %v: %w", transfer.CreateTransactionParams, err) return fmt.Errorf("could not save transaction %v: %w", transfer.CreateTransactionParams, err)
} }
_, err = ynab.queries.CreateTransaction(context, openTransfer.CreateTransactionParams) _, err = ynab.queries.CreateTransaction(ynab.Context, openTransfer.CreateTransactionParams)
if err != nil { if err != nil {
return fmt.Errorf("save transaction %v: %w", openTransfer.CreateTransactionParams, err) return fmt.Errorf("could not save transaction %v: %w", openTransfer.CreateTransactionParams, err)
} }
break break
} }
if !found { if !found {
*openTransfers = append(*openTransfers, transfer) openTransfers = append(openTransfers, transfer)
} }
} else {
payeeID, err := ynab.GetPayee(payeeName)
if err != nil {
return fmt.Errorf("could not get payee %s: %w", payeeName, err)
}
transaction.PayeeID = payeeID
_, err = ynab.queries.CreateTransaction(ynab.Context, transaction)
if err != nil {
return fmt.Errorf("could not save transaction %v: %w", transaction, err)
}
}
count++
}
for _, openTransfer := range openTransfers {
fmt.Printf("Saving unmatched transfer from %s to %s on %s over %f as regular transaction\n", openTransfer.FromAccount, openTransfer.ToAccount, openTransfer.Date, openTransfer.Amount.GetFloat64())
_, err = ynab.queries.CreateTransaction(ynab.Context, openTransfer.CreateTransactionParams)
if err != nil {
return fmt.Errorf("could not save transaction %v: %w", openTransfer.CreateTransactionParams, err)
}
}
fmt.Printf("Imported %d transactions\n", count)
return nil return nil
} }
func GetAmount(inflow string, outflow string) (numeric.Numeric, error) { func trimLastChar(s string) string {
in, err := numeric.ParseCurrency(inflow) r, size := utf8.DecodeLastRuneInString(s)
if err != nil { if r == utf8.RuneError && (size == 0 || size == 1) {
return in, fmt.Errorf("parse inflow: %w", err) size = 0
} }
return s[:len(s)-size]
}
if !in.IsZero() { func GetAmount(inflow string, outflow string) (Numeric, error) {
return in, nil // Remove trailing currency
inflow = strings.Replace(trimLastChar(inflow), ",", ".", 1)
outflow = strings.Replace(trimLastChar(outflow), ",", ".", 1)
num := Numeric{}
err := num.Set(inflow)
if err != nil {
return num, fmt.Errorf("Could not parse inflow %s: %w", inflow, err)
} }
// if inflow is zero, use outflow // if inflow is zero, use outflow
out, err := numeric.ParseCurrency("-" + outflow) if num.Int.Int64() != 0 {
if err != nil { return num, nil
return out, fmt.Errorf("parse outflow: %w", err)
} }
return out, nil
err = num.Set("-" + outflow)
if err != nil {
return num, fmt.Errorf("Could not parse outflow %s: %w", inflow, err)
}
return num, nil
} }
func (ynab *YNABImport) GetAccount(context context.Context, name string) (*Account, error) { func (ynab *YNABImport) GetAccount(name string) (*Account, error) {
for _, acc := range ynab.accounts { for _, acc := range ynab.accounts {
if acc.Name == name { if acc.Name == name {
return &acc, nil return &acc, nil
} }
} }
account, err := ynab.queries.CreateAccount(context, CreateAccountParams{Name: name, BudgetID: ynab.budgetID}) account, err := ynab.queries.CreateAccount(ynab.Context, CreateAccountParams{Name: name, BudgetID: ynab.budgetID})
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -331,7 +311,7 @@ func (ynab *YNABImport) GetAccount(context context.Context, name string) (*Accou
return &account, nil return &account, nil
} }
func (ynab *YNABImport) GetPayee(context context.Context, name string) (uuid.NullUUID, error) { func (ynab *YNABImport) GetPayee(name string) (uuid.NullUUID, error) {
if name == "" { if name == "" {
return uuid.NullUUID{}, nil return uuid.NullUUID{}, nil
} }
@@ -342,7 +322,7 @@ func (ynab *YNABImport) GetPayee(context context.Context, name string) (uuid.Nul
} }
} }
payee, err := ynab.queries.CreatePayee(context, CreatePayeeParams{Name: name, BudgetID: ynab.budgetID}) payee, err := ynab.queries.CreatePayee(ynab.Context, CreatePayeeParams{Name: name, BudgetID: ynab.budgetID})
if err != nil { if err != nil {
return uuid.NullUUID{}, err return uuid.NullUUID{}, err
} }
@@ -351,7 +331,7 @@ func (ynab *YNABImport) GetPayee(context context.Context, name string) (uuid.Nul
return uuid.NullUUID{UUID: payee.ID, Valid: true}, nil return uuid.NullUUID{UUID: payee.ID, Valid: true}, nil
} }
func (ynab *YNABImport) GetCategory(context context.Context, group string, name string) (uuid.NullUUID, error) { //nolint func (ynab *YNABImport) GetCategory(group string, name string) (uuid.NullUUID, error) {
if group == "" || name == "" { if group == "" || name == "" {
return uuid.NullUUID{}, nil return uuid.NullUUID{}, nil
} }
@@ -362,25 +342,32 @@ func (ynab *YNABImport) GetCategory(context context.Context, group string, name
} }
} }
var categoryGroup CategoryGroup for _, categoryGroup := range ynab.categoryGroups {
for _, existingGroup := range ynab.categoryGroups { if categoryGroup.Name == group {
if existingGroup.Name == group { createCategory := CreateCategoryParams{Name: name, CategoryGroupID: categoryGroup.ID}
categoryGroup = existingGroup category, err := ynab.queries.CreateCategory(ynab.Context, createCategory)
if err != nil {
return uuid.NullUUID{}, err
}
getCategory := GetCategoriesRow{
ID: category.ID,
CategoryGroupID: category.CategoryGroupID,
Name: category.Name,
Group: categoryGroup.Name,
}
ynab.categories = append(ynab.categories, getCategory)
return uuid.NullUUID{UUID: category.ID, Valid: true}, nil
} }
} }
if categoryGroup.Name == "" { categoryGroup, err := ynab.queries.CreateCategoryGroup(ynab.Context, CreateCategoryGroupParams{Name: group, BudgetID: ynab.budgetID})
newGroup := CreateCategoryGroupParams{Name: group, BudgetID: ynab.budgetID}
var err error
categoryGroup, err = ynab.queries.CreateCategoryGroup(context, newGroup)
if err != nil { if err != nil {
return uuid.NullUUID{}, err return uuid.NullUUID{}, err
} }
ynab.categoryGroups = append(ynab.categoryGroups, categoryGroup) ynab.categoryGroups = append(ynab.categoryGroups, categoryGroup)
}
newCategory := CreateCategoryParams{Name: name, CategoryGroupID: categoryGroup.ID} category, err := ynab.queries.CreateCategory(ynab.Context, CreateCategoryParams{Name: name, CategoryGroupID: categoryGroup.ID})
category, err := ynab.queries.CreateCategory(context, newCategory)
if err != nil { if err != nil {
return uuid.NullUUID{}, err return uuid.NullUUID{}, err
} }

View File

@@ -1,73 +0,0 @@
package server
import (
"net/http"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func (h *Handler) transactionsForAccount(c *gin.Context) {
accountID := c.Param("accountid")
accountUUID, err := uuid.Parse(accountID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
account, err := h.Service.GetAccount(c.Request.Context(), accountUUID)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
transactions, err := h.Service.GetTransactionsForAccount(c.Request.Context(), accountUUID)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
c.JSON(http.StatusOK, TransactionsResponse{account, transactions})
}
type TransactionsResponse struct {
Account postgres.Account
Transactions []postgres.DisplayTransaction
}
type EditAccountRequest struct {
Name string `json:"name"`
OnBudget bool `json:"onBudget"`
IsOpen bool `json:"isOpen"`
}
func (h *Handler) editAccount(c *gin.Context) {
accountID := c.Param("accountid")
accountUUID, err := uuid.Parse(accountID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
var request EditAccountRequest
err = c.BindJSON(&request)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
updateParams := postgres.UpdateAccountParams{
Name: request.Name,
OnBudget: request.OnBudget,
IsOpen: request.IsOpen,
ID: accountUUID,
}
account, err := h.Service.UpdateAccount(c.Request.Context(), updateParams)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
h.returnBudgetingData(c, account.BudgetID)
}

View File

@@ -1,72 +0,0 @@
package server
import (
"net/http"
"strings"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func (h *Handler) autocompleteCategories(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"budgetid missing from URL"})
return
}
query := c.Request.URL.Query().Get("s")
searchParams := postgres.SearchCategoriesParams{
BudgetID: budgetUUID,
Search: "%" + query + "%",
}
categories, err := h.Service.SearchCategories(c.Request.Context(), searchParams)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, categories)
}
func (h *Handler) autocompletePayee(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"budgetid missing from URL"})
return
}
query := c.Request.URL.Query().Get("s")
transferPrefix := "Transfer"
if strings.HasPrefix(query, transferPrefix) {
searchParams := postgres.SearchAccountsParams{
BudgetID: budgetUUID,
Search: "%" + strings.Trim(query[len(transferPrefix):], " \t\n:") + "%",
}
accounts, err := h.Service.SearchAccounts(c.Request.Context(), searchParams)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, accounts)
} else {
searchParams := postgres.SearchPayeesParams{
BudgetID: budgetUUID,
Search: query + "%",
}
payees, err := h.Service.SearchPayees(c.Request.Context(), searchParams)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, payees)
}
}

View File

@@ -1,200 +0,0 @@
package server
import (
"fmt"
"net/http"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func getFirstOfMonth(year, month int, location *time.Location) time.Time {
return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, location)
}
func getFirstOfMonthTime(date time.Time) time.Time {
var monthM time.Month
year, monthM, _ := date.Date()
month := int(monthM)
return getFirstOfMonth(year, month, date.Location())
}
type CategoryWithBalance struct {
*postgres.GetCategoriesRow
Available numeric.Numeric
AvailableLastMonth numeric.Numeric
Activity numeric.Numeric
Assigned numeric.Numeric
}
func NewCategoryWithBalance(category *postgres.GetCategoriesRow) CategoryWithBalance {
return CategoryWithBalance{
GetCategoriesRow: category,
Available: numeric.Zero(),
AvailableLastMonth: numeric.Zero(),
Activity: numeric.Zero(),
Assigned: numeric.Zero(),
}
}
func (h *Handler) budgetingForMonth(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"budgetid missing from URL"})
return
}
budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
firstOfMonth, err := getDate(c)
if err != nil {
c.Redirect(http.StatusTemporaryRedirect, "/budget/"+budgetUUID.String())
return
}
categories, err := h.Service.GetCategories(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
firstOfNextMonth := firstOfMonth.AddDate(0, 1, 0)
cumultativeBalances, err := h.Service.GetCumultativeBalances(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse{fmt.Sprintf("error loading balances: %s", err)})
return
}
categoriesWithBalance, moneyUsed := h.calculateBalances(
budget, firstOfNextMonth, firstOfMonth, categories, cumultativeBalances)
availableBalance := h.getAvailableBalance(budget, moneyUsed, cumultativeBalances, firstOfNextMonth)
for i := range categoriesWithBalance {
cat := &categoriesWithBalance[i]
if cat.ID != budget.IncomeCategoryID {
continue
}
cat.Available = availableBalance
cat.AvailableLastMonth = availableBalance
}
data := struct {
Categories []CategoryWithBalance
AvailableBalance numeric.Numeric
}{categoriesWithBalance, availableBalance}
c.JSON(http.StatusOK, data)
}
func (*Handler) getAvailableBalance(budget postgres.Budget,
moneyUsed numeric.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow,
firstOfNextMonth time.Time) numeric.Numeric {
availableBalance := moneyUsed
for _, bal := range cumultativeBalances {
if bal.CategoryID != budget.IncomeCategoryID {
continue
}
if !bal.Date.Before(firstOfNextMonth) {
continue
}
availableBalance.AddI(bal.Transactions)
availableBalance.AddI(bal.Assignments)
}
return availableBalance
}
type BudgetingResponse struct {
Accounts []postgres.GetAccountsWithBalanceRow
Budget postgres.Budget
}
func (h *Handler) budgeting(c *gin.Context) {
budgetID := c.Param("budgetid")
budgetUUID, err := uuid.Parse(budgetID)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"budgetid missing from URL"})
return
}
h.returnBudgetingData(c, budgetUUID)
}
func (h *Handler) returnBudgetingData(c *gin.Context, budgetUUID uuid.UUID) {
budget, err := h.Service.GetBudget(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
accounts, err := h.Service.GetAccountsWithBalance(c.Request.Context(), budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
data := BudgetingResponse{accounts, budget}
c.JSON(http.StatusOK, data)
}
func (h *Handler) calculateBalances(budget postgres.Budget,
firstOfNextMonth time.Time, firstOfMonth time.Time, categories []postgres.GetCategoriesRow,
cumultativeBalances []postgres.GetCumultativeBalancesRow) ([]CategoryWithBalance, numeric.Numeric) {
categoriesWithBalance := []CategoryWithBalance{}
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)
categoriesWithBalance = append(categoriesWithBalance, categoryWithBalance)
}
return categoriesWithBalance, *moneyUsed
}
func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow,
cumultativeBalances []postgres.GetCumultativeBalancesRow, firstOfNextMonth time.Time,
moneyUsed *numeric.Numeric, firstOfMonth time.Time, budget postgres.Budget) CategoryWithBalance {
categoryWithBalance := NewCategoryWithBalance(cat)
for _, bal := range cumultativeBalances {
if bal.CategoryID != cat.ID {
continue
}
// skip everything in the future
if !bal.Date.Before(firstOfNextMonth) {
continue
}
moneyUsed.SubI(bal.Assignments)
categoryWithBalance.Available.AddI(bal.Assignments)
categoryWithBalance.Available.AddI(bal.Transactions)
if !categoryWithBalance.Available.IsPositive() && bal.Date.Before(firstOfMonth) {
moneyUsed.AddI(categoryWithBalance.Available)
categoryWithBalance.Available = numeric.Zero()
}
if bal.Date.Before(firstOfMonth) {
categoryWithBalance.AvailableLastMonth = categoryWithBalance.Available
} else if bal.Date.Before(firstOfNextMonth) {
categoryWithBalance.Activity = bal.Transactions
categoryWithBalance.Assigned = bal.Assignments
}
}
return categoryWithBalance
}

View File

@@ -1,55 +0,0 @@
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
}
}

View File

@@ -1,109 +0,0 @@
package server
import (
"database/sql"
"fmt"
"net/http"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type ReconcileTransactionsRequest struct {
TransactionIDs []uuid.UUID `json:"transactionIds"`
ReconcilationTransactionAmount string `json:"reconciliationTransactionAmount"`
}
type ReconcileTransactionsResponse struct {
Message string
ReconciliationTransaction *postgres.DisplayTransaction
}
func (h *Handler) reconcileTransactions(c *gin.Context) {
accountID := c.Param("accountid")
accountUUID, err := uuid.Parse(accountID)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
var request ReconcileTransactionsRequest
err = c.BindJSON(&request)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse request: %w", err))
return
}
var amount numeric.Numeric
err = amount.Set(request.ReconcilationTransactionAmount)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse request: %w", err))
return
}
tx, err := h.Service.BeginTx(c.Request.Context(), &sql.TxOptions{})
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("begin tx: %w", err))
return
}
db := h.Service.WithTx(tx)
for _, transactionID := range request.TransactionIDs {
err := db.SetTransactionReconciled(c.Request.Context(), transactionID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("update transaction: %w", err))
return
}
}
reconciliationTransaction, err := h.CreateReconcilationTransaction(amount, accountUUID, db, c)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("insert new transaction: %w", err))
return
}
err = h.Service.SetLastReconciled(c.Request.Context(), accountUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("set last reconciled: %w", err))
return
}
err = tx.Commit()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("commit: %w", err))
return
}
c.JSON(http.StatusOK, ReconcileTransactionsResponse{
Message: fmt.Sprintf("Set status for %d transactions", len(request.TransactionIDs)),
ReconciliationTransaction: reconciliationTransaction,
})
}
func (*Handler) CreateReconcilationTransaction(amount numeric.Numeric, accountUUID uuid.UUID, db *postgres.Queries, c *gin.Context) (*postgres.DisplayTransaction, error) {
if amount.IsZero() {
return nil, nil //nolint: nilnil
}
createTransaction := postgres.CreateTransactionParams{
Date: time.Now(),
Memo: "Reconciliation Transaction",
Amount: amount,
AccountID: accountUUID,
Status: "Reconciled",
}
transactionUUID, err := db.CreateTransaction(c.Request.Context(), createTransaction)
if err != nil {
return nil, fmt.Errorf("insert new transaction: %w", err)
}
transaction, err := db.GetTransaction(c.Request.Context(), transactionUUID)
if err != nil {
return nil, fmt.Errorf("get created transaction: %w", err)
}
return &transaction, nil
}

View File

@@ -1,159 +0,0 @@
package server
import (
"context"
"fmt"
"net/http"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type NewTransactionPayload struct {
Date JSONDate `json:"date"`
Payee struct {
ID uuid.NullUUID
Name string
Type string
} `json:"payee"`
CategoryID uuid.NullUUID `json:"categoryId"`
Memo string `json:"memo"`
Amount string `json:"amount"`
BudgetID uuid.UUID `json:"budgetId"`
AccountID uuid.UUID `json:"accountId"`
State string `json:"state"`
}
func (h *Handler) newTransaction(c *gin.Context) {
var payload NewTransactionPayload
err := c.BindJSON(&payload)
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
amount, err := numeric.Parse(payload.Amount)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("amount: %w", err))
return
}
transactionID := c.Param("transactionid")
if transactionID != "" {
h.UpdateTransaction(payload, amount, transactionID, c)
return
}
newTransaction := postgres.CreateTransactionParams{
Memo: payload.Memo,
Date: time.Time(payload.Date),
Amount: amount,
Status: postgres.TransactionStatus(payload.State),
CategoryID: payload.CategoryID,
AccountID: payload.AccountID,
}
if payload.Payee.Type == "account" {
groupID, err := h.CreateTransferForOtherAccount(newTransaction, amount, payload, c)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
newTransaction.GroupID = groupID
} else {
payeeID, err := GetPayeeID(c.Request.Context(), payload, h)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create payee: %w", err))
}
newTransaction.PayeeID = payeeID
}
transactionUUID, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("create transaction: %w", err))
return
}
transaction, err := h.Service.GetTransaction(c.Request.Context(), transactionUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("get transaction: %w", err))
return
}
c.JSON(http.StatusOK, transaction)
}
func (h *Handler) UpdateTransaction(payload NewTransactionPayload, amount numeric.Numeric, transactionID string, c *gin.Context) {
transactionUUID := uuid.MustParse(transactionID)
if amount.IsZero() {
err := h.Service.DeleteTransaction(c.Request.Context(), transactionUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("delete transaction: %w", err))
}
return
}
editTransaction := postgres.UpdateTransactionParams{
Memo: payload.Memo,
Date: time.Time(payload.Date),
Amount: amount,
PayeeID: payload.Payee.ID,
CategoryID: payload.CategoryID,
ID: transactionUUID,
}
err := h.Service.UpdateTransaction(c.Request.Context(), editTransaction)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("edit transaction: %w", err))
return
}
transaction, err := h.Service.GetTransaction(c.Request.Context(), transactionUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("get transaction: %w", err))
return
}
c.JSON(http.StatusOK, transaction)
}
func (h *Handler) CreateTransferForOtherAccount(newTransaction postgres.CreateTransactionParams, amount numeric.Numeric, payload NewTransactionPayload, c *gin.Context) (uuid.NullUUID, error) {
newTransaction.GroupID = uuid.NullUUID{UUID: uuid.New(), Valid: true}
newTransaction.Amount = amount.Neg()
newTransaction.AccountID = payload.Payee.ID.UUID
// transfer does not need category. Either it's account is off-budget or no category was supplied.
newTransaction.CategoryID = uuid.NullUUID{}
_, err := h.Service.CreateTransaction(c.Request.Context(), newTransaction)
if err != nil {
return uuid.NullUUID{}, fmt.Errorf("create transfer transaction: %w", err)
}
return newTransaction.GroupID, nil
}
func GetPayeeID(context context.Context, payload NewTransactionPayload, h *Handler) (uuid.NullUUID, error) {
payeeID := payload.Payee.ID
if payeeID.Valid {
return payeeID, nil
}
if payload.Payee.Name == "" {
return uuid.NullUUID{}, nil
}
newPayee := postgres.CreatePayeeParams{
Name: payload.Payee.Name,
BudgetID: payload.BudgetID,
}
payee, err := h.Service.CreatePayee(context, newPayee)
if err != nil {
return uuid.NullUUID{}, fmt.Errorf("create payee: %w", err)
}
return uuid.NullUUID{UUID: payee.ID, Valid: true}, nil
}

View File

@@ -1,30 +0,0 @@
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
}

View File

@@ -1,117 +0,0 @@
package server
import (
"net/http"
"git.javil.eu/jacob1123/budgeteer/postgres"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func (h *Handler) importYNAB(c *gin.Context) {
budgetID, succ := c.Params.Get("budgetid")
if !succ {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"no budget_id specified"})
return
}
budgetUUID, err := uuid.Parse(budgetID)
if !succ {
c.AbortWithError(http.StatusBadRequest, err)
return
}
ynab, err := postgres.NewYNABImport(c.Request.Context(), h.Service.Queries, budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
transactionsFile, err := c.FormFile("transactions")
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
transactions, err := transactionsFile.Open()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
err = ynab.ImportTransactions(c.Request.Context(), transactions)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
assignmentsFile, err := c.FormFile("assignments")
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
assignments, err := assignmentsFile.Open()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
err = ynab.ImportAssignments(c.Request.Context(), assignments)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}
func (h *Handler) exportYNABTransactions(c *gin.Context) {
budgetID, succ := c.Params.Get("budgetid")
if !succ {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"no budget_id specified"})
return
}
budgetUUID, err := uuid.Parse(budgetID)
if !succ {
c.AbortWithError(http.StatusBadRequest, err)
return
}
ynab, err := postgres.NewYNABExport(c.Request.Context(), h.Service.Queries, budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
err = ynab.ExportTransactions(c.Request.Context(), c.Writer)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}
func (h *Handler) exportYNABAssignments(c *gin.Context) {
budgetID, succ := c.Params.Get("budgetid")
if !succ {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"no budget_id specified"})
return
}
budgetUUID, err := uuid.Parse(budgetID)
if !succ {
c.AbortWithError(http.StatusBadRequest, err)
return
}
ynab, err := postgres.NewYNABExport(c.Request.Context(), h.Service.Queries, budgetUUID)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
err = ynab.ExportAssignments(c.Request.Context(), c.Writer)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}

View File

@@ -7,11 +7,9 @@ packages:
queries: "postgres/queries/" queries: "postgres/queries/"
overrides: overrides:
- go_type: - go_type:
import: "git.javil.eu/jacob1123/budgeteer/postgres/numeric" type: "Numeric"
type: Numeric
db_type: "pg_catalog.numeric" db_type: "pg_catalog.numeric"
- go_type: - go_type:
import: "git.javil.eu/jacob1123/budgeteer/postgres/numeric" type: "Numeric"
type: Numeric
db_type: "pg_catalog.numeric" db_type: "pg_catalog.numeric"
nullable: true nullable: true

View File

@@ -5,7 +5,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
) )
// Token contains data that authenticates a user. // Token contains data that authenticates a user
type Token interface { type Token interface {
GetUsername() string GetUsername() string
GetName() string GetName() string
@@ -13,7 +13,7 @@ type Token interface {
GetID() uuid.UUID GetID() uuid.UUID
} }
// TokenVerifier verifies a Token. // TokenVerifier verifies a Token
type TokenVerifier interface { type TokenVerifier interface {
VerifyToken(string) (Token, error) VerifyToken(string) (Token, error)
CreateToken(*postgres.User) (string, error) CreateToken(*postgres.User) (string, error)

View File

@@ -1,17 +0,0 @@
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",
},
};

View File

@@ -6,8 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title> <title>Vite App</title>
</head> </head>
<body <body>
class="bg-slate-200 text-slate-800 dark:bg-slate-800 dark:text-slate-200 box-border w-full">
<div id="app"></div> <div id="app"></div>
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>

View File

@@ -11,7 +11,6 @@
"@mdi/font": "5.9.55", "@mdi/font": "5.9.55",
"@vueuse/core": "^7.6.1", "@vueuse/core": "^7.6.1",
"autoprefixer": "^10.4.2", "autoprefixer": "^10.4.2",
"file-saver": "^2.0.5",
"pinia": "^2.0.11", "pinia": "^2.0.11",
"postcss": "^8.4.6", "postcss": "^8.4.6",
"tailwindcss": "^3.0.18", "tailwindcss": "^3.0.18",
@@ -19,26 +18,13 @@
"vue-router": "^4.0.12" "vue-router": "^4.0.12"
}, },
"devDependencies": { "devDependencies": {
"@types/file-saver": "^2.0.5",
"@typescript-eslint/parser": "^5.13.0",
"@vitejs/plugin-vue": "^2.0.0", "@vitejs/plugin-vue": "^2.0.0",
"@vue/cli-plugin-babel": "5.0.0-beta.7", "@vue/cli-plugin-babel": "5.0.0-beta.7",
"@vue/cli-plugin-typescript": "~4.5.0", "@vue/cli-plugin-typescript": "~4.5.0",
"@vue/cli-service": "5.0.0-beta.7", "@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": "^1.38.0",
"sass-loader": "^10.0.0", "sass-loader": "^10.0.0",
"typescript": "^4.5.5",
"vite": "^2.7.2", "vite": "^2.7.2",
"vue-tsc": "^0.32.0" "vue-cli-plugin-vuetify": "~2.4.5"
}, }
"prettier": {
"bracketSameLine": true,
"embeddedLanguageFormatting": "off",
"tabWidth": 4,
"useTabs": false
},
"eslintIgnore": ["index.css"]
} }

View File

@@ -3,4 +3,4 @@ module.exports = {
tailwindcss: {}, tailwindcss: {},
autoprefixer: {}, autoprefixer: {},
}, },
}; }

View File

@@ -8,6 +8,7 @@ import { useSettingsStore } from "./stores/settings";
export default defineComponent({ export default defineComponent({
computed: { computed: {
...mapState(useBudgetsStore, ["CurrentBudgetName"]), ...mapState(useBudgetsStore, ["CurrentBudgetName"]),
...mapState(useSettingsStore, ["Menu"]),
...mapState(useSessionStore, ["LoggedIn"]), ...mapState(useSessionStore, ["LoggedIn"]),
}, },
methods: { methods: {
@@ -26,50 +27,39 @@ export default defineComponent({
</script> </script>
<template> <template>
<div class="flex flex-col md:flex-row flex-1 h-screen"> <div class="box-border w-full">
<router-view name="sidebar" /> <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>
<div class="flex-1 overflow-auto"> <span class="flex-1 font-bold text-5xl -my-3 md:hidden" @click="toggleMenu"></span>
<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>
<span class="flex-1">{{ CurrentBudgetName }}</span> <span class="flex-1">{{ CurrentBudgetName }}</span>
<div class="flex flex-1 flex-row justify-end -mx-4"> <div class="flex flex-1 flex-row justify-end -mx-4">
<router-link <router-link class="mx-4" v-if="LoggedIn" to="/dashboard">Dashboard</router-link>
v-if="LoggedIn" <router-link class="mx-4" v-if="!LoggedIn" to="/login">Login</router-link>
class="mx-4" <a class="mx-4" v-if="LoggedIn" @click="logout">Logout</a>
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> </div>
<div class="p-3 pl-6"> <div class="flex flex-col md:flex-row flex-1">
<router-view /> <div
:class="[Menu.Expand ? 'md:w-72' : 'md:w-36', Menu.Show ? '' : 'hidden']"
class="md:block flex-shrink-0 w-full"
>
<router-view name="sidebar"></router-view>
</div>
<div class="flex-1 p-6">
<router-view></router-view>
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
</style>

View File

@@ -1,13 +1,13 @@
import { useSessionStore } from "./stores/session"; import { useSessionStore } from "./stores/session";
export const BASE_URL = "/api/v1"; export const BASE_URL = "/api/v1"
export function GET(path: string) { export function GET(path: string) {
const sessionStore = useSessionStore(); const sessionStore = useSessionStore();
return fetch(BASE_URL + path, { return fetch(BASE_URL + path, {
headers: sessionStore.AuthHeaders, headers: sessionStore.AuthHeaders,
}); })
} };
export function POST(path: string, body: FormData | string | null) { export function POST(path: string, body: FormData | string | null) {
const sessionStore = useSessionStore(); const sessionStore = useSessionStore();
@@ -15,12 +15,12 @@ export function POST(path: string, body: FormData | string | null) {
method: "POST", method: "POST",
headers: sessionStore.AuthHeaders, headers: sessionStore.AuthHeaders,
body: body, body: body,
}); })
} }
export function DELETE(path: string) { export function DELETE(path: string) {
const sessionStore = useSessionStore(); const sessionStore = useSessionStore();
return fetch(BASE_URL + path, { return fetch(BASE_URL + path, {
method: "DELETE", method: "DELETE",
headers: sessionStore.AuthHeaders, headers: sessionStore.AuthHeaders,
}); })
} }

View File

@@ -1,35 +0,0 @@
<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>

View File

@@ -1,39 +1,43 @@
<script lang="ts" setup> <script lang="ts" setup>
import { ref, watch } from "vue" import { defineComponent, PropType, ref, watch } from "vue"
import { GET } from "../api"; import { GET } from "../api";
import { useBudgetsStore } from "../stores/budget"; import { useBudgetsStore } from "../stores/budget";
import Input from "./Input.vue";
export interface Suggestion { export interface Suggestion {
ID: string ID: string
Name: string Name: string
Type: string }
interface Data {
Selected: Suggestion | undefined
SearchQuery: String
Suggestions: Suggestion[]
} }
const props = defineProps<{ const props = defineProps<{
text: string, modelValue: Suggestion | undefined,
id: string | undefined, type: String
model: string,
type?: string | undefined,
}>(); }>();
const SearchQuery = ref(props.text || ""); const Selected = ref<Suggestion | undefined>(props.modelValue || undefined);
const SearchQuery = ref(props.modelValue?.Name || "");
const Suggestions = ref<Array<Suggestion>>([]); const Suggestions = ref<Array<Suggestion>>([]);
const emit = defineEmits(["update:id", "update:text", "update:type"]); const emit = defineEmits(["update:modelValue"]);
watch(SearchQuery, () => { watch(SearchQuery, () => {
load(SearchQuery.value); load(SearchQuery.value);
}); });
function saveTransaction(e: MouseEvent) {
e.preventDefault();
};
function load(text: String) { function load(text: String) {
emit('update:id', null); emit('update:modelValue', { ID: null, Name: text });
emit('update:text', text);
emit('update:type', undefined);
if (text == "") { if (text == "") {
Suggestions.value = []; Suggestions.value = [];
return; return;
} }
const budgetStore = useBudgetsStore(); const budgetStore = useBudgetsStore();
GET("/budget/" + budgetStore.CurrentBudgetID + "/autocomplete/" + props.model + "?s=" + text) GET("/budget/" + budgetStore.CurrentBudgetID + "/autocomplete/" + props.type + "?s=" + text)
.then(x => x.json()) .then(x => x.json())
.then(x => { .then(x => {
let suggestions = x || []; let suggestions = x || [];
@@ -44,9 +48,8 @@ function load(text: String) {
}); });
}; };
function keypress(e: KeyboardEvent) { function keypress(e: KeyboardEvent) {
if (e.key != "Enter") console.log(e.key);
return; if (e.key == "Enter") {
const selected = Suggestions.value[0]; const selected = Suggestions.value[0];
selectElement(selected); selectElement(selected);
const el = (<HTMLInputElement>e.target); const el = (<HTMLInputElement>e.target);
@@ -54,15 +57,14 @@ function keypress(e: KeyboardEvent) {
const currentIndex = inputElements.indexOf(el); const currentIndex = inputElements.indexOf(el);
const nextElement = inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0]; const nextElement = inputElements[currentIndex < inputElements.length - 1 ? currentIndex + 1 : 0];
(<HTMLInputElement>nextElement).focus(); (<HTMLInputElement>nextElement).focus();
};
}
};
function selectElement(element: Suggestion) { function selectElement(element: Suggestion) {
emit('update:id', element.ID); Selected.value = element;
emit('update:text', element.Name);
emit('update:type', element.Type);
Suggestions.value = []; Suggestions.value = [];
emit('update:modelValue', element);
}; };
function select(e: MouseEvent) { function select(e: MouseEvent) {
const target = (<HTMLInputElement>e.target); const target = (<HTMLInputElement>e.target);
const valueAttribute = target.attributes.getNamedItem("value"); const valueAttribute = target.attributes.getNamedItem("value");
@@ -72,38 +74,27 @@ function select(e: MouseEvent) {
const selected = Suggestions.value.filter(x => x.ID == selectedID)[0]; const selected = Suggestions.value.filter(x => x.ID == selectedID)[0];
selectElement(selected); selectElement(selected);
}; };
function clear() { function clear() {
emit('update:id', null); Selected.value = undefined;
emit('update:text', SearchQuery.value); emit('update:modelValue', { ID: null, Name: SearchQuery.value });
emit('update:type', undefined);
}; };
</script> </script>
<template> <template>
<div> <div>
<Input <input
v-if="id == undefined"
v-model="SearchQuery"
type="text"
class="border-b-2 border-black" class="border-b-2 border-black"
@keypress="keypress" @keypress="keypress"
v-if="Selected == undefined"
v-model="SearchQuery"
/> />
<span <span @click="clear" v-if="Selected != undefined" class="bg-gray-300">{{ Selected.Name }}</span>
v-if="id != undefined" <div v-if="Suggestions.length > 0" class="absolute bg-gray-400 w-64 p-2">
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 <span
v-for="suggestion in Suggestions" v-for="suggestion in Suggestions"
:key="suggestion.ID"
class="block" class="block"
:value="suggestion.ID"
@click="select" @click="select"
:value="suggestion.ID"
>{{ suggestion.Name }}</span> >{{ suggestion.Name }}</span>
</div> </div>
</div> </div>

View File

@@ -0,0 +1,8 @@
<script lang="ts" setup>
</script>
<template>
<div class="flex flex-row items-center bg-gray-300 h-32 rounded-lg">
<slot></slot>
</div>
</template>

View File

@@ -1,15 +0,0 @@
<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>

View File

@@ -1,11 +1,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed } from 'vue'; import { computed } from 'vue';
const props = defineProps<{ const props = defineProps<{ value: number | undefined }>();
value: number | undefined
negativeClass?: string
positiveClass?: string
}>();
const internalValue = computed(() => Number(props.value ?? 0)); const internalValue = computed(() => Number(props.value ?? 0));
@@ -15,8 +11,5 @@ const formattedValue = computed(() => internalValue.value.toLocaleString(undefin
</script> </script>
<template> <template>
<span <span class="text-right" :class="internalValue < 0 ? 'negative' : ''">{{ formattedValue }} </span>
class="text-right"
:class="internalValue < 0 ? (negativeClass ?? 'negative') : positiveClass"
>{{ formattedValue }} </span>
</template> </template>

View File

@@ -1,38 +0,0 @@
<script lang="ts" setup>
import Input from './Input.vue';
const props = defineProps<{
modelValue?: Date
}>();
const emit = defineEmits(['update:modelValue']);
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];
}
function updateValue(event: Event) {
const target = event.target as HTMLInputElement;
emit('update:modelValue', target.valueAsDate);
}
function selectAll(event: FocusEvent) {
// Workaround for Safari bug
// http://stackoverflow.com/questions/1269722/selecting-text-on-focus-using-jquery-not-working-in-safari-and-chrome
setTimeout(function () {
const target = event.target as HTMLInputElement;
target.select()
}, 0)
}
</script>
<template>
<Input
ref="input"
type="date"
:value="dateToYYYYMMDD(modelValue)"
@input="updateValue"
@focus="selectAll"
/>
</template>

View File

@@ -1,17 +0,0 @@
<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>

View File

@@ -1,77 +0,0 @@
<script lang="ts" setup>
import RowCard from './RowCard.vue';
import { ref } from "vue";
const props = defineProps<{
buttonText?: string,
}>();
const emit = defineEmits<{
(e: 'submit', event : {cancel:boolean}): boolean,
(e: 'open'): void,
}>();
const visible = ref(false);
function closeDialog() {
visible.value = false;
};
function openDialog() {
emit("open");
visible.value = true;
};
function submitDialog() {
const e = {cancel: false};
emit("submit", e);
if(e.cancel)
return;
visible.value = false;
}
</script>
<template>
<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
class="relative top-20 mx-auto p-5 w-96 shadow-lg rounded-md bg-white dark:bg-black"
>
<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>

View File

@@ -1,9 +0,0 @@
<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>

View File

@@ -1,7 +0,0 @@
<script lang="ts" setup></script>
<template>
<button class="px-4 rounded-md shadow-sm focus:outline-none focus:ring-2">
<slot />
</button>
</template>

View File

@@ -1,87 +0,0 @@
<script lang="ts" setup>
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
}>()
const emit = defineEmits(["save"]);
const transactionsStore = useTransactionsStore();
const TX = transactionsStore.Transactions.get(props.transactionid)!;
const payeeType = ref<string|undefined>(undefined);
const payload = computed(() => JSON.stringify({
date: TX.Date.toISOString().split("T")[0],
payee: {
Name: TX.Payee,
ID: TX.PayeeID,
Type: payeeType.value,
},
categoryId: TX.CategoryID,
memo: TX.Memo,
amount: TX.Amount.toString(),
state: "Uncleared"
}));
function saveTransaction(e: MouseEvent) {
e.preventDefault();
transactionsStore.editTransaction(TX.ID, payload.value);
emit('save');
}
</script>
<template>
<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>

View File

@@ -1,110 +1,61 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, ref } from "vue"; import { computed, ref } from "vue";
import Autocomplete from '../components/Autocomplete.vue' import Autocomplete, { Suggestion } from '../components/Autocomplete.vue'
import { Transaction, useTransactionsStore } from "../stores/transactions"; import { useAccountStore } from '../stores/budget-account'
import DateInput from "./DateInput.vue";
import Button from "./SimpleButton.vue";
import Input from "./Input.vue";
const props = defineProps<{ const props = defineProps<{
budgetid: string budgetid: string
accountid: string accountid: string
}>() }>()
const TX = ref<Transaction>({ const TransactionDate = ref(new Date().toISOString().substring(0, 10));
Date: new Date(), const Payee = ref<Suggestion | undefined>(undefined);
Memo: "", const Category = ref<Suggestion | undefined>(undefined);
Amount: 0, const Memo = ref("");
Payee: "", const Amount = ref("0");
PayeeID: undefined,
Category: "",
CategoryID: undefined,
CategoryGroup: "",
GroupID: "",
ID: "",
Status: "Uncleared",
TransferAccount: "",
Reconciled: false
});
const payeeType = ref<string|undefined>(undefined);
const payload = computed(() => JSON.stringify({ const payload = computed(() => JSON.stringify({
budgetId: props.budgetid, budget_id: props.budgetid,
accountId: props.accountid, account_id: props.accountid,
date: TX.value.Date.toISOString().split("T")[0], date: TransactionDate.value,
payee: { payee: Payee.value,
Name: TX.value.Payee, category: Category.value,
ID: TX.value.PayeeID, memo: Memo.value,
Type: payeeType.value, amount: Amount.value,
},
categoryId: TX.value.CategoryID,
memo: TX.value.Memo,
amount: TX.value.Amount.toString(),
state: "Uncleared" state: "Uncleared"
})); }));
const transactionsStore = useTransactionsStore(); const accountStore = useAccountStore();
function saveTransaction(e: MouseEvent) { function saveTransaction(e: MouseEvent) {
e.preventDefault(); e.preventDefault();
Save(); accountStore.saveTransaction(payload.value);
} }
function Save() {
transactionsStore.saveTransaction(payload.value);
}
defineExpose({Save});
</script> </script>
<template> <template>
<tr> <tr>
<label class="md:hidden">Date</label> <td style="width: 90px;" class="text-sm">
<td class="text-sm"> <input class="border-b-2 border-black" type="date" v-model="TransactionDate" />
<DateInput </td>
v-model="TX.Date" <td style="max-width: 150px;">
class="border-b-2 border-black" <Autocomplete v-model="Payee" type="payees" />
/> </td>
<td style="max-width: 200px;">
<Autocomplete v-model="Category" type="categories" />
</td> </td>
<label class="md:hidden">Payee</label>
<td> <td>
<Autocomplete <input class="block w-full border-b-2 border-black" type="text" v-model="Memo" />
v-model:text="TX.Payee"
v-model:id="TX.PayeeID"
v-model:type="payeeType"
model="payees"
/>
</td> </td>
<label class="md:hidden">Category</label> <td style="width: 80px;" class="text-right">
<td> <input
<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" class="text-right block w-full border-b-2 border-black"
type="currency" type="currency"
v-model="Amount"
/> />
</td> </td>
<td class="hidden md:table-cell"> <td style="width: 20px;">
<Button <input type="submit" @click="saveTransaction" value="Save" />
class="bg-blue-500"
@click="saveTransaction"
>
Save
</Button>
</td> </td>
<td style="width: 20px;"></td>
</tr> </tr>
</template> </template>

View File

@@ -1,100 +1,39 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, ref } from "vue"; import { computed } from "vue";
import { useBudgetsStore } from "../stores/budget"; import { useBudgetsStore } from "../stores/budget";
import { useTransactionsStore } from "../stores/transactions"; import { Transaction } from "../stores/budget-account";
import Currency from "./Currency.vue"; 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<{ const props = defineProps<{
transactionid: string, transaction: Transaction,
index: number, index: number,
}>(); }>();
const edit = ref(false); const CurrentBudgetID = computed(()=> useBudgetsStore().CurrentBudgetID);
const CurrentBudgetID = computed(() => useBudgetsStore().CurrentBudgetID);
const Reconciling = computed(() => useTransactionsStore().Reconciling);
const transactionsStore = useTransactionsStore();
const TX = transactionsStore.Transactions.get(props.transactionid)!;
function 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> </script>
<template> <template>
<tr v-if="dateChanged()" class="table-row md:hidden"> <tr class="{{transaction.Date.After now ? 'future' : ''}}"
<td class="py-2" colspan="5"> :class="[index % 6 < 3 ? 'bg-gray-300' : 'bg-gray-100']">
<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' : '']">--> <!--:class="[index % 6 < 3 ? index % 6 === 1 ? 'bg-gray-400' : 'bg-gray-300' : index % 6 !== 4 ? 'bg-gray-100' : '']">-->
<td class="hidden md:block"> <td style="width: 90px;">{{ transaction.Date.substring(0, 10) }}</td>
{{ formatDate(TX.Date) }} <td style="max-width: 150px;">{{ transaction.TransferAccount ? "Transfer : " + transaction.TransferAccount : transaction.Payee }}</td>
</td> <td style="max-width: 200px;">
<td class="pl-2 md:pl-0"> {{ transaction.CategoryGroup ? transaction.CategoryGroup + " : " + transaction.Category : "" }}
{{ TX.TransferAccount ? "Transfer : " + TX.TransferAccount : TX.Payee }}
</td> </td>
<td> <td>
{{ TX.CategoryGroup ? TX.CategoryGroup + " : " + TX.Category : "" }} <a :href="'/budget/' + CurrentBudgetID + '/transaction/' + transaction.ID">
{{ transaction.Memo }}
</a>
</td> </td>
<td> <td>
<a <Currency class="block" :value="transaction.Amount" />
:href="'/budget/' + CurrentBudgetID + '/transaction/' + TX.ID"
>{{ TX.Memo }}</a>
</td> </td>
<td> <td style="width: 20px;">
<Currency {{ transaction.Status == "Reconciled" ? "✔" : (transaction.Status == "Uncleared" ? "" : "*") }}
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> </td>
<td style="width: 20px;">{{ transaction.GroupID ? "☀" : "" }}</td>
</tr> </tr>
<TransactionEditRow
v-if="edit"
:transactionid="TX.ID"
@save="edit = false"
/>
</template> </template>
<style> <style>

View File

@@ -1,8 +0,0 @@
export function formatDate(date: Date): string {
return date.toLocaleDateString(undefined, {
// you can use undefined as first argument
year: "numeric",
month: "2-digit",
day: "2-digit",
});
}

View File

@@ -1,85 +0,0 @@
<script lang="ts" setup>
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 : {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 #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>

View File

@@ -1,28 +1,36 @@
<script lang="ts" setup> <script lang="ts" setup>
import Modal from '../components/Modal.vue'; import Card from '../components/Card.vue';
import { ref } from "vue"; import { ref } from "vue";
import { useBudgetsStore } from '../stores/budget'; import { useBudgetsStore } from '../stores/budget';
import Input from '../components/Input.vue';
const dialog = ref(false);
const budgetName = ref(""); const budgetName = ref("");
function saveBudget() { function saveBudget() {
useBudgetsStore().NewBudget(budgetName.value); useBudgetsStore().NewBudget(budgetName.value);
dialog.value = false;
};
function newBudget() {
dialog.value = true;
}; };
</script> </script>
<template> <template>
<Modal <Card>
button-text="New Budget" <p class="w-24 text-center text-6xl">+</p>
@submit="saveBudget" <button class="text-lg" dark @click="newBudget">New Budget</button>
> </Card>
<div class="mt-2 px-7 py-3"> <div v-if="dialog" justify="center">
<Input <div>
v-model="budgetName" <div>
class="border-2" <span class="text-h5">New Budget</span>
type="text" </div>
placeholder="Budget name" <div>
required <input type="text" v-model="budgetName" label="Budget name" required />
/> </div>
<div>
<button @click="dialog = false">Close</button>
<button @click="saveBudget">Save</button>
</div>
</div>
</div> </div>
</Modal>
</template> </template>

View File

@@ -9,9 +9,3 @@ h1 {
a { a {
text-decoration: underline; text-decoration: underline;
} }
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

View File

@@ -1,79 +1,25 @@
import { createApp } from "vue"; import { createApp } from 'vue'
import App from "./App.vue"; import App from './App.vue'
import "./index.css"; import './index.css'
import router from "./router"; import router from './router'
import { createPinia } from "pinia"; import { createPinia } from 'pinia'
import { useBudgetsStore } from "./stores/budget"; import { useBudgetsStore } from './stores/budget';
import { useAccountStore } from "./stores/budget-account"; import { useAccountStore } from './stores/budget-account'
import PiniaLogger from "./pinia-logger"; import PiniaLogger from './pinia-logger'
import { useSessionStore } from "./stores/session";
const app = createApp(App); const app = createApp(App)
app.use(router); app.use(router)
const pinia = createPinia(); const pinia = createPinia()
pinia.use( pinia.use(PiniaLogger())
PiniaLogger({ app.use(pinia)
expanded: false, app.mount('#app')
showDuration: true,
})
);
app.use(pinia);
app.mount("#app");
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to, from, next) => {
const budgetStore = useBudgetsStore(); const budgetStore = useBudgetsStore();
await budgetStore.SetCurrentBudget(<string>to.params.budgetid); await budgetStore.SetCurrentBudget((<string>to.params.budgetid));
const accountStore = useAccountStore(); const accountStore = useAccountStore();
await accountStore.SetCurrentAccount( await accountStore.SetCurrentAccount((<string>to.params.budgetid), (<string>to.params.accountid));
<string>to.params.budgetid,
<string>to.params.accountid
);
next(); 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;

View File

@@ -4,170 +4,40 @@ import Currency from "../components/Currency.vue";
import TransactionRow from "../components/TransactionRow.vue"; import TransactionRow from "../components/TransactionRow.vue";
import TransactionInputRow from "../components/TransactionInputRow.vue"; import TransactionInputRow from "../components/TransactionInputRow.vue";
import { useAccountStore } from "../stores/budget-account"; import { useAccountStore } from "../stores/budget-account";
import EditAccount from "../dialogs/EditAccount.vue";
import 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<{ const props = defineProps<{
budgetid: string budgetid: string
accountid: string accountid: string
}>() }>()
const modalInputRow = ref<typeof TransactionInputRow | null>(null); const accountStore = useAccountStore();
const CurrentAccount = computed(() => accountStore.CurrentAccount);
function submitModal() { const TransactionsList = computed(() => accountStore.TransactionsList);
modalInputRow.value!.Save();
}
const accounts = useAccountStore();
const transactions = useTransactionsStore();
const TargetReconcilingBalance = ref(0);
function setReconciled(event: Event) {
const target = event.target as HTMLInputElement;
transactions.SetReconciledForAllTransactions(target.checked);
}
function cancelReconcilation() {
transactions.SetReconciledForAllTransactions(false);
transactions.Reconciling = false;
}
function submitReconcilation() {
transactions.SubmitReconcilation(0);
transactions.Reconciling = false;
}
function createReconcilationTransaction() {
const diff = TargetReconcilingBalance.value - transactions.ReconcilingBalance;
transactions.SubmitReconcilation(diff);
transactions.Reconciling = false;
}
</script> </script>
<template> <template>
<div class="grid grid-cols-[1fr_auto]"> <h1>{{ CurrentAccount?.Name }}</h1>
<div> <p>
<h1 class="inline"> Current Balance:
{{ accounts.CurrentAccount?.Name }} <Currency :value="CurrentAccount?.Balance" />
</h1> </p>
<EditAccount />
</div>
<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 class="rounded-lg p-1 whitespace-nowrap flex-1">
Cleared:
<Currency :value="accounts.CurrentAccount?.ClearedBalance" />
</span>
<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" />
</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&nbsp;
<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> <table>
<tr class="font-bold"> <tr class="font-bold">
<td <td style="width: 90px;">Date</td>
class="hidden md:block" <td style="max-width: 150px;">Payee</td>
style="width: 90px;" <td style="max-width: 200px;">Category</td>
>
Date
</td>
<td style="max-width: 150px;">
Payee
</td>
<td style="max-width: 200px;">
Category
</td>
<td>Memo</td> <td>Memo</td>
<td class="text-right"> <td class="text-right">Amount</td>
Amount <td style="width: 20px;"></td>
</td> <td style="width: 20px;"></td>
<td style="width: 80px;">
<Checkbox
v-if="transactions.Reconciling"
@input="setReconciled"
/>
</td>
</tr> </tr>
<TransactionInputRow <TransactionInputRow :budgetid="budgetid" :accountid="accountid" />
class="hidden md:table-row"
:budgetid="budgetid"
:accountid="accountid"
/>
<TransactionRow <TransactionRow
v-for="(transaction, index) in transactions.TransactionsList" v-for="(transaction, index) in TransactionsList"
:key="transaction.ID" :transaction="transaction"
:transactionid="transaction.ID"
:index="index" :index="index"
/> />
</table> </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> </template>
<style> <style>

View File

@@ -1,14 +1,16 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed } from "vue"; import { computed } from "vue";
import Currency from "../components/Currency.vue"; import Currency from "../components/Currency.vue"
import { useBudgetsStore } from "../stores/budget"; import { useBudgetsStore } from "../stores/budget"
import { Account, useAccountStore } from "../stores/budget-account"; import { useAccountStore } from "../stores/budget-account"
import { useSettingsStore } from "../stores/settings"; import { useSettingsStore } from "../stores/settings"
import AccountWithReconciled from "../components/AccountWithReconciled.vue";
const settings = useSettingsStore(); const props = defineProps<{
const ExpandMenu = computed(() => settings.Menu.Expand); budgetid: string,
const ShowMenu = computed(() => settings.Menu.Show); accountid: string,
}>();
const ExpandMenu = computed(() => useSettingsStore().Menu.Expand);
const budgetStore = useBudgetsStore(); const budgetStore = useBudgetsStore();
const CurrentBudgetName = computed(() => budgetStore.CurrentBudgetName); const CurrentBudgetName = computed(() => budgetStore.CurrentBudgetName);
@@ -22,84 +24,48 @@ const OffBudgetAccountsBalance = computed(() => accountStore.OffBudgetAccountsBa
</script> </script>
<template> <template>
<div <div class="flex flex-col">
:class="[ExpandMenu ? 'md:w-72' : 'md:w-36', ShowMenu ? '' : 'hidden']" <span class="m-1 p-1 px-3 text-xl">
class="md:block flex-shrink-0 w-full bg-gray-500 border-r-4 border-black" <router-link to="/dashboard"></router-link>
> {{CurrentBudgetName}}
<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>
<span class="bg-gray-100 dark:bg-gray-700 p-2 px-3 flex flex-col"> <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> <router-link :to="'/budget/'+budgetid+'/budgeting'">Budget</router-link><br />
<br>
<!--<router-link :to="'/budget/'+CurrentBudgetID+'/reports'">Reports</router-link>--> <!--<router-link :to="'/budget/'+CurrentBudgetID+'/reports'">Reports</router-link>-->
<!--<router-link :to="'/budget/'+CurrentBudgetID+'/all-accounts'">All Accounts</router-link>--> <!--<router-link :to="'/budget/'+CurrentBudgetID+'/all-accounts'">All Accounts</router-link>-->
</span> </span>
<li class="bg-slate-200 dark:bg-slate-700 my-2 p-2 px-3"> <li class="bg-orange-200 rounded-lg m-1 p-1 px-3">
<div class="flex flex-row justify-between font-bold"> <div class="flex flex-row justify-between font-bold">
<span>On-Budget Accounts</span> <span>On-Budget Accounts</span>
<Currency <Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="OnBudgetAccountsBalance" />
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
:value="OnBudgetAccountsBalance"
/>
</div> </div>
<div <div v-for="account in OnBudgetAccounts" class="flex flex-row justify-between">
v-for="account in OnBudgetAccounts" <router-link :to="'/budget/'+budgetid+'/account/'+account.ID">{{account.Name}}</router-link>
:key="account.ID" <Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="account.Balance" />
class="flex flex-row justify-between"
>
<AccountWithReconciled :account="account" />
<Currency
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
:value="account.ClearedBalance"
/>
</div> </div>
</li> </li>
<li class="bg-slate-200 dark:bg-slate-700 my-2 p-2 px-3"> <li class="bg-red-200 rounded-lg m-1 p-1 px-3">
<div class="flex flex-row justify-between font-bold"> <div class="flex flex-row justify-between font-bold">
<span>Off-Budget Accounts</span> <span>Off-Budget Accounts</span>
<Currency <Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="OffBudgetAccountsBalance" />
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
:value="OffBudgetAccountsBalance"
/>
</div> </div>
<div <div v-for="account in OffBudgetAccounts" class="flex flex-row justify-between">
v-for="account in OffBudgetAccounts" <router-link :to="'/budget/'+budgetid+'/account/'+account.ID">{{account.Name}}</router-link>
:key="account.ID" <Currency :class="ExpandMenu?'md:inline':'md:hidden'" :value="account.Balance" />
class="flex flex-row justify-between"
>
<AccountWithReconciled :account="account" />
<Currency
:class="ExpandMenu ? 'md:inline' : 'md:hidden'"
:value="account.ClearedBalance"
/>
</div> </div>
</li> </li>
<!-- <li class="bg-red-200 rounded-lg m-1 p-1 px-3">
<li class="bg-slate-100 dark:bg-slate-800 my-2 p-2 px-3"> Closed Accounts
<div class="flex flex-row justify-between font-bold">
<span>Closed Accounts</span>
</div>
+ Add Account
</li> </li>
-->
<!--<li> <!--<li>
<router-link :to="'/budget/'+CurrentBudgetID+'/accounts'">Edit accounts</router-link> <router-link :to="'/budget/'+CurrentBudgetID+'/accounts'">Edit accounts</router-link>
</li>--> </li>-->
<li class="bg-red-100 dark:bg-slate-600 my-2 p-2 px-3"> <li class="bg-red-200 rounded-lg m-1 p-1 px-3">
<router-link :to="'/budget/' + CurrentBudgetID + '/settings'"> + Add Account
Budget-Settings </li>
</router-link> <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>
<!--<li><router-link to="/admin">Admin</router-link></li>--> <!--<li><router-link to="/admin">Admin</router-link></li>-->
</div> </div>
</div>
</template> </template>

View File

@@ -1,11 +1,9 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, defineProps, onMounted, ref, watchEffect } from "vue"; import { computed, defineProps, onMounted, watchEffect } from "vue";
import Currency from "../components/Currency.vue"; import Currency from "../components/Currency.vue";
import { useBudgetsStore } from "../stores/budget"; import { useBudgetsStore } from "../stores/budget";
import { Category, useAccountStore } from "../stores/budget-account"; import { useAccountStore } from "../stores/budget-account";
import { useSessionStore } from "../stores/session"; import { useSessionStore } from "../stores/session";
import Input from "../components/Input.vue";
import { POST } from "../api";
const props = defineProps<{ const props = defineProps<{
budgetid: string, budgetid: string,
@@ -16,19 +14,11 @@ const props = defineProps<{
const budgetsStore = useBudgetsStore(); const budgetsStore = useBudgetsStore();
const CurrentBudgetID = computed(() => budgetsStore.CurrentBudgetID); const CurrentBudgetID = computed(() => budgetsStore.CurrentBudgetID);
const accountStore = useAccountStore(); const categoriesForMonth = useAccountStore().CategoriesForMonth;
const categoriesForMonth = accountStore.CategoriesForMonthAndGroup; const Categories = computed(() => {
return [...categoriesForMonth(selected.value.Year, selected.value.Month)];
function GetCategories(group: string) {
return [...categoriesForMonth(selected.value.Year, selected.value.Month, group)];
};
const groupsForMonth = accountStore.CategoryGroupsForMonth;
const GroupsForMonth = computed(() => {
return [...groupsForMonth(selected.value.Year, selected.value.Month)];
}); });
const previous = computed(() => ({ const previous = computed(() => ({
Year: new Date(selected.value.Year, selected.value.Month - 1, 1).getFullYear(), Year: new Date(selected.value.Year, selected.value.Month - 1, 1).getFullYear(),
Month: new Date(selected.value.Year, selected.value.Month - 1, 1).getMonth(), Month: new Date(selected.value.Year, selected.value.Month - 1, 1).getMonth(),
@@ -54,120 +44,49 @@ watchEffect(() => {
onMounted(() => { onMounted(() => {
useSessionStore().setTitle("Budget for " + selected.value.Month + "/" + selected.value.Year); useSessionStore().setTitle("Budget for " + selected.value.Month + "/" + selected.value.Year);
}) })
const expandedGroups = ref<Map<string, boolean>>(new Map<string, boolean>())
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 {
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> </script>
<template> <template>
<h1>Budget for {{ selected.Month + 1 }}/{{ selected.Year }}</h1> <h1>Budget for {{ selected.Month + 1 }}/{{ selected.Year }}</h1>
<span>Available balance:
<Currency
:value="accountStore.GetIncomeAvailable(selected.Year, selected.Month)"
/></span>
<div> <div>
<router-link <router-link
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + previous.Year + '/' + previous.Month" :to="'/budget/' + CurrentBudgetID + '/budgeting/' + previous.Year + '/' + previous.Month"
> >Previous Month</router-link>-
&lt;&lt;
</router-link>&nbsp;
<router-link <router-link
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + current.Year + '/' + current.Month" :to="'/budget/' + CurrentBudgetID + '/budgeting/' + current.Year + '/' + current.Month"
> >Current Month</router-link>-
Current Month
</router-link>&nbsp;
<router-link <router-link
:to="'/budget/' + CurrentBudgetID + '/budgeting/' + next.Year + '/' + next.Month" :to="'/budget/' + CurrentBudgetID + '/budgeting/' + next.Year + '/' + next.Month"
> >Next Month</router-link>
&gt;&gt;
</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> </div>
<table class="container col-lg-12" id="content">
<tr>
<th>Group</th>
<th>Category</th>
<th></th>
<th></th>
<th>Leftover</th>
<th>Assigned</th>
<th>Activity</th>
<th>Available</th>
</tr>
<tr v-for="category in Categories">
<td>{{ category.Group }}</td>
<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>
</table>
</template> </template>

View File

@@ -1,6 +1,6 @@
<script lang="ts" setup> <script lang="ts" setup>
import NewBudget from '../dialogs/NewBudget.vue'; import NewBudget from '../dialogs/NewBudget.vue';
import RowCard from '../components/RowCard.vue'; import Card from '../components/Card.vue';
import { useSessionStore } from '../stores/session'; import { useSessionStore } from '../stores/session';
const props = defineProps<{ const props = defineProps<{
@@ -13,20 +13,13 @@ const BudgetsList = useSessionStore().BudgetsList;
<template> <template>
<h1>Budgets</h1> <h1>Budgets</h1>
<div class="grid md:grid-cols-2 gap-6"> <div class="grid md:grid-cols-2 gap-6">
<RowCard <Card v-for="budget in BudgetsList">
v-for="budget in BudgetsList" <router-link v-bind:to="'/budget/'+budget.ID+'/budgeting'" class="contents">
:key="budget.ID"
>
<router-link
:to="'/budget/'+budget.ID+'/budgeting'"
class="contents"
>
<!--<svg class="w-24"></svg>--> <!--<svg class="w-24"></svg>-->
<p class="w-24 text-center text-6xl" /> <p class="w-24 text-center text-6xl"></p>
<span class="text-lg">{{ budget.Name <span class="text-lg">{{budget.Name}}{{budget.ID == budgetid ? " *" : ""}}</span>
}}{{ budget.ID == budgetid ? " *" : "" }}</span>
</router-link> </router-link>
</RowCard> </Card>
<NewBudget /> <NewBudget />
</div> </div>
</template> </template>

13
web/src/pages/Index.vue Normal file
View File

@@ -0,0 +1,13 @@
<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>

View File

@@ -2,11 +2,9 @@
import { onMounted, ref } from "vue"; import { onMounted, ref } from "vue";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import { useSessionStore } from "../stores/session"; import { useSessionStore } from "../stores/session";
import Input from "../components/Input.vue";
const error = ref(""); const error = ref("");
const login = ref({ user: "", password: "" }); const login = ref({ user: "", password: "" });
const router = useRouter(); // has to be called in setup
onMounted(() => { onMounted(() => {
useSessionStore().setTitle("Login"); useSessionStore().setTitle("Login");
@@ -14,11 +12,10 @@ onMounted(() => {
function formSubmit(e: MouseEvent) { function formSubmit(e: MouseEvent) {
e.preventDefault(); e.preventDefault();
useSessionStore().login(login.value) useSessionStore().login(login)
.then(x => { .then(x => {
error.value = ""; error.value = "";
router.replace("/dashboard"); useRouter().replace("/dashboard");
return x;
}) })
.catch(x => error.value = "The entered credentials are invalid!"); .catch(x => error.value = "The entered credentials are invalid!");
@@ -29,31 +26,23 @@ function formSubmit(e: MouseEvent) {
<template> <template>
<div> <div>
<Input <input
v-model="login.user"
type="text" type="text"
v-model="login.user"
placeholder="Username" placeholder="Username"
class="border-2 border-black rounded-lg block px-2 my-2 w-48" class="border-2 border-black rounded-lg block px-2 my-2 w-48"
/> />
<Input <input
v-model="login.password"
type="password" type="password"
v-model="login.password"
placeholder="Password" placeholder="Password"
class="border-2 border-black rounded-lg block px-2 my-2 w-48" class="border-2 border-black rounded-lg block px-2 my-2 w-48"
/> />
</div> </div>
<div>{{ error }}</div> <div>{{ error }}</div>
<button <button type="submit" @click="formSubmit" class="bg-blue-300 rounded-lg p-2 w-48">Login</button>
type="submit"
class="bg-blue-300 rounded-lg p-2 w-48"
@click="formSubmit"
>
Login
</button>
<p> <p>
New user? New user?
<router-link to="/register"> <router-link to="/register">Register</router-link>instead!
Register
</router-link> instead!
</p> </p>
</template> </template>

View File

@@ -1,26 +1,16 @@
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, ref } from "vue"; import { ref } from 'vue';
import { useRouter } from "vue-router"; import { useSessionStore } from '../stores/session';
import { useSessionStore } from "../stores/session";
import Input from "../components/Input.vue";
const error = ref(""); const error = ref("");
const login = ref({ email: "", password: "", name: "" }); const login = ref({ email: "", password: "", name: "" });
const router = useRouter(); // has to be called in setup const showPassword = ref(false);
onMounted(() => { function formSubmit(e: FormDataEvent) {
useSessionStore().setTitle("Login");
});
function formSubmit(e: MouseEvent) {
e.preventDefault(); e.preventDefault();
useSessionStore().register(login.value) useSessionStore().register(login)
.then(x => { .then(() => error.value = "")
error.value = ""; .catch(() => error.value = "Something went wrong!");
router.replace("/dashboard");
return x;
})
.catch(x => error.value = "The entered credentials are invalid!");
// TODO display invalidCredentials // TODO display invalidCredentials
// TODO redirect to dashboard on success // TODO redirect to dashboard on success
@@ -28,38 +18,44 @@ function formSubmit(e: MouseEvent) {
</script> </script>
<template> <template>
<div> <v-container>
<Input <v-row>
v-model="login.name" <v-col cols="12">
type="text" <v-text-field v-model="login.email" type="text" label="E-Mail" />
placeholder="Name" </v-col>
class="border-2 border-black rounded-lg block px-2 my-2 w-48" <v-col cols="12">
/> <v-text-field v-model="login.name" type="text" label="Name" />
<Input </v-col>
v-model="login.email" <v-col cols="6">
type="text" <v-text-field
placeholder="Email"
class="border-2 border-black rounded-lg block px-2 my-2 w-48"
/>
<Input
v-model="login.password" v-model="login.password"
type="password" label="Password"
placeholder="Password" :append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
class="border-2 border-black rounded-lg block px-2 my-2 w-48" :type="showPassword ? 'text' : 'password'"
@click:append="showPassword = showPassword"
:error-message="error"
error-count="2"
error
/> />
</div> </v-col>
<div>{{ error }}</div> <v-col cols="6">
<button <v-text-field
type="submit" v-model="login.password"
class="bg-blue-300 rounded-lg p-2 w-48" label="Repeat password"
@click="formSubmit" :append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
> :type="showPassword ? 'text' : 'password'"
Register @click:append="showPassword = showPassword"
</button> :error-message="error"
error-count="2"
error
/>
</v-col>
</v-row>
<div class="form-group">{{ error }}</div>
<v-btn type="submit" @click="formSubmit">Register</v-btn>
<p> <p>
Existing user? Existing user?
<router-link to="/login"> <router-link to="/login">Login</router-link>instead!
Login
</router-link> instead!
</p> </p>
</v-container>
</template> </template>

View File

@@ -4,10 +4,6 @@ import { useRouter } from "vue-router";
import { DELETE, POST } from "../api"; import { DELETE, POST } from "../api";
import { useBudgetsStore } from "../stores/budget"; import { useBudgetsStore } from "../stores/budget";
import { useSessionStore } from "../stores/session"; import { useSessionStore } from "../stores/session";
import 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 transactionsFile = ref<File | undefined>(undefined);
const assignmentsFile = ref<File | undefined>(undefined); const assignmentsFile = ref<File | undefined>(undefined);
@@ -17,10 +13,6 @@ onMounted(() => {
useSessionStore().setTitle("Settings"); useSessionStore().setTitle("Settings");
}); });
const budgetStore = useBudgetsStore();
const CurrentBudgetID = computed(() => budgetStore.CurrentBudgetID);
const CurrentBudgetName = computed(() => budgetStore.CurrentBudgetName);
function gotAssignments(e: Event) { function gotAssignments(e: Event) {
const input = (<HTMLInputElement>e.target); const input = (<HTMLInputElement>e.target);
if (input.files != null) if (input.files != null)
@@ -32,17 +24,19 @@ function gotTransactions(e: Event) {
transactionsFile.value = input.files[0]; transactionsFile.value = input.files[0];
}; };
function deleteBudget() { function deleteBudget() {
if (CurrentBudgetID.value == null) const currentBudgetID = useBudgetsStore().CurrentBudgetID;
if (currentBudgetID == null)
return; return;
DELETE("/budget/" + CurrentBudgetID.value); DELETE("/budget/" + currentBudgetID);
const budgetStore = useSessionStore(); const budgetStore = useSessionStore();
budgetStore.Budgets.delete(CurrentBudgetID.value); budgetStore.Budgets.delete(currentBudgetID);
useRouter().push("/") useRouter().push("/")
}; };
function clearBudget() { function clearBudget() {
POST("/budget/" + CurrentBudgetID.value + "/settings/clear", null) const currentBudgetID = useBudgetsStore().CurrentBudgetID;
POST("/budget/" + currentBudgetID + "/settings/clear", null)
}; };
function cleanNegative() { function cleanNegative() {
// <a href="/budget/{{.Budget.ID}}/settings/clean-negative">Fix all historic negative category-balances</a> // <a href="/budget/{{.Budget.ID}}/settings/clean-negative">Fix all historic negative category-balances</a>
@@ -57,120 +51,75 @@ function ynabImport() {
const budgetStore = useBudgetsStore(); const budgetStore = useBudgetsStore();
budgetStore.ImportYNAB(formData); budgetStore.ImportYNAB(formData);
}; };
function ynabExport() {
const timeStamp = new Date().toISOString();
POST("/budget/"+CurrentBudgetID.value+"/export/ynab/assignments", "")
.then(x => x.text())
.then(x => {
var blob = new Blob([x], {type: "text/plain;charset=utf-8"});
saveAs(blob, timeStamp + " " + CurrentBudgetName.value + " - Budget.tsv");
})
POST("/budget/"+CurrentBudgetID.value+"/export/ynab/transactions", "")
.then(x => x.text())
.then(x => {
var blob = new Blob([x], {type: "text/plain;charset=utf-8"});
saveAs(blob, timeStamp + " " + CurrentBudgetName.value + " - Transactions.tsv");
})
}
</script> </script>
<template> <template>
<div> <v-container>
<h1>Danger Zone</h1> <h1>Danger Zone</h1>
<div class="grid md:grid-cols-2 gap-6"> <v-row>
<RowCard class="flex-col p-3"> <v-col cols="12" md="6" xl="3">
<h2 class="text-lg font-bold"> <v-card>
Clear Budget <v-card-header>
</h2> <v-card-header-text>
<p> <v-card-title>Clear Budget</v-card-title>
This removes transactions and assignments to start from <v-card-subtitle>This removes transactions and assignments to start from scratch. Accounts and categories are kept. Not undoable!</v-card-subtitle>
scratch. Accounts and categories are kept. Not undoable! </v-card-header-text>
</p> </v-card-header>
<v-card-actions class="justify-center">
<v-btn @click="clearBudget">Clear budget</v-btn>
</v-card-actions>
</v-card>
</v-col>
<v-col cols="12" md="6" xl="3">
<v-card>
<v-card-header>
<v-card-header-text>
<v-card-title>Delete Budget</v-card-title>
<v-card-subtitle>This deletes the whole bugdet including all transactions, assignments, accounts and categories. Not undoable!</v-card-subtitle>
</v-card-header-text>
</v-card-header>
<v-card-actions class="justify-center">
<v-btn @click="deleteBudget">Delete budget</v-btn>
</v-card-actions>
</v-card>
</v-col>
<v-col cols="12" md="6" xl="3">
<v-card>
<v-card-header>
<v-card-header-text>
<v-card-title>Fix all historic negative category-balances</v-card-title>
<v-card-subtitle>This restores YNABs functionality, that would substract any overspent categories' balances from next months inflows.</v-card-subtitle>
</v-card-header-text>
</v-card-header>
<v-card-actions class="justify-center">
<v-btn @click="cleanNegative">Fix negative</v-btn>
</v-card-actions>
</v-card>
</v-col>
<v-col cols="12" xl="6">
<v-card>
<v-card-header>
<v-card-header-text>
<v-card-title>Import YNAB Budget</v-card-title>
</v-card-header-text>
</v-card-header>
<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>
<label for="transactions_file"> <label for="transactions_file">
Transaktionen: Transaktionen:
<input <input type="file" @change="gotTransactions" accept="text/*" />
type="file"
accept="text/*"
@change="gotTransactions"
>
</label> </label>
<br> <br />
<label for="assignments_file"> <label for="assignments_file">
Budget: Budget:
<input <input type="file" @change="gotAssignments" accept="text/*" />
type="file"
accept="text/*"
@change="gotAssignments"
>
</label> </label>
</div>
<Button <v-card-actions class="justify-center">
class="bg-blue-500 py-2" <v-btn :disabled="filesIncomplete" @click="ynabImport">Importieren</v-btn>
:disabled="filesIncomplete" </v-card-actions>
@click="ynabImport" </v-card>
> </v-col>
Importieren </v-row>
</Button> <v-card></v-card>
</RowCard> </v-container>
<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> </template>

Some files were not shown because too many files have changed in this diff Show More