refactor: repositories (#28)

* cleanup unnecessary mocks

* refactor document storage location

* remove unused function

* move ownership to document types to repo package

* move types and mappers to repo package

* refactor sets to own package
This commit is contained in:
Hayden 2022-09-27 15:52:13 -08:00 committed by GitHub
parent 2e82398e5c
commit 343290a55a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
79 changed files with 3169 additions and 3160 deletions

View file

@ -4,29 +4,23 @@ import "github.com/hay-kot/homebox/backend/internal/repo"
type AllServices struct {
User *UserService
Admin *AdminService
Location *LocationService
Labels *LabelService
Items *ItemService
}
func NewServices(repos *repo.AllRepos, root string) *AllServices {
func NewServices(repos *repo.AllRepos) *AllServices {
if repos == nil {
panic("repos cannot be nil")
}
if root == "" {
panic("root cannot be empty")
}
return &AllServices{
User: &UserService{repos},
Admin: &AdminService{repos},
Location: &LocationService{repos},
Labels: &LabelService{repos},
Items: &ItemService{
repo: repos,
filepath: root,
at: attachmentTokens{},
repo: repos,
at: attachmentTokens{},
},
}
}

View file

@ -4,7 +4,7 @@ import (
"context"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/internal/repo"
)
type contextKeys struct {
@ -26,7 +26,7 @@ type Context struct {
GID uuid.UUID
// User is the acting user.
User *types.UserOut
User *repo.UserOut
}
// NewContext is a helper function that returns the service context from the context.
@ -43,16 +43,16 @@ func NewContext(ctx context.Context) Context {
// SetUserCtx is a helper function that sets the ContextUser and ContextUserToken
// values within the context of a web request (or any context).
func SetUserCtx(ctx context.Context, user *types.UserOut, token string) context.Context {
func SetUserCtx(ctx context.Context, user *repo.UserOut, token string) context.Context {
ctx = context.WithValue(ctx, ContextUser, user)
ctx = context.WithValue(ctx, ContextUserToken, token)
return ctx
}
// UseUserCtx is a helper function that returns the user from the context.
func UseUserCtx(ctx context.Context) *types.UserOut {
func UseUserCtx(ctx context.Context) *repo.UserOut {
if val := ctx.Value(ContextUser); val != nil {
return val.(*types.UserOut)
return val.(*repo.UserOut)
}
return nil
}

View file

@ -5,12 +5,12 @@ import (
"testing"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/stretchr/testify/assert"
)
func Test_SetAuthContext(t *testing.T) {
user := &types.UserOut{
user := &repo.UserOut{
ID: uuid.New(),
}

View file

@ -10,7 +10,6 @@ import (
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/faker"
_ "github.com/mattn/go-sqlite3"
)
@ -21,7 +20,7 @@ var (
tCtx = Context{}
tClient *ent.Client
tRepos *repo.AllRepos
tUser *ent.User
tUser repo.UserOut
tGroup *ent.Group
tSvc *AllServices
)
@ -37,7 +36,7 @@ func bootstrap() {
log.Fatal(err)
}
tUser, err = tRepos.Users.Create(ctx, types.UserCreate{
tUser, err = tRepos.Users.Create(ctx, repo.UserCreate{
Name: fk.Str(10),
Email: fk.Email(),
Password: fk.Str(10),
@ -63,11 +62,10 @@ func TestMain(m *testing.M) {
}
tClient = client
tRepos = repo.EntAllRepos(tClient)
tSvc = NewServices(tRepos, "/tmp/homebox")
tRepos = repo.EntAllRepos(tClient, os.TempDir()+"/homebox")
tSvc = NewServices(tRepos)
defer client.Close()
bootstrap()
tCtx = Context{
Context: context.Background(),

View file

@ -1,9 +0,0 @@
package mappers
func MapEach[T any, U any](items []T, fn func(T) U) []U {
result := make([]U, len(items))
for i, item := range items {
result[i] = fn(item)
}
return result
}

View file

@ -1,91 +0,0 @@
package mappers
import (
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/types"
)
func ToItemAttachment(attachment *ent.Attachment) *types.ItemAttachment {
return &types.ItemAttachment{
ID: attachment.ID,
CreatedAt: attachment.CreatedAt,
UpdatedAt: attachment.UpdatedAt,
Type: attachment.Type.String(),
Document: types.DocumentOut{
ID: attachment.Edges.Document.ID,
Title: attachment.Edges.Document.Title,
Path: attachment.Edges.Document.Path,
},
}
}
func ToItemSummary(item *ent.Item) *types.ItemSummary {
var location *types.LocationSummary
if item.Edges.Location != nil {
location = ToLocationSummary(item.Edges.Location)
}
var labels []*types.LabelSummary
if item.Edges.Label != nil {
labels = MapEach(item.Edges.Label, ToLabelSummary)
}
return &types.ItemSummary{
ID: item.ID,
Name: item.Name,
Description: item.Description,
CreatedAt: item.CreatedAt,
UpdatedAt: item.UpdatedAt,
Quantity: item.Quantity,
Insured: item.Insured,
// Warranty
LifetimeWarranty: item.LifetimeWarranty,
WarrantyExpires: item.WarrantyExpires,
WarrantyDetails: item.WarrantyDetails,
// Edges
Location: location,
Labels: labels,
// Identification
SerialNumber: item.SerialNumber,
ModelNumber: item.ModelNumber,
Manufacturer: item.Manufacturer,
// Purchase
PurchaseTime: item.PurchaseTime,
PurchaseFrom: item.PurchaseFrom,
PurchasePrice: item.PurchasePrice,
// Sold
SoldTime: item.SoldTime,
SoldTo: item.SoldTo,
SoldPrice: item.SoldPrice,
SoldNotes: item.SoldNotes,
// Extras
Notes: item.Notes,
}
}
func ToItemSummaryErr(item *ent.Item, err error) (*types.ItemSummary, error) {
return ToItemSummary(item), err
}
func ToItemOut(item *ent.Item) *types.ItemOut {
var attachments []*types.ItemAttachment
if item.Edges.Attachments != nil {
attachments = MapEach(item.Edges.Attachments, ToItemAttachment)
}
return &types.ItemOut{
ItemSummary: *ToItemSummary(item),
Attachments: attachments,
}
}
func ToItemOutErr(item *ent.Item, err error) (*types.ItemOut, error) {
return ToItemOut(item), err
}

View file

@ -1,31 +0,0 @@
package mappers
import (
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/types"
)
func ToLabelSummary(label *ent.Label) *types.LabelSummary {
return &types.LabelSummary{
ID: label.ID,
Name: label.Name,
Description: label.Description,
CreatedAt: label.CreatedAt,
UpdatedAt: label.UpdatedAt,
}
}
func ToLabelSummaryErr(label *ent.Label, err error) (*types.LabelSummary, error) {
return ToLabelSummary(label), err
}
func ToLabelOut(label *ent.Label) *types.LabelOut {
return &types.LabelOut{
LabelSummary: *ToLabelSummary(label),
Items: MapEach(label.Edges.Items, ToItemSummary),
}
}
func ToLabelOutErr(label *ent.Label, err error) (*types.LabelOut, error) {
return ToLabelOut(label), err
}

View file

@ -1,55 +0,0 @@
package mappers
import (
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/types"
)
func ToLocationCount(location *repo.LocationWithCount) *types.LocationCount {
return &types.LocationCount{
LocationSummary: types.LocationSummary{
ID: location.ID,
Name: location.Name,
Description: location.Description,
CreatedAt: location.CreatedAt,
UpdatedAt: location.UpdatedAt,
},
ItemCount: location.ItemCount,
}
}
func ToLocationCountErr(location *repo.LocationWithCount, err error) (*types.LocationCount, error) {
return ToLocationCount(location), err
}
func ToLocationSummary(location *ent.Location) *types.LocationSummary {
return &types.LocationSummary{
ID: location.ID,
Name: location.Name,
Description: location.Description,
CreatedAt: location.CreatedAt,
UpdatedAt: location.UpdatedAt,
}
}
func ToLocationSummaryErr(location *ent.Location, err error) (*types.LocationSummary, error) {
return ToLocationSummary(location), err
}
func ToLocationOut(location *ent.Location) *types.LocationOut {
return &types.LocationOut{
LocationSummary: types.LocationSummary{
ID: location.ID,
Name: location.Name,
Description: location.Description,
CreatedAt: location.CreatedAt,
UpdatedAt: location.UpdatedAt,
},
Items: MapEach(location.Edges.Items, ToItemSummary),
}
}
func ToLocationOutErr(location *ent.Location, err error) (*types.LocationOut, error) {
return ToLocationOut(location), err
}

View file

@ -1,20 +0,0 @@
package mappers
import (
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/types"
)
func ToOutUser(user *ent.User, err error) (*types.UserOut, error) {
if err != nil {
return &types.UserOut{}, err
}
return &types.UserOut{
ID: user.ID,
Name: user.Name,
Email: user.Email,
IsSuperuser: user.IsSuperuser,
GroupName: user.Edges.Group.Name,
GroupID: user.Edges.Group.ID,
}, nil
}

View file

@ -1,48 +0,0 @@
package services
import (
"context"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/types"
)
type AdminService struct {
repos *repo.AllRepos
}
func (svc *AdminService) Create(ctx context.Context, usr types.UserCreate) (*ent.User, error) {
return svc.repos.Users.Create(ctx, usr)
}
func (svc *AdminService) GetAll(ctx context.Context) ([]*ent.User, error) {
return svc.repos.Users.GetAll(ctx)
}
func (svc *AdminService) GetByID(ctx context.Context, id uuid.UUID) (*ent.User, error) {
return svc.repos.Users.GetOneId(ctx, id)
}
func (svc *AdminService) GetByEmail(ctx context.Context, email string) (*ent.User, error) {
return svc.repos.Users.GetOneEmail(ctx, email)
}
func (svc *AdminService) UpdateProperties(ctx context.Context, ID uuid.UUID, data types.UserUpdate) (*ent.User, error) {
err := svc.repos.Users.Update(ctx, ID, data)
if err != nil {
return &ent.User{}, err
}
return svc.repos.Users.GetOneId(ctx, ID)
}
func (svc *AdminService) Delete(ctx context.Context, id uuid.UUID) error {
return svc.repos.Users.Delete(ctx, id)
}
func (svc *AdminService) DeleteAll(ctx context.Context) error {
return svc.repos.Users.DeleteAll(ctx)
}

View file

@ -7,8 +7,6 @@ import (
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/services/mappers"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/rs/zerolog/log"
)
@ -26,76 +24,24 @@ type ItemService struct {
at attachmentTokens
}
func (svc *ItemService) GetOne(ctx context.Context, gid uuid.UUID, id uuid.UUID) (*types.ItemOut, error) {
result, err := svc.repo.Items.GetOne(ctx, id)
if err != nil {
return nil, err
}
if result.Edges.Group.ID != gid {
return nil, ErrNotOwner
}
return mappers.ToItemOut(result), nil
func (svc *ItemService) GetOne(ctx context.Context, gid uuid.UUID, id uuid.UUID) (repo.ItemOut, error) {
return svc.repo.Items.GetOneByGroup(ctx, gid, id)
}
func (svc *ItemService) GetAll(ctx context.Context, gid uuid.UUID) ([]*types.ItemSummary, error) {
items, err := svc.repo.Items.GetAll(ctx, gid)
if err != nil {
return nil, err
}
itemsOut := make([]*types.ItemSummary, len(items))
for i, item := range items {
itemsOut[i] = mappers.ToItemSummary(item)
}
return itemsOut, nil
func (svc *ItemService) GetAll(ctx context.Context, gid uuid.UUID) ([]repo.ItemSummary, error) {
return svc.repo.Items.GetAll(ctx, gid)
}
func (svc *ItemService) Create(ctx context.Context, gid uuid.UUID, data types.ItemCreate) (*types.ItemOut, error) {
item, err := svc.repo.Items.Create(ctx, gid, data)
if err != nil {
return nil, err
}
return mappers.ToItemOut(item), nil
func (svc *ItemService) Create(ctx context.Context, gid uuid.UUID, data repo.ItemCreate) (repo.ItemOut, error) {
return svc.repo.Items.Create(ctx, gid, data)
}
func (svc *ItemService) Delete(ctx context.Context, gid uuid.UUID, id uuid.UUID) error {
item, err := svc.repo.Items.GetOne(ctx, id)
if err != nil {
return err
}
if item.Edges.Group.ID != gid {
return ErrNotOwner
}
err = svc.repo.Items.Delete(ctx, id)
if err != nil {
return err
}
return nil
return svc.repo.Items.DeleteByGroup(ctx, gid, id)
}
func (svc *ItemService) Update(ctx context.Context, gid uuid.UUID, data types.ItemUpdate) (*types.ItemOut, error) {
item, err := svc.repo.Items.GetOne(ctx, data.ID)
if err != nil {
return nil, err
}
if item.Edges.Group.ID != gid {
return nil, ErrNotOwner
}
item, err = svc.repo.Items.Update(ctx, data)
if err != nil {
return nil, err
}
return mappers.ToItemOut(item), nil
func (svc *ItemService) Update(ctx context.Context, gid uuid.UUID, data repo.ItemUpdate) (repo.ItemOut, error) {
return svc.repo.Items.UpdateByGroup(ctx, gid, data)
}
func (svc *ItemService) CsvImport(ctx context.Context, gid uuid.UUID, data [][]string) error {
@ -144,7 +90,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, gid uuid.UUID, data [][]s
fmt.Println("Creating Location: ", row.Location)
result, err := svc.repo.Locations.Create(ctx, gid, types.LocationCreate{
result, err := svc.repo.Locations.Create(ctx, gid, repo.LocationCreate{
Name: row.Location,
Description: "",
})
@ -159,7 +105,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, gid uuid.UUID, data [][]s
if _, ok := labels[label]; ok {
continue
}
result, err := svc.repo.Labels.Create(ctx, gid, types.LabelCreate{
result, err := svc.repo.Labels.Create(ctx, gid, repo.LabelCreate{
Name: label,
Description: "",
})
@ -185,7 +131,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, gid uuid.UUID, data [][]s
Str("locationId", locationID.String()).
Msgf("Creating Item: %s", row.Item.Name)
result, err := svc.repo.Items.Create(ctx, gid, types.ItemCreate{
result, err := svc.repo.Items.Create(ctx, gid, repo.ItemCreate{
ImportRef: row.Item.ImportRef,
Name: row.Item.Name,
Description: row.Item.Description,
@ -198,7 +144,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, gid uuid.UUID, data [][]s
}
// Update the item with the rest of the data
_, err = svc.repo.Items.Update(ctx, types.ItemUpdate{
_, err = svc.repo.Items.UpdateByGroup(ctx, gid, repo.ItemUpdate{
// Edges
LocationID: locationID,
LabelIDs: labelIDs,
@ -209,6 +155,7 @@ func (svc *ItemService) CsvImport(ctx context.Context, gid uuid.UUID, data [][]s
Description: result.Description,
Insured: row.Item.Insured,
Notes: row.Item.Notes,
Quantity: row.Item.Quantity,
// Identifies the item as imported
SerialNumber: row.Item.SerialNumber,

View file

@ -4,14 +4,13 @@ import (
"context"
"io"
"os"
"path/filepath"
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/attachment"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/pkgs/hasher"
"github.com/hay-kot/homebox/backend/pkgs/pathlib"
"github.com/rs/zerolog/log"
)
@ -41,13 +40,10 @@ func (at attachmentTokens) Delete(token string) {
}
func (svc *ItemService) AttachmentToken(ctx Context, itemId, attachmentId uuid.UUID) (string, error) {
item, err := svc.repo.Items.GetOne(ctx, itemId)
_, err := svc.repo.Items.GetOneByGroup(ctx, ctx.GID, itemId)
if err != nil {
return "", err
}
if item.Edges.Group.ID != ctx.GID {
return "", ErrNotOwner
}
token := hasher.GenerateToken()
@ -67,52 +63,32 @@ func (svc *ItemService) AttachmentToken(ctx Context, itemId, attachmentId uuid.U
return token.Raw, nil
}
func (svc *ItemService) attachmentPath(gid, itemId uuid.UUID, filename string) string {
path := filepath.Join(svc.filepath, gid.String(), itemId.String(), filename)
path = pathlib.Safe(path)
log.Debug().Str("path", path).Msg("attachment path")
return path
}
func (svc *ItemService) AttachmentPath(ctx context.Context, token string) (string, error) {
func (svc *ItemService) AttachmentPath(ctx context.Context, token string) (*ent.Document, error) {
attachmentId, ok := svc.at.Get(token)
if !ok {
return "", ErrNotFound
return nil, ErrNotFound
}
attachment, err := svc.repo.Attachments.Get(ctx, attachmentId)
if err != nil {
return "", err
}
return attachment.Edges.Document.Path, nil
}
func (svc *ItemService) AttachmentUpdate(ctx Context, itemId uuid.UUID, data *types.ItemAttachmentUpdate) (*types.ItemOut, error) {
// Update Properties
attachment, err := svc.repo.Attachments.Update(ctx, data.ID, attachment.Type(data.Type))
if err != nil {
return nil, err
}
return attachment.Edges.Document, nil
}
func (svc *ItemService) AttachmentUpdate(ctx Context, itemId uuid.UUID, data *repo.ItemAttachmentUpdate) (repo.ItemOut, error) {
// Update Attachment
attachment, err := svc.repo.Attachments.Update(ctx, data.ID, attachment.Type(data.Type))
if err != nil {
return repo.ItemOut{}, err
}
// Update Document
attDoc := attachment.Edges.Document
if data.Title != attachment.Edges.Document.Title {
newPath := pathlib.Safe(svc.attachmentPath(ctx.GID, itemId, data.Title))
// Move File
err = os.Rename(attachment.Edges.Document.Path, newPath)
if err != nil {
return nil, err
}
_, err = svc.repo.Docs.Update(ctx, attDoc.ID, types.DocumentUpdate{
Title: data.Title,
Path: newPath,
})
if err != nil {
return nil, err
}
_, err = svc.repo.Docs.Rename(ctx, attDoc.ID, data.Title)
if err != nil {
return repo.ItemOut{}, err
}
return svc.GetOne(ctx, ctx.GID, itemId)
@ -121,50 +97,25 @@ func (svc *ItemService) AttachmentUpdate(ctx Context, itemId uuid.UUID, data *ty
// AttachmentAdd adds an attachment to an item by creating an entry in the Documents table and linking it to the Attachment
// Table and Items table. The file provided via the reader is stored on the file system based on the provided
// relative path during construction of the service.
func (svc *ItemService) AttachmentAdd(ctx Context, itemId uuid.UUID, filename string, attachmentType attachment.Type, file io.Reader) (*types.ItemOut, error) {
func (svc *ItemService) AttachmentAdd(ctx Context, itemId uuid.UUID, filename string, attachmentType attachment.Type, file io.Reader) (repo.ItemOut, error) {
// Get the Item
item, err := svc.repo.Items.GetOne(ctx, itemId)
_, err := svc.repo.Items.GetOneByGroup(ctx, ctx.GID, itemId)
if err != nil {
return nil, err
return repo.ItemOut{}, err
}
if item.Edges.Group.ID != ctx.GID {
return nil, ErrNotOwner
}
fp := svc.attachmentPath(ctx.GID, itemId, filename)
filename = filepath.Base(fp)
// Create the document
doc, err := svc.repo.Docs.Create(ctx, ctx.GID, types.DocumentCreate{
Title: filename,
Path: fp,
})
doc, err := svc.repo.Docs.Create(ctx, ctx.GID, repo.DocumentCreate{Title: filename, Content: file})
if err != nil {
return nil, err
log.Err(err).Msg("failed to create document")
return repo.ItemOut{}, err
}
// Create the attachment
_, err = svc.repo.Attachments.Create(ctx, itemId, doc.ID, attachmentType)
if err != nil {
return nil, err
}
// Read the contents and write them to a file on the file system
err = os.MkdirAll(filepath.Dir(doc.Path), os.ModePerm)
if err != nil {
return nil, err
}
f, err := os.Create(doc.Path)
if err != nil {
log.Err(err).Msg("failed to create file")
return nil, err
}
_, err = io.Copy(f, file)
if err != nil {
return nil, err
log.Err(err).Msg("failed to create attachment")
return repo.ItemOut{}, err
}
return svc.GetOne(ctx, ctx.GID, itemId)
@ -172,15 +123,11 @@ func (svc *ItemService) AttachmentAdd(ctx Context, itemId uuid.UUID, filename st
func (svc *ItemService) AttachmentDelete(ctx context.Context, gid, itemId, attachmentId uuid.UUID) error {
// Get the Item
item, err := svc.repo.Items.GetOne(ctx, itemId)
_, err := svc.repo.Items.GetOneByGroup(ctx, gid, itemId)
if err != nil {
return err
}
if item.Edges.Group.ID != gid {
return ErrNotOwner
}
attachment, err := svc.repo.Attachments.Get(ctx, attachmentId)
if err != nil {
return err

View file

@ -7,7 +7,7 @@ import (
"strings"
"testing"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/stretchr/testify/assert"
)
@ -19,14 +19,14 @@ func TestItemService_AddAttachment(t *testing.T) {
filepath: temp,
}
loc, err := tSvc.Location.Create(context.Background(), tGroup.ID, types.LocationCreate{
loc, err := tSvc.Location.Create(context.Background(), tGroup.ID, repo.LocationCreate{
Description: "test",
Name: "test",
})
assert.NoError(t, err)
assert.NotNil(t, loc)
itmC := types.ItemCreate{
itmC := repo.ItemCreate{
Name: fk.Str(10),
Description: fk.Str(10),
LocationID: loc.ID,
@ -52,7 +52,7 @@ func TestItemService_AddAttachment(t *testing.T) {
storedPath := afterAttachment.Attachments[0].Document.Path
// {root}/{group}/{item}/{attachment}
assert.Equal(t, path.Join(temp, tGroup.ID.String(), itm.ID.String(), "testfile.txt"), storedPath)
assert.Equal(t, path.Join(temp, "homebox", tGroup.ID.String(), "documents"), path.Dir(storedPath))
// Check that the file contents are correct
bts, err := os.ReadFile(storedPath)

View file

@ -6,7 +6,7 @@ import (
"strings"
"time"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/internal/repo"
)
var ErrInvalidCsv = errors.New("invalid csv")
@ -45,7 +45,7 @@ func parseInt(s string) int {
}
type csvRow struct {
Item types.ItemSummary
Item repo.ItemOut
Location string
LabelStr string
}
@ -54,12 +54,14 @@ func newCsvRow(row []string) csvRow {
return csvRow{
Location: row[1],
LabelStr: row[2],
Item: types.ItemSummary{
ImportRef: row[0],
Quantity: parseInt(row[3]),
Name: row[4],
Description: row[5],
Insured: parseBool(row[6]),
Item: repo.ItemOut{
ItemSummary: repo.ItemSummary{
ImportRef: row[0],
Quantity: parseInt(row[3]),
Name: row[4],
Description: row[5],
Insured: parseBool(row[6]),
},
SerialNumber: row[7],
ModelNumber: row[8],
Manufacturer: row[9],

View file

@ -71,19 +71,8 @@ func TestItemService_CsvImport(t *testing.T) {
for _, csvRow := range dataCsv {
if csvRow.Item.Name == item.Name {
assert.Equal(t, csvRow.Item.Description, item.Description)
assert.Equal(t, csvRow.Item.SerialNumber, item.SerialNumber)
assert.Equal(t, csvRow.Item.Manufacturer, item.Manufacturer)
assert.Equal(t, csvRow.Item.Notes, item.Notes)
// Purchase Fields
assert.Equal(t, csvRow.Item.PurchaseTime, item.PurchaseTime)
assert.Equal(t, csvRow.Item.PurchaseFrom, item.PurchaseFrom)
assert.Equal(t, csvRow.Item.PurchasePrice, item.PurchasePrice)
// Sold Fields
assert.Equal(t, csvRow.Item.SoldTime, item.SoldTime)
assert.Equal(t, csvRow.Item.SoldTo, item.SoldTo)
assert.Equal(t, csvRow.Item.SoldPrice, item.SoldPrice)
assert.Equal(t, csvRow.Item.Quantity, item.Quantity)
assert.Equal(t, csvRow.Item.Insured, item.Insured)
}
}
}

View file

@ -5,59 +5,33 @@ import (
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/services/mappers"
"github.com/hay-kot/homebox/backend/internal/types"
)
type LabelService struct {
repos *repo.AllRepos
}
func (svc *LabelService) Create(ctx context.Context, groupId uuid.UUID, data types.LabelCreate) (*types.LabelSummary, error) {
label, err := svc.repos.Labels.Create(ctx, groupId, data)
return mappers.ToLabelSummaryErr(label, err)
func (svc *LabelService) Create(ctx context.Context, groupId uuid.UUID, data repo.LabelCreate) (repo.LabelOut, error) {
return svc.repos.Labels.Create(ctx, groupId, data)
}
func (svc *LabelService) Update(ctx context.Context, groupId uuid.UUID, data types.LabelUpdate) (*types.LabelSummary, error) {
label, err := svc.repos.Labels.Update(ctx, data)
return mappers.ToLabelSummaryErr(label, err)
func (svc *LabelService) Update(ctx context.Context, groupId uuid.UUID, data repo.LabelUpdate) (repo.LabelOut, error) {
return svc.repos.Labels.Update(ctx, data)
}
func (svc *LabelService) Delete(ctx context.Context, groupId uuid.UUID, id uuid.UUID) error {
label, err := svc.repos.Labels.Get(ctx, id)
func (svc *LabelService) Delete(ctx context.Context, gid uuid.UUID, id uuid.UUID) error {
_, err := svc.repos.Labels.GetOneByGroup(ctx, gid, id)
if err != nil {
return err
}
if label.Edges.Group.ID != groupId {
return ErrNotOwner
}
return svc.repos.Labels.Delete(ctx, id)
}
func (svc *LabelService) Get(ctx context.Context, groupId uuid.UUID, id uuid.UUID) (*types.LabelOut, error) {
label, err := svc.repos.Labels.Get(ctx, id)
func (svc *LabelService) Get(ctx context.Context, gid uuid.UUID, id uuid.UUID) (repo.LabelOut, error) {
return svc.repos.Labels.GetOneByGroup(ctx, gid, id)
if err != nil {
return nil, err
}
if label.Edges.Group.ID != groupId {
return nil, ErrNotOwner
}
return mappers.ToLabelOut(label), nil
}
func (svc *LabelService) GetAll(ctx context.Context, groupId uuid.UUID) ([]*types.LabelSummary, error) {
labels, err := svc.repos.Labels.GetAll(ctx, groupId)
if err != nil {
return nil, err
}
labelsOut := make([]*types.LabelSummary, len(labels))
for i, label := range labels {
labelsOut[i] = mappers.ToLabelSummary(label)
}
return labelsOut, nil
func (svc *LabelService) GetAll(ctx context.Context, groupId uuid.UUID) ([]repo.LabelSummary, error) {
return svc.repos.Labels.GetAll(ctx, groupId)
}

View file

@ -6,8 +6,6 @@ import (
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/services/mappers"
"github.com/hay-kot/homebox/backend/internal/types"
)
var (
@ -18,59 +16,32 @@ type LocationService struct {
repos *repo.AllRepos
}
func (svc *LocationService) GetOne(ctx context.Context, groupId uuid.UUID, id uuid.UUID) (*types.LocationOut, error) {
location, err := svc.repos.Locations.Get(ctx, id)
if err != nil {
return nil, err
}
if location.Edges.Group.ID != groupId {
return nil, ErrNotOwner
}
return mappers.ToLocationOut(location), nil
func (svc *LocationService) GetOne(ctx context.Context, groupId uuid.UUID, id uuid.UUID) (repo.LocationOut, error) {
return svc.repos.Locations.GetOneByGroup(ctx, groupId, id)
}
func (svc *LocationService) GetAll(ctx context.Context, groupId uuid.UUID) ([]*types.LocationCount, error) {
locations, err := svc.repos.Locations.GetAll(ctx, groupId)
if err != nil {
return nil, err
}
locationsOut := make([]*types.LocationCount, len(locations))
for i, location := range locations {
locationsOut[i] = mappers.ToLocationCount(&location)
}
return locationsOut, nil
func (svc *LocationService) GetAll(ctx context.Context, groupId uuid.UUID) ([]repo.LocationOutCount, error) {
return svc.repos.Locations.GetAll(ctx, groupId)
}
func (svc *LocationService) Create(ctx context.Context, groupId uuid.UUID, data types.LocationCreate) (*types.LocationOut, error) {
location, err := svc.repos.Locations.Create(ctx, groupId, data)
return mappers.ToLocationOutErr(location, err)
func (svc *LocationService) Create(ctx context.Context, groupId uuid.UUID, data repo.LocationCreate) (repo.LocationOut, error) {
return svc.repos.Locations.Create(ctx, groupId, data)
}
func (svc *LocationService) Delete(ctx context.Context, groupId uuid.UUID, id uuid.UUID) error {
location, err := svc.repos.Locations.Get(ctx, id)
_, err := svc.repos.Locations.GetOneByGroup(ctx, groupId, id)
if err != nil {
return err
}
if location.Edges.Group.ID != groupId {
return ErrNotOwner
}
return svc.repos.Locations.Delete(ctx, id)
}
func (svc *LocationService) Update(ctx context.Context, groupId uuid.UUID, data types.LocationUpdate) (*types.LocationOut, error) {
location, err := svc.repos.Locations.Get(ctx, data.ID)
func (svc *LocationService) Update(ctx context.Context, groupId uuid.UUID, data repo.LocationUpdate) (repo.LocationOut, error) {
location, err := svc.repos.Locations.GetOneByGroup(ctx, groupId, data.ID)
if err != nil {
return nil, err
}
if location.Edges.Group.ID != groupId {
return nil, ErrNotOwner
return repo.LocationOut{}, err
}
return mappers.ToLocationOutErr(svc.repos.Locations.Update(ctx, data))
data.ID = location.ID
return svc.repos.Locations.Update(ctx, data)
}

View file

@ -7,9 +7,8 @@ import (
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/services/mappers"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/hasher"
"github.com/rs/zerolog/log"
)
var (
@ -23,18 +22,46 @@ type UserService struct {
repos *repo.AllRepos
}
type (
UserRegistration struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
GroupName string `json:"groupName"`
}
UserAuthTokenDetail struct {
Raw string `json:"raw"`
ExpiresAt time.Time `json:"expiresAt"`
}
UserAuthTokenCreate struct {
TokenHash []byte `json:"token"`
UserID uuid.UUID `json:"userId"`
ExpiresAt time.Time `json:"expiresAt"`
}
LoginForm struct {
Username string `json:"username"`
Password string `json:"password"`
}
)
// RegisterUser creates a new user and group in the data with the provided data. It also bootstraps the user's group
// with default Labels and Locations.
func (svc *UserService) RegisterUser(ctx context.Context, data types.UserRegistration) (*types.UserOut, error) {
func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration) (repo.UserOut, error) {
log.Debug().
Str("name", data.Name).
Str("email", data.Email).
Str("groupName", data.GroupName).
Msg("Registering new user")
group, err := svc.repos.Groups.Create(ctx, data.GroupName)
if err != nil {
return &types.UserOut{}, err
return repo.UserOut{}, err
}
hashed, _ := hasher.HashPassword(data.User.Password)
usrCreate := types.UserCreate{
Name: data.User.Name,
Email: data.User.Email,
hashed, _ := hasher.HashPassword(data.Password)
usrCreate := repo.UserCreate{
Name: data.Name,
Email: data.Email,
Password: hashed,
IsSuperuser: false,
GroupID: group.ID,
@ -42,61 +69,61 @@ func (svc *UserService) RegisterUser(ctx context.Context, data types.UserRegistr
usr, err := svc.repos.Users.Create(ctx, usrCreate)
if err != nil {
return &types.UserOut{}, err
return repo.UserOut{}, err
}
for _, label := range defaultLabels() {
_, err := svc.repos.Labels.Create(ctx, group.ID, label)
if err != nil {
return &types.UserOut{}, err
return repo.UserOut{}, err
}
}
for _, location := range defaultLocations() {
_, err := svc.repos.Locations.Create(ctx, group.ID, location)
if err != nil {
return &types.UserOut{}, err
return repo.UserOut{}, err
}
}
return mappers.ToOutUser(usr, nil)
return usr, nil
}
// GetSelf returns the user that is currently logged in based of the token provided within
func (svc *UserService) GetSelf(ctx context.Context, requestToken string) (*types.UserOut, error) {
func (svc *UserService) GetSelf(ctx context.Context, requestToken string) (repo.UserOut, error) {
hash := hasher.HashToken(requestToken)
return mappers.ToOutUser(svc.repos.AuthTokens.GetUserFromToken(ctx, hash))
return svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
}
func (svc *UserService) UpdateSelf(ctx context.Context, ID uuid.UUID, data types.UserUpdate) (*types.UserOut, error) {
func (svc *UserService) UpdateSelf(ctx context.Context, ID uuid.UUID, data repo.UserUpdate) (repo.UserOut, error) {
err := svc.repos.Users.Update(ctx, ID, data)
if err != nil {
return &types.UserOut{}, err
return repo.UserOut{}, err
}
return mappers.ToOutUser(svc.repos.Users.GetOneId(ctx, ID))
return svc.repos.Users.GetOneId(ctx, ID)
}
// ============================================================================
// User Authentication
func (svc *UserService) createToken(ctx context.Context, userId uuid.UUID) (types.UserAuthTokenDetail, error) {
func (svc *UserService) createToken(ctx context.Context, userId uuid.UUID) (UserAuthTokenDetail, error) {
newToken := hasher.GenerateToken()
created, err := svc.repos.AuthTokens.CreateToken(ctx, types.UserAuthTokenCreate{
created, err := svc.repos.AuthTokens.CreateToken(ctx, repo.UserAuthTokenCreate{
UserID: userId,
TokenHash: newToken.Hash,
ExpiresAt: time.Now().Add(oneWeek),
})
return types.UserAuthTokenDetail{Raw: newToken.Raw, ExpiresAt: created.ExpiresAt}, err
return UserAuthTokenDetail{Raw: newToken.Raw, ExpiresAt: created.ExpiresAt}, err
}
func (svc *UserService) Login(ctx context.Context, username, password string) (types.UserAuthTokenDetail, error) {
func (svc *UserService) Login(ctx context.Context, username, password string) (UserAuthTokenDetail, error) {
usr, err := svc.repos.Users.GetOneEmail(ctx, username)
if err != nil || !hasher.CheckPasswordHash(password, usr.Password) {
return types.UserAuthTokenDetail{}, ErrorInvalidLogin
if err != nil || !hasher.CheckPasswordHash(password, usr.PasswordHash) {
return UserAuthTokenDetail{}, ErrorInvalidLogin
}
return svc.createToken(ctx, usr.ID)
@ -108,13 +135,13 @@ func (svc *UserService) Logout(ctx context.Context, token string) error {
return err
}
func (svc *UserService) RenewToken(ctx context.Context, token string) (types.UserAuthTokenDetail, error) {
func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthTokenDetail, error) {
hash := hasher.HashToken(token)
dbToken, err := svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
if err != nil {
return types.UserAuthTokenDetail{}, ErrorInvalidToken
return UserAuthTokenDetail{}, ErrorInvalidToken
}
newToken, _ := svc.createToken(ctx, dbToken.ID)

View file

@ -1,9 +1,11 @@
package services
import "github.com/hay-kot/homebox/backend/internal/types"
import (
"github.com/hay-kot/homebox/backend/internal/repo"
)
func defaultLocations() []types.LocationCreate {
return []types.LocationCreate{
func defaultLocations() []repo.LocationCreate {
return []repo.LocationCreate{
{
Name: "Living Room",
},
@ -31,8 +33,8 @@ func defaultLocations() []types.LocationCreate {
}
}
func defaultLabels() []types.LabelCreate {
return []types.LabelCreate{
func defaultLabels() []repo.LabelCreate {
return []repo.LabelCreate{
{
Name: "Appliances",
},