feat(account): #49 implement save logic
Some checks failed
Build Docker Image / Build-Docker-Image (push) Failing after 4m44s

This commit is contained in:
2025-05-07 18:49:56 +02:00
parent c8daf6a04d
commit 0dbd63713e
12 changed files with 223 additions and 96 deletions

View File

@@ -7,6 +7,9 @@ import (
"spend-sparrow/utils" "spend-sparrow/utils"
"net/http" "net/http"
"github.com/a-h/templ"
"github.com/google/uuid"
) )
type Account interface { type Account interface {
@@ -28,8 +31,9 @@ func NewAccount(service service.Account, auth service.Auth, render *Render) Acco
} }
func (handler AccountImpl) Handle(router *http.ServeMux) { func (handler AccountImpl) Handle(router *http.ServeMux) {
router.Handle("/account", handler.handleAccountPage()) router.Handle("GET /account", handler.handleAccountPage())
// router.Handle("POST /account", handler.handleAddAccount()) router.Handle("GET /account/{id}", handler.handleAccountItemComp())
router.Handle("POST /account/{id}", handler.handleUpdateAccount())
// router.Handle("GET /account", handler.handleGetAccount()) // router.Handle("GET /account", handler.handleGetAccount())
// router.Handle("DELETE /account/{id}", handler.handleDeleteAccount()) // router.Handle("DELETE /account/{id}", handler.handleDeleteAccount())
} }
@@ -42,38 +46,58 @@ func (handler AccountImpl) handleAccountPage() http.HandlerFunc {
return return
} }
comp := account.Account() accounts, err := handler.service.GetAll(user)
if err != nil {
utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
return
}
comp := account.Account(accounts)
handler.render.RenderLayout(r, w, comp, user) handler.render.RenderLayout(r, w, comp, user)
} }
} }
// func (handler AccountImpl) handleAddAccount() http.HandlerFunc { func (handler AccountImpl) handleAccountItemComp() http.HandlerFunc {
// return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
// user := middleware.GetUser(r) user := middleware.GetUser(r)
// if user == nil { if user == nil {
// utils.DoRedirect(w, r, "/auth/signin") utils.DoRedirect(w, r, "/auth/signin")
// return return
// } }
// id, err := uuid.Parse(r.PathValue("id"))
// var dateStr = r.FormValue("date") if err != nil {
// var typeStr = r.FormValue("type") utils.TriggerToastWithStatus(w, r, "error", "Could not parse Id", http.StatusBadRequest)
// var setsStr = r.FormValue("sets") return
// var repsStr = r.FormValue("reps") }
//
// wo := service.NewAccountDto("", dateStr, typeStr, setsStr, repsStr) accounts, err := handler.service.Get(user, id)
// wo, err := handler.service.AddAccount(user, wo) if err != nil {
// if err != nil { utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
// utils.TriggerToast(w, r, "error", "Invalid input values", http.StatusBadRequest) return
// http.Error(w, "Invalid input values", http.StatusBadRequest) }
// return
// } var comp templ.Component
// wor := account.Account{Id: wo.RowId, Date: wo.Date, Type: wo.Type, Sets: wo.Sets, Reps: wo.Reps} if r.URL.Query().Get("edit") == "true" {
// comp = account.EditAccount(accounts)
// comp := account.AccountItemComp(wor, true) } else {
// handler.render.Render(r, w, comp) comp = account.AccountItem(accounts)
// } }
// } handler.render.Render(r, w, comp)
// }
}
func (handler AccountImpl) handleUpdateAccount() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user := middleware.GetUser(r)
if user == nil {
utils.DoRedirect(w, r, "/auth/signin")
return
}
utils.TriggerToastWithStatus(w, r, "error", "Account not yet updated", http.StatusBadRequest)
}
}
// func (handler AccountImpl) handleGetAccount() http.HandlerFunc { // func (handler AccountImpl) handleGetAccount() http.HandlerFunc {
// return func(w http.ResponseWriter, r *http.Request) { // return func(w http.ResponseWriter, r *http.Request) {
// user := middleware.GetUser(r) // user := middleware.GetUser(r)

View File

