feat: locations tree viewer (#248)

* location tree API

* test fixes

* initial tree location elements

* locations tree page

* update meta-data

* code-gen

* store item display preferences

* introduce basic table/card view elements

* codegen

* set parent location during location creation

* add item support for tree query

* refactor tree view

* wip: location selector improvements

* type gen

* rename items -> search

* remove various log statements

* fix markdown rendering for description

* update location selectors

* fix tests

* fix currency tests

* formatting
This commit is contained in:
Hayden 2023-01-28 11:53:00 -09:00 committed by GitHub
parent 4d220cdd9c
commit 3d295b5132
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 1119 additions and 79 deletions

View File

@ -11,6 +11,39 @@ import (
"github.com/rs/zerolog/log"
)
// HandleLocationTreeQuery godoc
// @Summary Get All Locations
// @Tags Locations
// @Produce json
// @Param withItems query bool false "include items in response tree"
// @Success 200 {object} server.Results{items=[]repo.TreeItem}
// @Router /v1/locations/tree [GET]
// @Security Bearer
func (ctrl *V1Controller) HandleLocationTreeQuery() server.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
user := services.UseUserCtx(r.Context())
q := r.URL.Query()
withItems := queryBool(q.Get("withItems"))
locTree, err := ctrl.repo.Locations.Tree(
r.Context(),
user.GroupID,
repo.TreeQuery{
WithItems: withItems,
},
)
if err != nil {
log.Err(err).Msg("failed to get locations tree")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
return server.Respond(w, http.StatusOK, server.Results{Items: locTree})
}
}
// HandleLocationGetAll godoc
// @Summary Get All Locations
// @Tags Locations

View File

