diff --git a/backend/.golangci.yml b/backend/.golangci.yml index 8f631103..46a451e5 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -1,7 +1,5 @@ run: timeout: 10m - skip-dirs: - - internal/data/ent.* linters-settings: goconst: min-len: 5 @@ -45,7 +43,7 @@ linters: - errcheck - errorlint - exhaustive - - exportloopref + - copyloopvar - gochecknoinits - goconst - gocritic @@ -71,4 +69,6 @@ linters: - sqlclosecheck issues: exclude-use-default: false + exclude-dirs: + - internal/data/ent.* fix: true diff --git a/backend/app/api/demo.go b/backend/app/api/demo.go index 7a62b558..54b04f07 100644 --- a/backend/app/api/demo.go +++ b/backend/app/api/demo.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "strings" "time" @@ -9,7 +10,7 @@ import ( "github.com/sysadminsmedia/homebox/backend/internal/core/services" ) -func (a *app) SetupDemo() { +func (a *app) SetupDemo() error { csvText := `HB.import_ref,HB.location,HB.labels,HB.quantity,HB.name,HB.description,HB.insured,HB.serial_number,HB.model_number,HB.manufacturer,HB.notes,HB.purchase_from,HB.purchase_price,HB.purchase_time,HB.lifetime_warranty,HB.warranty_expires,HB.warranty_details,HB.sold_to,HB.sold_price,HB.sold_time,HB.sold_notes ,Garage,IOT;Home Assistant; Z-Wave,1,Zooz Universal Relay ZEN17,"Zooz 700 Series Z-Wave Universal Relay ZEN17 for Awnings, Garage Doors, Sprinklers, and More | 2 NO-C-NC Relays (20A, 10A) | Signal Repeater | Hub Required (Compatible with SmartThings and Hubitat)",,,ZEN17,Zooz,,Amazon,39.95,10/13/2021,,,,,,, ,Living Room,IOT;Home Assistant; Z-Wave,1,Zooz Motion Sensor,"Zooz Z-Wave Plus S2 Motion Sensor ZSE18 with Magnetic Mount, Works with Vera and SmartThings",,,ZSE18,Zooz,,Amazon,29.95,10/15/2021,,,,,,, @@ -33,34 +34,34 @@ func (a *app) SetupDemo() { _, err := a.services.User.Login(ctx, registration.Email, registration.Password, false) if err == nil { log.Info().Msg("Demo user already exists, skipping setup") - return + return nil } log.Debug().Msg("Demo user does not exist, setting up demo") _, err = a.services.User.RegisterUser(ctx, registration) if err != nil { log.Err(err).Msg("Failed to register demo user") - log.Fatal().Msg("Failed to setup demo") + return errors.New("failed to setup demo") } token, err := a.services.User.Login(ctx, registration.Email, registration.Password, false) if err != nil { log.Err(err).Msg("Failed to login demo user") - log.Fatal().Msg("Failed to setup demo") - return + return errors.New("failed to setup demo") } self, err := a.services.User.GetSelf(ctx, token.Raw) if err != nil { log.Err(err).Msg("Failed to get self") - log.Fatal().Msg("Failed to setup demo") - return + return errors.New("failed to setup demo") } _, err = a.services.Items.CsvImport(ctx, self.GroupID, strings.NewReader(csvText)) if err != nil { log.Err(err).Msg("Failed to import CSV") - log.Fatal().Msg("Failed to setup demo") + return errors.New("failed to setup demo") } log.Info().Msg("Demo setup complete") + + return nil } diff --git a/backend/app/api/handlers/v1/v1_ctrl_locations.go b/backend/app/api/handlers/v1/v1_ctrl_locations.go index 8bd403bc..3903bd92 100644 --- a/backend/app/api/handlers/v1/v1_ctrl_locations.go +++ b/backend/app/api/handlers/v1/v1_ctrl_locations.go @@ -85,15 +85,15 @@ func (ctrl *V1Controller) HandleLocationDelete() errchain.HandlerFunc { return adapters.CommandID("id", fn, http.StatusNoContent) } -func (ctrl *V1Controller) GetLocationWithPrice(auth context.Context, GID uuid.UUID, ID uuid.UUID) (repo.LocationOut, error) { - var location, err = ctrl.repo.Locations.GetOneByGroup(auth, GID, ID) +func (ctrl *V1Controller) GetLocationWithPrice(auth context.Context, gid uuid.UUID, id uuid.UUID) (repo.LocationOut, error) { + var location, err = ctrl.repo.Locations.GetOneByGroup(auth, gid, id) if err != nil { return repo.LocationOut{}, err } // Add direct child items price totalPrice := new(big.Int) - items, err := ctrl.repo.Items.QueryByGroup(auth, GID, repo.ItemQuery{LocationIDs: []uuid.UUID{ID}}) + items, err := ctrl.repo.Items.QueryByGroup(auth, gid, repo.ItemQuery{LocationIDs: []uuid.UUID{id}}) if err != nil { return repo.LocationOut{}, err } @@ -112,7 +112,7 @@ func (ctrl *V1Controller) GetLocationWithPrice(auth context.Context, GID uuid.UU // Add price from child locations for _, childLocation := range location.Children { var childLocationWithPrice repo.LocationOut - childLocationWithPrice, err = ctrl.GetLocationWithPrice(auth, GID, childLocation.ID) + childLocationWithPrice, err = ctrl.GetLocationWithPrice(auth, gid, childLocation.ID) if err != nil { return repo.LocationOut{}, err } diff --git a/backend/app/api/main.go b/backend/app/api/main.go index 2ba6eb6e..6247fe6a 100644 --- a/backend/app/api/main.go +++ b/backend/app/api/main.go @@ -115,16 +115,17 @@ func run(cfg *config.Config) error { err = c.Schema.Create(context.Background(), options...) if err != nil { - log.Fatal(). + log.Error(). Err(err). Str("driver", "sqlite"). Str("url", cfg.Storage.SqliteURL). Msg("failed creating schema resources") + return err } err = os.RemoveAll(temp) if err != nil { - log.Fatal().Err(err).Msg("failed to remove temporary directory for database migrations") + log.Error().Err(err).Msg("failed to remove temporary directory for database migrations") return err } @@ -139,10 +140,11 @@ func run(cfg *config.Config) error { content, err := os.ReadFile(cfg.Options.CurrencyConfig) if err != nil { - log.Fatal(). + log.Error(). Err(err). Str("path", cfg.Options.CurrencyConfig). Msg("failed to read currency config file") + return err } collectFuncs = append(collectFuncs, currencies.CollectJSON(bytes.NewReader(content))) @@ -150,9 +152,10 @@ func run(cfg *config.Config) error { currencies, err := currencies.CollectionCurrencies(collectFuncs...) if err != nil { - log.Fatal(). + log.Error(). Err(err). Msg("failed to collect currencies") + return err } app.bus = eventbus.New() @@ -211,7 +214,10 @@ func run(cfg *config.Config) error { // TODO: Remove through external API that does setup if cfg.Demo { log.Info().Msg("Running in demo mode, creating demo data") - app.SetupDemo() + err := app.SetupDemo() + if err != nil { + log.Fatal().Msg(err.Error()) + } } return nil }) diff --git a/backend/internal/core/services/main_test.go b/backend/internal/core/services/main_test.go index 2bc0cc84..f2e35bb4 100644 --- a/backend/internal/core/services/main_test.go +++ b/backend/internal/core/services/main_test.go @@ -49,7 +49,7 @@ func bootstrap() { } } -func TestMain(m *testing.M) { +func MainNoExit(m *testing.M) int { client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1") if err != nil { log.Fatalf("failed opening connection to sqlite: %v", err) @@ -77,5 +77,9 @@ func TestMain(m *testing.M) { UID: tUser.ID, } - os.Exit(m.Run()) + return m.Run() +} + +func TestMain(m *testing.M) { + os.Exit(MainNoExit(m)) } diff --git a/backend/internal/core/services/reporting/io_sheet.go b/backend/internal/core/services/reporting/io_sheet.go index cc97bd9b..1db37bc6 100644 --- a/backend/internal/core/services/reporting/io_sheet.go +++ b/backend/internal/core/services/reporting/io_sheet.go @@ -153,7 +153,7 @@ func (s *IOSheet) Read(data io.Reader) error { } // ReadItems writes the sheet to a writer. -func (s *IOSheet) ReadItems(ctx context.Context, items []repo.ItemOut, GID uuid.UUID, repos *repo.AllRepos, hbURL string) error { +func (s *IOSheet) ReadItems(ctx context.Context, items []repo.ItemOut, gid uuid.UUID, repos *repo.AllRepos, hbURL string) error { s.Rows = make([]ExportCSVRow, len(items)) 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 locID := item.Location.ID - locPaths, err := repos.Locations.PathForLoc(context.Background(), GID, locID) + locPaths, err := repos.Locations.PathForLoc(context.Background(), gid, locID) if err != nil { log.Error().Err(err).Msg("could not get location path") return err diff --git a/backend/internal/core/services/service_items.go b/backend/internal/core/services/service_items.go index 88b7e28a..650ce6a6 100644 --- a/backend/internal/core/services/service_items.go +++ b/backend/internal/core/services/service_items.go @@ -38,13 +38,13 @@ func (svc *ItemService) Create(ctx Context, item repo.ItemCreate) (repo.ItemOut, return svc.repo.Items.Create(ctx, ctx.GID, item) } -func (svc *ItemService) EnsureAssetID(ctx context.Context, GID uuid.UUID) (int, error) { - items, err := svc.repo.Items.GetAllZeroAssetID(ctx, GID) +func (svc *ItemService) EnsureAssetID(ctx context.Context, gid uuid.UUID) (int, error) { + items, err := svc.repo.Items.GetAllZeroAssetID(ctx, gid) if err != nil { return 0, err } - highest, err := svc.repo.Items.GetHighestAssetID(ctx, GID) + highest, err := svc.repo.Items.GetHighestAssetID(ctx, gid) if err != nil { return 0, err } @@ -53,7 +53,7 @@ func (svc *ItemService) EnsureAssetID(ctx context.Context, GID uuid.UUID) (int, for _, item := range items { highest++ - err = svc.repo.Items.SetAssetID(ctx, GID, item.ID, highest) + err = svc.repo.Items.SetAssetID(ctx, gid, item.ID, highest) if err != nil { return 0, err } @@ -64,8 +64,8 @@ func (svc *ItemService) EnsureAssetID(ctx context.Context, GID uuid.UUID) (int, return finished, nil } -func (svc *ItemService) EnsureImportRef(ctx context.Context, GID uuid.UUID) (int, error) { - ids, err := svc.repo.Items.GetAllZeroImportRef(ctx, GID) +func (svc *ItemService) EnsureImportRef(ctx context.Context, gid uuid.UUID) (int, error) { + ids, err := svc.repo.Items.GetAllZeroImportRef(ctx, gid) if err != nil { return 0, err } @@ -74,7 +74,7 @@ func (svc *ItemService) EnsureImportRef(ctx context.Context, GID uuid.UUID) (int for _, itemID := range ids { ref := uuid.New().String()[0:8] - err = svc.repo.Items.Patch(ctx, GID, itemID, repo.ItemPatch{ImportRef: &ref}) + err = svc.repo.Items.Patch(ctx, gid, itemID, repo.ItemPatch{ImportRef: &ref}) if err != nil { return 0, err } @@ -96,7 +96,7 @@ func serializeLocation[T ~[]string](location T) string { // 1. If the item does not exist, it is created. // 2. If the item has a ImportRef and it exists it is skipped // 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, gid uuid.UUID, data io.Reader) (int, error) { sheet := reporting.IOSheet{} 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) { - labels, err := svc.repo.Labels.GetAll(ctx, GID) + labels, err := svc.repo.Labels.GetAll(ctx, gid) if err != nil { 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) { - locations, err := svc.repo.Locations.Tree(ctx, GID, repo.TreeQuery{WithItems: false}) + locations, err := svc.repo.Locations.Tree(ctx, gid, repo.TreeQuery{WithItems: false}) if err != nil { return 0, err } @@ -153,7 +153,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re // Asset ID Pre-Check highestAID := repo.AssetID(-1) if svc.autoIncrementAssetID { - highestAID, err = svc.repo.Items.GetHighestAssetID(ctx, GID) + highestAID, err = svc.repo.Items.GetHighestAssetID(ctx, gid) if err != nil { 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 if row.ImportRef != "" { - exists, err := svc.repo.Items.CheckRef(ctx, GID, row.ImportRef) + exists, err := svc.repo.Items.CheckRef(ctx, gid, row.ImportRef) if err != nil { 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] if !ok { - newLabel, err := svc.repo.Labels.Create(ctx, GID, repo.LabelCreate{Name: label}) + newLabel, err := svc.repo.Labels.Create(ctx, gid, repo.LabelCreate{Name: label}) if err != nil { return 0, err } @@ -220,7 +220,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re parentID = locationMap[parentPath] } - newLocation, err := svc.repo.Locations.Create(ctx, GID, repo.LocationCreate{ + newLocation, err := svc.repo.Locations.Create(ctx, gid, repo.LocationCreate{ ParentID: parentID, Name: pathElement, }) @@ -261,12 +261,12 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re LabelIDs: labelIds, } - item, err = svc.repo.Items.Create(ctx, GID, newItem) + item, err = svc.repo.Items.Create(ctx, gid, newItem) if err != nil { return 0, err } default: - item, err = svc.repo.Items.GetByRef(ctx, GID, row.ImportRef) + item, err = svc.repo.Items.GetByRef(ctx, gid, row.ImportRef) if err != nil { return 0, err } @@ -318,7 +318,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re Fields: fields, } - item, err = svc.repo.Items.UpdateByGroup(ctx, GID, updateItem) + item, err = svc.repo.Items.UpdateByGroup(ctx, gid, updateItem) if err != nil { return 0, err } @@ -329,15 +329,15 @@ func (svc *ItemService) CsvImport(ctx context.Context, GID uuid.UUID, data io.Re return finished, nil } -func (svc *ItemService) ExportCSV(ctx context.Context, GID uuid.UUID, hbURL string) ([][]string, error) { - items, err := svc.repo.Items.GetAll(ctx, GID) +func (svc *ItemService) ExportCSV(ctx context.Context, gid uuid.UUID, hbURL string) ([][]string, error) { + items, err := svc.repo.Items.GetAll(ctx, gid) if err != nil { return nil, err } sheet := reporting.IOSheet{} - err = sheet.ReadItems(ctx, items, GID, svc.repo, hbURL) + err = sheet.ReadItems(ctx, items, gid, svc.repo, hbURL) if err != nil { return nil, err } @@ -345,8 +345,8 @@ func (svc *ItemService) ExportCSV(ctx context.Context, GID uuid.UUID, hbURL stri return sheet.CSV() } -func (svc *ItemService) ExportBillOfMaterialsCSV(ctx context.Context, GID uuid.UUID) ([]byte, error) { - items, err := svc.repo.Items.GetAll(ctx, GID) +func (svc *ItemService) ExportBillOfMaterialsCSV(ctx context.Context, gid uuid.UUID) ([]byte, error) { + items, err := svc.repo.Items.GetAll(ctx, gid) if err != nil { return nil, err } diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.go index da5d893f..0b67cb31 100644 --- a/backend/internal/core/services/service_user.go +++ b/backend/internal/core/services/service_user.go @@ -132,13 +132,13 @@ func (svc *UserService) GetSelf(ctx context.Context, requestToken string) (repo. return svc.repos.AuthTokens.GetUserFromToken(ctx, hash) } -func (svc *UserService) UpdateSelf(ctx context.Context, ID uuid.UUID, data repo.UserUpdate) (repo.UserOut, error) { - err := svc.repos.Users.Update(ctx, ID, data) +func (svc *UserService) UpdateSelf(ctx context.Context, id uuid.UUID, data repo.UserUpdate) (repo.UserOut, error) { + err := svc.repos.Users.Update(ctx, id, data) if err != nil { return repo.UserOut{}, err } - return svc.repos.Users.GetOneID(ctx, ID) + return svc.repos.Users.GetOneID(ctx, id) } // ============================================================================ @@ -217,8 +217,8 @@ func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthT // 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 // be used when the identify of the user has been confirmed. -func (svc *UserService) DeleteSelf(ctx context.Context, ID uuid.UUID) error { - return svc.repos.Users.Delete(ctx, ID) +func (svc *UserService) DeleteSelf(ctx context.Context, id uuid.UUID) error { + return svc.repos.Users.Delete(ctx, id) } func (svc *UserService) ChangePassword(ctx Context, current string, new string) (ok bool) { diff --git a/backend/internal/data/repo/asset_id_type.go b/backend/internal/data/repo/asset_id_type.go index 0a53a4a1..1181b89d 100644 --- a/backend/internal/data/repo/asset_id_type.go +++ b/backend/internal/data/repo/asset_id_type.go @@ -16,9 +16,9 @@ func (aid AssetID) Int() int { return int(aid) } -func ParseAssetIDBytes(d []byte) (AID AssetID, ok bool) { - d = bytes.Replace(d, []byte(`"`), []byte(``), -1) - d = bytes.Replace(d, []byte(`-`), []byte(``), -1) +func ParseAssetIDBytes(d []byte) (aid AssetID, ok bool) { + d = bytes.ReplaceAll(d, []byte(`"`), []byte(``)) + d = bytes.ReplaceAll(d, []byte(`-`), []byte(``)) aidInt, err := strconv.Atoi(string(d)) if err != nil { @@ -28,7 +28,7 @@ func ParseAssetIDBytes(d []byte) (AID AssetID, ok bool) { return AssetID(aidInt), true } -func ParseAssetID(s string) (AID AssetID, ok bool) { +func ParseAssetID(s string) (aid AssetID, ok bool) { return ParseAssetIDBytes([]byte(s)) } @@ -52,8 +52,8 @@ func (aid *AssetID) UnmarshalJSON(d []byte) error { return nil } - d = bytes.Replace(d, []byte(`"`), []byte(``), -1) - d = bytes.Replace(d, []byte(`-`), []byte(``), -1) + d = bytes.ReplaceAll(d, []byte(`"`), []byte(``)) + d = bytes.ReplaceAll(d, []byte(`-`), []byte(``)) aidInt, err := strconv.Atoi(string(d)) if err != nil { diff --git a/backend/internal/data/repo/main_test.go b/backend/internal/data/repo/main_test.go index 3e9f5c6f..a633d63c 100644 --- a/backend/internal/data/repo/main_test.go +++ b/backend/internal/data/repo/main_test.go @@ -39,7 +39,7 @@ func bootstrap() { } } -func TestMain(m *testing.M) { +func MainNoExit(m *testing.M) int { client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1") if err != nil { log.Fatalf("failed opening connection to sqlite: %v", err) @@ -59,6 +59,9 @@ func TestMain(m *testing.M) { defer func() { _ = client.Close() }() bootstrap() - - os.Exit(m.Run()) + return m.Run() +} + +func TestMain(m *testing.M) { + os.Exit(MainNoExit(m)) } diff --git a/backend/internal/data/repo/repo_group.go b/backend/internal/data/repo/repo_group.go index d2e4abda..2498052e 100644 --- a/backend/internal/data/repo/repo_group.go +++ b/backend/internal/data/repo/repo_group.go @@ -109,12 +109,12 @@ func (r *GroupRepository) GetAllGroups(ctx context.Context) ([]Group, error) { 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, gid uuid.UUID) ([]TotalsByOrganizer, error) { var v []TotalsByOrganizer err := r.db.Location.Query(). Where( - location.HasGroupWith(group.ID(GID)), + location.HasGroupWith(group.ID(gid)), ). GroupBy(location.FieldID, location.FieldName). Aggregate(func(sq *sql.Selector) string { @@ -131,12 +131,12 @@ func (r *GroupRepository) StatsLocationsByPurchasePrice(ctx context.Context, GID return v, err } -func (r *GroupRepository) StatsLabelsByPurchasePrice(ctx context.Context, GID uuid.UUID) ([]TotalsByOrganizer, error) { +func (r *GroupRepository) StatsLabelsByPurchasePrice(ctx context.Context, gid uuid.UUID) ([]TotalsByOrganizer, error) { var v []TotalsByOrganizer err := r.db.Label.Query(). Where( - label.HasGroupWith(group.ID(GID)), + label.HasGroupWith(group.ID(gid)), ). GroupBy(label.FieldID, label.FieldName). Aggregate(func(sq *sql.Selector) string { @@ -157,7 +157,7 @@ func (r *GroupRepository) StatsLabelsByPurchasePrice(ctx context.Context, GID uu 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, gid uuid.UUID, start, end time.Time) (*ValueOverTime, error) { // Get the Totals for the Start and End of the Given Time Period q := ` SELECT @@ -180,7 +180,7 @@ func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, GID uuid.UUID, var maybeStart *float64 var maybeEnd *float64 - row := r.db.Sql().QueryRowContext(ctx, q, GID, sqliteDateFormat(start), GID, sqliteDateFormat(end)) + row := r.db.Sql().QueryRowContext(ctx, q, gid, sqliteDateFormat(start), gid, sqliteDateFormat(end)) err := row.Scan(&maybeStart, &maybeEnd) if err != nil { 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 err = r.db.Item.Query(). Where( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), item.CreatedAtGTE(start), item.CreatedAtLTE(end), item.Archived(false), @@ -226,7 +226,7 @@ func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, GID uuid.UUID, return &stats, nil } -func (r *GroupRepository) StatsGroup(ctx context.Context, GID uuid.UUID) (GroupStatistics, error) { +func (r *GroupRepository) StatsGroup(ctx context.Context, gid uuid.UUID) (GroupStatistics, error) { q := ` SELECT (SELECT COUNT(*) FROM users WHERE group_users = ?) AS total_users, @@ -242,7 +242,7 @@ func (r *GroupRepository) StatsGroup(ctx context.Context, GID uuid.UUID) (GroupS ) AS total_with_warranty ` var stats GroupStatistics - row := r.db.Sql().QueryRowContext(ctx, q, GID, GID, GID, GID, GID, GID) + row := r.db.Sql().QueryRowContext(ctx, q, gid, gid, gid, gid, gid, gid) var maybeTotalItemPrice *float64 var maybeTotalWithWarranty *int @@ -264,8 +264,8 @@ func (r *GroupRepository) GroupCreate(ctx context.Context, name string) (Group, Save(ctx)) } -func (r *GroupRepository) GroupUpdate(ctx context.Context, ID uuid.UUID, data GroupUpdate) (Group, error) { - entity, err := r.db.Group.UpdateOneID(ID). +func (r *GroupRepository) GroupUpdate(ctx context.Context, id uuid.UUID, data GroupUpdate) (Group, error) { + entity, err := r.db.Group.UpdateOneID(id). SetName(data.Name). SetCurrency(strings.ToLower(data.Currency)). Save(ctx) diff --git a/backend/internal/data/repo/repo_items.go b/backend/internal/data/repo/repo_items.go index c714e229..dafc203b 100644 --- a/backend/internal/data/repo/repo_items.go +++ b/backend/internal/data/repo/repo_items.go @@ -277,9 +277,9 @@ func mapItemOut(item *ent.Item) ItemOut { } } -func (e *ItemsRepository) publishMutationEvent(GID uuid.UUID) { +func (e *ItemsRepository) publishMutationEvent(gid uuid.UUID) { if e.bus != nil { - e.bus.Publish(eventbus.EventItemMutation, eventbus.GroupMutationEvent{GID: GID}) + e.bus.Publish(eventbus.EventItemMutation, eventbus.GroupMutationEvent{GID: gid}) } } @@ -305,13 +305,13 @@ func (e *ItemsRepository) GetOne(ctx context.Context, id uuid.UUID) (ItemOut, er return e.getOne(ctx, item.ID(id)) } -func (e *ItemsRepository) CheckRef(ctx context.Context, GID uuid.UUID, ref string) (bool, error) { - q := e.db.Item.Query().Where(item.HasGroupWith(group.ID(GID))) +func (e *ItemsRepository) CheckRef(ctx context.Context, gid uuid.UUID, ref string) (bool, error) { + q := e.db.Item.Query().Where(item.HasGroupWith(group.ID(gid))) return q.Where(item.ImportRef(ref)).Exist(ctx) } -func (e *ItemsRepository) GetByRef(ctx context.Context, GID uuid.UUID, ref string) (ItemOut, error) { - return e.getOne(ctx, item.ImportRef(ref), item.HasGroupWith(group.ID(GID))) +func (e *ItemsRepository) GetByRef(ctx context.Context, gid uuid.UUID, ref string) (ItemOut, error) { + return e.getOne(ctx, item.ImportRef(ref), item.HasGroupWith(group.ID(gid))) } // GetOneByGroup returns a single item by ID. If the item does not exist, an error is returned. @@ -498,9 +498,9 @@ func (e *ItemsRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]ItemOut, All(ctx)) } -func (e *ItemsRepository) GetAllZeroAssetID(ctx context.Context, GID uuid.UUID) ([]ItemSummary, error) { +func (e *ItemsRepository) GetAllZeroAssetID(ctx context.Context, gid uuid.UUID) ([]ItemSummary, error) { q := e.db.Item.Query().Where( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), item.AssetID(0), ).Order( ent.Asc(item.FieldCreatedAt), @@ -509,9 +509,9 @@ func (e *ItemsRepository) GetAllZeroAssetID(ctx context.Context, GID uuid.UUID) return mapItemsSummaryErr(q.All(ctx)) } -func (e *ItemsRepository) GetHighestAssetID(ctx context.Context, GID uuid.UUID) (AssetID, error) { +func (e *ItemsRepository) GetHighestAssetID(ctx context.Context, gid uuid.UUID) (AssetID, error) { q := e.db.Item.Query().Where( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), ).Order( ent.Desc(item.FieldAssetID), ).Limit(1) @@ -527,10 +527,10 @@ func (e *ItemsRepository) GetHighestAssetID(ctx context.Context, GID uuid.UUID) 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, gid uuid.UUID, id uuid.UUID, assetID AssetID) error { q := e.db.Item.Update().Where( - item.HasGroupWith(group.ID(GID)), - item.ID(ID), + item.HasGroupWith(group.ID(gid)), + item.ID(id), ) _, err := q.SetAssetID(int(assetID)).Save(ctx) @@ -546,7 +546,7 @@ func (e *ItemsRepository) Create(ctx context.Context, gid uuid.UUID, data ItemCr SetLocationID(data.LocationID). SetAssetID(int(data.AssetID)) - if data.LabelIDs != nil && len(data.LabelIDs) > 0 { + if len(data.LabelIDs) > 0 { q.AddLabelIDs(data.LabelIDs...) } @@ -584,8 +584,8 @@ func (e *ItemsRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID) return err } -func (e *ItemsRepository) UpdateByGroup(ctx context.Context, GID uuid.UUID, data ItemUpdate) (ItemOut, error) { - q := e.db.Item.Update().Where(item.ID(data.ID), item.HasGroupWith(group.ID(GID))). +func (e *ItemsRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, data ItemUpdate) (ItemOut, error) { + q := e.db.Item.Update().Where(item.ID(data.ID), item.HasGroupWith(group.ID(gid))). SetName(data.Name). SetDescription(data.Description). SetLocationID(data.LocationID). @@ -696,16 +696,16 @@ func (e *ItemsRepository) UpdateByGroup(ctx context.Context, GID uuid.UUID, data } } - e.publishMutationEvent(GID) + e.publishMutationEvent(gid) 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, gid uuid.UUID) ([]uuid.UUID, error) { var ids []uuid.UUID err := e.db.Item.Query(). Where( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), item.Or( item.ImportRefEQ(""), item.ImportRefIsNil(), @@ -720,11 +720,11 @@ func (e *ItemsRepository) GetAllZeroImportRef(ctx context.Context, GID uuid.UUID return ids, nil } -func (e *ItemsRepository) Patch(ctx context.Context, GID, ID uuid.UUID, data ItemPatch) error { +func (e *ItemsRepository) Patch(ctx context.Context, gid, id uuid.UUID, data ItemPatch) error { q := e.db.Item.Update(). Where( - item.ID(ID), - item.HasGroupWith(group.ID(GID)), + item.ID(id), + item.HasGroupWith(group.ID(gid)), ) if data.ImportRef != nil { @@ -735,11 +735,11 @@ func (e *ItemsRepository) Patch(ctx context.Context, GID, ID uuid.UUID, data Ite q.SetQuantity(*data.Quantity) } - e.publishMutationEvent(GID) + e.publishMutationEvent(gid) 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, gid uuid.UUID, name string) ([]string, error) { type st struct { Value string `json:"text_value"` } @@ -748,7 +748,7 @@ func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, GID uuid. err := e.db.Item.Query(). Where( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), ). QueryFields(). Where( @@ -769,7 +769,7 @@ func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, GID uuid. return valueStrings, nil } -func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, GID uuid.UUID) ([]string, error) { +func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, gid uuid.UUID) ([]string, error) { type st struct { Name string `json:"name"` } @@ -778,7 +778,7 @@ func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, GID uuid.U err := e.db.Item.Query(). Where( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), ). QueryFields(). Unique(true). @@ -802,9 +802,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 // frontend. This function is intended to be used as a one-time fix for existing databases and may be // removed in the future. -func (e *ItemsRepository) ZeroOutTimeFields(ctx context.Context, GID uuid.UUID) (int, error) { +func (e *ItemsRepository) ZeroOutTimeFields(ctx context.Context, gid uuid.UUID) (int, error) { q := e.db.Item.Query().Where( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), item.Or( item.PurchaseTimeNotNil(), item.PurchaseFromLT("0002-01-01"), @@ -873,11 +873,11 @@ func (e *ItemsRepository) ZeroOutTimeFields(ctx context.Context, GID uuid.UUID) return updated, nil } -func (e *ItemsRepository) SetPrimaryPhotos(ctx context.Context, GID uuid.UUID) (int, error) { +func (e *ItemsRepository) SetPrimaryPhotos(ctx context.Context, gid uuid.UUID) (int, error) { // All items where there is no primary photo itemIDs, err := e.db.Item.Query(). Where( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), item.HasAttachmentsWith( attachment.TypeEQ(attachment.TypePhoto), attachment.Not( diff --git a/backend/internal/data/repo/repo_labels.go b/backend/internal/data/repo/repo_labels.go index 51c90103..03e2b4c1 100644 --- a/backend/internal/data/repo/repo_labels.go +++ b/backend/internal/data/repo/repo_labels.go @@ -65,9 +65,9 @@ func mapLabelOut(label *ent.Label) LabelOut { } } -func (r *LabelRepository) publishMutationEvent(GID uuid.UUID) { +func (r *LabelRepository) publishMutationEvent(gid uuid.UUID) { if r.bus != nil { - r.bus.Publish(eventbus.EventLabelMutation, eventbus.GroupMutationEvent{GID: GID}) + r.bus.Publish(eventbus.EventLabelMutation, eventbus.GroupMutationEvent{GID: gid}) } } @@ -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) { - return r.getOne(ctx, label.ID(ID)) +func (r *LabelRepository) GetOne(ctx context.Context, id uuid.UUID) (LabelOut, error) { + return r.getOne(ctx, label.ID(id)) } 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) } -func (r *LabelRepository) UpdateByGroup(ctx context.Context, GID uuid.UUID, data LabelUpdate) (LabelOut, error) { - _, err := r.update(ctx, data, label.ID(data.ID), label.HasGroupWith(group.ID(GID))) +func (r *LabelRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, data LabelUpdate) (LabelOut, error) { + _, err := r.update(ctx, data, label.ID(data.ID), label.HasGroupWith(group.ID(gid))) if err != nil { return LabelOut{}, err } - r.publishMutationEvent(GID) + r.publishMutationEvent(gid) return r.GetOne(ctx, data.ID) } diff --git a/backend/internal/data/repo/repo_locations.go b/backend/internal/data/repo/repo_locations.go index 1797ca6f..7ece91b2 100644 --- a/backend/internal/data/repo/repo_locations.go +++ b/backend/internal/data/repo/repo_locations.go @@ -90,9 +90,9 @@ func mapLocationOut(location *ent.Location) LocationOut { } } -func (r *LocationRepository) publishMutationEvent(GID uuid.UUID) { +func (r *LocationRepository) publishMutationEvent(gid uuid.UUID) { if r.bus != nil { - r.bus.Publish(eventbus.EventLocationMutation, eventbus.GroupMutationEvent{GID: GID}) + r.bus.Publish(eventbus.EventLocationMutation, eventbus.GroupMutationEvent{GID: gid}) } } @@ -101,7 +101,7 @@ type LocationQuery struct { } // 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, gid uuid.UUID, filter LocationQuery) ([]LocationOutCount, error) { query := `--sql SELECT id, @@ -132,7 +132,7 @@ func (r *LocationRepository) GetAll(ctx context.Context, GID uuid.UUID, filter L query = strings.Replace(query, "{{ FILTER_CHILDREN }}", "", 1) } - rows, err := r.db.Sql().QueryContext(ctx, query, GID) + rows, err := r.db.Sql().QueryContext(ctx, query, gid) if err != nil { return nil, err } @@ -168,19 +168,19 @@ func (r *LocationRepository) getOne(ctx context.Context, where ...predicate.Loca Only(ctx)) } -func (r *LocationRepository) Get(ctx context.Context, ID uuid.UUID) (LocationOut, error) { - return r.getOne(ctx, location.ID(ID)) +func (r *LocationRepository) Get(ctx context.Context, id uuid.UUID) (LocationOut, error) { + return r.getOne(ctx, location.ID(id)) } -func (r *LocationRepository) GetOneByGroup(ctx context.Context, GID, ID uuid.UUID) (LocationOut, error) { - return r.getOne(ctx, location.ID(ID), location.HasGroupWith(group.ID(GID))) +func (r *LocationRepository) GetOneByGroup(ctx context.Context, gid, id uuid.UUID) (LocationOut, error) { + return r.getOne(ctx, location.ID(id), location.HasGroupWith(group.ID(gid))) } -func (r *LocationRepository) Create(ctx context.Context, GID uuid.UUID, data LocationCreate) (LocationOut, error) { +func (r *LocationRepository) Create(ctx context.Context, gid uuid.UUID, data LocationCreate) (LocationOut, error) { q := r.db.Location.Create(). SetName(data.Name). SetDescription(data.Description). - SetGroupID(GID) + SetGroupID(gid) if data.ParentID != uuid.Nil { q.SetParentID(data.ParentID) @@ -191,8 +191,8 @@ func (r *LocationRepository) Create(ctx context.Context, GID uuid.UUID, data Loc return LocationOut{}, err } - location.Edges.Group = &ent.Group{ID: GID} // bootstrap group ID - r.publishMutationEvent(GID) + location.Edges.Group = &ent.Group{ID: gid} // bootstrap group ID + r.publishMutationEvent(gid) return mapLocationOut(location), nil } @@ -216,28 +216,28 @@ func (r *LocationRepository) update(ctx context.Context, data LocationUpdate, wh return r.Get(ctx, data.ID) } -func (r *LocationRepository) UpdateByGroup(ctx context.Context, GID, ID uuid.UUID, data LocationUpdate) (LocationOut, error) { - v, err := r.update(ctx, data, location.ID(ID), location.HasGroupWith(group.ID(GID))) +func (r *LocationRepository) UpdateByGroup(ctx context.Context, gid, id uuid.UUID, data LocationUpdate) (LocationOut, error) { + v, err := r.update(ctx, data, location.ID(id), location.HasGroupWith(group.ID(gid))) if err != nil { return LocationOut{}, err } - r.publishMutationEvent(GID) + r.publishMutationEvent(gid) return v, err } // delete should only be used after checking that the location is owned by the // group. Otherwise, use DeleteByGroup -func (r *LocationRepository) delete(ctx context.Context, ID uuid.UUID) error { - return r.db.Location.DeleteOneID(ID).Exec(ctx) +func (r *LocationRepository) delete(ctx context.Context, id uuid.UUID) error { + return r.db.Location.DeleteOneID(id).Exec(ctx) } -func (r *LocationRepository) DeleteByGroup(ctx context.Context, GID, ID uuid.UUID) error { - _, err := r.db.Location.Delete().Where(location.ID(ID), location.HasGroupWith(group.ID(GID))).Exec(ctx) +func (r *LocationRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID) error { + _, err := r.db.Location.Delete().Where(location.ID(id), location.HasGroupWith(group.ID(gid))).Exec(ctx) if err != nil { return err } - r.publishMutationEvent(GID) + r.publishMutationEvent(gid) return err } @@ -274,7 +274,7 @@ type ItemPath struct { Name string `json:"name"` } -func (r *LocationRepository) PathForLoc(ctx context.Context, GID, locID uuid.UUID) ([]ItemPath, error) { +func (r *LocationRepository) PathForLoc(ctx context.Context, gid, locID uuid.UUID) ([]ItemPath, error) { query := `WITH RECURSIVE location_path AS ( SELECT id, name, location_children FROM locations @@ -291,7 +291,7 @@ func (r *LocationRepository) PathForLoc(ctx context.Context, GID, locID uuid.UUI SELECT id, name FROM location_path` - rows, err := r.db.Sql().QueryContext(ctx, query, locID, GID) + rows, err := r.db.Sql().QueryContext(ctx, query, locID, gid) if err != nil { return nil, err } @@ -321,7 +321,7 @@ func (r *LocationRepository) PathForLoc(ctx context.Context, GID, locID uuid.UUI return locations, nil } -func (r *LocationRepository) Tree(ctx context.Context, GID uuid.UUID, tq TreeQuery) ([]TreeItem, error) { +func (r *LocationRepository) Tree(ctx context.Context, gid uuid.UUID, tq TreeQuery) ([]TreeItem, error) { query := ` WITH recursive location_tree(id, NAME, parent_id, level, node_type) AS ( @@ -403,7 +403,7 @@ func (r *LocationRepository) Tree(ctx context.Context, GID uuid.UUID, tq TreeQue query = strings.ReplaceAll(query, "{{ WITH_ITEMS_FROM }}", "") } - rows, err := r.db.Sql().QueryContext(ctx, query, GID) + rows, err := r.db.Sql().QueryContext(ctx, query, gid) if err != nil { return nil, err } diff --git a/backend/internal/data/repo/repo_maintenance_entry.go b/backend/internal/data/repo/repo_maintenance_entry.go index 73fe6e9e..565ed0f8 100644 --- a/backend/internal/data/repo/repo_maintenance_entry.go +++ b/backend/internal/data/repo/repo_maintenance_entry.go @@ -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, gid uuid.UUID, dt types.Date) ([]MaintenanceEntry, error) { entries, err := r.db.MaintenanceEntry.Query(). Where( maintenanceentry.HasItemWith( - item.HasGroupWith(group.ID(GID)), + item.HasGroupWith(group.ID(gid)), ), maintenanceentry.ScheduledDate(dt.Time()), maintenanceentry.Or( @@ -118,8 +118,8 @@ func (r *MaintenanceEntryRepository) Create(ctx context.Context, itemID uuid.UUI return mapMaintenanceEntryErr(item, err) } -func (r *MaintenanceEntryRepository) Update(ctx context.Context, ID uuid.UUID, input MaintenanceEntryUpdate) (MaintenanceEntry, error) { - item, err := r.db.MaintenanceEntry.UpdateOneID(ID). +func (r *MaintenanceEntryRepository) Update(ctx context.Context, id uuid.UUID, input MaintenanceEntryUpdate) (MaintenanceEntry, error) { + item, err := r.db.MaintenanceEntry.UpdateOneID(id). SetDate(input.CompletedDate.Time()). SetScheduledDate(input.ScheduledDate.Time()). SetName(input.Name). @@ -202,6 +202,6 @@ FROM return log, nil } -func (r *MaintenanceEntryRepository) Delete(ctx context.Context, ID uuid.UUID) error { - return r.db.MaintenanceEntry.DeleteOneID(ID).Exec(ctx) +func (r *MaintenanceEntryRepository) Delete(ctx context.Context, id uuid.UUID) error { + return r.db.MaintenanceEntry.DeleteOneID(id).Exec(ctx) } diff --git a/backend/internal/data/repo/repo_notifier.go b/backend/internal/data/repo/repo_notifier.go index b9eb5a2d..8313bc69 100644 --- a/backend/internal/data/repo/repo_notifier.go +++ b/backend/internal/data/repo/repo_notifier.go @@ -114,7 +114,7 @@ func (r *NotifierRepository) Update(ctx context.Context, userID uuid.UUID, id uu return r.mapper.MapErr(notifier, err) } -func (r *NotifierRepository) Delete(ctx context.Context, userID uuid.UUID, ID uuid.UUID) error { - _, err := r.db.Notifier.Delete().Where(notifier.UserID(userID), notifier.ID(ID)).Exec(ctx) +func (r *NotifierRepository) Delete(ctx context.Context, userID uuid.UUID, id uuid.UUID) error { + _, err := r.db.Notifier.Delete().Where(notifier.UserID(userID), notifier.ID(id)).Exec(ctx) return err } diff --git a/backend/internal/data/repo/repo_users.go b/backend/internal/data/repo/repo_users.go index 378bf316..8007fbc0 100644 --- a/backend/internal/data/repo/repo_users.go +++ b/backend/internal/data/repo/repo_users.go @@ -60,9 +60,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, id uuid.UUID) (UserOut, error) { return mapUserOutErr(r.db.User.Query(). - Where(user.ID(ID)). + Where(user.ID(id)). WithGroup(). Only(ctx)) } @@ -101,9 +101,9 @@ func (r *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, e 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, id uuid.UUID, data UserUpdate) error { q := r.db.User.Update(). - Where(user.ID(ID)). + Where(user.ID(id)). SetName(data.Name). SetEmail(data.Email) @@ -130,6 +130,6 @@ func (r *UserRepository) GetSuperusers(ctx context.Context) ([]*ent.User, error) return users, nil } -func (r *UserRepository) ChangePassword(ctx context.Context, UID uuid.UUID, pw string) error { - return r.db.User.UpdateOneID(UID).SetPassword(pw).Exec(ctx) +func (r *UserRepository) ChangePassword(ctx context.Context, uid uuid.UUID, pw string) error { + return r.db.User.UpdateOneID(uid).SetPassword(pw).Exec(ctx) }