@@ -96,9 +96,9 @@ func (handler AuthImpl) handleSignIn() http.HandlerFunc {
if err != nil { if err != nil {
if err == service.ErrInvalidCredentials { if err == service.ErrInvalidCredentials {
utils.TriggerToast(w, r, "error", "Invalid email or password", http.StatusUnauthorized) utils.TriggerToastWithStatus(w, r, "error", "Invalid email or password", http.StatusUnauthorized)
} else { } else {
utils.TriggerToast(w, r, "error", "An error occurred", http.StatusInternalServerError) utils.TriggerToastWithStatus(w, r, "error", "An error occurred", http.StatusInternalServerError)
} }
return return
} }
@@ -204,19 +204,19 @@ func (handler AuthImpl) handleSignUp() http.HandlerFunc {
if err != nil { if err != nil {
if errors.Is(err, types.ErrInternal) { if errors.Is(err, types.ErrInternal) {
utils.TriggerToast(w, r, "error", "An error occurred", http.StatusInternalServerError) utils.TriggerToastWithStatus(w, r, "error", "An error occurred", http.StatusInternalServerError)
return return
} else if errors.Is(err, service.ErrInvalidEmail) { } else if errors.Is(err, service.ErrInvalidEmail) {
utils.TriggerToast(w, r, "error", "The email provided is invalid", http.StatusBadRequest) utils.TriggerToastWithStatus(w, r, "error", "The email provided is invalid", http.StatusBadRequest)
return return
} else if errors.Is(err, service.ErrInvalidPassword) { } else if errors.Is(err, service.ErrInvalidPassword) {
utils.TriggerToast(w, r, "error", service.ErrInvalidPassword.Error(), http.StatusBadRequest) utils.TriggerToastWithStatus(w, r, "error", service.ErrInvalidPassword.Error(), http.StatusBadRequest)
return return
} }
// If err is "service.ErrAccountExists", then just continue // If err is "service.ErrAccountExists", then just continue
} }
utils.TriggerToast(w, r, "success", "An activation link has been send to your email", http.StatusOK) utils.TriggerToastWithStatus(w, r, "success", "An activation link has been send to your email", http.StatusOK)
} }
} }
@@ -273,9 +273,9 @@ func (handler AuthImpl) handleDeleteAccountComp() http.HandlerFunc {
err := handler.service.DeleteAccount(user, password) err := handler.service.DeleteAccount(user, password)
if err != nil { if err != nil {
if err == service.ErrInvalidCredentials { if err == service.ErrInvalidCredentials {
utils.TriggerToast(w, r, "error", "Password not correct", http.StatusBadRequest) utils.TriggerToastWithStatus(w, r, "error", "Password not correct", http.StatusBadRequest)
} else { } else {
utils.TriggerToast(w, r, "error", "Internal Server Error", http.StatusInternalServerError) utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
} }
return return
} }
@@ -307,7 +307,7 @@ func (handler AuthImpl) handleChangePasswordComp() http.HandlerFunc {
session := middleware.GetSession(r) session := middleware.GetSession(r)
user := middleware.GetUser(r) user := middleware.GetUser(r)
if session == nil || user == nil { if session == nil || user == nil {
utils.TriggerToast(w, r, "error", "Unathorized", http.StatusUnauthorized) utils.TriggerToastWithStatus(w, r, "error", "Unathorized", http.StatusUnauthorized)
return return
} }
@@ -316,11 +316,11 @@ func (handler AuthImpl) handleChangePasswordComp() http.HandlerFunc {
err := handler.service.ChangePassword(user, session.Id, currPass, newPass) err := handler.service.ChangePassword(user, session.Id, currPass, newPass)
if err != nil { if err != nil {
utils.TriggerToast(w, r, "error", "Password not correct", http.StatusBadRequest) utils.TriggerToastWithStatus(w, r, "error", "Password not correct", http.StatusBadRequest)
return return
} }
utils.TriggerToast(w, r, "success", "Password changed", http.StatusOK) utils.TriggerToastWithStatus(w, r, "success", "Password changed", http.StatusOK)
} }
} }
@@ -343,7 +343,7 @@ func (handler AuthImpl) handleForgotPasswordComp() http.HandlerFunc {
email := r.FormValue("email") email := r.FormValue("email")
if email == "" { if email == "" {
utils.TriggerToast(w, r, "error", "Please enter an email", http.StatusBadRequest) utils.TriggerToastWithStatus(w, r, "error", "Please enter an email", http.StatusBadRequest)
return return
} }
@@ -353,9 +353,9 @@ func (handler AuthImpl) handleForgotPasswordComp() http.HandlerFunc {
}) })
if err != nil { if err != nil {
utils.TriggerToast(w, r, "error", "Internal Server Error", http.StatusInternalServerError) utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
} else { } else {
utils.TriggerToast(w, r, "info", "If the address exists, an email has been sent.", http.StatusOK) utils.TriggerToastWithStatus(w, r, "info", "If the address exists, an email has been sent.", http.StatusOK)
} }
} }
} }
@@ -365,7 +365,7 @@ func (handler AuthImpl) handleForgotPasswordResponseComp() http.HandlerFunc {
pageUrl, err := url.Parse(r.Header.Get("HX-Current-URL")) pageUrl, err := url.Parse(r.Header.Get("HX-Current-URL"))
if err != nil { if err != nil {
log.Error("Could not get current URL: %v", err) log.Error("Could not get current URL: %v", err)
utils.TriggerToast(w, r, "error", "Internal Server Error", http.StatusInternalServerError) utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
return return
} }
@@ -374,9 +374,9 @@ func (handler AuthImpl) handleForgotPasswordResponseComp() http.HandlerFunc {
err = handler.service.ForgotPassword(token, newPass) err = handler.service.ForgotPassword(token, newPass)
if err != nil { if err != nil {
utils.TriggerToast(w, r, "error", err.Error(), http.StatusBadRequest) utils.TriggerToastWithStatus(w, r, "error", err.Error(), http.StatusBadRequest)
} else { } else {
utils.TriggerToast(w, r, "success", "Password changed", http.StatusOK) utils.TriggerToastWithStatus(w, r, "success", "Password changed", http.StatusOK)
} }
} }
} }

