Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions dashboard/convert/dashboardtag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package convert

import (
"github.com/traggo/server/generated/gqlmodel"
"github.com/traggo/server/model"
)

func tagFiltersToExternal(tags []model.DashboardTagFilter, include bool) []*gqlmodel.TimeSpanTag {
if len(tags) == 0 {
return nil
}

result := []*gqlmodel.TimeSpanTag{}
for _, tag := range tags {
if tag.Include == include {
result = append(result, &gqlmodel.TimeSpanTag{
Key: tag.Key,
Value: tag.StringValue,
})
}
}
return result
}

func TagFiltersToInternal(gqls []*gqlmodel.InputTimeSpanTag, include bool) []model.DashboardTagFilter {
result := make([]model.DashboardTagFilter, 0)
for _, tag := range gqls {
result = append(result, tagFilterToInternal(*tag, include))
}
return result
}

func tagFilterToInternal(gqls gqlmodel.InputTimeSpanTag, include bool) model.DashboardTagFilter {
return model.DashboardTagFilter{
Key: gqls.Key,
StringValue: gqls.Value,
Include: include,
}
}
8 changes: 5 additions & 3 deletions dashboard/convert/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@ func ToExternalEntry(entry model.DashboardEntry) (*gqlmodel.DashboardEntry, erro
To: entry.RangeTo,
}
stats := &gqlmodel.StatsSelection{
Interval: ExternalInterval(entry.Interval),
Tags: strings.Split(entry.Keys, ","),
Range: dateRange,
Interval: ExternalInterval(entry.Interval),
Tags: strings.Split(entry.Keys, ","),
Range: dateRange,
ExcludeTags: tagFiltersToExternal(entry.TagFilters, false),
IncludeTags: tagFiltersToExternal(entry.TagFilters, true),
}
if entry.RangeID != model.NoRangeIDDefined {
stats.RangeID = &entry.RangeID
Expand Down
8 changes: 8 additions & 0 deletions dashboard/entry/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ func (r *ResolverForEntry) AddDashboardEntry(ctx context.Context, dashboardID in
return nil, err
}

tagFilters := convert.TagFiltersToInternal(stats.ExcludeTags, false)
tagFilters = append(tagFilters, convert.TagFiltersToInternal(stats.IncludeTags, true)...)

if err := tagsDuplicates(tagFilters); err != nil {
return nil, err
}

entry := model.DashboardEntry{
Keys: strings.Join(stats.Tags, ","),
Type: convert.InternalEntryType(entryType),
Expand All @@ -34,6 +41,7 @@ func (r *ResolverForEntry) AddDashboardEntry(ctx context.Context, dashboardID in
MobilePosition: convert.EmptyPos(),
DesktopPosition: convert.EmptyPos(),
RangeID: -1,
TagFilters: tagFilters,
}

if len(stats.Tags) == 0 {
Expand Down
33 changes: 33 additions & 0 deletions dashboard/entry/tagcheck.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package entry

import (
"fmt"

"github.com/traggo/server/model"
)

func tagsDuplicates(tags []model.DashboardTagFilter) error {
existingTags := make(map[model.DashboardTagFilter]struct{})

for _, tag := range tags {
if _, ok := existingTags[tag]; ok {
tagType := "exclude"
if tag.Include {
tagType = "include"
}

return fmt.Errorf("%s tags: tag '%s' is present multiple times", tagType, tag.Key+":"+tag.StringValue)
} else {
copyTag := tag
copyTag.Include = !copyTag.Include

if _, ok := existingTags[copyTag]; ok {
return fmt.Errorf("tag '%s' is present in both exclude tags and include tags", tag.Key+":"+tag.StringValue)
}
}

existingTags[tag] = struct{}{}
}

return nil
}
37 changes: 35 additions & 2 deletions dashboard/entry/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,22 @@ func (r *ResolverForEntry) UpdateDashboardEntry(ctx context.Context, id int, ent
entry.Total = *total
}

tx := r.DB.Begin()
if err := tx.Error; err != nil {
return nil, err
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
panic(r)
} else if tx != nil {
tx.Rollback()
}
}()

if stats != nil {
if stats.RangeID != nil {
if _, err := util.FindDashboardRange(r.DB, *stats.RangeID); err != nil {
if _, err := util.FindDashboardRange(tx, *stats.RangeID); err != nil {
return nil, err
}
entry.RangeID = *stats.RangeID
Expand All @@ -53,6 +66,19 @@ func (r *ResolverForEntry) UpdateDashboardEntry(ctx context.Context, id int, ent
entry.RangeFrom = stats.Range.From
entry.RangeTo = stats.Range.To
}

tagFilters := convert.TagFiltersToInternal(stats.ExcludeTags, false)
tagFilters = append(tagFilters, convert.TagFiltersToInternal(stats.IncludeTags, true)...)

if err := tagsDuplicates(tagFilters); err != nil {
return nil, err
}

if err := tx.Where("dashboard_entry_id = ?", id).Delete(new(model.DashboardTagFilter)).Error; err != nil {
return nil, fmt.Errorf("failed to update tag filters: %s", err)
}

entry.TagFilters = tagFilters
entry.Keys = strings.Join(stats.Tags, ",")
entry.Interval = convert.InternalInterval(stats.Interval)
}
Expand All @@ -65,7 +91,14 @@ func (r *ResolverForEntry) UpdateDashboardEntry(ctx context.Context, id int, ent
return &gqlmodel.DashboardEntry{}, err
}

r.DB.Save(entry)
if err := tx.Save(entry).Error; err != nil {
return nil, err
}

if err := tx.Commit().Error; err != nil {
return nil, err
}

tx = nil
return convert.ToExternalEntry(entry)
}
8 changes: 7 additions & 1 deletion dashboard/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@ func (r *ResolverForDashboard) Dashboards(ctx context.Context) ([]*gqlmodel.Dash
userID := auth.GetUser(ctx).ID

dashboards := []model.Dashboard{}
find := r.DB.Preload("Entries").Preload("Ranges").Where(&model.Dashboard{UserID: userID}).Find(&dashboards)

q := r.DB
q = q.Preload("Entries")
q = q.Preload("Entries.TagFilters")
q = q.Preload("Ranges")

find := q.Where(&model.Dashboard{UserID: userID}).Find(&dashboards)

if find.Error != nil {
return nil, find.Error
Expand Down
1 change: 1 addition & 0 deletions model/all.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ func All() []interface{} {
new(UserSetting),
new(Dashboard),
new(DashboardEntry),
new(DashboardTagFilter),
new(DashboardRange),
}
}
9 changes: 9 additions & 0 deletions model/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,20 @@ type DashboardEntry struct {
RangeID int
RangeFrom string
RangeTo string
TagFilters []DashboardTagFilter

MobilePosition string
DesktopPosition string
}

// DashboardTagFilter a tag for filtering timespans
type DashboardTagFilter struct {
DashboardEntryID int `gorm:"type:int REFERENCES dashboard_entries(id) ON DELETE CASCADE"`
Key string
StringValue string
Include bool
}

// DashboardType the dashboard type
type DashboardType string

Expand Down
11 changes: 10 additions & 1 deletion ui/src/dashboard/Entry/AddPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import * as gqlDashboard from '../../gql/dashboard';
import {Fade} from '../../common/Fade';
import {DashboardEntryForm, isValidDashboardEntry} from './DashboardEntryForm';
import {AddDashboardEntry, AddDashboardEntryVariables} from '../../gql/__generated__/AddDashboardEntry';
import {handleError} from '../../utils/errors';
import {useSnackbar} from 'notistack';

interface EditPopupProps {
dashboardId: number;
Expand Down Expand Up @@ -38,6 +40,9 @@ export const AddPopup: React.FC<EditPopupProps> = ({
refetchQueries: [{query: gqlDashboard.Dashboards}],
});
const valid = isValidDashboardEntry(entry);

const {enqueueSnackbar} = useSnackbar();

return (
<Popper
key="popup"
Expand Down Expand Up @@ -89,6 +94,8 @@ export const AddPopup: React.FC<EditPopupProps> = ({
}
: null,
rangeId: entry.statsSelection.rangeId,
excludeTags: entry.statsSelection.excludeTags,
includeTags: entry.statsSelection.includeTags,
},
pos: {
desktop: {
Expand All @@ -99,7 +106,9 @@ export const AddPopup: React.FC<EditPopupProps> = ({
},
},
},
}).then(finish);
})
.then(finish)
.catch(handleError('Add Dashboard Entry', enqueueSnackbar));
}}>
Add
</Button>
Expand Down
2 changes: 2 additions & 0 deletions ui/src/dashboard/Entry/DashboardEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ const SpecificDashboardEntry: React.FC<{entry: Dashboards_dashboards_items; rang
range,
interval,
tags: entry.statsSelection.tags,
excludeTags: entry.statsSelection.excludeTags,
includeTags: entry.statsSelection.includeTags,
},
},
});
Expand Down
43 changes: 43 additions & 0 deletions ui/src/dashboard/Entry/DashboardEntryForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/NativeSelect/NativeSelect';
import {EntryType, StatsInterval} from '../../gql/__generated__/globalTypes';
import {TagKeySelector} from '../../tag/TagKeySelector';
import {TagFilterSelector} from '../../tag/TagFilterSelector';
import {Dashboards_dashboards_items, Dashboards_dashboards_items_statsSelection_range} from '../../gql/__generated__/Dashboards';
import {RelativeDateTimeSelector} from '../../common/RelativeDateTimeSelector';
import {parseRelativeTime} from '../../utils/time';
Expand All @@ -31,6 +32,24 @@ export const isValidDashboardEntry = (item: Dashboards_dashboards_items): boolea
export const DashboardEntryForm: React.FC<EditPopupProps> = ({entry, onChange: setEntry, disabled = false, ranges}) => {
const [staticRange, setStaticRange] = React.useState(!entry.statsSelection.rangeId);

const excludeTags = (entry.statsSelection.excludeTags || []).map((tag) => ({
tag: {
key: tag.key,
color: '',
__typename: 'TagDefinition' as 'TagDefinition',
},
value: tag.value,
}));

const includeTags = (entry.statsSelection.includeTags || []).map((tag) => ({
tag: {
key: tag.key,
color: '',
__typename: 'TagDefinition' as 'TagDefinition',
},
value: tag.value,
}));

const range: Dashboards_dashboards_items_statsSelection_range = entry.statsSelection.range
? entry.statsSelection.range
: {
Expand Down Expand Up @@ -189,6 +208,30 @@ export const DashboardEntryForm: React.FC<EditPopupProps> = ({entry, onChange: s
setEntry(entry);
}}
/>
<TagFilterSelector
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason not to use the existing selector which is used for the timespans (ui/src/tag/TagSelector)?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanted for it to look more like TagKeySelector, to be more precise, the chips there don't have color and there is an X at the end.
Also I tweaked suggestions a bit (reversed them) so that they will suit the selection more, instead of creation.
Now, that I think about it more, I shouldn't reverse them, but just remove the first entry (user input) and maybe put it at the end.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be okay if i changed useSuggest a little?

diff --git a/ui/src/tag/suggest.ts b/ui/src/tag/suggest.ts
index 31a6f82..450b220 100644
--- a/ui/src/tag/suggest.ts
+++ b/ui/src/tag/suggest.ts
@@ -9,7 +9,8 @@ export const useSuggest = (
     tagResult: QueryResult<Tags, {}>,
     inputValue: string,
     usedTags: string[],
-    skipValue = false
+    skipValue = false,
+    showTagValue = true
 ): TagSelectorEntry[] => {
     const [tagKeySomeCase, tagValue] = inputValue.split(':');
     const tagKey = tagKeySomeCase.toLowerCase();
@@ -22,7 +23,7 @@ export const useSuggest = (
     });
 
     if (exactMatch && tagValue !== undefined && usedTags.indexOf(exactMatch.key) === -1 && !skipValue) {
-        return suggestTagValue(exactMatch, tagValue, valueResult);
+        return suggestTagValue(exactMatch, tagValue, valueResult, showTagValue);
     } else {
         return suggestTag(exactMatch, tagResult, tagKey, usedTags);
     }
@@ -59,11 +60,12 @@ const suggestTag = (
 const suggestTagValue = (
     exactMatch: TagSelectorEntry['tag'],
     tagValue: string,
-    valueResult: QueryResult<SuggestTagValue, SuggestTagValueVariables>
+    valueResult: QueryResult<SuggestTagValue, SuggestTagValueVariables>,
+    showTagValue: boolean
 ): TagSelectorEntry[] => {
     let someValues = (valueResult.data && valueResult.data.values) || [];
 
-    if (someValues.indexOf(tagValue) === -1) {
+    if (showTagValue && someValues.indexOf(tagValue) === -1) {
         someValues = [tagValue, ...someValues];
     }

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, maybe call it can get a name that's describes what it does. E.g. includeInputValueOnNoMatch

Copy link
Member

@jmattheis jmattheis Jun 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather use the existing picker as it has better UX.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I'd say changing the style of the existing selector is much easier than reimplementing it. E.g. this makes it look pretty much the same as the other inputs in the form.

const StyledTagSelector = ({label, ...props}: TagSelectorProps & {label: string}) => {
    return (
        <Box mt={1}>
            <FormControl fullWidth>
                <Box pt={2}>
                    <InputLabel shrink> {label} </InputLabel>
                    <Box className="MuiInput-underline">
                        <TagSelector {...props} />
                    </Box>
                </Box>
            </FormControl>
        </Box>
    );
};

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that using the old selector is easier but i was talking more about the styling and spacing of tag chips.
image

Also i think it is more tailored towards creating and assigning tags to timespans.
It's a bit strange when an include tags selection field offers you to create a tag:
image
Or prevents you from adding two identical tag names:
image

I understand that more props could be added to TagSelector to change this behavior, but this would add more complexity to the component. I think it would be better to keep it within its current scope.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think there are many changes needed in the TagSelector, probably <10 lines of code. I'll insist on this change, but I can do it myself. It'll probably take some time, as I'm busy right now.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was busy at that time too, but now i can work on this. I can do the changes to the TagsSelect, but first i need to know, what changes do you want.
From my side, i think, this should be changed:

  1. Add a flag to disable tag creation
  2. Adjust the margins on TagsSelect or TagKeySelect so they have the same gap size
  3. Maybe add a flag to add an X at the end?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Yeah 2. yeah, it should be consistent. 3. no, improving the existing TagSelector can be done in a separate PR.

type="Exclude"
value={excludeTags}
onChange={(tags) => {
entry.statsSelection.excludeTags = tags.map((tag) => ({
key: tag.tag.key,
value: tag.value,
__typename: 'TimeSpanTag',
}));
setEntry(entry);
}}
/>
<TagFilterSelector
type="Include"
value={includeTags}
onChange={(tags) => {
entry.statsSelection.includeTags = tags.map((tag) => ({
key: tag.tag.key,
value: tag.value,
__typename: 'TimeSpanTag',
}));
setEntry(entry);
}}
/>
</>
);
};
Expand Down
11 changes: 10 additions & 1 deletion ui/src/dashboard/Entry/EditPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import * as gqlDashboard from '../../gql/dashboard';
import {UpdateDashboardEntry, UpdateDashboardEntryVariables} from '../../gql/__generated__/UpdateDashboardEntry';
import {Fade} from '../../common/Fade';
import {DashboardEntryForm, isValidDashboardEntry} from './DashboardEntryForm';
import {handleError} from '../../utils/errors';
import {useSnackbar} from 'notistack';

interface EditPopupProps {
entry: Dashboards_dashboards_items;
Expand All @@ -24,6 +26,9 @@ export const EditPopup: React.FC<EditPopupProps> = ({entry, anchorEl, onChange:
refetchQueries: [{query: gqlDashboard.Dashboards}],
});
const valid = isValidDashboardEntry(entry);

const {enqueueSnackbar} = useSnackbar();

return (
<Popper
key="popup"
Expand Down Expand Up @@ -75,9 +80,13 @@ export const EditPopup: React.FC<EditPopupProps> = ({entry, anchorEl, onChange:
}
: null,
rangeId: entry.statsSelection.rangeId,
excludeTags: entry.statsSelection.excludeTags,
includeTags: entry.statsSelection.includeTags,
},
},
}).then(() => setEdit(null));
})
.then(() => setEdit(null))
.catch(handleError('Edit Dashboard Entry', enqueueSnackbar));
}}>
Save
</Button>
Expand Down
Loading