fix linter/test errors

This commit is contained in:
Hayden 2024-04-28 12:21:43 -05:00
parent 0c968de1fb
commit d7fd68765a
No known key found for this signature in database
GPG key ID: 17CF79474E257545
40 changed files with 207 additions and 212 deletions

View file

@ -84,6 +84,12 @@ tasks:
cmds: cmds:
- go mod tidy - go mod tidy
go:fmt:
desc: Runs go fmt on the backend
dir: backend
cmds:
- gofumpt -w .
go:lint: go:lint:
desc: Runs golangci-lint desc: Runs golangci-lint
dir: backend dir: backend

View file

@ -40,20 +40,18 @@ func (a *app) SetupDemo() {
_, err = a.services.User.RegisterUser(ctx, registration) _, err = a.services.User.RegisterUser(ctx, registration)
if err != nil { if err != nil {
log.Err(err).Msg("Failed to register demo user") log.Err(err).Msg("Failed to register demo user")
log.Fatal().Msg("Failed to setup demo") log.Fatal().Msg("Failed to setup demo") // nolint
} }
token, err := a.services.User.Login(ctx, registration.Email, registration.Password, false) token, err := a.services.User.Login(ctx, registration.Email, registration.Password, false)
if err != nil { if err != nil {
log.Err(err).Msg("Failed to login demo user") log.Err(err).Msg("Failed to login demo user")
log.Fatal().Msg("Failed to setup demo") log.Fatal().Msg("Failed to setup demo")
return
} }
self, err := a.services.User.GetSelf(ctx, token.Raw) self, err := a.services.User.GetSelf(ctx, token.Raw)
if err != nil { if err != nil {
log.Err(err).Msg("Failed to get self") log.Err(err).Msg("Failed to get self")
log.Fatal().Msg("Failed to setup demo") log.Fatal().Msg("Failed to setup demo")
return
} }
_, err = a.services.Items.CsvImport(ctx, self.GroupID, strings.NewReader(csvText)) _, err = a.services.Items.CsvImport(ctx, self.GroupID, strings.NewReader(csvText))

View file

@ -153,7 +153,7 @@ func (ctrl *V1Controller) HandleCacheWS() errchain.HandlerFunc {
m.HandleConnect(func(s *melody.Session) { m.HandleConnect(func(s *melody.Session) {
auth := services.NewContext(s.Request.Context()) auth := services.NewContext(s.Request.Context())
s.Set("gid", auth.GID) s.Set("gid", auth.GroupID)
}) })
factory := func(e string) func(data any) { factory := func(e string) func(data any) {

View file

@ -20,7 +20,7 @@ func actionHandlerFactory(ref string, fn func(context.Context, uuid.UUID) (int,
return func(w http.ResponseWriter, r *http.Request) error { return func(w http.ResponseWriter, r *http.Request) error {
ctx := services.NewContext(r.Context()) ctx := services.NewContext(r.Context())
totalCompleted, err := fn(ctx, ctx.GID) totalCompleted, err := fn(ctx, ctx.GroupID)
if err != nil { if err != nil {
log.Err(err).Str("action_ref", ref).Msg("failed to run action") log.Err(err).Str("action_ref", ref).Msg("failed to run action")
return validate.NewRequestError(err, http.StatusInternalServerError) return validate.NewRequestError(err, http.StatusInternalServerError)

View file

@ -52,7 +52,7 @@ func (ctrl *V1Controller) HandleAssetGet() errchain.HandlerFunc {
} }
} }
items, err := ctrl.repo.Items.QueryByAssetID(r.Context(), ctx.GID, repo.AssetID(assetID), int(page), int(pageSize)) items, err := ctrl.repo.Items.QueryByAssetID(r.Context(), ctx.GroupID, repo.AssetID(assetID), int(page), int(pageSize))
if err != nil { if err != nil {
log.Err(err).Msg("failed to get item") log.Err(err).Msg("failed to get item")
return validate.NewRequestError(err, http.StatusInternalServerError) return validate.NewRequestError(err, http.StatusInternalServerError)

View file

@ -35,7 +35,7 @@ type (
func (ctrl *V1Controller) HandleGroupGet() errchain.HandlerFunc { func (ctrl *V1Controller) HandleGroupGet() errchain.HandlerFunc {
fn := func(r *http.Request) (repo.Group, error) { fn := func(r *http.Request) (repo.Group, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Groups.GroupByID(auth, auth.GID) return ctrl.repo.Groups.GroupByID(auth, auth.GroupID)
} }
return adapters.Command(fn, http.StatusOK) return adapters.Command(fn, http.StatusOK)

View file

@ -79,7 +79,7 @@ func (ctrl *V1Controller) HandleItemsGetAll() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error { return func(w http.ResponseWriter, r *http.Request) error {
ctx := services.NewContext(r.Context()) ctx := services.NewContext(r.Context())
items, err := ctrl.repo.Items.QueryByGroup(ctx, ctx.GID, extractQuery(r)) items, err := ctrl.repo.Items.QueryByGroup(ctx, ctx.GroupID, extractQuery(r))
if err != nil { if err != nil {
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return server.JSON(w, http.StatusOK, repo.PaginationResult[repo.ItemSummary]{ return server.JSON(w, http.StatusOK, repo.PaginationResult[repo.ItemSummary]{
@ -105,12 +105,12 @@ func (ctrl *V1Controller) HandleItemsGetAll() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleItemFullPath() errchain.HandlerFunc { func (ctrl *V1Controller) HandleItemFullPath() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) ([]repo.ItemPath, error) { fn := func(r *http.Request, ID uuid.UUID) ([]repo.ItemPath, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
item, err := ctrl.repo.Items.GetOneByGroup(auth, auth.GID, ID) item, err := ctrl.repo.Items.GetOneByGroup(auth, auth.GroupID, ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
paths, err := ctrl.repo.Locations.PathForLoc(auth, auth.GID, item.Location.ID) paths, err := ctrl.repo.Locations.PathForLoc(auth, auth.GroupID, item.Location.ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -165,7 +165,7 @@ func (ctrl *V1Controller) HandleItemGet() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (repo.ItemOut, error) { fn := func(r *http.Request, ID uuid.UUID) (repo.ItemOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Items.GetOneByGroup(auth, auth.GID, ID) return ctrl.repo.Items.GetOneByGroup(auth, auth.GroupID, ID)
} }
return adapters.CommandID("id", fn, http.StatusOK) return adapters.CommandID("id", fn, http.StatusOK)
@ -183,7 +183,7 @@ func (ctrl *V1Controller) HandleItemGet() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleItemDelete() errchain.HandlerFunc { func (ctrl *V1Controller) HandleItemDelete() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (any, error) { fn := func(r *http.Request, ID uuid.UUID) (any, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
err := ctrl.repo.Items.DeleteByGroup(auth, auth.GID, ID) err := ctrl.repo.Items.DeleteByGroup(auth, auth.GroupID, ID)
return nil, err return nil, err
} }
@ -205,7 +205,7 @@ func (ctrl *V1Controller) HandleItemUpdate() errchain.HandlerFunc {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
body.ID = ID body.ID = ID
return ctrl.repo.Items.UpdateByGroup(auth, auth.GID, body) return ctrl.repo.Items.UpdateByGroup(auth, auth.GroupID, body)
} }
return adapters.ActionID("id", fn, http.StatusOK) return adapters.ActionID("id", fn, http.StatusOK)
@ -226,12 +226,12 @@ func (ctrl *V1Controller) HandleItemPatch() errchain.HandlerFunc {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
body.ID = ID body.ID = ID
err := ctrl.repo.Items.Patch(auth, auth.GID, ID, body) err := ctrl.repo.Items.Patch(auth, auth.GroupID, ID, body)
if err != nil { if err != nil {
return repo.ItemOut{}, err return repo.ItemOut{}, err
} }
return ctrl.repo.Items.GetOneByGroup(auth, auth.GID, ID) return ctrl.repo.Items.GetOneByGroup(auth, auth.GroupID, ID)
} }
return adapters.ActionID("id", fn, http.StatusOK) return adapters.ActionID("id", fn, http.StatusOK)
@ -249,7 +249,7 @@ func (ctrl *V1Controller) HandleItemPatch() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleGetAllCustomFieldNames() errchain.HandlerFunc { func (ctrl *V1Controller) HandleGetAllCustomFieldNames() errchain.HandlerFunc {
fn := func(r *http.Request) ([]string, error) { fn := func(r *http.Request) ([]string, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Items.GetAllCustomFieldNames(auth, auth.GID) return ctrl.repo.Items.GetAllCustomFieldNames(auth, auth.GroupID)
} }
return adapters.Command(fn, http.StatusOK) return adapters.Command(fn, http.StatusOK)
@ -271,7 +271,7 @@ func (ctrl *V1Controller) HandleGetAllCustomFieldValues() errchain.HandlerFunc {
fn := func(r *http.Request, q query) ([]string, error) { fn := func(r *http.Request, q query) ([]string, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Items.GetAllCustomFieldValues(auth, auth.GID, q.Field) return ctrl.repo.Items.GetAllCustomFieldValues(auth, auth.GroupID, q.Field)
} }
return adapters.Query(fn, http.StatusOK) return adapters.Query(fn, http.StatusOK)
@ -323,7 +323,7 @@ func (ctrl *V1Controller) HandleItemsExport() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error { return func(w http.ResponseWriter, r *http.Request) error {
ctx := services.NewContext(r.Context()) ctx := services.NewContext(r.Context())
csvData, err := ctrl.svc.Items.ExportTSV(r.Context(), ctx.GID) csvData, err := ctrl.svc.Items.ExportTSV(r.Context(), ctx.GroupID)
if err != nil { if err != nil {
log.Err(err).Msg("failed to export items") log.Err(err).Msg("failed to export items")
return validate.NewRequestError(err, http.StatusInternalServerError) return validate.NewRequestError(err, http.StatusInternalServerError)

View file

@ -168,7 +168,7 @@ func (ctrl *V1Controller) handleItemAttachmentsHandler(w http.ResponseWriter, r
// Delete Attachment Handler // Delete Attachment Handler
case http.MethodDelete: case http.MethodDelete:
err = ctrl.svc.Items.AttachmentDelete(r.Context(), ctx.GID, ID, attachmentID) err = ctrl.svc.Items.AttachmentDelete(r.Context(), ctx.GroupID, ID, attachmentID)
if err != nil { if err != nil {
log.Err(err).Msg("failed to delete attachment") log.Err(err).Msg("failed to delete attachment")
return validate.NewRequestError(err, http.StatusInternalServerError) return validate.NewRequestError(err, http.StatusInternalServerError)

View file

@ -21,7 +21,7 @@ import (
func (ctrl *V1Controller) HandleLabelsGetAll() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLabelsGetAll() errchain.HandlerFunc {
fn := func(r *http.Request) ([]repo.LabelSummary, error) { fn := func(r *http.Request) ([]repo.LabelSummary, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Labels.GetAll(auth, auth.GID) return ctrl.repo.Labels.GetAll(auth, auth.GroupID)
} }
return adapters.Command(fn, http.StatusOK) return adapters.Command(fn, http.StatusOK)
@ -39,7 +39,7 @@ func (ctrl *V1Controller) HandleLabelsGetAll() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleLabelsCreate() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLabelsCreate() errchain.HandlerFunc {
fn := func(r *http.Request, data repo.LabelCreate) (repo.LabelOut, error) { fn := func(r *http.Request, data repo.LabelCreate) (repo.LabelOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Labels.Create(auth, auth.GID, data) return ctrl.repo.Labels.Create(auth, auth.GroupID, data)
} }
return adapters.Action(fn, http.StatusCreated) return adapters.Action(fn, http.StatusCreated)
@ -57,7 +57,7 @@ func (ctrl *V1Controller) HandleLabelsCreate() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleLabelDelete() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLabelDelete() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (any, error) { fn := func(r *http.Request, ID uuid.UUID) (any, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
err := ctrl.repo.Labels.DeleteByGroup(auth, auth.GID, ID) err := ctrl.repo.Labels.DeleteByGroup(auth, auth.GroupID, ID)
return nil, err return nil, err
} }
@ -76,7 +76,7 @@ func (ctrl *V1Controller) HandleLabelDelete() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleLabelGet() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLabelGet() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (repo.LabelOut, error) { fn := func(r *http.Request, ID uuid.UUID) (repo.LabelOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Labels.GetOneByGroup(auth, auth.GID, ID) return ctrl.repo.Labels.GetOneByGroup(auth, auth.GroupID, ID)
} }
return adapters.CommandID("id", fn, http.StatusOK) return adapters.CommandID("id", fn, http.StatusOK)
@ -95,7 +95,7 @@ func (ctrl *V1Controller) HandleLabelUpdate() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID, data repo.LabelUpdate) (repo.LabelOut, error) { fn := func(r *http.Request, ID uuid.UUID, data repo.LabelUpdate) (repo.LabelOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
data.ID = ID data.ID = ID
return ctrl.repo.Labels.UpdateByGroup(auth, auth.GID, data) return ctrl.repo.Labels.UpdateByGroup(auth, auth.GroupID, data)
} }
return adapters.ActionID("id", fn, http.StatusOK) return adapters.ActionID("id", fn, http.StatusOK)

View file

@ -22,7 +22,7 @@ import (
func (ctrl *V1Controller) HandleLocationTreeQuery() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLocationTreeQuery() errchain.HandlerFunc {
fn := func(r *http.Request, query repo.TreeQuery) ([]repo.TreeItem, error) { fn := func(r *http.Request, query repo.TreeQuery) ([]repo.TreeItem, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Locations.Tree(auth, auth.GID, query) return ctrl.repo.Locations.Tree(auth, auth.GroupID, query)
} }
return adapters.Query(fn, http.StatusOK) return adapters.Query(fn, http.StatusOK)
@ -40,7 +40,7 @@ func (ctrl *V1Controller) HandleLocationTreeQuery() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleLocationGetAll() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLocationGetAll() errchain.HandlerFunc {
fn := func(r *http.Request, q repo.LocationQuery) ([]repo.LocationOutCount, error) { fn := func(r *http.Request, q repo.LocationQuery) ([]repo.LocationOutCount, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Locations.GetAll(auth, auth.GID, q) return ctrl.repo.Locations.GetAll(auth, auth.GroupID, q)
} }
return adapters.Query(fn, http.StatusOK) return adapters.Query(fn, http.StatusOK)
@ -58,7 +58,7 @@ func (ctrl *V1Controller) HandleLocationGetAll() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleLocationCreate() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLocationCreate() errchain.HandlerFunc {
fn := func(r *http.Request, createData repo.LocationCreate) (repo.LocationOut, error) { fn := func(r *http.Request, createData repo.LocationCreate) (repo.LocationOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Locations.Create(auth, auth.GID, createData) return ctrl.repo.Locations.Create(auth, auth.GroupID, createData)
} }
return adapters.Action(fn, http.StatusCreated) return adapters.Action(fn, http.StatusCreated)
@ -76,7 +76,7 @@ func (ctrl *V1Controller) HandleLocationCreate() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleLocationDelete() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLocationDelete() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (any, error) { fn := func(r *http.Request, ID uuid.UUID) (any, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
err := ctrl.repo.Locations.DeleteByGroup(auth, auth.GID, ID) err := ctrl.repo.Locations.DeleteByGroup(auth, auth.GroupID, ID)
return nil, err return nil, err
} }
@ -95,7 +95,7 @@ func (ctrl *V1Controller) HandleLocationDelete() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleLocationGet() errchain.HandlerFunc { func (ctrl *V1Controller) HandleLocationGet() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (repo.LocationOut, error) { fn := func(r *http.Request, ID uuid.UUID) (repo.LocationOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Locations.GetOneByGroup(auth, auth.GID, ID) return ctrl.repo.Locations.GetOneByGroup(auth, auth.GroupID, ID)
} }
return adapters.CommandID("id", fn, http.StatusOK) return adapters.CommandID("id", fn, http.StatusOK)
@ -115,7 +115,7 @@ func (ctrl *V1Controller) HandleLocationUpdate() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID, body repo.LocationUpdate) (repo.LocationOut, error) { fn := func(r *http.Request, ID uuid.UUID, body repo.LocationUpdate) (repo.LocationOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
body.ID = ID body.ID = ID
return ctrl.repo.Locations.UpdateByGroup(auth, auth.GID, ID, body) return ctrl.repo.Locations.UpdateByGroup(auth, auth.GroupID, ID, body)
} }
return adapters.ActionID("id", fn, http.StatusOK) return adapters.ActionID("id", fn, http.StatusOK)

View file

@ -21,7 +21,7 @@ import (
func (ctrl *V1Controller) HandleMaintenanceLogGet() errchain.HandlerFunc { func (ctrl *V1Controller) HandleMaintenanceLogGet() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID, q repo.MaintenanceLogQuery) (repo.MaintenanceLog, error) { fn := func(r *http.Request, ID uuid.UUID, q repo.MaintenanceLogQuery) (repo.MaintenanceLog, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.MaintEntry.GetLog(auth, auth.GID, ID, q) return ctrl.repo.MaintEntry.GetLog(auth, auth.GroupID, ID, q)
} }
return adapters.QueryID("id", fn, http.StatusOK) return adapters.QueryID("id", fn, http.StatusOK)

View file

@ -40,7 +40,7 @@ func (ctrl *V1Controller) HandleGetUserNotifiers() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleCreateNotifier() errchain.HandlerFunc { func (ctrl *V1Controller) HandleCreateNotifier() errchain.HandlerFunc {
fn := func(r *http.Request, in repo.NotifierCreate) (repo.NotifierOut, error) { fn := func(r *http.Request, in repo.NotifierCreate) (repo.NotifierOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Notifiers.Create(auth, auth.GID, auth.UID, in) return ctrl.repo.Notifiers.Create(auth, auth.GroupID, auth.UserID, in)
} }
return adapters.Action(fn, http.StatusCreated) return adapters.Action(fn, http.StatusCreated)
@ -57,7 +57,7 @@ func (ctrl *V1Controller) HandleCreateNotifier() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleDeleteNotifier() errchain.HandlerFunc { func (ctrl *V1Controller) HandleDeleteNotifier() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (any, error) { fn := func(r *http.Request, ID uuid.UUID) (any, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return nil, ctrl.repo.Notifiers.Delete(auth, auth.UID, ID) return nil, ctrl.repo.Notifiers.Delete(auth, auth.UserID, ID)
} }
return adapters.CommandID("id", fn, http.StatusNoContent) return adapters.CommandID("id", fn, http.StatusNoContent)
@ -75,7 +75,7 @@ func (ctrl *V1Controller) HandleDeleteNotifier() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleUpdateNotifier() errchain.HandlerFunc { func (ctrl *V1Controller) HandleUpdateNotifier() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID, in repo.NotifierUpdate) (repo.NotifierOut, error) { fn := func(r *http.Request, ID uuid.UUID, in repo.NotifierUpdate) (repo.NotifierOut, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Notifiers.Update(auth, auth.UID, ID, in) return ctrl.repo.Notifiers.Update(auth, auth.UserID, ID, in)
} }
return adapters.ActionID("id", fn, http.StatusOK) return adapters.ActionID("id", fn, http.StatusOK)

View file

@ -23,7 +23,7 @@ import (
func (ctrl *V1Controller) HandleGroupStatisticsLocations() errchain.HandlerFunc { func (ctrl *V1Controller) HandleGroupStatisticsLocations() errchain.HandlerFunc {
fn := func(r *http.Request) ([]repo.TotalsByOrganizer, error) { fn := func(r *http.Request) ([]repo.TotalsByOrganizer, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Groups.StatsLocationsByPurchasePrice(auth, auth.GID) return ctrl.repo.Groups.StatsLocationsByPurchasePrice(auth, auth.GroupID)
} }
return adapters.Command(fn, http.StatusOK) return adapters.Command(fn, http.StatusOK)
@ -40,7 +40,7 @@ func (ctrl *V1Controller) HandleGroupStatisticsLocations() errchain.HandlerFunc
func (ctrl *V1Controller) HandleGroupStatisticsLabels() errchain.HandlerFunc { func (ctrl *V1Controller) HandleGroupStatisticsLabels() errchain.HandlerFunc {
fn := func(r *http.Request) ([]repo.TotalsByOrganizer, error) { fn := func(r *http.Request) ([]repo.TotalsByOrganizer, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Groups.StatsLabelsByPurchasePrice(auth, auth.GID) return ctrl.repo.Groups.StatsLabelsByPurchasePrice(auth, auth.GroupID)
} }
return adapters.Command(fn, http.StatusOK) return adapters.Command(fn, http.StatusOK)
@ -57,7 +57,7 @@ func (ctrl *V1Controller) HandleGroupStatisticsLabels() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleGroupStatistics() errchain.HandlerFunc { func (ctrl *V1Controller) HandleGroupStatistics() errchain.HandlerFunc {
fn := func(r *http.Request) (repo.GroupStatistics, error) { fn := func(r *http.Request) (repo.GroupStatistics, error) {
auth := services.NewContext(r.Context()) auth := services.NewContext(r.Context())
return ctrl.repo.Groups.StatsGroup(auth, auth.GID) return ctrl.repo.Groups.StatsGroup(auth, auth.GroupID)
} }
return adapters.Command(fn, http.StatusOK) return adapters.Command(fn, http.StatusOK)
@ -94,7 +94,7 @@ func (ctrl *V1Controller) HandleGroupStatisticsPriceOverTime() errchain.HandlerF
return validate.NewRequestError(err, http.StatusBadRequest) return validate.NewRequestError(err, http.StatusBadRequest)
} }
stats, err := ctrl.repo.Groups.StatsPurchasePrice(ctx, ctx.GID, startDate, endDate) stats, err := ctrl.repo.Groups.StatsPurchasePrice(ctx, ctx.GroupID, startDate, endDate)
if err != nil { if err != nil {
return validate.NewRequestError(err, http.StatusInternalServerError) return validate.NewRequestError(err, http.StatusInternalServerError)
} }

View file

@ -115,11 +115,11 @@ func run(cfg *config.Config) error {
err = c.Schema.Create(context.Background(), options...) err = c.Schema.Create(context.Background(), options...)
if err != nil { if err != nil {
log.Fatal(). log.Fatal(). // nolint
Err(err). Err(err).
Str("driver", "sqlite"). Str("driver", "sqlite").
Str("url", cfg.Storage.SqliteURL). Str("url", cfg.Storage.SqliteURL).
Msg("failed creating schema resources") Msg("failed creating schema resources")
} }
err = os.RemoveAll(temp) err = os.RemoveAll(temp)

View file

@ -71,7 +71,7 @@ func main() {
text = replace.Regex.ReplaceAllString(text, replace.Text) text = replace.Regex.ReplaceAllString(text, replace.Text)
} }
err = os.WriteFile(path, []byte(text), 0644) err = os.WriteFile(path, []byte(text), 0o644)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)

View file

@ -115,8 +115,6 @@ github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
@ -126,8 +124,6 @@ github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJm
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/olahol/melody v1.1.4 h1:RQHfKZkQmDxI0+SLZRNBCn4LiXdqxLKRGSkT8Dyoe/E= github.com/olahol/melody v1.1.4 h1:RQHfKZkQmDxI0+SLZRNBCn4LiXdqxLKRGSkT8Dyoe/E=
github.com/olahol/melody v1.1.4/go.mod h1:GgkTl6Y7yWj/HtfD48Q5vLKPVoZOH+Qqgfa7CvJgJM4= github.com/olahol/melody v1.1.4/go.mod h1:GgkTl6Y7yWj/HtfD48Q5vLKPVoZOH+Qqgfa7CvJgJM4=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/onsi/ginkgo/v2 v2.9.2 h1:BA2GMJOtfGAfagzYtrAlufIP0lq6QERkFmHLMLPwFSU= github.com/onsi/ginkgo/v2 v2.9.2 h1:BA2GMJOtfGAfagzYtrAlufIP0lq6QERkFmHLMLPwFSU=
github.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts= github.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts=
github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE= github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE=
@ -145,10 +141,6 @@ github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=

View file

@ -19,11 +19,11 @@ var (
type Context struct { type Context struct {
context.Context context.Context
// UID is a unique identifier for the acting user. // UserID is a unique identifier for the acting user.
UID uuid.UUID UserID uuid.UUID
// GID is a unique identifier for the acting users group. // GroupID is a unique identifier for the acting users group.
GID uuid.UUID GroupID uuid.UUID
// User is the acting user. // User is the acting user.
User *repo.UserOut User *repo.UserOut
@ -35,8 +35,8 @@ func NewContext(ctx context.Context) Context {
user := UseUserCtx(ctx) user := UseUserCtx(ctx)
return Context{ return Context{
Context: ctx, Context: ctx,
UID: user.ID, UserID: user.ID,
GID: user.GroupID, GroupID: user.GroupID,
User: user, User: user,
} }
} }

View file

@ -69,14 +69,15 @@ func TestMain(m *testing.M) {
) )
tSvc = New(tRepos, "", &mailer.Mailer{}, WithCurrencies(defaults)) tSvc = New(tRepos, "", &mailer.Mailer{}, WithCurrencies(defaults))
defer func() { _ = client.Close() }()
bootstrap() bootstrap()
tCtx = Context{ tCtx = Context{
Context: context.Background(), Context: context.Background(),
GID: tGroup.ID, GroupID: tGroup.ID,
UID: tUser.ID, UserID: tUser.ID,
} }
os.Exit(m.Run()) exit := m.Run()
_ = client.Close()
os.Exit(exit)
} }

View file

@ -153,7 +153,7 @@ func (s *IOSheet) Read(data io.Reader) error {
} }
// ReadItems writes the sheet to a writer. // ReadItems writes the sheet to a writer.
func (s *IOSheet) ReadItems(ctx context.Context, items []repo.ItemOut, GID uuid.UUID, repos *repo.AllRepos) error { func (s *IOSheet) ReadItems(ctx context.Context, items []repo.ItemOut, groupID uuid.UUID, repos *repo.AllRepos) error {
s.Rows = make([]ExportTSVRow, len(items)) s.Rows = make([]ExportTSVRow, len(items))
extraHeaders := map[string]struct{}{} extraHeaders := map[string]struct{}{}
@ -164,7 +164,7 @@ func (s *IOSheet) ReadItems(ctx context.Context, items []repo.ItemOut, GID uuid.
// TODO: Support fetching nested locations // TODO: Support fetching nested locations
locID := item.Location.ID locID := item.Location.ID
locPaths, err := repos.Locations.PathForLoc(context.Background(), GID, locID) locPaths, err := repos.Locations.PathForLoc(context.Background(), groupID, locID)
if err != nil { if err != nil {
log.Error().Err(err).Msg("could not get location path") log.Error().Err(err).Msg("could not get location path")
return err return err

View file

@ -66,7 +66,6 @@ func (svc *BackgroundService) SendNotifiersToday(ctx context.Context) error {
var sendErrs []error var sendErrs []error
for i := range urls { for i := range urls {
err := shoutrrr.Send(urls[i], bldr.String()) err := shoutrrr.Send(urls[i], bldr.String())
if err != nil { if err != nil {
sendErrs = append(sendErrs, err) sendErrs = append(sendErrs, err)
} }

View file

@ -21,13 +21,13 @@ func (svc *GroupService) UpdateGroup(ctx Context, data repo.GroupUpdate) (repo.G
return repo.Group{}, errors.New("currency cannot be empty") return repo.Group{}, errors.New("currency cannot be empty")
} }
return svc.repos.Groups.GroupUpdate(ctx.Context, ctx.GID, data) return svc.repos.Groups.GroupUpdate(ctx.Context, ctx.GroupID, data)
} }
func (svc *GroupService) NewInvitation(ctx Context, uses int, expiresAt time.Time) (string, error) { func (svc *GroupService) NewInvitation(ctx Context, uses int, expiresAt time.Time) (string, error) {
token := hasher.GenerateToken() token := hasher.GenerateToken()
_, err := svc.repos.Groups.InvitationCreate(ctx, ctx.GID, repo.GroupInvitationCreate{ _, err := svc.repos.Groups.InvitationCreate(ctx, ctx.GroupID, repo.GroupInvitationCreate{
Token: token.Hash, Token: token.Hash,
Uses: uses, Uses: uses,
ExpiresAt: expiresAt, ExpiresAt: expiresAt,

View file

@ -27,7 +27,7 @@ type ItemService struct {
func (svc *ItemService) Create(ctx Context, item repo.ItemCreate) (repo.ItemOut, error) { func (svc *ItemService) Create(ctx Context, item repo.ItemCreate) (repo.ItemOut, error) {
if svc.autoIncrementAssetID { if svc.autoIncrementAssetID {
highest, err := svc.repo.Items.GetHighestAssetID(ctx, ctx.GID) highest, err := svc.repo.Items.GetHighestAssetID(ctx, ctx.GroupID)
if err != nil { if err != nil {
return repo.ItemOut{}, err return repo.ItemOut{}, err
} }
@ -35,16 +35,16 @@ func (svc *ItemService) Create(ctx Context, item repo.ItemCreate) (repo.ItemOut,
item.AssetID = highest + 1 item.AssetID = highest + 1
} }
return svc.repo.Items.Create(ctx, ctx.GID, item) return svc.repo.Items.Create(ctx, ctx.GroupID, item)
} }
func (svc *ItemService) EnsureAssetID(ctx context.Context, GID uuid.UUID) (int, error) { func (svc *ItemService) EnsureAssetID(ctx context.Context, groupID uuid.UUID) (int, error) {
items, err := svc.repo.Items.GetAllZeroAssetID(ctx, GID) items, err := svc.repo.Items.GetAllZeroAssetID(ctx, groupID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
highest, err := svc.repo.Items.GetHighestAssetID(ctx, GID) highest, err := svc.repo.Items.GetHighestAssetID(ctx, groupID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -53,7 +53,7 @@ func (svc *ItemService) EnsureAssetID(ctx context.Context, GID uuid.UUID) (int,
for _, item := range items { for _, item := range items {
highest++ highest++
err = svc.repo.Items.SetAssetID(ctx, GID, item.ID, highest) err = svc.repo.Items.SetAssetID(ctx, groupID, item.ID, highest)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -64,8 +64,8 @@ func (svc *ItemService) EnsureAssetID(ctx context.Context, GID uuid.UUID) (int,
return finished, nil return finished, nil
} }
func (svc *ItemService) EnsureImportRef(ctx context.Context, GID uuid.UUID) (int, error) { func (svc *ItemService) EnsureImportRef(ctx context.Context, groupID uuid.UUID) (int, error) {
ids, err := svc.repo.Items.GetAllZeroImportRef(ctx, GID) ids, err := svc.repo.Items.GetAllZeroImportRef(ctx, groupID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -74,7 +74,7 @@ func (svc *ItemService) EnsureImportRef(ctx context.Context, GID uuid.UUID) (int
for _, itemID := range ids { for _, itemID := range ids {
ref := uuid.New().String()[0:8] ref := uuid.New().String()[0:8]
err = svc.repo.Items.Patch(ctx, GID, itemID, repo.ItemPatch{ImportRef: &ref}) err = svc.repo.Items.Patch(ctx, groupID, itemID, repo.ItemPatch{ImportRef: &ref})
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -96,7 +96,7 @@ func serializeLocation[T ~[]string](location T) string {
// 1. If the item does not exist, it is created. // 1. If the item does not exist, it is created.
// 2. If the item has a ImportRef and it exists it is skipped // 2. If the item has a ImportRef and it exists it is skipped
// 3. Locations and Labels are created if they do not exist. // 3. Locations and Labels are created if they do not exist.
func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Reader) (int, error) { func (svc *ItemService) CsvImport(ctx context.Context, groupID uuid.UUID, data io.Reader) (int, error) {
sheet := reporting.IOSheet{} sheet := reporting.IOSheet{}
err := sheet.Read(data) err := sheet.Read(data)
@ -109,7 +109,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
labelMap := make(map[string]uuid.UUID) labelMap := make(map[string]uuid.UUID)
{ {
labels, err := svc.repo.Labels.GetAll(ctx, GID) labels, err := svc.repo.Labels.GetAll(ctx, groupID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -124,7 +124,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
locationMap := make(map[string]uuid.UUID) locationMap := make(map[string]uuid.UUID)
{ {
locations, err := svc.repo.Locations.Tree(ctx, GID, repo.TreeQuery{WithItems: false}) locations, err := svc.repo.Locations.Tree(ctx, groupID, repo.TreeQuery{WithItems: false})
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -153,7 +153,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
// Asset ID Pre-Check // Asset ID Pre-Check
highestAID := repo.AssetID(-1) highestAID := repo.AssetID(-1)
if svc.autoIncrementAssetID { if svc.autoIncrementAssetID {
highestAID, err = svc.repo.Items.GetHighestAssetID(ctx, GID) highestAID, err = svc.repo.Items.GetHighestAssetID(ctx, groupID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -169,7 +169,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
// ======================================== // ========================================
// Preflight check for existing item // Preflight check for existing item
if row.ImportRef != "" { if row.ImportRef != "" {
exists, err := svc.repo.Items.CheckRef(ctx, GID, row.ImportRef) exists, err := svc.repo.Items.CheckRef(ctx, groupID, row.ImportRef)
if err != nil { if err != nil {
return 0, fmt.Errorf("error checking for existing item with ref %q: %w", row.ImportRef, err) return 0, fmt.Errorf("error checking for existing item with ref %q: %w", row.ImportRef, err)
} }
@ -188,7 +188,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
id, ok := labelMap[label] id, ok := labelMap[label]
if !ok { if !ok {
newLabel, err := svc.repo.Labels.Create(ctx, GID, repo.LabelCreate{Name: label}) newLabel, err := svc.repo.Labels.Create(ctx, groupID, repo.LabelCreate{Name: label})
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -220,7 +220,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
parentID = locationMap[parentPath] parentID = locationMap[parentPath]
} }
newLocation, err := svc.repo.Locations.Create(ctx, GID, repo.LocationCreate{ newLocation, err := svc.repo.Locations.Create(ctx, groupID, repo.LocationCreate{
ParentID: parentID, ParentID: parentID,
Name: pathElement, Name: pathElement,
}) })
@ -261,12 +261,12 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
LabelIDs: labelIds, LabelIDs: labelIds,
} }
item, err = svc.repo.Items.Create(ctx, GID, newItem) item, err = svc.repo.Items.Create(ctx, groupID, newItem)
if err != nil { if err != nil {
return 0, err return 0, err
} }
default: default:
item, err = svc.repo.Items.GetByRef(ctx, GID, row.ImportRef) item, err = svc.repo.Items.GetByRef(ctx, groupID, row.ImportRef)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -318,7 +318,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
Fields: fields, Fields: fields,
} }
item, err = svc.repo.Items.UpdateByGroup(ctx, GID, updateItem) item, err = svc.repo.Items.UpdateByGroup(ctx, groupID, updateItem)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -329,15 +329,15 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re
return finished, nil return finished, nil
} }
func (svc *ItemService) ExportTSV(ctx context.Context, GID uuid.UUID) ([][]string, error) { func (svc *ItemService) ExportTSV(ctx context.Context, groupID uuid.UUID) ([][]string, error) {
items, err := svc.repo.Items.GetAll(ctx, GID) items, err := svc.repo.Items.GetAll(ctx, groupID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
sheet := reporting.IOSheet{} sheet := reporting.IOSheet{}
err = sheet.ReadItems(ctx, items, GID, svc.repo) err = sheet.ReadItems(ctx, items, groupID, svc.repo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -345,8 +345,8 @@ func (svc *ItemService) ExportTSV(ctx context.Context, GID uuid.UUID) ([][]strin
return sheet.TSV() return sheet.TSV()
} }
func (svc *ItemService) ExportBillOfMaterialsTSV(ctx context.Context, GID uuid.UUID) ([]byte, error) { func (svc *ItemService) ExportBillOfMaterialsTSV(ctx context.Context, groupID uuid.UUID) ([]byte, error) {
items, err := svc.repo.Items.GetAll(ctx, GID) items, err := svc.repo.Items.GetAll(ctx, groupID)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -35,7 +35,7 @@ func (svc *ItemService) AttachmentUpdate(ctx Context, itemID uuid.UUID, data *re
return repo.ItemOut{}, err return repo.ItemOut{}, err
} }
return svc.repo.Items.GetOneByGroup(ctx, ctx.GID, itemID) return svc.repo.Items.GetOneByGroup(ctx, ctx.GroupID, itemID)
} }
// AttachmentAdd adds an attachment to an item by creating an entry in the Documents table and linking it to the Attachment // AttachmentAdd adds an attachment to an item by creating an entry in the Documents table and linking it to the Attachment
@ -43,13 +43,13 @@ func (svc *ItemService) AttachmentUpdate(ctx Context, itemID uuid.UUID, data *re
// relative path during construction of the service. // relative path during construction of the service.
func (svc *ItemService) AttachmentAdd(ctx Context, itemID uuid.UUID, filename string, attachmentType attachment.Type, file io.Reader) (repo.ItemOut, error) { func (svc *ItemService) AttachmentAdd(ctx Context, itemID uuid.UUID, filename string, attachmentType attachment.Type, file io.Reader) (repo.ItemOut, error) {
// Get the Item // Get the Item
_, err := svc.repo.Items.GetOneByGroup(ctx, ctx.GID, itemID) _, err := svc.repo.Items.GetOneByGroup(ctx, ctx.GroupID, itemID)
if err != nil { if err != nil {
return repo.ItemOut{}, err return repo.ItemOut{}, err
} }
// Create the document // Create the document
doc, err := svc.repo.Docs.Create(ctx, ctx.GID, repo.DocumentCreate{Title: filename, Content: file}) doc, err := svc.repo.Docs.Create(ctx, ctx.GroupID, repo.DocumentCreate{Title: filename, Content: file})
if err != nil { if err != nil {
log.Err(err).Msg("failed to create document") log.Err(err).Msg("failed to create document")
return repo.ItemOut{}, err return repo.ItemOut{}, err
@ -62,7 +62,7 @@ func (svc *ItemService) AttachmentAdd(ctx Context, itemID uuid.UUID, filename st
return repo.ItemOut{}, err return repo.ItemOut{}, err
} }
return svc.repo.Items.GetOneByGroup(ctx, ctx.GID, itemID) return svc.repo.Items.GetOneByGroup(ctx, ctx.GroupID, itemID)
} }
func (svc *ItemService) AttachmentDelete(ctx context.Context, gid, itemID, attachmentID uuid.UUID) error { func (svc *ItemService) AttachmentDelete(ctx context.Context, gid, itemID, attachmentID uuid.UUID) error {

View file

@ -145,13 +145,13 @@ func (svc *UserService) GetSelf(ctx context.Context, requestToken string) (repo.
return svc.repos.AuthTokens.GetUserFromToken(ctx, hash) return svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
} }
func (svc *UserService) UpdateSelf(ctx context.Context, ID uuid.UUID, data repo.UserUpdate) (repo.UserOut, error) { func (svc *UserService) UpdateSelf(ctx context.Context, userID uuid.UUID, data repo.UserUpdate) (repo.UserOut, error) {
err := svc.repos.Users.Update(ctx, ID, data) err := svc.repos.Users.Update(ctx, userID, data)
if err != nil { if err != nil {
return repo.UserOut{}, err return repo.UserOut{}, err
} }
return svc.repos.Users.GetOneID(ctx, ID) return svc.repos.Users.GetOneID(ctx, userID)
} }
// ============================================================================ // ============================================================================
@ -230,12 +230,12 @@ func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthT
// DeleteSelf deletes the user that is currently logged based of the provided UUID // DeleteSelf deletes the user that is currently logged based of the provided UUID
// There is _NO_ protection against deleting the wrong user, as such this should only // There is _NO_ protection against deleting the wrong user, as such this should only
// be used when the identify of the user has been confirmed. // be used when the identify of the user has been confirmed.
func (svc *UserService) DeleteSelf(ctx context.Context, ID uuid.UUID) error { func (svc *UserService) DeleteSelf(ctx context.Context, userID uuid.UUID) error {
return svc.repos.Users.Delete(ctx, ID) return svc.repos.Users.Delete(ctx, userID)
} }
func (svc *UserService) ChangePassword(ctx Context, current string, new string) (ok bool) { func (svc *UserService) ChangePassword(ctx Context, current string, new string) (ok bool) {
usr, err := svc.repos.Users.GetOneID(ctx, ctx.UID) usr, err := svc.repos.Users.GetOneID(ctx, ctx.UserID)
if err != nil { if err != nil {
return false return false
} }
@ -251,7 +251,7 @@ func (svc *UserService) ChangePassword(ctx Context, current string, new string)
return false return false
} }
err = svc.repos.Users.ChangePassword(ctx.Context, ctx.UID, hashed) err = svc.repos.Users.ChangePassword(ctx.Context, ctx.UserID, hashed)
if err != nil { if err != nil {
log.Err(err).Msg("Failed to change password") log.Err(err).Msg("Failed to change password")
return false return false

View file

@ -16,9 +16,9 @@ func (aid AssetID) Int() int {
return int(aid) return int(aid)
} }
func ParseAssetIDBytes(d []byte) (AID AssetID, ok bool) { func ParseAssetIDBytes(d []byte) (assetID AssetID, ok bool) {
d = bytes.Replace(d, []byte(`"`), []byte(``), -1) d = bytes.ReplaceAll(d, []byte(`"`), []byte(``))
d = bytes.Replace(d, []byte(`-`), []byte(``), -1) d = bytes.ReplaceAll(d, []byte(`-`), []byte(``))
aidInt, err := strconv.Atoi(string(d)) aidInt, err := strconv.Atoi(string(d))
if err != nil { if err != nil {
@ -28,7 +28,7 @@ func ParseAssetIDBytes(d []byte) (AID AssetID, ok bool) {
return AssetID(aidInt), true return AssetID(aidInt), true
} }
func ParseAssetID(s string) (AID AssetID, ok bool) { func ParseAssetID(s string) (assetID AssetID, ok bool) {
return ParseAssetIDBytes([]byte(s)) return ParseAssetIDBytes([]byte(s))
} }
@ -52,8 +52,8 @@ func (aid *AssetID) UnmarshalJSON(d []byte) error {
return nil return nil
} }
d = bytes.Replace(d, []byte(`"`), []byte(``), -1) d = bytes.ReplaceAll(d, []byte(`"`), []byte(``))
d = bytes.Replace(d, []byte(`-`), []byte(``), -1) d = bytes.ReplaceAll(d, []byte(`-`), []byte(``))
aidInt, err := strconv.Atoi(string(d)) aidInt, err := strconv.Atoi(string(d))
if err != nil { if err != nil {

View file

@ -56,9 +56,10 @@ func TestMain(m *testing.M) {
tClient = client tClient = client
tRepos = New(tClient, tbus, os.TempDir()) tRepos = New(tClient, tbus, os.TempDir())
defer func() { _ = client.Close() }()
bootstrap() bootstrap()
os.Exit(m.Run()) exit := m.Run()
_ = client.Close()
os.Exit(exit)
} }

View file

@ -109,12 +109,12 @@ func (r *GroupRepository) GetAllGroups(ctx context.Context) ([]Group, error) {
return r.groupMapper.MapEachErr(r.db.Group.Query().All(ctx)) return r.groupMapper.MapEachErr(r.db.Group.Query().All(ctx))
} }
func (r *GroupRepository) StatsLocationsByPurchasePrice(ctx context.Context, GID uuid.UUID) ([]TotalsByOrganizer, error) { func (r *GroupRepository) StatsLocationsByPurchasePrice(ctx context.Context, groupID uuid.UUID) ([]TotalsByOrganizer, error) {
var v []TotalsByOrganizer var v []TotalsByOrganizer
err := r.db.Location.Query(). err := r.db.Location.Query().
Where( Where(
location.HasGroupWith(group.ID(GID)), location.HasGroupWith(group.ID(groupID)),
). ).
GroupBy(location.FieldID, location.FieldName). GroupBy(location.FieldID, location.FieldName).
Aggregate(func(sq *sql.Selector) string { Aggregate(func(sq *sql.Selector) string {
@ -131,12 +131,12 @@ func (r *GroupRepository) StatsLocationsByPurchasePrice(ctx context.Context, GID
return v, err return v, err
} }
func (r *GroupRepository) StatsLabelsByPurchasePrice(ctx context.Context, GID uuid.UUID) ([]TotalsByOrganizer, error) { func (r *GroupRepository) StatsLabelsByPurchasePrice(ctx context.Context, groupID uuid.UUID) ([]TotalsByOrganizer, error) {
var v []TotalsByOrganizer var v []TotalsByOrganizer
err := r.db.Label.Query(). err := r.db.Label.Query().
Where( Where(
label.HasGroupWith(group.ID(GID)), label.HasGroupWith(group.ID(groupID)),
). ).
GroupBy(label.FieldID, label.FieldName). GroupBy(label.FieldID, label.FieldName).
Aggregate(func(sq *sql.Selector) string { Aggregate(func(sq *sql.Selector) string {
@ -157,7 +157,7 @@ func (r *GroupRepository) StatsLabelsByPurchasePrice(ctx context.Context, GID uu
return v, err return v, err
} }
func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, GID uuid.UUID, start, end time.Time) (*ValueOverTime, error) { func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, groupID uuid.UUID, start, end time.Time) (*ValueOverTime, error) {
// Get the Totals for the Start and End of the Given Time Period // Get the Totals for the Start and End of the Given Time Period
q := ` q := `
SELECT SELECT
@ -180,7 +180,7 @@ func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, GID uuid.UUID,
var maybeStart *float64 var maybeStart *float64
var maybeEnd *float64 var maybeEnd *float64
row := r.db.Sql().QueryRowContext(ctx, q, GID, sqliteDateFormat(start), GID, sqliteDateFormat(end)) row := r.db.Sql().QueryRowContext(ctx, q, groupID, sqliteDateFormat(start), groupID, sqliteDateFormat(end))
err := row.Scan(&maybeStart, &maybeEnd) err := row.Scan(&maybeStart, &maybeEnd)
if err != nil { if err != nil {
return nil, err return nil, err
@ -198,7 +198,7 @@ func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, GID uuid.UUID,
// Get Created Date and Price of all items between start and end // Get Created Date and Price of all items between start and end
err = r.db.Item.Query(). err = r.db.Item.Query().
Where( Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
item.CreatedAtGTE(start), item.CreatedAtGTE(start),
item.CreatedAtLTE(end), item.CreatedAtLTE(end),
item.Archived(false), item.Archived(false),
@ -209,7 +209,6 @@ func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, GID uuid.UUID,
item.FieldPurchasePrice, item.FieldPurchasePrice,
). ).
Scan(ctx, &v) Scan(ctx, &v)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -226,7 +225,7 @@ func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, GID uuid.UUID,
return &stats, nil return &stats, nil
} }
func (r *GroupRepository) StatsGroup(ctx context.Context, GID uuid.UUID) (GroupStatistics, error) { func (r *GroupRepository) StatsGroup(ctx context.Context, groupID uuid.UUID) (GroupStatistics, error) {
q := ` q := `
SELECT SELECT
(SELECT COUNT(*) FROM users WHERE group_users = ?) AS total_users, (SELECT COUNT(*) FROM users WHERE group_users = ?) AS total_users,
@ -242,7 +241,7 @@ func (r *GroupRepository) StatsGroup(ctx context.Context, GID uuid.UUID) (GroupS
) AS total_with_warranty ) AS total_with_warranty
` `
var stats GroupStatistics var stats GroupStatistics
row := r.db.Sql().QueryRowContext(ctx, q, GID, GID, GID, GID, GID, GID) row := r.db.Sql().QueryRowContext(ctx, q, groupID, groupID, groupID, groupID, groupID, groupID)
var maybeTotalItemPrice *float64 var maybeTotalItemPrice *float64
var maybeTotalWithWarranty *int var maybeTotalWithWarranty *int
@ -264,8 +263,8 @@ func (r *GroupRepository) GroupCreate(ctx context.Context, name string) (Group,
Save(ctx)) Save(ctx))
} }
func (r *GroupRepository) GroupUpdate(ctx context.Context, ID uuid.UUID, data GroupUpdate) (Group, error) { func (r *GroupRepository) GroupUpdate(ctx context.Context, groupID uuid.UUID, data GroupUpdate) (Group, error) {
entity, err := r.db.Group.UpdateOneID(ID). entity, err := r.db.Group.UpdateOneID(groupID).
SetName(data.Name). SetName(data.Name).
SetCurrency(strings.ToLower(data.Currency)). SetCurrency(strings.ToLower(data.Currency)).
Save(ctx) Save(ctx)
@ -273,8 +272,8 @@ func (r *GroupRepository) GroupUpdate(ctx context.Context, ID uuid.UUID, data Gr
return r.groupMapper.MapErr(entity, err) return r.groupMapper.MapErr(entity, err)
} }
func (r *GroupRepository) GroupByID(ctx context.Context, id uuid.UUID) (Group, error) { func (r *GroupRepository) GroupByID(ctx context.Context, groupID uuid.UUID) (Group, error) {
return r.groupMapper.MapErr(r.db.Group.Get(ctx, id)) return r.groupMapper.MapErr(r.db.Group.Get(ctx, groupID))
} }
func (r *GroupRepository) InvitationGet(ctx context.Context, token []byte) (GroupInvitation, error) { func (r *GroupRepository) InvitationGet(ctx context.Context, token []byte) (GroupInvitation, error) {

View file

@ -276,9 +276,9 @@ func mapItemOut(item *ent.Item) ItemOut {
} }
} }
func (e *ItemsRepository) publishMutationEvent(GID uuid.UUID) { func (e *ItemsRepository) publishMutationEvent(groupID uuid.UUID) {
if e.bus != nil { if e.bus != nil {
e.bus.Publish(eventbus.EventItemMutation, eventbus.GroupMutationEvent{GID: GID}) e.bus.Publish(eventbus.EventItemMutation, eventbus.GroupMutationEvent{GID: groupID})
} }
} }
@ -304,13 +304,13 @@ func (e *ItemsRepository) GetOne(ctx context.Context, id uuid.UUID) (ItemOut, er
return e.getOne(ctx, item.ID(id)) return e.getOne(ctx, item.ID(id))
} }
func (e *ItemsRepository) CheckRef(ctx context.Context, GID uuid.UUID, ref string) (bool, error) { func (e *ItemsRepository) CheckRef(ctx context.Context, groupID uuid.UUID, ref string) (bool, error) {
q := e.db.Item.Query().Where(item.HasGroupWith(group.ID(GID))) q := e.db.Item.Query().Where(item.HasGroupWith(group.ID(groupID)))
return q.Where(item.ImportRef(ref)).Exist(ctx) return q.Where(item.ImportRef(ref)).Exist(ctx)
} }
func (e *ItemsRepository) GetByRef(ctx context.Context, GID uuid.UUID, ref string) (ItemOut, error) { func (e *ItemsRepository) GetByRef(ctx context.Context, groupID uuid.UUID, ref string) (ItemOut, error) {
return e.getOne(ctx, item.ImportRef(ref), item.HasGroupWith(group.ID(GID))) return e.getOne(ctx, item.ImportRef(ref), item.HasGroupWith(group.ID(groupID)))
} }
// GetOneByGroup returns a single item by ID. If the item does not exist, an error is returned. // GetOneByGroup returns a single item by ID. If the item does not exist, an error is returned.
@ -490,9 +490,9 @@ func (e *ItemsRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]ItemOut,
All(ctx)) All(ctx))
} }
func (e *ItemsRepository) GetAllZeroAssetID(ctx context.Context, GID uuid.UUID) ([]ItemSummary, error) { func (e *ItemsRepository) GetAllZeroAssetID(ctx context.Context, groupID uuid.UUID) ([]ItemSummary, error) {
q := e.db.Item.Query().Where( q := e.db.Item.Query().Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
item.AssetID(0), item.AssetID(0),
).Order( ).Order(
ent.Asc(item.FieldCreatedAt), ent.Asc(item.FieldCreatedAt),
@ -501,9 +501,9 @@ func (e *ItemsRepository) GetAllZeroAssetID(ctx context.Context, GID uuid.UUID)
return mapItemsSummaryErr(q.All(ctx)) return mapItemsSummaryErr(q.All(ctx))
} }
func (e *ItemsRepository) GetHighestAssetID(ctx context.Context, GID uuid.UUID) (AssetID, error) { func (e *ItemsRepository) GetHighestAssetID(ctx context.Context, groupID uuid.UUID) (AssetID, error) {
q := e.db.Item.Query().Where( q := e.db.Item.Query().Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
).Order( ).Order(
ent.Desc(item.FieldAssetID), ent.Desc(item.FieldAssetID),
).Limit(1) ).Limit(1)
@ -519,10 +519,10 @@ func (e *ItemsRepository) GetHighestAssetID(ctx context.Context, GID uuid.UUID)
return AssetID(result.AssetID), nil return AssetID(result.AssetID), nil
} }
func (e *ItemsRepository) SetAssetID(ctx context.Context, GID uuid.UUID, ID uuid.UUID, assetID AssetID) error { func (e *ItemsRepository) SetAssetID(ctx context.Context, groupID uuid.UUID, itemID uuid.UUID, assetID AssetID) error {
q := e.db.Item.Update().Where( q := e.db.Item.Update().Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
item.ID(ID), item.ID(itemID),
) )
_, err := q.SetAssetID(int(assetID)).Save(ctx) _, err := q.SetAssetID(int(assetID)).Save(ctx)
@ -576,8 +576,8 @@ func (e *ItemsRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID)
return err return err
} }
func (e *ItemsRepository) UpdateByGroup(ctx context.Context, GID uuid.UUID, data ItemUpdate) (ItemOut, error) { func (e *ItemsRepository) UpdateByGroup(ctx context.Context, groupID uuid.UUID, data ItemUpdate) (ItemOut, error) {
q := e.db.Item.Update().Where(item.ID(data.ID), item.HasGroupWith(group.ID(GID))). q := e.db.Item.Update().Where(item.ID(data.ID), item.HasGroupWith(group.ID(groupID))).
SetName(data.Name). SetName(data.Name).
SetDescription(data.Description). SetDescription(data.Description).
SetLocationID(data.LocationID). SetLocationID(data.LocationID).
@ -688,16 +688,16 @@ func (e *ItemsRepository) UpdateByGroup(ctx context.Context, GID uuid.UUID, data
} }
} }
e.publishMutationEvent(GID) e.publishMutationEvent(groupID)
return e.GetOne(ctx, data.ID) return e.GetOne(ctx, data.ID)
} }
func (e *ItemsRepository) GetAllZeroImportRef(ctx context.Context, GID uuid.UUID) ([]uuid.UUID, error) { func (e *ItemsRepository) GetAllZeroImportRef(ctx context.Context, groupID uuid.UUID) ([]uuid.UUID, error) {
var ids []uuid.UUID var ids []uuid.UUID
err := e.db.Item.Query(). err := e.db.Item.Query().
Where( Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
item.Or( item.Or(
item.ImportRefEQ(""), item.ImportRefEQ(""),
item.ImportRefIsNil(), item.ImportRefIsNil(),
@ -712,11 +712,11 @@ func (e *ItemsRepository) GetAllZeroImportRef(ctx context.Context, GID uuid.UUID
return ids, nil return ids, nil
} }
func (e *ItemsRepository) Patch(ctx context.Context, GID, ID uuid.UUID, data ItemPatch) error { func (e *ItemsRepository) Patch(ctx context.Context, groupID, itemID uuid.UUID, data ItemPatch) error {
q := e.db.Item.Update(). q := e.db.Item.Update().
Where( Where(
item.ID(ID), item.ID(itemID),
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
) )
if data.ImportRef != nil { if data.ImportRef != nil {
@ -727,11 +727,11 @@ func (e *ItemsRepository) Patch(ctx context.Context, GID, ID uuid.UUID, data Ite
q.SetQuantity(*data.Quantity) q.SetQuantity(*data.Quantity)
} }
e.publishMutationEvent(GID) e.publishMutationEvent(groupID)
return q.Exec(ctx) return q.Exec(ctx)
} }
func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, GID uuid.UUID, name string) ([]string, error) { func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, groupID uuid.UUID, name string) ([]string, error) {
type st struct { type st struct {
Value string `json:"text_value"` Value string `json:"text_value"`
} }
@ -740,7 +740,7 @@ func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, GID uuid.
err := e.db.Item.Query(). err := e.db.Item.Query().
Where( Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
). ).
QueryFields(). QueryFields().
Where( Where(
@ -761,7 +761,7 @@ func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, GID uuid.
return valueStrings, nil return valueStrings, nil
} }
func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, GID uuid.UUID) ([]string, error) { func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, groupID uuid.UUID) ([]string, error) {
type st struct { type st struct {
Name string `json:"name"` Name string `json:"name"`
} }
@ -770,7 +770,7 @@ func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, GID uuid.U
err := e.db.Item.Query(). err := e.db.Item.Query().
Where( Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
). ).
QueryFields(). QueryFields().
Unique(true). Unique(true).
@ -794,9 +794,9 @@ func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, GID uuid.U
// This is designed to resolve a long-time bug that has since been fixed with the time selector on the // This is designed to resolve a long-time bug that has since been fixed with the time selector on the
// frontend. This function is intended to be used as a one-time fix for existing databases and may be // frontend. This function is intended to be used as a one-time fix for existing databases and may be
// removed in the future. // removed in the future.
func (e *ItemsRepository) ZeroOutTimeFields(ctx context.Context, GID uuid.UUID) (int, error) { func (e *ItemsRepository) ZeroOutTimeFields(ctx context.Context, groupID uuid.UUID) (int, error) {
q := e.db.Item.Query().Where( q := e.db.Item.Query().Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
item.Or( item.Or(
item.PurchaseTimeNotNil(), item.PurchaseTimeNotNil(),
item.PurchaseFromLT("0002-01-01"), item.PurchaseFromLT("0002-01-01"),
@ -865,11 +865,11 @@ func (e *ItemsRepository) ZeroOutTimeFields(ctx context.Context, GID uuid.UUID)
return updated, nil return updated, nil
} }
func (e *ItemsRepository) SetPrimaryPhotos(ctx context.Context, GID uuid.UUID) (int, error) { func (e *ItemsRepository) SetPrimaryPhotos(ctx context.Context, groupID uuid.UUID) (int, error) {
// All items where there is no primary photo // All items where there is no primary photo
itemIDs, err := e.db.Item.Query(). itemIDs, err := e.db.Item.Query().
Where( Where(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
item.HasAttachmentsWith( item.HasAttachmentsWith(
attachment.TypeEQ(attachment.TypePhoto), attachment.TypeEQ(attachment.TypePhoto),
attachment.Not( attachment.Not(

View file

@ -65,9 +65,9 @@ func mapLabelOut(label *ent.Label) LabelOut {
} }
} }
func (r *LabelRepository) publishMutationEvent(GID uuid.UUID) { func (r *LabelRepository) publishMutationEvent(groupID uuid.UUID) {
if r.bus != nil { if r.bus != nil {
r.bus.Publish(eventbus.EventLabelMutation, eventbus.GroupMutationEvent{GID: GID}) r.bus.Publish(eventbus.EventLabelMutation, eventbus.GroupMutationEvent{GID: groupID})
} }
} }
@ -79,8 +79,8 @@ func (r *LabelRepository) getOne(ctx context.Context, where ...predicate.Label)
) )
} }
func (r *LabelRepository) GetOne(ctx context.Context, ID uuid.UUID) (LabelOut, error) { func (r *LabelRepository) GetOne(ctx context.Context, labelID uuid.UUID) (LabelOut, error) {
return r.getOne(ctx, label.ID(ID)) return r.getOne(ctx, label.ID(labelID))
} }
func (r *LabelRepository) GetOneByGroup(ctx context.Context, gid, ld uuid.UUID) (LabelOut, error) { func (r *LabelRepository) GetOneByGroup(ctx context.Context, gid, ld uuid.UUID) (LabelOut, error) {
@ -125,13 +125,13 @@ func (r *LabelRepository) update(ctx context.Context, data LabelUpdate, where ..
Save(ctx) Save(ctx)
} }
func (r *LabelRepository) UpdateByGroup(ctx context.Context, GID uuid.UUID, data LabelUpdate) (LabelOut, error) { func (r *LabelRepository) UpdateByGroup(ctx context.Context, groupID uuid.UUID, data LabelUpdate) (LabelOut, error) {
_, err := r.update(ctx, data, label.ID(data.ID), label.HasGroupWith(group.ID(GID))) _, err := r.update(ctx, data, label.ID(data.ID), label.HasGroupWith(group.ID(groupID)))
if err != nil { if err != nil {
return LabelOut{}, err return LabelOut{}, err
} }
r.publishMutationEvent(GID) r.publishMutationEvent(groupID)
return r.GetOne(ctx, data.ID) return r.GetOne(ctx, data.ID)
} }

View file

@ -89,9 +89,9 @@ func mapLocationOut(location *ent.Location) LocationOut {
} }
} }
func (r *LocationRepository) publishMutationEvent(GID uuid.UUID) { func (r *LocationRepository) publishMutationEvent(groupID uuid.UUID) {
if r.bus != nil { if r.bus != nil {
r.bus.Publish(eventbus.EventLocationMutation, eventbus.GroupMutationEvent{GID: GID}) r.bus.Publish(eventbus.EventLocationMutation, eventbus.GroupMutationEvent{GID: groupID})
} }
} }
@ -100,7 +100,7 @@ type LocationQuery struct {
} }
// GetAll returns all locations with item count field populated // GetAll returns all locations with item count field populated
func (r *LocationRepository) GetAll(ctx context.Context, GID uuid.UUID, filter LocationQuery) ([]LocationOutCount, error) { func (r *LocationRepository) GetAll(ctx context.Context, groupID uuid.UUID, filter LocationQuery) ([]LocationOutCount, error) {
query := `--sql query := `--sql
SELECT SELECT
id, id,
@ -131,7 +131,7 @@ func (r *LocationRepository) GetAll(ctx context.Context, GID uuid.UUID, filter L
query = strings.Replace(query, "{{ FILTER_CHILDREN }}", "", 1) query = strings.Replace(query, "{{ FILTER_CHILDREN }}", "", 1)
} }
rows, err := r.db.Sql().QueryContext(ctx, query, GID) rows, err := r.db.Sql().QueryContext(ctx, query, groupID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -167,19 +167,19 @@ func (r *LocationRepository) getOne(ctx context.Context, where ...predicate.Loca
Only(ctx)) Only(ctx))
} }
func (r *LocationRepository) Get(ctx context.Context, ID uuid.UUID) (LocationOut, error) { func (r *LocationRepository) Get(ctx context.Context, locationID uuid.UUID) (LocationOut, error) {
return r.getOne(ctx, location.ID(ID)) return r.getOne(ctx, location.ID(locationID))
} }
func (r *LocationRepository) GetOneByGroup(ctx context.Context, GID, ID uuid.UUID) (LocationOut, error) { func (r *LocationRepository) GetOneByGroup(ctx context.Context, groupID, locationID uuid.UUID) (LocationOut, error) {
return r.getOne(ctx, location.ID(ID), location.HasGroupWith(group.ID(GID))) return r.getOne(ctx, location.ID(locationID), location.HasGroupWith(group.ID(groupID)))
} }
func (r *LocationRepository) Create(ctx context.Context, GID uuid.UUID, data LocationCreate) (LocationOut, error) { func (r *LocationRepository) Create(ctx context.Context, groupID uuid.UUID, data LocationCreate) (LocationOut, error) {
q := r.db.Location.Create(). q := r.db.Location.Create().
SetName(data.Name). SetName(data.Name).
SetDescription(data.Description). SetDescription(data.Description).
SetGroupID(GID) SetGroupID(groupID)
if data.ParentID != uuid.Nil { if data.ParentID != uuid.Nil {
q.SetParentID(data.ParentID) q.SetParentID(data.ParentID)
@ -190,8 +190,8 @@ func (r *LocationRepository) Create(ctx context.Context, GID uuid.UUID, data Loc
return LocationOut{}, err return LocationOut{}, err
} }
location.Edges.Group = &ent.Group{ID: GID} // bootstrap group ID location.Edges.Group = &ent.Group{ID: groupID} // bootstrap group ID
r.publishMutationEvent(GID) r.publishMutationEvent(groupID)
return mapLocationOut(location), nil return mapLocationOut(location), nil
} }
@ -215,28 +215,28 @@ func (r *LocationRepository) update(ctx context.Context, data LocationUpdate, wh
return r.Get(ctx, data.ID) return r.Get(ctx, data.ID)
} }
func (r *LocationRepository) UpdateByGroup(ctx context.Context, GID, ID uuid.UUID, data LocationUpdate) (LocationOut, error) { func (r *LocationRepository) UpdateByGroup(ctx context.Context, groupID, locationID uuid.UUID, data LocationUpdate) (LocationOut, error) {
v, err := r.update(ctx, data, location.ID(ID), location.HasGroupWith(group.ID(GID))) v, err := r.update(ctx, data, location.ID(locationID), location.HasGroupWith(group.ID(groupID)))
if err != nil { if err != nil {
return LocationOut{}, err return LocationOut{}, err
} }
r.publishMutationEvent(GID) r.publishMutationEvent(groupID)
return v, err return v, err
} }
// delete should only be used after checking that the location is owned by the // delete should only be used after checking that the location is owned by the
// group. Otherwise, use DeleteByGroup // group. Otherwise, use DeleteByGroup
func (r *LocationRepository) delete(ctx context.Context, ID uuid.UUID) error { func (r *LocationRepository) delete(ctx context.Context, locationID uuid.UUID) error {
return r.db.Location.DeleteOneID(ID).Exec(ctx) return r.db.Location.DeleteOneID(locationID).Exec(ctx)
} }
func (r *LocationRepository) DeleteByGroup(ctx context.Context, GID, ID uuid.UUID) error { func (r *LocationRepository) DeleteByGroup(ctx context.Context, groupID, locationID uuid.UUID) error {
_, err := r.db.Location.Delete().Where(location.ID(ID), location.HasGroupWith(group.ID(GID))).Exec(ctx) _, err := r.db.Location.Delete().Where(location.ID(locationID), location.HasGroupWith(group.ID(groupID))).Exec(ctx)
if err != nil { if err != nil {
return err return err
} }
r.publishMutationEvent(GID) r.publishMutationEvent(groupID)
return err return err
} }
@ -273,7 +273,7 @@ type ItemPath struct {
Name string `json:"name"` Name string `json:"name"`
} }
func (r *LocationRepository) PathForLoc(ctx context.Context, GID, locID uuid.UUID) ([]ItemPath, error) { func (r *LocationRepository) PathForLoc(ctx context.Context, groupID, locID uuid.UUID) ([]ItemPath, error) {
query := `WITH RECURSIVE location_path AS ( query := `WITH RECURSIVE location_path AS (
SELECT id, name, location_children SELECT id, name, location_children
FROM locations FROM locations
@ -290,7 +290,7 @@ func (r *LocationRepository) PathForLoc(ctx context.Context, GID, locID uuid.UUI
SELECT id, name SELECT id, name
FROM location_path` FROM location_path`
rows, err := r.db.Sql().QueryContext(ctx, query, locID, GID) rows, err := r.db.Sql().QueryContext(ctx, query, locID, groupID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -320,7 +320,7 @@ func (r *LocationRepository) PathForLoc(ctx context.Context, GID, locID uuid.UUI
return locations, nil return locations, nil
} }
func (r *LocationRepository) Tree(ctx context.Context, GID uuid.UUID, tq TreeQuery) ([]TreeItem, error) { func (r *LocationRepository) Tree(ctx context.Context, groupID uuid.UUID, tq TreeQuery) ([]TreeItem, error) {
query := ` query := `
WITH recursive location_tree(id, NAME, parent_id, level, node_type) AS WITH recursive location_tree(id, NAME, parent_id, level, node_type) AS
( (
@ -402,7 +402,7 @@ func (r *LocationRepository) Tree(ctx context.Context, GID uuid.UUID, tq TreeQue
query = strings.ReplaceAll(query, "{{ WITH_ITEMS_FROM }}", "") query = strings.ReplaceAll(query, "{{ WITH_ITEMS_FROM }}", "")
} }
rows, err := r.db.Sql().QueryContext(ctx, query, GID) rows, err := r.db.Sql().QueryContext(ctx, query, groupID)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -84,11 +84,11 @@ func mapMaintenanceEntry(entry *ent.MaintenanceEntry) MaintenanceEntry {
} }
} }
func (r *MaintenanceEntryRepository) GetScheduled(ctx context.Context, GID uuid.UUID, dt types.Date) ([]MaintenanceEntry, error) { func (r *MaintenanceEntryRepository) GetScheduled(ctx context.Context, groupID uuid.UUID, dt types.Date) ([]MaintenanceEntry, error) {
entries, err := r.db.MaintenanceEntry.Query(). entries, err := r.db.MaintenanceEntry.Query().
Where( Where(
maintenanceentry.HasItemWith( maintenanceentry.HasItemWith(
item.HasGroupWith(group.ID(GID)), item.HasGroupWith(group.ID(groupID)),
), ),
maintenanceentry.ScheduledDate(dt.Time()), maintenanceentry.ScheduledDate(dt.Time()),
maintenanceentry.Or( maintenanceentry.Or(
@ -97,7 +97,6 @@ func (r *MaintenanceEntryRepository) GetScheduled(ctx context.Context, GID uuid.
), ),
). ).
All(ctx) All(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -118,8 +117,8 @@ func (r *MaintenanceEntryRepository) Create(ctx context.Context, itemID uuid.UUI
return mapMaintenanceEntryErr(item, err) return mapMaintenanceEntryErr(item, err)
} }
func (r *MaintenanceEntryRepository) Update(ctx context.Context, ID uuid.UUID, input MaintenanceEntryUpdate) (MaintenanceEntry, error) { func (r *MaintenanceEntryRepository) Update(ctx context.Context, entryID uuid.UUID, input MaintenanceEntryUpdate) (MaintenanceEntry, error) {
item, err := r.db.MaintenanceEntry.UpdateOneID(ID). item, err := r.db.MaintenanceEntry.UpdateOneID(entryID).
SetDate(input.CompletedDate.Time()). SetDate(input.CompletedDate.Time()).
SetScheduledDate(input.ScheduledDate.Time()). SetScheduledDate(input.ScheduledDate.Time()).
SetName(input.Name). SetName(input.Name).
@ -202,6 +201,6 @@ FROM
return log, nil return log, nil
} }
func (r *MaintenanceEntryRepository) Delete(ctx context.Context, ID uuid.UUID) error { func (r *MaintenanceEntryRepository) Delete(ctx context.Context, entryID uuid.UUID) error {
return r.db.MaintenanceEntry.DeleteOneID(ID).Exec(ctx) return r.db.MaintenanceEntry.DeleteOneID(entryID).Exec(ctx)
} }

View file

@ -78,7 +78,7 @@ func TestMaintenanceEntryRepository_GetLog(t *testing.T) {
} }
assert.InDelta(t, total, log.CostTotal, .001, "total cost should be equal to the sum of all entries") assert.InDelta(t, total, log.CostTotal, .001, "total cost should be equal to the sum of all entries")
assert.InDelta(t, total/2, log.CostAverage, 001, "average cost should be the average of the two months") assert.InDelta(t, total/2, log.CostAverage, 0o01, "average cost should be the average of the two months")
for _, entry := range log.Entries { for _, entry := range log.Entries {
err := tRepos.MaintEntry.Delete(context.Background(), entry.ID) err := tRepos.MaintEntry.Delete(context.Background(), entry.ID)

View file

@ -114,7 +114,7 @@ func (r *NotifierRepository) Update(ctx context.Context, userID uuid.UUID, id uu
return r.mapper.MapErr(notifier, err) return r.mapper.MapErr(notifier, err)
} }
func (r *NotifierRepository) Delete(ctx context.Context, userID uuid.UUID, ID uuid.UUID) error { func (r *NotifierRepository) Delete(ctx context.Context, userID uuid.UUID, notifierID uuid.UUID) error {
_, err := r.db.Notifier.Delete().Where(notifier.UserID(userID), notifier.ID(ID)).Exec(ctx) _, err := r.db.Notifier.Delete().Where(notifier.UserID(userID), notifier.ID(notifierID)).Exec(ctx)
return err return err
} }

View file

@ -61,9 +61,9 @@ func mapUserOut(user *ent.User) UserOut {
} }
} }
func (r *UserRepository) GetOneID(ctx context.Context, ID uuid.UUID) (UserOut, error) { func (r *UserRepository) GetOneID(ctx context.Context, userID uuid.UUID) (UserOut, error) {
return mapUserOutErr(r.db.User.Query(). return mapUserOutErr(r.db.User.Query().
Where(user.ID(ID)). Where(user.ID(userID)).
WithGroup(). WithGroup().
Only(ctx)) Only(ctx))
} }
@ -102,9 +102,9 @@ func (r *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, e
return r.GetOneID(ctx, entUser.ID) return r.GetOneID(ctx, entUser.ID)
} }
func (r *UserRepository) Update(ctx context.Context, ID uuid.UUID, data UserUpdate) error { func (r *UserRepository) Update(ctx context.Context, userID uuid.UUID, data UserUpdate) error {
q := r.db.User.Update(). q := r.db.User.Update().
Where(user.ID(ID)). Where(user.ID(userID)).
SetName(data.Name). SetName(data.Name).
SetEmail(data.Email) SetEmail(data.Email)
@ -131,13 +131,13 @@ func (r *UserRepository) GetSuperusers(ctx context.Context) ([]*ent.User, error)
return users, nil return users, nil
} }
func (r *UserRepository) ChangePassword(ctx context.Context, UID uuid.UUID, pw string) error { func (r *UserRepository) ChangePassword(ctx context.Context, userID uuid.UUID, pw string) error {
return r.db.User.UpdateOneID(UID).SetPassword(pw).Exec(ctx) return r.db.User.UpdateOneID(userID).SetPassword(pw).Exec(ctx)
} }
func (r *UserRepository) PasswordResetCreate(ctx context.Context, UID uuid.UUID, token []byte) error { func (r *UserRepository) PasswordResetCreate(ctx context.Context, userID uuid.UUID, token []byte) error {
return r.db.ActionToken.Create(). return r.db.ActionToken.Create().
SetUserID(UID). SetUserID(userID).
SetToken(token). SetToken(token).
SetAction(actiontoken.ActionResetPassword). SetAction(actiontoken.ActionResetPassword).
Exec(ctx) Exec(ctx)

View file

@ -5,8 +5,7 @@ import (
"errors" "errors"
) )
type UnauthorizedError struct { type UnauthorizedError struct{}
}
func (err *UnauthorizedError) Error() string { func (err *UnauthorizedError) Error() string {
return "unauthorized" return "unauthorized"

View file

@ -49,7 +49,6 @@ func init() { // nolint
return false return false
}) })
if err != nil { if err != nil {
panic(err) panic(err)
} }

View file

@ -6,5 +6,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
) )
type AdapterFunc[T any, Y any] func(*http.Request, T) (Y, error) type (
type IDFunc[T any, Y any] func(*http.Request, uuid.UUID, T) (Y, error) AdapterFunc[T any, Y any] func(*http.Request, T) (Y, error)
IDFunc[T any, Y any] func(*http.Request, uuid.UUID, T) (Y, error)
)

View file

@ -8,8 +8,10 @@ import (
"github.com/hay-kot/httpkit/server" "github.com/hay-kot/httpkit/server"
) )
type CommandFunc[T any] func(*http.Request) (T, error) type (
type CommandIDFunc[T any] func(*http.Request, uuid.UUID) (T, error) CommandFunc[T any] func(*http.Request) (T, error)
CommandIDFunc[T any] func(*http.Request, uuid.UUID) (T, error)
)
// Command is an HandlerAdapter that returns a errchain.HandlerFunc that // Command is an HandlerAdapter that returns a errchain.HandlerFunc that
// The command adapters are used to handle commands that do not accept a body // The command adapters are used to handle commands that do not accept a body

View file

@ -24,7 +24,6 @@ func GetTestMailer() (*Mailer, error) {
// Unmarshal JSON // Unmarshal JSON
err = json.Unmarshal(bytes, mailer) err = json.Unmarshal(bytes, mailer)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -48,7 +48,6 @@ func render(tpl string, data TemplateProps) (string, error) {
var tplBuffer bytes.Buffer var tplBuffer bytes.Buffer
err = tmpl.Execute(&tplBuffer, data) err = tmpl.Execute(&tplBuffer, data)
if err != nil { if err != nil {
return "", err return "", err
} }