@ -91,6 +91,7 @@ func (a *app) mountRoutes(repos *repo.AllRepos) {
a.server.Get(v1Base("/locations"), v1Ctrl.HandleLocationGetAll(), userMW...)
a.server.Post(v1Base("/locations"), v1Ctrl.HandleLocationCreate(), userMW...)
a.server.Get(v1Base("/locations/tree"), v1Ctrl.HandleLocationTreeQuery(), userMW...)
a.server.Get(v1Base("/locations/{id}"), v1Ctrl.HandleLocationGet(), userMW...)
a.server.Put(v1Base("/locations/{id}"), v1Ctrl.HandleLocationUpdate(), userMW...)
a.server.Delete(v1Base("/locations/{id}"), v1Ctrl.HandleLocationDelete(), userMW...)

View File

@ -1045,6 +1045,53 @@ const docTemplate = `{
}
}
},
"/v1/locations/tree": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"Locations"
],
"summary": "Get All Locations",
"parameters": [
{
"type": "boolean",
"description": "include items in response tree",
"name": "withItems",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"allOf": [
{
"$ref": "#/definitions/server.Results"
},
{
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"$ref": "#/definitions/repo.TreeItem"
}
}
}
}
]
}
}
}
}
},
"/v1/locations/{id}": {
"get": {
"security": [
@ -1906,6 +1953,10 @@ const docTemplate = `{
},
"name": {
"type": "string"
},
"parentId": {
"type": "string",
"x-nullable": true
}
}
},
@ -2116,6 +2167,26 @@ const docTemplate = `{
}
}
},
"repo.TreeItem": {
"type": "object",
"properties": {
"children": {
"type": "array",
"items": {
"$ref": "#/definitions/repo.TreeItem"
}
},
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"type": {
"type": "string"
}
}
},
"repo.UserOut": {
"type": "object",
"properties": {

View File

@ -1037,6 +1037,53 @@
}
}
},
"/v1/locations/tree": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"Locations"
],
"summary": "Get All Locations",
"parameters": [
{
"type": "boolean",
"description": "include items in response tree",
"name": "withItems",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"allOf": [
{
"$ref": "#/definitions/server.Results"
},
{
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"$ref": "#/definitions/repo.TreeItem"
}
}
}
}
]
}
}
}
}
},
"/v1/locations/{id}": {
"get": {
"security": [
@ -1898,6 +1945,10 @@
},
"name": {
"type": "string"
},
"parentId": {
"type": "string",
"x-nullable": true
}
}
},
@ -2108,6 +2159,26 @@
}
}
},
"repo.TreeItem": {
"type": "object",
"properties": {
"children": {
"type": "array",
"items": {
"$ref": "#/definitions/repo.TreeItem"
}
},
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"type": {
"type": "string"
}
}
},
"repo.UserOut": {
"type": "object",
"properties": {

View File

@ -322,6 +322,9 @@ definitions:
type: string
name:
type: string
parentId:
type: string
x-nullable: true
type: object
repo.LocationOut:
properties:
@ -459,6 +462,19 @@ definitions:
total:
type: number
type: object
repo.TreeItem:
properties:
children:
items:
$ref: '#/definitions/repo.TreeItem'
type: array
id:
type: string
name:
type: string
type:
type: string
type: object
repo.UserOut:
properties:
email:
@ -1301,6 +1317,32 @@ paths:
summary: updates a location
tags:
- Locations
/v1/locations/tree:
get:
parameters:
- description: include items in response tree
in: query
name: withItems
type: boolean
produces:
- application/json
responses:
"200":
description: OK
schema:
allOf:
- $ref: '#/definitions/server.Results'
- properties:
items:
items:
$ref: '#/definitions/repo.TreeItem'
type: array
type: object
security:
- Bearer: []
summary: Get All Locations
tags:
- Locations
/v1/qrcode:
get:
parameters:

View File

@ -131,6 +131,7 @@ const (
CurrencyDkk Currency = "dkk"
CurrencyInr Currency = "inr"
CurrencyRmb Currency = "rmb"
CurrencyBgn Currency = "bgn"
)
func (c Currency) String() string {
@ -140,7 +141,7 @@ func (c Currency) String() string {
// CurrencyValidator is a validator for the "currency" field enum values. It is called by the builders before save.
func CurrencyValidator(c Currency) error {
switch c {
case CurrencyUsd, CurrencyEur, CurrencyGbp, CurrencyJpy, CurrencyZar, CurrencyAud, CurrencyNok, CurrencySek, CurrencyDkk, CurrencyInr, CurrencyRmb:
case CurrencyUsd, CurrencyEur, CurrencyGbp, CurrencyJpy, CurrencyZar, CurrencyAud, CurrencyNok, CurrencySek, CurrencyDkk, CurrencyInr, CurrencyRmb, CurrencyBgn:
return nil
default:
return fmt.Errorf("group: invalid enum value for currency field: %q", c)

View File

@ -116,7 +116,7 @@ var (
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "currency", Type: field.TypeEnum, Enums: []string{"usd", "eur", "gbp", "jpy", "zar", "aud", "nok", "sek", "dkk", "inr", "rmb"}, Default: "usd"},
{Name: "currency", Type: field.TypeEnum, Enums: []string{"usd", "eur", "gbp", "jpy", "zar", "aud", "nok", "sek", "dkk", "inr", "rmb", "bgn"}, Default: "usd"},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{

View File

@ -27,7 +27,7 @@ func (Group) Fields() []ent.Field {
NotEmpty(),
field.Enum("currency").
Default("usd").
Values("usd", "eur", "gbp", "jpy", "zar", "aud", "nok", "sek", "dkk", "inr", "rmb"),
Values("usd", "eur", "gbp", "jpy", "zar", "aud", "nok", "sek", "dkk", "inr", "rmb", "bgn"),
}
}

View File

@ -356,7 +356,6 @@ func (e *ItemsRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q Ite
}
// QueryByAssetID returns items by asset ID. If the item does not exist, an error is returned.
func (e *ItemsRepository) QueryByAssetID(ctx context.Context, gid uuid.UUID, assetID AssetID, page int, pageSize int) (PaginationResult[ItemSummary], error) {
qb := e.db.Item.Query().Where(
@ -372,7 +371,7 @@ func (e *ItemsRepository) QueryByAssetID(ctx context.Context, gid uuid.UUID, ass
pageSize = -1
}
items, err := mapItemsSummaryErr(
items, err := mapItemsSummaryErr(
qb.Order(ent.Asc(item.FieldName)).
WithLabel().
WithLocation().

View File

@ -36,6 +36,8 @@ func useItems(t *testing.T, len int) []ItemOut {
for _, item := range items {
_ = tRepos.Items.Delete(context.Background(), item.ID)
}
_ = tRepos.Locations.Delete(context.Background(), location.ID)
})
return items

View File

@ -19,8 +19,9 @@ type LocationRepository struct {
type (
LocationCreate struct {
Name string `json:"name"`
Description string `json:"description"`
Name string `json:"name"`
ParentID uuid.UUID `json:"parentId" extensions:"x-nullable"`
Description string `json:"description"`
}
LocationUpdate struct {
@ -152,7 +153,9 @@ func (r *LocationRepository) getOne(ctx context.Context, where ...predicate.Loca
Where(where...).
WithGroup().
WithItems(func(iq *ent.ItemQuery) {
iq.Where(item.Archived(false)).WithLabel()
iq.Where(item.Archived(false)).
Order(ent.Asc(item.FieldName)).
WithLabel()
}).
WithParent().
WithChildren().
@ -168,11 +171,16 @@ func (r *LocationRepository) GetOneByGroup(ctx context.Context, GID, ID uuid.UUI
}
func (r *LocationRepository) Create(ctx context.Context, GID uuid.UUID, data LocationCreate) (LocationOut, error) {
location, err := r.db.Location.Create().
q := r.db.Location.Create().
SetName(data.Name).
SetDescription(data.Description).
SetGroupID(GID).
Save(ctx)
SetGroupID(GID)
if data.ParentID != uuid.Nil {
q.SetParentID(data.ParentID)
}
location, err := q.Save(ctx)
if err != nil {
return LocationOut{}, err
@ -218,3 +226,129 @@ func (r *LocationRepository) DeleteByGroup(ctx context.Context, GID, ID uuid.UUI
_, err := r.db.Location.Delete().Where(location.ID(ID), location.HasGroupWith(group.ID(GID))).Exec(ctx)
return err
}
type TreeItem struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Children []*TreeItem `json:"children"`
}
type FlatTreeItem struct {
ID uuid.UUID
Name string
Type string
ParentID uuid.UUID
Level int
}
type TreeQuery struct {
WithItems bool `json:"withItems"`
}
func (lr *LocationRepository) Tree(ctx context.Context, GID uuid.UUID, tq TreeQuery) ([]TreeItem, error) {
query := `
WITH recursive location_tree(id, NAME, location_children, level, node_type) AS
(
SELECT id,
NAME,
location_children,
0 AS level,
'location' AS node_type
FROM locations
WHERE location_children IS NULL
AND group_locations = ?
UNION ALL
SELECT c.id,
c.NAME,
c.location_children,
level + 1,
'location' AS node_type
FROM locations c
JOIN location_tree p
ON c.location_children = p.id
WHERE level < 10 -- prevent infinite loop & excessive recursion
{{ WITH_ITEMS }}
)
SELECT id,
NAME,
level,
location_children,
node_type
FROM location_tree
ORDER BY level,
node_type DESC, -- sort locations before items
NAME;`
if tq.WithItems {
itemQuery := `
UNION ALL
SELECT i.id,
i.name,
location_items as location_children,
level + 1,
'item' AS node_type
FROM items i
JOIN location_tree p
ON i.location_items = p.id
WHERE level < 10 -- prevent infinite loop & excessive recursion`
query = strings.ReplaceAll(query, "{{ WITH_ITEMS }}", itemQuery)
} else {
query = strings.ReplaceAll(query, "{{ WITH_ITEMS }}", "")
}
rows, err := lr.db.Sql().QueryContext(ctx, query, GID)
if err != nil {
return nil, err
}
defer rows.Close()
var locations []FlatTreeItem
for rows.Next() {
var location FlatTreeItem
if err := rows.Scan(&location.ID, &location.Name, &location.Level, &location.ParentID, &location.Type); err != nil {
return nil, err
}
locations = append(locations, location)
}
if err := rows.Err(); err != nil {
return nil, err
}
return ConvertLocationsToTree(locations), nil
}
func ConvertLocationsToTree(locations []FlatTreeItem) []TreeItem {
var locationMap = make(map[uuid.UUID]*TreeItem, len(locations))
var rootIds []uuid.UUID
for _, location := range locations {
loc := &TreeItem{
ID: location.ID,
Name: location.Name,
Type: location.Type,
Children: []*TreeItem{},
}
locationMap[location.ID] = loc
if location.ParentID != uuid.Nil {
parent, ok := locationMap[location.ParentID]
if ok {
parent.Children = append(parent.Children, loc)
}
} else {
rootIds = append(rootIds, location.ID)
}
}
roots := make([]TreeItem, 0, len(rootIds))
for _, id := range rootIds {
roots = append(roots, *locationMap[id])
}
return roots
}

View File

@ -2,8 +2,11 @@ package repo
import (
"context"
"encoding/json"
"testing"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/data/ent"
"github.com/stretchr/testify/assert"
)
@ -14,6 +17,30 @@ func locationFactory() LocationCreate {
}
}
func useLocations(t *testing.T, len int) []LocationOut {
t.Helper()
out := make([]LocationOut, len)
for i := 0; i < len; i++ {
loc, err := tRepos.Locations.Create(context.Background(), tGroup.ID, locationFactory())
assert.NoError(t, err)
out[i] = loc
}
t.Cleanup(func() {
for _, loc := range out {
err := tRepos.Locations.Delete(context.Background(), loc.ID)
if err != nil {
assert.True(t, ent.IsNotFound(err))
}
}
})
return out
}
func TestLocationRepository_Get(t *testing.T) {
loc, err := tRepos.Locations.Create(context.Background(), tGroup.ID, locationFactory())
assert.NoError(t, err)
@ -29,13 +56,9 @@ func TestLocationRepository_Get(t *testing.T) {
func TestLocationRepositoryGetAllWithCount(t *testing.T) {
ctx := context.Background()
result, err := tRepos.Locations.Create(ctx, tGroup.ID, LocationCreate{
Name: fk.Str(10),
Description: fk.Str(100),
})
assert.NoError(t, err)
result := useLocations(t, 1)[0]
_, err = tRepos.Items.Create(ctx, tGroup.ID, ItemCreate{
_, err := tRepos.Items.Create(ctx, tGroup.ID, ItemCreate{
Name: fk.Str(10),
Description: fk.Str(100),
LocationID: result.ID,
@ -55,8 +78,7 @@ func TestLocationRepositoryGetAllWithCount(t *testing.T) {
}
func TestLocationRepository_Create(t *testing.T) {
loc, err := tRepos.Locations.Create(context.Background(), tGroup.ID, locationFactory())
assert.NoError(t, err)
loc := useLocations(t, 1)[0]
// Get by ID
foundLoc, err := tRepos.Locations.Get(context.Background(), loc.ID)
@ -68,8 +90,7 @@ func TestLocationRepository_Create(t *testing.T) {
}
func TestLocationRepository_Update(t *testing.T) {
loc, err := tRepos.Locations.Create(context.Background(), tGroup.ID, locationFactory())
assert.NoError(t, err)
loc := useLocations(t, 1)[0]
updateData := LocationUpdate{
ID: loc.ID,
@ -92,12 +113,154 @@ func TestLocationRepository_Update(t *testing.T) {
}
func TestLocationRepository_Delete(t *testing.T) {
loc, err := tRepos.Locations.Create(context.Background(), tGroup.ID, locationFactory())
assert.NoError(t, err)
loc := useLocations(t, 1)[0]
err = tRepos.Locations.Delete(context.Background(), loc.ID)
err := tRepos.Locations.Delete(context.Background(), loc.ID)
assert.NoError(t, err)
_, err = tRepos.Locations.Get(context.Background(), loc.ID)
assert.Error(t, err)
}
func TestItemRepository_TreeQuery(t *testing.T) {
locs := useLocations(t, 3)
// Set relations
_, err := tRepos.Locations.UpdateOneByGroup(context.Background(), tGroup.ID, locs[0].ID, LocationUpdate{
ID: locs[0].ID,
ParentID: locs[1].ID,
Name: locs[0].Name,
Description: locs[0].Description,
})
assert.NoError(t, err)
locations, err := tRepos.Locations.Tree(context.Background(), tGroup.ID, TreeQuery{WithItems: true})
assert.NoError(t, err)
assert.Equal(t, 2, len(locations))
// Check roots
for _, loc := range locations {
if loc.ID == locs[1].ID {
assert.Equal(t, 1, len(loc.Children))
}
}
}
func TestConvertLocationsToTree(t *testing.T) {
uuid1, uuid2, uuid3, uuid4 := uuid.New(), uuid.New(), uuid.New(), uuid.New()
testCases := []struct {
name string
locations []FlatTreeItem
expected []TreeItem
}{
{
name: "Convert locations to tree",
locations: []FlatTreeItem{
{
ID: uuid1,
Name: "Root1",
ParentID: uuid.Nil,
Level: 0,
},
{
ID: uuid2,
Name: "Child1",
ParentID: uuid1,
Level: 1,
},
{
ID: uuid3,
Name: "Child2",
ParentID: uuid1,
Level: 1,
},
},
expected: []TreeItem{
{
ID: uuid1,
Name: "Root1",
Children: []*TreeItem{
{
ID: uuid2,
Name: "Child1",
Children: []*TreeItem{},
},
{
ID: uuid3,
Name: "Child2",
Children: []*TreeItem{},
},
},
},
},
},
{
name: "Convert locations to tree with deeply nested children",
locations: []FlatTreeItem{
{
ID: uuid1,
Name: "Root1",
ParentID: uuid.Nil,
Level: 0,
},
{
ID: uuid2,
Name: "Child1",
ParentID: uuid1,
Level: 1,
},
{
ID: uuid3,
Name: "Child2",
ParentID: uuid2,
Level: 2,
},
{
ID: uuid4,
Name: "Child3",
ParentID: uuid3,
Level: 3,
},
},
expected: []TreeItem{
{
ID: uuid1,
Name: "Root1",
Children: []*TreeItem{
{
ID: uuid2,
Name: "Child1",
Children: []*TreeItem{
{
ID: uuid3,
Name: "Child2",
Children: []*TreeItem{
{
ID: uuid4,
Name: "Child3",
Children: []*TreeItem{},
},
},
},
},
},
},
},
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := ConvertLocationsToTree(tc.locations)
// Compare JSON strings
expected, _ := json.Marshal(tc.expected)
got, _ := json.Marshal(result)
assert.Equal(t, string(expected), string(got))
})
}
}

View File

@ -6,7 +6,7 @@
<div class="dropdown dropdown-top sm:dropdown-end">
<div class="relative">
<input
v-model="isearch"
v-model="internalSearch"
tabindex="0"
class="input w-full items-center flex flex-wrap border border-gray-400 rounded-lg"
@keyup.enter="selectFirst"
@ -26,9 +26,11 @@
class="dropdown-content mb-1 menu shadow border border-gray-400 rounded bg-base-100 w-full z-[9999] max-h-60 overflow-y-scroll"
>
<li v-for="(obj, idx) in filtered" :key="idx">
<button type="button" @click="select(obj)">
{{ usingObjects ? obj[itemText] : obj }}
</button>
<div type="button" @click="select(obj)">
<slot name="display" v-bind="{ item: obj }">
{{ usingObjects ? obj[itemText] : obj }}
</slot>
</div>
</li>
<li class="hidden first:flex">
<button disabled>
@ -49,9 +51,10 @@
interface Props {
label: string;
modelValue: string | ItemsObject;
modelValue: string | ItemsObject | null | undefined;
items: ItemsObject[] | string[];
itemText?: keyof ItemsObject;
itemSearch?: keyof ItemsObject | null;
itemValue?: keyof ItemsObject;
search?: string;
noResultsText?: string;
@ -63,21 +66,34 @@
modelValue: "",
items: () => [],
itemText: "text",
itemValue: "value",
search: "",
itemSearch: null,
itemValue: "value",
noResultsText: "No Results Found",
});
const searchKey = computed(() => props.itemSearch || props.itemText);
function clear() {
select(value.value);
}
const isearch = ref("");
watch(isearch, () => {
internalSearch.value = isearch.value;
});
const internalSearch = ref("");
watch(
() => props.search,
val => {
internalSearch.value = val;
}
);
watch(
() => internalSearch.value,
val => {
emit("update:search", val);
}
);
const internalSearch = useVModel(props, "search", emit);
const value = useVModel(props, "modelValue", emit);
const usingObjects = computed(() => {
@ -102,9 +118,9 @@
() => {
if (value.value) {
if (typeof value.value === "string") {
isearch.value = value.value;
internalSearch.value = value.value;
} else {
isearch.value = value.value[props.itemText] as string;
internalSearch.value = value.value[searchKey.value] as string;
}
}
},
@ -113,7 +129,7 @@
}
);
function select(obj: string | ItemsObject) {
function select(obj: Props["modelValue"]) {
if (isStrings(props.items)) {
if (obj === value.value) {
value.value = "";
@ -131,16 +147,16 @@
}
const filtered = computed(() => {
if (!isearch.value || isearch.value === "") {
if (!internalSearch.value || internalSearch.value === "") {
return props.items;
}
if (isStrings(props.items)) {
return props.items.filter(item => item.toLowerCase().includes(isearch.value.toLowerCase()));
return props.items.filter(item => item.toLowerCase().includes(internalSearch.value.toLowerCase()));
} else {
return props.items.filter(item => {
if (props.itemText && props.itemText in item) {
return (item[props.itemText] as string).toLowerCase().includes(isearch.value.toLowerCase());
if (searchKey.value && searchKey.value in item) {
return (item[searchKey.value] as string).toLowerCase().includes(internalSearch.value.toLowerCase());
}
return false;
});

View File

@ -0,0 +1,65 @@
<script setup lang="ts">
import { ViewType } from "~~/composables/use-preferences";
import { ItemSummary } from "~~/lib/api/types/data-contracts";
type Props = {
view?: ViewType;
items: ItemSummary[];
};
const preferences = useViewPreferences();
const props = defineProps<Props>();
const viewSet = computed(() => {
return !!props.view;
});
const itemView = computed(() => {
return props.view ?? preferences.value.itemDisplayView;
});
function setViewPreference(view: ViewType) {
preferences.value.itemDisplayView = view;
}
</script>
<template>
<section>
<BaseSectionHeader class="mb-5 flex justify-between items-center">
Items
<template #description>
<div v-if="!viewSet" class="dropdown dropdown-hover dropdown-left">
<label tabindex="0" class="btn btn-ghost m-1">
<Icon name="mdi-dots-vertical" class="h-7 w-7" />
</label>
<ul tabindex="0" class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-32">
<li>
<button @click="setViewPreference('card')">
<Icon name="mdi-card-text-outline" class="h-5 w-5" />
Card
</button>
</li>
<li>
<button @click="setViewPreference('table')">
<Icon name="mdi-table" class="h-5 w-5" />
Table
</button>
</li>
</ul>
</div>
</template>
</BaseSectionHeader>
<template v-if="itemView === 'table'">
<ItemViewTable :items="items" />
</template>
<template v-else>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
<ItemCard v-for="item in items" :key="item.id" :item="item" />
</div>
</template>
</section>
</template>
<style scoped></style>

View File

@ -0,0 +1,10 @@
import { ItemSummary } from "~~/lib/api/types/data-contracts";
export type TableHeader = {
text: string;
value: keyof ItemSummary;
sortable?: boolean;
align?: "left" | "center" | "right";
};
export type TableData = Record<string, any>;

View File

@ -0,0 +1,141 @@
<template>
<BaseCard>
<table class="table w-full">
<thead>
<tr class="bg-primary">
<th
v-for="h in headers"
:key="h.value"
class="text-no-transform text-sm bg-neutral text-neutral-content"
:class="{
'text-center': h.align === 'center',
'text-right': h.align === 'right',
'text-left': h.align === 'left',
}"
>
<template v-if="typeof h === 'string'">{{ h }}</template>
<template v-else>{{ h.text }}</template>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(d, i) in data" :key="i" class="hover cursor-pointer" @click="navigateTo(`/item/${d.id}`)">
<td
v-for="h in headers"
:key="`${h.value}-${i}`"
class="bg-base-100"
:class="{
'text-center': h.align === 'center',
'text-right': h.align === 'right',
'text-left': h.align === 'left',
}"
>
<template v-if="cell(h) === 'cell-name'">
<NuxtLink class="hover" :to="`/item/${d.id}`">
{{ d.name }}
</NuxtLink>
</template>
<template v-else-if="cell(h) === 'cell-purchasePrice'">
<Currency :amount="d.purchasePrice" />
</template>
<template v-else-if="cell(h) === 'cell-insured'">
<Icon v-if="d.insured" name="mdi-check" class="text-green-500 h-5 w-5" />
<Icon v-else name="mdi-close" class="text-red-500 h-5 w-5" />
</template>
<slot v-else :name="cell(h)" v-bind="{ item: d }">
{{ extractValue(d, h.value) }}
</slot>
</td>
</tr>
</tbody>
</table>
<div class="border-t p-3 justify-end flex">
<div class="btn-group">
<button :disabled="!hasPrev" class="btn btn-sm" @click="prev()">«</button>
<button class="btn btn-sm">Page {{ pagination.page }}</button>
<button :disabled="!hasNext" class="btn btn-sm" @click="next()">»</button>
</div>
</div>
</BaseCard>
</template>
<script setup lang="ts">
import { TableData, TableHeader } from "./Table.types";
import { ItemSummary } from "~~/lib/api/types/data-contracts";
type Props = {
items: ItemSummary[];
};
const props = defineProps<Props>();
const sortByProperty = ref<keyof ItemSummary>("name");
const headers = computed<TableHeader[]>(() => {
return [
{ text: "Name", value: "name" },
{ text: "Quantity", value: "quantity", align: "center" },
{ text: "Insured", value: "insured", align: "center" },
{ text: "Price", value: "purchasePrice" },
] as TableHeader[];
});
const pagination = reactive({
sortBy: sortByProperty.value,
descending: false,
page: 1,
rowsPerPage: 10,
rowsNumber: 0,
});
const next = () => pagination.page++;
const hasNext = computed<boolean>(() => {
return pagination.page * pagination.rowsPerPage < props.items.length;
});
const prev = () => pagination.page--;
const hasPrev = computed<boolean>(() => {
return pagination.page > 1;
});
const data = computed<TableData[]>(() => {
// sort by property
let data = [...props.items].sort((a, b) => {
const aLower = a[sortByProperty.value]?.toLowerCase();
const bLower = b[sortByProperty.value]?.toLowerCase();
if (aLower < bLower) {
return -1;
}
if (aLower > bLower) {
return 1;
}
return 0;
});
// sort descending
if (pagination.descending) {
data.reverse();
}
// paginate
const start = (pagination.page - 1) * pagination.rowsPerPage;
const end = start + pagination.rowsPerPage;
data = data.slice(start, end);
return data;
});
function extractValue(data: TableData, value: string) {
const parts = value.split(".");
let current = data;
for (const part of parts) {
current = current[part];
}
return current;
}
function cell(h: TableHeader) {
return `cell-${h.value.replace(".", "_")}`;
}
</script>
<style scoped></style>

View File

@ -10,6 +10,7 @@
label="Location Name"
/>
<FormTextArea v-model="form.description" label="Location Description" />
<LocationSelector v-model="form.parent" />
<div class="modal-action">
<BaseButton type="submit" :loading="loading"> Create </BaseButton>
</div>
@ -18,6 +19,7 @@
</template>
<script setup lang="ts">
import { LocationSummary } from "~~/lib/api/types/data-contracts";
const props = defineProps({
modelValue: {
type: Boolean,
@ -31,6 +33,7 @@
const form = reactive({
name: "",
description: "",
parent: null as LocationSummary | null,
});
whenever(
@ -43,6 +46,7 @@
function reset() {
form.name = "";
form.description = "";
form.parent = null;
focused.value = false;
modal.value = false;
loading.value = false;
@ -54,7 +58,11 @@
async function create() {
loading.value = true;
const { data, error } = await api.locations.create(form);
const { data, error } = await api.locations.create({
name: form.name,
description: form.description,
parentId: form.parent ? form.parent.id : null,
});
if (error) {
toast.error("Couldn't create location");

View File

@ -0,0 +1,49 @@
<template>
<FormAutocomplete
v-model="value"
v-model:search="form.search"
:items="locations"
item-text="display"
item-value="id"
item-search="name"
label="Parent Location"
>
<template #display="{ item }">
<div>
<div>
{{ item.name }}
</div>
<div v-if="item.name != item.display" class="text-xs mt-1">{{ item.display }}</div>
</div>
</template>
</FormAutocomplete>
</template>
<script lang="ts" setup>
import { LocationSummary } from "~~/lib/api/types/data-contracts";
type Props = {
modelValue?: LocationSummary | null;
};
const props = defineProps<Props>();
const value = useVModel(props, "modelValue");
const locations = await useFlatLocations();
const form = ref({
parent: null as LocationSummary | null,
search: "",
});
// Whenever parent goes from value to null reset search
watch(
() => value.value,
() => {
if (!value.value) {
form.value.search = "";
}
}
);
</script>

View File

@ -0,0 +1,73 @@
<script setup lang="ts">
import { useTreeState } from "./tree-state";
import { TreeItem } from "~~/lib/api/types/data-contracts";
type Props = {
treeId: string;
item: TreeItem;
};
const props = withDefaults(defineProps<Props>(), {});
const link = computed(() => {
return props.item.type === "location" ? `/location/${props.item.id}` : `/item/${props.item.id}`;
});
const hasChildren = computed(() => {
return props.item.children.length > 0;
});
const state = useTreeState(props.treeId);
const openRef = computed({
get() {
return state.value[nodeHash.value] ?? false;
},
set(value) {
state.value[nodeHash.value] = value;
},
});
const nodeHash = computed(() => {
// converts a UUID to a short hash
return props.item.id.replace(/-/g, "").substring(0, 8);
});
</script>
<template>
<div>
<div
class="node flex items-center gap-1 rounded p-1"
:class="{
'cursor-pointer hover:bg-base-200': hasChildren,
}"
@click="openRef = !openRef"
>
<div
class="p-1/2 rounded mr-1 flex items-center justify-center"
:class="{
'hover:bg-base-200': hasChildren,
}"
>
<div v-if="!hasChildren" class="h-6 w-6"></div>
<label
v-else
class="swap swap-rotate"
:class="{
'swap-active': openRef,
}"
>
<Icon name="mdi-chevron-right" class="h-6 w-6 swap-off" />
<Icon name="mdi-chevron-down" class="h-6 w-6 swap-on" />
</label>
</div>
<Icon v-if="item.type === 'location'" name="mdi-map-marker" class="h-4 w-4" />
<Icon v-else name="mdi-package-variant" class="h-4 w-4" />
<NuxtLink class="hover:link text-lg" :to="link" @click.stop>{{ item.name }} </NuxtLink>
</div>
<div v-if="openRef" class="ml-4">
<LocationTreeNode v-for="child in item.children" :key="child.id" :item="child" :tree-id="treeId" />
</div>
</div>
</template>
<style scoped></style>

View File

@ -0,0 +1,18 @@
<script setup lang="ts">
import { TreeItem } from "~~/lib/api/types/data-contracts";
type Props = {
locs: TreeItem[];
treeId: string;
};
defineProps<Props>();
</script>
<template>
<div class="p-4 border-2 root">
<LocationTreeNode v-for="item in locs" :key="item.id" :item="item" :tree-id="treeId" />
</div>
</template>
<style></style>

View File

@ -0,0 +1,17 @@
import type { Ref } from "vue";
type TreeState = Record<string, boolean>;
const store: Record<string, Ref<TreeState>> = {};
export function newTreeKey(): string {
return Math.random().toString(36).substring(2);
}
export function useTreeState(key: string): Ref<TreeState> {
if (!store[key]) {
store[key] = ref({});
}
return store[key];
}

View File

@ -0,0 +1,44 @@
import { Ref } from "vue";
import { TreeItem } from "~~/lib/api/types/data-contracts";
export interface FlatTreeItem {
id: string;
name: string;
display: string;
}
export function flatTree(tree: TreeItem[]): Ref<FlatTreeItem[]> {
const v = ref<FlatTreeItem[]>([]);
// turns the nested items into a flat items array where
// the display is a string of the tree hierarchy separated by breadcrumbs
function flatten(items: TreeItem[], display: string) {
for (const item of items) {
v.value.push({
id: item.id,
name: item.name,
display: display + item.name,
});
if (item.children) {
flatten(item.children, display + item.name + " > ");
}
}
}
flatten(tree, "");
return v;
}
export async function useFlatLocations(): Promise<Ref<FlatTreeItem[]>> {
const api = useUserApi();
const locations = await api.locations.getTree();
if (!locations) {
return ref([]);
}
return flatTree(locations.data.items);
}

View File

@ -1,10 +1,13 @@
import { Ref } from "vue";
import { DaisyTheme } from "~~/lib/data/themes";
export type ViewType = "table" | "card" | "tree";
export type LocationViewPreferences = {
showDetails: boolean;
showEmpty: boolean;
editorAdvancedView: boolean;
itemDisplayView: ViewType;
theme: DaisyTheme;
};
@ -19,6 +22,7 @@ export function useViewPreferences(): Ref<LocationViewPreferences> {
showDetails: true,
showEmpty: true,
editorAdvancedView: false,
itemDisplayView: "card",
theme: "homebox",
},
{ mergeDefaults: true }

View File

@ -158,12 +158,19 @@
to: "/profile",
},
{
icon: "mdi-document",
icon: "mdi-magnify",
id: 3,
active: computed(() => route.path === "/items"),
name: "Items",
name: "Search",
to: "/items",
},
{
icon: "mdi-map-marker",
id: 4,
active: computed(() => route.path === "/locations"),
name: "Locations",
to: "/locations",
},
{
icon: "mdi-database",
id: 2,
@ -172,14 +179,6 @@
modals.import = true;
},
},
// {
// icon: "mdi-database-export",
// id: 5,
// name: "Export",
// action: () => {
// console.log("Export");
// },
// },
];
const labelStore = useLabelStore();

View File

@ -1,16 +1,24 @@
import { BaseAPI, route } from "../base";
import { LocationOutCount, LocationCreate, LocationOut, LocationUpdate } from "../types/data-contracts";
import { LocationOutCount, LocationCreate, LocationOut, LocationUpdate, TreeItem } from "../types/data-contracts";
import { Results } from "../types/non-generated";
export type LocationsQuery = {
filterChildren: boolean;
};
export type TreeQuery = {
withItems: boolean;
};
export class LocationsApi extends BaseAPI {
getAll(q: LocationsQuery = { filterChildren: false }) {
return this.http.get<Results<LocationOutCount>>({ url: route("/locations", q) });
}
getTree(tq = { withItems: false }) {
return this.http.get<Results<TreeItem>>({ url: route("/locations/tree", tq) });
}
create(body: LocationCreate) {
return this.http.post<LocationCreate, LocationOut>({ url: route("/locations"), body });
}

View File

@ -188,6 +188,7 @@ export interface LabelSummary {
export interface LocationCreate {
description: string;
name: string;
parentId: string | null;
}
export interface LocationOut {
@ -270,6 +271,13 @@ export interface TotalsByOrganizer {
total: number;
}
export interface TreeItem {
children: TreeItem[];
id: string;
name: string;
type: string;
}
export interface UserOut {
email: string;
groupId: string;
@ -347,13 +355,13 @@ export interface EnsureAssetIDResult {
}
export interface GroupInvitation {
expiresAt: string;
expiresAt: Date;
token: string;
uses: number;
}
export interface GroupInvitationCreate {
expiresAt: string;
expiresAt: Date;
uses: number;
}
@ -363,6 +371,6 @@ export interface ItemAttachmentToken {
export interface TokenResponse {
attachmentToken: string;
expiresAt: string;
expiresAt: Date;
token: string;
}

View File

@ -406,9 +406,7 @@
</ul>
</div>
<template #description>
<p class="text-lg">
{{ item ? item.description : "" }}
</p>
<Markdown :source="item.description"> </Markdown>
<div class="flex flex-wrap gap-2 mt-3">
<NuxtLink ref="badge" class="badge p-3" :to="`/location/${item.location.id}`">
<Icon name="heroicons-map-pin" class="mr-2 swap-on"></Icon>

View File

@ -358,13 +358,7 @@
</template>
</BaseSectionHeader>
<div class="px-5 mb-6 grid md:grid-cols-2 gap-4">
<FormSelect
v-if="item"
v-model="item.location"
label="Location"
:items="locations ?? []"
compare-key="id"
/>
<LocationSelector v-model="item.location" />
<FormMultiselect v-model="item.labels" label="Labels" :items="labels ?? []" />
<Autocomplete

View File

@ -114,8 +114,6 @@
entry.date = new Date(e.date);
entry.description = e.description;
entry.cost = e.cost;
console.log(e);
}
async function editEntry() {

View File

@ -9,7 +9,7 @@
});
useHead({
title: "Homebox | Home",
title: "Homebox | Items",
});
const searchLocked = ref(false);

View File

@ -131,7 +131,7 @@
<form v-if="location" @submit.prevent="update">
<FormTextField v-model="updateData.name" :autofocus="true" label="Location Name" />
<FormTextArea v-model="updateData.description" label="Location Description" />
<FormAutocomplete v-model="parent" :items="locations" item-text="name" item-value="id" label="Parent" />
<LocationSelector v-model="parent" />
<div class="modal-action">
<BaseButton type="submit" :loading="updating"> Update </BaseButton>
</div>
@ -179,12 +179,9 @@
<DetailsSection :details="details" />
</BaseCard>
<section v-if="location && location.items.length > 0">
<BaseSectionHeader class="mb-5"> Items </BaseSectionHeader>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
<ItemCard v-for="item in location.items" :key="item.id" :item="item" />
</div>
</section>
<template v-if="location && location.items.length > 0">
<ItemViewSelectable :items="location.items" />
</template>
<section v-if="location && location.children.length > 0">
<BaseSectionHeader class="mb-5"> Child Locations </BaseSectionHeader>

View File

@ -0,0 +1,78 @@
<script setup lang="ts">
import { useTreeState } from "~~/components/Location/Tree/tree-state";
definePageMeta({
middleware: ["auth"],
});
useHead({
title: "Homebox | Items",
});
const api = useUserApi();
const { data: tree } = useAsyncData(async () => {
const { data, error } = await api.locations.getTree({
withItems: true,
});
if (error) {
return [];
}
return data.items;
});
const locationTreeId = "locationTree";
const treeState = useTreeState(locationTreeId);
const route = useRouter();
onMounted(() => {
// set tree state from query params
const query = route.currentRoute.value.query;
if (query && query[locationTreeId]) {
console.debug("setting tree state from query params");
const data = JSON.parse(query[locationTreeId] as string);
for (const key in data) {
treeState.value[key] = data[key];
}
}
});
watch(
treeState,
() => {
// Push the current state to the URL
route.replace({ query: { [locationTreeId]: JSON.stringify(treeState.value) } });
},
{ deep: true }
);
function closeAll() {
for (const key in treeState.value) {
treeState.value[key] = false;
}
}
</script>
<template>
<BaseContainer class="mb-16">
<BaseSectionHeader> Locations </BaseSectionHeader>
<BaseCard>
<div class="p-4">
<div class="flex justify-end mb-2">
<div class="btn-group">
<button class="btn btn-sm tooltip tooltip-top" data-tip="Collapse Tree" @click="closeAll">
<Icon name="mdi-collapse-all-outline" />
</button>
</div>
</div>
<LocationTreeRoot v-if="tree" :locs="tree" :tree-id="locationTreeId" />
</div>
</BaseCard>
</BaseContainer>
</template>

View File

@ -1,7 +1,5 @@
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.hook("page:finish", () => {
console.log(document.body);
document.body.scrollTo({ top: 0 });
console.log("page:finish");
});
});