Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

M:M User and Group Relationship (#1174)

Matt5eb0120025d4
diff --git a/backend/app/api/demo.go b/backend/app/api/demo.go
index 54b04f07..98617a74 100644
--- a/backend/app/api/demo.go
+++ b/backend/app/api/demo.go
@@ -8,13 +8,14 @@ import (
"github.com/rs/zerolog/log"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"
)
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,,,,,,,
-,Office,IOT;Home Assistant; Z-Wave,1,Zooz 110v Power Switch,"Zooz Z-Wave Plus Power Switch ZEN15 for 110V AC Units, Sump Pumps, Humidifiers, and More",,,ZEN15,Zooz,,Amazon,39.95,10/13/2021,,,,,,,
+,Office,IOT; Home Assistant; Z-Wave,1,Zooz 110v Power Switch,"Zooz Z-Wave Plus Power Switch ZEN15 for 110V AC Units, Sump Pumps, Humidifiers, and More",,,ZEN15,Zooz,,Amazon,39.95,10/13/2021,,,,,,,
,Downstairs,IOT;Home Assistant; Z-Wave,1,Ecolink Z-Wave PIR Motion Sensor,"Ecolink Z-Wave PIR Motion Detector Pet Immune, White (PIRZWAVE2.5-ECO)",,,PIRZWAVE2.5-ECO,Ecolink,,Amazon,35.58,10/21/2020,,,,,,,
,Entry,IOT;Home Assistant; Z-Wave,1,Yale Security Touchscreen Deadbolt,"Yale Security YRD226-ZW2-619 YRD226ZW2619 Touchscreen Deadbolt, Satin Nickel",,,YRD226ZW2619,Yale,,Amazon,120.39,10/14/2020,,,,,,,
,Kitchen,IOT;Home Assistant; Z-Wave,1,Smart Rocker Light Dimmer,"UltraPro Z-Wave Smart Rocker Light Dimmer with QuickFit and SimpleWire, 3-Way Ready, Compatible with Alexa, Google Assistant, ZWave Hub Required, Repeater/Range Extender, White Paddle Only, 39351",,,39351,Honeywell,,Amazon,65.98,09/30/0202,,,,,,,
@@ -29,21 +30,26 @@ func (a *app) SetupDemo() error {
Password: "demo",
}
- // First check if we've already setup a demo user and skip if so
- log.Debug().Msg("Checking if demo user already exists")
- _, err := a.services.User.Login(ctx, registration.Email, registration.Password, false)
- if err == nil {
- log.Info().Msg("Demo user already exists, skipping setup")
+ // If demo user already exists, skip all demo seeding tasks
+ if a.services.User.ExistsByEmail(ctx, registration.Email) {
+ log.Info().Msg("Demo user already exists; skipping demo seeding")
return nil
}
- log.Debug().Msg("Demo user does not exist, setting up demo")
- _, err = a.services.User.RegisterUser(ctx, registration)
+ // Otherwise, register the demo user
+ log.Debug().Msg("Registering demo user")
+ _, err := a.services.User.RegisterUser(ctx, registration)
if err != nil {
+ if ent.IsConstraintError(err) {
+ // Concurrent creation race: treat as exists and skip
+ log.Info().Msg("Demo user concurrently created; skipping seeding")
+ return nil
+ }
log.Err(err).Msg("Failed to register demo user")
return errors.New("failed to setup demo")
}
+ // Login the demo user to get a token
token, err := a.services.User.Login(ctx, registration.Email, registration.Password, false)
if err != nil {
log.Err(err).Msg("Failed to login demo user")
@@ -55,7 +61,7 @@ func (a *app) SetupDemo() error {
return errors.New("failed to setup demo")
}
- _, err = a.services.Items.CsvImport(ctx, self.GroupID, strings.NewReader(csvText))
+ _, err = a.services.Items.CsvImport(ctx, self.DefaultGroupID, strings.NewReader(csvText))
if err != nil {
log.Err(err).Msg("Failed to import CSV")
return errors.New("failed to setup demo")
diff --git a/backend/app/api/handlers/v1/v1_ctrl_actions.go b/backend/app/api/handlers/v1/v1_ctrl_actions.go
index 9f3ccd3b..66d0c4d4 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_actions.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_actions.go
@@ -119,14 +119,14 @@ func (ctrl *V1Controller) HandleWipeInventory() errchain.HandlerFunc {
if ctrl.isDemo {
return validate.NewRequestError(errors.New("wipe inventory is not allowed in demo mode"), http.StatusForbidden)
}
-
+
ctx := services.NewContext(r.Context())
-
+
// Check if user is owner
if !ctx.User.IsOwner {
return validate.NewRequestError(errors.New("only group owners can wipe inventory"), http.StatusForbidden)
}
-
+
// Parse options from request body
var options WipeInventoryOptions
if err := server.Decode(r, &options); err != nil {
@@ -137,13 +137,13 @@ func (ctrl *V1Controller) HandleWipeInventory() errchain.HandlerFunc {
WipeMaintenance: false,
}
}
-
+
totalCompleted, err := ctrl.repo.Items.WipeInventory(ctx, ctx.GID, options.WipeLabels, options.WipeLocations, options.WipeMaintenance)
if err != nil {
log.Err(err).Str("action_ref", "wipe inventory").Msg("failed to run action")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
-
+
// Publish mutation events for wiped resources
if ctrl.bus != nil {
if options.WipeLabels {
@@ -153,7 +153,7 @@ func (ctrl *V1Controller) HandleWipeInventory() errchain.HandlerFunc {
ctrl.bus.Publish(eventbus.EventLocationMutation, eventbus.GroupMutationEvent{GID: ctx.GID})
}
}
-
+
return server.JSON(w, http.StatusOK, ActionAmountResult{Completed: totalCompleted})
}
}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_group.go b/backend/app/api/handlers/v1/v1_ctrl_group.go
index a29d2599..7f8aa6ef 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_group.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_group.go
@@ -1,9 +1,12 @@
package v1
import (
+ "errors"
"net/http"
"time"
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
"github.com/hay-kot/httpkit/errchain"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
@@ -22,6 +25,19 @@ type (
ExpiresAt time.Time `json:"expiresAt"`
Uses int `json:"uses"`
}
+
+ GroupMemberAdd struct {
+ UserID uuid.UUID `json:"userId" validate:"required"`
+ }
+
+ GroupAcceptInvitationResponse struct {
+ ID uuid.UUID `json:"id"`
+ Name string `json:"name"`
+ }
+
+ CreateRequest struct {
+ Name string `json:"name" validate:"required"`
+ }
)
// HandleGroupGet godoc
@@ -95,3 +111,222 @@ func (ctrl *V1Controller) HandleGroupInvitationsCreate() errchain.HandlerFunc {
return adapters.Action(fn, http.StatusCreated)
}
+
+// HandleGroupsGetAll godoc
+//
+// @Summary Get All Groups
+// @Tags Group
+// @Produce json
+// @Success 200 {object} []repo.Group
+// @Router /v1/groups/all [Get]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupsGetAll() errchain.HandlerFunc {
+ fn := func(r *http.Request) ([]repo.Group, error) {
+ auth := services.NewContext(r.Context())
+ return ctrl.repo.Groups.GetAllGroups(auth, auth.UID)
+ }
+
+ return adapters.Command(fn, http.StatusOK)
+}
+
+// HandleGroupCreate godoc
+//
+// @Summary Create Group
+// @Tags Group
+// @Produce json
+// @Param payload body CreateRequest true "Create group request"
+// @Success 201 {object} repo.Group
+// @Router /v1/groups [Post]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupCreate() errchain.HandlerFunc {
+ fn := func(r *http.Request, body CreateRequest) (repo.Group, error) {
+ auth := services.NewContext(r.Context())
+ return ctrl.svc.Group.CreateGroup(auth, body.Name)
+ }
+
+ return adapters.Action(fn, http.StatusCreated)
+}
+
+// HandleGroupDelete godoc
+//
+// @Summary Delete Group
+// @Tags Group
+// @Produce json
+// @Success 204
+// @Router /v1/groups [Delete]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupDelete() errchain.HandlerFunc {
+ fn := func(r *http.Request) (any, error) {
+ auth := services.NewContext(r.Context())
+
+ // Get the current user to check their groups
+ currentUser, err := ctrl.repo.Users.GetOneID(auth, auth.UID)
+ if err != nil {
+ return nil, err
+ }
+
+ // Safeguard: prevent deleting if this is the user's only group
+ if len(currentUser.GroupIDs) <= 1 {
+ return nil, validate.NewRequestError(errors.New("cannot delete the only group you are a member of"), http.StatusBadRequest)
+ }
+
+ // If the group being deleted is the user's default group, reassign to another group
+ if currentUser.DefaultGroupID == auth.GID {
+ // Find another group the user is a member of
+ var newDefaultGroupID uuid.UUID
+ for _, gid := range currentUser.GroupIDs {
+ if gid != auth.GID {
+ newDefaultGroupID = gid
+ break
+ }
+ }
+
+ // Update the user's default group
+ if err := ctrl.repo.Users.UpdateDefaultGroup(auth, auth.UID, newDefaultGroupID); err != nil {
+ return nil, err
+ }
+ }
+
+ err = ctrl.svc.Group.DeleteGroup(auth)
+ return nil, err
+ }
+
+ return adapters.Command(fn, http.StatusNoContent)
+}
+
+// HandleGroupInvitationsGetAll godoc
+//
+// @Summary Get All Group Invitations
+// @Tags Group
+// @Produce json
+// @Success 200 {object} []repo.GroupInvitation
+// @Router /v1/groups/invitations [Get]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupInvitationsGetAll() errchain.HandlerFunc {
+ fn := func(r *http.Request) ([]repo.GroupInvitation, error) {
+ auth := services.NewContext(r.Context())
+ return ctrl.repo.Groups.InvitationGetAll(auth, auth.GID)
+ }
+
+ return adapters.Command(fn, http.StatusOK)
+}
+
+// HandleGroupMembersGetAll godoc
+//
+// @Summary Get All Group Members
+// @Tags Group
+// @Produce json
+// @Success 200 {object} []repo.UserSummary
+// @Router /v1/groups/members [Get]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupMembersGetAll() errchain.HandlerFunc {
+ fn := func(r *http.Request) ([]repo.UserSummary, error) {
+ auth := services.NewContext(r.Context())
+ return ctrl.repo.Users.GetUsersByGroupID(auth, auth.GID)
+ }
+
+ return adapters.Command(fn, http.StatusOK)
+}
+
+// HandleGroupMemberAdd godoc
+//
+// @Summary Add User to Group
+// @Tags Group
+// @Produce json
+// @Param payload body GroupMemberAdd true "User ID"
+// @Success 204
+// @Router /v1/groups/members [Post]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupMemberAdd() errchain.HandlerFunc {
+ fn := func(r *http.Request, body GroupMemberAdd) (any, error) {
+ auth := services.NewContext(r.Context())
+ err := ctrl.svc.Group.AddMember(auth, body.UserID)
+ return nil, err
+ }
+
+ return adapters.Action(fn, http.StatusNoContent)
+}
+
+// HandleGroupMemberRemove godoc
+//
+// @Summary Remove User from Group
+// @Tags Group
+// @Produce json
+// @Param user_id path string true "User ID"
+// @Success 204
+// @Router /v1/groups/members/{user_id} [Delete]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupMemberRemove() errchain.HandlerFunc {
+ fn := func(r *http.Request, userID uuid.UUID) (any, error) {
+ auth := services.NewContext(r.Context())
+
+ // Safeguard: prevent user from removing themselves
+ if userID == auth.UID {
+ return nil, validate.NewRequestError(errors.New("cannot remove yourself from the group"), http.StatusBadRequest)
+ }
+
+ // Safeguard: prevent removing the last member
+ members, err := ctrl.repo.Users.GetUsersByGroupID(auth, auth.GID)
+ if err != nil {
+ return nil, err
+ }
+ if len(members) <= 1 {
+ return nil, validate.NewRequestError(errors.New("cannot remove the last member from the group"), http.StatusBadRequest)
+ }
+
+ err = ctrl.svc.Group.RemoveMember(auth, userID)
+ return nil, err
+ }
+
+ return adapters.CommandID("user_id", fn, http.StatusNoContent)
+}
+
+// HandleGroupInvitationsDelete godoc
+//
+// @Summary Delete Group Invitation
+// @Tags Group
+// @Produce json
+// @Param id path string true "Invitation ID"
+// @Success 204
+// @Router /v1/groups/invitations/{id} [Delete]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupInvitationsDelete() errchain.HandlerFunc {
+ fn := func(r *http.Request, id uuid.UUID) (any, error) {
+ auth := services.NewContext(r.Context())
+ err := ctrl.svc.Group.DeleteInvitation(auth, id)
+ return nil, err
+ }
+
+ return adapters.CommandID("id", fn, http.StatusNoContent)
+}
+
+// HandleGroupInvitationsAccept godoc
+//
+// @Summary Accept Group Invitation
+// @Tags Group
+// @Produce json
+// @Param id path string true "Invitation Token"
+// @Success 200 {object} GroupAcceptInvitationResponse
+// @Router /v1/groups/invitations/{id} [Post]
+// @Security Bearer
+func (ctrl *V1Controller) HandleGroupInvitationsAccept() errchain.HandlerFunc {
+ fn := func(r *http.Request) (GroupAcceptInvitationResponse, error) {
+ token := chi.URLParam(r, "id")
+ if token == "" {
+ return GroupAcceptInvitationResponse{}, validate.NewRequestError(errors.New("token is required"), http.StatusBadRequest)
+ }
+
+ auth := services.NewContext(r.Context())
+ group, err := ctrl.svc.Group.AcceptInvitation(auth, token)
+ if err != nil {
+ if errors.Is(err, errors.New("user already a member of this group")) {
+ return GroupAcceptInvitationResponse{}, validate.NewRequestError(err, http.StatusBadRequest)
+ }
+ return GroupAcceptInvitationResponse{}, err
+ }
+
+ return GroupAcceptInvitationResponse{ID: group.ID, Name: group.Name}, nil
+ }
+
+ return adapters.Command(fn, http.StatusOK)
+}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_items.go b/backend/app/api/handlers/v1/v1_ctrl_items.go
index 5b38bda7..44a3bc8e 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_items.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_items.go
@@ -337,9 +337,9 @@ func (ctrl *V1Controller) HandleItemsImport() errchain.HandlerFunc {
return validate.NewRequestError(err, http.StatusInternalServerError)
}
- user := services.UseUserCtx(r.Context())
+ tenant := services.UseTenantCtx(r.Context())
- _, err = ctrl.svc.Items.CsvImport(r.Context(), user.GroupID, file)
+ _, err = ctrl.svc.Items.CsvImport(r.Context(), tenant, file)
if err != nil {
log.Err(err).Msg("failed to import items")
return validate.NewRequestError(err, http.StatusInternalServerError)
diff --git a/backend/app/api/handlers/v1/v1_ctrl_items_attachments.go b/backend/app/api/handlers/v1/v1_ctrl_items_attachments.go
index e862f2cc..882d80c2 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_items_attachments.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_items_attachments.go
@@ -212,7 +212,7 @@ func (ctrl *V1Controller) handleItemAttachmentsHandler(w http.ResponseWriter, r
// Delete Attachment Handler
case http.MethodDelete:
- err = ctrl.svc.Items.AttachmentDelete(r.Context(), ctx.GID, ID, attachmentID)
+ err = ctrl.svc.Items.AttachmentDelete(r.Context(), ctx.GID, attachmentID)
if err != nil {
log.Err(err).Msg("failed to delete attachment")
return validate.NewRequestError(err, http.StatusInternalServerError)
diff --git a/backend/app/api/handlers/v1/v1_ctrl_notifiers.go b/backend/app/api/handlers/v1/v1_ctrl_notifiers.go
index a119e498..35665b83 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_notifiers.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_notifiers.go
@@ -22,7 +22,8 @@ import (
func (ctrl *V1Controller) HandleGetUserNotifiers() errchain.HandlerFunc {
fn := func(r *http.Request, _ struct{}) ([]repo.NotifierOut, error) {
user := services.UseUserCtx(r.Context())
- return ctrl.repo.Notifiers.GetByUser(r.Context(), user.ID)
+ tenant := services.UseTenantCtx(r.Context())
+ return ctrl.repo.Notifiers.GetByUser(r.Context(), user.ID, tenant)
}
return adapters.Query(fn, http.StatusOK)
diff --git a/backend/app/api/handlers/v1/v1_ctrl_reporting.go b/backend/app/api/handlers/v1/v1_ctrl_reporting.go
index 6df58e17..69ac7a3b 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_reporting.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_reporting.go
@@ -1,9 +1,13 @@
package v1
import (
+ "errors"
+ "net/http"
+
+ "github.com/google/uuid"
"github.com/hay-kot/httpkit/errchain"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
- "net/http"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
)
// HandleBillOfMaterialsExport godoc
@@ -16,9 +20,13 @@ import (
// @Security Bearer
func (ctrl *V1Controller) HandleBillOfMaterialsExport() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- actor := services.UseUserCtx(r.Context())
+ tenant := services.UseTenantCtx(r.Context())
+
+ if tenant == uuid.Nil {
+ return validate.NewRequestError(errors.New("tenant required"), http.StatusBadRequest)
+ }
- csv, err := ctrl.svc.Items.ExportBillOfMaterialsCSV(r.Context(), actor.GroupID)
+ csv, err := ctrl.svc.Items.ExportBillOfMaterialsCSV(r.Context(), tenant)
if err != nil {
return err
}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_user.go b/backend/app/api/handlers/v1/v1_ctrl_user.go
index f1dbefa2..8b38f809 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_user.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_user.go
@@ -15,13 +15,13 @@ import (
// HandleUserRegistration godoc
//
-// @Summary Register New User
-// @Tags User
-// @Produce json
-// @Param payload body services.UserRegistration true "User Data"
-// @Success 204
-// @Failure 403 {string} string "Local login is not enabled"
-// @Router /v1/users/register [Post]
+// @Summary Register New User
+// @Tags User
+// @Produce json
+// @Param payload body services.UserRegistration true "User Data"
+// @Success 204
+// @Failure 403 {string} string "Local login is not enabled"
+// @Router /v1/users/register [Post]
func (ctrl *V1Controller) HandleUserRegistration() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
// Forbidden if local login is not enabled
diff --git a/backend/app/api/middleware.go b/backend/app/api/middleware.go
index 45495933..1525f480 100644
--- a/backend/app/api/middleware.go
+++ b/backend/app/api/middleware.go
@@ -7,6 +7,7 @@ import (
"net/url"
"strings"
+ "github.com/google/uuid"
"github.com/hay-kot/httpkit/errchain"
v1 "github.com/sysadminsmedia/homebox/backend/app/api/handlers/v1"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
@@ -152,3 +153,53 @@ func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {
return next.ServeHTTP(w, r)
})
}
+
+// mwTenant is a middleware that will parse the X-Tenant header and validate the user has access
+// to the requested tenant. If no header is provided, the user's default group is used.
+//
+// WARNING: This middleware _MUST_ be called after mwAuthToken
+func (a *app) mwTenant(next errchain.Handler) errchain.Handler {
+ return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
+ ctx := r.Context()
+
+ // Get the user from context (set by mwAuthToken)
+ user := services.UseUserCtx(ctx)
+ if user == nil {
+ return validate.NewRequestError(errors.New("user context not found"), http.StatusInternalServerError)
+ }
+
+ tenantID := user.DefaultGroupID
+
+ // Check for X-Tenant header or tenant query parameter
+ tenantHeader := r.Header.Get("X-Tenant")
+ if tenantHeader == "" {
+ tenantHeader = r.URL.Query().Get("tenant")
+ }
+
+ if tenantHeader != "" {
+ parsedTenantID, err := uuid.Parse(tenantHeader)
+ if err != nil {
+ return validate.NewRequestError(errors.New("invalid X-Tenant header format"), http.StatusBadRequest)
+ }
+
+ // Validate user has access to the requested tenant
+ hasAccess := false
+ for _, gid := range user.GroupIDs {
+ if gid == parsedTenantID {
+ hasAccess = true
+ break
+ }
+ }
+
+ if !hasAccess {
+ return validate.NewRequestError(errors.New("user does not have access to the requested tenant"), http.StatusForbidden)
+ }
+
+ tenantID = parsedTenantID
+ }
+
+ // Set the tenant in context
+ r = r.WithContext(services.SetTenantCtx(ctx, tenantID))
+ return next.ServeHTTP(w, r)
+ })
+}
diff --git a/backend/app/api/routes.go b/backend/app/api/routes.go
index f655a543..010daaa8 100644
--- a/backend/app/api/routes.go
+++ b/backend/app/api/routes.go
@@ -82,10 +82,13 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
userMW := []errchain.Middleware{
a.mwAuthToken,
+ a.mwTenant,
a.mwRoles(RoleModeOr, authroles.RoleUser.String()),
}
r.Get("/ws/events", chain.ToHandlerFunc(v1Ctrl.HandleCacheWS(), userMW...))
+
+ // User management endpoints
r.Get("/users/self", chain.ToHandlerFunc(v1Ctrl.HandleUserSelf(), userMW...))
r.Put("/users/self", chain.ToHandlerFunc(v1Ctrl.HandleUserSelfUpdate(), userMW...))
r.Delete("/users/self", chain.ToHandlerFunc(v1Ctrl.HandleUserSelfDelete(), userMW...))
@@ -93,16 +96,27 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
r.Get("/users/refresh", chain.ToHandlerFunc(v1Ctrl.HandleAuthRefresh(), userMW...))
r.Put("/users/self/change-password", chain.ToHandlerFunc(v1Ctrl.HandleUserSelfChangePassword(), userMW...))
+ // Group management endpoints
+ r.Get("/groups/all", chain.ToHandlerFunc(v1Ctrl.HandleGroupsGetAll(), userMW...))
+ r.Post("/groups", chain.ToHandlerFunc(v1Ctrl.HandleGroupCreate(), userMW...))
+ r.Get("/groups", chain.ToHandlerFunc(v1Ctrl.HandleGroupGet(), userMW...))
+ r.Put("/groups", chain.ToHandlerFunc(v1Ctrl.HandleGroupUpdate(), userMW...))
+ r.Delete("/groups", chain.ToHandlerFunc(v1Ctrl.HandleGroupDelete(), userMW...))
+
+ r.Get("/groups/members", chain.ToHandlerFunc(v1Ctrl.HandleGroupMembersGetAll(), userMW...))
+ r.Post("/groups/members", chain.ToHandlerFunc(v1Ctrl.HandleGroupMemberAdd(), userMW...))
+ r.Delete("/groups/members/{user_id}", chain.ToHandlerFunc(v1Ctrl.HandleGroupMemberRemove(), userMW...))
+
+ r.Get("/groups/invitations", chain.ToHandlerFunc(v1Ctrl.HandleGroupInvitationsGetAll(), userMW...))
r.Post("/groups/invitations", chain.ToHandlerFunc(v1Ctrl.HandleGroupInvitationsCreate(), userMW...))
+ r.Post("/groups/invitations/{id}", chain.ToHandlerFunc(v1Ctrl.HandleGroupInvitationsAccept(), userMW...))
+ r.Delete("/groups/invitations/{id}", chain.ToHandlerFunc(v1Ctrl.HandleGroupInvitationsDelete(), userMW...))
r.Get("/groups/statistics", chain.ToHandlerFunc(v1Ctrl.HandleGroupStatistics(), userMW...))
r.Get("/groups/statistics/purchase-price", chain.ToHandlerFunc(v1Ctrl.HandleGroupStatisticsPriceOverTime(), userMW...))
r.Get("/groups/statistics/locations", chain.ToHandlerFunc(v1Ctrl.HandleGroupStatisticsLocations(), userMW...))
r.Get("/groups/statistics/labels", chain.ToHandlerFunc(v1Ctrl.HandleGroupStatisticsLabels(), userMW...))
- // TODO: I don't like /groups being the URL for users
- r.Get("/groups", chain.ToHandlerFunc(v1Ctrl.HandleGroupGet(), userMW...))
- r.Put("/groups", chain.ToHandlerFunc(v1Ctrl.HandleGroupUpdate(), userMW...))
-
+ // Action endpoints
r.Post("/actions/ensure-asset-ids", chain.ToHandlerFunc(v1Ctrl.HandleEnsureAssetID(), userMW...))
r.Post("/actions/zero-item-time-fields", chain.ToHandlerFunc(v1Ctrl.HandleItemDateZeroOut(), userMW...))
r.Post("/actions/ensure-import-refs", chain.ToHandlerFunc(v1Ctrl.HandleEnsureImportRefs(), userMW...))
@@ -110,6 +124,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
r.Post("/actions/create-missing-thumbnails", chain.ToHandlerFunc(v1Ctrl.HandleCreateMissingThumbnails(), userMW...))
r.Post("/actions/wipe-inventory", chain.ToHandlerFunc(v1Ctrl.HandleWipeInventory(), userMW...))
+ // Location endpoints
r.Get("/locations", chain.ToHandlerFunc(v1Ctrl.HandleLocationGetAll(), userMW...))
r.Post("/locations", chain.ToHandlerFunc(v1Ctrl.HandleLocationCreate(), userMW...))
r.Get("/locations/tree", chain.ToHandlerFunc(v1Ctrl.HandleLocationTreeQuery(), userMW...))
@@ -117,12 +132,14 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
r.Put("/locations/{id}", chain.ToHandlerFunc(v1Ctrl.HandleLocationUpdate(), userMW...))
r.Delete("/locations/{id}", chain.ToHandlerFunc(v1Ctrl.HandleLocationDelete(), userMW...))
+ // Labels (tags) endpoints
r.Get("/labels", chain.ToHandlerFunc(v1Ctrl.HandleLabelsGetAll(), userMW...))
r.Post("/labels", chain.ToHandlerFunc(v1Ctrl.HandleLabelsCreate(), userMW...))
r.Get("/labels/{id}", chain.ToHandlerFunc(v1Ctrl.HandleLabelGet(), userMW...))
r.Put("/labels/{id}", chain.ToHandlerFunc(v1Ctrl.HandleLabelUpdate(), userMW...))
r.Delete("/labels/{id}", chain.ToHandlerFunc(v1Ctrl.HandleLabelDelete(), userMW...))
+ // Item endpoints
r.Get("/items", chain.ToHandlerFunc(v1Ctrl.HandleItemsGetAll(), userMW...))
r.Post("/items", chain.ToHandlerFunc(v1Ctrl.HandleItemsCreate(), userMW...))
r.Post("/items/import", chain.ToHandlerFunc(v1Ctrl.HandleItemsImport(), userMW...))
@@ -137,10 +154,12 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
r.Delete("/items/{id}", chain.ToHandlerFunc(v1Ctrl.HandleItemDelete(), userMW...))
r.Post("/items/{id}/duplicate", chain.ToHandlerFunc(v1Ctrl.HandleItemDuplicate(), userMW...))
+ // Item attachment endpoints
r.Post("/items/{id}/attachments", chain.ToHandlerFunc(v1Ctrl.HandleItemAttachmentCreate(), userMW...))
r.Put("/items/{id}/attachments/{attachment_id}", chain.ToHandlerFunc(v1Ctrl.HandleItemAttachmentUpdate(), userMW...))
r.Delete("/items/{id}/attachments/{attachment_id}", chain.ToHandlerFunc(v1Ctrl.HandleItemAttachmentDelete(), userMW...))
+ // Item maintenance endpoints
r.Get("/items/{id}/maintenance", chain.ToHandlerFunc(v1Ctrl.HandleMaintenanceLogGet(), userMW...))
r.Post("/items/{id}/maintenance", chain.ToHandlerFunc(v1Ctrl.HandleMaintenanceEntryCreate(), userMW...))
@@ -169,6 +188,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
// Asset-Like endpoints
assetMW := []errchain.Middleware{
a.mwAuthToken,
+ a.mwTenant,
a.mwRoles(RoleModeOr, authroles.RoleUser.String(), authroles.RoleAttachments.String()),
}
diff --git a/backend/app/api/static/docs/docs.go b/backend/app/api/static/docs/docs.go
index d08de9b6..c2ce3d4b 100644
--- a/backend/app/api/static/docs/docs.go
+++ b/backend/app/api/static/docs/docs.go
@@ -285,9 +285,113 @@ const docTemplate = `{
}
}
}
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Create Group",
+ "parameters": [
+ {
+ "description": "Create group request",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.CreateRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.Group"
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group",
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/all": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Groups",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.Group"
+ }
+ }
+ }
+ }
}
},
"/v1/groups/invitations": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Invitations",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.GroupInvitation"
+ }
+ }
+ }
+ }
+ },
"post": {
"security": [
{
@@ -322,6 +426,154 @@ const docTemplate = `{
}
}
},
+ "/v1/groups/invitations/{id}": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Accept Group Invitation",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Invitation Token",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/v1.GroupAcceptInvitationResponse"
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group Invitation",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Invitation ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Members",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.UserSummary"
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Add User to Group",
+ "parameters": [
+ {
+ "description": "User ID",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.GroupMemberAdd"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members/{user_id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Remove User from Group",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "User ID",
+ "name": "user_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/groups/statistics": {
"get": {
"security": [
@@ -3529,6 +3781,10 @@ const docTemplate = `{
"description": "CreatedAt holds the value of the \"created_at\" field.",
"type": "string"
},
+ "default_group_id": {
+ "description": "DefaultGroupID holds the value of the \"default_group_id\" field.",
+ "type": "string"
+ },
"edges": {
"description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserQuery when eager-loading is set.",
"allOf": [
@@ -3589,13 +3845,12 @@ const docTemplate = `{
"$ref": "#/definitions/ent.AuthTokens"
}
},
- "group": {
- "description": "Group holds the value of the group edge.",
- "allOf": [
- {
- "$ref": "#/definitions/ent.Group"
- }
- ]
+ "groups": {
+ "description": "Groups holds the value of the groups edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/ent.Group"
+ }
},
"notifiers": {
"description": "Notifiers holds the value of the notifiers edge.",
@@ -3689,6 +3944,23 @@ const docTemplate = `{
}
}
},
+ "repo.GroupInvitation": {
+ "type": "object",
+ "properties": {
+ "expiresAt": {
+ "type": "string"
+ },
+ "group": {
+ "$ref": "#/definitions/repo.Group"
+ },
+ "id": {
+ "type": "string"
+ },
+ "uses": {
+ "type": "integer"
+ }
+ }
+ },
"repo.GroupStatistics": {
"type": "object",
"properties": {
@@ -4906,14 +5178,17 @@ const docTemplate = `{
"repo.UserOut": {
"type": "object",
"properties": {
- "email": {
+ "defaultGroupId": {
"type": "string"
},
- "groupId": {
+ "email": {
"type": "string"
},
- "groupName": {
- "type": "string"
+ "groupIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
},
"id": {
"type": "string"
@@ -4935,6 +5210,23 @@ const docTemplate = `{
}
}
},
+ "repo.UserSummary": {
+ "type": "object",
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "isOwner": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"repo.UserUpdate": {
"type": "object",
"properties": {
@@ -5104,6 +5396,28 @@ const docTemplate = `{
}
}
},
+ "v1.CreateRequest": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ }
+ },
+ "v1.GroupAcceptInvitationResponse": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"v1.GroupInvitation": {
"type": "object",
"properties": {
@@ -5134,6 +5448,17 @@ const docTemplate = `{
}
}
},
+ "v1.GroupMemberAdd": {
+ "type": "object",
+ "required": [
+ "userId"
+ ],
+ "properties": {
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"v1.ItemAttachmentToken": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/openapi-3.json b/backend/app/api/static/docs/openapi-3.json
index f4ce81bf..58eb9a09 100644
--- a/backend/app/api/static/docs/openapi-3.json
+++ b/backend/app/api/static/docs/openapi-3.json
@@ -289,9 +289,113 @@
}
}
}
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Create Group",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/v1.CreateRequest"
+ }
+ }
+ },
+ "description": "Create group request",
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "Created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/repo.Group"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group",
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/all": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Groups",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/repo.Group"
+ }
+ }
+ }
+ }
+ }
+ }
}
},
"/v1/groups/invitations": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Invitations",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/repo.GroupInvitation"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"post": {
"security": [
{
@@ -327,6 +431,153 @@
}
}
},
+ "/v1/groups/invitations/{id}": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Accept Group Invitation",
+ "parameters": [
+ {
+ "description": "Invitation Token",
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/v1.GroupAcceptInvitationResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group Invitation",
+ "parameters": [
+ {
+ "description": "Invitation ID",
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Members",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/repo.UserSummary"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Add User to Group",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/v1.GroupMemberAdd"
+ }
+ }
+ },
+ "description": "User ID",
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members/{user_id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Remove User from Group",
+ "parameters": [
+ {
+ "description": "User ID",
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/groups/statistics": {
"get": {
"security": [
@@ -3727,6 +3978,10 @@
"description": "CreatedAt holds the value of the \"created_at\" field.",
"type": "string"
},
+ "default_group_id": {
+ "description": "DefaultGroupID holds the value of the \"default_group_id\" field.",
+ "type": "string"
+ },
"edges": {
"description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserQuery when eager-loading is set.",
"allOf": [
@@ -3787,13 +4042,12 @@
"$ref": "#/components/schemas/ent.AuthTokens"
}
},
- "group": {
- "description": "Group holds the value of the group edge.",
- "allOf": [
- {
- "$ref": "#/components/schemas/ent.Group"
- }
- ]
+ "groups": {
+ "description": "Groups holds the value of the groups edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ent.Group"
+ }
},
"notifiers": {
"description": "Notifiers holds the value of the notifiers edge.",
@@ -3887,6 +4141,23 @@
}
}
},
+ "repo.GroupInvitation": {
+ "type": "object",
+ "properties": {
+ "expiresAt": {
+ "type": "string"
+ },
+ "group": {
+ "$ref": "#/components/schemas/repo.Group"
+ },
+ "id": {
+ "type": "string"
+ },
+ "uses": {
+ "type": "integer"
+ }
+ }
+ },
"repo.GroupStatistics": {
"type": "object",
"properties": {
@@ -5104,14 +5375,17 @@
"repo.UserOut": {
"type": "object",
"properties": {
- "email": {
+ "defaultGroupId": {
"type": "string"
},
- "groupId": {
+ "email": {
"type": "string"
},
- "groupName": {
- "type": "string"
+ "groupIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
},
"id": {
"type": "string"
@@ -5133,6 +5407,23 @@
}
}
},
+ "repo.UserSummary": {
+ "type": "object",
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "isOwner": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"repo.UserUpdate": {
"type": "object",
"properties": {
@@ -5302,6 +5593,28 @@
}
}
},
+ "v1.CreateRequest": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ }
+ },
+ "v1.GroupAcceptInvitationResponse": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"v1.GroupInvitation": {
"type": "object",
"properties": {
@@ -5332,6 +5645,17 @@
}
}
},
+ "v1.GroupMemberAdd": {
+ "type": "object",
+ "required": [
+ "userId"
+ ],
+ "properties": {
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"v1.ItemAttachmentToken": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/openapi-3.yaml b/backend/app/api/static/docs/openapi-3.yaml
index eda39cf7..da6563b2 100644
--- a/backend/app/api/static/docs/openapi-3.yaml
+++ b/backend/app/api/static/docs/openapi-3.yaml
@@ -170,7 +170,67 @@ paths:
application/json:
schema:
$ref: "#/components/schemas/repo.Group"
+ post:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Create Group
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/v1.CreateRequest"
+ description: Create group request
+ required: true
+ responses:
+ "201":
+ description: Created
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/repo.Group"
+ delete:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Delete Group
+ responses:
+ "204":
+ description: No Content
+ /v1/groups/all:
+ get:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Get All Groups
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/repo.Group"
/v1/groups/invitations:
+ get:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Get All Group Invitations
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/repo.GroupInvitation"
post:
security:
- Bearer: []
@@ -191,6 +251,92 @@ paths:
application/json:
schema:
$ref: "#/components/schemas/v1.GroupInvitation"
+ "/v1/groups/invitations/{id}":
+ post:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Accept Group Invitation
+ parameters:
+ - description: Invitation Token
+ name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/v1.GroupAcceptInvitationResponse"
+ delete:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Delete Group Invitation
+ parameters:
+ - description: Invitation ID
+ name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "204":
+ description: No Content
+ /v1/groups/members:
+ get:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Get All Group Members
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/repo.UserSummary"
+ post:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Add User to Group
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/v1.GroupMemberAdd"
+ description: User ID
+ required: true
+ responses:
+ "204":
+ description: No Content
+ "/v1/groups/members/{user_id}":
+ delete:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Remove User from Group
+ parameters:
+ - description: User ID
+ name: user_id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "204":
+ description: No Content
/v1/groups/statistics:
get:
security:
@@ -2322,6 +2468,9 @@ components:
created_at:
description: CreatedAt holds the value of the "created_at" field.
type: string
+ default_group_id:
+ description: DefaultGroupID holds the value of the "default_group_id" field.
+ type: string
edges:
description: >-
Edges holds the relations/edges for other nodes in the graph.
@@ -2365,10 +2514,11 @@ components:
type: array
items:
$ref: "#/components/schemas/ent.AuthTokens"
- group:
- description: Group holds the value of the group edge.
- allOf:
- - $ref: "#/components/schemas/ent.Group"
+ groups:
+ description: Groups holds the value of the groups edge.
+ type: array
+ items:
+ $ref: "#/components/schemas/ent.Group"
notifiers:
description: Notifiers holds the value of the notifiers edge.
type: array
@@ -2431,6 +2581,17 @@ components:
type: string
updatedAt:
type: string
+ repo.GroupInvitation:
+ type: object
+ properties:
+ expiresAt:
+ type: string
+ group:
+ $ref: "#/components/schemas/repo.Group"
+ id:
+ type: string
+ uses:
+ type: integer
repo.GroupStatistics:
type: object
properties:
@@ -3264,12 +3425,14 @@ components:
repo.UserOut:
type: object
properties:
- email:
- type: string
- groupId:
+ defaultGroupId:
type: string
- groupName:
+ email:
type: string
+ groupIds:
+ type: array
+ items:
+ type: string
id:
type: string
isOwner:
@@ -3282,6 +3445,17 @@ components:
type: string
oidcSubject:
type: string
+ repo.UserSummary:
+ type: object
+ properties:
+ email:
+ type: string
+ id:
+ type: string
+ isOwner:
+ type: boolean
+ name:
+ type: string
repo.UserUpdate:
type: object
properties:
@@ -3393,6 +3567,20 @@ components:
type: string
new:
type: string
+ v1.CreateRequest:
+ type: object
+ required:
+ - name
+ properties:
+ name:
+ type: string
+ v1.GroupAcceptInvitationResponse:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
v1.GroupInvitation:
type: object
properties:
@@ -3413,6 +3601,13 @@ components:
type: integer
maximum: 100
minimum: 1
+ v1.GroupMemberAdd:
+ type: object
+ required:
+ - userId
+ properties:
+ userId:
+ type: string
v1.ItemAttachmentToken:
type: object
properties:
diff --git a/backend/app/api/static/docs/swagger.json b/backend/app/api/static/docs/swagger.json
index cb5a49f4..b2edcda4 100644
--- a/backend/app/api/static/docs/swagger.json
+++ b/backend/app/api/static/docs/swagger.json
@@ -283,9 +283,113 @@
}
}
}
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Create Group",
+ "parameters": [
+ {
+ "description": "Create group request",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.CreateRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.Group"
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group",
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/all": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Groups",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.Group"
+ }
+ }
+ }
+ }
}
},
"/v1/groups/invitations": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Invitations",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.GroupInvitation"
+ }
+ }
+ }
+ }
+ },
"post": {
"security": [
{
@@ -320,6 +424,154 @@
}
}
},
+ "/v1/groups/invitations/{id}": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Accept Group Invitation",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Invitation Token",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/v1.GroupAcceptInvitationResponse"
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group Invitation",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Invitation ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Members",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.UserSummary"
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Add User to Group",
+ "parameters": [
+ {
+ "description": "User ID",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.GroupMemberAdd"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members/{user_id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Remove User from Group",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "User ID",
+ "name": "user_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/groups/statistics": {
"get": {
"security": [
@@ -3527,6 +3779,10 @@
"description": "CreatedAt holds the value of the \"created_at\" field.",
"type": "string"
},
+ "default_group_id": {
+ "description": "DefaultGroupID holds the value of the \"default_group_id\" field.",
+ "type": "string"
+ },
"edges": {
"description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserQuery when eager-loading is set.",
"allOf": [
@@ -3587,13 +3843,12 @@
"$ref": "#/definitions/ent.AuthTokens"
}
},
- "group": {
- "description": "Group holds the value of the group edge.",
- "allOf": [
- {
- "$ref": "#/definitions/ent.Group"
- }
- ]
+ "groups": {
+ "description": "Groups holds the value of the groups edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/ent.Group"
+ }
},
"notifiers": {
"description": "Notifiers holds the value of the notifiers edge.",
@@ -3687,6 +3942,23 @@
}
}
},
+ "repo.GroupInvitation": {
+ "type": "object",
+ "properties": {
+ "expiresAt": {
+ "type": "string"
+ },
+ "group": {
+ "$ref": "#/definitions/repo.Group"
+ },
+ "id": {
+ "type": "string"
+ },
+ "uses": {
+ "type": "integer"
+ }
+ }
+ },
"repo.GroupStatistics": {
"type": "object",
"properties": {
@@ -4904,14 +5176,17 @@
"repo.UserOut": {
"type": "object",
"properties": {
- "email": {
+ "defaultGroupId": {
"type": "string"
},
- "groupId": {
+ "email": {
"type": "string"
},
- "groupName": {
- "type": "string"
+ "groupIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
},
"id": {
"type": "string"
@@ -4933,6 +5208,23 @@
}
}
},
+ "repo.UserSummary": {
+ "type": "object",
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "isOwner": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"repo.UserUpdate": {
"type": "object",
"properties": {
@@ -5102,6 +5394,28 @@
}
}
},
+ "v1.CreateRequest": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ }
+ },
+ "v1.GroupAcceptInvitationResponse": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"v1.GroupInvitation": {
"type": "object",
"properties": {
@@ -5132,6 +5446,17 @@
}
}
},
+ "v1.GroupMemberAdd": {
+ "type": "object",
+ "required": [
+ "userId"
+ ],
+ "properties": {
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"v1.ItemAttachmentToken": {
"type": "object",
"properties": {
diff --git a/backend/app/api/static/docs/swagger.yaml b/backend/app/api/static/docs/swagger.yaml
index 0d234331..96c17e8c 100644
--- a/backend/app/api/static/docs/swagger.yaml
+++ b/backend/app/api/static/docs/swagger.yaml
@@ -719,6 +719,9 @@ definitions:
created_at:
description: CreatedAt holds the value of the "created_at" field.
type: string
+ default_group_id:
+ description: DefaultGroupID holds the value of the "default_group_id" field.
+ type: string
edges:
allOf:
- $ref: '#/definitions/ent.UserEdges'
@@ -761,10 +764,11 @@ definitions:
items:
$ref: '#/definitions/ent.AuthTokens'
type: array
- group:
- allOf:
- - $ref: '#/definitions/ent.Group'
- description: Group holds the value of the group edge.
+ groups:
+ description: Groups holds the value of the groups edge.
+ items:
+ $ref: '#/definitions/ent.Group'
+ type: array
notifiers:
description: Notifiers holds the value of the notifiers edge.
items:
@@ -828,6 +832,17 @@ definitions:
updatedAt:
type: string
type: object
+ repo.GroupInvitation:
+ properties:
+ expiresAt:
+ type: string
+ group:
+ $ref: '#/definitions/repo.Group'
+ id:
+ type: string
+ uses:
+ type: integer
+ type: object
repo.GroupStatistics:
properties:
totalItemPrice:
@@ -1660,12 +1675,14 @@ definitions:
type: object
repo.UserOut:
properties:
- email:
+ defaultGroupId:
type: string
- groupId:
- type: string
- groupName:
+ email:
type: string
+ groupIds:
+ items:
+ type: string
+ type: array
id:
type: string
isOwner:
@@ -1679,6 +1696,17 @@ definitions:
oidcSubject:
type: string
type: object
+ repo.UserSummary:
+ properties:
+ email:
+ type: string
+ id:
+ type: string
+ isOwner:
+ type: boolean
+ name:
+ type: string
+ type: object
repo.UserUpdate:
properties:
email:
@@ -1790,6 +1818,20 @@ definitions:
new:
type: string
type: object
+ v1.CreateRequest:
+ properties:
+ name:
+ type: string
+ required:
+ - name
+ type: object
+ v1.GroupAcceptInvitationResponse:
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ type: object
v1.GroupInvitation:
properties:
expiresAt:
@@ -1810,6 +1852,13 @@ definitions:
required:
- uses
type: object
+ v1.GroupMemberAdd:
+ properties:
+ userId:
+ type: string
+ required:
+ - userId
+ type: object
v1.ItemAttachmentToken:
properties:
token:
@@ -2025,6 +2074,17 @@ paths:
tags:
- Base
/v1/groups:
+ delete:
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Delete Group
+ tags:
+ - Group
get:
produces:
- application/json
@@ -2038,6 +2098,26 @@ paths:
summary: Get Group
tags:
- Group
+ post:
+ parameters:
+ - description: Create group request
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/v1.CreateRequest'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: Created
+ schema:
+ $ref: '#/definitions/repo.Group'
+ security:
+ - Bearer: []
+ summary: Create Group
+ tags:
+ - Group
put:
parameters:
- description: User Data
@@ -2058,7 +2138,38 @@ paths:
summary: Update Group
tags:
- Group
+ /v1/groups/all:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.Group'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Groups
+ tags:
+ - Group
/v1/groups/invitations:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.GroupInvitation'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Group Invitations
+ tags:
+ - Group
post:
parameters:
- description: User Data
@@ -2079,6 +2190,95 @@ paths:
summary: Create Group Invitation
tags:
- Group
+ /v1/groups/invitations/{id}:
+ delete:
+ parameters:
+ - description: Invitation ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Delete Group Invitation
+ tags:
+ - Group
+ post:
+ parameters:
+ - description: Invitation Token
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ $ref: '#/definitions/v1.GroupAcceptInvitationResponse'
+ security:
+ - Bearer: []
+ summary: Accept Group Invitation
+ tags:
+ - Group
+ /v1/groups/members:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.UserSummary'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Group Members
+ tags:
+ - Group
+ post:
+ parameters:
+ - description: User ID
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/v1.GroupMemberAdd'
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Add User to Group
+ tags:
+ - Group
+ /v1/groups/members/{user_id}:
+ delete:
+ parameters:
+ - description: User ID
+ in: path
+ name: user_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Remove User from Group
+ tags:
+ - Group
/v1/groups/statistics:
get:
produces:
diff --git a/backend/go.sum b/backend/go.sum
index 6f11d8f1..0d766402 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -325,6 +325,8 @@ 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.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
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.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
@@ -347,6 +349,8 @@ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOF
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/olahol/melody v1.4.0 h1:Pa5SdeZL/zXPi1tJuMAPDbl4n3gQOThSL6G1p4qZ4SI=
github.com/olahol/melody v1.4.0/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/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts=
github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE=
@@ -389,6 +393,10 @@ github.com/shirou/gopsutil/v4 v4.25.11 h1:X53gB7muL9Gnwwo2evPSE+SfOrltMoR6V3xJAX
github.com/shirou/gopsutil/v4 v4.25.11/go.mod h1:EivAfP5x2EhLp2ovdpKSozecVXn1TmuG7SMzs/Wh4PU=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+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/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
diff --git a/backend/internal/core/services/contexts.go b/backend/internal/core/services/contexts.go
index 096b3866..8f1a4153 100644
--- a/backend/internal/core/services/contexts.go
+++ b/backend/internal/core/services/contexts.go
@@ -14,6 +14,7 @@ type contextKeys struct {
var (
ContextUser = &contextKeys{name: "User"}
ContextUserToken = &contextKeys{name: "UserToken"}
+ ContextTenant = &contextKeys{name: "Tenant"}
)
type Context struct {
@@ -33,10 +34,20 @@ type Context struct {
// This extracts the users from the context and embeds it into the ServiceContext struct
func NewContext(ctx context.Context) Context {
user := UseUserCtx(ctx)
+ gid := UseTenantCtx(ctx)
+
+ var uid uuid.UUID
+ if user != nil {
+ uid = user.ID
+ if gid == uuid.Nil {
+ gid = user.DefaultGroupID
+ }
+ }
+
return Context{
Context: ctx,
- UID: user.ID,
- GID: user.GroupID,
+ UID: uid,
+ GID: gid,
User: user,
}
}
@@ -64,3 +75,17 @@ func UseTokenCtx(ctx context.Context) string {
}
return ""
}
+
+// UseTenantCtx is a helper function that returns the tenant group ID from the context.
+// Returns uuid.Nil if not set.
+func UseTenantCtx(ctx context.Context) uuid.UUID {
+ if val := ctx.Value(ContextTenant); val != nil {
+ return val.(uuid.UUID)
+ }
+ return uuid.Nil
+}
+
+// SetTenantCtx is a helper function that sets the ContextTenant in the context.
+func SetTenantCtx(ctx context.Context, tenantID uuid.UUID) context.Context {
+ return context.WithValue(ctx, ContextTenant, tenantID)
+}
diff --git a/backend/internal/core/services/main_test.go b/backend/internal/core/services/main_test.go
index 43d5921a..56dafb99 100644
--- a/backend/internal/core/services/main_test.go
+++ b/backend/internal/core/services/main_test.go
@@ -2,11 +2,13 @@ package services
import (
"context"
- "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
"log"
"os"
"testing"
+ "github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
+
_ "github.com/mattn/go-sqlite3"
"github.com/sysadminsmedia/homebox/backend/internal/core/currencies"
"github.com/sysadminsmedia/homebox/backend/internal/core/services/reporting/eventbus"
@@ -33,18 +35,18 @@ func bootstrap() {
ctx = context.Background()
)
- tGroup, err = tRepos.Groups.GroupCreate(ctx, "test-group")
+ tGroup, err = tRepos.Groups.GroupCreate(ctx, "test-group", uuid.Nil)
if err != nil {
log.Fatal(err)
}
password := fk.Str(10)
tUser, err = tRepos.Users.Create(ctx, repo.UserCreate{
- Name: fk.Str(10),
- Email: fk.Email(),
- Password: &password,
- IsSuperuser: fk.Bool(),
- GroupID: tGroup.ID,
+ Name: fk.Str(10),
+ Email: fk.Email(),
+ Password: &password,
+ IsSuperuser: fk.Bool(),
+ DefaultGroupID: tGroup.ID,
})
if err != nil {
log.Fatal(err)
diff --git a/backend/internal/core/services/service_background.go b/backend/internal/core/services/service_background.go
index 54710336..b3c65154 100644
--- a/backend/internal/core/services/service_background.go
+++ b/backend/internal/core/services/service_background.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/containrrr/shoutrrr"
+ "github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
"github.com/sysadminsmedia/homebox/backend/internal/data/types"
@@ -25,7 +26,7 @@ type BackgroundService struct {
func (svc *BackgroundService) SendNotifiersToday(ctx context.Context) error {
// Get All Groups
- groups, err := svc.repos.Groups.GetAllGroups(ctx)
+ groups, err := svc.repos.Groups.GetAllGroups(ctx, uuid.Nil)
if err != nil {
return err
}
diff --git a/backend/internal/core/services/service_group.go b/backend/internal/core/services/service_group.go
index 7b90fa29..25126c7e 100644
--- a/backend/internal/core/services/service_group.go
+++ b/backend/internal/core/services/service_group.go
@@ -4,6 +4,7 @@ import (
"errors"
"time"
+ "github.com/google/uuid"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
"github.com/sysadminsmedia/homebox/backend/pkgs/hasher"
)
@@ -14,7 +15,7 @@ type GroupService struct {
func (svc *GroupService) UpdateGroup(ctx Context, data repo.GroupUpdate) (repo.Group, error) {
if data.Name == "" {
- data.Name = ctx.User.GroupName
+ return repo.Group{}, errors.New("group name cannot be empty")
}
if data.Currency == "" {
@@ -24,6 +25,22 @@ func (svc *GroupService) UpdateGroup(ctx Context, data repo.GroupUpdate) (repo.G
return svc.repos.Groups.GroupUpdate(ctx.Context, ctx.GID, data)
}
+func (svc *GroupService) CreateGroup(ctx Context, name string) (repo.Group, error) {
+ if name == "" {
+ return repo.Group{}, errors.New("group name cannot be empty")
+ }
+
+ if ctx.UID == uuid.Nil {
+ return repo.Group{}, errors.New("user ID cannot be empty when creating a group")
+ }
+
+ return svc.repos.Groups.GroupCreate(ctx.Context, name, ctx.UID)
+}
+
+func (svc *GroupService) DeleteGroup(ctx Context) error {
+ return svc.repos.Groups.GroupDelete(ctx.Context, ctx.GID)
+}
+
func (svc *GroupService) NewInvitation(ctx Context, uses int, expiresAt time.Time) (string, error) {
token := hasher.GenerateToken()
@@ -38,3 +55,28 @@ func (svc *GroupService) NewInvitation(ctx Context, uses int, expiresAt time.Tim
return token.Raw, nil
}
+
+func (svc *GroupService) AddMember(ctx Context, userID uuid.UUID) error {
+ if userID == uuid.Nil {
+ return errors.New("user ID cannot be empty")
+ }
+
+ return svc.repos.Groups.AddMember(ctx.Context, ctx.GID, userID)
+}
+
+func (svc *GroupService) RemoveMember(ctx Context, userID uuid.UUID) error {
+ if userID == uuid.Nil {
+ return errors.New("user ID cannot be empty")
+ }
+
+ return svc.repos.Groups.RemoveMember(ctx.Context, ctx.GID, userID)
+}
+
+func (svc *GroupService) DeleteInvitation(ctx Context, id uuid.UUID) error {
+ return svc.repos.Groups.InvitationDelete(ctx.Context, ctx.GID, id)
+}
+
+func (svc *GroupService) AcceptInvitation(ctx Context, token string) (repo.Group, error) {
+ hashedToken := hasher.HashToken(token)
+ return svc.repos.Groups.InvitationAccept(ctx.Context, hashedToken, ctx.UID)
+}
diff --git a/backend/internal/core/services/service_items_attachments.go b/backend/internal/core/services/service_items_attachments.go
index 4ce0decc..e5387544 100644
--- a/backend/internal/core/services/service_items_attachments.go
+++ b/backend/internal/core/services/service_items_attachments.go
@@ -2,12 +2,13 @@ package services
import (
"context"
+ "io"
+
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
- "io"
)
func (svc *ItemService) AttachmentPath(ctx context.Context, gid uuid.UUID, attachmentID uuid.UUID) (*ent.Attachment, error) {
@@ -56,9 +57,9 @@ func (svc *ItemService) AttachmentAdd(ctx Context, itemID uuid.UUID, filename st
return svc.repo.Items.GetOneByGroup(ctx, ctx.GID, itemID)
}
-func (svc *ItemService) AttachmentDelete(ctx context.Context, gid uuid.UUID, id uuid.UUID, attachmentID uuid.UUID) error {
+func (svc *ItemService) AttachmentDelete(ctx context.Context, gid uuid.UUID, attachmentID uuid.UUID) error {
// Delete the attachment
- err := svc.repo.Attachments.Delete(ctx, gid, id, attachmentID)
+ err := svc.repo.Attachments.Delete(ctx, gid, attachmentID)
if err != nil {
return err
}
diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.go
index 8b13a653..e63adb90 100644
--- a/backend/internal/core/services/service_user.go
+++ b/backend/internal/core/services/service_user.go
@@ -3,6 +3,7 @@ package services
import (
"context"
"errors"
+ "fmt"
"strings"
"time"
@@ -64,7 +65,7 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
case "":
log.Debug().Msg("creating new group")
creatingGroup = true
- group, err = svc.repos.Groups.GroupCreate(ctx, "Home")
+ group, err = svc.repos.Groups.GroupCreate(ctx, fmt.Sprintf("%ss' Home", data.Name), uuid.Nil)
if err != nil {
log.Err(err).Msg("Failed to create group")
return repo.UserOut{}, err
@@ -76,17 +77,29 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
log.Err(err).Msg("Failed to get invitation token")
return repo.UserOut{}, err
}
+
+ if token.ExpiresAt.Before(time.Now()) {
+ return repo.UserOut{}, errors.New("invitation expired")
+ }
+ if token.Uses <= 0 {
+ return repo.UserOut{}, errors.New("invitation used up")
+ }
+
group = token.Group
}
- hashed, _ := hasher.HashPassword(data.Password)
+ hashed, err := hasher.HashPassword(data.Password)
+ if err != nil {
+ log.Err(err).Msg("Failed to hash password")
+ return repo.UserOut{}, err
+ }
usrCreate := repo.UserCreate{
- Name: data.Name,
- Email: data.Email,
- Password: &hashed,
- IsSuperuser: false,
- GroupID: group.ID,
- IsOwner: creatingGroup,
+ Name: data.Name,
+ Email: data.Email,
+ Password: &hashed,
+ IsSuperuser: false,
+ DefaultGroupID: group.ID,
+ IsOwner: creatingGroup,
}
usr, err := svc.repos.Users.Create(ctx, usrCreate)
@@ -99,7 +112,7 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
if creatingGroup {
log.Debug().Msg("creating default labels")
for _, label := range defaultLabels() {
- _, err := svc.repos.Labels.Create(ctx, usr.GroupID, label)
+ _, err := svc.repos.Labels.Create(ctx, usr.DefaultGroupID, label)
if err != nil {
return repo.UserOut{}, err
}
@@ -107,7 +120,7 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
log.Debug().Msg("creating default locations")
for _, location := range defaultLocations() {
- _, err := svc.repos.Locations.Create(ctx, usr.GroupID, location)
+ _, err := svc.repos.Locations.Create(ctx, usr.DefaultGroupID, location)
if err != nil {
return repo.UserOut{}, err
}
@@ -117,7 +130,7 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
// Decrement the invitation token if it was used.
if token.ID != uuid.Nil {
log.Debug().Msg("decrementing invitation token")
- err = svc.repos.Groups.InvitationUpdate(ctx, token.ID, token.Uses-1)
+ err = svc.repos.Groups.InvitationDecrement(ctx, token.ID)
if err != nil {
log.Err(err).Msg("Failed to update invitation token")
return repo.UserOut{}, err
@@ -280,19 +293,19 @@ func (svc *UserService) LoginOIDC(ctx context.Context, issuer, subject, email, n
// registerOIDCUser creates a new user for OIDC authentication with issuer+subject identity.
func (svc *UserService) registerOIDCUser(ctx context.Context, issuer, subject, email, name string) (repo.UserOut, error) {
- group, err := svc.repos.Groups.GroupCreate(ctx, "Home")
+ group, err := svc.repos.Groups.GroupCreate(ctx, "Home", uuid.Nil)
if err != nil {
log.Err(err).Msg("Failed to create group for OIDC user")
return repo.UserOut{}, err
}
usrCreate := repo.UserCreate{
- Name: name,
- Email: email,
- Password: nil,
- IsSuperuser: false,
- GroupID: group.ID,
- IsOwner: true,
+ Name: name,
+ Email: email,
+ Password: nil,
+ IsSuperuser: false,
+ DefaultGroupID: group.ID,
+ IsOwner: true,
}
entUser, err := svc.repos.Users.CreateWithOIDC(ctx, usrCreate, issuer, subject)
@@ -369,3 +382,32 @@ func (svc *UserService) ChangePassword(ctx Context, current string, new string)
return true
}
+
+// EnsureUserPassword ensures that the user with the given email has the specified password. If the password does not match, it updates the user's password to the new value.
+// WARNING: This method bypasses normal checks, it should only be used for demos and/or superuser level administrative processes.
+func (svc *UserService) EnsureUserPassword(ctx context.Context, email, password string) error {
+ usr, err := svc.repos.Users.GetOneEmailNoEdges(ctx, email)
+ if err != nil {
+ return err
+ }
+ match := false
+ if usr.PasswordHash != "" {
+ match, _ = hasher.CheckPasswordHash(password, usr.PasswordHash)
+ }
+ if !match {
+ hash, herr := hasher.HashPassword(password)
+ if herr != nil {
+ return herr
+ }
+ if cerr := svc.repos.Users.ChangePassword(ctx, usr.ID, hash); cerr != nil {
+ return cerr
+ }
+ }
+ return nil
+}
+
+// ExistsByEmail returns true if a user with the given email exists.
+func (svc *UserService) ExistsByEmail(ctx context.Context, email string) bool {
+ _, err := svc.repos.Users.GetOneEmailNoEdges(ctx, email)
+ return err == nil
+}
diff --git a/backend/internal/data/ent/client.go b/backend/internal/data/ent/client.go
index 7cd5830c..5ecd1927 100644
--- a/backend/internal/data/ent/client.go
+++ b/backend/internal/data/ent/client.go
@@ -909,7 +909,7 @@ func (c *GroupClient) QueryUsers(_m *Group) *UserQuery {
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
- sqlgraph.Edge(sqlgraph.O2M, false, group.UsersTable, group.UsersColumn),
+ sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
@@ -2711,15 +2711,15 @@ func (c *UserClient) GetX(ctx context.Context, id uuid.UUID) *User {
return obj
}
-// QueryGroup queries the group edge of a User.
-func (c *UserClient) QueryGroup(_m *User) *GroupQuery {
+// QueryGroups queries the groups edge of a User.
+func (c *UserClient) QueryGroups(_m *User) *GroupQuery {
query := (&GroupClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
- sqlgraph.Edge(sqlgraph.M2O, true, user.GroupTable, user.GroupColumn),
+ sqlgraph.Edge(sqlgraph.M2M, false, user.GroupsTable, user.GroupsPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
diff --git a/backend/internal/data/ent/group/group.go b/backend/internal/data/ent/group/group.go
index 80dc3398..68b49a07 100644
--- a/backend/internal/data/ent/group/group.go
+++ b/backend/internal/data/ent/group/group.go
@@ -39,13 +39,11 @@ const (
EdgeItemTemplates = "item_templates"
// Table holds the table name of the group in the database.
Table = "groups"
- // UsersTable is the table that holds the users relation/edge.
- UsersTable = "users"
+ // UsersTable is the table that holds the users relation/edge. The primary key declared below.
+ UsersTable = "user_groups"
// UsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UsersInverseTable = "users"
- // UsersColumn is the table column denoting the users relation/edge.
- UsersColumn = "group_users"
// LocationsTable is the table that holds the locations relation/edge.
LocationsTable = "locations"
// LocationsInverseTable is the table name for the Location entity.
@@ -99,6 +97,12 @@ var Columns = []string{
FieldCurrency,
}
+var (
+ // UsersPrimaryKey and UsersColumn2 are the table columns denoting the
+ // primary key for the users relation (M2M).
+ UsersPrimaryKey = []string{"user_id", "group_id"}
+)
+
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
@@ -253,7 +257,7 @@ func newUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
- sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
+ sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...),
)
}
func newLocationsStep() *sqlgraph.Step {
diff --git a/backend/internal/data/ent/group/where.go b/backend/internal/data/ent/group/where.go
index fec4b27c..f0c3caf4 100644
--- a/backend/internal/data/ent/group/where.go
+++ b/backend/internal/data/ent/group/where.go
@@ -291,7 +291,7 @@ func HasUsers() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
- sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
+ sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
diff --git a/backend/internal/data/ent/group_create.go b/backend/internal/data/ent/group_create.go
index 9eb4bac1..32e46319 100644
--- a/backend/internal/data/ent/group_create.go
+++ b/backend/internal/data/ent/group_create.go
@@ -320,10 +320,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
}
if nodes := _c.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.O2M,
- Inverse: false,
+ Rel: sqlgraph.M2M,
+ Inverse: true,
Table: group.UsersTable,
- Columns: []string{group.UsersColumn},
+ Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
diff --git a/backend/internal/data/ent/group_query.go b/backend/internal/data/ent/group_query.go
index 20124988..61fda631 100644
--- a/backend/internal/data/ent/group_query.go
+++ b/backend/internal/data/ent/group_query.go
@@ -88,7 +88,7 @@ func (_q *GroupQuery) QueryUsers() *UserQuery {
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
- sqlgraph.Edge(sqlgraph.O2M, false, group.UsersTable, group.UsersColumn),
+ sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
@@ -671,33 +671,63 @@ func (_q *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
}
func (_q *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error {
- fks := make([]driver.Value, 0, len(nodes))
- nodeids := make(map[uuid.UUID]*Group)
- for i := range nodes {
- fks = append(fks, nodes[i].ID)
- nodeids[nodes[i].ID] = nodes[i]
+ edgeIDs := make([]driver.Value, len(nodes))
+ byID := make(map[uuid.UUID]*Group)
+ nids := make(map[uuid.UUID]map[*Group]struct{})
+ for i, node := range nodes {
+ edgeIDs[i] = node.ID
+ byID[node.ID] = node
if init != nil {
- init(nodes[i])
+ init(node)
}
}
- query.withFKs = true
- query.Where(predicate.User(func(s *sql.Selector) {
- s.Where(sql.InValues(s.C(group.UsersColumn), fks...))
- }))
- neighbors, err := query.All(ctx)
+ query.Where(func(s *sql.Selector) {
+ joinT := sql.Table(group.UsersTable)
+ s.Join(joinT).On(s.C(user.FieldID), joinT.C(group.UsersPrimaryKey[0]))
+ s.Where(sql.InValues(joinT.C(group.UsersPrimaryKey[1]), edgeIDs...))
+ columns := s.SelectedColumns()
+ s.Select(joinT.C(group.UsersPrimaryKey[1]))
+ s.AppendSelect(columns...)
+ s.SetDistinct(false)
+ })
+ if err := query.prepareQuery(ctx); err != nil {
+ return err
+ }
+ qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
+ return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
+ assign := spec.Assign
+ values := spec.ScanValues
+ spec.ScanValues = func(columns []string) ([]any, error) {
+ values, err := values(columns[1:])
+ if err != nil {
+ return nil, err
+ }
+ return append([]any{new(uuid.UUID)}, values...), nil
+ }
+ spec.Assign = func(columns []string, values []any) error {
+ outValue := *values[0].(*uuid.UUID)
+ inValue := *values[1].(*uuid.UUID)
+ if nids[inValue] == nil {
+ nids[inValue] = map[*Group]struct{}{byID[outValue]: {}}
+ return assign(columns[1:], values[1:])
+ }
+ nids[inValue][byID[outValue]] = struct{}{}
+ return nil
+ }
+ })
+ })
+ neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
- fk := n.group_users
- if fk == nil {
- return fmt.Errorf(`foreign-key "group_users" is nil for node %v`, n.ID)
- }
- node, ok := nodeids[*fk]
+ nodes, ok := nids[n.ID]
if !ok {
- return fmt.Errorf(`unexpected referenced foreign-key "group_users" returned %v for node %v`, *fk, n.ID)
+ return fmt.Errorf(`unexpected "users" node returned %v`, n.ID)
+ }
+ for kn := range nodes {
+ assign(kn, n)
}
- assign(node, n)
}
return nil
}
diff --git a/backend/internal/data/ent/group_update.go b/backend/internal/data/ent/group_update.go
index d0190d49..2258b8ea 100644
--- a/backend/internal/data/ent/group_update.go
+++ b/backend/internal/data/ent/group_update.go
@@ -396,10 +396,10 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.O2M,
- Inverse: false,
+ Rel: sqlgraph.M2M,
+ Inverse: true,
Table: group.UsersTable,
- Columns: []string{group.UsersColumn},
+ Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
@@ -409,10 +409,10 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.O2M,
- Inverse: false,
+ Rel: sqlgraph.M2M,
+ Inverse: true,
Table: group.UsersTable,
- Columns: []string{group.UsersColumn},
+ Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
@@ -425,10 +425,10 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.O2M,
- Inverse: false,
+ Rel: sqlgraph.M2M,
+ Inverse: true,
Table: group.UsersTable,
- Columns: []string{group.UsersColumn},
+ Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
@@ -1119,10 +1119,10 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
}
if _u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.O2M,
- Inverse: false,
+ Rel: sqlgraph.M2M,
+ Inverse: true,
Table: group.UsersTable,
- Columns: []string{group.UsersColumn},
+ Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
@@ -1132,10 +1132,10 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
}
if nodes := _u.mutation.RemovedUsersIDs(); len(nodes) > 0 && !_u.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.O2M,
- Inverse: false,
+ Rel: sqlgraph.M2M,
+ Inverse: true,
Table: group.UsersTable,
- Columns: []string{group.UsersColumn},
+ Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
@@ -1148,10 +1148,10 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
}
if nodes := _u.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.O2M,
- Inverse: false,
+ Rel: sqlgraph.M2M,
+ Inverse: true,
Table: group.UsersTable,
- Columns: []string{group.UsersColumn},
+ Columns: group.UsersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
diff --git a/backend/internal/data/ent/migrate/schema.go b/backend/internal/data/ent/migrate/schema.go
index ef6161d8..743d9b27 100644
--- a/backend/internal/data/ent/migrate/schema.go
+++ b/backend/internal/data/ent/migrate/schema.go
@@ -468,21 +468,13 @@ var (
{Name: "activated_on", Type: field.TypeTime, Nullable: true},
{Name: "oidc_issuer", Type: field.TypeString, Nullable: true},
{Name: "oidc_subject", Type: field.TypeString, Nullable: true},
- {Name: "group_users", Type: field.TypeUUID},
+ {Name: "default_group_id", Type: field.TypeUUID, Nullable: true},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
- ForeignKeys: []*schema.ForeignKey{
- {
- Symbol: "users_groups_users",
- Columns: []*schema.Column{UsersColumns[12]},
- RefColumns: []*schema.Column{GroupsColumns[0]},
- OnDelete: schema.Cascade,
- },
- },
Indexes: []*schema.Index{
{
Name: "user_oidc_issuer_oidc_subject",
@@ -516,6 +508,31 @@ var (
},
},
}
+ // UserGroupsColumns holds the columns for the "user_groups" table.
+ UserGroupsColumns = []*schema.Column{
+ {Name: "user_id", Type: field.TypeUUID},
+ {Name: "group_id", Type: field.TypeUUID},
+ }
+ // UserGroupsTable holds the schema information for the "user_groups" table.
+ UserGroupsTable = &schema.Table{
+ Name: "user_groups",
+ Columns: UserGroupsColumns,
+ PrimaryKey: []*schema.Column{UserGroupsColumns[0], UserGroupsColumns[1]},
+ ForeignKeys: []*schema.ForeignKey{
+ {
+ Symbol: "user_groups_user_id",
+ Columns: []*schema.Column{UserGroupsColumns[0]},
+ RefColumns: []*schema.Column{UsersColumns[0]},
+ OnDelete: schema.Cascade,
+ },
+ {
+ Symbol: "user_groups_group_id",
+ Columns: []*schema.Column{UserGroupsColumns[1]},
+ RefColumns: []*schema.Column{GroupsColumns[0]},
+ OnDelete: schema.Cascade,
+ },
+ },
+ }
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
AttachmentsTable,
@@ -533,6 +550,7 @@ var (
TemplateFieldsTable,
UsersTable,
LabelItemsTable,
+ UserGroupsTable,
}
)
@@ -555,7 +573,8 @@ func init() {
NotifiersTable.ForeignKeys[0].RefTable = GroupsTable
NotifiersTable.ForeignKeys[1].RefTable = UsersTable
TemplateFieldsTable.ForeignKeys[0].RefTable = ItemTemplatesTable
- UsersTable.ForeignKeys[0].RefTable = GroupsTable
LabelItemsTable.ForeignKeys[0].RefTable = LabelsTable
LabelItemsTable.ForeignKeys[1].RefTable = ItemsTable
+ UserGroupsTable.ForeignKeys[0].RefTable = UsersTable
+ UserGroupsTable.ForeignKeys[1].RefTable = GroupsTable
}
diff --git a/backend/internal/data/ent/mutation.go b/backend/internal/data/ent/mutation.go
index f5a1b13d..c6a8fbbf 100644
--- a/backend/internal/data/ent/mutation.go
+++ b/backend/internal/data/ent/mutation.go
@@ -12583,9 +12583,11 @@ type UserMutation struct {
activated_on *time.Time
oidc_issuer *string
oidc_subject *string
+ default_group_id *uuid.UUID
clearedFields map[string]struct{}
- group *uuid.UUID
- clearedgroup bool
+ groups map[uuid.UUID]struct{}
+ removedgroups map[uuid.UUID]struct{}
+ clearedgroups bool
auth_tokens map[uuid.UUID]struct{}
removedauth_tokens map[uuid.UUID]struct{}
clearedauth_tokens bool
@@ -13149,43 +13151,107 @@ func (m *UserMutation) ResetOidcSubject() {
delete(m.clearedFields, user.FieldOidcSubject)
}
-// SetGroupID sets the "group" edge to the Group entity by id.
-func (m *UserMutation) SetGroupID(id uuid.UUID) {
- m.group = &id
+// SetDefaultGroupID sets the "default_group_id" field.
+func (m *UserMutation) SetDefaultGroupID(u uuid.UUID) {
+ m.default_group_id = &u
}
-// ClearGroup clears the "group" edge to the Group entity.
-func (m *UserMutation) ClearGroup() {
- m.clearedgroup = true
+// DefaultGroupID returns the value of the "default_group_id" field in the mutation.
+func (m *UserMutation) DefaultGroupID() (r uuid.UUID, exists bool) {
+ v := m.default_group_id
+ if v == nil {
+ return
+ }
+ return *v, true
}
-// GroupCleared reports if the "group" edge to the Group entity was cleared.
-func (m *UserMutation) GroupCleared() bool {
- return m.clearedgroup
+// OldDefaultGroupID returns the old "default_group_id" field's value of the User entity.
+// If the User object wasn't provided to the builder, the object is fetched from the database.
+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
+func (m *UserMutation) OldDefaultGroupID(ctx context.Context) (v *uuid.UUID, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldDefaultGroupID is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldDefaultGroupID requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldDefaultGroupID: %w", err)
+ }
+ return oldValue.DefaultGroupID, nil
}
-// GroupID returns the "group" edge ID in the mutation.
-func (m *UserMutation) GroupID() (id uuid.UUID, exists bool) {
- if m.group != nil {
- return *m.group, true
+// ClearDefaultGroupID clears the value of the "default_group_id" field.
+func (m *UserMutation) ClearDefaultGroupID() {
+ m.default_group_id = nil
+ m.clearedFields[user.FieldDefaultGroupID] = struct{}{}
+}
+
+// DefaultGroupIDCleared returns if the "default_group_id" field was cleared in this mutation.
+func (m *UserMutation) DefaultGroupIDCleared() bool {
+ _, ok := m.clearedFields[user.FieldDefaultGroupID]
+ return ok
+}
+
+// ResetDefaultGroupID resets all changes to the "default_group_id" field.
+func (m *UserMutation) ResetDefaultGroupID() {
+ m.default_group_id = nil
+ delete(m.clearedFields, user.FieldDefaultGroupID)
+}
+
+// AddGroupIDs adds the "groups" edge to the Group entity by ids.
+func (m *UserMutation) AddGroupIDs(ids ...uuid.UUID) {
+ if m.groups == nil {
+ m.groups = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ m.groups[ids[i]] = struct{}{}
+ }
+}
+
+// ClearGroups clears the "groups" edge to the Group entity.
+func (m *UserMutation) ClearGroups() {
+ m.clearedgroups = true
+}
+
+// GroupsCleared reports if the "groups" edge to the Group entity was cleared.
+func (m *UserMutation) GroupsCleared() bool {
+ return m.clearedgroups
+}
+
+// RemoveGroupIDs removes the "groups" edge to the Group entity by IDs.
+func (m *UserMutation) RemoveGroupIDs(ids ...uuid.UUID) {
+ if m.removedgroups == nil {
+ m.removedgroups = make(map[uuid.UUID]struct{})
+ }
+ for i := range ids {
+ delete(m.groups, ids[i])
+ m.removedgroups[ids[i]] = struct{}{}
+ }
+}
+
+// RemovedGroups returns the removed IDs of the "groups" edge to the Group entity.
+func (m *UserMutation) RemovedGroupsIDs() (ids []uuid.UUID) {
+ for id := range m.removedgroups {
+ ids = append(ids, id)
}
return
}
-// GroupIDs returns the "group" edge IDs in the mutation.
-// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
-// GroupID instead. It exists only for internal usage by the builders.
-func (m *UserMutation) GroupIDs() (ids []uuid.UUID) {
- if id := m.group; id != nil {
- ids = append(ids, *id)
+// GroupsIDs returns the "groups" edge IDs in the mutation.
+func (m *UserMutation) GroupsIDs() (ids []uuid.UUID) {
+ for id := range m.groups {
+ ids = append(ids, id)
}
return
}
-// ResetGroup resets all changes to the "group" edge.
-func (m *UserMutation) ResetGroup() {
- m.group = nil
- m.clearedgroup = false
+// ResetGroups resets all changes to the "groups" edge.
+func (m *UserMutation) ResetGroups() {
+ m.groups = nil
+ m.clearedgroups = false
+ m.removedgroups = nil
}
// AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by ids.
@@ -13330,7 +13396,7 @@ func (m *UserMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *UserMutation) Fields() []string {
- fields := make([]string, 0, 11)
+ fields := make([]string, 0, 12)
if m.created_at != nil {
fields = append(fields, user.FieldCreatedAt)
}
@@ -13364,6 +13430,9 @@ func (m *UserMutation) Fields() []string {
if m.oidc_subject != nil {
fields = append(fields, user.FieldOidcSubject)
}
+ if m.default_group_id != nil {
+ fields = append(fields, user.FieldDefaultGroupID)
+ }
return fields
}
@@ -13394,6 +13463,8 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) {
return m.OidcIssuer()
case user.FieldOidcSubject:
return m.OidcSubject()
+ case user.FieldDefaultGroupID:
+ return m.DefaultGroupID()
}
return nil, false
}
@@ -13425,6 +13496,8 @@ func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, er
return m.OldOidcIssuer(ctx)
case user.FieldOidcSubject:
return m.OldOidcSubject(ctx)
+ case user.FieldDefaultGroupID:
+ return m.OldDefaultGroupID(ctx)
}
return nil, fmt.Errorf("unknown User field %s", name)
}
@@ -13511,6 +13584,13 @@ func (m *UserMutation) SetField(name string, value ent.Value) error {
}
m.SetOidcSubject(v)
return nil
+ case user.FieldDefaultGroupID:
+ v, ok := value.(uuid.UUID)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetDefaultGroupID(v)
+ return nil
}
return fmt.Errorf("unknown User field %s", name)
}
@@ -13553,6 +13633,9 @@ func (m *UserMutation) ClearedFields() []string {
if m.FieldCleared(user.FieldOidcSubject) {
fields = append(fields, user.FieldOidcSubject)
}
+ if m.FieldCleared(user.FieldDefaultGroupID) {
+ fields = append(fields, user.FieldDefaultGroupID)
+ }
return fields
}
@@ -13579,6 +13662,9 @@ func (m *UserMutation) ClearField(name string) error {
case user.FieldOidcSubject:
m.ClearOidcSubject()
return nil
+ case user.FieldDefaultGroupID:
+ m.ClearDefaultGroupID()
+ return nil
}
return fmt.Errorf("unknown User nullable field %s", name)
}
@@ -13620,6 +13706,9 @@ func (m *UserMutation) ResetField(name string) error {
case user.FieldOidcSubject:
m.ResetOidcSubject()
return nil
+ case user.FieldDefaultGroupID:
+ m.ResetDefaultGroupID()
+ return nil
}
return fmt.Errorf("unknown User field %s", name)
}
@@ -13627,8 +13716,8 @@ func (m *UserMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *UserMutation) AddedEdges() []string {
edges := make([]string, 0, 3)
- if m.group != nil {
- edges = append(edges, user.EdgeGroup)
+ if m.groups != nil {
+ edges = append(edges, user.EdgeGroups)
}
if m.auth_tokens != nil {
edges = append(edges, user.EdgeAuthTokens)
@@ -13643,10 +13732,12 @@ func (m *UserMutation) AddedEdges() []string {
// name in this mutation.
func (m *UserMutation) AddedIDs(name string) []ent.Value {
switch name {
- case user.EdgeGroup:
- if id := m.group; id != nil {
- return []ent.Value{*id}
+ case user.EdgeGroups:
+ ids := make([]ent.Value, 0, len(m.groups))
+ for id := range m.groups {
+ ids = append(ids, id)
}
+ return ids
case user.EdgeAuthTokens:
ids := make([]ent.Value, 0, len(m.auth_tokens))
for id := range m.auth_tokens {
@@ -13666,6 +13757,9 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value {
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *UserMutation) RemovedEdges() []string {
edges := make([]string, 0, 3)
+ if m.removedgroups != nil {
+ edges = append(edges, user.EdgeGroups)
+ }
if m.removedauth_tokens != nil {
edges = append(edges, user.EdgeAuthTokens)
}
@@ -13679,6 +13773,12 @@ func (m *UserMutation) RemovedEdges() []string {
// the given name in this mutation.
func (m *UserMutation) RemovedIDs(name string) []ent.Value {
switch name {
+ case user.EdgeGroups:
+ ids := make([]ent.Value, 0, len(m.removedgroups))
+ for id := range m.removedgroups {
+ ids = append(ids, id)
+ }
+ return ids
case user.EdgeAuthTokens:
ids := make([]ent.Value, 0, len(m.removedauth_tokens))
for id := range m.removedauth_tokens {
@@ -13698,8 +13798,8 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value {
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *UserMutation) ClearedEdges() []string {
edges := make([]string, 0, 3)
- if m.clearedgroup {
- edges = append(edges, user.EdgeGroup)
+ if m.clearedgroups {
+ edges = append(edges, user.EdgeGroups)
}
if m.clearedauth_tokens {
edges = append(edges, user.EdgeAuthTokens)
@@ -13714,8 +13814,8 @@ func (m *UserMutation) ClearedEdges() []string {
// was cleared in this mutation.
func (m *UserMutation) EdgeCleared(name string) bool {
switch name {
- case user.EdgeGroup:
- return m.clearedgroup
+ case user.EdgeGroups:
+ return m.clearedgroups
case user.EdgeAuthTokens:
return m.clearedauth_tokens
case user.EdgeNotifiers:
@@ -13728,9 +13828,6 @@ func (m *UserMutation) EdgeCleared(name string) bool {
// if that edge is not defined in the schema.
func (m *UserMutation) ClearEdge(name string) error {
switch name {
- case user.EdgeGroup:
- m.ClearGroup()
- return nil
}
return fmt.Errorf("unknown User unique edge %s", name)
}
@@ -13739,8 +13836,8 @@ func (m *UserMutation) ClearEdge(name string) error {
// It returns an error if the edge is not defined in the schema.
func (m *UserMutation) ResetEdge(name string) error {
switch name {
- case user.EdgeGroup:
- m.ResetGroup()
+ case user.EdgeGroups:
+ m.ResetGroups()
return nil
case user.EdgeAuthTokens:
m.ResetAuthTokens()
diff --git a/backend/internal/data/ent/schema/group.go b/backend/internal/data/ent/schema/group.go
index 4deac1ae..292bee40 100644
--- a/backend/internal/data/ent/schema/group.go
+++ b/backend/internal/data/ent/schema/group.go
@@ -42,7 +42,8 @@ func (Group) Edges() []ent.Edge {
}
return []ent.Edge{
- owned("users", User.Type),
+ // Use edge.From + Ref("groups") to model M:M between users and groups via junction table
+ edge.From("users", User.Type).Ref("groups"),
owned("locations", Location.Type),
owned("items", Item.Type),
owned("labels", Label.Type),
@@ -72,14 +73,14 @@ func (g GroupMixin) Fields() []ent.Field {
}
func (g GroupMixin) Edges() []ent.Edge {
- edge := edge.From("group", Group.Type).
+ e := edge.From("group", Group.Type).
Ref(g.ref).
Unique().
Required()
if g.field != "" {
- edge = edge.Field(g.field)
+ e = e.Field(g.field)
}
- return []ent.Edge{edge}
+ return []ent.Edge{e}
}
diff --git a/backend/internal/data/ent/schema/user.go b/backend/internal/data/ent/schema/user.go
index c1ff9c29..221c7090 100644
--- a/backend/internal/data/ent/schema/user.go
+++ b/backend/internal/data/ent/schema/user.go
@@ -19,7 +19,6 @@ type User struct {
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
- GroupMixin{ref: "users"},
}
}
@@ -54,6 +53,10 @@ func (User) Fields() []ent.Field {
field.String("oidc_subject").
Optional().
Nillable(),
+ // default_group_id is the user's primary tenant/group
+ field.UUID("default_group_id", uuid.UUID{}).
+ Optional().
+ Nillable(),
}
}
@@ -66,6 +69,7 @@ func (User) Indexes() []ent.Index {
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
+ edge.To("groups", Group.Type),
edge.To("auth_tokens", AuthTokens.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
diff --git a/backend/internal/data/ent/user.go b/backend/internal/data/ent/user.go
index 9d7d4866..8adaf794 100644
--- a/backend/internal/data/ent/user.go
+++ b/backend/internal/data/ent/user.go
@@ -10,7 +10,6 @@ import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
- "github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
)
@@ -41,17 +40,18 @@ type User struct {
OidcIssuer *string `json:"oidc_issuer,omitempty"`
// OidcSubject holds the value of the "oidc_subject" field.
OidcSubject *string `json:"oidc_subject,omitempty"`
+ // DefaultGroupID holds the value of the "default_group_id" field.
+ DefaultGroupID *uuid.UUID `json:"default_group_id,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
- group_users *uuid.UUID
selectValues sql.SelectValues
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
- // Group holds the value of the group edge.
- Group *Group `json:"group,omitempty"`
+ // Groups holds the value of the groups edge.
+ Groups []*Group `json:"groups,omitempty"`
// AuthTokens holds the value of the auth_tokens edge.
AuthTokens []*AuthTokens `json:"auth_tokens,omitempty"`
// Notifiers holds the value of the notifiers edge.
@@ -61,15 +61,13 @@ type UserEdges struct {
loadedTypes [3]bool
}
-// GroupOrErr returns the Group value or an error if the edge
-// was not loaded in eager-loading, or loaded but was not found.
-func (e UserEdges) GroupOrErr() (*Group, error) {
- if e.Group != nil {
- return e.Group, nil
- } else if e.loadedTypes[0] {
- return nil, &NotFoundError{label: group.Label}
+// GroupsOrErr returns the Groups value or an error if the edge
+// was not loaded in eager-loading.
+func (e UserEdges) GroupsOrErr() ([]*Group, error) {
+ if e.loadedTypes[0] {
+ return e.Groups, nil
}
- return nil, &NotLoadedError{edge: "group"}
+ return nil, &NotLoadedError{edge: "groups"}
}
// AuthTokensOrErr returns the AuthTokens value or an error if the edge
@@ -95,6 +93,8 @@ func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
+ case user.FieldDefaultGroupID:
+ values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case user.FieldIsSuperuser, user.FieldSuperuser:
values[i] = new(sql.NullBool)
case user.FieldName, user.FieldEmail, user.FieldPassword, user.FieldRole, user.FieldOidcIssuer, user.FieldOidcSubject:
@@ -103,8 +103,6 @@ func (*User) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullTime)
case user.FieldID:
values[i] = new(uuid.UUID)
- case user.ForeignKeys[0]: // group_users
- values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
values[i] = new(sql.UnknownType)
}
@@ -195,12 +193,12 @@ func (_m *User) assignValues(columns []string, values []any) error {
_m.OidcSubject = new(string)
*_m.OidcSubject = value.String
}
- case user.ForeignKeys[0]:
+ case user.FieldDefaultGroupID:
if value, ok := values[i].(*sql.NullScanner); !ok {
- return fmt.Errorf("unexpected type %T for field group_users", values[i])
+ return fmt.Errorf("unexpected type %T for field default_group_id", values[i])
} else if value.Valid {
- _m.group_users = new(uuid.UUID)
- *_m.group_users = *value.S.(*uuid.UUID)
+ _m.DefaultGroupID = new(uuid.UUID)
+ *_m.DefaultGroupID = *value.S.(*uuid.UUID)
}
default:
_m.selectValues.Set(columns[i], values[i])
@@ -215,9 +213,9 @@ func (_m *User) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
-// QueryGroup queries the "group" edge of the User entity.
-func (_m *User) QueryGroup() *GroupQuery {
- return NewUserClient(_m.config).QueryGroup(_m)
+// QueryGroups queries the "groups" edge of the User entity.
+func (_m *User) QueryGroups() *GroupQuery {
+ return NewUserClient(_m.config).QueryGroups(_m)
}
// QueryAuthTokens queries the "auth_tokens" edge of the User entity.
@@ -288,6 +286,11 @@ func (_m *User) String() string {
builder.WriteString("oidc_subject=")
builder.WriteString(*v)
}
+ builder.WriteString(", ")
+ if v := _m.DefaultGroupID; v != nil {
+ builder.WriteString("default_group_id=")
+ builder.WriteString(fmt.Sprintf("%v", *v))
+ }
builder.WriteByte(')')
return builder.String()
}
diff --git a/backend/internal/data/ent/user/user.go b/backend/internal/data/ent/user/user.go
index 473d1d7f..6ecf60d1 100644
--- a/backend/internal/data/ent/user/user.go
+++ b/backend/internal/data/ent/user/user.go
@@ -38,21 +38,21 @@ const (
FieldOidcIssuer = "oidc_issuer"
// FieldOidcSubject holds the string denoting the oidc_subject field in the database.
FieldOidcSubject = "oidc_subject"
- // EdgeGroup holds the string denoting the group edge name in mutations.
- EdgeGroup = "group"
+ // FieldDefaultGroupID holds the string denoting the default_group_id field in the database.
+ FieldDefaultGroupID = "default_group_id"
+ // EdgeGroups holds the string denoting the groups edge name in mutations.
+ EdgeGroups = "groups"
// EdgeAuthTokens holds the string denoting the auth_tokens edge name in mutations.
EdgeAuthTokens = "auth_tokens"
// EdgeNotifiers holds the string denoting the notifiers edge name in mutations.
EdgeNotifiers = "notifiers"
// Table holds the table name of the user in the database.
Table = "users"
- // GroupTable is the table that holds the group relation/edge.
- GroupTable = "users"
- // GroupInverseTable is the table name for the Group entity.
+ // GroupsTable is the table that holds the groups relation/edge. The primary key declared below.
+ GroupsTable = "user_groups"
+ // GroupsInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
- GroupInverseTable = "groups"
- // GroupColumn is the table column denoting the group relation/edge.
- GroupColumn = "group_users"
+ GroupsInverseTable = "groups"
// AuthTokensTable is the table that holds the auth_tokens relation/edge.
AuthTokensTable = "auth_tokens"
// AuthTokensInverseTable is the table name for the AuthTokens entity.
@@ -83,13 +83,14 @@ var Columns = []string{
FieldActivatedOn,
FieldOidcIssuer,
FieldOidcSubject,
+ FieldDefaultGroupID,
}
-// ForeignKeys holds the SQL foreign-keys that are owned by the "users"
-// table and are not defined as standalone fields in the schema.
-var ForeignKeys = []string{
- "group_users",
-}
+var (
+ // GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the
+ // primary key for the groups relation (M2M).
+ GroupsPrimaryKey = []string{"user_id", "group_id"}
+)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
@@ -98,11 +99,6 @@ func ValidColumn(column string) bool {
return true
}
}
- for i := range ForeignKeys {
- if column == ForeignKeys[i] {
- return true
- }
- }
return false
}
@@ -216,10 +212,22 @@ func ByOidcSubject(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOidcSubject, opts...).ToFunc()
}
-// ByGroupField orders the results by group field.
-func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
+// ByDefaultGroupID orders the results by the default_group_id field.
+func ByDefaultGroupID(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldDefaultGroupID, opts...).ToFunc()
+}
+
+// ByGroupsCount orders the results by groups count.
+func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption {
+ return func(s *sql.Selector) {
+ sqlgraph.OrderByNeighborsCount(s, newGroupsStep(), opts...)
+ }
+}
+
+// ByGroups orders the results by groups terms.
+func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
- sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
+ sqlgraph.OrderByNeighborTerms(s, newGroupsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
@@ -250,11 +258,11 @@ func ByNotifiers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
sqlgraph.OrderByNeighborTerms(s, newNotifiersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
-func newGroupStep() *sqlgraph.Step {
+func newGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
- sqlgraph.To(GroupInverseTable, FieldID),
- sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
+ sqlgraph.To(GroupsInverseTable, FieldID),
+ sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...),
)
}
func newAuthTokensStep() *sqlgraph.Step {
diff --git a/backend/internal/data/ent/user/where.go b/backend/internal/data/ent/user/where.go
index 0d4ed5cd..0600426b 100644
--- a/backend/internal/data/ent/user/where.go
+++ b/backend/internal/data/ent/user/where.go
@@ -106,6 +106,11 @@ func OidcSubject(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldOidcSubject, v))
}
+// DefaultGroupID applies equality check predicate on the "default_group_id" field. It's identical to DefaultGroupIDEQ.
+func DefaultGroupID(v uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldDefaultGroupID, v))
+}
+
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
@@ -631,21 +636,71 @@ func OidcSubjectContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldOidcSubject, v))
}
-// HasGroup applies the HasEdge predicate on the "group" edge.
-func HasGroup() predicate.User {
+// DefaultGroupIDEQ applies the EQ predicate on the "default_group_id" field.
+func DefaultGroupIDEQ(v uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldEQ(FieldDefaultGroupID, v))
+}
+
+// DefaultGroupIDNEQ applies the NEQ predicate on the "default_group_id" field.
+func DefaultGroupIDNEQ(v uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldNEQ(FieldDefaultGroupID, v))
+}
+
+// DefaultGroupIDIn applies the In predicate on the "default_group_id" field.
+func DefaultGroupIDIn(vs ...uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldIn(FieldDefaultGroupID, vs...))
+}
+
+// DefaultGroupIDNotIn applies the NotIn predicate on the "default_group_id" field.
+func DefaultGroupIDNotIn(vs ...uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldNotIn(FieldDefaultGroupID, vs...))
+}
+
+// DefaultGroupIDGT applies the GT predicate on the "default_group_id" field.
+func DefaultGroupIDGT(v uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldGT(FieldDefaultGroupID, v))
+}
+
+// DefaultGroupIDGTE applies the GTE predicate on the "default_group_id" field.
+func DefaultGroupIDGTE(v uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldGTE(FieldDefaultGroupID, v))
+}
+
+// DefaultGroupIDLT applies the LT predicate on the "default_group_id" field.
+func DefaultGroupIDLT(v uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldLT(FieldDefaultGroupID, v))
+}
+
+// DefaultGroupIDLTE applies the LTE predicate on the "default_group_id" field.
+func DefaultGroupIDLTE(v uuid.UUID) predicate.User {
+ return predicate.User(sql.FieldLTE(FieldDefaultGroupID, v))
+}
+
+// DefaultGroupIDIsNil applies the IsNil predicate on the "default_group_id" field.
+func DefaultGroupIDIsNil() predicate.User {
+ return predicate.User(sql.FieldIsNull(FieldDefaultGroupID))
+}
+
+// DefaultGroupIDNotNil applies the NotNil predicate on the "default_group_id" field.
+func DefaultGroupIDNotNil() predicate.User {
+ return predicate.User(sql.FieldNotNull(FieldDefaultGroupID))
+}
+
+// HasGroups applies the HasEdge predicate on the "groups" edge.
+func HasGroups() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
- sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
+ sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
-// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
-func HasGroupWith(preds ...predicate.Group) predicate.User {
+// HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates).
+func HasGroupsWith(preds ...predicate.Group) predicate.User {
return predicate.User(func(s *sql.Selector) {
- step := newGroupStep()
+ step := newGroupsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
diff --git a/backend/internal/data/ent/user_create.go b/backend/internal/data/ent/user_create.go
index 3269f609..597cf7f1 100644
--- a/backend/internal/data/ent/user_create.go
+++ b/backend/internal/data/ent/user_create.go
@@ -162,6 +162,20 @@ func (_c *UserCreate) SetNillableOidcSubject(v *string) *UserCreate {
return _c
}
+// SetDefaultGroupID sets the "default_group_id" field.
+func (_c *UserCreate) SetDefaultGroupID(v uuid.UUID) *UserCreate {
+ _c.mutation.SetDefaultGroupID(v)
+ return _c
+}
+
+// SetNillableDefaultGroupID sets the "default_group_id" field if the given value is not nil.
+func (_c *UserCreate) SetNillableDefaultGroupID(v *uuid.UUID) *UserCreate {
+ if v != nil {
+ _c.SetDefaultGroupID(*v)
+ }
+ return _c
+}
+
// SetID sets the "id" field.
func (_c *UserCreate) SetID(v uuid.UUID) *UserCreate {
_c.mutation.SetID(v)
@@ -176,15 +190,19 @@ func (_c *UserCreate) SetNillableID(v *uuid.UUID) *UserCreate {
return _c
}
-// SetGroupID sets the "group" edge to the Group entity by ID.
-func (_c *UserCreate) SetGroupID(id uuid.UUID) *UserCreate {
- _c.mutation.SetGroupID(id)
+// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
+func (_c *UserCreate) AddGroupIDs(ids ...uuid.UUID) *UserCreate {
+ _c.mutation.AddGroupIDs(ids...)
return _c
}
-// SetGroup sets the "group" edge to the Group entity.
-func (_c *UserCreate) SetGroup(v *Group) *UserCreate {
- return _c.SetGroupID(v.ID)
+// AddGroups adds the "groups" edges to the Group entity.
+func (_c *UserCreate) AddGroups(v ...*Group) *UserCreate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _c.AddGroupIDs(ids...)
}
// AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs.
@@ -321,9 +339,6 @@ func (_c *UserCreate) check() error {
return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "User.role": %w`, err)}
}
}
- if len(_c.mutation.GroupIDs()) == 0 {
- return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "User.group"`)}
- }
return nil
}
@@ -403,12 +418,16 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
_spec.SetField(user.FieldOidcSubject, field.TypeString, value)
_node.OidcSubject = &value
}
- if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 {
+ if value, ok := _c.mutation.DefaultGroupID(); ok {
+ _spec.SetField(user.FieldDefaultGroupID, field.TypeUUID, value)
+ _node.DefaultGroupID = &value
+ }
+ if nodes := _c.mutation.GroupsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.M2O,
- Inverse: true,
- Table: user.GroupTable,
- Columns: []string{user.GroupColumn},
+ Rel: sqlgraph.M2M,
+ Inverse: false,
+ Table: user.GroupsTable,
+ Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
@@ -417,7 +436,6 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
- _node.group_users = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.AuthTokensIDs(); len(nodes) > 0 {
diff --git a/backend/internal/data/ent/user_query.go b/backend/internal/data/ent/user_query.go
index 1084a718..95600062 100644
--- a/backend/internal/data/ent/user_query.go
+++ b/backend/internal/data/ent/user_query.go
@@ -27,10 +27,9 @@ type UserQuery struct {
order []user.OrderOption
inters []Interceptor
predicates []predicate.User
- withGroup *GroupQuery
+ withGroups *GroupQuery
withAuthTokens *AuthTokensQuery
withNotifiers *NotifierQuery
- withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
@@ -67,8 +66,8 @@ func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery {
return _q
}
-// QueryGroup chains the current query on the "group" edge.
-func (_q *UserQuery) QueryGroup() *GroupQuery {
+// QueryGroups chains the current query on the "groups" edge.
+func (_q *UserQuery) QueryGroups() *GroupQuery {
query := (&GroupClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
@@ -81,7 +80,7 @@ func (_q *UserQuery) QueryGroup() *GroupQuery {
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
- sqlgraph.Edge(sqlgraph.M2O, true, user.GroupTable, user.GroupColumn),
+ sqlgraph.Edge(sqlgraph.M2M, false, user.GroupsTable, user.GroupsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
@@ -325,7 +324,7 @@ func (_q *UserQuery) Clone() *UserQuery {
order: append([]user.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.User{}, _q.predicates...),
- withGroup: _q.withGroup.Clone(),
+ withGroups: _q.withGroups.Clone(),
withAuthTokens: _q.withAuthTokens.Clone(),
withNotifiers: _q.withNotifiers.Clone(),
// clone intermediate query.
@@ -334,14 +333,14 @@ func (_q *UserQuery) Clone() *UserQuery {
}
}
-// WithGroup tells the query-builder to eager-load the nodes that are connected to
-// the "group" edge. The optional arguments are used to configure the query builder of the edge.
-func (_q *UserQuery) WithGroup(opts ...func(*GroupQuery)) *UserQuery {
+// WithGroups tells the query-builder to eager-load the nodes that are connected to
+// the "groups" edge. The optional arguments are used to configure the query builder of the edge.
+func (_q *UserQuery) WithGroups(opts ...func(*GroupQuery)) *UserQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
- _q.withGroup = query
+ _q.withGroups = query
return _q
}
@@ -444,20 +443,13 @@ func (_q *UserQuery) prepareQuery(ctx context.Context) error {
func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
var (
nodes = []*User{}
- withFKs = _q.withFKs
_spec = _q.querySpec()
loadedTypes = [3]bool{
- _q.withGroup != nil,
+ _q.withGroups != nil,
_q.withAuthTokens != nil,
_q.withNotifiers != nil,
}
)
- if _q.withGroup != nil {
- withFKs = true
- }
- if withFKs {
- _spec.Node.Columns = append(_spec.Node.Columns, user.ForeignKeys...)
- }
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*User).scanValues(nil, columns)
}
@@ -476,9 +468,10 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e
if len(nodes) == 0 {
return nodes, nil
}
- if query := _q.withGroup; query != nil {
- if err := _q.loadGroup(ctx, query, nodes, nil,
- func(n *User, e *Group) { n.Edges.Group = e }); err != nil {
+ if query := _q.withGroups; query != nil {
+ if err := _q.loadGroups(ctx, query, nodes,
+ func(n *User) { n.Edges.Groups = []*Group{} },
+ func(n *User, e *Group) { n.Edges.Groups = append(n.Edges.Groups, e) }); err != nil {
return nil, err
}
}
@@ -499,34 +492,63 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e
return nodes, nil
}
-func (_q *UserQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*User, init func(*User), assign func(*User, *Group)) error {
- ids := make([]uuid.UUID, 0, len(nodes))
- nodeids := make(map[uuid.UUID][]*User)
- for i := range nodes {
- if nodes[i].group_users == nil {
- continue
- }
- fk := *nodes[i].group_users
- if _, ok := nodeids[fk]; !ok {
- ids = append(ids, fk)
+func (_q *UserQuery) loadGroups(ctx context.Context, query *GroupQuery, nodes []*User, init func(*User), assign func(*User, *Group)) error {
+ edgeIDs := make([]driver.Value, len(nodes))
+ byID := make(map[uuid.UUID]*User)
+ nids := make(map[uuid.UUID]map[*User]struct{})
+ for i, node := range nodes {
+ edgeIDs[i] = node.ID
+ byID[node.ID] = node
+ if init != nil {
+ init(node)
}
- nodeids[fk] = append(nodeids[fk], nodes[i])
}
- if len(ids) == 0 {
- return nil
+ query.Where(func(s *sql.Selector) {
+ joinT := sql.Table(user.GroupsTable)
+ s.Join(joinT).On(s.C(group.FieldID), joinT.C(user.GroupsPrimaryKey[1]))
+ s.Where(sql.InValues(joinT.C(user.GroupsPrimaryKey[0]), edgeIDs...))
+ columns := s.SelectedColumns()
+ s.Select(joinT.C(user.GroupsPrimaryKey[0]))
+ s.AppendSelect(columns...)
+ s.SetDistinct(false)
+ })
+ if err := query.prepareQuery(ctx); err != nil {
+ return err
}
- query.Where(group.IDIn(ids...))
- neighbors, err := query.All(ctx)
+ qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
+ return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
+ assign := spec.Assign
+ values := spec.ScanValues
+ spec.ScanValues = func(columns []string) ([]any, error) {
+ values, err := values(columns[1:])
+ if err != nil {
+ return nil, err
+ }
+ return append([]any{new(uuid.UUID)}, values...), nil
+ }
+ spec.Assign = func(columns []string, values []any) error {
+ outValue := *values[0].(*uuid.UUID)
+ inValue := *values[1].(*uuid.UUID)
+ if nids[inValue] == nil {
+ nids[inValue] = map[*User]struct{}{byID[outValue]: {}}
+ return assign(columns[1:], values[1:])
+ }
+ nids[inValue][byID[outValue]] = struct{}{}
+ return nil
+ }
+ })
+ })
+ neighbors, err := withInterceptors[[]*Group](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
- nodes, ok := nodeids[n.ID]
+ nodes, ok := nids[n.ID]
if !ok {
- return fmt.Errorf(`unexpected foreign-key "group_users" returned %v`, n.ID)
+ return fmt.Errorf(`unexpected "groups" node returned %v`, n.ID)
}
- for i := range nodes {
- assign(nodes[i], n)
+ for kn := range nodes {
+ assign(kn, n)
}
}
return nil
diff --git a/backend/internal/data/ent/user_update.go b/backend/internal/data/ent/user_update.go
index c13f4057..cbfb3eba 100644
--- a/backend/internal/data/ent/user_update.go
+++ b/backend/internal/data/ent/user_update.go
@@ -188,15 +188,39 @@ func (_u *UserUpdate) ClearOidcSubject() *UserUpdate {
return _u
}
-// SetGroupID sets the "group" edge to the Group entity by ID.
-func (_u *UserUpdate) SetGroupID(id uuid.UUID) *UserUpdate {
- _u.mutation.SetGroupID(id)
+// SetDefaultGroupID sets the "default_group_id" field.
+func (_u *UserUpdate) SetDefaultGroupID(v uuid.UUID) *UserUpdate {
+ _u.mutation.SetDefaultGroupID(v)
return _u
}
-// SetGroup sets the "group" edge to the Group entity.
-func (_u *UserUpdate) SetGroup(v *Group) *UserUpdate {
- return _u.SetGroupID(v.ID)
+// SetNillableDefaultGroupID sets the "default_group_id" field if the given value is not nil.
+func (_u *UserUpdate) SetNillableDefaultGroupID(v *uuid.UUID) *UserUpdate {
+ if v != nil {
+ _u.SetDefaultGroupID(*v)
+ }
+ return _u
+}
+
+// ClearDefaultGroupID clears the value of the "default_group_id" field.
+func (_u *UserUpdate) ClearDefaultGroupID() *UserUpdate {
+ _u.mutation.ClearDefaultGroupID()
+ return _u
+}
+
+// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
+func (_u *UserUpdate) AddGroupIDs(ids ...uuid.UUID) *UserUpdate {
+ _u.mutation.AddGroupIDs(ids...)
+ return _u
+}
+
+// AddGroups adds the "groups" edges to the Group entity.
+func (_u *UserUpdate) AddGroups(v ...*Group) *UserUpdate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.AddGroupIDs(ids...)
}
// AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs.
@@ -234,12 +258,27 @@ func (_u *UserUpdate) Mutation() *UserMutation {
return _u.mutation
}
-// ClearGroup clears the "group" edge to the Group entity.
-func (_u *UserUpdate) ClearGroup() *UserUpdate {
- _u.mutation.ClearGroup()
+// ClearGroups clears all "groups" edges to the Group entity.
+func (_u *UserUpdate) ClearGroups() *UserUpdate {
+ _u.mutation.ClearGroups()
+ return _u
+}
+
+// RemoveGroupIDs removes the "groups" edge to Group entities by IDs.
+func (_u *UserUpdate) RemoveGroupIDs(ids ...uuid.UUID) *UserUpdate {
+ _u.mutation.RemoveGroupIDs(ids...)
return _u
}
+// RemoveGroups removes "groups" edges to Group entities.
+func (_u *UserUpdate) RemoveGroups(v ...*Group) *UserUpdate {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.RemoveGroupIDs(ids...)
+}
+
// ClearAuthTokens clears all "auth_tokens" edges to the AuthTokens entity.
func (_u *UserUpdate) ClearAuthTokens() *UserUpdate {
_u.mutation.ClearAuthTokens()
@@ -340,9 +379,6 @@ func (_u *UserUpdate) check() error {
return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "User.role": %w`, err)}
}
}
- if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
- return errors.New(`ent: clearing a required unique edge "User.group"`)
- }
return nil
}
@@ -400,25 +436,47 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if _u.mutation.OidcSubjectCleared() {
_spec.ClearField(user.FieldOidcSubject, field.TypeString)
}
- if _u.mutation.GroupCleared() {
+ if value, ok := _u.mutation.DefaultGroupID(); ok {
+ _spec.SetField(user.FieldDefaultGroupID, field.TypeUUID, value)
+ }
+ if _u.mutation.DefaultGroupIDCleared() {
+ _spec.ClearField(user.FieldDefaultGroupID, field.TypeUUID)
+ }
+ if _u.mutation.GroupsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2M,
+ Inverse: false,
+ Table: user.GroupsTable,
+ Columns: user.GroupsPrimaryKey,
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !_u.mutation.GroupsCleared() {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.M2O,
- Inverse: true,
- Table: user.GroupTable,
- Columns: []string{user.GroupColumn},
+ Rel: sqlgraph.M2M,
+ Inverse: false,
+ Table: user.GroupsTable,
+ Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
},
}
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
- if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
+ if nodes := _u.mutation.GroupsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.M2O,
- Inverse: true,
- Table: user.GroupTable,
- Columns: []string{user.GroupColumn},
+ Rel: sqlgraph.M2M,
+ Inverse: false,
+ Table: user.GroupsTable,
+ Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
@@ -695,15 +753,39 @@ func (_u *UserUpdateOne) ClearOidcSubject() *UserUpdateOne {
return _u
}
-// SetGroupID sets the "group" edge to the Group entity by ID.
-func (_u *UserUpdateOne) SetGroupID(id uuid.UUID) *UserUpdateOne {
- _u.mutation.SetGroupID(id)
+// SetDefaultGroupID sets the "default_group_id" field.
+func (_u *UserUpdateOne) SetDefaultGroupID(v uuid.UUID) *UserUpdateOne {
+ _u.mutation.SetDefaultGroupID(v)
return _u
}
-// SetGroup sets the "group" edge to the Group entity.
-func (_u *UserUpdateOne) SetGroup(v *Group) *UserUpdateOne {
- return _u.SetGroupID(v.ID)
+// SetNillableDefaultGroupID sets the "default_group_id" field if the given value is not nil.
+func (_u *UserUpdateOne) SetNillableDefaultGroupID(v *uuid.UUID) *UserUpdateOne {
+ if v != nil {
+ _u.SetDefaultGroupID(*v)
+ }
+ return _u
+}
+
+// ClearDefaultGroupID clears the value of the "default_group_id" field.
+func (_u *UserUpdateOne) ClearDefaultGroupID() *UserUpdateOne {
+ _u.mutation.ClearDefaultGroupID()
+ return _u
+}
+
+// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
+func (_u *UserUpdateOne) AddGroupIDs(ids ...uuid.UUID) *UserUpdateOne {
+ _u.mutation.AddGroupIDs(ids...)
+ return _u
+}
+
+// AddGroups adds the "groups" edges to the Group entity.
+func (_u *UserUpdateOne) AddGroups(v ...*Group) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.AddGroupIDs(ids...)
}
// AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs.
@@ -741,12 +823,27 @@ func (_u *UserUpdateOne) Mutation() *UserMutation {
return _u.mutation
}
-// ClearGroup clears the "group" edge to the Group entity.
-func (_u *UserUpdateOne) ClearGroup() *UserUpdateOne {
- _u.mutation.ClearGroup()
+// ClearGroups clears all "groups" edges to the Group entity.
+func (_u *UserUpdateOne) ClearGroups() *UserUpdateOne {
+ _u.mutation.ClearGroups()
+ return _u
+}
+
+// RemoveGroupIDs removes the "groups" edge to Group entities by IDs.
+func (_u *UserUpdateOne) RemoveGroupIDs(ids ...uuid.UUID) *UserUpdateOne {
+ _u.mutation.RemoveGroupIDs(ids...)
return _u
}
+// RemoveGroups removes "groups" edges to Group entities.
+func (_u *UserUpdateOne) RemoveGroups(v ...*Group) *UserUpdateOne {
+ ids := make([]uuid.UUID, len(v))
+ for i := range v {
+ ids[i] = v[i].ID
+ }
+ return _u.RemoveGroupIDs(ids...)
+}
+
// ClearAuthTokens clears all "auth_tokens" edges to the AuthTokens entity.
func (_u *UserUpdateOne) ClearAuthTokens() *UserUpdateOne {
_u.mutation.ClearAuthTokens()
@@ -860,9 +957,6 @@ func (_u *UserUpdateOne) check() error {
return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "User.role": %w`, err)}
}
}
- if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
- return errors.New(`ent: clearing a required unique edge "User.group"`)
- }
return nil
}
@@ -937,25 +1031,47 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
if _u.mutation.OidcSubjectCleared() {
_spec.ClearField(user.FieldOidcSubject, field.TypeString)
}
- if _u.mutation.GroupCleared() {
+ if value, ok := _u.mutation.DefaultGroupID(); ok {
+ _spec.SetField(user.FieldDefaultGroupID, field.TypeUUID, value)
+ }
+ if _u.mutation.DefaultGroupIDCleared() {
+ _spec.ClearField(user.FieldDefaultGroupID, field.TypeUUID)
+ }
+ if _u.mutation.GroupsCleared() {
+ edge := &sqlgraph.EdgeSpec{
+ Rel: sqlgraph.M2M,
+ Inverse: false,
+ Table: user.GroupsTable,
+ Columns: user.GroupsPrimaryKey,
+ Bidi: false,
+ Target: &sqlgraph.EdgeTarget{
+ IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
+ },
+ }
+ _spec.Edges.Clear = append(_spec.Edges.Clear, edge)
+ }
+ if nodes := _u.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !_u.mutation.GroupsCleared() {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.M2O,
- Inverse: true,
- Table: user.GroupTable,
- Columns: []string{user.GroupColumn},
+ Rel: sqlgraph.M2M,
+ Inverse: false,
+ Table: user.GroupsTable,
+ Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
},
}
+ for _, k := range nodes {
+ edge.Target.Nodes = append(edge.Target.Nodes, k)
+ }
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
- if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
+ if nodes := _u.mutation.GroupsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
- Rel: sqlgraph.M2O,
- Inverse: true,
- Table: user.GroupTable,
- Columns: []string{user.GroupColumn},
+ Rel: sqlgraph.M2M,
+ Inverse: false,
+ Table: user.GroupsTable,
+ Columns: user.GroupsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeUUID),
diff --git a/backend/internal/data/migrations/migrations.go b/backend/internal/data/migrations/migrations.go
index 05bac552..fda595c2 100644
--- a/backend/internal/data/migrations/migrations.go
+++ b/backend/internal/data/migrations/migrations.go
@@ -31,5 +31,4 @@ func Migrations(dialect string) (embed.FS, error) {
return embed.FS{}, fmt.Errorf("unknown sql dialect: %s", dialect)
}
// This should never get hit, but just in case
- return sqliteFiles, nil
}
diff --git a/backend/internal/data/migrations/postgres/20251226000000_user_group_m2m.sql b/backend/internal/data/migrations/postgres/20251226000000_user_group_m2m.sql
new file mode 100644
index 00000000..eebc40ab
--- /dev/null
+++ b/backend/internal/data/migrations/postgres/20251226000000_user_group_m2m.sql
@@ -0,0 +1,47 @@
+-- +goose Up
+-- Create user_groups junction table for M:M relationship
+CREATE TABLE IF NOT EXISTS "user_groups" (
+ "user_id" uuid NOT NULL,
+ "group_id" uuid NOT NULL,
+ PRIMARY KEY ("user_id", "group_id"),
+ CONSTRAINT "user_groups_user_id" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON UPDATE NO ACTION ON DELETE CASCADE,
+ CONSTRAINT "user_groups_group_id" FOREIGN KEY ("group_id") REFERENCES "groups" ("id") ON UPDATE NO ACTION ON DELETE CASCADE
+);
+
+-- Migrate existing user->group relationships to the junction table
+INSERT INTO "user_groups" ("user_id", "group_id")
+SELECT "id", "group_users" FROM "users" WHERE "group_users" IS NOT NULL;
+
+-- Add default_group_id column to users table
+ALTER TABLE "users" ADD COLUMN "default_group_id" uuid;
+
+-- Set default_group_id to the user's current group
+UPDATE "users" SET "default_group_id" = "group_users" WHERE "group_users" IS NOT NULL;
+
+-- Drop the old group_users foreign key constraint and column
+ALTER TABLE "users" DROP CONSTRAINT "users_groups_users";
+ALTER TABLE "users" DROP COLUMN "group_users";
+
+-- Add foreign key constraint for default_group_id
+ALTER TABLE "users" ADD CONSTRAINT "users_groups_users_default" FOREIGN KEY ("default_group_id") REFERENCES "groups" ("id") ON UPDATE NO ACTION ON DELETE SET NULL;
+
+-- +goose Down
+-- Recreate group_users column with foreign key
+ALTER TABLE "users" ADD COLUMN "group_users" uuid;
+
+-- Restore the group_users values from user_groups (using the default_group_id or first entry)
+UPDATE "users"
+SET "group_users" = COALESCE("default_group_id", (
+ SELECT "group_id" FROM "user_groups" WHERE "user_id" = "users"."id" LIMIT 1
+));
+
+-- Drop the default_group_id foreign key and column
+ALTER TABLE "users" DROP CONSTRAINT "users_groups_users_default";
+ALTER TABLE "users" DROP COLUMN "default_group_id";
+
+-- Add back the original foreign key constraint
+ALTER TABLE "users" ADD CONSTRAINT "users_groups_users" FOREIGN KEY ("group_users") REFERENCES "groups" ("id") ON UPDATE NO ACTION ON DELETE CASCADE;
+
+-- Drop the junction table
+DROP TABLE IF EXISTS "user_groups";
+
diff --git a/backend/internal/data/migrations/sqlite3/20251227000000_user_group_m2m.sql b/backend/internal/data/migrations/sqlite3/20251227000000_user_group_m2m.sql
new file mode 100644
index 00000000..ab8e4983
--- /dev/null
+++ b/backend/internal/data/migrations/sqlite3/20251227000000_user_group_m2m.sql
@@ -0,0 +1,68 @@
+-- +goose Up
+-- +goose no transaction
+-- Turn off foreign key constraints because otherwise we'll wipe notifiers out of the database when dropping the older users table
+PRAGMA foreign_keys=OFF;
+-- Create user_groups junction table for M:M relationship
+CREATE TABLE IF NOT EXISTS user_groups (
+ user_id UUID NOT NULL,
+ group_id UUID NOT NULL,
+ PRIMARY KEY (user_id, group_id),
+ CONSTRAINT user_groups_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT user_groups_group_id FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
+);
+
+-- Migrate existing user->group relationships to the junction table
+INSERT INTO user_groups (user_id, group_id)
+SELECT id, group_users FROM users WHERE group_users IS NOT NULL;
+
+-- Add default_group_id column to users table
+ALTER TABLE users ADD COLUMN default_group_id UUID;
+
+-- Set default_group_id to the user's current group
+UPDATE users SET default_group_id = group_users WHERE group_users IS NOT NULL;
+
+-- Add foreign key constraint for default_group_id
+CREATE TABLE users_new (
+ id UUID NOT NULL,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME NOT NULL,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL UNIQUE,
+ password TEXT,
+ is_superuser BOOLEAN NOT NULL DEFAULT false,
+ superuser BOOLEAN NOT NULL DEFAULT false,
+ role TEXT NOT NULL DEFAULT 'user',
+ activated_on DATETIME,
+ oidc_issuer TEXT,
+ oidc_subject TEXT,
+ default_group_id UUID,
+ PRIMARY KEY (id),
+ CONSTRAINT users_groups_users_default FOREIGN KEY (default_group_id) REFERENCES groups(id) ON DELETE SET NULL,
+ UNIQUE (oidc_issuer, oidc_subject)
+);
+
+-- Copy data from old table to new table
+INSERT INTO users_new (
+ id, created_at, updated_at, name, email, password, is_superuser, superuser, role,
+ activated_on, oidc_issuer, oidc_subject, default_group_id
+)
+SELECT
+ id, created_at, updated_at, name, email, password, is_superuser, superuser, role,
+ activated_on, oidc_issuer, oidc_subject, default_group_id
+FROM users;
+
+-- Drop old indexes
+DROP INDEX IF EXISTS users_email_key;
+DROP INDEX IF EXISTS users_oidc_issuer_subject_key;
+
+-- Drop old table
+DROP TABLE users;
+
+-- Rename new table to users
+ALTER TABLE users_new RENAME TO users;
+
+-- Recreate indexes
+CREATE UNIQUE INDEX IF NOT EXISTS users_email_key ON users(email);
+CREATE UNIQUE INDEX IF NOT EXISTS users_oidc_issuer_subject_key ON users(oidc_issuer, oidc_subject);
+
+PRAGMA foreign_keys=ON;
diff --git a/backend/internal/data/repo/main_test.go b/backend/internal/data/repo/main_test.go
index bda60e36..bf7d8bda 100644
--- a/backend/internal/data/repo/main_test.go
+++ b/backend/internal/data/repo/main_test.go
@@ -2,6 +2,7 @@ package repo
import (
"context"
+ "github.com/google/uuid"
"github.com/sysadminsmedia/homebox/backend/internal/sys/config"
"log"
"os"
@@ -29,7 +30,7 @@ func bootstrap() {
ctx = context.Background()
)
- tGroup, err = tRepos.Groups.GroupCreate(ctx, "test-group")
+ tGroup, err = tRepos.Groups.GroupCreate(ctx, "test-group", uuid.Nil)
if err != nil {
log.Fatal(err)
}
diff --git a/backend/internal/data/repo/repo_group.go b/backend/internal/data/repo/repo_group.go
index de1f01f4..3a42174e 100644
--- a/backend/internal/data/repo/repo_group.go
+++ b/backend/internal/data/repo/repo_group.go
@@ -2,23 +2,28 @@ package repo
import (
"context"
+ "fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
+ "github.com/rs/zerolog/log"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/groupinvitationtoken"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/item"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/label"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/location"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/notifier"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
)
type GroupRepository struct {
db *ent.Client
groupMapper MapFunc[*ent.Group, Group]
invitationMapper MapFunc[*ent.GroupInvitationToken, GroupInvitation]
+ attachments *AttachmentRepo
}
func NewGroupRepository(db *ent.Client) *GroupRepository {
@@ -105,8 +110,12 @@ type (
}
)
-func (r *GroupRepository) GetAllGroups(ctx context.Context) ([]Group, error) {
- return r.groupMapper.MapEachErr(r.db.Group.Query().All(ctx))
+func (r *GroupRepository) GetAllGroups(ctx context.Context, userID uuid.UUID) ([]Group, error) {
+ q := r.db.Group.Query()
+ if userID != uuid.Nil {
+ q.Where(group.HasUsersWith(user.ID(userID)))
+ }
+ return r.groupMapper.MapEachErr(q.All(ctx))
}
func (r *GroupRepository) StatsLocationsByPurchasePrice(ctx context.Context, gid uuid.UUID) ([]TotalsByOrganizer, error) {
@@ -223,7 +232,7 @@ func (r *GroupRepository) StatsPurchasePrice(ctx context.Context, gid uuid.UUID,
func (r *GroupRepository) StatsGroup(ctx context.Context, gid uuid.UUID) (GroupStatistics, error) {
q := `
SELECT
- (SELECT COUNT(*) FROM users WHERE group_users = $2) AS total_users,
+ (SELECT COUNT(*) FROM user_groups WHERE group_id = $2) AS total_users,
(SELECT COUNT(*) FROM items WHERE group_items = $2 AND items.archived = false) AS total_items,
(SELECT COUNT(*) FROM locations WHERE group_locations = $2) AS total_locations,
(SELECT COUNT(*) FROM labels WHERE group_labels = $2) AS total_labels,
@@ -252,10 +261,15 @@ func (r *GroupRepository) StatsGroup(ctx context.Context, gid uuid.UUID) (GroupS
return stats, nil
}
-func (r *GroupRepository) GroupCreate(ctx context.Context, name string) (Group, error) {
- return r.groupMapper.MapErr(r.db.Group.Create().
- SetName(name).
- Save(ctx))
+func (r *GroupRepository) GroupCreate(ctx context.Context, name string, userID uuid.UUID) (Group, error) {
+ createQuery := r.db.Group.Create().SetName(name)
+
+ // Only link user if a valid user ID is provided
+ if userID != uuid.Nil {
+ createQuery = createQuery.AddUserIDs(userID)
+ }
+
+ return r.groupMapper.MapErr(createQuery.Save(ctx))
}
func (r *GroupRepository) GroupUpdate(ctx context.Context, id uuid.UUID, data GroupUpdate) (Group, error) {
@@ -271,6 +285,62 @@ func (r *GroupRepository) GroupByID(ctx context.Context, id uuid.UUID) (Group, e
return r.groupMapper.MapErr(r.db.Group.Get(ctx, id))
}
+func (r *GroupRepository) GroupDelete(ctx context.Context, id uuid.UUID) error {
+ tx, err := r.db.Tx(ctx)
+ if err != nil {
+ return err
+ }
+
+ itm, err := tx.Item.Query().
+ Where(item.HasGroupWith(group.ID(id))).
+ WithGroup().
+ WithAttachments().
+ All(ctx)
+ if err != nil {
+ return err
+ }
+
+ // Delete all attachments (and their files) before deleting the items
+ for _, it := range itm {
+ for _, att := range it.Edges.Attachments {
+ if err := r.attachments.Delete(ctx, id, att.ID); err != nil {
+ log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during item deletion")
+ // Continue with other attachments even if one fails
+ }
+ }
+ }
+
+ // Delete all items from the database
+ if _, err := tx.Item.Delete().
+ Where(item.HasGroupWith(group.ID(id))).
+ Exec(ctx); err != nil {
+ if rerr := tx.Rollback(); rerr != nil {
+ log.Error().Err(rerr).Msg("failed to rollback transaction")
+ }
+ return err
+ }
+
+ // Delete any associated notifiers
+ if _, err := tx.Notifier.Delete().
+ Where(notifier.HasGroupWith(group.ID(id))).
+ Exec(ctx); err != nil {
+ if rerr := tx.Rollback(); rerr != nil {
+ log.Error().Err(rerr).Msg("failed to rollback transaction")
+ }
+ return err
+ }
+
+ // Delete the group
+ if err := tx.Group.DeleteOneID(id).Exec(ctx); err != nil {
+ if rerr := tx.Rollback(); rerr != nil {
+ log.Error().Err(rerr).Msg("failed to rollback transaction")
+ }
+ return err
+ }
+
+ return tx.Commit()
+}
+
func (r *GroupRepository) InvitationGet(ctx context.Context, token []byte) (GroupInvitation, error) {
return r.invitationMapper.MapErr(r.db.GroupInvitationToken.Query().
Where(groupinvitationtoken.Token(token)).
@@ -278,6 +348,18 @@ func (r *GroupRepository) InvitationGet(ctx context.Context, token []byte) (Grou
Only(ctx))
}
+func (r *GroupRepository) InvitationGetAll(ctx context.Context, groupID uuid.UUID) ([]GroupInvitation, error) {
+ invitations, err := r.db.GroupInvitationToken.Query().
+ Where(groupinvitationtoken.HasGroupWith(group.ID(groupID))).
+ WithGroup().
+ All(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ return r.invitationMapper.MapEach(invitations), nil
+}
+
func (r *GroupRepository) InvitationCreate(ctx context.Context, groupID uuid.UUID, invite GroupInvitationCreate) (GroupInvitation, error) {
entity, err := r.db.GroupInvitationToken.Create().
SetGroupID(groupID).
@@ -297,6 +379,22 @@ func (r *GroupRepository) InvitationUpdate(ctx context.Context, id uuid.UUID, us
return err
}
+func (r *GroupRepository) InvitationDelete(ctx context.Context, groupID uuid.UUID, id uuid.UUID) error {
+ n, err := r.db.GroupInvitationToken.Delete().
+ Where(
+ groupinvitationtoken.ID(id),
+ groupinvitationtoken.HasGroupWith(group.ID(groupID)),
+ ).
+ Exec(ctx)
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return &ent.NotFoundError{}
+ }
+ return nil
+}
+
// InvitationPurge removes all expired invitations or those that have been used up.
// It returns the number of deleted invitations.
func (r *GroupRepository) InvitationPurge(ctx context.Context) (amount int, err error) {
@@ -308,3 +406,120 @@ func (r *GroupRepository) InvitationPurge(ctx context.Context) (amount int, err
return q.Exec(ctx)
}
+
+func (r *GroupRepository) IsMember(ctx context.Context, groupID, userID uuid.UUID) (bool, error) {
+ return r.db.Group.Query().
+ Where(group.ID(groupID), group.HasUsersWith(user.ID(userID))).
+ Exist(ctx)
+}
+
+func (r *GroupRepository) AddMember(ctx context.Context, groupID, userID uuid.UUID) error {
+ return r.db.Group.UpdateOneID(groupID).AddUserIDs(userID).Exec(ctx)
+}
+
+func (r *GroupRepository) RemoveMember(ctx context.Context, groupID, userID uuid.UUID) error {
+ return r.db.Group.UpdateOneID(groupID).RemoveUserIDs(userID).Exec(ctx)
+}
+
+func (r *GroupRepository) InvitationDecrement(ctx context.Context, id uuid.UUID) error {
+ n, err := r.db.GroupInvitationToken.Update().
+ Where(
+ groupinvitationtoken.ID(id),
+ groupinvitationtoken.UsesGT(0),
+ ).
+ AddUses(-1).
+ Save(ctx)
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return fmt.Errorf("invitation used up")
+ }
+ return nil
+}
+
+func (r *GroupRepository) InvitationAccept(ctx context.Context, token []byte, userID uuid.UUID) (Group, error) {
+ tx, err := r.db.Tx(ctx)
+ if err != nil {
+ return Group{}, err
+ }
+
+ // 1. Get invitation
+ invitation, err := tx.GroupInvitationToken.Query().
+ Where(groupinvitationtoken.Token(token)).
+ WithGroup().
+ Only(ctx)
+ if err != nil {
+ if err := tx.Rollback(); err != nil {
+ log.Warn().Err(err).Msg("failed to rollback transaction")
+ }
+ return Group{}, err
+ }
+
+ // 2. Checks
+ if invitation.ExpiresAt.Before(time.Now()) {
+ if err := tx.Rollback(); err != nil {
+ log.Warn().Err(err).Msg("failed to rollback transaction")
+ }
+ return Group{}, fmt.Errorf("invitation expired")
+ }
+ if invitation.Uses <= 0 {
+ if err := tx.Rollback(); err != nil {
+ log.Warn().Err(err).Msg("failed to rollback transaction")
+ }
+ return Group{}, fmt.Errorf("invitation used up")
+ }
+
+ // 3. Check membership
+ isMember, err := tx.Group.Query().
+ Where(group.ID(invitation.Edges.Group.ID), group.HasUsersWith(user.ID(userID))).
+ Exist(ctx)
+ if err != nil {
+ if err := tx.Rollback(); err != nil {
+ log.Warn().Err(err).Msg("failed to rollback transaction")
+ }
+ return Group{}, err
+ }
+ if isMember {
+ if err := tx.Rollback(); err != nil {
+ log.Warn().Err(err).Msg("failed to rollback transaction")
+ }
+ return Group{}, fmt.Errorf("user already a member of this group")
+ }
+
+ // 4. Add member
+ err = tx.Group.UpdateOneID(invitation.Edges.Group.ID).AddUserIDs(userID).Exec(ctx)
+ if err != nil {
+ if err := tx.Rollback(); err != nil {
+ log.Warn().Err(err).Msg("failed to rollback transaction")
+ }
+ return Group{}, err
+ }
+
+ // 5. Decrement uses atomically
+ n, err := tx.GroupInvitationToken.Update().
+ Where(
+ groupinvitationtoken.ID(invitation.ID),
+ groupinvitationtoken.UsesGT(0),
+ ).
+ AddUses(-1).
+ Save(ctx)
+ if err != nil {
+ if err := tx.Rollback(); err != nil {
+ log.Warn().Err(err).Msg("failed to rollback transaction")
+ }
+ return Group{}, err
+ }
+ if n == 0 {
+ if err := tx.Rollback(); err != nil {
+ log.Warn().Err(err).Msg("failed to rollback transaction")
+ }
+ return Group{}, fmt.Errorf("invitation used up")
+ }
+
+ if err := tx.Commit(); err != nil {
+ return Group{}, err
+ }
+
+ return r.groupMapper.Map(invitation.Edges.Group), nil
+}
diff --git a/backend/internal/data/repo/repo_group_test.go b/backend/internal/data/repo/repo_group_test.go
index 91b7844b..3ea48cf5 100644
--- a/backend/internal/data/repo/repo_group_test.go
+++ b/backend/internal/data/repo/repo_group_test.go
@@ -4,12 +4,13 @@ import (
"context"
"testing"
+ "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_Group_Create(t *testing.T) {
- g, err := tRepos.Groups.GroupCreate(context.Background(), "test")
+ g, err := tRepos.Groups.GroupCreate(context.Background(), "test", uuid.Nil)
require.NoError(t, err)
assert.Equal(t, "test", g.Name)
@@ -20,8 +21,31 @@ func Test_Group_Create(t *testing.T) {
assert.Equal(t, g.ID, foundGroup.ID)
}
+func Test_Group_Create_WithUser(t *testing.T) {
+ // Create a test user first
+ password := "password123"
+ user, err := tRepos.Users.Create(context.Background(), UserCreate{
+ Name: "test_user",
+ Email: "[email protected]",
+ Password: &password,
+ DefaultGroupID: tGroup.ID,
+ })
+ require.NoError(t, err)
+
+ // Create a group with the user
+ g, err := tRepos.Groups.GroupCreate(context.Background(), "test_group_with_user", user.ID)
+ require.NoError(t, err)
+ assert.Equal(t, "test_group_with_user", g.Name)
+
+ // Verify the user is a member of the group
+ members, err := tRepos.Users.GetUsersByGroupID(context.Background(), g.ID)
+ require.NoError(t, err)
+ assert.Len(t, members, 1, "Group should have exactly one member")
+ assert.Equal(t, user.Name, members[0].Name, "The member should be the user who created the group")
+}
+
func Test_Group_Update(t *testing.T) {
- g, err := tRepos.Groups.GroupCreate(context.Background(), "test")
+ g, err := tRepos.Groups.GroupCreate(context.Background(), "test", uuid.Nil)
require.NoError(t, err)
g, err = tRepos.Groups.GroupUpdate(context.Background(), g.ID, GroupUpdate{
@@ -46,3 +70,29 @@ func Test_Group_Update(t *testing.T) {
assert.Equal(t, 1, stats.TotalUsers)
assert.Equal(t, 1, stats.TotalLocations)
}*/
+
+func Test_Group_IsMember(t *testing.T) {
+ ctx := context.Background()
+
+ group, err := tRepos.Groups.GroupCreate(ctx, "member-check", uuid.Nil)
+ require.NoError(t, err)
+
+ user := userFactory()
+ user.DefaultGroupID = group.ID
+ createdUser, err := tRepos.Users.Create(ctx, user)
+ require.NoError(t, err)
+
+ // Newly created user is added to default group in Create()
+ isMember, err := tRepos.Groups.IsMember(ctx, group.ID, createdUser.ID)
+ require.NoError(t, err)
+ assert.True(t, isMember)
+
+ otherUser := userFactory()
+ otherUser.DefaultGroupID = tGroup.ID
+ createdOther, err := tRepos.Users.Create(ctx, otherUser)
+ require.NoError(t, err)
+
+ isMember, err = tRepos.Groups.IsMember(ctx, group.ID, createdOther.ID)
+ require.NoError(t, err)
+ assert.False(t, isMember)
+}
diff --git a/backend/internal/data/repo/repo_item_attachments.go b/backend/internal/data/repo/repo_item_attachments.go
index d86a52f2..0b4aa612 100644
--- a/backend/internal/data/repo/repo_item_attachments.go
+++ b/backend/internal/data/repo/repo_item_attachments.go
@@ -114,17 +114,17 @@ func (r *AttachmentRepo) fullPath(relativePath string) string {
// Normalize path separators to forward slashes for blob storage
// The blob library expects forward slashes in keys regardless of OS
normalizedRelativePath := normalizePath(relativePath)
-
+
// Always use forward slashes when joining paths for blob storage
if r.storage.PrefixPath == "" {
return normalizedRelativePath
}
normalizedPrefix := normalizePath(r.storage.PrefixPath)
-
+
if normalizedPrefix == "" {
return normalizedRelativePath
}
-
+
return fmt.Sprintf("%s/%s", normalizedPrefix, normalizedRelativePath)
}
@@ -386,7 +386,7 @@ func (r *AttachmentRepo) Update(ctx context.Context, gid uuid.UUID, id uuid.UUID
return r.Get(ctx, gid, updatedAttachment.ID)
}
-func (r *AttachmentRepo) Delete(ctx context.Context, gid uuid.UUID, itemId uuid.UUID, id uuid.UUID) error {
+func (r *AttachmentRepo) Delete(ctx context.Context, gid uuid.UUID, id uuid.UUID) error {
// Validate that the attachment belongs to the specified group
doc, err := r.db.Attachment.Query().
Where(
diff --git a/backend/internal/data/repo/repo_item_attachments_test.go b/backend/internal/data/repo/repo_item_attachments_test.go
index cbd839e5..81ee394c 100644
--- a/backend/internal/data/repo/repo_item_attachments_test.go
+++ b/backend/internal/data/repo/repo_item_attachments_test.go
@@ -16,10 +16,10 @@ import (
func TestAttachmentRepo_Create(t *testing.T) {
item := useItems(t, 1)[0]
- ids := []uuid.UUID{item.ID}
+ var ids []uuid.UUID
t.Cleanup(func() {
for _, id := range ids {
- _ = tRepos.Attachments.Delete(context.Background(), tGroup.ID, item.ID, id)
+ _ = tRepos.Attachments.Delete(context.Background(), tGroup.ID, id)
}
})
@@ -87,7 +87,7 @@ func useAttachments(t *testing.T, n int) []*ent.Attachment {
ids := make([]uuid.UUID, 0, n)
t.Cleanup(func() {
for _, id := range ids {
- _ = tRepos.Attachments.Delete(context.Background(), tGroup.ID, item.ID, id)
+ _ = tRepos.Attachments.Delete(context.Background(), tGroup.ID, id)
}
})
@@ -123,9 +123,8 @@ func TestAttachmentRepo_Update(t *testing.T) {
func TestAttachmentRepo_Delete(t *testing.T) {
entity := useAttachments(t, 1)[0]
- item := useItems(t, 1)[0]
- err := tRepos.Attachments.Delete(context.Background(), tGroup.ID, item.ID, entity.ID)
+ err := tRepos.Attachments.Delete(context.Background(), tGroup.ID, entity.ID)
require.NoError(t, err)
_, err = tRepos.Attachments.Get(context.Background(), tGroup.ID, entity.ID)
@@ -168,8 +167,8 @@ func TestAttachmentRepo_UpdateNonPhotoDoesNotAffectPrimaryPhoto(t *testing.T) {
// Cleanup
t.Cleanup(func() {
- _ = tRepos.Attachments.Delete(ctx, tGroup.ID, item.ID, photoAttachment.ID)
- _ = tRepos.Attachments.Delete(ctx, tGroup.ID, item.ID, manualAttachment.ID)
+ _ = tRepos.Attachments.Delete(ctx, tGroup.ID, photoAttachment.ID)
+ _ = tRepos.Attachments.Delete(ctx, tGroup.ID, manualAttachment.ID)
})
// Verify photo is primary initially
@@ -206,7 +205,7 @@ func TestAttachmentRepo_AddingPDFAfterPhotoKeepsPhotoAsPrimary(t *testing.T) {
// Cleanup
t.Cleanup(func() {
- _ = tRepos.Attachments.Delete(ctx, tGroup.ID, item.ID, photoAttachment.ID)
+ _ = tRepos.Attachments.Delete(ctx, tGroup.ID, photoAttachment.ID)
})
// Verify photo becomes primary automatically (since it's the first photo)
@@ -220,7 +219,7 @@ func TestAttachmentRepo_AddingPDFAfterPhotoKeepsPhotoAsPrimary(t *testing.T) {
// Add to cleanup
t.Cleanup(func() {
- _ = tRepos.Attachments.Delete(ctx, tGroup.ID, item.ID, pdfAttachment.ID)
+ _ = tRepos.Attachments.Delete(ctx, tGroup.ID, pdfAttachment.ID)
})
// Step 3: Verify photo is still primary after adding PDF
@@ -255,8 +254,8 @@ func TestAttachmentRepo_SettingPhotoPrimaryStillWorks(t *testing.T) {
// Cleanup
t.Cleanup(func() {
- _ = tRepos.Attachments.Delete(ctx, tGroup.ID, item.ID, photo1.ID)
- _ = tRepos.Attachments.Delete(ctx, tGroup.ID, item.ID, photo2.ID)
+ _ = tRepos.Attachments.Delete(ctx, tGroup.ID, photo1.ID)
+ _ = tRepos.Attachments.Delete(ctx, tGroup.ID, photo2.ID)
})
// First photo should be primary (since it was created first)
@@ -290,25 +289,25 @@ func TestAttachmentRepo_PathNormalization(t *testing.T) {
PrefixPath: ".data",
},
}
-
+
testGUID := uuid.MustParse("eb6bf410-a1a8-478d-a803-ca3948368a0c")
testHash := "f295eb01-18a9-4631-a797-70bd9623edd4.png"
-
+
// Test path() method - should always return forward slashes
relativePath := repo.path(testGUID, testHash)
assert.Equal(t, "eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", relativePath)
assert.NotContains(t, relativePath, "\\", "path() should not contain backslashes")
-
+
// Test fullPath() with forward slash input (from database)
fullPath := repo.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png")
assert.Equal(t, ".data/eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", fullPath)
assert.NotContains(t, fullPath, "\\", "fullPath() should not contain backslashes")
-
+
// Test fullPath() with backslash input (legacy Windows paths from old database)
fullPathWithBackslash := repo.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c\\documents\\f295eb01-18a9-4631-a797-70bd9623edd4.png")
assert.Equal(t, ".data/eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", fullPathWithBackslash)
assert.NotContains(t, fullPathWithBackslash, "\\", "fullPath() should normalize backslashes to forward slashes")
-
+
// Test with Windows-style prefix path
repoWindows := &AttachmentRepo{
storage: config.Storage{
@@ -317,7 +316,7 @@ func TestAttachmentRepo_PathNormalization(t *testing.T) {
}
fullPathWindows := repoWindows.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png")
assert.NotContains(t, fullPathWindows, "\\", "fullPath() should normalize Windows paths")
-
+
// Test empty prefix
repoNoPrefix := &AttachmentRepo{
storage: config.Storage{
@@ -326,7 +325,7 @@ func TestAttachmentRepo_PathNormalization(t *testing.T) {
}
fullPathNoPrefix := repoNoPrefix.fullPath("eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png")
assert.Equal(t, "eb6bf410-a1a8-478d-a803-ca3948368a0c/documents/f295eb01-18a9-4631-a797-70bd9623edd4.png", fullPathNoPrefix)
-
+
// Test with single slash prefix (like in tests)
repoSlashPrefix := &AttachmentRepo{
storage: config.Storage{
diff --git a/backend/internal/data/repo/repo_item_templates.go b/backend/internal/data/repo/repo_item_templates.go
index 6b9eba03..4b64904a 100644
--- a/backend/internal/data/repo/repo_item_templates.go
+++ b/backend/internal/data/repo/repo_item_templates.go
@@ -43,18 +43,18 @@ type (
Notes string `json:"notes" validate:"max=1000"`
// Default values for items
- DefaultQuantity *int `json:"defaultQuantity,omitempty" extensions:"x-nullable"`
+ DefaultQuantity *int `json:"defaultQuantity,omitempty" extensions:"x-nullable"`
DefaultInsured bool `json:"defaultInsured"`
- DefaultName *string `json:"defaultName,omitempty" extensions:"x-nullable" validate:"omitempty,max=255"`
- DefaultDescription *string `json:"defaultDescription,omitempty" extensions:"x-nullable" validate:"omitempty,max=1000"`
- DefaultManufacturer *string `json:"defaultManufacturer,omitempty" extensions:"x-nullable" validate:"omitempty,max=255"`
- DefaultModelNumber *string `json:"defaultModelNumber,omitempty" extensions:"x-nullable" validate:"omitempty,max=255"`
+ DefaultName *string `json:"defaultName,omitempty" validate:"omitempty,max=255" extensions:"x-nullable"`
+ DefaultDescription *string `json:"defaultDescription,omitempty" validate:"omitempty,max=1000" extensions:"x-nullable"`
+ DefaultManufacturer *string `json:"defaultManufacturer,omitempty" validate:"omitempty,max=255" extensions:"x-nullable"`
+ DefaultModelNumber *string `json:"defaultModelNumber,omitempty" validate:"omitempty,max=255" extensions:"x-nullable"`
DefaultLifetimeWarranty bool `json:"defaultLifetimeWarranty"`
- DefaultWarrantyDetails *string `json:"defaultWarrantyDetails,omitempty" extensions:"x-nullable" validate:"omitempty,max=1000"`
+ DefaultWarrantyDetails *string `json:"defaultWarrantyDetails,omitempty" validate:"omitempty,max=1000" extensions:"x-nullable"`
// Default location and labels
DefaultLocationID uuid.UUID `json:"defaultLocationId,omitempty" extensions:"x-nullable"`
- DefaultLabelIDs *[]uuid.UUID `json:"defaultLabelIds,omitempty" extensions:"x-nullable"`
+ DefaultLabelIDs *[]uuid.UUID `json:"defaultLabelIds,omitempty" extensions:"x-nullable"`
// Metadata flags
IncludeWarrantyFields bool `json:"includeWarrantyFields"`
@@ -72,18 +72,18 @@ type (
Notes string `json:"notes" validate:"max=1000"`
// Default values for items
- DefaultQuantity *int `json:"defaultQuantity,omitempty" extensions:"x-nullable"`
+ DefaultQuantity *int `json:"defaultQuantity,omitempty" extensions:"x-nullable"`
DefaultInsured bool `json:"defaultInsured"`
- DefaultName *string `json:"defaultName,omitempty" extensions:"x-nullable" validate:"omitempty,max=255"`
- DefaultDescription *string `json:"defaultDescription,omitempty" extensions:"x-nullable" validate:"omitempty,max=1000"`
- DefaultManufacturer *string `json:"defaultManufacturer,omitempty" extensions:"x-nullable" validate:"omitempty,max=255"`
- DefaultModelNumber *string `json:"defaultModelNumber,omitempty" extensions:"x-nullable" validate:"omitempty,max=255"`
+ DefaultName *string `json:"defaultName,omitempty" validate:"omitempty,max=255" extensions:"x-nullable"`
+ DefaultDescription *string `json:"defaultDescription,omitempty" validate:"omitempty,max=1000" extensions:"x-nullable"`
+ DefaultManufacturer *string `json:"defaultManufacturer,omitempty" validate:"omitempty,max=255" extensions:"x-nullable"`
+ DefaultModelNumber *string `json:"defaultModelNumber,omitempty" validate:"omitempty,max=255" extensions:"x-nullable"`
DefaultLifetimeWarranty bool `json:"defaultLifetimeWarranty"`
- DefaultWarrantyDetails *string `json:"defaultWarrantyDetails,omitempty" extensions:"x-nullable" validate:"omitempty,max=1000"`
+ DefaultWarrantyDetails *string `json:"defaultWarrantyDetails,omitempty" validate:"omitempty,max=1000" extensions:"x-nullable"`
// Default location and labels
DefaultLocationID uuid.UUID `json:"defaultLocationId,omitempty" extensions:"x-nullable"`
- DefaultLabelIDs *[]uuid.UUID `json:"defaultLabelIds,omitempty" extensions:"x-nullable"`
+ DefaultLabelIDs *[]uuid.UUID `json:"defaultLabelIds,omitempty" extensions:"x-nullable"`
// Metadata flags
IncludeWarrantyFields bool `json:"includeWarrantyFields"`
diff --git a/backend/internal/data/repo/repo_items.go b/backend/internal/data/repo/repo_items.go
index 3d2390fc..3ad9abee 100644
--- a/backend/internal/data/repo/repo_items.go
+++ b/backend/internal/data/repo/repo_items.go
@@ -757,7 +757,7 @@ func (e *ItemsRepository) Delete(ctx context.Context, id uuid.UUID) error {
// Delete all attachments (and their files) before deleting the item
for _, att := range itm.Edges.Attachments {
- err := e.attachments.Delete(ctx, gid, id, att.ID)
+ err := e.attachments.Delete(ctx, gid, att.ID)
if err != nil {
log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during item deletion")
// Continue with other attachments even if one fails
@@ -788,7 +788,7 @@ func (e *ItemsRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID)
// Delete all attachments (and their files) before deleting the item
for _, att := range itm.Edges.Attachments {
- err := e.attachments.Delete(ctx, gid, id, att.ID)
+ err := e.attachments.Delete(ctx, gid, att.ID)
if err != nil {
log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during item deletion")
// Continue with other attachments even if one fails
@@ -841,7 +841,7 @@ func (e *ItemsRepository) WipeInventory(ctx context.Context, gid uuid.UUID, wipe
for _, itm := range items {
// Delete all attachments first
for _, att := range itm.Edges.Attachments {
- err := e.attachments.Delete(ctx, gid, itm.ID, att.ID)
+ err := e.attachments.Delete(ctx, gid, att.ID)
if err != nil {
log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during wipe inventory")
// Continue with other attachments even if one fails
diff --git a/backend/internal/data/repo/repo_items_search_test.go b/backend/internal/data/repo/repo_items_search_test.go
index e2156815..76019a61 100644
--- a/backend/internal/data/repo/repo_items_search_test.go
+++ b/backend/internal/data/repo/repo_items_search_test.go
@@ -164,7 +164,7 @@ func TestItemsRepository_AccentInsensitiveSearch(t *testing.T) {
if tc.shouldMatch {
// If it should match, then either the original query should match
// or the normalized query should match when applied to the stored data
- assert.NotEqual(t, "", normalizedSearch, "Normalized search should not be empty")
+ assert.NotEmpty(t, normalizedSearch, "Normalized search should not be empty")
// The key insight is that we're searching with both the original and normalized queries
// So "electrónica" will be found when searching for "electronica" because:
diff --git a/backend/internal/data/repo/repo_items_test.go b/backend/internal/data/repo/repo_items_test.go
index 59f45fc2..a3b26f44 100644
--- a/backend/internal/data/repo/repo_items_test.go
+++ b/backend/internal/data/repo/repo_items_test.go
@@ -313,7 +313,7 @@ func TestItemRepository_GetAllCustomFields(t *testing.T) {
// Test getting all values from field
{
- results, err := tRepos.Items.GetAllCustomFieldValues(context.Background(), tUser.GroupID, names[0])
+ results, err := tRepos.Items.GetAllCustomFieldValues(context.Background(), tUser.DefaultGroupID, names[0])
require.NoError(t, err)
assert.ElementsMatch(t, values[:1], results)
@@ -400,33 +400,33 @@ func TestItemsRepository_DeleteByGroupWithAttachments(t *testing.T) {
func TestItemsRepository_WipeInventory(t *testing.T) {
// Create test data: items, labels, locations, and maintenance entries
-
+
// Create locations
loc1, err := tRepos.Locations.Create(context.Background(), tGroup.ID, LocationCreate{
Name: "Test Location 1",
Description: "Test location for wipe test",
})
require.NoError(t, err)
-
+
loc2, err := tRepos.Locations.Create(context.Background(), tGroup.ID, LocationCreate{
Name: "Test Location 2",
Description: "Another test location",
})
require.NoError(t, err)
-
+
// Create labels
label1, err := tRepos.Labels.Create(context.Background(), tGroup.ID, LabelCreate{
Name: "Test Label 1",
Description: "Test label for wipe test",
})
require.NoError(t, err)
-
+
label2, err := tRepos.Labels.Create(context.Background(), tGroup.ID, LabelCreate{
Name: "Test Label 2",
Description: "Another test label",
})
require.NoError(t, err)
-
+
// Create items
item1, err := tRepos.Items.Create(context.Background(), tGroup.ID, ItemCreate{
Name: "Test Item 1",
@@ -435,7 +435,7 @@ func TestItemsRepository_WipeInventory(t *testing.T) {
LabelIDs: []uuid.UUID{label1.ID},
})
require.NoError(t, err)
-
+
item2, err := tRepos.Items.Create(context.Background(), tGroup.ID, ItemCreate{
Name: "Test Item 2",
Description: "Another test item",
@@ -443,7 +443,7 @@ func TestItemsRepository_WipeInventory(t *testing.T) {
LabelIDs: []uuid.UUID{label2.ID},
})
require.NoError(t, err)
-
+
// Create maintenance entries for items
_, err = tRepos.MaintEntry.Create(context.Background(), item1.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
@@ -452,7 +452,7 @@ func TestItemsRepository_WipeInventory(t *testing.T) {
Cost: 100.0,
})
require.NoError(t, err)
-
+
_, err = tRepos.MaintEntry.Create(context.Background(), item2.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Test Maintenance 2",
@@ -460,40 +460,40 @@ func TestItemsRepository_WipeInventory(t *testing.T) {
Cost: 200.0,
})
require.NoError(t, err)
-
+
// Test 1: Wipe inventory with all options enabled
t.Run("wipe all including labels, locations, and maintenance", func(t *testing.T) {
deleted, err := tRepos.Items.WipeInventory(context.Background(), tGroup.ID, true, true, true)
require.NoError(t, err)
- assert.Greater(t, deleted, 0, "Should have deleted at least some entities")
-
+ assert.Positive(t, deleted, "Should have deleted at least some entities")
+
// Verify items are deleted
_, err = tRepos.Items.GetOneByGroup(context.Background(), tGroup.ID, item1.ID)
require.Error(t, err, "Item 1 should be deleted")
-
+
_, err = tRepos.Items.GetOneByGroup(context.Background(), tGroup.ID, item2.ID)
require.Error(t, err, "Item 2 should be deleted")
-
+
// Verify maintenance entries are deleted (query by item ID, should return empty)
maint1List, err := tRepos.MaintEntry.GetMaintenanceByItemID(context.Background(), tGroup.ID, item1.ID, MaintenanceFilters{})
require.NoError(t, err)
assert.Empty(t, maint1List, "Maintenance entry 1 should be deleted")
-
+
maint2List, err := tRepos.MaintEntry.GetMaintenanceByItemID(context.Background(), tGroup.ID, item2.ID, MaintenanceFilters{})
require.NoError(t, err)
assert.Empty(t, maint2List, "Maintenance entry 2 should be deleted")
-
+
// Verify labels are deleted
_, err = tRepos.Labels.GetOneByGroup(context.Background(), tGroup.ID, label1.ID)
require.Error(t, err, "Label 1 should be deleted")
-
+
_, err = tRepos.Labels.GetOneByGroup(context.Background(), tGroup.ID, label2.ID)
require.Error(t, err, "Label 2 should be deleted")
-
+
// Verify locations are deleted
_, err = tRepos.Locations.Get(context.Background(), loc1.ID)
require.Error(t, err, "Location 1 should be deleted")
-
+
_, err = tRepos.Locations.Get(context.Background(), loc2.ID)
require.Error(t, err, "Location 2 should be deleted")
})
@@ -506,13 +506,13 @@ func TestItemsRepository_WipeInventory_OnlyItems(t *testing.T) {
Description: "Test location for wipe test",
})
require.NoError(t, err)
-
+
label, err := tRepos.Labels.Create(context.Background(), tGroup.ID, LabelCreate{
Name: "Test Label",
Description: "Test label for wipe test",
})
require.NoError(t, err)
-
+
item, err := tRepos.Items.Create(context.Background(), tGroup.ID, ItemCreate{
Name: "Test Item",
Description: "Test item for wipe test",
@@ -520,7 +520,7 @@ func TestItemsRepository_WipeInventory_OnlyItems(t *testing.T) {
LabelIDs: []uuid.UUID{label.ID},
})
require.NoError(t, err)
-
+
_, err = tRepos.MaintEntry.Create(context.Background(), item.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Test Maintenance",
@@ -528,31 +528,30 @@ func TestItemsRepository_WipeInventory_OnlyItems(t *testing.T) {
Cost: 100.0,
})
require.NoError(t, err)
-
+
// Test: Wipe inventory with only items (no labels, locations, or maintenance)
deleted, err := tRepos.Items.WipeInventory(context.Background(), tGroup.ID, false, false, false)
require.NoError(t, err)
- assert.Greater(t, deleted, 0, "Should have deleted at least the item")
-
+ assert.Positive(t, deleted, "Should have deleted at least the item")
+
// Verify item is deleted
_, err = tRepos.Items.GetOneByGroup(context.Background(), tGroup.ID, item.ID)
require.Error(t, err, "Item should be deleted")
-
+
// Verify maintenance entry is deleted due to cascade
maintList, err := tRepos.MaintEntry.GetMaintenanceByItemID(context.Background(), tGroup.ID, item.ID, MaintenanceFilters{})
require.NoError(t, err)
assert.Empty(t, maintList, "Maintenance entry should be cascade deleted with item")
-
+
// Verify label still exists
_, err = tRepos.Labels.GetOneByGroup(context.Background(), tGroup.ID, label.ID)
require.NoError(t, err, "Label should still exist")
-
+
// Verify location still exists
_, err = tRepos.Locations.Get(context.Background(), loc.ID)
require.NoError(t, err, "Location should still exist")
-
+
// Cleanup
_ = tRepos.Labels.DeleteByGroup(context.Background(), tGroup.ID, label.ID)
_ = tRepos.Locations.delete(context.Background(), loc.ID)
}
-
diff --git a/backend/internal/data/repo/repo_notifier.go b/backend/internal/data/repo/repo_notifier.go
index 867271b7..337122d7 100644
--- a/backend/internal/data/repo/repo_notifier.go
+++ b/backend/internal/data/repo/repo_notifier.go
@@ -59,9 +59,10 @@ type (
}
)
-func (r *NotifierRepository) GetByUser(ctx context.Context, userID uuid.UUID) ([]NotifierOut, error) {
+func (r *NotifierRepository) GetByUser(ctx context.Context, userID uuid.UUID, tenantID uuid.UUID) ([]NotifierOut, error) {
notifier, err := r.db.Notifier.Query().
Where(notifier.UserID(userID)).
+ Where(notifier.GroupID(tenantID)).
Order(ent.Asc(notifier.FieldName)).
All(ctx)
diff --git a/backend/internal/data/repo/repo_tokens.go b/backend/internal/data/repo/repo_tokens.go
index f6b93260..355a9df1 100644
--- a/backend/internal/data/repo/repo_tokens.go
+++ b/backend/internal/data/repo/repo_tokens.go
@@ -40,7 +40,7 @@ func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (U
Where(authtokens.ExpiresAtGTE(time.Now())).
WithUser().
QueryUser().
- WithGroup().
+ WithGroups().
Only(ctx)
if err != nil {
return UserOut{}, err
diff --git a/backend/internal/data/repo/repo_users.go b/backend/internal/data/repo/repo_users.go
index 9af394fa..814edeb8 100644
--- a/backend/internal/data/repo/repo_users.go
+++ b/backend/internal/data/repo/repo_users.go
@@ -5,6 +5,7 @@ import (
"github.com/google/uuid"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
)
@@ -17,12 +18,12 @@ type (
// in the database. It should to create users from an API unless the user has
// rights to create SuperUsers. For regular user in data use the UserIn struct.
UserCreate struct {
- Name string `json:"name"`
- Email string `json:"email"`
- Password *string `json:"password"`
- IsSuperuser bool `json:"isSuperuser"`
- GroupID uuid.UUID `json:"groupID"`
- IsOwner bool `json:"isOwner"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Password *string `json:"password"`
+ IsSuperuser bool `json:"isSuperUser"`
+ DefaultGroupID uuid.UUID `json:"defaultGroupID"`
+ IsOwner bool `json:"isOwner"`
}
UserUpdate struct {
@@ -31,22 +32,30 @@ type (
}
UserOut struct {
- ID uuid.UUID `json:"id"`
- Name string `json:"name"`
- Email string `json:"email"`
- IsSuperuser bool `json:"isSuperuser"`
- GroupID uuid.UUID `json:"groupId"`
- GroupName string `json:"groupName"`
- PasswordHash string `json:"-"`
- IsOwner bool `json:"isOwner"`
- OidcIssuer *string `json:"oidcIssuer"`
- OidcSubject *string `json:"oidcSubject"`
+ ID uuid.UUID `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ IsSuperuser bool `json:"isSuperuser"`
+ DefaultGroupID uuid.UUID `json:"defaultGroupId"`
+ GroupIDs []uuid.UUID `json:"groupIds"`
+ PasswordHash string `json:"-"`
+ IsOwner bool `json:"isOwner"`
+ OidcIssuer *string `json:"oidcIssuer"`
+ OidcSubject *string `json:"oidcSubject"`
+ }
+
+ UserSummary struct {
+ Name string `json:"name"`
+ Email string `json:"email"`
+ IsOwner bool `json:"isOwner"`
+ ID uuid.UUID `json:"id"`
}
)
var (
- mapUserOutErr = mapTErrFunc(mapUserOut)
- mapUsersOutErr = mapTEachErrFunc(mapUserOut)
+ mapUserOutErr = mapTErrFunc(mapUserOut)
+ mapUsersOutErr = mapTEachErrFunc(mapUserOut)
+ mapUsersSummaryErr = mapTEachErrFunc(mapUserSummary)
)
func mapUserOut(user *ent.User) UserOut {
@@ -55,37 +64,64 @@ func mapUserOut(user *ent.User) UserOut {
passwordHash = *user.Password
}
+ groupIDs := make([]uuid.UUID, len(user.Edges.Groups))
+ for i, g := range user.Edges.Groups {
+ groupIDs[i] = g.ID
+ }
+
+ // Get the default group ID, handling the optional pointer
+ defaultGroupID := uuid.Nil
+ if user.DefaultGroupID != nil {
+ defaultGroupID = *user.DefaultGroupID
+ }
+
return UserOut{
- ID: user.ID,
- Name: user.Name,
- Email: user.Email,
- IsSuperuser: user.IsSuperuser,
- GroupID: user.Edges.Group.ID,
- GroupName: user.Edges.Group.Name,
- PasswordHash: passwordHash,
- IsOwner: user.Role == "owner",
- OidcIssuer: user.OidcIssuer,
- OidcSubject: user.OidcSubject,
+ ID: user.ID,
+ Name: user.Name,
+ Email: user.Email,
+ IsSuperuser: user.IsSuperuser,
+ DefaultGroupID: defaultGroupID,
+ GroupIDs: groupIDs,
+ PasswordHash: passwordHash,
+ IsOwner: user.Role == "owner",
+ OidcIssuer: user.OidcIssuer,
+ OidcSubject: user.OidcSubject,
+ }
+}
+
+func mapUserSummary(user *ent.User) UserSummary {
+ return UserSummary{
+ Name: user.Name,
+ Email: user.Email,
+ IsOwner: user.Role == "owner",
+ ID: user.ID,
}
}
func (r *UserRepository) GetOneID(ctx context.Context, id uuid.UUID) (UserOut, error) {
return mapUserOutErr(r.db.User.Query().
Where(user.ID(id)).
- WithGroup().
+ WithGroups().
Only(ctx))
}
func (r *UserRepository) GetOneEmail(ctx context.Context, email string) (UserOut, error) {
return mapUserOutErr(r.db.User.Query().
Where(user.EmailEqualFold(email)).
- WithGroup().
+ WithGroups().
+ Only(ctx),
+ )
+}
+
+func (r *UserRepository) GetOneEmailNoEdges(ctx context.Context, email string) (UserOut, error) {
+ return mapUserOutErr(r.db.User.Query().
+ Where(user.EmailEqualFold(email)).
Only(ctx),
)
}
func (r *UserRepository) GetAll(ctx context.Context) ([]UserOut, error) {
- return mapUsersOutErr(r.db.User.Query().WithGroup().All(ctx))
+ return mapUsersOutErr(r.db.User.Query().WithGroups().All(ctx))
}
func (r *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, error) {
@@ -99,8 +135,9 @@ func (r *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, e
SetName(usr.Name).
SetEmail(usr.Email).
SetIsSuperuser(usr.IsSuperuser).
- SetGroupID(usr.GroupID).
- SetRole(role)
+ SetDefaultGroupID(usr.DefaultGroupID).
+ SetRole(role).
+ AddGroupIDs(usr.DefaultGroupID)
// Only set password if provided (non-nil)
if usr.Password != nil {
@@ -126,10 +163,11 @@ func (r *UserRepository) CreateWithOIDC(ctx context.Context, usr UserCreate, iss
SetName(usr.Name).
SetEmail(usr.Email).
SetIsSuperuser(usr.IsSuperuser).
- SetGroupID(usr.GroupID).
+ SetDefaultGroupID(usr.DefaultGroupID).
SetRole(role).
SetOidcIssuer(issuer).
- SetOidcSubject(subject)
+ SetOidcSubject(subject).
+ AddGroupIDs(usr.DefaultGroupID)
if usr.Password != nil {
createQuery = createQuery.SetPassword(*usr.Password)
@@ -153,6 +191,10 @@ func (r *UserRepository) Update(ctx context.Context, id uuid.UUID, data UserUpda
return err
}
+func (r *UserRepository) UpdateDefaultGroup(ctx context.Context, id uuid.UUID, groupID uuid.UUID) error {
+ return r.db.User.UpdateOneID(id).SetDefaultGroupID(groupID).Exec(ctx)
+}
+
func (r *UserRepository) Delete(ctx context.Context, id uuid.UUID) error {
_, err := r.db.User.Delete().Where(user.ID(id)).Exec(ctx)
return err
@@ -183,6 +225,12 @@ func (r *UserRepository) SetOIDCIdentity(ctx context.Context, uid uuid.UUID, iss
func (r *UserRepository) GetOneOIDC(ctx context.Context, issuer, subject string) (UserOut, error) {
return mapUserOutErr(r.db.User.Query().
Where(user.OidcIssuerEQ(issuer), user.OidcSubjectEQ(subject)).
- WithGroup().
+ WithGroups().
Only(ctx))
}
+
+func (r *UserRepository) GetUsersByGroupID(ctx context.Context, gid uuid.UUID) ([]UserSummary, error) {
+ return mapUsersSummaryErr(r.db.User.Query().
+ Where(user.HasGroupsWith(group.ID(gid))).
+ All(ctx))
+}
diff --git a/backend/internal/data/repo/repo_users_test.go b/backend/internal/data/repo/repo_users_test.go
index 65de5e0b..33ce67fa 100644
--- a/backend/internal/data/repo/repo_users_test.go
+++ b/backend/internal/data/repo/repo_users_test.go
@@ -4,6 +4,7 @@ import (
"context"
"testing"
+ "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -11,11 +12,11 @@ import (
func userFactory() UserCreate {
password := fk.Str(10)
return UserCreate{
- Name: fk.Str(10),
- Email: fk.Email(),
- Password: &password,
- IsSuperuser: fk.Bool(),
- GroupID: tGroup.ID,
+ Name: fk.Str(10),
+ Email: fk.Email(),
+ Password: &password,
+ IsSuperuser: fk.Bool(),
+ DefaultGroupID: tGroup.ID,
}
}
@@ -87,7 +88,8 @@ func TestUserRepo_GetAll(t *testing.T) {
assert.Equal(t, usr.Email, usr2.Email)
// Check groups are loaded
- assert.NotNil(t, usr2.GroupID)
+ assert.NotEqual(t, uuid.Nil, usr2.DefaultGroupID)
+ assert.NotEmpty(t, usr2.GroupIDs)
}
}
}
diff --git a/backend/internal/data/repo/repo_wipe_integration_test.go b/backend/internal/data/repo/repo_wipe_integration_test.go
index 30a0fb95..1fe456bf 100644
--- a/backend/internal/data/repo/repo_wipe_integration_test.go
+++ b/backend/internal/data/repo/repo_wipe_integration_test.go
@@ -21,26 +21,26 @@ func TestWipeInventory_Integration(t *testing.T) {
Description: "Garage location",
})
require.NoError(t, err)
-
+
loc2, err := tRepos.Locations.Create(context.Background(), tGroup.ID, LocationCreate{
Name: "Test Basement",
Description: "Basement location",
})
require.NoError(t, err)
-
+
// 2. Create labels
label1, err := tRepos.Labels.Create(context.Background(), tGroup.ID, LabelCreate{
Name: "Test Electronics",
Description: "Electronics label",
})
require.NoError(t, err)
-
+
label2, err := tRepos.Labels.Create(context.Background(), tGroup.ID, LabelCreate{
Name: "Test Tools",
Description: "Tools label",
})
require.NoError(t, err)
-
+
// 3. Create items
item1, err := tRepos.Items.Create(context.Background(), tGroup.ID, ItemCreate{
Name: "Test Laptop",
@@ -49,7 +49,7 @@ func TestWipeInventory_Integration(t *testing.T) {
LabelIDs: []uuid.UUID{label1.ID},
})
require.NoError(t, err)
-
+
item2, err := tRepos.Items.Create(context.Background(), tGroup.ID, ItemCreate{
Name: "Test Drill",
Description: "Power drill",
@@ -57,7 +57,7 @@ func TestWipeInventory_Integration(t *testing.T) {
LabelIDs: []uuid.UUID{label2.ID},
})
require.NoError(t, err)
-
+
item3, err := tRepos.Items.Create(context.Background(), tGroup.ID, ItemCreate{
Name: "Test Monitor",
Description: "Computer monitor",
@@ -65,7 +65,7 @@ func TestWipeInventory_Integration(t *testing.T) {
LabelIDs: []uuid.UUID{label1.ID},
})
require.NoError(t, err)
-
+
// 4. Create maintenance entries
_, err = tRepos.MaintEntry.Create(context.Background(), item1.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
@@ -74,7 +74,7 @@ func TestWipeInventory_Integration(t *testing.T) {
Cost: 0,
})
require.NoError(t, err)
-
+
_, err = tRepos.MaintEntry.Create(context.Background(), item2.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Drill maintenance",
@@ -82,7 +82,7 @@ func TestWipeInventory_Integration(t *testing.T) {
Cost: 5.00,
})
require.NoError(t, err)
-
+
_, err = tRepos.MaintEntry.Create(context.Background(), item3.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Monitor calibration",
@@ -90,47 +90,47 @@ func TestWipeInventory_Integration(t *testing.T) {
Cost: 0,
})
require.NoError(t, err)
-
+
// 5. Verify items exist
allItems, err := tRepos.Items.GetAll(context.Background(), tGroup.ID)
require.NoError(t, err)
assert.GreaterOrEqual(t, len(allItems), 3, "Should have at least 3 items")
-
+
// 6. Verify maintenance entries exist
maint1List, err := tRepos.MaintEntry.GetMaintenanceByItemID(context.Background(), tGroup.ID, item1.ID, MaintenanceFilters{})
require.NoError(t, err)
assert.NotEmpty(t, maint1List, "Item 1 should have maintenance records")
-
+
maint2List, err := tRepos.MaintEntry.GetMaintenanceByItemID(context.Background(), tGroup.ID, item2.ID, MaintenanceFilters{})
require.NoError(t, err)
assert.NotEmpty(t, maint2List, "Item 2 should have maintenance records")
-
+
// 7. Test wipe inventory with all options enabled
deleted, err := tRepos.Items.WipeInventory(context.Background(), tGroup.ID, true, true, true)
require.NoError(t, err)
- assert.Greater(t, deleted, 0, "Should have deleted entities")
-
+ assert.Positive(t, deleted, "Should have deleted entities")
+
// 8. Verify all items are deleted
allItemsAfter, err := tRepos.Items.GetAll(context.Background(), tGroup.ID)
require.NoError(t, err)
- assert.Equal(t, 0, len(allItemsAfter), "All items should be deleted")
-
+ assert.Empty(t, allItemsAfter, "All items should be deleted")
+
// 9. Verify maintenance entries are deleted
maint1After, err := tRepos.MaintEntry.GetMaintenanceByItemID(context.Background(), tGroup.ID, item1.ID, MaintenanceFilters{})
require.NoError(t, err)
assert.Empty(t, maint1After, "Item 1 maintenance records should be deleted")
-
+
// 10. Verify labels are deleted
_, err = tRepos.Labels.GetOneByGroup(context.Background(), tGroup.ID, label1.ID)
require.Error(t, err, "Label 1 should be deleted")
-
+
_, err = tRepos.Labels.GetOneByGroup(context.Background(), tGroup.ID, label2.ID)
require.Error(t, err, "Label 2 should be deleted")
-
+
// 11. Verify locations are deleted
_, err = tRepos.Locations.Get(context.Background(), loc1.ID)
require.Error(t, err, "Location 1 should be deleted")
-
+
_, err = tRepos.Locations.Get(context.Background(), loc2.ID)
require.Error(t, err, "Location 2 should be deleted")
}
@@ -143,13 +143,13 @@ func TestWipeInventory_SelectiveWipe(t *testing.T) {
Description: "Office location",
})
require.NoError(t, err)
-
+
label, err := tRepos.Labels.Create(context.Background(), tGroup.ID, LabelCreate{
Name: "Test Important",
Description: "Important label",
})
require.NoError(t, err)
-
+
item, err := tRepos.Items.Create(context.Background(), tGroup.ID, ItemCreate{
Name: "Test Computer",
Description: "Desktop computer",
@@ -157,7 +157,7 @@ func TestWipeInventory_SelectiveWipe(t *testing.T) {
LabelIDs: []uuid.UUID{label.ID},
})
require.NoError(t, err)
-
+
_, err = tRepos.MaintEntry.Create(context.Background(), item.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "System update",
@@ -165,29 +165,29 @@ func TestWipeInventory_SelectiveWipe(t *testing.T) {
Cost: 0,
})
require.NoError(t, err)
-
+
// Test: Wipe only items (keep labels and locations)
deleted, err := tRepos.Items.WipeInventory(context.Background(), tGroup.ID, false, false, false)
require.NoError(t, err)
- assert.Greater(t, deleted, 0, "Should have deleted at least items")
-
+ assert.Positive(t, deleted, "Should have deleted at least items")
+
// Verify item is deleted
_, err = tRepos.Items.GetOneByGroup(context.Background(), tGroup.ID, item.ID)
require.Error(t, err, "Item should be deleted")
-
+
// Verify maintenance is cascade deleted
maintList, err := tRepos.MaintEntry.GetMaintenanceByItemID(context.Background(), tGroup.ID, item.ID, MaintenanceFilters{})
require.NoError(t, err)
assert.Empty(t, maintList, "Maintenance should be cascade deleted")
-
+
// Verify label still exists
_, err = tRepos.Labels.GetOneByGroup(context.Background(), tGroup.ID, label.ID)
require.NoError(t, err, "Label should still exist")
-
+
// Verify location still exists
_, err = tRepos.Locations.Get(context.Background(), loc.ID)
require.NoError(t, err, "Location should still exist")
-
+
// Cleanup
_ = tRepos.Labels.DeleteByGroup(context.Background(), tGroup.ID, label.ID)
_ = tRepos.Locations.delete(context.Background(), loc.ID)
diff --git a/backend/internal/sys/config/conf.go b/backend/internal/sys/config/conf.go
index 5525e380..8d37570e 100644
--- a/backend/internal/sys/config/conf.go
+++ b/backend/internal/sys/config/conf.go
@@ -65,14 +65,14 @@ type WebConfig struct {
}
type LabelMakerConf struct {
- Width int64 `yaml:"width" conf:"default:526"`
- Height int64 `yaml:"height" conf:"default:200"`
- Padding int64 `yaml:"padding" conf:"default:32"`
- Margin int64 `yaml:"margin" conf:"default:32"`
- FontSize float64 `yaml:"font_size" conf:"default:32.0"`
+ Width int64 `yaml:"width" conf:"default:526"`
+ Height int64 `yaml:"height" conf:"default:200"`
+ Padding int64 `yaml:"padding" conf:"default:32"`
+ Margin int64 `yaml:"margin" conf:"default:32"`
+ FontSize float64 `yaml:"font_size" conf:"default:32.0"`
PrintCommand *string `yaml:"string"`
AdditionalInformation *string `yaml:"string"`
- DynamicLength bool `yaml:"bool" conf:"default:true"`
+ DynamicLength bool `yaml:"bool" conf:"default:true"`
LabelServiceUrl *string `yaml:"label_service_url"`
LabelServiceTimeout *time.Duration `yaml:"label_service_timeout"`
RegularFontPath *string `yaml:"regular_font_path"`
@@ -80,13 +80,13 @@ type LabelMakerConf struct {
}
type OIDCConf struct {
- Enabled bool `yaml:"enabled" conf:"default:false"`
+ Enabled bool `yaml:"enabled" conf:"default:false"`
IssuerURL string `yaml:"issuer_url"`
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"`
Scope string `yaml:"scope" conf:"default:openid profile email"`
AllowedGroups string `yaml:"allowed_groups"`
- AutoRedirect bool `yaml:"auto_redirect" conf:"default:false"`
+ AutoRedirect bool `yaml:"auto_redirect" conf:"default:false"`
VerifyEmail bool `yaml:"verify_email" conf:"default:false"`
GroupClaim string `yaml:"group_claim" conf:"default:groups"`
EmailClaim string `yaml:"email_claim" conf:"default:email"`
diff --git a/backend/pkgs/textutils/normalize.go b/backend/pkgs/textutils/normalize.go
index 4e86235d..f484f4d6 100644
--- a/backend/pkgs/textutils/normalize.go
+++ b/backend/pkgs/textutils/normalize.go
@@ -22,13 +22,13 @@ func RemoveAccents(text string) string {
// 2. Removes diacritical marks (combining characters)
// 3. Normalizes back to NFC (canonical composition)
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
-
+
result, _, err := transform.String(t, text)
if err != nil {
// If transformation fails, return the original text
return text
}
-
+
return result
}
diff --git a/docs/en/api/openapi-2.0.json b/docs/en/api/openapi-2.0.json
index cb5a49f4..b2edcda4 100644
--- a/docs/en/api/openapi-2.0.json
+++ b/docs/en/api/openapi-2.0.json
@@ -283,9 +283,113 @@
}
}
}
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Create Group",
+ "parameters": [
+ {
+ "description": "Create group request",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.CreateRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.Group"
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group",
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/all": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Groups",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.Group"
+ }
+ }
+ }
+ }
}
},
"/v1/groups/invitations": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Invitations",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.GroupInvitation"
+ }
+ }
+ }
+ }
+ },
"post": {
"security": [
{
@@ -320,6 +424,154 @@
}
}
},
+ "/v1/groups/invitations/{id}": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Accept Group Invitation",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Invitation Token",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/v1.GroupAcceptInvitationResponse"
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group Invitation",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Invitation ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Members",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.UserSummary"
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Add User to Group",
+ "parameters": [
+ {
+ "description": "User ID",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.GroupMemberAdd"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members/{user_id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Remove User from Group",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "User ID",
+ "name": "user_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/groups/statistics": {
"get": {
"security": [
@@ -3527,6 +3779,10 @@
"description": "CreatedAt holds the value of the \"created_at\" field.",
"type": "string"
},
+ "default_group_id": {
+ "description": "DefaultGroupID holds the value of the \"default_group_id\" field.",
+ "type": "string"
+ },
"edges": {
"description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserQuery when eager-loading is set.",
"allOf": [
@@ -3587,13 +3843,12 @@
"$ref": "#/definitions/ent.AuthTokens"
}
},
- "group": {
- "description": "Group holds the value of the group edge.",
- "allOf": [
- {
- "$ref": "#/definitions/ent.Group"
- }
- ]
+ "groups": {
+ "description": "Groups holds the value of the groups edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/ent.Group"
+ }
},
"notifiers": {
"description": "Notifiers holds the value of the notifiers edge.",
@@ -3687,6 +3942,23 @@
}
}
},
+ "repo.GroupInvitation": {
+ "type": "object",
+ "properties": {
+ "expiresAt": {
+ "type": "string"
+ },
+ "group": {
+ "$ref": "#/definitions/repo.Group"
+ },
+ "id": {
+ "type": "string"
+ },
+ "uses": {
+ "type": "integer"
+ }
+ }
+ },
"repo.GroupStatistics": {
"type": "object",
"properties": {
@@ -4904,14 +5176,17 @@
"repo.UserOut": {
"type": "object",
"properties": {
- "email": {
+ "defaultGroupId": {
"type": "string"
},
- "groupId": {
+ "email": {
"type": "string"
},
- "groupName": {
- "type": "string"
+ "groupIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
},
"id": {
"type": "string"
@@ -4933,6 +5208,23 @@
}
}
},
+ "repo.UserSummary": {
+ "type": "object",
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "isOwner": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"repo.UserUpdate": {
"type": "object",
"properties": {
@@ -5102,6 +5394,28 @@
}
}
},
+ "v1.CreateRequest": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ }
+ },
+ "v1.GroupAcceptInvitationResponse": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"v1.GroupInvitation": {
"type": "object",
"properties": {
@@ -5132,6 +5446,17 @@
}
}
},
+ "v1.GroupMemberAdd": {
+ "type": "object",
+ "required": [
+ "userId"
+ ],
+ "properties": {
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"v1.ItemAttachmentToken": {
"type": "object",
"properties": {
diff --git a/docs/en/api/openapi-2.0.yaml b/docs/en/api/openapi-2.0.yaml
index 0d234331..96c17e8c 100644
--- a/docs/en/api/openapi-2.0.yaml
+++ b/docs/en/api/openapi-2.0.yaml
@@ -719,6 +719,9 @@ definitions:
created_at:
description: CreatedAt holds the value of the "created_at" field.
type: string
+ default_group_id:
+ description: DefaultGroupID holds the value of the "default_group_id" field.
+ type: string
edges:
allOf:
- $ref: '#/definitions/ent.UserEdges'
@@ -761,10 +764,11 @@ definitions:
items:
$ref: '#/definitions/ent.AuthTokens'
type: array
- group:
- allOf:
- - $ref: '#/definitions/ent.Group'
- description: Group holds the value of the group edge.
+ groups:
+ description: Groups holds the value of the groups edge.
+ items:
+ $ref: '#/definitions/ent.Group'
+ type: array
notifiers:
description: Notifiers holds the value of the notifiers edge.
items:
@@ -828,6 +832,17 @@ definitions:
updatedAt:
type: string
type: object
+ repo.GroupInvitation:
+ properties:
+ expiresAt:
+ type: string
+ group:
+ $ref: '#/definitions/repo.Group'
+ id:
+ type: string
+ uses:
+ type: integer
+ type: object
repo.GroupStatistics:
properties:
totalItemPrice:
@@ -1660,12 +1675,14 @@ definitions:
type: object
repo.UserOut:
properties:
- email:
+ defaultGroupId:
type: string
- groupId:
- type: string
- groupName:
+ email:
type: string
+ groupIds:
+ items:
+ type: string
+ type: array
id:
type: string
isOwner:
@@ -1679,6 +1696,17 @@ definitions:
oidcSubject:
type: string
type: object
+ repo.UserSummary:
+ properties:
+ email:
+ type: string
+ id:
+ type: string
+ isOwner:
+ type: boolean
+ name:
+ type: string
+ type: object
repo.UserUpdate:
properties:
email:
@@ -1790,6 +1818,20 @@ definitions:
new:
type: string
type: object
+ v1.CreateRequest:
+ properties:
+ name:
+ type: string
+ required:
+ - name
+ type: object
+ v1.GroupAcceptInvitationResponse:
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ type: object
v1.GroupInvitation:
properties:
expiresAt:
@@ -1810,6 +1852,13 @@ definitions:
required:
- uses
type: object
+ v1.GroupMemberAdd:
+ properties:
+ userId:
+ type: string
+ required:
+ - userId
+ type: object
v1.ItemAttachmentToken:
properties:
token:
@@ -2025,6 +2074,17 @@ paths:
tags:
- Base
/v1/groups:
+ delete:
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Delete Group
+ tags:
+ - Group
get:
produces:
- application/json
@@ -2038,6 +2098,26 @@ paths:
summary: Get Group
tags:
- Group
+ post:
+ parameters:
+ - description: Create group request
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/v1.CreateRequest'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: Created
+ schema:
+ $ref: '#/definitions/repo.Group'
+ security:
+ - Bearer: []
+ summary: Create Group
+ tags:
+ - Group
put:
parameters:
- description: User Data
@@ -2058,7 +2138,38 @@ paths:
summary: Update Group
tags:
- Group
+ /v1/groups/all:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.Group'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Groups
+ tags:
+ - Group
/v1/groups/invitations:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.GroupInvitation'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Group Invitations
+ tags:
+ - Group
post:
parameters:
- description: User Data
@@ -2079,6 +2190,95 @@ paths:
summary: Create Group Invitation
tags:
- Group
+ /v1/groups/invitations/{id}:
+ delete:
+ parameters:
+ - description: Invitation ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Delete Group Invitation
+ tags:
+ - Group
+ post:
+ parameters:
+ - description: Invitation Token
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ $ref: '#/definitions/v1.GroupAcceptInvitationResponse'
+ security:
+ - Bearer: []
+ summary: Accept Group Invitation
+ tags:
+ - Group
+ /v1/groups/members:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.UserSummary'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Group Members
+ tags:
+ - Group
+ post:
+ parameters:
+ - description: User ID
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/v1.GroupMemberAdd'
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Add User to Group
+ tags:
+ - Group
+ /v1/groups/members/{user_id}:
+ delete:
+ parameters:
+ - description: User ID
+ in: path
+ name: user_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Remove User from Group
+ tags:
+ - Group
/v1/groups/statistics:
get:
produces:
diff --git a/docs/en/api/openapi-3.0.json b/docs/en/api/openapi-3.0.json
index f4ce81bf..58eb9a09 100644
--- a/docs/en/api/openapi-3.0.json
+++ b/docs/en/api/openapi-3.0.json
@@ -289,9 +289,113 @@
}
}
}
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Create Group",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/v1.CreateRequest"
+ }
+ }
+ },
+ "description": "Create group request",
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "Created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/repo.Group"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group",
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/all": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Groups",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/repo.Group"
+ }
+ }
+ }
+ }
+ }
+ }
}
},
"/v1/groups/invitations": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Invitations",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/repo.GroupInvitation"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"post": {
"security": [
{
@@ -327,6 +431,153 @@
}
}
},
+ "/v1/groups/invitations/{id}": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Accept Group Invitation",
+ "parameters": [
+ {
+ "description": "Invitation Token",
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/v1.GroupAcceptInvitationResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group Invitation",
+ "parameters": [
+ {
+ "description": "Invitation ID",
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Members",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/repo.UserSummary"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Add User to Group",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/v1.GroupMemberAdd"
+ }
+ }
+ },
+ "description": "User ID",
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members/{user_id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Remove User from Group",
+ "parameters": [
+ {
+ "description": "User ID",
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/groups/statistics": {
"get": {
"security": [
@@ -3727,6 +3978,10 @@
"description": "CreatedAt holds the value of the \"created_at\" field.",
"type": "string"
},
+ "default_group_id": {
+ "description": "DefaultGroupID holds the value of the \"default_group_id\" field.",
+ "type": "string"
+ },
"edges": {
"description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserQuery when eager-loading is set.",
"allOf": [
@@ -3787,13 +4042,12 @@
"$ref": "#/components/schemas/ent.AuthTokens"
}
},
- "group": {
- "description": "Group holds the value of the group edge.",
- "allOf": [
- {
- "$ref": "#/components/schemas/ent.Group"
- }
- ]
+ "groups": {
+ "description": "Groups holds the value of the groups edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ent.Group"
+ }
},
"notifiers": {
"description": "Notifiers holds the value of the notifiers edge.",
@@ -3887,6 +4141,23 @@
}
}
},
+ "repo.GroupInvitation": {
+ "type": "object",
+ "properties": {
+ "expiresAt": {
+ "type": "string"
+ },
+ "group": {
+ "$ref": "#/components/schemas/repo.Group"
+ },
+ "id": {
+ "type": "string"
+ },
+ "uses": {
+ "type": "integer"
+ }
+ }
+ },
"repo.GroupStatistics": {
"type": "object",
"properties": {
@@ -5104,14 +5375,17 @@
"repo.UserOut": {
"type": "object",
"properties": {
- "email": {
+ "defaultGroupId": {
"type": "string"
},
- "groupId": {
+ "email": {
"type": "string"
},
- "groupName": {
- "type": "string"
+ "groupIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
},
"id": {
"type": "string"
@@ -5133,6 +5407,23 @@
}
}
},
+ "repo.UserSummary": {
+ "type": "object",
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "isOwner": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"repo.UserUpdate": {
"type": "object",
"properties": {
@@ -5302,6 +5593,28 @@
}
}
},
+ "v1.CreateRequest": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ }
+ },
+ "v1.GroupAcceptInvitationResponse": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"v1.GroupInvitation": {
"type": "object",
"properties": {
@@ -5332,6 +5645,17 @@
}
}
},
+ "v1.GroupMemberAdd": {
+ "type": "object",
+ "required": [
+ "userId"
+ ],
+ "properties": {
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"v1.ItemAttachmentToken": {
"type": "object",
"properties": {
diff --git a/docs/en/api/openapi-3.0.yaml b/docs/en/api/openapi-3.0.yaml
index eda39cf7..da6563b2 100644
--- a/docs/en/api/openapi-3.0.yaml
+++ b/docs/en/api/openapi-3.0.yaml
@@ -170,7 +170,67 @@ paths:
application/json:
schema:
$ref: "#/components/schemas/repo.Group"
+ post:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Create Group
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/v1.CreateRequest"
+ description: Create group request
+ required: true
+ responses:
+ "201":
+ description: Created
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/repo.Group"
+ delete:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Delete Group
+ responses:
+ "204":
+ description: No Content
+ /v1/groups/all:
+ get:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Get All Groups
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/repo.Group"
/v1/groups/invitations:
+ get:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Get All Group Invitations
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/repo.GroupInvitation"
post:
security:
- Bearer: []
@@ -191,6 +251,92 @@ paths:
application/json:
schema:
$ref: "#/components/schemas/v1.GroupInvitation"
+ "/v1/groups/invitations/{id}":
+ post:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Accept Group Invitation
+ parameters:
+ - description: Invitation Token
+ name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/v1.GroupAcceptInvitationResponse"
+ delete:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Delete Group Invitation
+ parameters:
+ - description: Invitation ID
+ name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "204":
+ description: No Content
+ /v1/groups/members:
+ get:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Get All Group Members
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: "#/components/schemas/repo.UserSummary"
+ post:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Add User to Group
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/v1.GroupMemberAdd"
+ description: User ID
+ required: true
+ responses:
+ "204":
+ description: No Content
+ "/v1/groups/members/{user_id}":
+ delete:
+ security:
+ - Bearer: []
+ tags:
+ - Group
+ summary: Remove User from Group
+ parameters:
+ - description: User ID
+ name: user_id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "204":
+ description: No Content
/v1/groups/statistics:
get:
security:
@@ -2322,6 +2468,9 @@ components:
created_at:
description: CreatedAt holds the value of the "created_at" field.
type: string
+ default_group_id:
+ description: DefaultGroupID holds the value of the "default_group_id" field.
+ type: string
edges:
description: >-
Edges holds the relations/edges for other nodes in the graph.
@@ -2365,10 +2514,11 @@ components:
type: array
items:
$ref: "#/components/schemas/ent.AuthTokens"
- group:
- description: Group holds the value of the group edge.
- allOf:
- - $ref: "#/components/schemas/ent.Group"
+ groups:
+ description: Groups holds the value of the groups edge.
+ type: array
+ items:
+ $ref: "#/components/schemas/ent.Group"
notifiers:
description: Notifiers holds the value of the notifiers edge.
type: array
@@ -2431,6 +2581,17 @@ components:
type: string
updatedAt:
type: string
+ repo.GroupInvitation:
+ type: object
+ properties:
+ expiresAt:
+ type: string
+ group:
+ $ref: "#/components/schemas/repo.Group"
+ id:
+ type: string
+ uses:
+ type: integer
repo.GroupStatistics:
type: object
properties:
@@ -3264,12 +3425,14 @@ components:
repo.UserOut:
type: object
properties:
- email:
- type: string
- groupId:
+ defaultGroupId:
type: string
- groupName:
+ email:
type: string
+ groupIds:
+ type: array
+ items:
+ type: string
id:
type: string
isOwner:
@@ -3282,6 +3445,17 @@ components:
type: string
oidcSubject:
type: string
+ repo.UserSummary:
+ type: object
+ properties:
+ email:
+ type: string
+ id:
+ type: string
+ isOwner:
+ type: boolean
+ name:
+ type: string
repo.UserUpdate:
type: object
properties:
@@ -3393,6 +3567,20 @@ components:
type: string
new:
type: string
+ v1.CreateRequest:
+ type: object
+ required:
+ - name
+ properties:
+ name:
+ type: string
+ v1.GroupAcceptInvitationResponse:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
v1.GroupInvitation:
type: object
properties:
@@ -3413,6 +3601,13 @@ components:
type: integer
maximum: 100
minimum: 1
+ v1.GroupMemberAdd:
+ type: object
+ required:
+ - userId
+ properties:
+ userId:
+ type: string
v1.ItemAttachmentToken:
type: object
properties:
diff --git a/docs/en/api/swagger-2.0.json b/docs/en/api/swagger-2.0.json
index cb5a49f4..b2edcda4 100644
--- a/docs/en/api/swagger-2.0.json
+++ b/docs/en/api/swagger-2.0.json
@@ -283,9 +283,113 @@
}
}
}
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Create Group",
+ "parameters": [
+ {
+ "description": "Create group request",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.CreateRequest"
+ }
+ }
+ ],
+ "responses": {
+ "201": {
+ "description": "Created",
+ "schema": {
+ "$ref": "#/definitions/repo.Group"
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group",
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/all": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Groups",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.Group"
+ }
+ }
+ }
+ }
}
},
"/v1/groups/invitations": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Invitations",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.GroupInvitation"
+ }
+ }
+ }
+ }
+ },
"post": {
"security": [
{
@@ -320,6 +424,154 @@
}
}
},
+ "/v1/groups/invitations/{id}": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Accept Group Invitation",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Invitation Token",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "$ref": "#/definitions/v1.GroupAcceptInvitationResponse"
+ }
+ }
+ }
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Delete Group Invitation",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "Invitation ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Get All Group Members",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/repo.UserSummary"
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Add User to Group",
+ "parameters": [
+ {
+ "description": "User ID",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/v1.GroupMemberAdd"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
+ "/v1/groups/members/{user_id}": {
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Group"
+ ],
+ "summary": "Remove User from Group",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "User ID",
+ "name": "user_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "No Content"
+ }
+ }
+ }
+ },
"/v1/groups/statistics": {
"get": {
"security": [
@@ -3527,6 +3779,10 @@
"description": "CreatedAt holds the value of the \"created_at\" field.",
"type": "string"
},
+ "default_group_id": {
+ "description": "DefaultGroupID holds the value of the \"default_group_id\" field.",
+ "type": "string"
+ },
"edges": {
"description": "Edges holds the relations/edges for other nodes in the graph.\nThe values are being populated by the UserQuery when eager-loading is set.",
"allOf": [
@@ -3587,13 +3843,12 @@
"$ref": "#/definitions/ent.AuthTokens"
}
},
- "group": {
- "description": "Group holds the value of the group edge.",
- "allOf": [
- {
- "$ref": "#/definitions/ent.Group"
- }
- ]
+ "groups": {
+ "description": "Groups holds the value of the groups edge.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/ent.Group"
+ }
},
"notifiers": {
"description": "Notifiers holds the value of the notifiers edge.",
@@ -3687,6 +3942,23 @@
}
}
},
+ "repo.GroupInvitation": {
+ "type": "object",
+ "properties": {
+ "expiresAt": {
+ "type": "string"
+ },
+ "group": {
+ "$ref": "#/definitions/repo.Group"
+ },
+ "id": {
+ "type": "string"
+ },
+ "uses": {
+ "type": "integer"
+ }
+ }
+ },
"repo.GroupStatistics": {
"type": "object",
"properties": {
@@ -4904,14 +5176,17 @@
"repo.UserOut": {
"type": "object",
"properties": {
- "email": {
+ "defaultGroupId": {
"type": "string"
},
- "groupId": {
+ "email": {
"type": "string"
},
- "groupName": {
- "type": "string"
+ "groupIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
},
"id": {
"type": "string"
@@ -4933,6 +5208,23 @@
}
}
},
+ "repo.UserSummary": {
+ "type": "object",
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "isOwner": {
+ "type": "boolean"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"repo.UserUpdate": {
"type": "object",
"properties": {
@@ -5102,6 +5394,28 @@
}
}
},
+ "v1.CreateRequest": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ }
+ },
+ "v1.GroupAcceptInvitationResponse": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ }
+ },
"v1.GroupInvitation": {
"type": "object",
"properties": {
@@ -5132,6 +5446,17 @@
}
}
},
+ "v1.GroupMemberAdd": {
+ "type": "object",
+ "required": [
+ "userId"
+ ],
+ "properties": {
+ "userId": {
+ "type": "string"
+ }
+ }
+ },
"v1.ItemAttachmentToken": {
"type": "object",
"properties": {
diff --git a/docs/en/api/swagger-2.0.yaml b/docs/en/api/swagger-2.0.yaml
index 0d234331..96c17e8c 100644
--- a/docs/en/api/swagger-2.0.yaml
+++ b/docs/en/api/swagger-2.0.yaml
@@ -719,6 +719,9 @@ definitions:
created_at:
description: CreatedAt holds the value of the "created_at" field.
type: string
+ default_group_id:
+ description: DefaultGroupID holds the value of the "default_group_id" field.
+ type: string
edges:
allOf:
- $ref: '#/definitions/ent.UserEdges'
@@ -761,10 +764,11 @@ definitions:
items:
$ref: '#/definitions/ent.AuthTokens'
type: array
- group:
- allOf:
- - $ref: '#/definitions/ent.Group'
- description: Group holds the value of the group edge.
+ groups:
+ description: Groups holds the value of the groups edge.
+ items:
+ $ref: '#/definitions/ent.Group'
+ type: array
notifiers:
description: Notifiers holds the value of the notifiers edge.
items:
@@ -828,6 +832,17 @@ definitions:
updatedAt:
type: string
type: object
+ repo.GroupInvitation:
+ properties:
+ expiresAt:
+ type: string
+ group:
+ $ref: '#/definitions/repo.Group'
+ id:
+ type: string
+ uses:
+ type: integer
+ type: object
repo.GroupStatistics:
properties:
totalItemPrice:
@@ -1660,12 +1675,14 @@ definitions:
type: object
repo.UserOut:
properties:
- email:
+ defaultGroupId:
type: string
- groupId:
- type: string
- groupName:
+ email:
type: string
+ groupIds:
+ items:
+ type: string
+ type: array
id:
type: string
isOwner:
@@ -1679,6 +1696,17 @@ definitions:
oidcSubject:
type: string
type: object
+ repo.UserSummary:
+ properties:
+ email:
+ type: string
+ id:
+ type: string
+ isOwner:
+ type: boolean
+ name:
+ type: string
+ type: object
repo.UserUpdate:
properties:
email:
@@ -1790,6 +1818,20 @@ definitions:
new:
type: string
type: object
+ v1.CreateRequest:
+ properties:
+ name:
+ type: string
+ required:
+ - name
+ type: object
+ v1.GroupAcceptInvitationResponse:
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ type: object
v1.GroupInvitation:
properties:
expiresAt:
@@ -1810,6 +1852,13 @@ definitions:
required:
- uses
type: object
+ v1.GroupMemberAdd:
+ properties:
+ userId:
+ type: string
+ required:
+ - userId
+ type: object
v1.ItemAttachmentToken:
properties:
token:
@@ -2025,6 +2074,17 @@ paths:
tags:
- Base
/v1/groups:
+ delete:
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Delete Group
+ tags:
+ - Group
get:
produces:
- application/json
@@ -2038,6 +2098,26 @@ paths:
summary: Get Group
tags:
- Group
+ post:
+ parameters:
+ - description: Create group request
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/v1.CreateRequest'
+ produces:
+ - application/json
+ responses:
+ "201":
+ description: Created
+ schema:
+ $ref: '#/definitions/repo.Group'
+ security:
+ - Bearer: []
+ summary: Create Group
+ tags:
+ - Group
put:
parameters:
- description: User Data
@@ -2058,7 +2138,38 @@ paths:
summary: Update Group
tags:
- Group
+ /v1/groups/all:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.Group'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Groups
+ tags:
+ - Group
/v1/groups/invitations:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.GroupInvitation'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Group Invitations
+ tags:
+ - Group
post:
parameters:
- description: User Data
@@ -2079,6 +2190,95 @@ paths:
summary: Create Group Invitation
tags:
- Group
+ /v1/groups/invitations/{id}:
+ delete:
+ parameters:
+ - description: Invitation ID
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Delete Group Invitation
+ tags:
+ - Group
+ post:
+ parameters:
+ - description: Invitation Token
+ in: path
+ name: id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ $ref: '#/definitions/v1.GroupAcceptInvitationResponse'
+ security:
+ - Bearer: []
+ summary: Accept Group Invitation
+ tags:
+ - Group
+ /v1/groups/members:
+ get:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ items:
+ $ref: '#/definitions/repo.UserSummary'
+ type: array
+ security:
+ - Bearer: []
+ summary: Get All Group Members
+ tags:
+ - Group
+ post:
+ parameters:
+ - description: User ID
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: '#/definitions/v1.GroupMemberAdd'
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Add User to Group
+ tags:
+ - Group
+ /v1/groups/members/{user_id}:
+ delete:
+ parameters:
+ - description: User ID
+ in: path
+ name: user_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "204":
+ description: No Content
+ security:
+ - Bearer: []
+ summary: Remove User from Group
+ tags:
+ - Group
/v1/groups/statistics:
get:
produces:
diff --git a/frontend/components/App/CreateModal.vue b/frontend/components/App/CreateModal.vue
index 5720a972..fff86ffd 100644
--- a/frontend/components/App/CreateModal.vue
+++ b/frontend/components/App/CreateModal.vue
@@ -10,7 +10,7 @@
<slot />
- <DialogFooter>
+ <DialogFooter v-if="!hideFooter">
<i18n-t
keypath="components.app.create_modal.createAndAddAnother"
tag="span"
@@ -55,5 +55,6 @@
defineProps<{
dialogId: DialogID;
title: string;
+ hideFooter?: boolean;
}>();
</script>
diff --git a/frontend/components/Base/Container.vue b/frontend/components/Base/Container.vue
index 13d80719..cc240883 100644
--- a/frontend/components/Base/Container.vue
+++ b/frontend/components/Base/Container.vue
@@ -1,14 +1,22 @@
<script lang="ts" setup>
- defineProps({
+ import { cn } from "~/lib/utils";
+
+ const props = defineProps({
cmp: {
type: String,
default: "div",
},
+ class: {
+ type: String,
+ default: "",
+ },
});
+
+ const cmpClass = computed(() => cn("container mx-auto my-4 max-w-7xl px-4", props.class));
</script>
<template>
- <component :is="cmp" class="container mx-auto my-4 max-w-7xl px-4">
+ <component :is="cmp" :class="cmpClass">
<slot />
</component>
</template>
diff --git a/frontend/components/Collection/CreateModal.vue b/frontend/components/Collection/CreateModal.vue
new file mode 100644
index 00000000..0b847635
--- /dev/null
+++ b/frontend/components/Collection/CreateModal.vue
@@ -0,0 +1,118 @@
+<template>
+ <BaseModal :dialog-id="DialogID.CreateCollection" :title="$t('components.collection.create_modal.title')">
+ <form class="flex min-w-0 flex-col gap-2" @submit.prevent="create()">
+ <FormTextField
+ v-model="form.name"
+ :trigger-focus="focused"
+ :autofocus="true"
+ :required="true"
+ :label="$t('components.collection.create_modal.name_label')"
+ :max-length="255"
+ :min-length="1"
+ />
+
+ <div class="mt-4 flex flex-row-reverse">
+ <ButtonGroup>
+ <Button :disabled="loading" type="submit">{{ $t("global.create") }}</Button>
+ <Button variant="outline" :disabled="loading" type="button" @click="create(false)">
+ {{ $t("global.create_and_add") }}
+ </Button>
+ </ButtonGroup>
+ </div>
+ </form>
+ </BaseModal>
+</template>
+
+<script setup lang="ts">
+ import { useI18n } from "vue-i18n";
+ import { DialogID } from "@/components/ui/dialog-provider/utils";
+ import { toast } from "@/components/ui/sonner";
+ import BaseModal from "@/components/App/CreateModal.vue";
+ import { useDialog } from "~/components/ui/dialog-provider";
+ import FormTextField from "~/components/Form/TextField.vue";
+ import { Button, ButtonGroup } from "~/components/ui/button";
+ import { useUserApi } from "~/composables/use-api";
+ import { useCollections } from "~/composables/use-collections";
+
+ const { t } = useI18n();
+
+ const { activeDialog, closeDialog, registerOpenDialogCallback } = useDialog();
+
+ const loading = ref(false);
+ const focused = ref(false);
+
+ const form = reactive({ name: "" });
+
+ const api = useUserApi();
+ const collections = useCollections();
+ const { shift } = useMagicKeys();
+
+ const redirectTo = ref("");
+
+ onMounted(() => {
+ const cleanup = registerOpenDialogCallback(DialogID.CreateCollection, params => {
+ redirectTo.value = params?.redirectTo || "";
+ });
+
+ onUnmounted(cleanup);
+ });
+
+ watch(
+ () => activeDialog.value,
+ active => {
+ if (active && active === DialogID.CreateCollection) {
+ // reset and focus on open
+ form.name = "";
+ focused.value = true;
+ }
+ }
+ );
+
+ async function create(close = true) {
+ if (loading.value) {
+ toast.error(t("components.collection.create_modal.toast.already_creating"));
+ return;
+ }
+
+ if (!form.name || form.name.trim().length === 0) {
+ toast.error(t("components.collection.create_modal.toast.please_enter_name"));
+ return;
+ }
+
+ loading.value = true;
+
+ if (shift?.value) close = false;
+
+ const { data, error } = await api.group.create(form.name.trim());
+
+ if (error) {
+ loading.value = false;
+ toast.error(t("components.collection.create_modal.toast.create_failed"));
+ return;
+ }
+
+ if (data) {
+ toast.success(t("components.collection.create_modal.toast.create_success"));
+ }
+
+ form.name = "";
+ loading.value = false;
+
+ if (close) {
+ closeDialog(DialogID.CreateCollection);
+ if (data) {
+ const createdId = data.id;
+ collections.set(createdId);
+ if (redirectTo.value === "") {
+ // reload page to reflect new collection
+ window.location.reload();
+ } else {
+ window.location.href = redirectTo.value;
+ }
+ }
+ } else {
+ // refresh global collections list
+ await collections.load();
+ }
+ }
+</script>
diff --git a/frontend/components/Collection/InviteCreateModal.vue b/frontend/components/Collection/InviteCreateModal.vue
new file mode 100644
index 00000000..7c8980da
--- /dev/null
+++ b/frontend/components/Collection/InviteCreateModal.vue
@@ -0,0 +1,121 @@
+<template>
+ <BaseModal :dialog-id="DialogID.CreateGroupInvite" :title="$t('collection.create_invite')" :hide-footer="true">
+ <form class="flex min-w-0 flex-col gap-4" @submit.prevent="create">
+ <FormTextField v-model="form.uses" :label="$t('collection.uses')" type="number" :required="true" />
+
+ <div class="flex w-full flex-col gap-1.5">
+ <Label class="cursor-pointer">{{ $t("collection.expires_at") }}</Label>
+ <VueDatePicker
+ v-model="form.expiresAt"
+ :enable-time-picker="true"
+ clearable
+ :dark="isDark"
+ :format="formatDateTime"
+ />
+ </div>
+
+ <div class="mt-4 flex flex-row-reverse">
+ <ButtonGroup>
+ <Button :disabled="loading" type="submit">
+ {{ $t("global.create") }}
+ </Button>
+ </ButtonGroup>
+ </div>
+ </form>
+ </BaseModal>
+</template>
+
+<script setup lang="ts">
+ import { useI18n } from "vue-i18n";
+ import VueDatePicker from "@vuepic/vue-datepicker";
+ import "@vuepic/vue-datepicker/dist/main.css";
+ import { DialogID } from "@/components/ui/dialog-provider/utils";
+ import { useDialog } from "~/components/ui/dialog-provider";
+ import BaseModal from "@/components/App/CreateModal.vue";
+ import FormTextField from "~/components/Form/TextField.vue";
+ import { Button, ButtonGroup } from "~/components/ui/button";
+ import { Label } from "~/components/ui/label";
+ import { toast } from "@/components/ui/sonner";
+ import { useUserApi } from "~/composables/use-api";
+ import { darkThemes } from "~/lib/data/themes";
+
+ const { t } = useI18n();
+ const { activeDialog, closeDialog } = useDialog();
+ const api = useUserApi();
+
+ const loading = ref(false);
+ const form = reactive<{ uses: number; expiresAt: Date | null }>({
+ uses: 1,
+ expiresAt: defaultExpiry(),
+ });
+
+ const isDark = useIsThemeInList(darkThemes);
+
+ const formatDateTime = (date: Date | string | number) => fmtDate(date, "human", "datetime");
+
+ function defaultExpiry(): Date {
+ return new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
+ }
+
+ watch(
+ () => activeDialog.value,
+ active => {
+ if (active && active === DialogID.CreateGroupInvite) {
+ form.uses = 1;
+ form.expiresAt = defaultExpiry();
+ loading.value = false;
+ }
+ }
+ );
+
+ async function create() {
+ if (loading.value) {
+ return;
+ }
+
+ const parsedUses = Number(form.uses ?? 0);
+ if (!Number.isFinite(parsedUses) || parsedUses < 1 || parsedUses > 100) {
+ toast.error(t("components.collection.invite_create_modal.toast.invalid_uses"));
+ return;
+ }
+ const uses = parsedUses;
+
+ if (!form.expiresAt) {
+ toast.error(t("components.collection.invite_create_modal.toast.invalid_expiry_missing"));
+ return;
+ }
+
+ const now = new Date();
+ const exp = new Date(form.expiresAt);
+ if (exp.getTime() <= now.getTime()) {
+ toast.error(t("components.collection.invite_create_modal.toast.invalid_expiry_past"));
+ return;
+ }
+
+ const expiresAtToSend: Date = exp;
+
+ loading.value = true;
+
+ try {
+ const res = await api.group.createInvitation({
+ expiresAt: expiresAtToSend,
+ uses,
+ });
+
+ if (res.error) {
+ const msg = t("errors.api_failure") + String(res.error);
+ toast.error(msg);
+ loading.value = false;
+ return;
+ }
+
+ const data = res.data ?? undefined;
+ closeDialog(DialogID.CreateGroupInvite, data);
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ toast.error(msg);
+ } finally {
+ loading.value = false;
+ }
+ }
+</script>
diff --git a/frontend/components/Collection/JoinModal.vue b/frontend/components/Collection/JoinModal.vue
new file mode 100644
index 00000000..370a594e
--- /dev/null
+++ b/frontend/components/Collection/JoinModal.vue
@@ -0,0 +1,130 @@
+<template>
+ <BaseModal :dialog-id="DialogID.JoinCollection" :title="$t('components.collection.join_modal.title')" hide-footer>
+ <form class="flex min-w-0 flex-col gap-2" @submit.prevent="join()">
+ <FormTextField
+ v-model="form.inviteCode"
+ :trigger-focus="focused"
+ :autofocus="true"
+ :required="true"
+ :label="$t('components.collection.join_modal.invite_code_label')"
+ />
+
+ <div class="mt-2 flex flex-col">
+ <span class="text-sm text-muted-foreground">
+ {{ $t("components.collection.join_modal.invites_should_look_like") }}
+ </span>
+ <div>
+ <Badge variant="outline"> AYQ4W4K5MT4CZOPB2PZRCZ4PTY </Badge>
+ <Badge variant="outline"> {{ `${domain}?token=AYQ4W4K5MT4CZOPB2PZRCZ4PTY` }} </Badge>
+ </div>
+ </div>
+
+ <Button type="button" class="mt-2" variant="outline" @click="openDialog(DialogID.CreateCollection)">
+ {{ $t("components.collection.join_modal.no_invite_code_create_one") }}
+ </Button>
+
+ <div class="mt-2 flex flex-row-reverse">
+ <Button :disabled="loading" type="submit">{{ $t("components.collection.join_modal.join") }}</Button>
+ </div>
+ </form>
+ </BaseModal>
+</template>
+
+<script setup lang="ts">
+ import { useI18n } from "vue-i18n";
+ import { DialogID } from "@/components/ui/dialog-provider/utils";
+ import { toast } from "@/components/ui/sonner";
+ import BaseModal from "@/components/App/CreateModal.vue";
+ import { useDialog } from "~/components/ui/dialog-provider";
+ import FormTextField from "~/components/Form/TextField.vue";
+ import { Button } from "~/components/ui/button";
+ import { Badge } from "~/components/ui/badge";
+ import { useUserApi } from "~/composables/use-api";
+ import { useCollections } from "~/composables/use-collections";
+
+ const { t } = useI18n();
+
+ const { activeDialog, closeDialog, openDialog, registerOpenDialogCallback } = useDialog();
+
+ const loading = ref(false);
+ const focused = ref(false);
+
+ const form = reactive({ inviteCode: "" });
+
+ const api = useUserApi();
+ const collections = useCollections();
+
+ const domain = window.location.protocol + "//" + window.location.host;
+
+ const redirectTo = ref("");
+
+ onMounted(() => {
+ const cleanup = registerOpenDialogCallback(DialogID.JoinCollection, params => {
+ redirectTo.value = params?.redirectTo || "";
+ });
+
+ onUnmounted(cleanup);
+ });
+
+ watch(
+ () => activeDialog.value,
+ active => {
+ if (active && active === DialogID.JoinCollection) {
+ // reset and focus on open
+ form.inviteCode = "";
+ focused.value = true;
+ }
+ }
+ );
+
+ async function join() {
+ if (loading.value) {
+ toast.error(t("components.collection.join_modal.toast.already_joining"));
+ return;
+ }
+
+ if (!form.inviteCode || form.inviteCode.trim().length === 0) {
+ toast.error(t("components.collection.join_modal.toast.please_enter_valid_join_code"));
+ return;
+ }
+
+ // remove everything before the first '?' character
+ const code = form.inviteCode.includes("?")
+ ? form.inviteCode.split("?")[1]?.replace("token=", "").trim()
+ : form.inviteCode.trim();
+
+ if (!code || code.length !== 26) {
+ toast.error(t("components.collection.join_modal.toast.please_enter_valid_join_code"));
+ return;
+ }
+
+ loading.value = true;
+
+ const { data, error } = await api.group.acceptInvitation(code);
+
+ if (error) {
+ loading.value = false;
+ toast.error(t("components.collection.join_modal.toast.join_failed"));
+ return;
+ }
+
+ if (data) {
+ toast.success(t("components.collection.join_modal.toast.join_success"));
+ }
+
+ form.inviteCode = "";
+ loading.value = false;
+
+ closeDialog(DialogID.JoinCollection);
+ if (data) {
+ const joinedId = data.id;
+ collections.set(joinedId);
+ if (redirectTo.value === "") {
+ // reload page to reflect joined collection
+ window.location.reload();
+ } else {
+ window.location.href = redirectTo.value;
+ }
+ }
+ }
+</script>
diff --git a/frontend/components/Collection/Selector.vue b/frontend/components/Collection/Selector.vue
new file mode 100644
index 00000000..78085659
--- /dev/null
+++ b/frontend/components/Collection/Selector.vue
@@ -0,0 +1,146 @@
+<template>
+ <Popover v-model:open="open">
+ <PopoverTrigger as-child>
+ <Button
+ variant="outline"
+ role="combobox"
+ :aria-expanded="open"
+ :size="sidebar.state.value === 'collapsed' ? 'icon' : undefined"
+ :class="sidebar.state.value === 'collapsed' ? 'size-10' : 'w-full justify-between drop-shadow-md'"
+ aria-label="Collections"
+ title="Collections"
+ >
+ <template v-if="sidebar.state.value === 'collapsed'">
+ <MdiHomeGroup class="size-5" />
+ </template>
+ <template v-else>
+ <span class="flex items-center truncate">
+ <span class="truncate">
+ {{
+ selectedCollection && selectedCollection.name
+ ? selectedCollection.name
+ : t("components.collection.selector.select_collection")
+ }}
+ </span>
+ </span>
+
+ <ChevronsUpDown class="ml-2 size-4 shrink-0 opacity-50" />
+ </template>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ :class="[sidebar.state.value === 'collapsed' ? 'min-w-48 p-0' : 'w-[--reka-popper-anchor-width] p-0']"
+ >
+ <Command :ignore-filter="true">
+ <CommandGroup>
+ <CommandItem
+ value="create-collection"
+ @select="
+ () => {
+ open = false;
+ openDialog(DialogID.CreateCollection);
+ }
+ "
+ >
+ <Plus class="mr-2 size-4" /> {{ t("components.collection.selector.create_collection") }}
+ </CommandItem>
+ <CommandItem
+ value="join-collection"
+ @select="
+ () => {
+ open = false;
+ openDialog(DialogID.JoinCollection);
+ }
+ "
+ >
+ <UserPlus class="mr-2 size-4" /> {{ t("components.collection.selector.join_collection") }}
+ </CommandItem>
+ <CommandItem as-child value="collection-settings">
+ <NuxtLink to="/collection/members" class="flex w-full items-center" @click="open = false">
+ <Settings class="mr-2 size-4" />
+ {{ t("components.collection.selector.collection_options") }}
+ </NuxtLink>
+ </CommandItem>
+ </CommandGroup>
+ <CommandInput
+ v-model="search"
+ :placeholder="t('components.collection.selector.search_collections')"
+ :display-value="_ => ''"
+ />
+ <CommandEmpty>{{ t("components.collection.selector.no_collection_found") }}</CommandEmpty>
+ <CommandList>
+ <CommandGroup :heading="t('components.collection.selector.your_collections')">
+ <CommandItem
+ v-for="collection in filteredCollections"
+ :key="collection.id"
+ :value="collection.id"
+ @select="selectCollection(collection)"
+ >
+ <Check
+ :class="cn('mr-2 h-4 w-4', selectedCollection?.id === collection.id ? 'opacity-100' : 'opacity-0')"
+ />
+ <div class="flex w-full items-center justify-between gap-2">
+ {{ collection.name }}
+ <div class="flex items-center gap-2"></div>
+ </div>
+ </CommandItem>
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+</template>
+
+<script setup lang="ts">
+ import { Check, ChevronsUpDown, Plus, UserPlus, Settings } from "lucide-vue-next";
+ import MdiHomeGroup from "~icons/mdi/home-group";
+ import fuzzysort from "fuzzysort";
+ import { Button } from "~/components/ui/button";
+ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "~/components/ui/command";
+ import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover";
+ import { cn } from "~/lib/utils";
+ import { ref, computed, watch, onMounted } from "vue";
+ import { useSidebar } from "@/components/ui/sidebar/utils";
+ import { useI18n } from "vue-i18n";
+ import { DialogID } from "@/components/ui/dialog-provider/utils";
+ import { useDialog } from "~/components/ui/dialog-provider";
+
+ const { openDialog } = useDialog();
+
+ const { t } = useI18n();
+
+ const open = ref(false);
+ const search = ref("");
+
+ const { collections, selectedCollection, load, set } = useCollections();
+ const collectionsList = computed(() => collections.value);
+
+ function selectCollection(collection: CollectionSummary) {
+ if (selectedCollection.value?.id !== collection.id) {
+ set(collection.id);
+ window.location.reload();
+ }
+ open.value = false;
+ }
+
+ const sidebar = useSidebar();
+
+ const filteredCollections = computed(() => {
+ const filtered = fuzzysort.go(search.value, collectionsList.value, { key: "name", all: true }).map(i => i.obj);
+ return filtered;
+ });
+
+ // Reset search when value is cleared
+ watch(
+ () => selectedCollection.value?.id,
+ () => {
+ if (!selectedCollection.value) {
+ search.value = "";
+ }
+ }
+ );
+
+ onMounted(() => {
+ load();
+ });
+</script>
diff --git a/frontend/components/global/CopyText.vue b/frontend/components/global/CopyText.vue
index 31903c9a..ee825ec9 100644
--- a/frontend/components/global/CopyText.vue
+++ b/frontend/components/global/CopyText.vue
@@ -1,25 +1,34 @@
<template>
- <Button size="icon" variant="outline" class="relative" @click="copyText">
- <div
- :data-copied="copied"
- class="group absolute inset-0 flex items-center justify-center transition-transform duration-300 data-[copied=true]:rotate-[360deg]"
- >
- <MdiContentCopy
- class="group-data-[copied=true]:hidden"
- :style="{
- height: `${iconSize}px`,
- width: `${iconSize}px`,
- }"
- />
- <MdiClipboard
- class="hidden group-data-[copied=true]:block"
- :style="{
- height: `${iconSize}px`,
- width: `${iconSize}px`,
- }"
- />
- </div>
- </Button>
+ <TooltipProvider :delay-duration="0">
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <Button size="icon" variant="outline" class="relative" @click="copyText">
+ <div
+ :data-copied="copied"
+ class="group absolute inset-0 flex items-center justify-center transition-transform duration-300 data-[copied=true]:rotate-[360deg]"
+ >
+ <MdiContentCopy
+ class="group-data-[copied=true]:hidden"
+ :style="{
+ height: `${iconSize}px`,
+ width: `${iconSize}px`,
+ }"
+ />
+ <MdiClipboard
+ class="hidden group-data-[copied=true]:block"
+ :style="{
+ height: `${iconSize}px`,
+ width: `${iconSize}px`,
+ }"
+ />
+ </div>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent v-if="tooltip">
+ {{ tooltip }}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
<AlertDialog v-model:open="copyError">
<AlertDialogContent>
@@ -60,6 +69,7 @@
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
+ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
const props = defineProps({
text: {
@@ -70,6 +80,10 @@
type: Number as () => number,
default: 20,
},
+ tooltip: {
+ type: String as () => string,
+ default: "",
+ },
});
const { copy, copied } = useClipboard({ source: props.text, copiedDuring: 1000 });
diff --git a/frontend/components/ui/dialog-provider/utils.ts b/frontend/components/ui/dialog-provider/utils.ts
index a833f92d..4d0acd4e 100644
--- a/frontend/components/ui/dialog-provider/utils.ts
+++ b/frontend/components/ui/dialog-provider/utils.ts
@@ -1,7 +1,13 @@
import { computed, type ComputedRef } from "vue";
import { createContext } from "reka-ui";
import { useMagicKeys, useActiveElement } from "@vueuse/core";
-import type { BarcodeProduct, ItemSummary, MaintenanceEntry, MaintenanceEntryWithDetails } from "~~/lib/api/types/data-contracts";
+import type {
+ BarcodeProduct,
+ GroupInvitation,
+ ItemSummary,
+ MaintenanceEntry,
+ MaintenanceEntryWithDetails,
+} from "~~/lib/api/types/data-contracts";
export enum DialogID {
AttachmentEdit = "attachment-edit",
@@ -9,6 +15,9 @@ export enum DialogID {
CreateItem = "create-item",
CreateLocation = "create-location",
CreateLabel = "create-label",
+ CreateCollection = "create-collection",
+ CreateGroupInvite = "create-group-invite",
+ JoinCollection = "join-collection",
CreateNotifier = "create-notifier",
CreateTemplate = "create-template",
DuplicateSettings = "duplicate-settings",
@@ -63,6 +72,8 @@ export type DialogParamsMap = {
addLabels?: boolean;
removeLabels?: boolean;
};
+ [DialogID.CreateCollection]?: { redirectTo?: string };
+ [DialogID.JoinCollection]?: { redirectTo?: string };
};
/**
@@ -73,6 +84,7 @@ export type DialogResultMap = {
[DialogID.EditMaintenance]?: boolean;
[DialogID.ItemChangeDetails]?: boolean;
[DialogID.WipeInventory]?: { wipeLabels: boolean; wipeLocations: boolean; wipeMaintenance: boolean };
+ [DialogID.CreateGroupInvite]?: GroupInvitation;
};
/** Helpers to split IDs by requirement */
diff --git a/frontend/composables/use-api.ts b/frontend/composables/use-api.ts
index ddea5d94..cf031bee 100644
--- a/frontend/composables/use-api.ts
+++ b/frontend/composables/use-api.ts
@@ -30,15 +30,41 @@ export function usePublicApi(): PublicApi {
export function useUserApi(): UserClient {
const authCtx = useAuthContext();
+ const prefs = useViewPreferences();
- const requests = new Requests("", "", {});
+ const headers: Record<string, string> = {};
+ if (prefs?.value?.collectionId) {
+ headers["X-Tenant"] = prefs.value.collectionId;
+ }
+
+ const requests = new Requests("", "", headers);
requests.addResponseInterceptor(logger);
- requests.addResponseInterceptor(r => {
+ requests.addResponseInterceptor(async r => {
if (r.status === 401) {
console.error("unauthorized request, invalidating session");
authCtx.invalidateSession();
navigateTo("/");
}
+
+ if (r.status === 403) {
+ try {
+ const contentType = r.headers.get("Content-Type") ?? "";
+ if (!contentType.startsWith("application/json")) {
+ return;
+ }
+
+ const body = (await r.json().catch(() => null)) as { error?: string } | null;
+
+ if (body?.error === "user does not have access to the requested tenant") {
+ if (prefs?.value) {
+ prefs.value.collectionId = null;
+ }
+ }
+ } catch {
+ // ignore parsing errors to avoid breaking the interceptor chain
+ console.log("failed to parse 403 response body");
+ }
+ }
});
for (const [_, observer] of Object.entries(observers)) {
diff --git a/frontend/composables/use-collections.ts b/frontend/composables/use-collections.ts
new file mode 100644
index 00000000..616bbb3a
--- /dev/null
+++ b/frontend/composables/use-collections.ts
@@ -0,0 +1,90 @@
+import { ref, computed } from "vue";
+import { useUserApi } from "~/composables/use-api";
+import { useViewPreferences } from "~/composables/use-preferences";
+import { useRoute, navigateTo } from "#imports";
+
+export type CollectionSummary = {
+ id: string;
+ name: string;
+};
+
+const collections = ref<CollectionSummary[]>([]);
+const selectedId = ref<string | null>(null);
+const refreshing = ref(false);
+
+export const useCollections = () => {
+ const load = async () => {
+ if (refreshing.value) return;
+ refreshing.value = true;
+
+ try {
+ const api = useUserApi();
+ const prefs = useViewPreferences();
+
+ const { data: userResp } = await api.user.self();
+ const user = userResp?.item;
+
+ const { data: allGroups } = await api.group.getAll();
+ const available = Array.isArray(allGroups)
+ ? (allGroups as Array<{ id: string; name: string }>).map(g => ({ id: g.id, name: g.name }))
+ : [];
+
+ collections.value = available;
+
+ try {
+ const route = useRoute();
+ if (collections.value.length === 0) {
+ if (import.meta.client && route.path !== "/no-collections") {
+ void navigateTo("/no-collections");
+ }
+ }
+ } catch (e) {
+ console.error("Navigation error in useCollections:", e);
+ }
+ const prefId = prefs.value.collectionId ?? null;
+ if (prefId && collections.value.find(c => c.id === prefId)) {
+ selectedId.value = prefId;
+ } else if (user?.defaultGroupId && collections.value.find(c => c.id === user.defaultGroupId)) {
+ selectedId.value = user.defaultGroupId;
+ prefs.value.collectionId = selectedId.value;
+ } else if (collections.value.length > 0) {
+ const first = collections.value[0];
+ if (first) {
+ selectedId.value = first.id;
+ prefs.value.collectionId = selectedId.value;
+ }
+ } else {
+ selectedId.value = null;
+ prefs.value.collectionId = null;
+ }
+ } finally {
+ refreshing.value = false;
+ }
+ };
+
+ const set = (id: string | null) => {
+ selectedId.value = id;
+ try {
+ const prefs = useViewPreferences();
+ prefs.value.collectionId = id;
+ } catch (e) {
+ // ignore
+ }
+ };
+
+ const clear = () => {
+ set(null);
+ };
+
+ const selectedCollection = computed(() => collections.value.find(c => c.id === selectedId.value) ?? null);
+
+ return {
+ collections,
+ selectedId,
+ selectedCollection,
+ refreshing,
+ load,
+ set,
+ clear,
+ };
+};
diff --git a/frontend/composables/use-preferences.ts b/frontend/composables/use-preferences.ts
index 97cad2a4..bb7bc23f 100644
--- a/frontend/composables/use-preferences.ts
+++ b/frontend/composables/use-preferences.ts
@@ -26,6 +26,7 @@ export type LocationViewPreferences = {
legacyImageFit: boolean;
language?: string;
overrideFormatLocale?: string;
+ collectionId?: string | null;
duplicateSettings: DuplicateSettings;
shownMultiTabWarning: boolean;
quickActions: {
@@ -47,6 +48,7 @@ export function useViewPreferences(): Ref<LocationViewPreferences> {
itemDisplayView: "card",
theme: "homebox",
itemsPerTablePage: 10,
+ collectionId: null,
displayLegacyHeader: false,
legacyImageFit: false,
language: null,
diff --git a/frontend/composables/use-server-events.ts b/frontend/composables/use-server-events.ts
index 356fa59d..0d61087a 100644
--- a/frontend/composables/use-server-events.ts
+++ b/frontend/composables/use-server-events.ts
@@ -1,3 +1,6 @@
+import { useViewPreferences } from "./use-preferences";
+import { watch } from "vue";
+
export enum ServerEvent {
LocationMutation = "location.mutation",
ItemMutation = "item.mutation",
@@ -9,6 +12,8 @@ export type EventMessage = {
};
let socket: WebSocket | null = null;
+let currentTenantId: string | null = null;
+let watcherSetup = false;
const listeners = new Map<ServerEvent, (() => void)[]>();
@@ -22,7 +27,12 @@ function connect(onmessage: (m: EventMessage) => void) {
const host = dev ? window.location.host.replace("3000", "7745") : window.location.host;
- const ws = new WebSocket(`${protocol}://${host}/api/v1/ws/events`);
+ let url = `${protocol}://${host}/api/v1/ws/events`;
+ if (currentTenantId) {
+ url += `?tenant=${currentTenantId}`;
+ }
+
+ const ws = new WebSocket(url);
ws.onopen = () => {
console.debug("connected to server");
@@ -57,6 +67,28 @@ function connect(onmessage: (m: EventMessage) => void) {
}
export function onServerEvent(event: ServerEvent, callback: () => void) {
+ const prefs = useViewPreferences();
+ currentTenantId = prefs.value.collectionId || null;
+
+ if (!watcherSetup) {
+ watch(
+ () => prefs.value.collectionId,
+ newId => {
+ currentTenantId = newId || null;
+ if (socket) {
+ socket.onclose = null;
+ socket.close();
+ socket = null;
+ connect(e => {
+ console.debug("received event", e);
+ listeners.get(e.event)?.forEach(c => c());
+ });
+ }
+ }
+ );
+ watcherSetup = true;
+ }
+
if (socket === null) {
connect(e => {
console.debug("received event", e);
diff --git a/frontend/layouts/default.vue b/frontend/layouts/default.vue
index b4b2fbee..70577502 100644
--- a/frontend/layouts/default.vue
+++ b/frontend/layouts/default.vue
@@ -14,6 +14,9 @@
<ItemBarcodeModal />
<AppQuickMenuModal :actions="quickMenuActions" />
<AppScannerModal />
+ <CollectionCreateModal />
+ <CollectionJoinModal />
+ <CollectionInviteCreateModal />
<SidebarProvider :default-open="sidebarState">
<Sidebar collapsible="icon">
<SidebarHeader class="items-center">
@@ -25,10 +28,13 @@
<AppLogo />
</div>
</NuxtLink>
+
+ <CollectionSelector />
+
<DropdownMenu>
<DropdownMenuTrigger as-child>
<SidebarMenuButton
- class="flex justify-center bg-primary text-primary-foreground shadow hover:bg-primary/90 group-data-[collapsible=icon]:justify-start"
+ class="flex justify-center bg-primary text-primary-foreground drop-shadow-md hover:bg-primary/90 active:bg-primary/90 active:text-primary-foreground group-data-[collapsible=icon]:justify-start"
:tooltip="$t('global.create')"
hotkey="Shortcut: Ctrl+`"
>
@@ -227,6 +233,10 @@
import AppLogo from "~/components/App/Logo.vue";
import AppHeaderDecor from "~/components/App/HeaderDecor.vue";
import AppHeaderText from "~/components/App/HeaderText.vue";
+ import CollectionSelector from "~/components/Collection/Selector.vue";
+ import CollectionCreateModal from "~/components/Collection/CreateModal.vue";
+ import CollectionJoinModal from "~/components/Collection/JoinModal.vue";
+ import CollectionInviteCreateModal from "~/components/Collection/InviteCreateModal.vue";
const { t, locale } = useI18n();
const username = computed(() => authCtx.user?.name || "User");
@@ -357,9 +367,9 @@
{
icon: MdiCog,
id: 6,
- active: computed(() => route.path === "/tools"),
- name: computed(() => t("menu.tools")),
- to: "/tools",
+ active: computed(() => route.path.includes("/collection")),
+ name: computed(() => t("menu.collection_options")),
+ to: "/collection/members",
},
];
diff --git a/frontend/lib/api/__test__/user/group.test.ts b/frontend/lib/api/__test__/user/group.test.ts
index 88b31356..ab3fdcf3 100644
--- a/frontend/lib/api/__test__/user/group.test.ts
+++ b/frontend/lib/api/__test__/user/group.test.ts
@@ -7,12 +7,16 @@ describe("first time user workflow (register, login, join group)", () => {
test("user should be able to update group", async () => {
const { client } = await factories.client.singleUse();
+ const { data: user } = await client.user.self();
const name = faker.person.firstName();
- const { response, data: group } = await client.group.update({
- name,
- currency: "eur",
- });
+ const { response, data: group } = await client.group.update(
+ {
+ name,
+ currency: "eur",
+ },
+ user.item.defaultGroupId
+ );
expect(response.status).toBe(200);
expect(group.name).toBe(name);
@@ -21,7 +25,8 @@ describe("first time user workflow (register, login, join group)", () => {
test("user should be able to get own group", async () => {
const { client } = await factories.client.singleUse();
- const { response, data: group } = await client.group.get();
+ const { data: user } = await client.user.self();
+ const { response, data: group } = await client.group.get(user.item.defaultGroupId);
expect(response.status).toBe(200);
expect(group.name).toBeTruthy();
@@ -57,7 +62,7 @@ describe("first time user workflow (register, login, join group)", () => {
const client2 = factories.client.user(loginData.token);
const { data: user2 } = await client2.user.self();
- user2.item.groupName = user1.item.groupName;
+ expect(user2.item.defaultGroupId).toBe(user1.item.defaultGroupId);
// Cleanup User 2
const { response: deleteResp } = await client2.user.delete();
diff --git a/frontend/lib/api/base/base-api.ts b/frontend/lib/api/base/base-api.ts
index b853342c..41c144e7 100644
--- a/frontend/lib/api/base/base-api.ts
+++ b/frontend/lib/api/base/base-api.ts
@@ -77,7 +77,8 @@ export class BaseAPI {
// URL already has a query param, this will not work.
authURL(url: string): string {
if (this.attachmentToken) {
- return route(url, { access_token: this.attachmentToken });
+ const { selectedId } = useCollections();
+ return route(url, { access_token: this.attachmentToken, tenant: selectedId.value });
}
return url;
}
diff --git a/frontend/lib/api/classes/group.ts b/frontend/lib/api/classes/group.ts
index a33dbf9c..ffe5bea3 100644
--- a/frontend/lib/api/classes/group.ts
+++ b/frontend/lib/api/classes/group.ts
@@ -2,12 +2,18 @@ import { BaseAPI, route } from "../base";
import type {
CurrenciesCurrency,
Group,
+ GroupAcceptInvitationResponse,
GroupInvitation,
GroupInvitationCreate,
+ GroupMemberAdd,
GroupUpdate,
+ UserSummary,
} from "../types/data-contracts";
export class GroupApi extends BaseAPI {
+ /**
+ * Create a new invitation for the current group.
+ */
createInvitation(data: GroupInvitationCreate) {
return this.http.post<GroupInvitationCreate, GroupInvitation>({
url: route("/groups/invitations"),
@@ -15,19 +21,152 @@ export class GroupApi extends BaseAPI {
});
}
- update(data: GroupUpdate) {
+ /**
+ * Accept an invitation.
+ */
+ acceptInvitation(id: string) {
+ return this.http.post<null, GroupAcceptInvitationResponse>({
+ url: route(`/groups/invitations/${id}`),
+ });
+ }
+
+ /**
+ * Get all invitations for the current group.
+ */
+ getInvitations() {
+ return this.http.get<GroupInvitation[]>({
+ url: route("/groups/invitations"),
+ });
+ }
+
+ /**
+ * Delete an invitation by ID.
+ */
+ deleteInvitation(id: string) {
+ return this.http.delete<void>({
+ url: route(`/groups/invitations/${id}`),
+ });
+ }
+
+ /**
+ * Get all members of the current (or specified) group.
+ */
+ getMembers(groupId?: string) {
+ const headers = groupId
+ ? {
+ "X-Tenant": groupId,
+ }
+ : undefined;
+ return this.http.get<UserSummary[]>({
+ url: route(`/groups/members`),
+ headers,
+ });
+ }
+
+ /**
+ * Add a user to the current (or specified) group.
+ */
+ addMember(data: GroupMemberAdd, groupId?: string) {
+ const headers = groupId
+ ? {
+ "X-Tenant": groupId,
+ }
+ : undefined;
+ return this.http.post<GroupMemberAdd, void>({
+ url: route(`/groups/members`),
+ headers,
+ body: data,
+ });
+ }
+
+ /**
+ * Remove a user from the current (or specified) group.
+ */
+ removeMember(userId: string, groupId?: string) {
+ const headers = groupId
+ ? {
+ "X-Tenant": groupId,
+ }
+ : undefined;
+ return this.http.delete<void>({
+ url: route(`/groups/members/${userId}`),
+ headers,
+ });
+ }
+
+ /**
+ * Update group name and currency.
+ */
+ update(data: GroupUpdate, groupId?: string) {
+ const headers = groupId
+ ? {
+ "X-Tenant": groupId,
+ }
+ : undefined;
return this.http.put<GroupUpdate, Group>({
- url: route("/groups"),
+ url: route(`/groups`),
+ headers,
body: data,
});
}
- get() {
+ /**
+ * Get a group by ID, if no ID is provided, get the current group.
+ */
+ get(groupId?: string) {
+ const headers = groupId
+ ? {
+ "X-Tenant": groupId,
+ }
+ : undefined;
return this.http.get<Group>({
+ url: route(`/groups`),
+ headers,
+ });
+ }
+
+ /**
+ * Get all groups the user is a member of.
+ */
+ getAll() {
+ return this.http.get<Group[]>({
+ url: route("/groups/all"),
+ });
+ }
+
+ /**
+ * Create a new group with the given name.
+ */
+ create(name: string) {
+ return this.http.post<
+ {
+ name: string;
+ },
+ Group
+ >({
url: route("/groups"),
+ body: { name },
+ });
+ }
+
+ /**
+ * Delete a group by ID, if no ID is provided, delete the current group.
+ */
+ delete(groupId?: string) {
+ const headers = groupId
+ ? {
+ "X-Tenant": groupId,
+ }
+ : undefined;
+ return this.http.delete<void>({
+ url: route(`/groups`),
+ headers,
});
}
+ /**
+ * Get all currencies.
+ */
currencies() {
return this.http.get<CurrenciesCurrency[]>({
url: route("/currencies"),
diff --git a/frontend/lib/api/types/data-contracts.ts b/frontend/lib/api/types/data-contracts.ts
index 3f7e283c..c073fcdf 100644
--- a/frontend/lib/api/types/data-contracts.ts
+++ b/frontend/lib/api/types/data-contracts.ts
@@ -508,6 +508,8 @@ export interface EntUser {
activated_on: string;
/** CreatedAt holds the value of the "created_at" field. */
created_at: string;
+ /** DefaultGroupID holds the value of the "default_group_id" field. */
+ default_group_id: string;
/**
* Edges holds the relations/edges for other nodes in the graph.
* The values are being populated by the UserQuery when eager-loading is set.
@@ -536,8 +538,8 @@ export interface EntUser {
export interface EntUserEdges {
/** AuthTokens holds the value of the auth_tokens edge. */
auth_tokens: EntAuthTokens[];
- /** Group holds the value of the group edge. */
- group: EntGroup;
+ /** Groups holds the value of the groups edge. */
+ groups: EntGroup[];
/** Notifiers holds the value of the notifiers edge. */
notifiers: EntNotifier[];
}
@@ -570,6 +572,13 @@ export interface Group {
updatedAt: Date | string;
}
+export interface GroupInvitation {
+ expiresAt: Date | string;
+ group: Group;
+ id: string;
+ uses: number;
+}
+
export interface GroupStatistics {
totalItemPrice: number;
totalItems: number;
@@ -1027,9 +1036,9 @@ export interface TreeItem {
}
export interface UserOut {
+ defaultGroupId: string;
email: string;
- groupId: string;
- groupName: string;
+ groupIds: string[];
id: string;
isOwner: boolean;
isSuperuser: boolean;
@@ -1038,6 +1047,13 @@ export interface UserOut {
oidcSubject: string;
}
+export interface UserSummary {
+ email: string;
+ id: string;
+ isOwner: boolean;
+ name: string;
+}
+
export interface UserUpdate {
email: string;
name: string;
@@ -1097,6 +1113,15 @@ export interface ChangePassword {
new: string;
}
+export interface CreateRequest {
+ name: string;
+}
+
+export interface GroupAcceptInvitationResponse {
+ id: string;
+ name: string;
+}
+
export interface GroupInvitation {
expiresAt: Date | string;
token: string;
@@ -1112,6 +1137,10 @@ export interface GroupInvitationCreate {
uses: number;
}
+export interface GroupMemberAdd {
+ userId: string;
+}
+
export interface ItemAttachmentToken {
token: string;
}
diff --git a/frontend/lib/requests/requests.ts b/frontend/lib/requests/requests.ts
index fed69986..1f4509e5 100644
--- a/frontend/lib/requests/requests.ts
+++ b/frontend/lib/requests/requests.ts
@@ -33,7 +33,7 @@ export class Requests {
}
private callResponseInterceptors(response: Response, request?: RequestInit) {
- this.responseInterceptors.forEach(i => i(response, request));
+ this.responseInterceptors.forEach(i => i(response.clone(), request));
}
private url(rest: string): string {
diff --git a/frontend/locales/en.json b/frontend/locales/en.json
index 3a6c3f0c..32bb6a70 100644
--- a/frontend/locales/en.json
+++ b/frontend/locales/en.json
@@ -292,6 +292,47 @@
"updated": "Template updated"
},
"using_template": "Using template: {name}"
+ },
+ "collection": {
+ "selector": {
+ "select_collection": "Select Collection",
+ "create_collection": "Create New Collection",
+ "join_collection": "Join Existing Collection",
+ "no_collection_found": "No collection found",
+ "your_collections": "Your Collections",
+ "collection_options": "Collection Options",
+ "search_collections": "Search Collections..."
+ },
+ "create_modal": {
+ "title": "Create Collection",
+ "name_label": "Collection Name",
+ "toast": {
+ "already_creating": "Already creating a collection",
+ "create_failed": "Failed to create collection",
+ "create_success": "Collection created",
+ "please_enter_name": "Please enter a collection name"
+ }
+ },
+ "join_modal": {
+ "title": "Join Collection",
+ "invite_code_label": "Collection Invite Code",
+ "join": "Join Collection",
+ "no_invite_code_create_one": "No invite code? Create a new collection instead",
+ "invites_should_look_like": "Invites should look like:",
+ "toast": {
+ "already_joining": "Already joining a collection",
+ "join_failed": "Failed to join collection",
+ "join_success": "Collection joined",
+ "please_enter_valid_join_code": "Please enter a valid collection invite code"
+ }
+ },
+ "invite_create_modal": {
+ "toast": {
+ "invalid_uses": "Uses must be a number between 1 and 100.",
+ "invalid_expiry_missing": "Please choose an expiration date and time.",
+ "invalid_expiry_past": "Expiration date must be in the future."
+ }
+ }
}
},
"errors": {
@@ -619,7 +660,7 @@
"scanner": "Scanner",
"search": "Search",
"templates": "Templates",
- "tools": "Tools"
+ "collection_options": "Collection Options"
},
"pages": {
"templates": {
@@ -639,7 +680,6 @@
"display_legacy_header": "{ currentValue, select, true {Disable Legacy Header} false {Enable Legacy Header} other {Not Hit}}",
"enabled": "Enabled",
"example": "Example",
- "gen_invite": "Generate Invite Link",
"group_settings": "Group Settings",
"group_settings_sub": "Shared Group Settings. You may need to refresh your browser for some settings to apply.",
"inactive": "Inactive",
@@ -673,7 +713,13 @@
"update_language": "Update Language",
"url": "URL",
"user_profile": "User Profile",
- "user_profile_sub": "Invite users, and manage your account."
+ "user_profile_sub": "Invite users, and manage your account.",
+ "moved_notice_title": "Looking for notifiers, invites, or currency settings?",
+ "moved_notice_description": "These settings are now managed per collection.",
+ "moved_notice_body": "Notifiers, invites, and currency settings have been moved to the collection pages.",
+ "moved_notice_link_settings": "Collection currency settings",
+ "moved_notice_link_notifiers": "Collection notifiers",
+ "moved_notice_link_invites": "Collection invites"
},
"reports": {
"label_generator": {
@@ -790,5 +836,49 @@
"failed_zero_datetimes": "Failed to reset date and time values.",
"wipe_inventory_success": "Successfully wiped inventory. { results } items deleted."
}
+ },
+ "collection": {
+ "manage_collection": "Manage Collection",
+ "no_collections": {
+ "title": "No Collections Found",
+ "message": "It looks like you're not part of a collection. Create a new collection for your things, or join one you've been invited to.",
+ "create": "Create a new collection",
+ "join": "Join an existing collection"
+ },
+ "tabs": {
+ "members": "Members",
+ "invites": "Invites",
+ "settings": "Settings",
+ "notifiers": "Notifiers",
+ "tools": "Tools"
+ },
+ "leave_collection": "Leave Collection",
+ "delete_collection": "Delete Collection",
+ "leave_confirm": "Are you sure you want to leave this collection?",
+ "delete_confirm": "Are you sure you want to delete this collection? This action cannot be undone.",
+ "left_collection": "You have left the collection.",
+ "deleted_collection": "Collection deleted.",
+ "invites": "Invites",
+ "no_invites": "No invites",
+ "invite_token": "Token",
+ "expires_at": "Expires",
+ "uses": "Uses",
+ "invite_token_warning": "Invite tokens are only shown once. Copy the link now; you will not be able to view this token again after leaving or refreshing this page.",
+ "invite_token_hidden": "No longer visible",
+ "invites_delete_confirm": "Are you sure you want to delete this invite?",
+ "create_invite": "Create Invite",
+ "copy_invite": "Copy Invite Link",
+ "remaining_uses": "Remaining uses",
+ "members": {
+ "cannot_remove_last": "You cannot remove the last member.",
+ "removed": "Member removed",
+ "remove_confirm": "Are you sure you want to remove this member?",
+ "empty": "No members in this collection yet.",
+ "name": "Name",
+ "email": "Email",
+ "role": "Role",
+ "owner": "Owner",
+ "member": "Member"
+ }
}
}
diff --git a/frontend/pages/collection/index.vue b/frontend/pages/collection/index.vue
new file mode 100644
index 00000000..0a7f6faf
--- /dev/null
+++ b/frontend/pages/collection/index.vue
@@ -0,0 +1,252 @@
+<script setup lang="ts">
+ import { useI18n } from "vue-i18n";
+ import BaseContainer from "@/components/Base/Container.vue";
+ import { Card } from "@/components/ui/card";
+ import { Button, ButtonGroup } from "@/components/ui/button";
+ import { toast } from "@/components/ui/sonner";
+
+ import MdiAccountMultiple from "~icons/mdi/account-multiple";
+ import MdiEmailPlus from "~icons/mdi/email-plus";
+ import MdiBell from "~icons/mdi/bell";
+ import MdiCog from "~icons/mdi/cog";
+ import MdiWrench from "~icons/mdi/wrench";
+ import MdiLogout from "~icons/mdi/logout";
+ import MdiDelete from "~icons/mdi/delete";
+ import type { UserSummary } from "~/lib/api/types/data-contracts";
+
+ definePageMeta({
+ middleware: ["auth"],
+ });
+
+ const { t } = useI18n();
+
+ const route = useRoute();
+ const api = useUserApi();
+ const auth = useAuthContext();
+ const confirm = useConfirm();
+
+ const currentPath = computed(() => route.path);
+
+ const tabs = computed(() => [
+ {
+ id: "members",
+ label: "collection.tabs.members",
+ to: "/collection/members",
+ icon: MdiAccountMultiple,
+ },
+ {
+ id: "invites",
+ label: "collection.tabs.invites",
+ to: "/collection/invites",
+ icon: MdiEmailPlus,
+ },
+ {
+ id: "notifiers",
+ label: "collection.tabs.notifiers",
+ to: "/collection/notifiers",
+ icon: MdiBell,
+ },
+ {
+ id: "settings",
+ label: "collection.tabs.settings",
+ to: "/collection/settings",
+ icon: MdiCog,
+ },
+ {
+ id: "tools",
+ label: "collection.tabs.tools",
+ to: "/collection/tools",
+ icon: MdiWrench,
+ },
+ ]);
+
+ const { selectedCollection, load: reloadCollections } = useCollections();
+
+ const members = ref<Array<UserSummary>>([]);
+ const membersLoading = ref(false);
+ const actionLoading = ref(false);
+
+ const currentUserId = computed(() => auth.user?.id ?? "");
+
+ const membersCount = computed(() => members.value.length);
+
+ const isOnlyMember = computed(() => {
+ if (membersCount.value !== 1 || !currentUserId.value) return false;
+ const member = members.value[0];
+ return Boolean(member && member.id && member.id === currentUserId.value);
+ });
+ const isActionDisabled = computed(() => !selectedCollection.value || membersLoading.value || actionLoading.value);
+
+ const loadMembers = async () => {
+ if (!selectedCollection.value) {
+ members.value = [];
+ return;
+ }
+
+ membersLoading.value = true;
+ try {
+ const res = await api.group.getMembers();
+ if (res.error) {
+ const msg = t("errors.api_failure") + String(res.error);
+ toast.error(msg);
+ members.value = [];
+ } else {
+ members.value = Array.isArray(res.data) ? (res.data as Array<UserSummary>) : [];
+ }
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ toast.error(msg);
+ members.value = [];
+ } finally {
+ membersLoading.value = false;
+ }
+ };
+
+ watch(
+ () => selectedCollection.value?.id,
+ () => {
+ void loadMembers();
+ },
+ { immediate: true }
+ );
+
+ const handleLeaveCollection = async () => {
+ if (!selectedCollection.value) return;
+
+ const result = await confirm.open(t("collection.leave_confirm"));
+ if (result.isCanceled) {
+ return;
+ }
+
+ actionLoading.value = true;
+
+ try {
+ let userId = currentUserId.value;
+ if (!userId) {
+ const { data } = await api.user.self();
+ userId = data?.item.id ?? "";
+ }
+
+ if (!userId) {
+ const msg = t("errors.api_failure") + "Missing user id";
+ toast.error(msg);
+ return;
+ }
+
+ const res = await api.group.removeMember(userId);
+ if (res.error) {
+ const msg = t("errors.api_failure") + String(res.error);
+ toast.error(msg);
+ return;
+ }
+
+ toast.success(t("collection.left_collection"));
+ await reloadCollections();
+ window.location.reload();
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ toast.error(msg);
+ } finally {
+ actionLoading.value = false;
+ }
+ };
+
+ const handleDeleteCollection = async () => {
+ if (!selectedCollection.value) return;
+
+ const result = await confirm.open(t("collection.delete_confirm"));
+ if (result.isCanceled) {
+ return;
+ }
+
+ actionLoading.value = true;
+
+ try {
+ const res = await api.group.delete(selectedCollection.value.id);
+ if (res.error) {
+ const msg = t("errors.api_failure") + String(res.error);
+ toast.error(msg);
+ return;
+ }
+
+ toast.success(t("collection.deleted_collection"));
+ await reloadCollections();
+ window.location.reload();
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ toast.error(msg);
+ } finally {
+ actionLoading.value = false;
+ }
+ };
+
+ const handleCollectionPrimaryAction = async () => {
+ if (!selectedCollection.value) return;
+
+ if (isOnlyMember.value) {
+ await handleDeleteCollection();
+ } else {
+ await handleLeaveCollection();
+ }
+ };
+</script>
+
+<template>
+ <BaseContainer>
+ <Title>{{ t("menu.collection_options") }}</Title>
+
+ <section>
+ <Card class="p-3">
+ <header>
+ <div class="flex flex-wrap items-center justify-between gap-2">
+ <div>
+ <h1 class="text-2xl">
+ {{
+ selectedCollection?.name
+ ? t("collection.manage_collection") + " - " + selectedCollection.name
+ : t("global.loading")
+ }}
+ </h1>
+ </div>
+ </div>
+ </header>
+ </Card>
+
+ <div class="my-3 flex flex-wrap items-center justify-between gap-2">
+ <ButtonGroup>
+ <Button
+ v-for="tab in tabs"
+ :key="tab.id"
+ as-child
+ :variant="tab.to === currentPath ? 'default' : 'outline'"
+ size="sm"
+ >
+ <NuxtLink :to="tab.to" class="flex items-center gap-2">
+ <component :is="tab.icon" v-if="tab.icon" class="size-4" />
+ <span class="hidden sm:block">{{ t(tab.label) }}</span>
+ </NuxtLink>
+ </Button>
+ </ButtonGroup>
+
+ <div id="collection-header-actions" class="ml-auto flex items-center gap-1">
+ <Button
+ variant="outline"
+ size="icon"
+ class="size-8"
+ :aria-label="$t(isOnlyMember ? 'collection.delete_collection' : 'collection.leave_collection')"
+ :disabled="isActionDisabled"
+ @click="handleCollectionPrimaryAction"
+ >
+ <component :is="isOnlyMember ? MdiDelete : MdiLogout" class="size-4" />
+ </Button>
+ </div>
+ </div>
+ </section>
+
+ <section>
+ <div class="space-y-6">
+ <NuxtPage />
+ </div>
+ </section>
+ </BaseContainer>
+</template>
diff --git a/frontend/pages/collection/index/invites.vue b/frontend/pages/collection/index/invites.vue
new file mode 100644
index 00000000..aa225f3b
--- /dev/null
+++ b/frontend/pages/collection/index/invites.vue
@@ -0,0 +1,222 @@
+<script setup lang="ts">
+ import { useI18n } from "vue-i18n";
+ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+ import { Button } from "@/components/ui/button";
+ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+ import MdiPlus from "~icons/mdi/plus";
+ import MdiDelete from "~icons/mdi/delete";
+ import { toast } from "@/components/ui/sonner";
+ import { useUserApi } from "~/composables/use-api";
+ import { useDialog } from "~/components/ui/dialog-provider";
+ import { DialogID } from "@/components/ui/dialog-provider/utils";
+ import CopyText from "@/components/global/CopyText.vue";
+ import type { Group, GroupInvitation } from "~~/lib/api/types/data-contracts";
+
+ definePageMeta({
+ middleware: ["auth"],
+ });
+
+ type Invitation = GroupInvitation & { id: string; group?: Group };
+ type InvitationResult = GroupInvitation & { id?: string; group?: Group };
+
+ const { t } = useI18n();
+
+ useHead({ title: `HomeBox | ${t("collection.invites") || t("invites")}` });
+
+ const api = useUserApi();
+ const { openDialog } = useDialog();
+ const confirm = useConfirm();
+ const localInvites = ref<Invitation[]>([]);
+ const baseUrl = `${window.location.protocol}//${window.location.host}`;
+ const loading = ref(true);
+ const invites = ref<Invitation[]>([]);
+ const error = ref<string | null>(null);
+ const removing = ref<Record<string, boolean>>({});
+
+ const allInvites = computed<Invitation[]>(() => {
+ const now = Date.now();
+
+ const isActive = (inv: Invitation) => {
+ if (!inv.expiresAt) return true;
+
+ const expiresAtTime = new Date(inv.expiresAt).getTime();
+ return Number.isFinite(expiresAtTime) && expiresAtTime > now;
+ };
+
+ return [...localInvites.value.filter(isActive), ...invites.value.filter(isActive)];
+ });
+
+ const loadInvites = async () => {
+ loading.value = true;
+ error.value = null;
+
+ try {
+ const res = await api.group.getInvitations();
+
+ if (res.error) {
+ const msg = t("errors.api_failure") + String(res.error);
+ error.value = msg;
+ invites.value = [];
+ toast.error(msg);
+ } else {
+ invites.value = (res.data || []) as Invitation[];
+ }
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ error.value = msg;
+ invites.value = [];
+ toast.error(msg);
+ } finally {
+ loading.value = false;
+ }
+ };
+
+ const handleOpenCreate = () => {
+ openDialog(DialogID.CreateGroupInvite, {
+ onClose: (result?: InvitationResult) => {
+ if (!result) return;
+
+ const localId = result.id || `local-${Date.now()}-${Math.random().toString(36).slice(2)}`;
+ const localInvite: Invitation = {
+ ...(result as InvitationResult),
+ id: localId,
+ };
+
+ localInvites.value = [localInvite, ...localInvites.value];
+ },
+ });
+ };
+
+ const handleDelete = async (inv: Invitation) => {
+ if (!inv?.id) return;
+
+ const result = await confirm.open(t("collection.invites_delete_confirm"));
+ if (result.isCanceled) {
+ return;
+ }
+
+ removing.value = { ...removing.value, [inv.id]: true };
+
+ try {
+ const res = await api.group.deleteInvitation(inv.id);
+
+ if (res.error) {
+ const msg = t("errors.api_failure") + String(res.error);
+ toast.error(msg);
+ } else {
+ invites.value = invites.value.filter(i => i.id !== inv.id);
+ localInvites.value = localInvites.value.filter(i => i.id !== inv.id && i.token !== inv.token);
+ }
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ toast.error(msg);
+ } finally {
+ removing.value = { ...removing.value, [inv.id]: false };
+ }
+ };
+
+ onMounted(() => {
+ loadInvites();
+ });
+</script>
+
+<template>
+ <div class="space-y-4">
+ <Teleport to="#collection-header-actions" defer>
+ <TooltipProvider :delay-duration="0">
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <Button
+ class="size-8"
+ variant="outline"
+ size="icon"
+ :aria-label="$t('collection.create_invite')"
+ :disabled="loading"
+ @click="handleOpenCreate"
+ >
+ <MdiPlus class="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {{ $t("collection.create_invite") }}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Teleport>
+
+ <div v-if="loading" class="rounded-md border bg-card p-4 text-sm text-muted-foreground">
+ {{ $t("global.loading") }}
+ </div>
+
+ <div v-else class="space-y-3">
+ <div v-if="localInvites.length" class="rounded-md bg-secondary p-3 text-xs font-bold text-secondary-foreground">
+ {{ $t("collection.invite_token_warning") }}
+ </div>
+
+ <div v-if="!allInvites.length" class="rounded-md border bg-card p-4 text-sm text-muted-foreground">
+ {{ $t("collection.no_invites") }}
+ </div>
+
+ <div v-else class="scroll-bg overflow-x-auto rounded-md border bg-card">
+ <Table class="min-w-[640px]">
+ <TableHeader>
+ <TableRow>
+ <TableHead>{{ $t("collection.invite_token") }}</TableHead>
+ <TableHead>{{ $t("collection.expires_at") }}</TableHead>
+ <TableHead>{{ $t("collection.remaining_uses") }}</TableHead>
+ <TableHead class="w-40 text-right"></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ <TableRow v-for="inv in allInvites" :key="inv.id || inv.token">
+ <TableCell>
+ <span class="break-all font-mono text-xs">
+ <template v-if="inv.token">
+ {{ inv.token }}
+ </template>
+ <span v-else class="font-sans text-muted-foreground">
+ {{ $t("collection.invite_token_hidden") }}
+ </span>
+ </span>
+ </TableCell>
+ <TableCell>
+ {{ new Date(inv.expiresAt).toLocaleString() }}
+ </TableCell>
+ <TableCell>
+ {{ inv.uses }}
+ </TableCell>
+ <TableCell>
+ <div class="ml-auto flex items-center gap-2">
+ <CopyText
+ v-if="inv.token"
+ :text="`${baseUrl}?token=${inv.token}`"
+ :icon-size="16"
+ :tooltip="$t('collection.copy_invite')"
+ />
+ <TooltipProvider :delay-duration="0">
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <Button
+ variant="destructive"
+ size="icon"
+ :aria-label="$t('global.delete')"
+ :disabled="removing[inv.id]"
+ @click="handleDelete(inv)"
+ >
+ <MdiDelete class="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {{ $t("global.delete") }}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </TableCell>
+ </TableRow>
+ </TableBody>
+ </Table>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/frontend/pages/collection/index/members.vue b/frontend/pages/collection/index/members.vue
new file mode 100644
index 00000000..19211513
--- /dev/null
+++ b/frontend/pages/collection/index/members.vue
@@ -0,0 +1,141 @@
+<script setup lang="ts">
+ import { useI18n } from "vue-i18n";
+ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+ import { Button } from "@/components/ui/button";
+ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+ import MdiDelete from "~icons/mdi/delete";
+ import { toast } from "@/components/ui/sonner";
+ import type { UserSummary } from "~~/lib/api/types/data-contracts";
+
+ definePageMeta({
+ middleware: ["auth"],
+ });
+
+ const { t } = useI18n();
+ const api = useUserApi();
+ const auth = useAuthContext();
+ const confirm = useConfirm();
+
+ const loading = ref(true);
+ const members = ref<UserSummary[]>([]);
+ const error = ref<string | null>(null);
+ const removing = ref<Record<string, boolean>>({});
+
+ const currentUserId = computed(() => auth.user?.id ?? "");
+
+ const isLastMember = computed(() => members.value.length <= 1);
+
+ const loadMembers = async () => {
+ loading.value = true;
+ error.value = null;
+
+ try {
+ const res = await api.group.getMembers();
+ if (res.error) {
+ const msg = t("errors.api_failure") + String(res.error);
+ error.value = msg;
+ members.value = [];
+ toast.error(msg);
+ } else {
+ members.value = res.data ?? [];
+ }
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ error.value = msg;
+ members.value = [];
+ toast.error(msg);
+ } finally {
+ loading.value = false;
+ }
+ };
+
+ const handleRemove = async (user: UserSummary) => {
+ if (!user?.id) return;
+
+ if (isLastMember.value && user.id === currentUserId.value) {
+ toast.error(t("collection.members.cannot_remove_last"));
+ return;
+ }
+
+ const result = await confirm.open(t("collection.members.remove_confirm"));
+ if (result.isCanceled) {
+ return;
+ }
+
+ removing.value = { ...removing.value, [user.id]: true };
+
+ try {
+ const res = await api.group.removeMember(user.id);
+ if (res.error) {
+ const msg = t("errors.api_failure") + String(res.error);
+ toast.error(msg);
+ } else {
+ members.value = members.value.filter(m => m.id !== user.id);
+ toast.success(t("collection.members.removed"));
+ }
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ toast.error(msg);
+ } finally {
+ removing.value = { ...removing.value, [user.id]: false };
+ }
+ };
+
+ onMounted(() => {
+ loadMembers();
+ });
+</script>
+
+<template>
+ <div class="space-y-4">
+ <div v-if="loading" class="rounded-md border bg-card p-4 text-sm text-muted-foreground">
+ {{ $t("global.loading") }}
+ </div>
+
+ <div v-else>
+ <div v-if="!members.length" class="rounded-md border bg-card p-4 text-sm text-muted-foreground">
+ {{ $t("collection.members.empty") }}
+ </div>
+
+ <div v-else class="scroll-bg overflow-x-auto rounded-md border bg-card">
+ <Table class="min-w-[480px]">
+ <TableHeader>
+ <TableRow>
+ <TableHead>{{ $t("collection.members.name") }}</TableHead>
+ <TableHead>{{ $t("collection.members.email") }}</TableHead>
+ <TableHead class="w-32 text-right"></TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ <TableRow v-for="user in members" :key="user.id">
+ <TableCell>{{ user.name }}</TableCell>
+ <TableCell>{{ user.email }}</TableCell>
+ <TableCell>
+ <div class="ml-auto">
+ <TooltipProvider :delay-duration="0">
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <Button
+ variant="destructive"
+ size="icon"
+ :aria-label="$t('global.delete')"
+ :disabled="removing[user.id] || (isLastMember && user.id === currentUserId)"
+ @click="handleRemove(user)"
+ >
+ <MdiDelete class="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {{ $t("global.delete") }}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </TableCell>
+ </TableRow>
+ </TableBody>
+ </Table>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/frontend/pages/collection/index/notifiers.vue b/frontend/pages/collection/index/notifiers.vue
new file mode 100644
index 00000000..2f80c7a3
--- /dev/null
+++ b/frontend/pages/collection/index/notifiers.vue
@@ -0,0 +1,210 @@
+<script setup lang="ts">
+ import { useI18n } from "vue-i18n";
+ import { toast } from "@/components/ui/sonner";
+ import { Button } from "@/components/ui/button";
+ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+ import { useDialog } from "@/components/ui/dialog-provider";
+ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+ import { badgeVariants } from "@/components/ui/badge";
+ import FormCheckbox from "~/components/Form/Checkbox.vue";
+ import FormTextField from "~/components/Form/TextField.vue";
+ import DateTime from "@/components/global/DateTime.vue";
+ import MdiMegaphone from "~icons/mdi/megaphone";
+ import MdiDelete from "~icons/mdi/delete";
+ import MdiPencil from "~icons/mdi/pencil";
+ import { DialogID } from "~/components/ui/dialog-provider/utils";
+ import type { NotifierCreate, NotifierOut } from "~~/lib/api/types/data-contracts";
+
+ definePageMeta({
+ middleware: ["auth"],
+ });
+
+ const { t } = useI18n();
+ const api = useUserApi();
+ const confirm = useConfirm();
+ const { openDialog, closeDialog } = useDialog();
+
+ const notifiers = useAsyncData(async () => {
+ const { data } = await api.notifiers.getAll();
+ return data;
+ });
+
+ const targetID = ref("");
+ const notifier = ref<NotifierCreate | null>(null);
+
+ const openNotifierDialog = (v: NotifierOut | null) => {
+ if (v) {
+ targetID.value = v.id;
+ notifier.value = {
+ name: v.name,
+ url: v.url,
+ isActive: v.isActive,
+ };
+ } else {
+ targetID.value = "";
+ notifier.value = {
+ name: "",
+ url: "",
+ isActive: true,
+ };
+ }
+
+ openDialog(DialogID.CreateNotifier);
+ };
+
+ const createNotifier = async () => {
+ if (!notifier.value) return;
+
+ if (targetID.value) {
+ await editNotifier();
+ return;
+ }
+
+ const result = await api.notifiers.create({
+ name: notifier.value.name,
+ url: notifier.value.url || "",
+ isActive: notifier.value.isActive,
+ });
+
+ if (result.error) {
+ toast.error(t("profile.toast.failed_create_notifier"));
+ }
+
+ notifier.value = null;
+ closeDialog(DialogID.CreateNotifier);
+ await notifiers.refresh();
+ };
+
+ const editNotifier = async () => {
+ if (!notifier.value) return;
+
+ const result = await api.notifiers.update(targetID.value, {
+ name: notifier.value.name,
+ url: notifier.value.url || "",
+ isActive: notifier.value.isActive,
+ });
+
+ if (result.error) {
+ toast.error(t("profile.toast.failed_update_notifier"));
+ }
+
+ notifier.value = null;
+ targetID.value = "";
+ closeDialog(DialogID.CreateNotifier);
+ await notifiers.refresh();
+ };
+
+ const deleteNotifier = async (id: string) => {
+ const result = await confirm.open(t("profile.delete_notifier_confirm"));
+
+ if (result.isCanceled) return;
+
+ const { error } = await api.notifiers.delete(id);
+
+ if (error) {
+ toast.error(t("profile.toast.failed_delete_notifier"));
+ return;
+ }
+
+ await notifiers.refresh();
+ };
+
+ const testNotifier = async () => {
+ if (!notifier.value) return;
+
+ const { error } = await api.notifiers.test(notifier.value.url);
+
+ if (error) {
+ toast.error(t("profile.toast.failed_test_notifier"));
+ return;
+ }
+
+ toast.success(t("profile.toast.notifier_test_success"));
+ };
+</script>
+
+<template>
+ <div class="space-y-4">
+ <Dialog :dialog-id="DialogID.CreateNotifier">
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{{ $t("profile.notifier_modal", { type: notifier != null }) }}</DialogTitle>
+ </DialogHeader>
+
+ <form @submit.prevent="createNotifier">
+ <template v-if="notifier">
+ <FormTextField v-model="notifier.name" :label="$t('global.name')" class="mb-2" />
+ <FormTextField v-model="notifier.url" :label="$t('profile.url')" class="mb-2" />
+ <div class="max-w-[100px]">
+ <FormCheckbox v-model="notifier.isActive" :label="$t('profile.enabled')" />
+ </div>
+ </template>
+ <div class="mt-4 flex justify-between gap-2">
+ <DialogFooter class="flex w-full">
+ <Button variant="secondary" :disabled="!(notifier && notifier.url)" type="button" @click="testNotifier">
+ {{ $t("profile.test") }}
+ </Button>
+ <div class="grow" />
+ <Button type="submit">{{ $t("global.submit") }}</Button>
+ </DialogFooter>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+
+ <div class="rounded-md border bg-card p-4">
+ <header class="mb-2 flex items-center gap-2">
+ <MdiMegaphone class="-mt-1" />
+ <div>
+ <h2 class="text-lg font-semibold">{{ $t("profile.notifiers") }}</h2>
+ <p class="text-sm text-muted-foreground">{{ $t("profile.notifiers_sub") }}</p>
+ </div>
+ </header>
+
+ <div v-if="notifiers.data.value" class="mx-1 divide-y rounded-md border">
+ <p v-if="notifiers.data.value.length === 0" class="p-2 text-center text-sm">
+ {{ $t("profile.no_notifiers") }}
+ </p>
+ <article v-for="n in notifiers.data.value" v-else :key="n.id" class="p-2">
+ <div class="flex flex-wrap items-center gap-2">
+ <p class="mr-auto text-lg">{{ n.name }}</p>
+ <TooltipProvider :delay-duration="0" class="flex justify-end gap-2">
+ <Tooltip>
+ <TooltipTrigger>
+ <Button variant="destructive" size="icon" @click="deleteNotifier(n.id)">
+ <MdiDelete />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ $t("global.delete") }}</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger>
+ <Button variant="outline" size="icon" @click="openNotifierDialog(n)">
+ <MdiPencil />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ $t("global.edit") }}</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ <div class="flex flex-wrap justify-between py-1 text-sm">
+ <p>
+ <span v-if="n.isActive" :class="badgeVariants()">{{ $t("profile.active") }}</span>
+ <span v-else :class="badgeVariants({ variant: 'destructive' })">{{ $t("profile.inactive") }}</span>
+ </p>
+ <p>
+ {{ $t("global.created") }}
+ <DateTime format="relative" datetime-type="time" :date="n.createdAt" />
+ </p>
+ </div>
+ </article>
+ </div>
+
+ <div class="mt-4">
+ <Button variant="secondary" size="sm" @click="openNotifierDialog(null)">
+ {{ $t("global.create") }}
+ </Button>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/frontend/pages/collection/index/settings.vue b/frontend/pages/collection/index/settings.vue
new file mode 100644
index 00000000..99fa5918
--- /dev/null
+++ b/frontend/pages/collection/index/settings.vue
@@ -0,0 +1,169 @@
+<script setup lang="ts">
+ import { useI18n } from "vue-i18n";
+ import { toast } from "@/components/ui/sonner";
+ import { Button } from "@/components/ui/button";
+ import { Label } from "@/components/ui/label";
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+ import MdiLoading from "~icons/mdi/loading";
+ import FormTextField from "~/components/Form/TextField.vue";
+ import type { CurrenciesCurrency, Group } from "~~/lib/api/types/data-contracts";
+ import { fmtCurrencyAsync } from "~/composables/utils";
+ import { getLocaleCode } from "~/composables/use-formatters";
+
+ definePageMeta({
+ middleware: ["auth"],
+ });
+
+ const { t } = useI18n();
+ const api = useUserApi();
+ const { selectedCollection, load: reloadCollections } = useCollections();
+
+ const loading = ref(true);
+ const saving = ref(false);
+ const error = ref<string | null>(null);
+
+ const group = ref<Group | null>(null);
+ const currencies = ref<CurrenciesCurrency[]>([]);
+ const name = ref("");
+ const currencyCode = ref("USD");
+ const currencyExample = ref("$1,000.00");
+
+ const loadSettings = async () => {
+ if (!selectedCollection.value) {
+ loading.value = false;
+ return;
+ }
+
+ loading.value = true;
+ error.value = null;
+
+ try {
+ if (!currencies.value.length) {
+ const respCurrencies = await api.group.currencies();
+ if (respCurrencies.error) {
+ toast.error(t("profile.toast.failed_get_currencies"));
+ } else if (respCurrencies.data) {
+ currencies.value = respCurrencies.data;
+ }
+ }
+
+ const res = await api.group.get(selectedCollection.value.id);
+ if (res.error || !res.data) {
+ const msg = t("errors.api_failure") + String(res.error ?? "");
+ error.value = msg;
+ toast.error(msg);
+ return;
+ }
+
+ group.value = res.data;
+ name.value = res.data.name;
+ currencyCode.value = res.data.currency;
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ error.value = msg;
+ toast.error(msg);
+ } finally {
+ loading.value = false;
+ }
+ };
+
+ watch(
+ () => selectedCollection.value?.id,
+ () => {
+ void loadSettings();
+ },
+ { immediate: true }
+ );
+
+ watch(
+ currencyCode,
+ async () => {
+ if (!currencyCode.value) return;
+ try {
+ currencyExample.value = await fmtCurrencyAsync(1000, currencyCode.value, getLocaleCode());
+ } catch {
+ currencyExample.value = `${currencyCode.value} 1000`;
+ }
+ },
+ { immediate: true }
+ );
+
+ const save = async () => {
+ if (!selectedCollection.value) return;
+
+ saving.value = true;
+ error.value = null;
+
+ try {
+ const res = await api.group.update(
+ {
+ name: name.value,
+ currency: currencyCode.value,
+ },
+ selectedCollection.value.id
+ );
+
+ if (res.error || !res.data) {
+ const msg = t("profile.toast.failed_update_group");
+ error.value = msg;
+ toast.error(msg);
+ return;
+ }
+
+ group.value = res.data;
+ toast.success(t("profile.toast.group_updated"));
+
+ await reloadCollections();
+ } catch (e) {
+ const msg = (e as Error).message ?? String(e);
+ error.value = msg;
+ toast.error(msg);
+ } finally {
+ saving.value = false;
+ }
+ };
+</script>
+
+<template>
+ <div class="space-y-4">
+ <div v-if="loading" class="rounded-md border bg-card p-4 text-sm text-muted-foreground">
+ {{ $t("global.loading") }}
+ </div>
+
+ <div v-else>
+ <div v-if="!selectedCollection" class="rounded-md border bg-card p-4 text-sm text-muted-foreground">
+ {{ $t("components.collection.selector.select_collection") }}
+ </div>
+
+ <div v-else class="space-y-4 rounded-md border bg-card p-4">
+ <FormTextField v-model="name" :label="$t('global.name')" />
+
+ <div>
+ <Label for="currency"> {{ $t("profile.currency_format") }} </Label>
+ <Select
+ id="currency"
+ :model-value="currencyCode"
+ @update:model-value="val => (currencyCode = String(val || ''))"
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="c in currencies" :key="c.code" :value="c.code">
+ {{ c.name }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <p class="m-2 text-sm">{{ $t("profile.example") }}: {{ currencyExample }}</p>
+ </div>
+
+ <div class="mt-4">
+ <Button variant="secondary" size="sm" :disabled="saving" @click="save">
+ <MdiLoading v-if="saving" class="mr-2 inline-block animate-spin" />
+ <span>{{ $t("profile.update_group") }}</span>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/frontend/pages/tools.vue b/frontend/pages/collection/index/tools.vue
similarity index 95%
rename from frontend/pages/tools.vue
rename to frontend/pages/collection/index/tools.vue
index 57a66906..fb41cfe2 100644
--- a/frontend/pages/tools.vue
+++ b/frontend/pages/collection/index/tools.vue
@@ -1,7 +1,7 @@
<template>
<div>
<AppImportDialog />
- <BaseContainer class="flex flex-col gap-4">
+ <BaseContainer class="m-0 flex flex-col gap-4 px-0">
<BaseCard>
<template #title>
<BaseSectionHeader>
@@ -131,25 +131,23 @@
const api = useUserApi();
const confirm = useConfirm();
-
- // Fetch status to check for demo mode
const pubApi = usePublicApi();
const { data: status } = useAsyncData(async () => {
const { data } = await pubApi.status();
return data;
});
- function getBillOfMaterials() {
+ const getBillOfMaterials = () => {
const url = api.reports.billOfMaterialsURL();
window.open(url, "_blank");
- }
+ };
- function getExportCSV() {
+ const getExportCSV = () => {
const url = api.items.exportURL();
window.open(url, "_blank");
- }
+ };
- async function ensureAssetIDs() {
+ const ensureAssetIDs = async () => {
const { isCanceled } = await confirm.open(t("tools.actions_set.ensure_ids_confirm"));
if (isCanceled) {
@@ -164,9 +162,9 @@
}
toast.success(t("tools.toast.asset_success", { results: result.data.completed }));
- }
+ };
- async function createMissingThumbnails() {
+ const createMissingThumbnails = async () => {
const { isCanceled } = await confirm.open(t("tools.actions_set.create_missing_thumbnails_confirm"));
if (isCanceled) {
@@ -181,9 +179,9 @@
}
toast.success(t("tools.toast.asset_success", { results: result.data.completed }));
- }
+ };
- async function ensureImportRefs() {
+ const ensureImportRefs = async () => {
const { isCanceled } = await confirm.open(t("tools.import_export_set.import_ref_confirm"));
if (isCanceled) {
@@ -198,9 +196,9 @@
}
toast.success(t("tools.toast.asset_success", { results: result.data.completed }));
- }
+ };
- async function resetItemDateTimes() {
+ const resetItemDateTimes = async () => {
const { isCanceled } = await confirm.open(t("tools.actions_set.zero_datetimes_confirm"));
if (isCanceled) {
@@ -215,9 +213,9 @@
}
toast.success(t("tools.toast.asset_success", { results: result.data.completed }));
- }
+ };
- async function setPrimaryPhotos() {
+ const setPrimaryPhotos = async () => {
const { isCanceled } = await confirm.open(t("tools.actions_set.set_primary_photo_confirm"));
if (isCanceled) {
@@ -232,10 +230,9 @@
}
toast.success(t("tools.toast.asset_success", { results: result.data.completed }));
- }
+ };
- async function wipeInventory() {
- // Check if in demo mode
+ const wipeInventory = async () => {
if (status.value?.demo) {
await confirm.open(t("tools.demo_mode_error.wipe_inventory"));
return;
@@ -261,7 +258,5 @@
toast.success(t("tools.toast.wipe_inventory_success", { results: apiResult.data.completed }));
},
});
- }
+ };
</script>
-
-<style scoped></style>
diff --git a/frontend/pages/no-collections.vue b/frontend/pages/no-collections.vue
new file mode 100644
index 00000000..5ab3d385
--- /dev/null
+++ b/frontend/pages/no-collections.vue
@@ -0,0 +1,61 @@
+<script setup lang="ts">
+ import { Button } from "@/components/ui/button";
+ import BaseContainer from "@/components/Base/Container.vue";
+ import BaseCard from "@/components/Base/Card.vue";
+ import { useDialog } from "@/components/ui/dialog-provider";
+ import { DialogID } from "@/components/ui/dialog-provider/utils";
+
+ definePageMeta({
+ middleware: ["auth"],
+ });
+
+ const { openDialog } = useDialog();
+</script>
+
+<template>
+ <BaseContainer class="flex justify-center">
+ <div class="w-full">
+ <BaseCard>
+ <template #title>
+ <h2 class="text-center text-xl font-semibold tracking-tight">
+ {{ $t("collection.no_collections.title") }}
+ </h2>
+ </template>
+
+ <div class="mx-4 mb-4 flex flex-col gap-4 text-sm text-muted-foreground">
+ <p class="text-center text-base text-foreground">
+ {{ $t("collection.no_collections.message") }}
+ </p>
+
+ <div class="flex flex-col gap-2 sm:flex-row sm:justify-center">
+ <Button
+ class="w-full sm:w-auto"
+ @click="
+ openDialog(DialogID.CreateCollection, {
+ params: {
+ redirectTo: '/home',
+ },
+ })
+ "
+ >
+ {{ $t("collection.no_collections.create") }}
+ </Button>
+ <Button
+ class="w-full sm:w-auto"
+ variant="secondary"
+ @click="
+ openDialog(DialogID.JoinCollection, {
+ params: {
+ redirectTo: '/home',
+ },
+ })
+ "
+ >
+ {{ $t("collection.no_collections.join") }}
+ </Button>
+ </div>
+ </div>
+ </BaseCard>
+ </div>
+ </BaseContainer>
+</template>
diff --git a/frontend/pages/profile.vue b/frontend/pages/profile.vue
index 0143ca4d..a090f720 100644
--- a/frontend/pages/profile.vue
+++ b/frontend/pages/profile.vue
@@ -2,36 +2,22 @@
import { useI18n } from "vue-i18n";
import { toast } from "@/components/ui/sonner";
import type { Detail } from "~~/components/global/DetailsSection/types";
- import type { CurrenciesCurrency, NotifierCreate, NotifierOut } from "~~/lib/api/types/data-contracts";
import MdiLoading from "~icons/mdi/loading";
import MdiAccount from "~icons/mdi/account";
- import MdiMegaphone from "~icons/mdi/megaphone";
import MdiDelete from "~icons/mdi/delete";
import MdiFill from "~icons/mdi/fill";
- import MdiPencil from "~icons/mdi/pencil";
- import MdiAccountMultiple from "~icons/mdi/account-multiple";
- import { getLocaleCode } from "~/composables/use-formatters";
- import { fmtCurrencyAsync } from "~/composables/utils";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useDialog } from "@/components/ui/dialog-provider";
- import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
- import { Label } from "@/components/ui/label";
- import { badgeVariants } from "@/components/ui/badge";
import LanguageSelector from "~/components/App/LanguageSelector.vue";
- import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { DialogID } from "~/components/ui/dialog-provider/utils";
import ThemePicker from "~/components/App/ThemePicker.vue";
import ItemDuplicateSettings from "~/components/Item/DuplicateSettings.vue";
import FormPassword from "~/components/Form/Password.vue";
- import FormCheckbox from "~/components/Form/Checkbox.vue";
- import FormTextField from "~/components/Form/TextField.vue";
import BaseContainer from "@/components/Base/Container.vue";
import BaseCard from "@/components/Base/Card.vue";
import BaseSectionHeader from "@/components/Base/SectionHeader.vue";
import DetailsSection from "@/components/global/DetailsSection/DetailsSection.vue";
- import CopyText from "@/components/global/CopyText.vue";
- import DateTime from "@/components/global/DateTime.vue";
import PasswordScore from "~/components/global/PasswordScore.vue";
const { t } = useI18n();
@@ -48,16 +34,6 @@
const { openDialog, closeDialog } = useDialog();
- const currencies = computedAsync(async () => {
- const resp = await api.group.currencies();
- if (resp.error) {
- toast.error(t("profile.toast.failed_get_currencies"));
- return [];
- }
-
- return resp.data;
- });
-
const preferences = useViewPreferences();
function setDisplayHeader() {
preferences.value.displayLegacyHeader = !preferences.value.displayLegacyHeader;
@@ -66,74 +42,9 @@
preferences.value.legacyImageFit = !preferences.value.legacyImageFit;
}
- // Currency Selection
- const currency = ref<CurrenciesCurrency>({
- code: "USD",
- name: "United States Dollar",
- local: "en-US",
- symbol: "$",
- decimals: 2,
- });
- watch(currency, () => {
- if (group.value) {
- group.value.currency = currency.value.code;
- }
- });
-
- const currencyExample = ref("$1,000.00");
-
- // Update currency example when currency changes
- watch(
- currency,
- async () => {
- if (currency.value) {
- currencyExample.value = await fmtCurrencyAsync(1000, currency.value.code, getLocaleCode());
- }
- },
- { immediate: true }
- );
-
- const { data: group } = useAsyncData(async () => {
- const { data } = await api.group.get();
- return data;
- });
-
- // Sync Initial Currency
- watch(group, () => {
- if (!group.value) {
- return;
- }
-
- // @ts-expect-error - typescript is stupid, it should know group.value is not null
- const found = currencies.value.find(c => c.code === group.value.currency);
- if (found) {
- currency.value = found;
- }
- });
-
- async function updateGroup() {
- if (!group.value) {
- return;
- }
-
- const { data, error } = await api.group.update({
- name: group.value.name,
- currency: group.value.currency,
- });
-
- if (error) {
- toast.error(t("profile.toast.failed_update_group"));
- return;
- }
-
- group.value = data;
- toast.success(t("profile.toast.group_updated"));
- }
-
const auth = useAuthContext();
const details = computed(() => {
- console.log(auth.user);
return [
{
name: "global.name",
@@ -164,28 +75,6 @@
toast.error(t("profile.toast.failed_delete_account"));
}
- const token = ref("");
- const tokenUrl = computed(() => {
- if (!window) {
- return "";
- }
-
- return `${window.location.origin}?token=${token.value}`;
- });
-
- async function generateToken() {
- const date = new Date();
-
- const { response, data } = await api.group.createInvitation({
- expiresAt: new Date(date.setDate(date.getDate() + 7)),
- uses: 1,
- });
-
- if (response?.status === 201) {
- token.value = data.token;
- }
- }
-
const passwordChange = reactive({
loading: false,
current: "",
@@ -213,117 +102,6 @@
passwordChange.current = "";
passwordChange.loading = false;
}
-
- // ===========================================================
- // Notifiers
-
- const notifiers = useAsyncData(async () => {
- const { data } = await api.notifiers.getAll();
-
- return data;
- });
-
- const targetID = ref("");
- const notifier = ref<NotifierCreate | null>(null);
-
- function openNotifierDialog(v: NotifierOut | null) {
- if (v) {
- targetID.value = v.id;
- notifier.value = {
- name: v.name,
- url: v.url,
- isActive: v.isActive,
- };
- } else {
- notifier.value = {
- name: "",
- url: "",
- isActive: true,
- };
- }
-
- openDialog(DialogID.CreateNotifier);
- }
-
- async function createNotifier() {
- if (!notifier.value) {
- return;
- }
-
- if (targetID.value) {
- await editNotifier();
- return;
- }
-
- const result = await api.notifiers.create({
- name: notifier.value.name,
- url: notifier.value.url || "",
- isActive: notifier.value.isActive,
- });
-
- if (result.error) {
- toast.error(t("profile.toast.failed_create_notifier"));
- }
-
- notifier.value = null;
- closeDialog(DialogID.CreateNotifier);
-
- await notifiers.refresh();
- }
-
- async function editNotifier() {
- if (!notifier.value) {
- return;
- }
-
- const result = await api.notifiers.update(targetID.value, {
- name: notifier.value.name,
- url: notifier.value.url || "",
- isActive: notifier.value.isActive,
- });
-
- if (result.error) {
- toast.error(t("profile.toast.failed_update_notifier"));
- }
-
- notifier.value = null;
- closeDialog(DialogID.CreateNotifier);
- targetID.value = "";
-
- await notifiers.refresh();
- }
-
- async function deleteNotifier(id: string) {
- const result = await confirm.open(t("profile.delete_notifier_confirm"));
-
- if (result.isCanceled) {
- return;
- }
-
- const { error } = await api.notifiers.delete(id);
-
- if (error) {
- toast.error(t("profile.toast.failed_delete_notifier"));
- return;
- }
-
- await notifiers.refresh();
- }
-
- async function testNotifier() {
- if (!notifier.value) {
- return;
- }
-
- const { error } = await api.notifiers.test(notifier.value.url);
-
- if (error) {
- toast.error(t("profile.toast.failed_test_notifier"));
- return;
- }
-
- toast.success(t("profile.toast.notifier_test_success"));
- }
</script>
<template>
@@ -366,33 +144,6 @@
</DialogContent>
</Dialog>
- <Dialog :dialog-id="DialogID.CreateNotifier">
- <DialogContent>
- <DialogHeader>
- <DialogTitle> {{ $t("profile.notifier_modal", { type: notifier != null }) }} </DialogTitle>
- </DialogHeader>
-
- <form @submit.prevent="createNotifier">
- <template v-if="notifier">
- <FormTextField v-model="notifier.name" :label="$t('global.name')" class="mb-2" />
- <FormTextField v-model="notifier.url" :label="$t('profile.url')" class="mb-2" />
- <div class="max-w-[100px]">
- <FormCheckbox v-model="notifier.isActive" :label="$t('profile.enabled')" />
- </div>
- </template>
- <div class="mt-4 flex justify-between gap-2">
- <DialogFooter class="flex w-full">
- <Button variant="secondary" :disabled="!(notifier && notifier.url)" type="button" @click="testNotifier">
- {{ $t("profile.test") }}
- </Button>
- <div class="grow" />
- <Button type="submit"> {{ $t("global.submit") }} </Button>
- </DialogFooter>
- </div>
- </form>
- </DialogContent>
- </Dialog>
-
<BaseContainer class="flex flex-col gap-4">
<BaseCard>
<template #title>
@@ -410,118 +161,42 @@
<Button variant="secondary" size="sm" @click="openDialog(DialogID.ChangePassword)">
{{ $t("profile.change_password") }}
</Button>
- <Button variant="secondary" size="sm" @click="generateToken"> {{ $t("profile.gen_invite") }} </Button>
<Button variant="secondary" size="sm" @click="openDialog(DialogID.DuplicateSettings)">
{{ $t("items.duplicate.title") }}
</Button>
</div>
- <div v-if="token" class="flex items-center gap-2 pl-1 pt-4">
- <CopyText :text="tokenUrl" />
- {{ tokenUrl }}
- </div>
- <div v-if="token" class="flex items-center gap-2 pl-1 pt-4">
- <CopyText :text="token" />
- {{ token }}
- </div>
</div>
<LanguageSelector />
</BaseCard>
+ <!-- TODO: Remove this notice once users are familiar with the collection-based settings. -->
<BaseCard>
<template #title>
<BaseSectionHeader>
- <MdiMegaphone class="-mt-1 mr-2" />
- <span> {{ $t("profile.notifiers") }} </span>
- <template #description> {{ $t("profile.notifiers_sub") }} </template>
- </BaseSectionHeader>
- </template>
-
- <div v-if="notifiers.data.value" class="mx-4 divide-y rounded-md border">
- <p v-if="notifiers.data.value.length === 0" class="p-2 text-center text-sm">
- {{ $t("profile.no_notifiers") }}
- </p>
- <article v-for="n in notifiers.data.value" v-else :key="n.id" class="p-2">
- <div class="flex flex-wrap items-center gap-2">
- <p class="mr-auto text-lg">{{ n.name }}</p>
- <TooltipProvider :delay-duration="0" class="flex justify-end gap-2">
- <Tooltip>
- <TooltipTrigger>
- <Button variant="destructive" size="icon" @click="deleteNotifier(n.id)">
- <MdiDelete />
- </Button>
- </TooltipTrigger>
- <TooltipContent> {{ $t("global.delete") }} </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger>
- <Button variant="outline" size="icon" @click="openNotifierDialog(n)">
- <MdiPencil />
- </Button>
- </TooltipTrigger>
- <TooltipContent> {{ $t("global.edit") }} </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <div class="flex flex-wrap justify-between py-1 text-sm">
- <p>
- <span v-if="n.isActive" :class="badgeVariants()"> {{ $t("profile.active") }} </span>
- <span v-else :class="badgeVariants({ variant: 'destructive' })"> {{ $t("profile.inactive") }} </span>
- </p>
- <p>
- {{ $t("global.created") }}
- <DateTime format="relative" datetime-type="time" :date="n.createdAt" />
- </p>
- </div>
- </article>
- </div>
-
- <div class="p-4">
- <Button variant="secondary" size="sm" @click="openNotifierDialog"> {{ $t("global.create") }} </Button>
- </div>
- </BaseCard>
-
- <BaseCard>
- <template #title>
- <BaseSectionHeader class="pb-0">
- <MdiAccountMultiple class="-mt-1 mr-2" />
- <span> {{ $t("profile.group_settings") }} </span>
+ <span> {{ $t("profile.moved_notice_title") }} </span>
<template #description>
- {{ $t("profile.group_settings_sub") }}
+ {{ $t("profile.moved_notice_description") }}
</template>
</BaseSectionHeader>
</template>
- <div v-if="group && currencies && currencies.length > 0" class="p-5 pt-0">
- <Label for="currency"> {{ $t("profile.currency_format") }} </Label>
- <Select
- id="currency"
- :model-value="currency.code"
- @update:model-value="
- event => {
- const newCurrency = currencies?.find(c => c.code === event);
- if (newCurrency) {
- currency = newCurrency;
- }
- }
- "
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="c in currencies" :key="c.code" :value="c.code">
- {{ c.name }}
- </SelectItem>
- </SelectContent>
- </Select>
- <p class="m-2 text-sm">{{ $t("profile.example") }}: {{ currencyExample }}</p>
-
- <div class="mt-4">
- <Button variant="secondary" size="sm" @click="updateGroup"> {{ $t("profile.update_group") }} </Button>
+ <div class="space-y-2 px-4 pb-4 text-sm text-muted-foreground">
+ <p>
+ {{ $t("profile.moved_notice_body") }}
+ </p>
+ <div class="flex flex-wrap gap-2">
+ <NuxtLink to="/collection/settings" class="text-primary underline">
+ {{ $t("profile.moved_notice_link_settings") }}
+ </NuxtLink>
+ <NuxtLink to="/collection/notifiers" class="text-primary underline">
+ {{ $t("profile.moved_notice_link_notifiers") }}
+ </NuxtLink>
+ <NuxtLink to="/collection/invites" class="text-primary underline">
+ {{ $t("profile.moved_notice_link_invites") }}
+ </NuxtLink>
</div>
</div>
</BaseCard>
-
<BaseCard>
<template #title>
<BaseSectionHeader>