View File

@@ -59,7 +59,7 @@ func CrossSiteRequestForgery(auth service.Auth) func(http.Handler) http.Handler
if session == nil || csrfToken == "" || !auth.IsCsrfTokenValid(csrfToken, session.Id) { if session == nil || csrfToken == "" || !auth.IsCsrfTokenValid(csrfToken, session.Id) {
log.Info("CSRF-Token not correct") log.Info("CSRF-Token not correct")
if r.Header.Get("HX-Request") == "true" { if r.Header.Get("HX-Request") == "true" {
utils.TriggerToast(w, r, "error", "CSRF-Token not correct", http.StatusBadRequest) utils.TriggerToastWithStatus(w, r, "error", "CSRF-Token not correct", http.StatusBadRequest)
} else { } else {
http.Error(w, "CSRF-Token not correct", http.StatusBadRequest) http.Error(w, "CSRF-Token not correct", http.StatusBadRequest)
} }

View File

@@ -0,0 +1,32 @@
package middleware
import (
"compress/gzip"
"io"
"net/http"
"strings"
)
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func Gzip(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w}
next.ServeHTTP(gzr, r)
})
}

View File

@@ -2,10 +2,11 @@ package middleware
import "net/http" import "net/http"
// Chain list of handlers together
func Wrapper(next http.Handler, handlers ...func(http.Handler) http.Handler) http.Handler { func Wrapper(next http.Handler, handlers ...func(http.Handler) http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lastHandler := next lastHandler := next
for i := len(handlers) - 1; i >= 0; i-- { for i := 0; i < len(handlers); i++ {
lastHandler = handlers[i](lastHandler) lastHandler = handlers[i](lastHandler)
} }
lastHandler.ServeHTTP(w, r) lastHandler.ServeHTTP(w, r)

View File

@@ -130,10 +130,12 @@ func createHandler(d *sqlx.DB, serverSettings *types.Settings) http.Handler {
return middleware.Wrapper( return middleware.Wrapper(
router, router,
middleware.Log,
middleware.CacheControl,
middleware.SecurityHeaders(serverSettings), middleware.SecurityHeaders(serverSettings),
middleware.Authenticate(authService), middleware.CacheControl,
middleware.CrossSiteRequestForgery(authService), middleware.CrossSiteRequestForgery(authService),
middleware.Authenticate(authService),
middleware.Log,
// Gzip last, as it compresses the body
middleware.Gzip,
) )
} }

View File

@@ -18,7 +18,8 @@ var (
type Account interface { type Account interface {
Add(user *types.User, name string) (*types.Account, error) Add(user *types.User, name string) (*types.Account, error)
Update(user *types.User, id uuid.UUID, name string) (*types.Account, error) Update(user *types.User, id uuid.UUID, name string) (*types.Account, error)
Get(user *types.User) ([]*types.Account, error) Get(user *types.User, id uuid.UUID) (*types.Account, error)
GetAll(user *types.User) ([]*types.Account, error)
Delete(user *types.User, id uuid.UUID) error Delete(user *types.User, id uuid.UUID) error
} }
@@ -111,13 +112,27 @@ func (service AccountImpl) Update(user *types.User, id uuid.UUID, name string) (
return account, nil return account, nil
} }
func (service AccountImpl) Get(user *types.User) ([]*types.Account, error) { func (service AccountImpl) Get(user *types.User, id uuid.UUID) (*types.Account, error) {
if user == nil { if user == nil {
return nil, types.ErrInternal return nil, types.ErrInternal
} }
accounts, err := service.db.GetAll(user.GroupId) account, err := service.db.Get(user.Id, id)
if err != nil {
return nil, types.ErrInternal
}
return account, nil
}
func (service AccountImpl) GetAll(user *types.User) ([]*types.Account, error) {
if user == nil {
return nil, types.ErrInternal
}
accounts, err := service.db.GetAll(user.Id)
if err != nil { if err != nil {
return nil, types.ErrInternal return nil, types.ErrInternal
} }

View File

@@ -1,5 +1,4 @@
function getClass(type) { function getClass(type) {
switch (type) { switch (type) {
case "error": case "error":

View File

@@ -2,32 +2,63 @@ package account
import "fmt" import "fmt"
import "spend-sparrow/template/svg" import "spend-sparrow/template/svg"
import "spend-sparrow/types"
templ Account() { templ Account(accounts []*types.Account) {
<div class="max-w-6xl mt-10 mx-auto"> <div class="max-w-6xl mt-10 mx-auto">
<button class="ml-auto button button-primary px-2 flex-1 flex items-center gap-2 justify-center"> <button class="ml-auto button button-primary px-2 flex-1 flex items-center gap-2 justify-center">
@svg.Plus() @svg.Plus()
<p class="">New Account</p> <p class="">New Account</p>
</button> </button>
<div class="my-6 flex flex-col items-center"> <div class="my-6 flex flex-col items-center">
@accountItem("Sparkasse", 51268) for _, account := range accounts {
@accountItem("Bargeld", 11822) @AccountItem(account)
@accountItem("Bargeld Milch", 8200) }
</div> </div>
</div> </div>
} }
func displayBalance(balance int) string { templ EditAccount(account *types.Account) {
<div id="account" class="border-1 border-gray-300 w-full my-4 p-4 bg-gray-50 rounded-lg">
euros := float64(balance) / 100 <form
return fmt.Sprintf("%.2f €", euros) hx-post={ "/account/" + account.Id.String() }
hx-target="closest #account"
hx-swap="outerHTML"
class="text-xl flex justify-end gap-4 items-center"
>
<input type="text" value={ account.Name } class="mr-auto input"/>
<button type="submit" class="button button-neglect px-1 flex items-center gap-2">
@svg.Save()
<span>
Save
</span>
</button>
<button
hx-get={ "/account/" + account.Id.String() }
hx-target="closest #account"
hx-swap="outerHTML"
class="button button-neglect px-1 flex items-center gap-2"
>
@svg.Cancel()
<span>
Cancel
</span>
</button>
</form>
</div>
} }
templ accountItem(name string, balance int) { templ AccountItem(account *types.Account) {
<div class="border-1 border-gray-300 w-full my-4 p-4 bg-gray-50 rounded-lg text-xl flex justify-end gap-4"> <div id="account" class="border-1 border-gray-300 w-full my-4 p-4 bg-gray-50 rounded-lg">
<p class="mr-auto">{ name }</p> <div class="text-xl flex justify-end gap-4">
<p class="mr-20 text-green-700">{ displayBalance(balance) }</p> <p class="mr-auto">{ account.Name }</p>
<button class="button button-neglect px-1 flex items-center gap-2"> <p class="mr-20 text-green-700">{ displayBalance(account.CurrentBalance) }</p>
<button
hx-get={ "/account/" + account.Id.String() + "?edit=true" }
hx-target="closest #account"
hx-swap="outerHTML"
class="button button-neglect px-1 flex items-center gap-2"
>
@svg.Edit() @svg.Edit()
<span> <span>
Edit Edit
@@ -39,11 +70,18 @@ templ accountItem(name string, balance int) {
Delete Delete
</span> </span>
</button> </button>
<button title="View Account Transactions" class="button button-neglect px-1 flex items-center gap-2"> <!-- <button title="View Account Transactions" class="button button-neglect px-1 flex items-center gap-2"> -->
@svg.Eye() <!-- @svg.Eye() -->
<span> <!-- <span> -->
View <!-- View -->
</span> <!-- </span> -->
</button> <!-- </button> -->
</div>
</div> </div>
} }
func displayBalance(balance int64) string {
euros := float64(balance) / 100
return fmt.Sprintf("%.2f €", euros)
}

View File

@@ -23,3 +23,15 @@ templ Plus() {
<path fill="currentColor" d="M299 213H171v128h-43V213H0v-42h128V43h43v128h128v42z"></path> <path fill="currentColor" d="M299 213H171v128h-43V213H0v-42h128V43h43v128h128v42z"></path>
</svg> </svg>
} }
templ Save() {
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="h-4 w-4 text-gray-500">
<path fill="currentColor" d="M21 7v12q0 .825-.588 1.413T19 21H5q-.825 0-1.413-.588T3 19V5q0-.825.588-1.413T5 3h12l4 4Zm-9 11q1.25 0 2.125-.875T15 15q0-1.25-.875-2.125T12 12q-1.25 0-2.125.875T9 15q0 1.25.875 2.125T12 18Zm-6-8h9V6H6v4Z"></path>
</svg>
}
templ Cancel() {
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" class="h-4 w-4 text-gray-500">
<path fill="currentColor" d="m654 501l346 346l-154 154l-346-346l-346 346L0 847l346-346L0 155L154 1l346 346L846 1l154 154z"></path>
</svg>
}

View File

@@ -38,21 +38,21 @@ type Transaction struct {
// The Account holds money // The Account holds money
type Account struct { type Account struct {
Id uuid.UUID Id uuid.UUID
GroupId uuid.UUID GroupId uuid.UUID `db:"group_id"`
// Custom Name of the account, e.g. "Bank", "Cash", "Credit Card" // Custom Name of the account, e.g. "Bank", "Cash", "Credit Card"
Name string Name string
CurrentBalance int64 CurrentBalance int64 `db:"current_balance"`
LastTransaction *time.Time LastTransaction *time.Time `db:"last_transaction"`
// The current precalculated value of: // The current precalculated value of:
// Account.Balance - [PiggyBank.Balance...] // Account.Balance - [PiggyBank.Balance...]
OinkBalance int64 OinkBalance int64 `db:"oink_balance"`
CreatedAt time.Time CreatedAt time.Time `db:"created_at"`
CreatedBy uuid.UUID CreatedBy uuid.UUID `db:"created_by"`
UpdatedAt *time.Time UpdatedAt *time.Time `db:"updated_at"`
UpdatedBy *uuid.UUID UpdatedBy *uuid.UUID `db:"updated_by"`
} }
// The PiggyBank is a fictional account. The money it "holds" is actually in the Account // The PiggyBank is a fictional account. The money it "holds" is actually in the Account

View File

@@ -8,15 +8,19 @@ import (
"spend-sparrow/log" "spend-sparrow/log"
) )
func TriggerToast(w http.ResponseWriter, r *http.Request, class string, message string, statusCode int) { func TriggerToast(w http.ResponseWriter, r *http.Request, class string, message string) {
if isHtmx(r) { if isHtmx(r) {
w.Header().Set("HX-Trigger", fmt.Sprintf(`{"toast": "%v|%v"}`, class, message)) w.Header().Set("HX-Trigger", fmt.Sprintf(`{"toast": "%v|%v"}`, class, message))
w.WriteHeader(statusCode)
} else { } else {
log.Error("Trying to trigger toast in non-HTMX request") log.Error("Trying to trigger toast in non-HTMX request")
} }
} }
func TriggerToastWithStatus(w http.ResponseWriter, r *http.Request, class string, message string, statusCode int) {
TriggerToast(w, r, class, message)
w.WriteHeader(statusCode)
}
func DoRedirect(w http.ResponseWriter, r *http.Request, url string) { func DoRedirect(w http.ResponseWriter, r *http.Request, url string) {
if isHtmx(r) { if isHtmx(r) {
w.Header().Add("HX-Redirect", url) w.Header().Add("HX-Redirect", url)