mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-28 19:20:41 +00:00
Compare commits
31 Commits
perf/uplot
...
feat/syste
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb9e1b9a93 | ||
|
|
3c4eda82eb | ||
|
|
3ac1479cc3 | ||
|
|
fb55fbd303 | ||
|
|
24bd5efe7c | ||
|
|
79894a0f96 | ||
|
|
1d8655c606 | ||
|
|
a34b75f86d | ||
|
|
7339662720 | ||
|
|
d1dd086cec | ||
|
|
909c378c9b | ||
|
|
1c7a93bd7a | ||
|
|
dabd6bf45e | ||
|
|
3fd05f57ba | ||
|
|
79f7d35033 | ||
|
|
5c9379e4ad | ||
|
|
11bda9f282 | ||
|
|
726f89a893 | ||
|
|
3851339e6c | ||
|
|
a4dde27546 | ||
|
|
0402254209 | ||
|
|
4225452554 | ||
|
|
50dfec7247 | ||
|
|
ce1117eaa0 | ||
|
|
2eb46f19fb | ||
|
|
e37e94af53 | ||
|
|
f060e262d2 | ||
|
|
27a11ada95 | ||
|
|
a4d83ea2fd | ||
|
|
2e4d47a124 | ||
|
|
5a62bcd85c |
@@ -10,6 +10,5 @@
|
||||
- **Use convensional commit format** for commits and PR title.
|
||||
- **Do not amend the commits once pushed.** Always create a new commit once changes are pushed to remote.
|
||||
- **Review fixes are new commits too.** A force push hides what changed from human reviewers and makes Greptile post its findings again. Bring in `main` with a merge; only a stacked branch (`gh stack`) rebases, since the stack moves as a unit.
|
||||
- **A review fix to an AI-owned file fixes its generator too.** A file with the AI-owned banner (story mocks and plays, `tests/e2e/drivers/`) is rewritten by the skill or agent that made it, so a fix made only in the file comes back on the next run. In the same PR, add the lesson to that skill or agent as a concrete case.
|
||||
- **Answer every Greptile thread.** Reply with the commit that fixes it (`Fixed in 4df6f3198d: <what changed>`) or the reason it stays, then resolve. Never resolve one with neither: Greptile withdraws a finding, and remembers it, only when told why.
|
||||
- **Leave human review threads to the author.** Fix the code they ask for, but never reply to or resolve a human reviewer's thread.
|
||||
|
||||
@@ -110,9 +110,8 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
|
||||
|
||||
CI runs each play once, with its story's own args. Anyone can flip a control in the panel, and nothing runs the play against that value, so a play that breaks on it goes unnoticed. Write each play so it cannot.
|
||||
|
||||
Before writing the clicks, list what has to be on screen for the play's target to exist. Then walk every control the story exposes, the page's own as well as the shared ones, and return early for each value that takes something on that list away. These are the cases plays have missed:
|
||||
Before writing the clicks, list what has to be on screen for the play's target to exist, and return early when the args take it away. These are the cases plays have missed:
|
||||
|
||||
- An arg the story sets. The story sets it because the play needs what that value renders, and the panel can flip it. On the `mine` view the dashboards Created-by filter opens with a tag to remove; on the other views it opens empty and there is no × to click. Check the tag is there by parsing the route the view resolves to.
|
||||
- The controls every story has. `State` on loading or error renders no rows and no filter suggestions. `Access`, `Permissions` and `Revoked` remove rows, row actions and gated buttons, and the `editor` and `viewer` presets grant telemetry reads only, so a page gated on its own resource shows them nothing. `Check state` on loading disables every gated control, and on error an `AuthZButton` stays enabled while an `AuthZGuardContent` set to fail closed hides what it wraps. `License` and `Banner` decide the plan, so a cloud-only form is gone on the others. `Hold tooltips open` shows a label a second time, inside its tooltip.
|
||||
- A count at 0. The page can swap its whole list for an empty state, and the header, filters and column picker go with it.
|
||||
- A view, filter or invalid query that leaves no rows, even when the count is above 0.
|
||||
|
||||
12
.github/workflows/goci.yaml
vendored
12
.github/workflows/goci.yaml
vendored
@@ -63,7 +63,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: check-semconv-generated-files
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: qemu-install
|
||||
@@ -114,7 +114,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-openapi
|
||||
@@ -131,7 +131,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-authz
|
||||
@@ -148,7 +148,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-web-settings
|
||||
@@ -165,7 +165,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-transaction-groups
|
||||
|
||||
@@ -131,10 +131,6 @@ func runGenerateAuthz(_ context.Context) error {
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceNotificationChannel).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceUser).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorPassword).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionKey).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionLimit).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceMetaResourceAuthDomain).String(): true,
|
||||
coretypes.NewResourceRef(coretypes.ResourceOrganization).String(): true,
|
||||
}
|
||||
|
||||
allowedTypes := map[string]bool{}
|
||||
|
||||
@@ -318,11 +318,6 @@
|
||||
"name": "redux",
|
||||
"message": "[State mgmt] redux is deprecated. Migrate to Zustand, nuqs, or react-query."
|
||||
},
|
||||
{
|
||||
"name": "@signozhq/design-tokens",
|
||||
"importNames": ["Style"],
|
||||
"message": "[bundle] Style is a large object of CSS variable strings and is not tree-shaken. Write the CSS variable directly, for example 'var(--l3-foreground)'."
|
||||
},
|
||||
{
|
||||
"name": "react-redux",
|
||||
"message": "[State mgmt] react-redux is deprecated. Migrate to Zustand, nuqs, or react-query."
|
||||
@@ -345,11 +340,6 @@
|
||||
"importNames": ["patchDashboardV2", "usePatchDashboardV2"],
|
||||
"message": "[dashboard-v2] Don't call patchDashboardV2/usePatchDashboardV2 directly — use useOptimisticPatch().patchAsync so spec edits update the react-query cache optimistically and reconcile on settle."
|
||||
},
|
||||
{
|
||||
"name": "antd/lib",
|
||||
"allowTypeImports": true,
|
||||
"message": "[bundle] antd/lib is the CommonJS root and bundles every antd component. Import from 'antd' instead."
|
||||
},
|
||||
{
|
||||
"name": "motion/react-client",
|
||||
"message": "[motion] motion/react-client is for React Server Components only. Use 'motion/react' instead — it provides the same exports and works correctly in client-side SPAs."
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
content="frame-src 'self' blob: data:"
|
||||
/>
|
||||
|
||||
<link rel="stylesheet" href="css/uPlot.min.css" />
|
||||
|
||||
<script>
|
||||
// i18n's language detector would pick the browser locale (e.g. `en-US`), which
|
||||
// /public/locales does not ship; pin it to the bundled language instead.
|
||||
|
||||
@@ -22,7 +22,6 @@ import i18n from '../src/ReactI18';
|
||||
// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does
|
||||
// not report because the requests look like static assets.
|
||||
import '../src/lib/monaco/loader';
|
||||
import '../src/lib/uPlotStylesheet';
|
||||
|
||||
import '../src/styles.scss';
|
||||
|
||||
@@ -198,9 +197,7 @@ const preview: Preview = {
|
||||
['Overview', 'Authz'],
|
||||
'Service Accounts',
|
||||
'Ingestion',
|
||||
['Overview', 'Authz'],
|
||||
'Single Sign-on',
|
||||
['Overview', 'Authz'],
|
||||
'Keyboard Shortcuts',
|
||||
],
|
||||
'Auth',
|
||||
|
||||
@@ -157,6 +157,7 @@
|
||||
})(document, 'script');
|
||||
}
|
||||
</script>
|
||||
<link rel="stylesheet" href="css/uPlot.min.css" />
|
||||
<script type="module" src="./src/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
1
frontend/public/css/uPlot.min.css
vendored
Normal file
1
frontend/public/css/uPlot.min.css
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}
|
||||
@@ -175,8 +175,8 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
pathname === ROUTES.SETTINGS ||
|
||||
pathname === ROUTES.BILLING ||
|
||||
pathname === ROUTES.MEMBERS_SETTINGS ||
|
||||
pathname === ROUTES.ORG_SETTINGS ||
|
||||
(isAdmin && pathname === ROUTES.MY_SETTINGS);
|
||||
(isAdmin &&
|
||||
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
|
||||
|
||||
if (
|
||||
pathname !== ROUTES.WORKSPACE_LOCKED &&
|
||||
|
||||
@@ -808,7 +808,7 @@ describe('PrivateRoute', () => {
|
||||
assertStaysOnRoute(ROUTES.BILLING);
|
||||
});
|
||||
|
||||
it('should allow VIEWER to access org-settings when workspace is blocked', () => {
|
||||
it('should redirect VIEWER to workspace locked when trying to access org-settings', async () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.ORG_SETTINGS,
|
||||
appContext: {
|
||||
@@ -821,7 +821,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
|
||||
});
|
||||
|
||||
it('should allow VIEWER to access members settings when workspace is blocked', () => {
|
||||
@@ -1707,7 +1707,6 @@ describe('PrivateRoute', () => {
|
||||
// Everything under /settings resolves to the non-exact SETTINGS route
|
||||
SETTINGS: { path: ROUTES.SETTINGS, deniedRoles: DENIED_ROLES },
|
||||
MY_SETTINGS: { path: ROUTES.MY_SETTINGS, deniedRoles: DENIED_ROLES },
|
||||
ORG_SETTINGS: { path: ROUTES.ORG_SETTINGS, deniedRoles: DENIED_ROLES },
|
||||
ROLES_SETTINGS: { path: ROUTES.ROLES_SETTINGS, deniedRoles: DENIED_ROLES },
|
||||
ROLE_CREATE: { path: ROUTES.ROLE_CREATE, deniedRoles: DENIED_ROLES },
|
||||
ROLE_DETAILS: {
|
||||
|
||||
@@ -14,14 +14,14 @@ export type CreatedByProps =
|
||||
creatorOptions: CreatorOption[];
|
||||
createdBy: string[];
|
||||
onCreatedByChange: (emails: string[]) => void;
|
||||
// Run a Created-by change made with the dropdown closed.
|
||||
onCreatedByCommit: (emails: string[]) => void;
|
||||
// Clear all Created-by selections and run immediately.
|
||||
onClearCreatedBy: () => void;
|
||||
}
|
||||
| {
|
||||
creatorOptions?: undefined;
|
||||
createdBy?: undefined;
|
||||
onCreatedByChange?: undefined;
|
||||
onCreatedByCommit?: undefined;
|
||||
onClearCreatedBy?: undefined;
|
||||
};
|
||||
|
||||
type Props = CreatedByProps & {
|
||||
@@ -61,8 +61,8 @@ function FilterChips(props: Props): JSX.Element {
|
||||
placeholder="Created by"
|
||||
testId={`${testIdPrefix}-filter-created-by`}
|
||||
disabled={disabled}
|
||||
onClear={props.onClearCreatedBy}
|
||||
onChange={props.onCreatedByChange}
|
||||
onCommit={props.onCreatedByCommit}
|
||||
onDropdownVisibleChange={runOnClose}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -81,7 +81,7 @@ function FilterZone({
|
||||
applyDraft,
|
||||
handleCreatedByChange,
|
||||
handleUpdatedChange,
|
||||
handleCreatedByCommit,
|
||||
handleClearCreatedBy,
|
||||
handleClear,
|
||||
} = useFilterZoneDraft({
|
||||
query,
|
||||
@@ -96,7 +96,7 @@ function FilterZone({
|
||||
creatorOptions,
|
||||
createdBy: reflected.createdBy,
|
||||
onCreatedByChange: handleCreatedByChange,
|
||||
onCreatedByCommit: handleCreatedByCommit,
|
||||
onClearCreatedBy: handleClearCreatedBy,
|
||||
}
|
||||
: {};
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { ConfigProvider, Select } from 'antd';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
import cx from 'classnames';
|
||||
@@ -21,9 +20,7 @@ interface Props {
|
||||
placeholder: string;
|
||||
testId: string;
|
||||
onChange: (values: string[]) => void;
|
||||
// A change made with the dropdown closed (a tag's ×, the clear icon) has no
|
||||
// close to run on, so it is committed here instead of staged via onChange.
|
||||
onCommit: (values: string[]) => void;
|
||||
onClear?: () => void;
|
||||
onDropdownVisibleChange?: (open: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
@@ -34,31 +31,10 @@ function MultiSelectFilter({
|
||||
placeholder,
|
||||
testId,
|
||||
onChange,
|
||||
onCommit,
|
||||
onClear,
|
||||
onDropdownVisibleChange,
|
||||
disabled = false,
|
||||
}: Props): JSX.Element {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(next: string[]): void => {
|
||||
if (!isOpen) {
|
||||
onCommit(next);
|
||||
return;
|
||||
}
|
||||
onChange(next);
|
||||
},
|
||||
[isOpen, onChange, onCommit],
|
||||
);
|
||||
|
||||
const handleDropdownVisibleChange = useCallback(
|
||||
(nextOpen: boolean): void => {
|
||||
setIsOpen(nextOpen);
|
||||
onDropdownVisibleChange?.(nextOpen);
|
||||
},
|
||||
[onDropdownVisibleChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<ConfigProvider theme={CHECKBOX_SELECT_THEME}>
|
||||
<Select
|
||||
@@ -75,6 +51,7 @@ function MultiSelectFilter({
|
||||
menuItemSelectedIcon={null}
|
||||
data-testid={testId}
|
||||
disabled={disabled}
|
||||
onClear={onClear}
|
||||
optionRender={(option): JSX.Element => (
|
||||
<div
|
||||
className={styles.checkOption}
|
||||
@@ -89,8 +66,8 @@ function MultiSelectFilter({
|
||||
<span className={styles.checkOptionLabel}>{option.label}</span>
|
||||
</div>
|
||||
)}
|
||||
onChange={(next): void => handleChange(next as string[])}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
onChange={(next): void => onChange(next as string[])}
|
||||
onDropdownVisibleChange={onDropdownVisibleChange}
|
||||
/>
|
||||
</ConfigProvider>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import type { DslGrammar } from '../../dsl/types';
|
||||
import FilterZone from '../FilterZone';
|
||||
@@ -48,33 +47,4 @@ describe('FilterZone', () => {
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('things-filter-updated')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('runs the query when a creator is removed with the dropdown closed', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onQueryChange = jest.fn();
|
||||
render(
|
||||
<FilterZone
|
||||
query="created_by = 'ada@example.com'"
|
||||
grammar={grammar}
|
||||
testIdPrefix="things"
|
||||
creatorOptions={[{ email: 'ada@example.com', label: 'Ada' }]}
|
||||
source={source}
|
||||
onQueryChange={onQueryChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
// antd renders the tag's × aria-hidden.
|
||||
await user.click(
|
||||
within(screen.getByTitle('Ada')).getByRole('img', {
|
||||
name: 'close',
|
||||
hidden: true,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
within(screen.getByTestId('things-filter-created-by')).getByRole('combobox'),
|
||||
).toHaveAttribute('aria-expanded', 'false');
|
||||
|
||||
expect(onQueryChange).toHaveBeenCalledWith('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -106,20 +106,12 @@ describe('useFilterZoneDraft', () => {
|
||||
"created_by = 'a@x.io' AND name = 'x'",
|
||||
);
|
||||
|
||||
act(() => result.current.handleCreatedByCommit([]));
|
||||
act(() => result.current.handleClearCreatedBy());
|
||||
|
||||
expect(result.current.draft).toBe("name = 'x'");
|
||||
expect(onQueryChange).toHaveBeenCalledWith("name = 'x'");
|
||||
});
|
||||
|
||||
it('runs the remaining creators when one is removed', () => {
|
||||
const { result, onQueryChange } = setup("created_by IN ['a@x.io', 'b@x.io']");
|
||||
|
||||
act(() => result.current.handleCreatedByCommit(['b@x.io']));
|
||||
|
||||
expect(onQueryChange).toHaveBeenCalledWith("created_by = 'b@x.io'");
|
||||
});
|
||||
|
||||
it('empties the draft and runs the empty query on clear', () => {
|
||||
const { result, onQueryChange, onCleared, onClearAll } = setup();
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ interface FilterZoneDraft {
|
||||
applyDraft: (next: string) => void;
|
||||
handleCreatedByChange: (emails: string[]) => void;
|
||||
handleUpdatedChange: (window: UpdatedWindow) => void;
|
||||
handleCreatedByCommit: (emails: string[]) => void;
|
||||
handleClearCreatedBy: () => void;
|
||||
handleClear: () => void;
|
||||
}
|
||||
|
||||
@@ -97,14 +97,10 @@ export function useFilterZoneDraft({
|
||||
[draft, applyDraft, onFilterApplied],
|
||||
);
|
||||
|
||||
// Runs a Created-by change made with its dropdown closed.
|
||||
const handleCreatedByCommit = useCallback(
|
||||
(emails: string[]): void => {
|
||||
onFilterApplied?.('createdBy', { valueCount: emails.length });
|
||||
applyDraft(spliceClause(draft, 'created_by', createdByClause(emails)));
|
||||
},
|
||||
[draft, applyDraft, onFilterApplied],
|
||||
);
|
||||
// Clear-all on the Created-by select removes its clause and runs immediately.
|
||||
const handleClearCreatedBy = useCallback((): void => {
|
||||
applyDraft(spliceClause(draft, 'created_by', null));
|
||||
}, [draft, applyDraft]);
|
||||
|
||||
// Clear resets the draft and runs immediately (empty query).
|
||||
const handleClear = useCallback((): void => {
|
||||
@@ -126,7 +122,7 @@ export function useFilterZoneDraft({
|
||||
applyDraft,
|
||||
handleCreatedByChange,
|
||||
handleUpdatedChange,
|
||||
handleCreatedByCommit,
|
||||
handleClearCreatedBy,
|
||||
handleClear,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ interface Props {
|
||||
confirmLabel: string;
|
||||
/** Name the input holds each time the dialog opens. */
|
||||
initialName?: string;
|
||||
placeholder: string;
|
||||
testIdPrefix: string;
|
||||
}
|
||||
|
||||
@@ -36,7 +35,6 @@ function ViewNameDialog({
|
||||
description,
|
||||
confirmLabel,
|
||||
initialName = '',
|
||||
placeholder,
|
||||
testIdPrefix,
|
||||
}: Props): JSX.Element {
|
||||
const [name, setName] = useState(initialName);
|
||||
@@ -118,7 +116,7 @@ function ViewNameDialog({
|
||||
id={inputId}
|
||||
value={name}
|
||||
maxLength={VIEW_NAME_MAX_LENGTH}
|
||||
placeholder={placeholder}
|
||||
placeholder="e.g. Prod alerts"
|
||||
autoComplete="off"
|
||||
testId={`${testIdPrefix}-name`}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>): void =>
|
||||
|
||||
@@ -39,7 +39,6 @@ interface Props {
|
||||
saveTestIdPrefix?: string;
|
||||
renameTestIdPrefix?: string;
|
||||
customSectionLabel?: string;
|
||||
viewNamePlaceholder?: string;
|
||||
deleteDescription?: string;
|
||||
/** Wraps the rail body, e.g. in an authz guard. */
|
||||
guard?: (content: ReactElement) => ReactElement;
|
||||
@@ -68,7 +67,6 @@ function ViewsRail({
|
||||
saveTestIdPrefix = 'save-view',
|
||||
renameTestIdPrefix = 'rename-view',
|
||||
customSectionLabel = 'My views',
|
||||
viewNamePlaceholder = 'e.g. Production',
|
||||
deleteDescription = 'This removes the saved view.',
|
||||
guard,
|
||||
onViewSaved,
|
||||
@@ -289,7 +287,6 @@ function ViewsRail({
|
||||
title="Save as view"
|
||||
description="Save the current filters as a view you can return to."
|
||||
confirmLabel="Save view"
|
||||
placeholder={viewNamePlaceholder}
|
||||
testIdPrefix={saveTestIdPrefix}
|
||||
/>
|
||||
<ViewNameDialog
|
||||
@@ -300,7 +297,6 @@ function ViewsRail({
|
||||
description="The view keeps its filters under the new name."
|
||||
confirmLabel="Rename"
|
||||
initialName={renameTarget?.label}
|
||||
placeholder={viewNamePlaceholder}
|
||||
testIdPrefix={renameTestIdPrefix}
|
||||
/>
|
||||
{contextHolder}
|
||||
|
||||
@@ -163,22 +163,6 @@ describe('ViewsRail', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the list placeholder in the save and rename dialogs', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderRail({ viewNamePlaceholder: 'e.g. Prod things' });
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-save-trigger`));
|
||||
await expect(
|
||||
screen.findByTestId('save-view-name-field'),
|
||||
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
|
||||
await user.click(screen.getByTestId('save-view-cancel'));
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));
|
||||
await expect(
|
||||
screen.findByTestId('rename-view-name-field'),
|
||||
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
|
||||
});
|
||||
|
||||
it('opens the save dialog empty again after a cancel', async () => {
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail({ isModified: true });
|
||||
|
||||
@@ -105,8 +105,6 @@ const stopEventsExtension = EditorView.domEventHandlers({
|
||||
},
|
||||
});
|
||||
|
||||
const EDITOR_BASIC_SETUP = { lineNumbers: false };
|
||||
|
||||
interface QuerySearchProps {
|
||||
placeholder?: string;
|
||||
onChange: (value: string) => void;
|
||||
@@ -715,17 +713,14 @@ function QuerySearch({
|
||||
}
|
||||
}, []);
|
||||
|
||||
const onChangeRef = useRef(onChange);
|
||||
onChangeRef.current = onChange;
|
||||
|
||||
const handleChange = useCallback((value: string): void => {
|
||||
const handleChange = (value: string): void => {
|
||||
if (isProgrammaticChangeRef.current) {
|
||||
isProgrammaticChangeRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
onChangeRef.current(value);
|
||||
}, []);
|
||||
onChange(value);
|
||||
};
|
||||
|
||||
const handleBlur = (): void => {
|
||||
const currentExpression = getCurrentExpression();
|
||||
@@ -1479,65 +1474,6 @@ function QuerySearch({
|
||||
};
|
||||
}
|
||||
|
||||
const completionSourceRef = useRef(combinedSuggestions);
|
||||
completionSourceRef.current = combinedSuggestions;
|
||||
const handleRunRef = useRef(handleRun);
|
||||
handleRunRef.current = handleRun;
|
||||
|
||||
// Built once: new extensions reconfigure CodeMirror, which closes the open suggestions.
|
||||
const editorExtensions = useMemo(
|
||||
() => [
|
||||
autocompletion({
|
||||
override: [
|
||||
(context: CompletionContext): CompletionResult | null =>
|
||||
completionSourceRef.current(context),
|
||||
],
|
||||
defaultKeymap: true,
|
||||
closeOnBlur: true,
|
||||
activateOnTyping: true,
|
||||
maxRenderedOptions: 50,
|
||||
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
|
||||
}),
|
||||
javascript({ jsx: false, typescript: false }),
|
||||
EditorView.lineWrapping,
|
||||
stopEventsExtension,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
...completionKeymap,
|
||||
{
|
||||
key: 'Escape',
|
||||
run: closeCompletion,
|
||||
},
|
||||
{
|
||||
key: 'Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Enter to add new line
|
||||
// and instead run a custom action
|
||||
run: (): boolean => true,
|
||||
},
|
||||
{
|
||||
key: 'Mod-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Mod-Enter to add new line
|
||||
// and instead run a custom action
|
||||
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
|
||||
run: (): boolean => {
|
||||
handleRunRef.current();
|
||||
return true;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Shift-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Shift-Enter to add new line
|
||||
run: (): boolean => true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
// Effect to handle focus state and trigger suggestions
|
||||
useEffect(() => {
|
||||
const clearTimeout = toggleSuggestions(10);
|
||||
@@ -1714,9 +1650,56 @@ function QuerySearch({
|
||||
hasErrors: validation.errors.length > 0,
|
||||
hasInitialExpression: isScopedFilter && !showScopeChip,
|
||||
})}
|
||||
extensions={editorExtensions}
|
||||
extensions={[
|
||||
autocompletion({
|
||||
override: [combinedSuggestions],
|
||||
defaultKeymap: true,
|
||||
closeOnBlur: true,
|
||||
activateOnTyping: true,
|
||||
maxRenderedOptions: 50,
|
||||
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
|
||||
}),
|
||||
javascript({ jsx: false, typescript: false }),
|
||||
EditorView.lineWrapping,
|
||||
stopEventsExtension,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
...completionKeymap,
|
||||
{
|
||||
key: 'Escape',
|
||||
run: closeCompletion,
|
||||
},
|
||||
{
|
||||
key: 'Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Enter to add new line
|
||||
// and instead run a custom action
|
||||
run: (): boolean => true,
|
||||
},
|
||||
{
|
||||
key: 'Mod-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Mod-Enter to add new line
|
||||
// and instead run a custom action
|
||||
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
|
||||
run: (): boolean => {
|
||||
handleRun();
|
||||
return true;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Shift-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Shift-Enter to add new line
|
||||
run: (): boolean => true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
]}
|
||||
placeholder={placeholder}
|
||||
basicSetup={EDITOR_BASIC_SETUP}
|
||||
basicSetup={{
|
||||
lineNumbers: false,
|
||||
}}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
}}
|
||||
|
||||
@@ -192,8 +192,6 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
release();
|
||||
// Outlasts the 10 ms timer QuerySearch uses to reopen suggestions.
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
|
||||
// Outlasts the 100 ms CodeMirror waits before it queries suggestions again.
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
|
||||
expect(screen.getByText('payment-service')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { ChevronDown, ChevronRight, Undo2 } from '@signozhq/icons';
|
||||
|
||||
@@ -20,6 +22,31 @@ export function CheckboxFilterV2Header({
|
||||
onToggleOpen,
|
||||
onClear,
|
||||
}: CheckboxFilterHeaderProps): JSX.Element {
|
||||
const [isTitleTruncated, setIsTitleTruncated] = useState(false);
|
||||
|
||||
const measureTitle = (el: HTMLElement | null): void => {
|
||||
if (el) {
|
||||
setIsTitleTruncated(el.scrollWidth > el.clientWidth);
|
||||
}
|
||||
};
|
||||
|
||||
const titleText = (
|
||||
<Typography
|
||||
ref={measureTitle}
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
display="inline-block"
|
||||
minWidth={0}
|
||||
textOverflow="ellipsis"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
);
|
||||
|
||||
return (
|
||||
<section
|
||||
role="button"
|
||||
@@ -40,19 +67,7 @@ export function CheckboxFilterV2Header({
|
||||
) : (
|
||||
<ChevronRight size={13} cursor="pointer" />
|
||||
)}
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
display="inline-block"
|
||||
minWidth={0}
|
||||
textOverflow="ellipsis"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
<Tooltip title={isTitleTruncated ? title : undefined}>{titleText}</Tooltip>
|
||||
</section>
|
||||
{isOpen && canReset && (
|
||||
<section className={styles.rightAction}>
|
||||
|
||||
@@ -120,4 +120,43 @@ describe('CheckboxFilterV2Header', () => {
|
||||
expect(onToggleOpen).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('title tooltip', () => {
|
||||
// jsdom has no layout, so truncation is simulated at the prototype level
|
||||
// before mount (the component measures in a layout effect).
|
||||
function mockTitleWidths(scrollWidth: number, clientWidth: number): void {
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'scrollWidth', 'get')
|
||||
.mockReturnValue(scrollWidth);
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'clientWidth', 'get')
|
||||
.mockReturnValue(clientWidth);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('shows the full name on hover when the title is truncated', async () => {
|
||||
mockTitleWidths(200, 100);
|
||||
const user = userEvent.setup();
|
||||
render(<CheckboxFilterV2Header {...defaultProps} />);
|
||||
|
||||
await user.hover(screen.getByText(defaultProps.title));
|
||||
|
||||
await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
|
||||
defaultProps.title,
|
||||
);
|
||||
});
|
||||
|
||||
it('shows no tooltip when the title fits', async () => {
|
||||
mockTitleWidths(100, 100);
|
||||
const user = userEvent.setup();
|
||||
render(<CheckboxFilterV2Header {...defaultProps} />);
|
||||
|
||||
await user.hover(screen.getByText(defaultProps.title));
|
||||
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -114,19 +114,6 @@ export const loadingFiltersHandlers = [
|
||||
),
|
||||
];
|
||||
|
||||
export const longTitleConfig = [
|
||||
{
|
||||
attributeKey: {
|
||||
dataType: DataTypes.Int64,
|
||||
key: 'http.request.content_length_uncompressed',
|
||||
type: 'tag',
|
||||
},
|
||||
defaultOpen: false,
|
||||
title: 'Http Request Content Length Uncompressed',
|
||||
type: FiltersType.CHECKBOX,
|
||||
},
|
||||
];
|
||||
|
||||
export const LONG_FILTER_VALUES = [
|
||||
'checkout-service.production-eu-central-1.svc.cluster.local',
|
||||
'payments-authorisation-worker.production-us-east-2.svc.cluster.local',
|
||||
|
||||
@@ -8,7 +8,6 @@ import type { GlobalMockArgs } from '@/storybook/globals';
|
||||
import QuickFilters from '../QuickFilters';
|
||||
import {
|
||||
dirtySettings,
|
||||
hoverTruncatedTitle,
|
||||
openQueryPicker,
|
||||
openSettings,
|
||||
} from './__story_mockdata__/quickFilters.play';
|
||||
@@ -19,7 +18,6 @@ import {
|
||||
handlers,
|
||||
LONG_FILTER_VALUES,
|
||||
loadingFiltersHandlers,
|
||||
longTitleConfig,
|
||||
MANY_FILTER_VALUES,
|
||||
queryBuilder,
|
||||
selectedServiceQueryBuilder,
|
||||
@@ -161,15 +159,6 @@ export const Tooltips: GlobalArgsStory = {
|
||||
},
|
||||
};
|
||||
|
||||
/** A section title too long for the rail: hovering it shows the full title once. */
|
||||
export const TruncatedTitle: GlobalArgsStory = {
|
||||
args: { config: longTitleConfig },
|
||||
parameters: {
|
||||
msw: { handlers: [noSavedFiltersHandler, ...handlers] },
|
||||
},
|
||||
play: hoverTruncatedTitle,
|
||||
};
|
||||
|
||||
const [firstQuery] = queryBuilder.currentQuery.builder.queryData;
|
||||
|
||||
/** Interaction: the query picker lists every query the filters can follow. */
|
||||
|
||||
@@ -8,12 +8,9 @@ import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissio
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { grantsAll } from '@/storybook/access/access';
|
||||
import { hoverTruncatableText } from '@/storybook/play/truncatedText';
|
||||
import type { GlobalMockArgs } from '@/storybook/globals';
|
||||
|
||||
import type QuickFilters from '../../QuickFilters';
|
||||
import { longTitleConfig } from '../QuickFilters.stories.mocks';
|
||||
import { FiltersType } from '../../types';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
@@ -64,26 +61,6 @@ export const dirtySettings = async (context: PlayContext): Promise<void> => {
|
||||
await screen.findByRole('button', { name: 'Save changes' });
|
||||
};
|
||||
|
||||
export const hoverTruncatedTitle = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
const [filter] = args.config ?? [];
|
||||
// Duration and slider sections render no title of their own.
|
||||
if (filter?.type !== FiltersType.CHECKBOX || !filter.title) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [label] = await within(canvasElement).findAllByText(
|
||||
filter.title,
|
||||
{},
|
||||
UNTIL_LOADED,
|
||||
);
|
||||
await hoverTruncatableText(label, filter.title, {
|
||||
cut: filter.title === longTitleConfig[0].title || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
export const openQueryPicker = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
|
||||
@@ -14,6 +14,7 @@ import uPlot from 'uplot';
|
||||
|
||||
import tooltipPlugin from './tooltipPlugin';
|
||||
|
||||
import 'uplot/dist/uPlot.min.css';
|
||||
import './AnomalyAlertEvaluationView.styles.scss';
|
||||
|
||||
const { Search } = Input;
|
||||
|
||||
@@ -32,10 +32,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.ingestion-keys-search-auth-trigger {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.ant-table-row {
|
||||
.ant-table-cell {
|
||||
padding: 0;
|
||||
|
||||
@@ -26,13 +26,13 @@ import type { NotificationInstance } from 'antd/es/notification/interface';
|
||||
import type { CollapseProps } from 'antd/lib';
|
||||
import {
|
||||
useCreateIngestionKey,
|
||||
useCreateIngestionLimit,
|
||||
useCreateIngestionKeyLimit,
|
||||
useDeleteIngestionKey,
|
||||
useDeleteIngestionLimit,
|
||||
useDeleteIngestionKeyLimit,
|
||||
useGetIngestionKeys,
|
||||
useSearchIngestionKeys,
|
||||
useUpdateIngestionKey,
|
||||
useUpdateIngestionLimit,
|
||||
useUpdateIngestionKeyLimit,
|
||||
} from 'api/generated/services/gateway';
|
||||
import {
|
||||
GatewaytypesIngestionKeyDTO,
|
||||
@@ -71,21 +71,6 @@ import {
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from '@signozhq/icons';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import {
|
||||
buildIngestionKeyAttachPermission,
|
||||
buildIngestionKeyDeletePermission,
|
||||
buildIngestionKeyDetachPermission,
|
||||
buildIngestionKeyUpdatePermission,
|
||||
buildIngestionLimitDeletePermission,
|
||||
buildIngestionLimitUpdatePermission,
|
||||
IngestionKeyCreatePermission,
|
||||
IngestionKeyListPermission,
|
||||
IngestionLimitCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/ingestion.permissions';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import {
|
||||
@@ -225,13 +210,6 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
|
||||
const [totalIngestionKeys, setTotalIngestionKeys] = useState(0);
|
||||
|
||||
const { permissions: authzPermissions } = useAuthZ([
|
||||
IngestionKeyListPermission,
|
||||
]);
|
||||
|
||||
const canListIngestionKeys =
|
||||
authzPermissions?.[IngestionKeyListPermission].isGranted ?? false;
|
||||
|
||||
const [
|
||||
hasCreateLimitForIngestionKeyError,
|
||||
setHasCreateLimitForIngestionKeyError,
|
||||
@@ -336,7 +314,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
},
|
||||
{
|
||||
query: {
|
||||
enabled: !isSearching && canListIngestionKeys,
|
||||
enabled: !isSearching,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -356,7 +334,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
},
|
||||
{
|
||||
query: {
|
||||
enabled: isSearching && canListIngestionKeys,
|
||||
enabled: isSearching,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -367,14 +345,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
: ingestionKeysData;
|
||||
const isLoading = isSearching ? isLoadingSearch : isLoadingGet;
|
||||
const isRefetching = isSearching ? isRefetchingSearch : isRefetchingGet;
|
||||
const refetchKeysQuery = isSearching
|
||||
? refetchSearchAPIKeys
|
||||
: refetchGetAPIKeys;
|
||||
const refetchAPIKeys = async (): Promise<void> => {
|
||||
if (canListIngestionKeys) {
|
||||
await refetchKeysQuery();
|
||||
}
|
||||
};
|
||||
const refetchAPIKeys = isSearching ? refetchSearchAPIKeys : refetchGetAPIKeys;
|
||||
const error = isSearching ? searchError : getError;
|
||||
const isError = isSearching ? isSearchError : isGetError;
|
||||
|
||||
@@ -422,15 +393,15 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
useDeleteIngestionKey<AxiosError<RenderErrorResponseDTO>>();
|
||||
|
||||
const { mutate: createLimitForIngestionKey, isLoading: isLoadingLimitForKey } =
|
||||
useCreateIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
useCreateIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
|
||||
const {
|
||||
mutate: updateLimitForIngestionKey,
|
||||
isLoading: isLoadingUpdatedLimitForKey,
|
||||
} = useUpdateIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
} = useUpdateIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
|
||||
const { mutate: deleteLimitForKey, isLoading: isDeletingLimit } =
|
||||
useDeleteIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
useDeleteIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
|
||||
|
||||
const onDeleteHandler = (): void => {
|
||||
clearSearch();
|
||||
@@ -667,8 +638,8 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
|
||||
createLimitForIngestionKey(
|
||||
{
|
||||
pathParams: { keyId: payload.keyID },
|
||||
data: {
|
||||
keyId: payload.keyID,
|
||||
signal: payload.signal,
|
||||
config: payload.config,
|
||||
},
|
||||
@@ -1056,14 +1027,12 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
icon
|
||||
color="secondary"
|
||||
aria-label="Edit ingestion key"
|
||||
testId={`ingestion-key-edit-btn-${APIKey.id}`}
|
||||
onClick={onEditKey}
|
||||
>
|
||||
<PenLine size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
aria-label="Delete ingestion key"
|
||||
testId={`ingestion-key-delete-open-btn-${APIKey.id}`}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon
|
||||
@@ -1191,19 +1160,8 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
});
|
||||
};
|
||||
|
||||
const isAddingNewLimit = !hasLimits(signalName);
|
||||
|
||||
const ingestionLimitPermissions = APIKey?.id
|
||||
? isAddingNewLimit
|
||||
? [
|
||||
IngestionLimitCreatePermission,
|
||||
buildIngestionKeyAttachPermission(APIKey.id),
|
||||
]
|
||||
: [buildIngestionLimitUpdatePermission(limit.id)]
|
||||
: [];
|
||||
|
||||
const onSaveSignalLimit = (): void => {
|
||||
if (isAddingNewLimit) {
|
||||
if (!hasLimits(signalName)) {
|
||||
handleAddLimit(APIKey, signalName);
|
||||
} else {
|
||||
handleUpdateLimit(APIKey, limitsDict[signalName]);
|
||||
@@ -1242,7 +1200,6 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
icon
|
||||
color="danger"
|
||||
aria-label={`Delete ${signalName} limit`}
|
||||
testId={`ingestion-limit-delete-open-btn-${signalName}`}
|
||||
disabled={
|
||||
!!(activeAPIKey?.id === APIKey?.id && activeSignal)
|
||||
}
|
||||
@@ -1260,7 +1217,6 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
prefix={<Plus size={12} />}
|
||||
disabled={!!(activeAPIKey?.id === APIKey?.id && activeSignal)}
|
||||
onClick={onAddSignalLimit}
|
||||
testId={`ingestion-limit-add-btn-${signalName}`}
|
||||
>
|
||||
Limits
|
||||
</Button>
|
||||
@@ -1492,7 +1448,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
isEditAddLimitOpen && (
|
||||
<div className="signal-limit-save-discard">
|
||||
<div className="signal-limit-save-discard-actions">
|
||||
<AuthZButton
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
size="sm"
|
||||
@@ -1500,11 +1456,9 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
isLoadingLimitForKey || isLoadingUpdatedLimitForKey
|
||||
}
|
||||
onClick={onSaveSignalLimit}
|
||||
testId="ingestion-limit-save-btn"
|
||||
checks={ingestionLimitPermissions}
|
||||
>
|
||||
Save
|
||||
</AuthZButton>
|
||||
</Button>
|
||||
<Button
|
||||
disabledTooltip="Wait for the limit to save"
|
||||
variant="outlined"
|
||||
@@ -1827,50 +1781,42 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
)}
|
||||
|
||||
<div className="ingestion-keys-search-add-new">
|
||||
<AuthZTooltip
|
||||
triggerClassName="ingestion-keys-search-auth-trigger"
|
||||
checks={[IngestionKeyListPermission]}
|
||||
>
|
||||
<Input
|
||||
placeholder="Search for ingestion key..."
|
||||
prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
|
||||
value={searchValue}
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
</AuthZTooltip>
|
||||
<Input
|
||||
placeholder="Search for ingestion key..."
|
||||
prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
|
||||
value={searchValue}
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
|
||||
<div className="ingestion-keys-add-new">
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
color="primary"
|
||||
variant="solid"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={showAddModal}
|
||||
testId="ingestion-key-add-btn"
|
||||
checks={[IngestionKeyCreatePermission]}
|
||||
>
|
||||
New Ingestion key
|
||||
</AuthZButton>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AuthZGuardContent checks={[IngestionKeyListPermission]}>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={dataSource}
|
||||
loading={isLoading || isRefetching}
|
||||
showHeader={false}
|
||||
onChange={handleTableChange}
|
||||
pagination={{
|
||||
pageSize: isSearching ? SEARCH_PAGE_SIZE : paginationParams?.per_page,
|
||||
hideOnSinglePage: true,
|
||||
showTotal: (total: number, range: number[]): string =>
|
||||
`${range[0]}-${range[1]} of ${total} Ingestion keys`,
|
||||
total: totalIngestionKeys,
|
||||
}}
|
||||
className="ingestion-keys-table"
|
||||
/>
|
||||
</AuthZGuardContent>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={dataSource}
|
||||
loading={isLoading || isRefetching}
|
||||
showHeader={false}
|
||||
onChange={handleTableChange}
|
||||
pagination={{
|
||||
pageSize: isSearching ? SEARCH_PAGE_SIZE : paginationParams?.per_page,
|
||||
hideOnSinglePage: true,
|
||||
showTotal: (total: number, range: number[]): string =>
|
||||
`${range[0]}-${range[1]} of ${total} Ingestion keys`,
|
||||
total: totalIngestionKeys,
|
||||
}}
|
||||
className="ingestion-keys-table"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Delete Key Modal */}
|
||||
@@ -1893,7 +1839,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</Button>,
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
key="submit"
|
||||
variant="solid"
|
||||
@@ -1901,15 +1847,9 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
prefix={<Trash2 size={16} />}
|
||||
loading={isDeleteingAPIKey}
|
||||
onClick={onDeleteHandler}
|
||||
testId="ingestion-key-delete-btn"
|
||||
checks={
|
||||
isDeleteModalOpen && activeAPIKey?.id
|
||||
? [buildIngestionKeyDeletePermission(activeAPIKey.id)]
|
||||
: []
|
||||
}
|
||||
>
|
||||
Delete Ingestion Key
|
||||
</AuthZButton>,
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Typography
|
||||
@@ -1946,7 +1886,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</Button>,
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
key="submit"
|
||||
variant="solid"
|
||||
@@ -1954,18 +1894,9 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
prefix={<Trash2 size={16} />}
|
||||
loading={isDeletingLimit}
|
||||
onClick={onDeleteLimitHandler}
|
||||
testId="ingestion-limit-delete-btn"
|
||||
checks={
|
||||
isDeleteLimitModalOpen && activeSignal?.id && activeAPIKey?.id
|
||||
? [
|
||||
buildIngestionLimitDeletePermission(activeSignal.id),
|
||||
buildIngestionKeyDetachPermission(activeAPIKey.id),
|
||||
]
|
||||
: []
|
||||
}
|
||||
>
|
||||
Delete Limit
|
||||
</AuthZButton>,
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Typography
|
||||
@@ -2005,7 +1936,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</Button>,
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
color="primary"
|
||||
key="submit"
|
||||
@@ -2013,15 +1944,9 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
prefix={<Check size={14} />}
|
||||
loading={isLoadingUpdateAPIKey}
|
||||
onClick={onUpdateApiKey}
|
||||
testId="ingestion-key-update-btn"
|
||||
checks={
|
||||
isEditModalOpen && activeAPIKey?.id
|
||||
? [buildIngestionKeyUpdatePermission(activeAPIKey.id)]
|
||||
: []
|
||||
}
|
||||
>
|
||||
Update Ingestion Key
|
||||
</AuthZButton>,
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Form
|
||||
|
||||
@@ -1,376 +0,0 @@
|
||||
import dayjs from 'dayjs';
|
||||
import type {
|
||||
AuthtypesTransactionDTO,
|
||||
GatewaytypesIngestionKeyDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
buildIngestionKeyAttachPermission,
|
||||
buildIngestionKeyDeletePermission,
|
||||
buildIngestionKeyDetachPermission,
|
||||
buildIngestionKeyUpdatePermission,
|
||||
buildIngestionLimitDeletePermission,
|
||||
buildIngestionLimitUpdatePermission,
|
||||
IngestionKeyCreatePermission,
|
||||
IngestionKeyListPermission,
|
||||
IngestionLimitCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/ingestion.permissions';
|
||||
import { gettableTransactionToPermission } from 'lib/authz/hooks/useAuthZ/utils';
|
||||
import {
|
||||
AUTHZ_CHECK_URL,
|
||||
setupAuthzAdmin,
|
||||
setupAuthzDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import MultiIngestionSettings from '../MultiIngestionSettings';
|
||||
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
const ROUTE = '/ingestion-settings';
|
||||
const DATE = '2024-01-01T00:00:00Z';
|
||||
const EXPIRES_AT = '2030-01-01T00:00:00Z';
|
||||
|
||||
const DENIED_TEXT = /is not authorized to perform/i;
|
||||
|
||||
const makeKey = (
|
||||
id: string,
|
||||
name: string,
|
||||
limits: GatewaytypesIngestionKeyDTO['limits'] = [],
|
||||
): GatewaytypesIngestionKeyDTO => ({
|
||||
id,
|
||||
name,
|
||||
value: 'secret',
|
||||
workspace_id: 'w1',
|
||||
expires_at: EXPIRES_AT,
|
||||
created_at: DATE,
|
||||
updated_at: DATE,
|
||||
tags: [],
|
||||
limits,
|
||||
});
|
||||
|
||||
const KEY_ONE = makeKey('k1', 'Key One', [
|
||||
{ id: 'l1', signal: 'logs', config: { day: { size: 1073741824 } } },
|
||||
]);
|
||||
const KEY_TWO = makeKey('k2', 'Key Two');
|
||||
const KEY_THREE = makeKey('k3', 'Key Three');
|
||||
|
||||
function mockKeys(keys: GatewaytypesIngestionKeyDTO[]): jest.Mock {
|
||||
const onList = jest.fn();
|
||||
server.use(
|
||||
rest.get('*/api/v1/global/config*', (_req, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
external_url: '',
|
||||
ingestion_url: 'http://ingest.example.com',
|
||||
ai_assistant_url: null,
|
||||
mcp_url: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
rest.get('*/api/v2/gateway/ingestion_keys*', (_req, res, ctx) => {
|
||||
onList();
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
keys,
|
||||
_pagination: {
|
||||
page: 1,
|
||||
per_page: 10,
|
||||
pages: 1,
|
||||
total: keys.length,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return onList;
|
||||
}
|
||||
|
||||
function recordAuthzChecks(): Set<string> {
|
||||
const seen = new Set<string>();
|
||||
server.use(
|
||||
rest.post(AUTHZ_CHECK_URL, async (req) => {
|
||||
const payload = (await req.json()) as AuthtypesTransactionDTO[];
|
||||
payload.forEach((txn) => seen.add(gettableTransactionToPermission(txn)));
|
||||
return undefined;
|
||||
}),
|
||||
);
|
||||
return seen;
|
||||
}
|
||||
|
||||
async function expandKey(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
name: string,
|
||||
): Promise<void> {
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: new RegExp(`right ${name}`, 'i') }),
|
||||
);
|
||||
await screen.findByText('LIMITS');
|
||||
}
|
||||
|
||||
async function settledButton(testId: string): Promise<HTMLElement> {
|
||||
const button = await screen.findByTestId(testId);
|
||||
await waitFor(() => {
|
||||
expect(button).not.toHaveAttribute('aria-busy');
|
||||
});
|
||||
return button;
|
||||
}
|
||||
|
||||
function renderPage(): ReturnType<typeof userEvent.setup> {
|
||||
render(<MultiIngestionSettings />, undefined, { initialRoute: ROUTE });
|
||||
return userEvent.setup({ pointerEventsCheck: 0 });
|
||||
}
|
||||
|
||||
describe('MultiIngestionSettings authz', () => {
|
||||
afterEach(async () => {
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 100);
|
||||
});
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('ingestion-key:list', () => {
|
||||
it('hides the list, disables search and fires no list request when denied', async () => {
|
||||
const onList = mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(IngestionKeyListPermission));
|
||||
|
||||
renderPage();
|
||||
|
||||
await screen.findByText(DENIED_TEXT);
|
||||
expect(
|
||||
screen.getByPlaceholderText('Search for ingestion key...'),
|
||||
).toBeDisabled();
|
||||
expect(screen.queryByText('Key One')).not.toBeInTheDocument();
|
||||
expect(onList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows the list and requests it when granted', async () => {
|
||||
const onList = mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzAdmin());
|
||||
|
||||
renderPage();
|
||||
|
||||
await screen.findByText('Key One');
|
||||
expect(onList).toHaveBeenCalled();
|
||||
expect(screen.queryByText(DENIED_TEXT)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ingestion-key:create', () => {
|
||||
it('disables "New Ingestion key" when denied', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(IngestionKeyCreatePermission));
|
||||
|
||||
renderPage();
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-key-add-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('enables "New Ingestion key" and opens the modal when granted', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzAdmin());
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-key-add-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(screen.getByTestId('ingestion-key-add-btn'));
|
||||
|
||||
await screen.findByTestId('create-new-key');
|
||||
});
|
||||
});
|
||||
|
||||
describe('creating a key without list access', () => {
|
||||
it('sends no list request after the key is created', async () => {
|
||||
const onList = mockKeys([KEY_ONE]);
|
||||
const onCreate = jest.fn();
|
||||
server.use(
|
||||
setupAuthzDeny(IngestionKeyListPermission),
|
||||
rest.post('*/api/v2/gateway/ingestion_keys', (_req, res, ctx) => {
|
||||
onCreate();
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success', data: { id: 'k9', value: 'v' } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-key-add-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(screen.getByTestId('ingestion-key-add-btn'));
|
||||
await user.type(await screen.findByLabelText('Name'), 'new-key');
|
||||
await user.click(screen.getByLabelText('Expiration'));
|
||||
await user.click(
|
||||
await screen.findByTitle(dayjs().add(1, 'day').format('YYYY-MM-DD')),
|
||||
);
|
||||
await user.click(screen.getByTestId('create-new-key'));
|
||||
|
||||
await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1));
|
||||
await screen.findByText(DENIED_TEXT);
|
||||
expect(onList).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ingestion-key:update', () => {
|
||||
it('disables "Update Ingestion Key" for the denied key', async () => {
|
||||
mockKeys([KEY_ONE, KEY_TWO]);
|
||||
server.use(setupAuthzDeny(buildIngestionKeyUpdatePermission('k1')));
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await user.click(await screen.findByTestId('ingestion-key-edit-btn-k1'));
|
||||
await expect(
|
||||
settledButton('ingestion-key-update-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('keeps "Update Ingestion Key" enabled for another key', async () => {
|
||||
mockKeys([KEY_ONE, KEY_TWO]);
|
||||
server.use(setupAuthzDeny(buildIngestionKeyUpdatePermission('k1')));
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await user.click(await screen.findByTestId('ingestion-key-edit-btn-k2'));
|
||||
await expect(
|
||||
settledButton('ingestion-key-update-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ingestion-key:delete', () => {
|
||||
it('disables "Delete Ingestion Key" when denied for that key', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(buildIngestionKeyDeletePermission('k1')));
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await user.click(
|
||||
await screen.findByTestId('ingestion-key-delete-open-btn-k1'),
|
||||
);
|
||||
await expect(
|
||||
settledButton('ingestion-key-delete-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saving a new limit', () => {
|
||||
it('disables "Save" when attach is denied on the key', async () => {
|
||||
mockKeys([KEY_TWO]);
|
||||
server.use(setupAuthzDeny(buildIngestionKeyAttachPermission('k2')));
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key Two');
|
||||
await user.click(screen.getByTestId('ingestion-limit-add-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-save-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('disables "Save" when ingestion-limit:create is denied', async () => {
|
||||
mockKeys([KEY_TWO]);
|
||||
server.use(setupAuthzDeny(IngestionLimitCreatePermission));
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key Two');
|
||||
await user.click(screen.getByTestId('ingestion-limit-add-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-save-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saving an existing limit', () => {
|
||||
it('disables "Save" when update is denied on that limit', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(buildIngestionLimitUpdatePermission('l1')));
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key One');
|
||||
await user.click(screen.getByTestId('edit-limit-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-save-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('keeps "Save" enabled when only create and attach are denied', async () => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(
|
||||
setupAuthzDeny(
|
||||
IngestionLimitCreatePermission,
|
||||
buildIngestionKeyAttachPermission('k1'),
|
||||
),
|
||||
);
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key One');
|
||||
await user.click(screen.getByTestId('edit-limit-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-save-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleting a limit', () => {
|
||||
it.each([
|
||||
['ingestion-limit:delete', buildIngestionLimitDeletePermission('l1')],
|
||||
['ingestion-key:detach', buildIngestionKeyDetachPermission('k1')],
|
||||
])('disables "Delete Limit" when %s is denied', async (_name, denied) => {
|
||||
mockKeys([KEY_ONE]);
|
||||
server.use(setupAuthzDeny(denied));
|
||||
|
||||
const user = renderPage();
|
||||
await expandKey(user, 'Key One');
|
||||
await user.click(screen.getByTestId('ingestion-limit-delete-open-btn-logs'));
|
||||
|
||||
await expect(
|
||||
settledButton('ingestion-limit-delete-btn'),
|
||||
).resolves.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('id checks', () => {
|
||||
it('only checks list and create on load, and per-id checks once a modal opens', async () => {
|
||||
mockKeys([KEY_ONE, KEY_TWO, KEY_THREE]);
|
||||
server.use(setupAuthzAdmin());
|
||||
const seen = recordAuthzChecks();
|
||||
|
||||
const user = renderPage();
|
||||
|
||||
await screen.findByText('Key Three');
|
||||
await expect(
|
||||
settledButton('ingestion-key-add-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
expect([...seen].sort()).toStrictEqual(
|
||||
[IngestionKeyListPermission, IngestionKeyCreatePermission].sort(),
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('ingestion-key-edit-btn-k1'));
|
||||
await expect(
|
||||
settledButton('ingestion-key-update-btn'),
|
||||
).resolves.not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
expect(seen.has(buildIngestionKeyUpdatePermission('k1'))).toBe(true);
|
||||
expect(seen.has(buildIngestionKeyUpdatePermission('k2'))).toBe(false);
|
||||
expect(seen.has(buildIngestionKeyUpdatePermission('k3'))).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { GatewaytypesGettableIngestionKeysDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
@@ -40,7 +39,6 @@ const GLOBAL_CONFIG_RESPONSE = {
|
||||
describe('MultiIngestionSettings Page', () => {
|
||||
beforeEach(() => {
|
||||
mockNavigate.mockClear();
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -352,7 +350,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
initialRoute: INGESTION_SETTINGS_ROUTE,
|
||||
});
|
||||
|
||||
await screen.findByText('Key Regular', undefined, { timeout: 5000 });
|
||||
await screen.findByText('Key Regular');
|
||||
expect(getHandler).toHaveBeenCalled();
|
||||
expect(searchHandler).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ import { Dispatch, SetStateAction, useEffect, useMemo, useState } from 'react';
|
||||
import { useAppNavigate } from 'lib/router/useAppNavigate';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Select, SelectProps, Skeleton } from 'antd';
|
||||
import { Select, Skeleton } from 'antd';
|
||||
import { SelectProps } from 'antd/lib';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { useListAccounts } from 'api/generated/services/cloudintegration';
|
||||
import cx from 'classnames';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Modal } from 'antd';
|
||||
import { Modal } from 'antd/lib';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { useDisconnectAccount } from 'api/generated/services/cloudintegration';
|
||||
import { CloudintegrationtypesGCPConnectionMethodDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
@@ -3,18 +3,6 @@
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-8);
|
||||
padding: var(--spacing-0) var(--spacing-0);
|
||||
//TODO: remove this once we have a proper dashboard page.
|
||||
// The embedded V2 DashboardContainer renders its own page header (dashboard
|
||||
// title + share/feedback chrome) removed it for now
|
||||
:global([class*='dashboardPageHeader']),
|
||||
:global([class*='dashboardInfoWithActions']) {
|
||||
display: none;
|
||||
}
|
||||
// Embedded read-only: the add-variable and panel-action triggers are dead here.
|
||||
:global([class*='addSlot']),
|
||||
:global([data-testid^='panel-actions-']) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.errorState {
|
||||
|
||||
@@ -3,10 +3,21 @@ import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import Spinner from 'components/Spinner';
|
||||
import DashboardContainer from 'pages/DashboardPage/DashboardContainer';
|
||||
import type { DashboardControlsInput } from 'pages/DashboardPage/DashboardContainer/controls/types';
|
||||
|
||||
import { useSystemDashboard } from './hooks/useSystemDashboard';
|
||||
import {
|
||||
SYSTEM_DASHBOARD_SOURCE,
|
||||
useSystemDashboard,
|
||||
} from './hooks/useSystemDashboard';
|
||||
import styles from './Overview.module.scss';
|
||||
|
||||
// Embedded under the AI Observability tabs, which own the page header.
|
||||
const EMBEDDED_CONTROLS: DashboardControlsInput = {
|
||||
header: false,
|
||||
title: false,
|
||||
dashboardActions: false,
|
||||
};
|
||||
|
||||
function Overview(): JSX.Element {
|
||||
const { dashboard, isLoading, isError, error, refetch } = useSystemDashboard();
|
||||
|
||||
@@ -51,7 +62,9 @@ function Overview(): JSX.Element {
|
||||
<DashboardContainer
|
||||
dashboard={dashboard}
|
||||
refetch={refetch}
|
||||
canEditDashboardOverride={false}
|
||||
source={SYSTEM_DASHBOARD_SOURCE}
|
||||
readOnly
|
||||
controls={EMBEDDED_CONTROLS}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,20 +1,34 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import { useCallback } from 'react';
|
||||
|
||||
import {
|
||||
getGetDashboardV2QueryKey,
|
||||
getGetSystemDashboardQueryKey,
|
||||
useGetSystemDashboard,
|
||||
} from 'api/generated/services/dashboard';
|
||||
import type { GetSystemDashboardQueryError } from 'api/generated/services/dashboard';
|
||||
import type {
|
||||
DashboardtypesGettableDashboardV2DTO,
|
||||
GetDashboardV2200,
|
||||
GetSystemDashboard200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { DashboardQuerySource } from 'pages/DashboardPage/DashboardContainer/store/slices/editContextSlice';
|
||||
|
||||
const SYSTEM_DASHBOARD_NAME = 'ai-o11y-overview';
|
||||
|
||||
const DASHBOARD_ID = 'llm-observability-overview';
|
||||
|
||||
// System dashboards have no `id`; a fixed one keys the store's per-dashboard state.
|
||||
const selectDashboard = (
|
||||
response: GetSystemDashboard200,
|
||||
): DashboardtypesGettableDashboardV2DTO =>
|
||||
({
|
||||
...response.data,
|
||||
id: DASHBOARD_ID,
|
||||
}) as DashboardtypesGettableDashboardV2DTO;
|
||||
|
||||
export const SYSTEM_DASHBOARD_SOURCE: DashboardQuerySource = {
|
||||
queryKey: getGetSystemDashboardQueryKey({ name: SYSTEM_DASHBOARD_NAME }),
|
||||
select: selectDashboard,
|
||||
};
|
||||
|
||||
export interface UseSystemDashboardResult {
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO | undefined;
|
||||
isLoading: boolean;
|
||||
@@ -24,30 +38,23 @@ export interface UseSystemDashboardResult {
|
||||
}
|
||||
|
||||
export function useSystemDashboard(): UseSystemDashboardResult {
|
||||
const queryClient = useQueryClient();
|
||||
const { data, isLoading, isError, error, refetch } = useGetSystemDashboard(
|
||||
const {
|
||||
data: dashboard,
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
refetch,
|
||||
} = useGetSystemDashboard(
|
||||
{ name: SYSTEM_DASHBOARD_NAME },
|
||||
{ query: { staleTime: Infinity, refetchOnMount: false } },
|
||||
{
|
||||
query: {
|
||||
select: selectDashboard,
|
||||
staleTime: Infinity,
|
||||
refetchOnMount: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const dashboard = useMemo(
|
||||
() =>
|
||||
data
|
||||
? ({
|
||||
...data.data,
|
||||
id: DASHBOARD_ID,
|
||||
} as DashboardtypesGettableDashboardV2DTO)
|
||||
: undefined,
|
||||
[data],
|
||||
);
|
||||
|
||||
if (dashboard) {
|
||||
queryClient.setQueryData<GetDashboardV2200>(
|
||||
getGetDashboardV2QueryKey({ id: DASHBOARD_ID }),
|
||||
{ data: dashboard, status: 'success' },
|
||||
);
|
||||
}
|
||||
|
||||
const refetchDashboard = useCallback((): void => {
|
||||
void refetch();
|
||||
}, [refetch]);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import MultiSelectFilter, {
|
||||
type MultiSelectFilterOption,
|
||||
@@ -25,27 +25,25 @@ function RuleStatesFilter({
|
||||
onChange,
|
||||
}: RuleStatesFilterProps): JSX.Element {
|
||||
const [draft, setDraft] = useState(states);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(states);
|
||||
}, [states]);
|
||||
|
||||
const handleCommit = useCallback(
|
||||
(next: string[]): void => {
|
||||
setDraft(next);
|
||||
const handleChange = (next: string[]): void => {
|
||||
setDraft(next);
|
||||
if (!open) {
|
||||
onChange(next);
|
||||
},
|
||||
[onChange],
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDropdownVisibleChange = useCallback(
|
||||
(isOpen: boolean): void => {
|
||||
if (!isOpen && !isSameStates(draft, states)) {
|
||||
onChange(draft);
|
||||
}
|
||||
},
|
||||
[draft, states, onChange],
|
||||
);
|
||||
const handleDropdownVisibleChange = (nextOpen: boolean): void => {
|
||||
setOpen(nextOpen);
|
||||
if (!nextOpen && !isSameStates(draft, states)) {
|
||||
onChange(draft);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<MultiSelectFilter
|
||||
@@ -53,8 +51,7 @@ function RuleStatesFilter({
|
||||
options={STATE_OPTIONS}
|
||||
placeholder="Status"
|
||||
testId="alert-rules-filter-states"
|
||||
onChange={setDraft}
|
||||
onCommit={handleCommit}
|
||||
onChange={handleChange}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -212,7 +212,6 @@ function ListAlertRules(): JSX.Element {
|
||||
testIdPrefix="alert-rules"
|
||||
saveTestIdPrefix="save-alert-rule-view"
|
||||
renameTestIdPrefix="rename-alert-rule-view"
|
||||
viewNamePlaceholder="e.g. Prod alerts"
|
||||
deleteDescription="Views are shared across your organization, so this removes it for everyone. Alert rules are not affected."
|
||||
/>
|
||||
<div className={styles.main}>
|
||||
|
||||
@@ -2,77 +2,14 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.meter-explorer-date-time {
|
||||
display: flex;
|
||||
min-height: 30px;
|
||||
justify-content: end;
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
padding: 10px 16px;
|
||||
}
|
||||
|
||||
.meter-explorer-graphs {
|
||||
.meter-explorer-notices {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 20px;
|
||||
gap: 36px;
|
||||
gap: 12px;
|
||||
padding: 16px 20px 0;
|
||||
|
||||
.info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.meter-column-graph {
|
||||
.row-card {
|
||||
background-color: var(--l2-background);
|
||||
padding-left: 10px;
|
||||
height: 32px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
.section-title {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 14px;
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
|
||||
.graph-description {
|
||||
padding: 10px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.meter-page-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
.meter-graph {
|
||||
height: 400px;
|
||||
padding: 10px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.total {
|
||||
.meter-column-graph {
|
||||
.meter-page-grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
|
||||
.meter-graph {
|
||||
height: 200px;
|
||||
}
|
||||
}
|
||||
}
|
||||
&:empty {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,133 +1,40 @@
|
||||
import { useCallback } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { Alert } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import getLocalStorageApi from 'api/browser/localstorage/get';
|
||||
import setLocalStorageApi from 'api/browser/localstorage/set';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import GridCard from 'container/WidgetCard/Card';
|
||||
import { Card, CardContainer } from 'container/WidgetCard/styles';
|
||||
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
|
||||
import { useQuery } from 'react-query';
|
||||
import dayjs from 'dayjs';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { UpdateTimeInterval } from 'store/actions';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { Widgets } from 'types/api/widgets/widget';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
import { identity, noop } from 'lodash-es';
|
||||
import DashboardContainer from 'pages/DashboardPage/DashboardContainer';
|
||||
import {
|
||||
getLogCountWidgetData,
|
||||
getLogSizeWidgetData,
|
||||
getMetricCountWidgetData,
|
||||
getSpanCountWidgetData,
|
||||
getSpanSizeWidgetData,
|
||||
getTotalLogSizeWidgetData,
|
||||
getTotalMetricDatapointCountWidgetData,
|
||||
getTotalTraceSizeWidgetData,
|
||||
} from './graphs';
|
||||
CHARTS_ONLY,
|
||||
withControls,
|
||||
} from 'pages/DashboardPage/DashboardContainer/controls/presets';
|
||||
import type { DashboardQuerySource } from 'pages/DashboardPage/DashboardContainer/store/slices/editContextSlice';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import { COST_METER_DASHBOARD } from './dashboard';
|
||||
|
||||
import './BreakDown.styles.scss';
|
||||
|
||||
type MetricSection = {
|
||||
id: string;
|
||||
title: string;
|
||||
graphs: Widgets[];
|
||||
};
|
||||
// Built in the frontend, never fetched: the container reads it back from this cache entry.
|
||||
const QUERY_KEY = ['cost-meter-breakdown-dashboard'];
|
||||
const SOURCE: DashboardQuerySource = { queryKey: QUERY_KEY, select: identity };
|
||||
|
||||
const sections: MetricSection[] = [
|
||||
{
|
||||
id: uuid(),
|
||||
title: 'Total',
|
||||
graphs: [
|
||||
getTotalLogSizeWidgetData(),
|
||||
getTotalTraceSizeWidgetData(),
|
||||
getTotalMetricDatapointCountWidgetData(),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: uuid(),
|
||||
title: 'Logs',
|
||||
graphs: [getLogCountWidgetData(), getLogSizeWidgetData()],
|
||||
},
|
||||
{
|
||||
id: uuid(),
|
||||
title: 'Traces',
|
||||
graphs: [getSpanCountWidgetData(), getSpanSizeWidgetData()],
|
||||
},
|
||||
{
|
||||
id: uuid(),
|
||||
title: 'Metrics',
|
||||
graphs: [getMetricCountWidgetData()],
|
||||
},
|
||||
];
|
||||
|
||||
function Section(section: MetricSection): JSX.Element {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const { title, graphs } = section;
|
||||
const { pathname } = useAppLocation();
|
||||
const dispatch = useDispatch();
|
||||
const urlQuery = useUrlQuery();
|
||||
|
||||
const onDragSelect = useCallback(
|
||||
(start: number, end: number) => {
|
||||
const startTimestamp = Math.trunc(start);
|
||||
const endTimestamp = Math.trunc(end);
|
||||
|
||||
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
|
||||
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
|
||||
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
|
||||
navigate(generatedUrl);
|
||||
|
||||
if (startTimestamp !== endTimestamp) {
|
||||
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
|
||||
}
|
||||
},
|
||||
[dispatch, pathname, urlQuery],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="meter-column-graph"
|
||||
data-testid={`meter-breakdown-section-${title.toLowerCase()}`}
|
||||
>
|
||||
<CardContainer className="row-card" isDarkMode={isDarkMode}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
</CardContainer>
|
||||
<div className="meter-page-grid">
|
||||
{graphs.map((widget) => (
|
||||
<Card
|
||||
key={widget?.id}
|
||||
isDarkMode={isDarkMode}
|
||||
$panelType={PANEL_TYPES.BAR}
|
||||
className="meter-graph"
|
||||
>
|
||||
<GridCard widget={widget} onDragSelect={onDragSelect} version="v5" />
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const CONTROLS = withControls(CHARTS_ONLY, {
|
||||
toolbar: { autoRefresh: false },
|
||||
});
|
||||
|
||||
function BreakDown(): JSX.Element {
|
||||
const { isCloudUser } = useGetTenantLicense();
|
||||
useQuery(QUERY_KEY, () => COST_METER_DASHBOARD, {
|
||||
initialData: COST_METER_DASHBOARD,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
@@ -142,12 +49,10 @@ function BreakDown(): JSX.Element {
|
||||
|
||||
return (
|
||||
<div className="meter-explorer-breakdown">
|
||||
<section className="meter-explorer-date-time">
|
||||
<DateTimeSelectionV2 showAutoRefresh={false} />
|
||||
</section>
|
||||
<section className="meter-explorer-graphs">
|
||||
<section className="meter-explorer-notices">
|
||||
{showInfo && (
|
||||
<Alert
|
||||
data-testid="cost-meter-utc-notice"
|
||||
type="info"
|
||||
showIcon
|
||||
closable
|
||||
@@ -188,28 +93,14 @@ function BreakDown(): JSX.Element {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<section className="total">
|
||||
<Section
|
||||
id={sections[0].id}
|
||||
title={sections[0].title}
|
||||
graphs={sections[0].graphs}
|
||||
/>
|
||||
</section>
|
||||
{sections.map((section, idx) => {
|
||||
if (idx === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<Section
|
||||
key={section.id}
|
||||
id={section.id}
|
||||
title={section.title}
|
||||
graphs={section.graphs}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
<DashboardContainer
|
||||
dashboard={COST_METER_DASHBOARD}
|
||||
refetch={noop}
|
||||
source={SOURCE}
|
||||
readOnly
|
||||
controls={CONTROLS}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { DashboardControlsInput } from 'pages/DashboardPage/DashboardContainer/controls/types';
|
||||
import { resolveControls } from 'pages/DashboardPage/DashboardContainer/controls/dashboardControls';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import BreakDown from '../BreakDown';
|
||||
import {
|
||||
COST_METER_DASHBOARD,
|
||||
COST_METER_DASHBOARD_ID,
|
||||
SECTIONS,
|
||||
} from '../dashboard';
|
||||
|
||||
jest.mock('pages/DashboardPage/DashboardContainer', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
dashboard,
|
||||
readOnly,
|
||||
controls,
|
||||
}: {
|
||||
dashboard: DashboardtypesGettableDashboardV2DTO;
|
||||
readOnly: boolean;
|
||||
controls: DashboardControlsInput;
|
||||
}): JSX.Element => (
|
||||
<div
|
||||
data-testid="dashboard-container"
|
||||
data-dashboard-id={dashboard.id}
|
||||
data-read-only={String(readOnly)}
|
||||
data-controls={JSON.stringify(controls)}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('Cost meter breakdown', () => {
|
||||
it('mounts the assembled dashboard read-only as charts only, without auto-refresh', () => {
|
||||
render(<BreakDown />);
|
||||
|
||||
const dashboard = screen.getByTestId('dashboard-container');
|
||||
expect(dashboard).toHaveAttribute(
|
||||
'data-dashboard-id',
|
||||
COST_METER_DASHBOARD_ID,
|
||||
);
|
||||
expect(dashboard).toHaveAttribute('data-read-only', 'true');
|
||||
const controls = resolveControls(
|
||||
JSON.parse(dashboard.getAttribute('data-controls') ?? ''),
|
||||
true,
|
||||
);
|
||||
expect(controls.header.breadcrumbs).toBe(false);
|
||||
expect(controls.panelActions.createAlert).toBe(false);
|
||||
expect(controls.panelActions.drilldown).toBe(false);
|
||||
expect(controls.panelActions.zoom).toBe(true);
|
||||
expect(controls.toolbar.autoRefresh).toBe(false);
|
||||
expect(controls.toolbar.timeRange).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the UTC billing notice above the dashboard', () => {
|
||||
render(<BreakDown />);
|
||||
|
||||
expect(screen.getByTestId('cost-meter-utc-notice')).toHaveTextContent(
|
||||
'Billing is calculated in UTC',
|
||||
);
|
||||
});
|
||||
|
||||
it('places every panel exactly once, in its section', () => {
|
||||
const placed = COST_METER_DASHBOARD.spec.layouts.flatMap((layout) =>
|
||||
(layout.spec.items ?? []).map((item) =>
|
||||
item.content?.$ref?.replace('#/spec/panels/', ''),
|
||||
),
|
||||
);
|
||||
|
||||
expect(placed.sort()).toStrictEqual(
|
||||
Object.keys(COST_METER_DASHBOARD.spec.panels).sort(),
|
||||
);
|
||||
expect(
|
||||
COST_METER_DASHBOARD.spec.layouts.map((l) => l.spec.display?.title),
|
||||
).toStrictEqual(SECTIONS.map((s) => s.title));
|
||||
});
|
||||
});
|
||||
220
frontend/src/container/MeterExplorer/Breakdown/dashboard.ts
Normal file
220
frontend/src/container/MeterExplorer/Breakdown/dashboard.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import {
|
||||
DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpecDTOKind as GridKind,
|
||||
DashboardtypesPanelKindDTO as PanelKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTOKind as BarChartKind,
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpecDTOKind as NumberKind,
|
||||
DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpecDTOKind as BuilderQueryKind,
|
||||
DashboardtypesSourceDTO,
|
||||
DashboardtypesTimePreferenceDTO,
|
||||
MetrictypesSpaceAggregationDTO,
|
||||
MetrictypesTimeAggregationDTO,
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
|
||||
Querybuildertypesv5ReduceToDTO,
|
||||
Querybuildertypesv5RequestTypeDTO as RequestType,
|
||||
TelemetrytypesSourceDTO,
|
||||
type DashboardtypesGettableDashboardV2DTO,
|
||||
type DashboardtypesLayoutDTO,
|
||||
type DashboardtypesPanelDTO,
|
||||
type DashboardtypesQueryDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
/** Namespaced: persisted per-dashboard state keys on it, so it must never match a server id. */
|
||||
export const COST_METER_DASHBOARD_ID = 'signoz-app:cost-meter-breakdown';
|
||||
|
||||
export enum MeterUnit {
|
||||
Bytes = 'bytes',
|
||||
Short = 'short',
|
||||
}
|
||||
|
||||
interface MeterPanel {
|
||||
id: string;
|
||||
name: string;
|
||||
metric: string;
|
||||
unit: MeterUnit;
|
||||
}
|
||||
|
||||
interface MeterSection {
|
||||
title: string;
|
||||
/** Window totals as numbers; otherwise hourly bars. */
|
||||
isTotal?: boolean;
|
||||
panels: MeterPanel[];
|
||||
}
|
||||
|
||||
export const SECTIONS: MeterSection[] = [
|
||||
{
|
||||
title: 'Total',
|
||||
isTotal: true,
|
||||
panels: [
|
||||
{
|
||||
id: 'total-log-size',
|
||||
name: 'Total size of log records ingested',
|
||||
metric: 'signoz.meter.log.size',
|
||||
unit: MeterUnit.Bytes,
|
||||
},
|
||||
{
|
||||
id: 'total-span-size',
|
||||
name: 'Total size of spans ingested',
|
||||
metric: 'signoz.meter.span.size',
|
||||
unit: MeterUnit.Bytes,
|
||||
},
|
||||
{
|
||||
id: 'total-metric-datapoints',
|
||||
name: 'Total metric datapoints ingested',
|
||||
metric: 'signoz.meter.metric.datapoint.count',
|
||||
unit: MeterUnit.Short,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Logs',
|
||||
panels: [
|
||||
{
|
||||
id: 'log-count',
|
||||
name: 'Count of log records ingested',
|
||||
metric: 'signoz.meter.log.count',
|
||||
unit: MeterUnit.Short,
|
||||
},
|
||||
{
|
||||
id: 'log-size',
|
||||
name: 'Size of log records ingested',
|
||||
metric: 'signoz.meter.log.size',
|
||||
unit: MeterUnit.Bytes,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Traces',
|
||||
panels: [
|
||||
{
|
||||
id: 'span-count',
|
||||
name: 'Count of spans ingested',
|
||||
metric: 'signoz.meter.span.count',
|
||||
unit: MeterUnit.Short,
|
||||
},
|
||||
{
|
||||
id: 'span-size',
|
||||
name: 'Size of spans ingested',
|
||||
metric: 'signoz.meter.span.size',
|
||||
unit: MeterUnit.Bytes,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Metrics',
|
||||
panels: [
|
||||
{
|
||||
id: 'metric-datapoints',
|
||||
name: 'Count of metric datapoints ingested',
|
||||
metric: 'signoz.meter.metric.datapoint.count',
|
||||
unit: MeterUnit.Short,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const buildMeterQuery = (
|
||||
{ metric, unit }: MeterPanel,
|
||||
kind: RequestType,
|
||||
): DashboardtypesQueryDTO => ({
|
||||
kind,
|
||||
spec: {
|
||||
plugin: {
|
||||
kind: BuilderQueryKind['signoz/BuilderQuery'],
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: MetricSignal.metrics,
|
||||
source: TelemetrytypesSourceDTO.meter,
|
||||
aggregations: [
|
||||
{
|
||||
metricName: metric,
|
||||
timeAggregation: MetrictypesTimeAggregationDTO.increase,
|
||||
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
|
||||
reduceTo: Querybuildertypesv5ReduceToDTO.sum,
|
||||
},
|
||||
],
|
||||
legend: unit === MeterUnit.Bytes ? 'size' : 'count',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const buildMeterPanel = (
|
||||
panel: MeterPanel,
|
||||
isTotal: boolean,
|
||||
): DashboardtypesPanelDTO => ({
|
||||
kind: PanelKind.Panel,
|
||||
spec: {
|
||||
display: { name: panel.name },
|
||||
plugin: isTotal
|
||||
? {
|
||||
kind: NumberKind['signoz/NumberPanel'],
|
||||
spec: {
|
||||
formatting: { unit: panel.unit },
|
||||
visualization: {
|
||||
timePreference: DashboardtypesTimePreferenceDTO.global_time,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {
|
||||
kind: BarChartKind['signoz/BarChartPanel'],
|
||||
spec: {
|
||||
formatting: { unit: panel.unit },
|
||||
visualization: { stackedBarChart: false },
|
||||
},
|
||||
},
|
||||
queries: [
|
||||
buildMeterQuery(
|
||||
panel,
|
||||
isTotal ? RequestType.scalar : RequestType.time_series,
|
||||
),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const buildGridLayout = ({
|
||||
title,
|
||||
isTotal,
|
||||
panels,
|
||||
}: MeterSection): DashboardtypesLayoutDTO => {
|
||||
const width = isTotal ? 4 : 6;
|
||||
const height = isTotal ? 3 : 6;
|
||||
const perRow = 12 / width;
|
||||
|
||||
return {
|
||||
kind: GridKind.Grid,
|
||||
spec: {
|
||||
display: { title },
|
||||
items: panels.map((panel, index) => ({
|
||||
x: (index % perRow) * width,
|
||||
y: Math.floor(index / perRow) * height,
|
||||
width,
|
||||
height,
|
||||
content: { $ref: `#/spec/panels/${panel.id}` },
|
||||
})),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const COST_METER_DASHBOARD: DashboardtypesGettableDashboardV2DTO = {
|
||||
id: COST_METER_DASHBOARD_ID,
|
||||
orgId: '',
|
||||
name: 'cost-meter-breakdown',
|
||||
schemaVersion: 'v6',
|
||||
source: DashboardtypesSourceDTO.system,
|
||||
locked: true,
|
||||
tags: [],
|
||||
spec: {
|
||||
display: {
|
||||
name: 'Cost Meter Breakdown',
|
||||
description:
|
||||
'Logs, spans and metric datapoints ingested, from the signoz.meter.* metrics. Aggregated hourly; billing is calculated in UTC.',
|
||||
},
|
||||
variables: [],
|
||||
layouts: SECTIONS.map(buildGridLayout),
|
||||
panels: Object.fromEntries(
|
||||
SECTIONS.flatMap(({ isTotal = false, panels }) =>
|
||||
panels.map((panel) => [panel.id, buildMeterPanel(panel, isTotal)]),
|
||||
),
|
||||
),
|
||||
},
|
||||
};
|
||||
@@ -1,374 +0,0 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetWidgetQueryBuilderProps } from 'container/MetricsApplication/types';
|
||||
import { Widgets } from 'types/api/widgets/widget';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import {
|
||||
IBuilderFormula,
|
||||
IBuilderQuery,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
interface GetWidgetQueryProps {
|
||||
title: string;
|
||||
description: string;
|
||||
queryData: IBuilderQuery[];
|
||||
queryFormulas?: IBuilderFormula[];
|
||||
panelTypes?: PANEL_TYPES;
|
||||
yAxisUnit?: string;
|
||||
columnUnits?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface GetWidgetQueryPropsReturn extends GetWidgetQueryBuilderProps {
|
||||
description?: string;
|
||||
nullZeroValues: string;
|
||||
columnUnits?: Record<string, string>;
|
||||
}
|
||||
|
||||
export const getWidgetQueryBuilder = ({
|
||||
query,
|
||||
title = '',
|
||||
panelTypes,
|
||||
yAxisUnit = '',
|
||||
fillSpans = false,
|
||||
id,
|
||||
nullZeroValues,
|
||||
description,
|
||||
}: GetWidgetQueryPropsReturn): Widgets => ({
|
||||
description: description || '',
|
||||
id: id || uuid(),
|
||||
nullZeroValues: nullZeroValues || '',
|
||||
opacity: '1',
|
||||
panelTypes,
|
||||
query,
|
||||
timePreferance: 'GLOBAL_TIME',
|
||||
title,
|
||||
yAxisUnit,
|
||||
softMax: null,
|
||||
softMin: null,
|
||||
selectedLogFields: [],
|
||||
selectedTracesFields: [],
|
||||
fillSpans,
|
||||
});
|
||||
|
||||
export function getWidgetQuery(
|
||||
props: GetWidgetQueryProps,
|
||||
): GetWidgetQueryPropsReturn {
|
||||
const { title, description, panelTypes, yAxisUnit, columnUnits } = props;
|
||||
return {
|
||||
title,
|
||||
yAxisUnit: yAxisUnit || 'none',
|
||||
panelTypes: panelTypes || PANEL_TYPES.TIME_SERIES,
|
||||
fillSpans: false,
|
||||
description,
|
||||
nullZeroValues: 'zero',
|
||||
columnUnits,
|
||||
query: {
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
promql: [],
|
||||
builder: {
|
||||
queryData: props.queryData,
|
||||
queryFormulas: (props.queryFormulas as IBuilderFormula[]) || [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
clickhouse_sql: [],
|
||||
id: uuid(),
|
||||
},
|
||||
};
|
||||
}
|
||||
export const getTotalLogSizeWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.log.size',
|
||||
id: 'signoz.meter.log.size--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.SUM,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Total size of log records ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.VALUE,
|
||||
yAxisUnit: 'bytes',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getTotalTraceSizeWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.span.size',
|
||||
id: 'signoz.meter.span.size--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.SUM,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Total size of spans ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.VALUE,
|
||||
yAxisUnit: 'bytes',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getTotalMetricDatapointCountWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.metric.datapoint.count',
|
||||
id: 'signoz.meter.metric.datapoint.count--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.SUM,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Total metric datapoints ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.VALUE,
|
||||
yAxisUnit: 'short',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getLogCountWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.log.count',
|
||||
id: 'signoz.meter.log.count--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Count of log records ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'short',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getLogSizeWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.log.size',
|
||||
id: 'signoz.meter.log.size--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'size',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Size of log records ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'bytes',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getSpanCountWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.span.count',
|
||||
id: 'signoz.meter.span.count--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Count of spans ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'short',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getSpanSizeWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.span.size',
|
||||
id: 'signoz.meter.span.size--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'size',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Size of spans ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'bytes',
|
||||
}),
|
||||
);
|
||||
|
||||
export const getMetricCountWidgetData = (): Widgets =>
|
||||
getWidgetQueryBuilder(
|
||||
getWidgetQuery({
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'signoz.meter.metric.datapoint.count',
|
||||
id: 'signoz.meter.metric.datapoint.count--float64--Sum--true',
|
||||
type: 'Sum',
|
||||
},
|
||||
aggregateOperator: 'increase',
|
||||
dataSource: DataSource.METRICS,
|
||||
source: 'meter',
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: { items: [], op: 'AND' },
|
||||
functions: [],
|
||||
groupBy: [],
|
||||
having: [],
|
||||
legend: 'count',
|
||||
limit: null,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: null,
|
||||
timeAggregation: 'increase',
|
||||
},
|
||||
],
|
||||
title: 'Count of metric datapoints ingested',
|
||||
description: '',
|
||||
panelTypes: PANEL_TYPES.BAR,
|
||||
yAxisUnit: 'short',
|
||||
}),
|
||||
);
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Color, Style } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
@@ -81,7 +81,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="google-domain">
|
||||
Domain
|
||||
<Tooltip title="The email domain for users who should use SSO (e.g., `example.com` for users with `@example.com` emails)">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -104,7 +104,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="google-client-id">
|
||||
Client ID
|
||||
<Tooltip title="ClientID is the application's ID. For example, 292085223830.apps.googleusercontent.com.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -122,7 +122,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="google-client-secret">
|
||||
Client Secret
|
||||
<Tooltip title="It is the application's secret.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -161,7 +161,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title='Whether to skip email verification. Defaults to "false"'>
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -243,7 +243,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="Enable fetching Google Workspace groups for the user. Requires service account configuration.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -256,7 +256,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
>
|
||||
Service Account JSON
|
||||
<Tooltip title="The JSON content of the Google Service Account credentials file. Required for group fetching.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -298,7 +298,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="If enabled, recursively fetch groups that contain other groups (transitive membership).">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -309,7 +309,7 @@ function ConfigureGoogleAuthAuthnProvider({
|
||||
>
|
||||
Allowed Groups
|
||||
<Tooltip title="Optional list of allowed groups. If configured, only users belonging to one of these groups will be allowed to login.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Style } from '@signozhq/design-tokens';
|
||||
import { CircleHelp, TriangleAlert } from '@signozhq/icons';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
@@ -54,7 +55,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-domain">
|
||||
Domain
|
||||
<Tooltip title="The email domain for users who should use SSO (e.g., `example.com` for users with `@example.com` emails)">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -76,7 +77,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-issuer">
|
||||
Issuer URL
|
||||
<Tooltip title='The URL identifier for the OIDC provider. For example: "https://accounts.google.com" or "https://login.salesforce.com".'>
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -94,7 +95,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-issuer-alias">
|
||||
Issuer Alias
|
||||
<Tooltip title="Optional: Override the issuer URL from .well-known/openid-configuration for providers like Azure or Oracle IDCS.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -109,7 +110,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-client-id">
|
||||
Client ID
|
||||
<Tooltip title="The application's client ID from your OIDC provider.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -127,7 +128,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="oidc-client-secret">
|
||||
Client Secret
|
||||
<Tooltip title="The application's client secret from your OIDC provider.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -165,7 +166,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title='Whether to skip email verification. Defaults to "false"'>
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -186,7 +187,7 @@ function ConfigureOIDCAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="Use the userinfo endpoint to get additional claims. Useful when providers return thin ID tokens.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="authn-provider__callout-wrapper">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Style } from '@signozhq/design-tokens';
|
||||
import { CircleHelp, TriangleAlert } from '@signozhq/icons';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
@@ -53,7 +54,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="saml-domain">
|
||||
Domain
|
||||
<Tooltip title="The email domain for users who should use SSO (e.g., `example.com` for users with `@example.com` emails)">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -75,7 +76,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="saml-acs-url">
|
||||
SAML ACS URL
|
||||
<Tooltip title="The SSO endpoint of the SAML identity provider. It can typically be found in the SingleSignOnService element in the SAML metadata of the identity provider.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -97,7 +98,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="saml-entity-id">
|
||||
SAML Entity ID
|
||||
<Tooltip title="The entityID of the SAML identity provider. It can typically be found in the EntityID attribute of the EntityDescriptor element in the SAML metadata.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -119,7 +120,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
<label className="authn-provider__label" htmlFor="saml-certificate">
|
||||
SAML X.509 Certificate
|
||||
<Tooltip title="The certificate of the SAML identity provider. It can typically be found in the X509Certificate element in the SAML metadata.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -162,7 +163,7 @@ function ConfigureSAMLAuthnProvider({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="Whether to skip signing the SAML requests. For providers like JumpCloud, this should be enabled.">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Color, Style } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
@@ -98,7 +98,7 @@ function AttributeMappingSection({
|
||||
>
|
||||
Email Attribute
|
||||
<Tooltip title="The SAML attribute key that contains the user's email. Default: 'email'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -117,7 +117,7 @@ function AttributeMappingSection({
|
||||
>
|
||||
Name Attribute
|
||||
<Tooltip title="The SAML attribute key that contains the user's display name. Default: 'name'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -136,7 +136,7 @@ function AttributeMappingSection({
|
||||
>
|
||||
Groups Attribute
|
||||
<Tooltip title="The SAML attribute key that contains the user's group memberships. Used for role mapping. Default: 'groups'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -155,7 +155,7 @@ function AttributeMappingSection({
|
||||
>
|
||||
Role Attribute
|
||||
<Tooltip title="The SAML attribute key that contains the user's role directly from the IDP. Default: 'role'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Color, Style } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
@@ -93,7 +93,7 @@ function ClaimMappingSection({
|
||||
<label className="claim-mapping-section__label" htmlFor="email-claim">
|
||||
Email Claim
|
||||
<Tooltip title="The claim key that contains the user's email address. Default: 'email'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -109,7 +109,7 @@ function ClaimMappingSection({
|
||||
<label className="claim-mapping-section__label" htmlFor="name-claim">
|
||||
Name Claim
|
||||
<Tooltip title="The claim key that contains the user's display name. Default: 'name'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -125,7 +125,7 @@ function ClaimMappingSection({
|
||||
<label className="claim-mapping-section__label" htmlFor="groups-claim">
|
||||
Groups Claim
|
||||
<Tooltip title="The claim key that contains the user's group memberships. Used for role mapping. Default: 'groups'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -141,7 +141,7 @@ function ClaimMappingSection({
|
||||
<label className="claim-mapping-section__label" htmlFor="role-claim">
|
||||
Role Claim
|
||||
<Tooltip title="The claim key that contains the user's role directly from the IDP. Default: 'role'">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Color, Style } from '@signozhq/design-tokens';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
@@ -108,7 +108,7 @@ function RoleMappingSection({
|
||||
<label className="role-mapping-section__label" htmlFor="default-role">
|
||||
Default Role
|
||||
<Tooltip title='The default role assigned to new SSO users if no other role mapping applies. Default: "signoz-viewer"'>
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</label>
|
||||
<Form.Item
|
||||
@@ -148,7 +148,7 @@ function RoleMappingSection({
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
<Tooltip title="If enabled, the role claim/attribute from the IDP will be used directly instead of group mappings. The role value must match a SigNoz role name (e.g. signoz-viewer, signoz-editor, signoz-admin, or a custom role).">
|
||||
<CircleHelp size={14} color="var(--l3-foreground)" cursor="help" />
|
||||
<CircleHelp size={14} color={Style.L3_FOREGROUND} cursor="help" />
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import {
|
||||
AuthDomainListPermission,
|
||||
buildAuthDomainDeletePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/auth-domain.permissions';
|
||||
import {
|
||||
setupAuthzAdmin,
|
||||
setupAuthzAllow,
|
||||
setupAuthzDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import AuthDomain from '../index';
|
||||
import {
|
||||
AUTH_DOMAINS_DELETE_ENDPOINT,
|
||||
AUTH_DOMAINS_LIST_ENDPOINT,
|
||||
mockDeleteSuccessResponse,
|
||||
mockDomainsListResponse,
|
||||
mockGoogleAuthDomain,
|
||||
} from './mocks';
|
||||
|
||||
jest.mock('@signozhq/ui/toast', () => ({
|
||||
...jest.requireActual('@signozhq/ui/toast'),
|
||||
toast: {
|
||||
success: jest.fn(),
|
||||
danger: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const FIRST_ID = mockGoogleAuthDomain.id ?? '';
|
||||
const FIRST_ROW = `auth-domain-row-${mockGoogleAuthDomain.name}`;
|
||||
|
||||
function useListHandler(): { calls: () => number } {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
rest.get(AUTH_DOMAINS_LIST_ENDPOINT, (_, res, ctx) => {
|
||||
calls += 1;
|
||||
return res(ctx.status(200), ctx.json(mockDomainsListResponse));
|
||||
}),
|
||||
);
|
||||
return { calls: (): number => calls };
|
||||
}
|
||||
|
||||
async function openDeleteModal(rowIndex = 0): Promise<void> {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
await screen.findByTestId(FIRST_ROW);
|
||||
await user.click(screen.getAllByTestId('auth-domain-delete')[rowIndex]);
|
||||
await screen.findByTestId('auth-domain-delete-confirm');
|
||||
}
|
||||
|
||||
async function confirmAfterCheck(): Promise<HTMLElement> {
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('auth-domain-delete-confirm')).not.toHaveAttribute(
|
||||
'aria-busy',
|
||||
),
|
||||
);
|
||||
return screen.getByTestId('auth-domain-delete-confirm');
|
||||
}
|
||||
|
||||
describe('AuthDomain — authz', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('renders the domains when list is granted', async () => {
|
||||
server.use(setupAuthzAdmin());
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
|
||||
await expect(screen.findByTestId(FIRST_ROW)).resolves.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(/is not authorized to perform/i),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the permission-denied UI and sends no list request when list is denied', async () => {
|
||||
server.use(setupAuthzDeny(AuthDomainListPermission));
|
||||
const list = useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
|
||||
await expect(
|
||||
screen.findByText(/is not authorized to perform/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTestId(FIRST_ROW)).not.toBeInTheDocument();
|
||||
expect(list.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it('keeps Add Domain and Configure enabled without create or update grants', async () => {
|
||||
server.use(setupAuthzAllow(AuthDomainListPermission));
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
|
||||
await screen.findByTestId(FIRST_ROW);
|
||||
|
||||
expect(screen.getByTestId('auth-domain-add')).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
expect(
|
||||
screen.getAllByTestId('auth-domain-configure')[0],
|
||||
).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('deletes the domain and refetches the list when delete is granted', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
let deletedId: string | readonly string[] | undefined;
|
||||
server.use(
|
||||
setupAuthzAdmin(),
|
||||
rest.delete(AUTH_DOMAINS_DELETE_ENDPOINT, (req, res, ctx) => {
|
||||
deletedId = req.params.id;
|
||||
return res(ctx.status(200), ctx.json(mockDeleteSuccessResponse));
|
||||
}),
|
||||
);
|
||||
const list = useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
await openDeleteModal();
|
||||
|
||||
const confirm = await confirmAfterCheck();
|
||||
expect(confirm).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(confirm);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(toast.success).toHaveBeenCalledWith('Domain deleted successfully'),
|
||||
);
|
||||
expect(deletedId).toBe(mockGoogleAuthDomain.id);
|
||||
await waitFor(() => expect(list.calls()).toBeGreaterThan(1));
|
||||
});
|
||||
|
||||
it('disables confirm with the denied permission when delete is denied on that domain', async () => {
|
||||
server.use(setupAuthzDeny(buildAuthDomainDeletePermission(FIRST_ID)));
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
await openDeleteModal();
|
||||
|
||||
const confirm = await confirmAfterCheck();
|
||||
expect(confirm).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(confirm).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
expect.stringContaining(FIRST_ID),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps confirm enabled on a domain whose delete is granted', async () => {
|
||||
server.use(setupAuthzDeny(buildAuthDomainDeletePermission(FIRST_ID)));
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
await openDeleteModal(1);
|
||||
|
||||
const confirm = await confirmAfterCheck();
|
||||
expect(confirm).not.toHaveAttribute('data-denied-permissions');
|
||||
expect(confirm).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
it('shows the error modal and keeps the domain when the delete is rejected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
server.use(
|
||||
setupAuthzAdmin(),
|
||||
rest.delete(AUTH_DOMAINS_DELETE_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(403),
|
||||
ctx.json({
|
||||
error: {
|
||||
code: 'authz_forbidden',
|
||||
message: 'not allowed to delete this domain',
|
||||
url: '',
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
useListHandler();
|
||||
|
||||
render(<AuthDomain />);
|
||||
await openDeleteModal();
|
||||
|
||||
const confirm = await confirmAfterCheck();
|
||||
expect(confirm).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(confirm);
|
||||
|
||||
expect(
|
||||
(await screen.findAllByText(/not allowed to delete this domain/i)).length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId(FIRST_ROW)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
@@ -21,7 +20,6 @@ jest.mock('@signozhq/ui/toast', () => ({
|
||||
describe('AuthDomain', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import CreateEdit from '../CreateEdit/CreateEdit';
|
||||
import {
|
||||
AUTH_DOMAINS_CREATE_ENDPOINT,
|
||||
AUTH_DOMAINS_UPDATE_ENDPOINT,
|
||||
mockGoogleAuthDomain,
|
||||
} from './mocks';
|
||||
|
||||
// The real @signozhq/ui/button keeps form.validateFields() from resolving inside
|
||||
// act(); see CreateEdit.payload.test.tsx for the same workaround.
|
||||
jest.mock('@signozhq/ui/button', () => ({
|
||||
...jest.requireActual('@signozhq/ui/button'),
|
||||
Button: ({
|
||||
children,
|
||||
onClick,
|
||||
loading,
|
||||
disabled,
|
||||
testId,
|
||||
}: {
|
||||
children?: React.ReactNode;
|
||||
onClick?: React.MouseEventHandler<HTMLButtonElement>;
|
||||
loading?: boolean;
|
||||
disabled?: boolean;
|
||||
testId?: string;
|
||||
}) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled || loading}
|
||||
data-testid={testId}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
}));
|
||||
|
||||
const FORBIDDEN_RESPONSE = {
|
||||
error: {
|
||||
code: 'authz_forbidden',
|
||||
message: 'not allowed to save this domain',
|
||||
url: '',
|
||||
},
|
||||
};
|
||||
|
||||
describe('CreateEdit — authz', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('shows the error modal and keeps the filled form when create is rejected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onClose = jest.fn();
|
||||
server.use(
|
||||
rest.post(AUTH_DOMAINS_CREATE_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(403), ctx.json(FORBIDDEN_RESPONSE)),
|
||||
),
|
||||
);
|
||||
|
||||
render(<CreateEdit isCreate onClose={onClose} />);
|
||||
|
||||
await user.click(
|
||||
await screen.findByTestId('authn-provider-configure-google'),
|
||||
);
|
||||
await user.type(await screen.findByLabelText(/^domain/i), 'acme.io');
|
||||
await user.type(screen.getByLabelText(/client id/i), 'client-id');
|
||||
await user.type(screen.getByLabelText(/client secret/i), 'secret');
|
||||
await user.click(screen.getByTestId('auth-domain-save'));
|
||||
|
||||
expect(
|
||||
(
|
||||
await screen.findAllByText(/not allowed to save this domain/i, undefined, {
|
||||
timeout: 5000,
|
||||
})
|
||||
).length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
expect(screen.getByLabelText(/^domain/i)).toHaveValue('acme.io');
|
||||
expect(screen.getByLabelText(/client id/i)).toHaveValue('client-id');
|
||||
});
|
||||
|
||||
it('shows the error modal and keeps the form when update is rejected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onClose = jest.fn();
|
||||
let updateCalls = 0;
|
||||
server.use(
|
||||
rest.put(AUTH_DOMAINS_UPDATE_ENDPOINT, (_, res, ctx) => {
|
||||
updateCalls += 1;
|
||||
return res(ctx.status(403), ctx.json(FORBIDDEN_RESPONSE));
|
||||
}),
|
||||
);
|
||||
|
||||
render(
|
||||
<CreateEdit
|
||||
isCreate={false}
|
||||
record={mockGoogleAuthDomain}
|
||||
onClose={onClose}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(await screen.findByTestId('auth-domain-save'));
|
||||
|
||||
await waitFor(() => expect(updateCalls).toBe(1));
|
||||
expect(
|
||||
(
|
||||
await screen.findAllByText(/not allowed to save this domain/i, undefined, {
|
||||
timeout: 5000,
|
||||
})
|
||||
).length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
expect(screen.getByLabelText(/client id/i)).toHaveValue('test-client-id');
|
||||
});
|
||||
});
|
||||
@@ -156,44 +156,6 @@ describe('SSOEnforcementToggle', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('reverts the switch and shows the error modal when the update is forbidden', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
server.use(
|
||||
rest.put(AUTH_DOMAINS_UPDATE_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(403),
|
||||
ctx.json({
|
||||
error: {
|
||||
code: 'authz_forbidden',
|
||||
message: 'not allowed to update this domain',
|
||||
url: '',
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
render(
|
||||
<SSOEnforcementToggle
|
||||
isDefaultChecked={true}
|
||||
record={mockGoogleAuthDomain}
|
||||
/>,
|
||||
);
|
||||
|
||||
const switchElement = screen.getByRole('switch');
|
||||
await user.click(switchElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/not allowed to update this domain/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'true'),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not call API when record has no id', async () => {
|
||||
const user = userEvent.setup();
|
||||
let apiCalled = false;
|
||||
|
||||
@@ -24,13 +24,6 @@ import SSOEnforcementToggle from './SSOEnforcementToggle';
|
||||
|
||||
import './AuthDomain.styles.scss';
|
||||
import '../../IngestionSettings/IngestionSettings.styles.scss';
|
||||
import { useAuthZ } from '@/lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import {
|
||||
AuthDomainListPermission,
|
||||
buildAuthDomainDeletePermission,
|
||||
} from '@/lib/authz/hooks/useAuthZ/permissions/auth-domain.permissions';
|
||||
import { AuthZGuardContent } from '@/lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
import AuthZButton from '@/lib/authz/components/AuthZButton/AuthZButton';
|
||||
|
||||
export const SSOType = new Map<string, string>([
|
||||
['google', 'Google Auth'],
|
||||
@@ -48,18 +41,13 @@ function AuthDomain(): JSX.Element {
|
||||
|
||||
const { showErrorModal } = useErrorModal();
|
||||
|
||||
const { permissions: authzPermissions } = useAuthZ([AuthDomainListPermission]);
|
||||
|
||||
const canListAuthDomains =
|
||||
authzPermissions?.[AuthDomainListPermission]?.isGranted ?? false;
|
||||
|
||||
const {
|
||||
data: authDomainListResponse,
|
||||
isLoading: isLoadingAuthDomainListResponse,
|
||||
isFetching: isFetchingAuthDomainListResponse,
|
||||
error: errorFetchingAuthDomainListResponse,
|
||||
refetch: refetchAuthDomainListResponse,
|
||||
} = useListAuthDomains({ query: { enabled: canListAuthDomains } });
|
||||
} = useListAuthDomains();
|
||||
|
||||
const { mutate: deleteAuthDomain, isLoading } =
|
||||
useDeleteAuthDomain<AxiosError<RenderErrorResponseDTO>>();
|
||||
@@ -210,29 +198,25 @@ function AuthDomain(): JSX.Element {
|
||||
</Button>
|
||||
</section>
|
||||
{formattedError && <ErrorContent error={formattedError} />}
|
||||
<AuthZGuardContent checks={[AuthDomainListPermission]}>
|
||||
{!errorFetchingAuthDomainListResponse ? (
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={authDomainListResponse?.data}
|
||||
onRow={(
|
||||
record: AuthtypesGettableAuthDomainDTO,
|
||||
): HTMLAttributes<HTMLElement> =>
|
||||
// data-* attributes are valid row props but absent from the antd typing
|
||||
({
|
||||
'data-testid': `auth-domain-row-${record.name}`,
|
||||
}) as unknown as HTMLAttributes<HTMLElement>
|
||||
}
|
||||
loading={
|
||||
isLoadingAuthDomainListResponse || isFetchingAuthDomainListResponse
|
||||
}
|
||||
className="auth-domain-list"
|
||||
rowKey="id"
|
||||
/>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</AuthZGuardContent>
|
||||
{!errorFetchingAuthDomainListResponse && (
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={authDomainListResponse?.data}
|
||||
onRow={(
|
||||
record: AuthtypesGettableAuthDomainDTO,
|
||||
): HTMLAttributes<HTMLElement> =>
|
||||
// data-* attributes are valid row props but absent from the antd typing
|
||||
({
|
||||
'data-testid': `auth-domain-row-${record.name}`,
|
||||
}) as unknown as HTMLAttributes<HTMLElement>
|
||||
}
|
||||
loading={
|
||||
isLoadingAuthDomainListResponse || isFetchingAuthDomainListResponse
|
||||
}
|
||||
className="auth-domain-list"
|
||||
rowKey="id"
|
||||
/>
|
||||
)}
|
||||
{(addDomain || record) && (
|
||||
<CreateEdit
|
||||
isCreate={!record}
|
||||
@@ -240,9 +224,7 @@ function AuthDomain(): JSX.Element {
|
||||
onClose={(): void => {
|
||||
setAddDomain(false);
|
||||
setRecord(undefined);
|
||||
if (canListAuthDomains) {
|
||||
void refetchAuthDomainListResponse();
|
||||
}
|
||||
refetchAuthDomainListResponse();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -266,7 +248,7 @@ function AuthDomain(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</Button>,
|
||||
<AuthZButton
|
||||
<Button
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="danger"
|
||||
@@ -275,14 +257,9 @@ function AuthDomain(): JSX.Element {
|
||||
onClick={handleDeleteDomain}
|
||||
loading={isLoading}
|
||||
testId="auth-domain-delete-confirm"
|
||||
checks={
|
||||
isDeleteModalOpen && activeDomain?.id
|
||||
? [buildAuthDomainDeletePermission(activeDomain.id)]
|
||||
: []
|
||||
}
|
||||
>
|
||||
Delete Domain
|
||||
</AuthZButton>,
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<p className="delete-text">
|
||||
|
||||
@@ -8,10 +8,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.org-input-disabled-tooltip-class {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.field-error {
|
||||
color: var(--destructive);
|
||||
margin-top: var(--spacing-2);
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
import {
|
||||
buildOrganizationReadPermission,
|
||||
buildOrganizationUpdatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/organization.permissions';
|
||||
import {
|
||||
setupAuthzAdmin,
|
||||
setupAuthzDeny,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import DisplayName from '../index';
|
||||
|
||||
const ORG_ID = 'does-not-matter-id';
|
||||
const ORG_ME_ENDPOINT = '*/api/v2/orgs/me';
|
||||
|
||||
function renderWithoutSavedName(): void {
|
||||
render(<DisplayName index={0} id={ORG_ID} />, undefined, {
|
||||
appContextOverrides: {
|
||||
org: [{ createdAt: 0, id: ORG_ID, displayName: '' }],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function useOrgFetchHandler(): { calls: () => number } {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
rest.get(ORG_ME_ENDPOINT, (_, res, ctx) => {
|
||||
calls += 1;
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: { id: ORG_ID, displayName: 'Fetched Org' },
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return { calls: (): number => calls };
|
||||
}
|
||||
|
||||
describe('DisplayName — authz', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('disables the input and submit with the denied permission when update is denied', async () => {
|
||||
server.use(setupAuthzDeny(buildOrganizationUpdatePermission(ORG_ID)));
|
||||
|
||||
render(<DisplayName index={0} id={ORG_ID} />);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('org-display-name-submit')).not.toHaveAttribute(
|
||||
'aria-busy',
|
||||
),
|
||||
);
|
||||
const submit = screen.getByTestId('org-display-name-submit');
|
||||
expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(submit).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
expect.stringContaining('update'),
|
||||
);
|
||||
expect(screen.getByTestId('org-display-name-input-field')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows the denial instead of the form and skips the fetch when read is denied', async () => {
|
||||
server.use(setupAuthzDeny(buildOrganizationReadPermission(ORG_ID)));
|
||||
const fetch = useOrgFetchHandler();
|
||||
|
||||
renderWithoutSavedName();
|
||||
|
||||
await expect(
|
||||
screen.findByText(/is not authorized/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText(/read:organization/i)).toBeInTheDocument();
|
||||
expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('org-display-name-submit'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(fetch.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it('fetches the organization when read is granted', async () => {
|
||||
const fetch = useOrgFetchHandler();
|
||||
server.use(setupAuthzAdmin());
|
||||
|
||||
renderWithoutSavedName();
|
||||
|
||||
await waitFor(() => expect(fetch.calls()).toBe(1));
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
fireEvent,
|
||||
@@ -26,7 +25,6 @@ const defaultProps = { index: 0, id: 'does-not-matter-id' };
|
||||
describe('DisplayName', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -36,15 +34,10 @@ describe('DisplayName', () => {
|
||||
it('renders form pre-filled with org displayName from context', async () => {
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByTestId('org-display-name-input-field');
|
||||
const input = await screen.findByRole('textbox');
|
||||
expect(input).toHaveValue('Pentagon');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('org-display-name-submit')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
),
|
||||
);
|
||||
expect(screen.getByRole('button', { name: /submit/i })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables submit and calls PUT when display name is changed', async () => {
|
||||
@@ -54,15 +47,12 @@ describe('DisplayName', () => {
|
||||
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByTestId('org-display-name-input-field');
|
||||
await waitFor(() => expect(input).toBeEnabled());
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'New Org Name');
|
||||
|
||||
const submitBtn = screen.getByTestId('org-display-name-submit');
|
||||
await waitFor(() =>
|
||||
expect(submitBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
const submitBtn = screen.getByRole('button', { name: /submit/i });
|
||||
expect(submitBtn).toBeEnabled();
|
||||
|
||||
await user.click(submitBtn);
|
||||
|
||||
@@ -76,8 +66,7 @@ describe('DisplayName', () => {
|
||||
|
||||
render(<DisplayName {...defaultProps} />);
|
||||
|
||||
const input = await screen.findByTestId('org-display-name-input-field');
|
||||
await waitFor(() => expect(input).toBeEnabled());
|
||||
const input = await screen.findByRole('textbox');
|
||||
await user.clear(input);
|
||||
|
||||
fireEvent.submit(screen.getByTestId('org-display-name-form'));
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { Button, Input } from 'antd';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import {
|
||||
useGetMyOrganization,
|
||||
@@ -10,42 +10,25 @@ import {
|
||||
} from 'api/generated/services/orgs';
|
||||
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { AxiosError } from 'axios';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import {
|
||||
buildOrganizationReadPermission,
|
||||
buildOrganizationUpdatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/organization.permissions';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { IUser } from 'providers/App/types';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { requireErrorMessage } from 'utils/form/requireErrorMessage';
|
||||
|
||||
import { getSubmitBlockedReason } from './utils';
|
||||
|
||||
import './DisplayName.styles.scss';
|
||||
import { AuthZGuardContent } from '@/lib/authz/components/AuthZGuard/AuthZGuardContent';
|
||||
|
||||
function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
const { t } = useTranslation(['organizationsettings', 'common']);
|
||||
const { showErrorModal } = useErrorModal();
|
||||
const { org, updateOrg } = useAppContext();
|
||||
const { org, updateOrg, user } = useAppContext();
|
||||
const currentOrg = (org || [])[index];
|
||||
const readPermission = buildOrganizationReadPermission(orgId);
|
||||
const updatePermission = buildOrganizationUpdatePermission(orgId);
|
||||
const { permissions: authzPermissions } = useAuthZ([
|
||||
readPermission,
|
||||
updatePermission,
|
||||
]);
|
||||
|
||||
const canReadOrg = authzPermissions?.[readPermission]?.isGranted ?? false;
|
||||
const canUpdateOrg = authzPermissions?.[updatePermission]?.isGranted ?? false;
|
||||
const isAdmin = user.role === USER_ROLES.ADMIN;
|
||||
|
||||
const { data: orgData } = useGetMyOrganization({
|
||||
query: {
|
||||
enabled: canReadOrg && !currentOrg?.displayName,
|
||||
enabled: isAdmin && !currentOrg?.displayName,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -93,11 +76,7 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const submitBlockedReason = getSubmitBlockedReason({
|
||||
canUpdate: canUpdateOrg,
|
||||
name: orgName,
|
||||
savedName: displayName,
|
||||
});
|
||||
const isDisabled = isLoading || orgName === displayName || !orgName;
|
||||
|
||||
return (
|
||||
<form
|
||||
@@ -108,50 +87,38 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
|
||||
>
|
||||
<div className="form-field">
|
||||
<label htmlFor="displayName">Display name</label>
|
||||
<AuthZGuardContent checks={[readPermission]}>
|
||||
<Controller
|
||||
name="displayName"
|
||||
control={control}
|
||||
rules={{ required: requireErrorMessage('Display name') }}
|
||||
render={({ field, fieldState }): JSX.Element => (
|
||||
<>
|
||||
<AuthZTooltip
|
||||
triggerClassName="org-input-disabled-tooltip-class"
|
||||
checks={[updatePermission]}
|
||||
>
|
||||
<Input
|
||||
{...field}
|
||||
id="displayName"
|
||||
testId="org-display-name-input"
|
||||
size="lg"
|
||||
placeholder={t('signoz')}
|
||||
status={fieldState.error ? 'danger' : undefined}
|
||||
/>
|
||||
</AuthZTooltip>
|
||||
{fieldState.error && (
|
||||
<div className="field-error">{fieldState.error.message}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</AuthZGuardContent>
|
||||
<Controller
|
||||
name="displayName"
|
||||
control={control}
|
||||
rules={{ required: requireErrorMessage('Display name') }}
|
||||
render={({ field, fieldState }): JSX.Element => (
|
||||
<>
|
||||
<Input
|
||||
{...field}
|
||||
id="displayName"
|
||||
data-testid="org-display-name-input"
|
||||
size="large"
|
||||
placeholder={t('signoz')}
|
||||
status={fieldState.error ? 'error' : ''}
|
||||
/>
|
||||
{fieldState.error && (
|
||||
<div className="field-error">{fieldState.error.message}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
loading={isLoading}
|
||||
disabled={isDisabled}
|
||||
type="primary"
|
||||
htmlType="submit"
|
||||
data-testid="org-display-name-submit"
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
{canReadOrg && (
|
||||
<div>
|
||||
<AuthZButton
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
type="submit"
|
||||
loading={isLoading}
|
||||
disabledTooltip={submitBlockedReason}
|
||||
testId="org-display-name-submit"
|
||||
checks={[updatePermission]}
|
||||
>
|
||||
Submit
|
||||
</AuthZButton>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
interface SubmitBlockedReasonArgs {
|
||||
canUpdate: boolean;
|
||||
name: string;
|
||||
savedName: string;
|
||||
}
|
||||
|
||||
// A permission denial is left to AuthZButton, which names the missing scope.
|
||||
export function getSubmitBlockedReason({
|
||||
canUpdate,
|
||||
name,
|
||||
savedName,
|
||||
}: SubmitBlockedReasonArgs): string | undefined {
|
||||
if (!canUpdate) {
|
||||
return undefined;
|
||||
}
|
||||
if (name === savedName) {
|
||||
return 'No change detected';
|
||||
}
|
||||
if (!name) {
|
||||
return "Can't be empty";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -108,8 +108,6 @@
|
||||
.left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
gap: 8px;
|
||||
|
||||
.value {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import cx from 'classnames';
|
||||
import { isEmpty, isObject } from 'lodash-es';
|
||||
@@ -45,73 +46,28 @@ function Suggestions(props: ISuggestionsProps): React.ReactElement {
|
||||
return (
|
||||
<div className="option">
|
||||
{!isEmpty(optionType) && isObject(value) ? (
|
||||
<div className="container">
|
||||
<section className="left-section">
|
||||
{value.isIndexed ? (
|
||||
<Zap size={12} fill={Color.BG_AMBER_500} />
|
||||
) : (
|
||||
<div className="dot" />
|
||||
)}
|
||||
<div className="value">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="ellipsis"
|
||||
>
|
||||
{label}
|
||||
</Typography>
|
||||
</div>
|
||||
</section>
|
||||
<section className="right-section">
|
||||
<div className="data-type">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="visible"
|
||||
>
|
||||
{value.dataType}
|
||||
</Typography>
|
||||
</div>
|
||||
<section className={cx('type-tag', value.type)}>
|
||||
<div className="dot" />
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="visible"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{value.type}
|
||||
</Typography>
|
||||
<Tooltip title={value.key} placement="topLeft">
|
||||
<div className="container">
|
||||
<section className="left-section">
|
||||
{value.isIndexed ? (
|
||||
<Zap size={12} fill={Color.BG_AMBER_500} />
|
||||
) : (
|
||||
<div className="dot" />
|
||||
)}
|
||||
<div className="value">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="ellipsis"
|
||||
>
|
||||
{label}
|
||||
</Typography>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</div>
|
||||
) : (
|
||||
<div className="container-without-tag">
|
||||
<section className="left">
|
||||
<div className="dot" />
|
||||
<div className={cx('value', option)}>
|
||||
<Typography
|
||||
{...labelTextStyle}
|
||||
size="base"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="ellipsis"
|
||||
>
|
||||
{`${label}`}
|
||||
</Typography>
|
||||
</div>
|
||||
</section>
|
||||
<section className="right">
|
||||
{dataType && (
|
||||
<section className="right-section">
|
||||
<div className="data-type">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
@@ -121,13 +77,62 @@ function Suggestions(props: ISuggestionsProps): React.ReactElement {
|
||||
as="p"
|
||||
textOverflow="visible"
|
||||
>
|
||||
{dataType}
|
||||
{value.dataType}
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
{tagValue.includes(label) && <Check size={14} />}
|
||||
</section>
|
||||
</div>
|
||||
<section className={cx('type-tag', value.type)}>
|
||||
<div className="dot" />
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="visible"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{value.type}
|
||||
</Typography>
|
||||
</section>
|
||||
</section>
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip title={label} placement="topLeft">
|
||||
<div className="container-without-tag">
|
||||
<section className="left">
|
||||
<div className="dot" />
|
||||
<div className={cx('value', option)}>
|
||||
<Typography
|
||||
{...labelTextStyle}
|
||||
size="base"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="ellipsis"
|
||||
>
|
||||
{`${label}`}
|
||||
</Typography>
|
||||
</div>
|
||||
</section>
|
||||
<section className="right">
|
||||
{dataType && (
|
||||
<div className="data-type">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="p"
|
||||
textOverflow="visible"
|
||||
>
|
||||
{dataType}
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
{tagValue.includes(label) && <Check size={14} />}
|
||||
</section>
|
||||
</div>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import {
|
||||
getResourcePanel,
|
||||
getResourceVerbs,
|
||||
RESOURCE_ORDER,
|
||||
} from '../permissions.config';
|
||||
|
||||
describe('ingestion permissions in the roles editor', () => {
|
||||
it('lists both entities', () => {
|
||||
expect(RESOURCE_ORDER).toContain('ingestion-key');
|
||||
expect(RESOURCE_ORDER).toContain('ingestion-limit');
|
||||
expect(getResourcePanel('ingestion-key').label).toBe('Ingestion Keys');
|
||||
expect(getResourcePanel('ingestion-limit').label).toBe('Ingestion Limits');
|
||||
});
|
||||
|
||||
it('offers every metaresource verb for ingestion-key', () => {
|
||||
expect([...getResourceVerbs('ingestion-key')].sort()).toStrictEqual([
|
||||
'attach',
|
||||
'create',
|
||||
'delete',
|
||||
'detach',
|
||||
'list',
|
||||
'read',
|
||||
'update',
|
||||
]);
|
||||
});
|
||||
|
||||
it('offers no attach or detach for ingestion-limit', () => {
|
||||
expect([...getResourceVerbs('ingestion-limit')].sort()).toStrictEqual([
|
||||
'create',
|
||||
'delete',
|
||||
'list',
|
||||
'read',
|
||||
'update',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -329,19 +329,15 @@ describe('transformTransactionGroupsToResourcePermissions', () => {
|
||||
it('returns all resources from RESOURCE_ORDER even with empty transaction groups', () => {
|
||||
const result = transformTransactionGroupsToResourcePermissions([]);
|
||||
|
||||
expect(result).toHaveLength(19);
|
||||
expect(result).toHaveLength(15);
|
||||
expect(result.map((r) => r.resourceKind)).toStrictEqual([
|
||||
'factor-api-key',
|
||||
'auth-domain',
|
||||
'dashboard',
|
||||
'ingestion-key',
|
||||
'ingestion-limit',
|
||||
'license',
|
||||
'logs',
|
||||
'meter-metrics',
|
||||
'metrics',
|
||||
'notification-channel',
|
||||
'organization',
|
||||
'factor-password',
|
||||
'quick-filter',
|
||||
'role',
|
||||
@@ -430,19 +426,15 @@ describe('createEmptyRolePermissions', () => {
|
||||
it('creates permissions for all resources in RESOURCE_ORDER', () => {
|
||||
const result = createEmptyRolePermissions();
|
||||
|
||||
expect(result).toHaveLength(19);
|
||||
expect(result).toHaveLength(15);
|
||||
expect(result.map((r) => r.resourceKind)).toStrictEqual([
|
||||
'factor-api-key',
|
||||
'auth-domain',
|
||||
'dashboard',
|
||||
'ingestion-key',
|
||||
'ingestion-limit',
|
||||
'license',
|
||||
'logs',
|
||||
'meter-metrics',
|
||||
'metrics',
|
||||
'notification-channel',
|
||||
'organization',
|
||||
'factor-password',
|
||||
'quick-filter',
|
||||
'role',
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
Bot,
|
||||
Building,
|
||||
Cable,
|
||||
ChartLine,
|
||||
DraftingCompass,
|
||||
@@ -9,7 +8,6 @@ import {
|
||||
Grid3X3,
|
||||
Key,
|
||||
ListFilter,
|
||||
LogIn,
|
||||
Logs,
|
||||
Receipt,
|
||||
Shield,
|
||||
@@ -167,37 +165,6 @@ export const RESOURCE_PANELS: Record<AuthZResource, ResourcePanelConfig> = {
|
||||
'Type password ID, separate multiple with comma or space',
|
||||
docsAnchor: 'factor-password',
|
||||
},
|
||||
'ingestion-key': {
|
||||
label: 'Ingestion Keys',
|
||||
description: 'Keys used to send telemetry to the workspace.',
|
||||
icon: Key,
|
||||
selectorPlaceholder:
|
||||
'Type ingestion key ID, separate multiple with comma or space',
|
||||
docsAnchor: 'ingestion-key',
|
||||
},
|
||||
'ingestion-limit': {
|
||||
label: 'Ingestion Limits',
|
||||
description: 'Daily and per-second limits set on ingestion keys.',
|
||||
icon: Gauge,
|
||||
selectorPlaceholder:
|
||||
'Type ingestion limit ID, separate multiple with comma or space',
|
||||
docsAnchor: 'ingestion-limit',
|
||||
},
|
||||
'auth-domain': {
|
||||
label: 'Auth Domains',
|
||||
description: 'SSO domains and the roles they grant at sign-in.',
|
||||
icon: LogIn,
|
||||
selectorPlaceholder:
|
||||
'Type auth domain ID, separate multiple with comma or space',
|
||||
docsAnchor: 'auth-domain',
|
||||
},
|
||||
organization: {
|
||||
label: 'Organization',
|
||||
description: 'The workspace organization and its display name.',
|
||||
icon: Building,
|
||||
selectorPlaceholder: 'Type * to cover the workspace organization',
|
||||
docsAnchor: 'organization',
|
||||
},
|
||||
};
|
||||
|
||||
export const RESOURCE_ORDER = (
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useCallback } from 'react';
|
||||
import MultiSelectFilter from 'components/ListFilter/FilterZone/MultiSelectFilter';
|
||||
|
||||
import { SERVICE_ACCOUNTS_STATUS_OPTIONS } from './list.config';
|
||||
@@ -11,34 +10,15 @@ interface Props {
|
||||
setDraft: (newDraft: string) => void;
|
||||
}
|
||||
|
||||
// Picks splice into the draft and run when the dropdown closes; a tag's × or
|
||||
// Clear runs at once. A status term the box holds with another operator shows
|
||||
// as nothing picked.
|
||||
// Picks splice into the draft and run when the dropdown closes; Clear runs at
|
||||
// once. A status term the box holds with another operator shows as nothing
|
||||
// picked.
|
||||
function ServiceAccountStatusFilter({
|
||||
draft,
|
||||
disabled,
|
||||
onApplyDraft,
|
||||
setDraft,
|
||||
}: Props): JSX.Element {
|
||||
const handleChange = useCallback(
|
||||
(statuses: string[]): void => setDraft(withStatuses(draft, statuses)),
|
||||
[draft, setDraft],
|
||||
);
|
||||
|
||||
const handleCommit = useCallback(
|
||||
(statuses: string[]): void => onApplyDraft(withStatuses(draft, statuses)),
|
||||
[draft, onApplyDraft],
|
||||
);
|
||||
|
||||
const handleDropdownVisibleChange = useCallback(
|
||||
(isOpen: boolean): void => {
|
||||
if (!isOpen) {
|
||||
onApplyDraft(draft);
|
||||
}
|
||||
},
|
||||
[draft, onApplyDraft],
|
||||
);
|
||||
|
||||
return (
|
||||
<MultiSelectFilter
|
||||
value={statusesOfQuery(draft)}
|
||||
@@ -46,9 +26,13 @@ function ServiceAccountStatusFilter({
|
||||
placeholder="Status"
|
||||
testId="sa-filter-status"
|
||||
disabled={disabled}
|
||||
onChange={handleChange}
|
||||
onCommit={handleCommit}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
onChange={(statuses): void => setDraft(withStatuses(draft, statuses))}
|
||||
onClear={(): void => onApplyDraft(withStatuses(draft, []))}
|
||||
onDropdownVisibleChange={(open): void => {
|
||||
if (!open) {
|
||||
onApplyDraft(draft);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ import { GlobalShortcuts } from 'constants/shortcuts/globalShortcuts';
|
||||
import { USER_PREFERENCES } from 'constants/userPreferences';
|
||||
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
|
||||
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
|
||||
import useComponentPermission from 'hooks/useComponentPermission';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
@@ -614,7 +615,14 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
|
||||
changelog,
|
||||
]);
|
||||
|
||||
const settingsRoute = ROUTES.ORG_SETTINGS;
|
||||
const [isCurrentOrgSettings] = useComponentPermission(
|
||||
['current_org_settings'],
|
||||
user.role,
|
||||
);
|
||||
|
||||
const settingsRoute = isCurrentOrgSettings
|
||||
? ROUTES.ORG_SETTINGS
|
||||
: ROUTES.SETTINGS;
|
||||
|
||||
const handleMenuItemClick = (event: MouseEvent, item: SidebarItem): void => {
|
||||
if (item.key === ROUTES.SETTINGS) {
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
SettingsNavSection,
|
||||
SidebarItem,
|
||||
} from './sideNav.types';
|
||||
import { Style } from '@signozhq/design-tokens';
|
||||
import Noz from 'components/Noz/Noz';
|
||||
import { NOZ_TOOLTIP_TITLE } from 'components/Noz/Noz.constants';
|
||||
|
||||
@@ -522,7 +523,7 @@ export const getUserSettingsDropdownMenuItems = ({
|
||||
type: 'item',
|
||||
value: 'workspace',
|
||||
label: USER_SETTINGS_MENU_LABELS.workspace,
|
||||
prefix: <Building2 size={14} color="var(--l1-foreground)" />,
|
||||
prefix: <Building2 size={14} color={Style.L1_FOREGROUND} />,
|
||||
testId: 'workspace-settings-nav-item',
|
||||
disabled: isWorkspaceBlocked,
|
||||
disabledTooltip: WORKSPACE_LOCKED_TOOLTIP,
|
||||
@@ -532,7 +533,7 @@ export const getUserSettingsDropdownMenuItems = ({
|
||||
type: 'item',
|
||||
value: 'account',
|
||||
label: USER_SETTINGS_MENU_LABELS.account,
|
||||
prefix: <User size={14} color="var(--l1-foreground)" />,
|
||||
prefix: <User size={14} color={Style.L1_FOREGROUND} />,
|
||||
testId: 'account-settings-nav-item',
|
||||
onClick: (event): void => onSelect('account', event),
|
||||
},
|
||||
@@ -543,7 +544,7 @@ export const getUserSettingsDropdownMenuItems = ({
|
||||
type: 'item',
|
||||
value: 'license',
|
||||
label: USER_SETTINGS_MENU_LABELS.license,
|
||||
prefix: <Shield size={14} color="var(--l1-foreground)" />,
|
||||
prefix: <Shield size={14} color={Style.L1_FOREGROUND} />,
|
||||
testId: 'manage-license-nav-item',
|
||||
onClick: (event): void => onSelect('license', event),
|
||||
});
|
||||
@@ -553,7 +554,7 @@ export const getUserSettingsDropdownMenuItems = ({
|
||||
type: 'item',
|
||||
value: 'keyboard-shortcuts',
|
||||
label: USER_SETTINGS_MENU_LABELS['keyboard-shortcuts'],
|
||||
prefix: <Keyboard size={14} color="var(--l1-foreground)" />,
|
||||
prefix: <Keyboard size={14} color={Style.L1_FOREGROUND} />,
|
||||
testId: 'keyboard-shortcuts-nav-item',
|
||||
onClick: (event): void => onSelect('keyboard-shortcuts', event),
|
||||
});
|
||||
|
||||
@@ -7,7 +7,8 @@ import {
|
||||
useState,
|
||||
} from 'react';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { Form, FormInstance } from 'antd';
|
||||
import { Form } from 'antd';
|
||||
import { FormInstance } from 'antd/lib';
|
||||
import { useUpdateAccount } from 'api/generated/services/cloudintegration';
|
||||
import { CloudAccount } from 'container/Integrations/CloudIntegration/AmazonWebServices/types';
|
||||
import { INTEGRATION_TYPES } from 'container/Integrations/constants';
|
||||
|
||||
@@ -7,7 +7,8 @@ import {
|
||||
useState,
|
||||
} from 'react';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { Form, FormInstance } from 'antd';
|
||||
import { Form } from 'antd';
|
||||
import { FormInstance } from 'antd/lib';
|
||||
import { useUpdateAccount } from 'api/generated/services/cloudintegration';
|
||||
import { INTEGRATION_TYPES } from 'container/Integrations/constants';
|
||||
import { CloudAccount } from 'container/Integrations/types';
|
||||
|
||||
@@ -7,7 +7,8 @@ import {
|
||||
useState,
|
||||
} from 'react';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { Form, FormInstance } from 'antd';
|
||||
import { Form } from 'antd';
|
||||
import { FormInstance } from 'antd/lib';
|
||||
import { useUpdateAccount } from 'api/generated/services/cloudintegration';
|
||||
import { INTEGRATION_TYPES } from 'container/Integrations/constants';
|
||||
import { CloudAccount } from 'container/Integrations/types';
|
||||
|
||||
@@ -5,6 +5,7 @@ import useComponentPermission from './useComponentPermission';
|
||||
|
||||
describe('useComponentPermission', () => {
|
||||
const componentList: ComponentTypes[] = [
|
||||
'current_org_settings',
|
||||
'create_new_dashboards',
|
||||
'import_dashboard',
|
||||
'export_dashboard',
|
||||
@@ -26,6 +27,7 @@ describe('useComponentPermission', () => {
|
||||
useComponentPermission(componentList, 'ADMIN'),
|
||||
);
|
||||
const expectedResult = [
|
||||
true, // current_org_settings
|
||||
true, // create_new_dashboards
|
||||
true, // import_dashboard
|
||||
true, // export_dashboard
|
||||
@@ -49,6 +51,7 @@ describe('useComponentPermission', () => {
|
||||
useComponentPermission(componentList, 'EDITOR'),
|
||||
);
|
||||
const expectedResult = [
|
||||
false, // current_org_settings
|
||||
true, // create_new_dashboards
|
||||
true, // import_dashboard
|
||||
true, // export_dashboard
|
||||
@@ -72,6 +75,7 @@ describe('useComponentPermission', () => {
|
||||
useComponentPermission(componentList, 'VIEWER'),
|
||||
);
|
||||
const expectedResult = [
|
||||
false, // current_org_settings
|
||||
false, // create_new_dashboards
|
||||
false, // import_dashboard
|
||||
true, // export_dashboard
|
||||
|
||||
@@ -18,7 +18,6 @@ import 'lib/monaco/loader';
|
||||
import './ReactI18';
|
||||
|
||||
import 'styles.scss';
|
||||
import 'lib/uPlotStylesheet';
|
||||
|
||||
installTranslationResilience();
|
||||
configureOverlayScrollbars();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CircleSlash2 } from '@signozhq/icons';
|
||||
|
||||
import styles from './PermissionDeniedFullPage.module.scss';
|
||||
import { Style } from '@signozhq/design-tokens';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
import { formatPermission } from 'lib/authz/hooks/useAuthZ/utils';
|
||||
@@ -30,7 +31,7 @@ function PermissionDeniedFullPage({
|
||||
<div className={styles.container}>
|
||||
<div className={styles.content}>
|
||||
<span className={styles.icon}>
|
||||
<CircleSlash2 color="var(--callout-error-title)" size={14} />
|
||||
<CircleSlash2 color={Style.CALLOUT_ERROR_TITLE} size={14} />
|
||||
</span>
|
||||
<p className={styles.title}>Uh-oh! You are not authorized</p>
|
||||
<p className={styles.subtitle}>
|
||||
|
||||
@@ -3,19 +3,6 @@ export default {
|
||||
status: 'success',
|
||||
data: {
|
||||
resources: [
|
||||
{
|
||||
kind: 'auth-domain',
|
||||
type: 'metaresource',
|
||||
allowedVerbs: [
|
||||
'attach',
|
||||
'create',
|
||||
'delete',
|
||||
'detach',
|
||||
'list',
|
||||
'read',
|
||||
'update',
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'dashboard',
|
||||
type: 'metaresource',
|
||||
@@ -31,24 +18,6 @@ export default {
|
||||
type: 'metaresource',
|
||||
allowedVerbs: ['create', 'list', 'read'],
|
||||
},
|
||||
{
|
||||
kind: 'ingestion-key',
|
||||
type: 'metaresource',
|
||||
allowedVerbs: [
|
||||
'attach',
|
||||
'create',
|
||||
'delete',
|
||||
'detach',
|
||||
'list',
|
||||
'read',
|
||||
'update',
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'ingestion-limit',
|
||||
type: 'metaresource',
|
||||
allowedVerbs: ['create', 'delete', 'list', 'read', 'update'],
|
||||
},
|
||||
{
|
||||
kind: 'license',
|
||||
type: 'metaresource',
|
||||
@@ -82,11 +51,6 @@ export default {
|
||||
type: 'metaresource',
|
||||
allowedVerbs: ['create', 'delete', 'list', 'read', 'update'],
|
||||
},
|
||||
{
|
||||
kind: 'organization',
|
||||
type: 'organization',
|
||||
allowedVerbs: ['read', 'update'],
|
||||
},
|
||||
{
|
||||
kind: 'role',
|
||||
type: 'role',
|
||||
@@ -157,13 +121,12 @@ export default {
|
||||
list: ['metaresource', 'role', 'serviceaccount', 'user'],
|
||||
read: [
|
||||
'metaresource',
|
||||
'organization',
|
||||
'role',
|
||||
'serviceaccount',
|
||||
'telemetryresource',
|
||||
'user',
|
||||
],
|
||||
update: ['metaresource', 'organization', 'role', 'serviceaccount', 'user'],
|
||||
update: ['metaresource', 'role', 'serviceaccount', 'user'],
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { BrandedPermission } from '../types';
|
||||
import { buildPermission } from '../utils';
|
||||
|
||||
export const AuthDomainListPermission = buildPermission(
|
||||
'list',
|
||||
'auth-domain:*',
|
||||
);
|
||||
|
||||
export const buildAuthDomainDeletePermission = (
|
||||
id: string,
|
||||
): BrandedPermission => buildPermission('delete', `auth-domain:${id}`);
|
||||
@@ -1,35 +0,0 @@
|
||||
import { formatPermission } from '../utils';
|
||||
import {
|
||||
AuthDomainListPermission,
|
||||
buildAuthDomainDeletePermission,
|
||||
} from './auth-domain.permissions';
|
||||
import {
|
||||
buildOrganizationReadPermission,
|
||||
buildOrganizationUpdatePermission,
|
||||
} from './organization.permissions';
|
||||
|
||||
describe('auth domain permissions', () => {
|
||||
it('checks list on the collection wildcard', () => {
|
||||
expect(formatPermission(AuthDomainListPermission)).toBe('list:auth-domain:*');
|
||||
});
|
||||
|
||||
it('checks delete on the given domain id', () => {
|
||||
expect(formatPermission(buildAuthDomainDeletePermission('domain-1'))).toBe(
|
||||
'delete:auth-domain:domain-1',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('organization permissions', () => {
|
||||
it('checks read on the given org id', () => {
|
||||
expect(formatPermission(buildOrganizationReadPermission('org-1'))).toBe(
|
||||
'read:organization:org-1',
|
||||
);
|
||||
});
|
||||
|
||||
it('checks update on the given org id', () => {
|
||||
expect(formatPermission(buildOrganizationUpdatePermission('org-1'))).toBe(
|
||||
'update:organization:org-1',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { BrandedPermission } from '../types';
|
||||
import { buildPermission } from '../utils';
|
||||
|
||||
export const IngestionKeyListPermission = buildPermission(
|
||||
'list',
|
||||
'ingestion-key:*',
|
||||
);
|
||||
|
||||
export const IngestionKeyCreatePermission = buildPermission(
|
||||
'create',
|
||||
'ingestion-key:*',
|
||||
);
|
||||
|
||||
export const buildIngestionKeyUpdatePermission = (
|
||||
keyId: string,
|
||||
): BrandedPermission => buildPermission('update', `ingestion-key:${keyId}`);
|
||||
|
||||
export const buildIngestionKeyDeletePermission = (
|
||||
keyId: string,
|
||||
): BrandedPermission => buildPermission('delete', `ingestion-key:${keyId}`);
|
||||
|
||||
export const buildIngestionKeyAttachPermission = (
|
||||
keyId: string,
|
||||
): BrandedPermission => buildPermission('attach', `ingestion-key:${keyId}`);
|
||||
|
||||
export const buildIngestionKeyDetachPermission = (
|
||||
keyId: string,
|
||||
): BrandedPermission => buildPermission('detach', `ingestion-key:${keyId}`);
|
||||
|
||||
export const IngestionLimitCreatePermission = buildPermission(
|
||||
'create',
|
||||
'ingestion-limit:*',
|
||||
);
|
||||
export const buildIngestionLimitUpdatePermission = (
|
||||
id: string,
|
||||
): BrandedPermission => buildPermission('update', `ingestion-limit:${id}`);
|
||||
|
||||
export const buildIngestionLimitDeletePermission = (
|
||||
id: string,
|
||||
): BrandedPermission => buildPermission('delete', `ingestion-limit:${id}`);
|
||||
@@ -1,10 +0,0 @@
|
||||
import { BrandedPermission } from '../types';
|
||||
import { buildPermission } from '../utils';
|
||||
|
||||
export const buildOrganizationReadPermission = (
|
||||
id: string,
|
||||
): BrandedPermission => buildPermission('read', `organization:${id}`);
|
||||
|
||||
export const buildOrganizationUpdatePermission = (
|
||||
id: string,
|
||||
): BrandedPermission => buildPermission('update', `organization:${id}`);
|
||||
@@ -1,7 +0,0 @@
|
||||
import href from 'uplot/dist/uPlot.min.css?url';
|
||||
|
||||
// Appended to the end of <body> so uPlot's rules win ties over the app's stylesheets.
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = href;
|
||||
document.body.appendChild(link);
|
||||
@@ -12,7 +12,6 @@ import { getFiltersFromKeyValue } from '../CeleryOverviewUtils';
|
||||
import OverviewRightPanelGraph from './OverviewRightPanelGraph';
|
||||
import ValueInfo from './ValueInfo';
|
||||
|
||||
import 'components/CeleryTask/CeleryTaskDetail/CeleryTaskDetail.style.scss';
|
||||
import './CeleryOverviewDetails.styles.scss';
|
||||
|
||||
export default function CeleryOverviewDetails({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { FullScreenHandle } from 'react-full-screen';
|
||||
import { buildRoutePath } from 'lib/router/buildRoutePath';
|
||||
import {
|
||||
@@ -26,19 +26,21 @@ import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
|
||||
import AuthZDropdown from 'lib/authz/components/AuthZDropdown/AuthZDropdown';
|
||||
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
|
||||
import type {
|
||||
AuthZDropdownItemType,
|
||||
AuthZGroupChildType,
|
||||
} from 'lib/authz/components/AuthZDropdown/types';
|
||||
import { blockedBy } from 'lib/authz/components/AuthZDropdown/utils';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import { DashboardCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
|
||||
import DashboardSettings from '../../DashboardSettings';
|
||||
import { useAddSection } from '../../PanelsAndSectionsLayout/Section/hooks/useAddSection';
|
||||
import SectionTitleModal from '../../PanelsAndSectionsLayout/Section/SectionTitleModal';
|
||||
import JsonEditorDrawer from '../JsonEditorDrawer/JsonEditorDrawer';
|
||||
import SettingsDrawer from '../SettingsDrawer';
|
||||
import styles from './DashboardActions.module.scss';
|
||||
import { useDeleteDashboardAction } from './useDeleteDashboardAction';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
|
||||
|
||||
interface DashboardActionsProps {
|
||||
title: string;
|
||||
@@ -66,13 +68,14 @@ function DashboardActions({
|
||||
deleteChecks,
|
||||
deleteDisabledTooltip,
|
||||
} = useDashboardEditContext();
|
||||
const settingsRequest = useDashboardStore((s) => s.settingsRequest);
|
||||
const clearSettingsRequest = useDashboardStore((s) => s.clearSettingsRequest);
|
||||
const actionControls = useDashboardControlGroup('dashboardActions');
|
||||
const requestSettings = useDashboardStore((s) => s.requestSettings);
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const { showErrorModal } = useErrorModal();
|
||||
const { disabledTooltip: lockDisabledTooltip } = useDashboardLockPermission({
|
||||
dashboardId: dashboard.id,
|
||||
source: dashboard.source,
|
||||
enabled: actionControls.lock,
|
||||
});
|
||||
|
||||
// Cloning creates a new dashboard, so it needs `create` too, and no lock gate.
|
||||
@@ -81,8 +84,6 @@ function DashboardActions({
|
||||
[editChecks],
|
||||
);
|
||||
|
||||
const [isSettingsDrawerOpen, setIsSettingsDrawerOpen] =
|
||||
useState<boolean>(false);
|
||||
const [isJsonEditorOpen, setIsJsonEditorOpen] = useState<boolean>(false);
|
||||
const [isCloning, setIsCloning] = useState<boolean>(false);
|
||||
const [isNewSectionOpen, setIsNewSectionOpen] = useState<boolean>(false);
|
||||
@@ -94,14 +95,6 @@ function DashboardActions({
|
||||
panelCount: Object.keys(dashboard.spec.panels).length,
|
||||
});
|
||||
|
||||
// Open the settings drawer when something in the tree requests it (e.g. the
|
||||
// variables bar's "Add variable" button).
|
||||
useEffect(() => {
|
||||
if (settingsRequest) {
|
||||
setIsSettingsDrawerOpen(true);
|
||||
}
|
||||
}, [settingsRequest]);
|
||||
|
||||
const { addSection, isSaving: isAddingSection } = useAddSection({
|
||||
layouts: dashboard.spec.layouts,
|
||||
});
|
||||
@@ -143,8 +136,8 @@ function DashboardActions({
|
||||
void logEvent(DashboardDetailEvents.SettingsOpened, {
|
||||
dashboardId: dashboard.id,
|
||||
});
|
||||
setIsSettingsDrawerOpen(true);
|
||||
}, [dashboard.id]);
|
||||
requestSettings({ tab: 'Overview' });
|
||||
}, [dashboard.id, requestSettings]);
|
||||
|
||||
const handleOpenJsonEditor = useCallback((): void => {
|
||||
void logEvent(DashboardDetailEvents.JsonEditorOpened, {
|
||||
@@ -162,61 +155,68 @@ function DashboardActions({
|
||||
void handle.enter();
|
||||
}, [dashboard.id, handle]);
|
||||
|
||||
// Unavailable items stay in the menu, carrying the reason.
|
||||
const menuItems = useMemo<AuthZDropdownItemType[]>(
|
||||
() => [
|
||||
{
|
||||
type: 'group',
|
||||
value: 'group-dashboard',
|
||||
label: 'Dashboard',
|
||||
items: [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'rename',
|
||||
testId: 'dashboard-action-rename',
|
||||
label: 'Rename',
|
||||
prefix: <PenLine size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(editDisabledTooltip),
|
||||
onClick: onOpenRename,
|
||||
},
|
||||
// Clone creates a new dashboard, so it's not lock-gated.
|
||||
{
|
||||
type: 'item',
|
||||
value: 'clone',
|
||||
testId: 'dashboard-action-clone',
|
||||
label: 'Clone dashboard',
|
||||
prefix: <Copy size={14} />,
|
||||
checks: cloneChecks,
|
||||
loading: isCloning,
|
||||
loadingTooltip: 'Cloning dashboard',
|
||||
onClick: (): void => void handleClone(),
|
||||
},
|
||||
{
|
||||
type: 'item',
|
||||
value: 'lock',
|
||||
testId: 'dashboard-action-lock',
|
||||
label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',
|
||||
prefix: <LockKeyhole size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(lockDisabledTooltip),
|
||||
onClick: onLockToggle,
|
||||
},
|
||||
{
|
||||
type: 'item',
|
||||
value: 'fullscreen',
|
||||
testId: 'dashboard-action-fullscreen',
|
||||
label: 'Full screen',
|
||||
prefix: <Fullscreen size={14} />,
|
||||
onClick: handleEnterFullScreen,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
value: 'group-layout',
|
||||
label: 'Layout',
|
||||
items: [
|
||||
// Unavailable items stay in the menu, carrying the reason; hidden ones are dropped.
|
||||
const menuItems = useMemo<AuthZDropdownItemType[]>(() => {
|
||||
const dashboardItems: AuthZGroupChildType[] = [
|
||||
...(actionControls.rename
|
||||
? [
|
||||
{
|
||||
type: 'item' as const,
|
||||
value: 'rename',
|
||||
testId: 'dashboard-action-rename',
|
||||
label: 'Rename',
|
||||
prefix: <PenLine size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(editDisabledTooltip),
|
||||
onClick: onOpenRename,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Clone creates a new dashboard, so it's not lock-gated.
|
||||
...(actionControls.clone
|
||||
? [
|
||||
{
|
||||
type: 'item' as const,
|
||||
value: 'clone',
|
||||
testId: 'dashboard-action-clone',
|
||||
label: 'Clone dashboard',
|
||||
prefix: <Copy size={14} />,
|
||||
checks: cloneChecks,
|
||||
loading: isCloning,
|
||||
loadingTooltip: 'Cloning dashboard',
|
||||
onClick: (): void => void handleClone(),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(actionControls.lock
|
||||
? [
|
||||
{
|
||||
type: 'item' as const,
|
||||
value: 'lock',
|
||||
testId: 'dashboard-action-lock',
|
||||
label: isDashboardLocked ? 'Unlock dashboard' : 'Lock dashboard',
|
||||
prefix: <LockKeyhole size={14} />,
|
||||
checks: editChecks,
|
||||
...blockedBy(lockDisabledTooltip),
|
||||
onClick: onLockToggle,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(actionControls.fullscreen
|
||||
? [
|
||||
{
|
||||
type: 'item' as const,
|
||||
value: 'fullscreen',
|
||||
testId: 'dashboard-action-fullscreen',
|
||||
label: 'Full screen',
|
||||
prefix: <Fullscreen size={14} />,
|
||||
onClick: handleEnterFullScreen,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const layoutItems: AuthZGroupChildType[] = actionControls.newSection
|
||||
? [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'new-section',
|
||||
@@ -227,101 +227,124 @@ function DashboardActions({
|
||||
...blockedBy(editDisabledTooltip),
|
||||
onClick: (): void => setIsNewSectionOpen(true),
|
||||
},
|
||||
],
|
||||
},
|
||||
{ type: 'separator', value: 'divider-danger' },
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete',
|
||||
testId: 'dashboard-action-delete',
|
||||
label: 'Delete dashboard',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
checks: deleteChecks,
|
||||
// Independent of read/update, but a locked dashboard can't be removed.
|
||||
...blockedBy(deleteDisabledTooltip),
|
||||
onClick: confirmDeleteDashboard,
|
||||
},
|
||||
],
|
||||
[
|
||||
editChecks,
|
||||
editDisabledTooltip,
|
||||
deleteChecks,
|
||||
deleteDisabledTooltip,
|
||||
cloneChecks,
|
||||
isCloning,
|
||||
lockDisabledTooltip,
|
||||
isDashboardLocked,
|
||||
onOpenRename,
|
||||
handleClone,
|
||||
onLockToggle,
|
||||
handleEnterFullScreen,
|
||||
confirmDeleteDashboard,
|
||||
],
|
||||
);
|
||||
]
|
||||
: [];
|
||||
|
||||
return [
|
||||
...(dashboardItems.length
|
||||
? [
|
||||
{
|
||||
type: 'group' as const,
|
||||
value: 'group-dashboard',
|
||||
label: 'Dashboard',
|
||||
items: dashboardItems,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(layoutItems.length
|
||||
? [
|
||||
{
|
||||
type: 'group' as const,
|
||||
value: 'group-layout',
|
||||
label: 'Layout',
|
||||
items: layoutItems,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(actionControls.delete
|
||||
? [
|
||||
{ type: 'separator' as const, value: 'divider-danger' },
|
||||
{
|
||||
type: 'item' as const,
|
||||
value: 'delete',
|
||||
testId: 'dashboard-action-delete',
|
||||
label: 'Delete dashboard',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
checks: deleteChecks,
|
||||
// Independent of read/update, but a locked dashboard can't be removed.
|
||||
...blockedBy(deleteDisabledTooltip),
|
||||
onClick: confirmDeleteDashboard,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
}, [
|
||||
actionControls,
|
||||
editChecks,
|
||||
editDisabledTooltip,
|
||||
deleteChecks,
|
||||
deleteDisabledTooltip,
|
||||
cloneChecks,
|
||||
isCloning,
|
||||
lockDisabledTooltip,
|
||||
isDashboardLocked,
|
||||
onOpenRename,
|
||||
handleClone,
|
||||
onLockToggle,
|
||||
handleEnterFullScreen,
|
||||
confirmDeleteDashboard,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className={styles.dashboardActionsContainer}>
|
||||
<AuthZDropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
{menuItems.length > 0 && (
|
||||
<AuthZDropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Button
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size="md"
|
||||
prefix={<Grid3X3 size="md" />}
|
||||
testId="options"
|
||||
>
|
||||
Actions
|
||||
</Button>
|
||||
</AuthZDropdown>
|
||||
)}
|
||||
{actionControls.configure && (
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
prefix={<Configure size="md" />}
|
||||
testId="actionControls-drawer"
|
||||
disabled={!isEditable}
|
||||
onClick={handleOpenSettings}
|
||||
size="md"
|
||||
>
|
||||
Configure
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
)}
|
||||
{actionControls.json && (
|
||||
<Button
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size="md"
|
||||
prefix={<Grid3X3 size="md" />}
|
||||
testId="options"
|
||||
>
|
||||
Actions
|
||||
</Button>
|
||||
</AuthZDropdown>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
prefix={<Configure size="md" />}
|
||||
testId="show-drawer"
|
||||
disabled={!isEditable}
|
||||
onClick={handleOpenSettings}
|
||||
prefix={<Braces size="md" />}
|
||||
testId="edit-json"
|
||||
onClick={handleOpenJsonEditor}
|
||||
size="md"
|
||||
>
|
||||
Configure
|
||||
JSON
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
<SettingsDrawer
|
||||
drawerTitle="Dashboard Configuration"
|
||||
isOpen={isSettingsDrawerOpen}
|
||||
destroyOnClose
|
||||
onClose={(): void => {
|
||||
setIsSettingsDrawerOpen(false);
|
||||
clearSettingsRequest();
|
||||
}}
|
||||
>
|
||||
<DashboardSettings dashboard={dashboard} />
|
||||
</SettingsDrawer>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
prefix={<Braces size="md" />}
|
||||
testId="edit-json"
|
||||
onClick={handleOpenJsonEditor}
|
||||
size="md"
|
||||
>
|
||||
JSON
|
||||
</Button>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={onAddPanel}
|
||||
prefix={<Plus size="md" />}
|
||||
testId="add-panel-header"
|
||||
disabled={!isEditable}
|
||||
size="md"
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
)}
|
||||
{actionControls.newPanel && (
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={onAddPanel}
|
||||
prefix={<Plus size="md" />}
|
||||
testId="add-panel-header"
|
||||
disabled={!isEditable}
|
||||
size="md"
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
)}
|
||||
<JsonEditorDrawer
|
||||
dashboard={dashboard}
|
||||
isOpen={isJsonEditorOpen}
|
||||
|
||||
@@ -23,12 +23,14 @@ import { openInNewTab } from 'utils/navigation';
|
||||
import styles from './DashboardInfo.module.scss';
|
||||
|
||||
import TagsOverflowTooltip from './TagsOverflowTooltip';
|
||||
import { getLockTooltip } from './utils';
|
||||
import { DASHBOARD_NAME_MAX_LENGTH } from '../../constants';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControlGroup } from '../../controls/useDashboardControlGroup';
|
||||
|
||||
// The tag cluster keeps a fixed footprint so a long title ellipsizes around it
|
||||
// instead of collapsing the tags: show up to two tags, then a `+N` overflow badge.
|
||||
// instead of collapsing the tags: titleControls up to two tags, then a `+N` overflow badge.
|
||||
const MAX_VISIBLE_TAGS = 2;
|
||||
|
||||
interface DashboardInfoProps {
|
||||
@@ -74,27 +76,19 @@ function DashboardInfo({
|
||||
}: DashboardInfoProps): JSX.Element {
|
||||
const { isEditable: canEdit } = useDashboardEditContext();
|
||||
const dashboardId = useDashboardStore((s) => s.dashboardId);
|
||||
const titleControls = useDashboardControlGroup('title');
|
||||
|
||||
const hasTags = tags.length > 0;
|
||||
const hasDescription = !isEmpty(description);
|
||||
const hasTags = titleControls.tags && tags.length > 0;
|
||||
const hasDescription = titleControls.description && !isEmpty(description);
|
||||
|
||||
const visibleTags = tags.slice(0, MAX_VISIBLE_TAGS);
|
||||
const remainingTags = tags.slice(MAX_VISIBLE_TAGS);
|
||||
|
||||
// Without a toggle, say why it can't be toggled rather than only restating the
|
||||
// lock state.
|
||||
let lockTooltip: string;
|
||||
if (onToggleLock) {
|
||||
lockTooltip = isDashboardLocked
|
||||
? 'Locked — click to unlock'
|
||||
: 'Unlocked — click to lock';
|
||||
} else if (lockDisabledTooltip) {
|
||||
lockTooltip = lockDisabledTooltip;
|
||||
} else {
|
||||
lockTooltip = isDashboardLocked
|
||||
? 'This dashboard is locked'
|
||||
: 'This dashboard is unlocked';
|
||||
}
|
||||
const lockTooltip = getLockTooltip({
|
||||
isLocked: isDashboardLocked,
|
||||
canToggle: !!onToggleLock,
|
||||
disabledReason: lockDisabledTooltip,
|
||||
});
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
|
||||
if (event.key === 'Enter') {
|
||||
@@ -143,68 +137,71 @@ function DashboardInfo({
|
||||
|
||||
return (
|
||||
<div className={styles.dashboardInfo}>
|
||||
<img src={image} alt={title} className={styles.dashboardImage} />
|
||||
{titleControls.name && (
|
||||
<img src={image} alt={title} className={styles.dashboardImage} />
|
||||
)}
|
||||
|
||||
{isEditing ? (
|
||||
<div className={styles.dashboardTitleEditor} onBlur={onEditorBlur}>
|
||||
<div className={styles.dashboardTitleInput}>
|
||||
<Input
|
||||
autoFocus
|
||||
value={draft}
|
||||
testId="dashboard-title-input"
|
||||
maxLength={DASHBOARD_NAME_MAX_LENGTH}
|
||||
onChange={(e): void => onDraftChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label="Save title"
|
||||
testId="dashboard-title-save"
|
||||
onClick={onCommit}
|
||||
>
|
||||
<Check size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label="Cancel title edit"
|
||||
testId="dashboard-title-cancel"
|
||||
onClick={onCancel}
|
||||
>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{canEdit ? (
|
||||
{titleControls.name &&
|
||||
(isEditing ? (
|
||||
<div className={styles.dashboardTitleEditor} onBlur={onEditorBlur}>
|
||||
<div className={styles.dashboardTitleInput}>
|
||||
<Input
|
||||
autoFocus
|
||||
value={draft}
|
||||
testId="dashboard-title-input"
|
||||
maxLength={DASHBOARD_NAME_MAX_LENGTH}
|
||||
onChange={(e): void => onDraftChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label="Save title"
|
||||
testId="dashboard-title-save"
|
||||
onClick={onCommit}
|
||||
>
|
||||
<Check size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
onClick={onStartEdit}
|
||||
icon
|
||||
aria-label="Cancel title edit"
|
||||
testId="dashboard-title-cancel"
|
||||
onClick={onCancel}
|
||||
>
|
||||
{titleText}
|
||||
<X size={14} />
|
||||
</Button>
|
||||
) : (
|
||||
titleText
|
||||
)}
|
||||
<CopyButton
|
||||
value={dashboardId}
|
||||
ariaLabel="Copy dashboard ID"
|
||||
testId="dashboard-copy-id"
|
||||
onCopy={handleCopyId}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{canEdit ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
onClick={onStartEdit}
|
||||
>
|
||||
{titleText}
|
||||
</Button>
|
||||
) : (
|
||||
titleText
|
||||
)}
|
||||
<CopyButton
|
||||
value={dashboardId}
|
||||
ariaLabel="Copy dashboard ID"
|
||||
testId="dashboard-copy-id"
|
||||
onCopy={handleCopyId}
|
||||
/>
|
||||
</>
|
||||
))}
|
||||
|
||||
{hasDescription && (
|
||||
<Tooltip
|
||||
@@ -223,7 +220,7 @@ function DashboardInfo({
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{isPublicDashboard && (
|
||||
{titleControls.publicBadge && isPublicDashboard && (
|
||||
<Tooltip title="This dashboard is publicly accessible. Click to open the public page.">
|
||||
<Button
|
||||
type="button"
|
||||
@@ -240,7 +237,7 @@ function DashboardInfo({
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
{showLockToggle && (
|
||||
{titleControls.lock && showLockToggle && (
|
||||
<Tooltip title={onToggleLock ? lockTooltip : undefined}>
|
||||
<Button
|
||||
disabledTooltip={lockTooltip}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Without a toggle, say why it can't be toggled rather than only restating the
|
||||
// lock state.
|
||||
export function getLockTooltip({
|
||||
isLocked,
|
||||
canToggle,
|
||||
disabledReason,
|
||||
}: {
|
||||
isLocked: boolean;
|
||||
canToggle: boolean;
|
||||
disabledReason?: string;
|
||||
}): string {
|
||||
if (canToggle) {
|
||||
return isLocked ? 'Locked — click to unlock' : 'Unlocked — click to lock';
|
||||
}
|
||||
if (disabledReason) {
|
||||
return disabledReason;
|
||||
}
|
||||
return isLocked ? 'This dashboard is locked' : 'This dashboard is unlocked';
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { FullScreenHandle } from 'react-full-screen';
|
||||
import { useDashboardLockPermission } from 'hooks/dashboards/useDashboardLockPermission';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { dashboardResponse } from '../../../stories/__story_mockdata__/dashboard';
|
||||
import type { DashboardControlsInput } from '../../controls/types';
|
||||
|
||||
import { usePublicDashboardMeta } from '../../DashboardSettings/PublicDashboard/usePublicDashboardMeta';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import DashboardPageToolbar from '../index';
|
||||
|
||||
const { data: dashboard } = dashboardResponse({
|
||||
panels: 0,
|
||||
sectioned: false,
|
||||
variables: [],
|
||||
locked: true,
|
||||
});
|
||||
|
||||
const handle: FullScreenHandle = {
|
||||
active: false,
|
||||
enter: jest.fn(),
|
||||
exit: jest.fn(),
|
||||
node: { current: null },
|
||||
};
|
||||
|
||||
jest.mock('../DashboardActions/DashboardActions', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="dashboard-actions" />,
|
||||
}));
|
||||
jest.mock('../DashboardInfo/DashboardInfo', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="dashboard-info" />,
|
||||
}));
|
||||
jest.mock('../../VariablesBar/VariablesBar', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="variables-bar" />,
|
||||
}));
|
||||
jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="time-selection" />,
|
||||
}));
|
||||
jest.mock(
|
||||
'../../PanelsAndSectionsLayout/Panel/PanelTypeSelectionModal/PanelTypeSelectionModal',
|
||||
() => ({ __esModule: true, default: (): null => null }),
|
||||
);
|
||||
jest.mock('../../hooks/useCreatePanel', () => ({
|
||||
useCreatePanel: (): unknown => ({
|
||||
isPickerOpen: false,
|
||||
openPicker: jest.fn(),
|
||||
closePicker: jest.fn(),
|
||||
createPanel: jest.fn(),
|
||||
targetLayoutIndex: 0,
|
||||
}),
|
||||
}));
|
||||
jest.mock('../../hooks/useOptimisticPatch', () => ({
|
||||
useOptimisticPatch: (): unknown => ({ patchAsync: jest.fn() }),
|
||||
}));
|
||||
jest.mock('hooks/dashboards/useToggleDashboardLock', () => ({
|
||||
useToggleDashboardLock: (): unknown => ({ toggleLock: jest.fn() }),
|
||||
}));
|
||||
jest.mock('hooks/dashboards/useDashboardLockPermission', () => ({
|
||||
useDashboardLockPermission: jest.fn(() => ({
|
||||
canToggleLock: false,
|
||||
isLoading: false,
|
||||
disabledTooltip: '',
|
||||
})),
|
||||
}));
|
||||
jest.mock(
|
||||
'../../DashboardSettings/PublicDashboard/usePublicDashboardMeta',
|
||||
() => ({
|
||||
usePublicDashboardMeta: jest.fn(() => ({
|
||||
isPublic: false,
|
||||
publicMeta: undefined,
|
||||
})),
|
||||
}),
|
||||
);
|
||||
|
||||
function renderToolbar(
|
||||
ctx: { readOnly?: boolean; controls?: DashboardControlsInput } = {},
|
||||
): void {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: dashboard.id, refetch: jest.fn(), ...ctx });
|
||||
render(<DashboardPageToolbar dashboard={dashboard} handle={handle} />);
|
||||
}
|
||||
|
||||
describe('DashboardPageToolbar - controls', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders every row and checks lock + share by default', () => {
|
||||
renderToolbar();
|
||||
|
||||
expect(screen.getByTestId('dashboard-info')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('dashboard-actions')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('time-selection')).toBeInTheDocument();
|
||||
expect(jest.mocked(useDashboardLockPermission)).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ enabled: true }),
|
||||
);
|
||||
expect(jest.mocked(usePublicDashboardMeta)).toHaveBeenCalledWith(
|
||||
dashboard.id,
|
||||
{
|
||||
enabled: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('skips the lock permission check on a read-only mount', () => {
|
||||
renderToolbar({ readOnly: true });
|
||||
|
||||
expect(jest.mocked(useDashboardLockPermission)).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ enabled: false }),
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the title row and actions the host hides, and their requests', () => {
|
||||
renderToolbar({
|
||||
readOnly: true,
|
||||
controls: { title: false, dashboardActions: false },
|
||||
});
|
||||
|
||||
expect(screen.queryByTestId('dashboard-info')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('dashboard-actions')).not.toBeInTheDocument();
|
||||
expect(jest.mocked(usePublicDashboardMeta)).toHaveBeenCalledWith(
|
||||
dashboard.id,
|
||||
{
|
||||
enabled: false,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('hides the time range and keeps the variables bar mounted but hidden', () => {
|
||||
renderToolbar({
|
||||
controls: { toolbar: { timeRange: false, variables: false } },
|
||||
});
|
||||
|
||||
expect(screen.queryByTestId('time-selection')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('variables-bar')).not.toBeVisible();
|
||||
});
|
||||
|
||||
it('hides the whole toolbar when the host turns every row off', () => {
|
||||
renderToolbar({
|
||||
readOnly: true,
|
||||
controls: { title: false, dashboardActions: false, toolbar: false },
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('dashboard-page-toolbar')).not.toBeVisible();
|
||||
expect(screen.getByTestId('variables-bar')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the toolbar when only the variables bar is on', () => {
|
||||
renderToolbar({
|
||||
readOnly: true,
|
||||
controls: {
|
||||
title: false,
|
||||
dashboardActions: false,
|
||||
toolbar: { timeRange: false, autoRefresh: false, variables: true },
|
||||
},
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('dashboard-page-toolbar')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import { getAbsoluteUrl } from 'utils/basePath';
|
||||
|
||||
import { useCreatePanel } from '../hooks/useCreatePanel';
|
||||
import { useOptimisticPatch } from '../hooks/useOptimisticPatch';
|
||||
import { useDashboardControlGroup } from '../controls/useDashboardControlGroup';
|
||||
import { usePublicDashboardMeta } from '../DashboardSettings/PublicDashboard/usePublicDashboardMeta';
|
||||
import PanelTypeSelectionModal from '../PanelsAndSectionsLayout/Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
|
||||
import DashboardActions from './DashboardActions/DashboardActions';
|
||||
@@ -56,6 +57,16 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
|
||||
[dashboard.tags],
|
||||
);
|
||||
|
||||
const titleControls = useDashboardControlGroup('title');
|
||||
const actionControls = useDashboardControlGroup('dashboardActions');
|
||||
const toolbarControls = useDashboardControlGroup('toolbar');
|
||||
const hasTitleRow = Object.values(titleControls).some(Boolean);
|
||||
const hasActions = Object.values(actionControls).some(Boolean);
|
||||
const hasVisibleRows =
|
||||
hasTitleRow ||
|
||||
hasActions ||
|
||||
toolbarControls.timeRange ||
|
||||
toolbarControls.variables;
|
||||
const { showErrorModal } = useErrorModal();
|
||||
const { patchAsync } = useOptimisticPatch();
|
||||
const {
|
||||
@@ -71,10 +82,13 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
|
||||
useDashboardLockPermission({
|
||||
dashboardId: id,
|
||||
source: dashboard.source,
|
||||
enabled: titleControls.lock || actionControls.lock,
|
||||
});
|
||||
|
||||
// Public-sharing meta (deduped react-query read); drives the header globe.
|
||||
const { isPublic, publicMeta } = usePublicDashboardMeta(id);
|
||||
const { isPublic, publicMeta } = usePublicDashboardMeta(id, {
|
||||
enabled: titleControls.publicBadge,
|
||||
});
|
||||
const publicUrl = getAbsoluteUrl(publicMeta?.publicPath ?? '');
|
||||
|
||||
// Shared with the list's row menu — it owns the API call, the toast and the
|
||||
@@ -154,49 +168,71 @@ function DashboardPageToolbar(props: DashboardPageToolbarProps): JSX.Element {
|
||||
}, [id, openPicker]);
|
||||
|
||||
return (
|
||||
<section className={styles.dashboardPageToolbarContainer}>
|
||||
<div className={styles.dashboardInfoWithActions}>
|
||||
<DashboardInfo
|
||||
title={title}
|
||||
image={image}
|
||||
tags={tags}
|
||||
description={description}
|
||||
isPublicDashboard={isPublic}
|
||||
publicUrl={publicUrl}
|
||||
isDashboardLocked={isDashboardLocked}
|
||||
showLockToggle={showLockToggle}
|
||||
onToggleLock={
|
||||
canToggleLock
|
||||
? (): void => handleLockDashboardToggle('header')
|
||||
: undefined
|
||||
}
|
||||
lockDisabledTooltip={lockDisabledTooltip}
|
||||
isEditing={isEditing}
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
onStartEdit={startEdit}
|
||||
onCommit={commit}
|
||||
onCancel={cancel}
|
||||
/>
|
||||
<DashboardActions
|
||||
title={title}
|
||||
dashboard={dashboard}
|
||||
handle={handle}
|
||||
isDashboardLocked={isDashboardLocked}
|
||||
onAddPanel={onAddPanel}
|
||||
onLockToggle={(): void => handleLockDashboardToggle('menu')}
|
||||
onOpenRename={startEdit}
|
||||
/>
|
||||
</div>
|
||||
<section
|
||||
className={styles.dashboardPageToolbarContainer}
|
||||
data-testid="dashboard-page-toolbar"
|
||||
hidden={!hasVisibleRows}
|
||||
>
|
||||
{(hasTitleRow || hasActions) && (
|
||||
<div className={styles.dashboardInfoWithActions}>
|
||||
{hasTitleRow && (
|
||||
<DashboardInfo
|
||||
title={title}
|
||||
image={image}
|
||||
tags={tags}
|
||||
description={description}
|
||||
isPublicDashboard={isPublic}
|
||||
publicUrl={publicUrl}
|
||||
isDashboardLocked={isDashboardLocked}
|
||||
showLockToggle={showLockToggle}
|
||||
onToggleLock={
|
||||
canToggleLock
|
||||
? (): void => handleLockDashboardToggle('header')
|
||||
: undefined
|
||||
}
|
||||
lockDisabledTooltip={lockDisabledTooltip}
|
||||
isEditing={isEditing}
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
onStartEdit={startEdit}
|
||||
onCommit={commit}
|
||||
onCancel={cancel}
|
||||
/>
|
||||
)}
|
||||
{hasActions && (
|
||||
<DashboardActions
|
||||
title={title}
|
||||
dashboard={dashboard}
|
||||
handle={handle}
|
||||
isDashboardLocked={isDashboardLocked}
|
||||
onAddPanel={onAddPanel}
|
||||
onLockToggle={(): void => handleLockDashboardToggle('menu')}
|
||||
onOpenRename={startEdit}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Row 2: the time selector floats top-right (declared first so the
|
||||
variables bar's content wraps around it); the variables bar
|
||||
collapses to one line and, when expanded, wraps full-width under it. */}
|
||||
<div className={styles.toolbarRow}>
|
||||
<div className={styles.timeCluster}>
|
||||
<DateTimeSelectionV2 showAutoRefresh hideShareModal />
|
||||
</div>
|
||||
<VariablesBar dashboard={dashboard} />
|
||||
{toolbarControls.timeRange && (
|
||||
<div className={styles.timeCluster}>
|
||||
<DateTimeSelectionV2
|
||||
showAutoRefresh={toolbarControls.autoRefresh}
|
||||
hideShareModal
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{toolbarControls.variables ? (
|
||||
<VariablesBar dashboard={dashboard} />
|
||||
) : (
|
||||
// Still mounted: the selectors seed and auto-select the values panels query with.
|
||||
<div hidden>
|
||||
<VariablesBar dashboard={dashboard} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<PanelTypeSelectionModal
|
||||
open={isPickerOpen}
|
||||
|
||||
@@ -26,9 +26,13 @@ const PUBLIC_META_STALE_TIME = 5 * 60 * 1000;
|
||||
*/
|
||||
export function usePublicDashboardMeta(
|
||||
dashboardId: string,
|
||||
options?: { enabled?: boolean },
|
||||
): UsePublicDashboardMetaReturn {
|
||||
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
|
||||
const enabled = !!dashboardId && (isCloudUser || isEnterpriseSelfHostedUser);
|
||||
const enabled =
|
||||
(options?.enabled ?? true) &&
|
||||
!!dashboardId &&
|
||||
(isCloudUser || isEnterpriseSelfHostedUser);
|
||||
|
||||
const { data, isLoading, isFetching, error, refetch } = useGetPublicDashboard(
|
||||
{ id: dashboardId },
|
||||
|
||||
@@ -2,33 +2,17 @@ import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useContextLinkVariables } from '../useContextLinkVariables';
|
||||
|
||||
const mockUseGetDashboardV2 = jest.fn();
|
||||
const mockUseDashboardVariableNames = jest.fn();
|
||||
const mockUseQueryBuilder = jest.fn();
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/store/useDashboardStore',
|
||||
() => ({
|
||||
useDashboardStore: (
|
||||
selector: (s: { dashboardId: string }) => unknown,
|
||||
): unknown => selector({ dashboardId: 'dash-1' }),
|
||||
}),
|
||||
);
|
||||
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: (): unknown => mockUseQueryBuilder(),
|
||||
}));
|
||||
|
||||
jest.mock('api/generated/services/dashboard', () => ({
|
||||
useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
|
||||
}));
|
||||
|
||||
// dtoToFormModel is exercised by its own suite; here we only need it to surface a name.
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableAdapters',
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardVariableNames',
|
||||
() => ({
|
||||
dtoToFormModel: (dto: { name: string }): { name: string } => ({
|
||||
name: dto.name,
|
||||
}),
|
||||
useDashboardVariableNames: (): unknown => mockUseDashboardVariableNames(),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -45,11 +29,7 @@ describe('useContextLinkVariables', () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
mockUseGetDashboardV2.mockReturnValue({
|
||||
data: {
|
||||
data: { spec: { variables: [{ name: 'region' }, { name: 'tier' }] } },
|
||||
},
|
||||
});
|
||||
mockUseDashboardVariableNames.mockReturnValue(['region', 'tier']);
|
||||
});
|
||||
|
||||
it('orders globals, then _prefixed query fields (deduped), then dashboard vars', () => {
|
||||
@@ -69,9 +49,7 @@ describe('useContextLinkVariables', () => {
|
||||
mockUseQueryBuilder.mockReturnValue({
|
||||
currentQuery: { builder: { queryData: [] } },
|
||||
});
|
||||
// Loaded dashboard with no variables — useDashboardFetchRequired guarantees the
|
||||
// dashboard is present, so the empty case is an empty spec, not `undefined`.
|
||||
mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
|
||||
mockUseDashboardVariableNames.mockReturnValue([]);
|
||||
|
||||
const { result } = renderHook(() => useContextLinkVariables());
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import PanelTypeSelectionModal from '../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
|
||||
import styles from './DashboardEmptyState.module.scss';
|
||||
import { useDashboardEditContext } from '../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControl } from '../../controls/useDashboardControl';
|
||||
|
||||
interface DashboardEmptyStateProps {
|
||||
canAddPanel: boolean;
|
||||
@@ -24,9 +25,11 @@ function DashboardEmptyState({
|
||||
const { isPickerOpen, openPicker, closePicker, createPanel } =
|
||||
useCreatePanel();
|
||||
const requestSettings = useDashboardStore((s) => s.requestSettings);
|
||||
const showConfigure = useDashboardControl('dashboardActions.configure');
|
||||
const showNewPanel = useDashboardControl('dashboardActions.newPanel');
|
||||
|
||||
return (
|
||||
<section className={styles.emptyState}>
|
||||
<section className={styles.emptyState} data-testid="dashboard-empty-state">
|
||||
<div className={styles.content}>
|
||||
<div className={styles.heading}>
|
||||
<img src={dashboardEmojiUrl} alt="" className={styles.emoji} />
|
||||
@@ -53,90 +56,94 @@ function DashboardEmptyState({
|
||||
</div>
|
||||
|
||||
<div className={styles.steps}>
|
||||
<div className={styles.step}>
|
||||
<div className={styles.stepText}>
|
||||
<Configure size={14} className={styles.stepIcon} />
|
||||
<div className={styles.stepCopy}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Configure your new dashboard
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="tertiary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Give it a name, add description, tags and variables
|
||||
</Typography>
|
||||
{showConfigure && (
|
||||
<div className={styles.step}>
|
||||
<div className={styles.stepText}>
|
||||
<Configure size={14} className={styles.stepIcon} />
|
||||
<div className={styles.stepCopy}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Configure your new dashboard
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="tertiary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Give it a name, add description, tags and variables
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
width="140px"
|
||||
prefix={<Configure size="md" />}
|
||||
disabled={!isEditable}
|
||||
onClick={(): void => requestSettings({ tab: 'Overview' })}
|
||||
testId="empty-configure"
|
||||
>
|
||||
Configure
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
width="140px"
|
||||
prefix={<Configure size="md" />}
|
||||
disabled={!isEditable}
|
||||
onClick={(): void => requestSettings({ tab: 'Overview' })}
|
||||
testId="empty-configure"
|
||||
>
|
||||
Configure
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.step}>
|
||||
<div className={styles.stepText}>
|
||||
<img src={landscapeUrl} alt="" className={styles.stepIcon} />
|
||||
<div className={styles.stepCopy}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Add panels
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="tertiary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Add panels to visualize your data
|
||||
</Typography>
|
||||
{showNewPanel && (
|
||||
<div className={styles.step}>
|
||||
<div className={styles.stepText}>
|
||||
<img src={landscapeUrl} alt="" className={styles.stepIcon} />
|
||||
<div className={styles.stepCopy}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Add panels
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="tertiary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Add panels to visualize your data
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<Plus size="md" />}
|
||||
disabled={!canAddPanel}
|
||||
onClick={(): void => openPicker()}
|
||||
testId="add-panel"
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<Plus size="md" />}
|
||||
disabled={!canAddPanel}
|
||||
onClick={(): void => openPicker()}
|
||||
testId="add-panel"
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<PanelTypeSelectionModal
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
|
||||
import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
|
||||
|
||||
import type { DashboardSection } from '../../../../utils';
|
||||
import { useDashboardStore } from '../../../../store/useDashboardStore';
|
||||
import { usePanelActionItems } from '../usePanelActionItems';
|
||||
|
||||
/** Keys of the disabled items, in order. */
|
||||
@@ -494,4 +495,43 @@ describe('usePanelActionItems', () => {
|
||||
click(actionRow(result.current.items, 'create-alert'));
|
||||
expect(mockCreateAlert).toHaveBeenCalledWith(mockPanel, 'panel-1');
|
||||
});
|
||||
|
||||
describe('host controls', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
});
|
||||
|
||||
it('drops every writing action on a read-only mount', () => {
|
||||
useDashboardStore.getState().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch: jest.fn(),
|
||||
readOnly: true,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => usePanelActionItems(baseArgs));
|
||||
|
||||
expect(itemKeys(result.current)).toStrictEqual([
|
||||
'view-panel',
|
||||
'separator',
|
||||
'download',
|
||||
'create-alert',
|
||||
]);
|
||||
});
|
||||
|
||||
it('drops the actions the host hides', () => {
|
||||
useDashboardStore.getState().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch: jest.fn(),
|
||||
controls: { panelActions: { createAlert: false, delete: false } },
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => usePanelActionItems(baseArgs));
|
||||
|
||||
expect(itemKeys(result.current)).not.toContain('create-alert');
|
||||
expect(itemKeys(result.current)).not.toContain('delete-panel');
|
||||
expect(itemKeys(result.current)).toContain('edit-panel');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,6 +28,7 @@ import { buildMoveItems } from '../utils/buildMoveItems';
|
||||
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
|
||||
import { blockedBy } from 'lib/authz/components/AuthZDropdown/utils';
|
||||
import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControlGroup } from '../../../controls/useDashboardControlGroup';
|
||||
|
||||
// Stable fallback so renders without layout context don't churn the mutation
|
||||
// hooks' deps (a fresh [] each render would re-create their callbacks).
|
||||
@@ -64,6 +65,7 @@ export function usePanelActionItems({
|
||||
const panelKind = panel.spec.plugin.kind;
|
||||
const { isEditable, editChecks, editDisabledTooltip } =
|
||||
useDashboardEditContext();
|
||||
const panelControls = useDashboardControlGroup('panelActions');
|
||||
const openPanelEditor = useOpenPanelEditor();
|
||||
const createAlert = useCreateAlertFromPanel();
|
||||
const { openView } = useViewPanel();
|
||||
@@ -101,7 +103,7 @@ export function usePanelActionItems({
|
||||
const editGate = { checks: editChecks, ...blockedBy(editDisabledTooltip) };
|
||||
|
||||
const panelGroup: AuthZDropdownItemType[] = [];
|
||||
if (panelCapabilities.view) {
|
||||
if (panelControls.view && panelCapabilities.view) {
|
||||
panelGroup.push({
|
||||
type: 'item',
|
||||
value: 'view-panel',
|
||||
@@ -110,7 +112,7 @@ export function usePanelActionItems({
|
||||
onClick: (): void => openView(panelId, panel),
|
||||
});
|
||||
}
|
||||
if (panelCapabilities.edit) {
|
||||
if (panelControls.edit && panelCapabilities.edit) {
|
||||
panelGroup.push({
|
||||
type: 'item',
|
||||
value: 'edit-panel',
|
||||
@@ -120,7 +122,7 @@ export function usePanelActionItems({
|
||||
onClick: (): void => openPanelEditor(panelId, { panel }),
|
||||
});
|
||||
}
|
||||
if (panelCapabilities.clone) {
|
||||
if (panelControls.clone && panelCapabilities.clone) {
|
||||
// Needs section context to place the copy; disabled without it.
|
||||
panelGroup.push({
|
||||
type: 'item',
|
||||
@@ -140,13 +142,13 @@ export function usePanelActionItems({
|
||||
}
|
||||
|
||||
const dataGroup: AuthZDropdownItemType[] = [];
|
||||
if (downloadItem) {
|
||||
if (panelControls.download && downloadItem) {
|
||||
dataGroup.push(downloadItem);
|
||||
}
|
||||
|
||||
// Create Alerts opens a new tab and never mutates the dashboard, so —
|
||||
// unlike edit/clone — it isn't gated on editability (V1 parity).
|
||||
if (panelCapabilities.createAlert) {
|
||||
if (panelControls.createAlert && panelCapabilities.createAlert) {
|
||||
dataGroup.push({
|
||||
type: 'item',
|
||||
value: 'create-alert',
|
||||
@@ -156,8 +158,9 @@ export function usePanelActionItems({
|
||||
});
|
||||
}
|
||||
|
||||
const moveGroup: AuthZDropdownItemType[] =
|
||||
isEditable && panelActions
|
||||
const moveGroup: AuthZDropdownItemType[] = !panelControls.move
|
||||
? []
|
||||
: isEditable && panelActions
|
||||
? buildMoveItems({
|
||||
sections,
|
||||
currentLayoutIndex: panelActions.currentLayoutIndex,
|
||||
@@ -174,17 +177,19 @@ export function usePanelActionItems({
|
||||
},
|
||||
];
|
||||
|
||||
const deleteGroup: AuthZDropdownItemType[] = [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete-panel',
|
||||
label: 'Delete panel',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
...editGate,
|
||||
onClick: (): void => requestDelete(),
|
||||
},
|
||||
];
|
||||
const deleteGroup: AuthZDropdownItemType[] = !panelControls.delete
|
||||
? []
|
||||
: [
|
||||
{
|
||||
type: 'item',
|
||||
value: 'delete-panel',
|
||||
label: 'Delete panel',
|
||||
prefix: <Trash2 size={14} />,
|
||||
danger: true,
|
||||
...editGate,
|
||||
onClick: (): void => requestDelete(),
|
||||
},
|
||||
];
|
||||
|
||||
return [panelGroup, dataGroup, moveGroup, deleteGroup]
|
||||
.filter((group) => group.length > 0)
|
||||
@@ -194,6 +199,7 @@ export function usePanelActionItems({
|
||||
: [{ type: 'separator', value: `separator-${index}` }, ...group],
|
||||
);
|
||||
}, [
|
||||
panelControls,
|
||||
isEditable,
|
||||
editChecks,
|
||||
editDisabledTooltip,
|
||||
|
||||
@@ -14,6 +14,7 @@ import { EQueryType } from 'types/common/dashboard';
|
||||
import styles from './ViewPanelModal.module.scss';
|
||||
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import { useDashboardEditContext } from '../../../hooks/useDashboardEditContext';
|
||||
import { useDashboardControl } from '../../../controls/useDashboardControl';
|
||||
|
||||
interface ViewPanelModalHeaderBaseProps {
|
||||
onSwitchToEdit: () => void;
|
||||
@@ -70,6 +71,7 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
|
||||
editChecks,
|
||||
editDisabledTooltip,
|
||||
} = useDashboardEditContext();
|
||||
const showSwitchToEdit = useDashboardControl('viewModal.switchToEdit');
|
||||
// Same capabilities-guarded options as the editor's PanelTypeSwitcher, so the two
|
||||
// selectors disable the same kinds (e.g. List under PromQL, metrics-only kinds).
|
||||
const panelTypeItems = usePanelTypeSelectItems({
|
||||
@@ -87,20 +89,22 @@ function ViewPanelModalHeader(props: ViewPanelModalHeaderProps): JSX.Element {
|
||||
onChange={onChangePanelKind}
|
||||
/>
|
||||
</div>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
prefix={<PenLine />}
|
||||
disabled={!canSwitchToEdit}
|
||||
onClick={onSwitchToEdit}
|
||||
testId="view-panel-switch-to-edit"
|
||||
>
|
||||
Switch to Edit Mode
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
{showSwitchToEdit && (
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
size="md"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
prefix={<PenLine />}
|
||||
disabled={!canSwitchToEdit}
|
||||
onClick={onSwitchToEdit}
|
||||
testId="view-panel-switch-to-edit"
|
||||
>
|
||||
Switch to Edit Mode
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
)}
|
||||
{query && (
|
||||
<Button
|
||||
size="md"
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { useDashboardStore } from '../../../../store/useDashboardStore';
|
||||
import ViewPanelModalHeader from '../ViewPanelModalHeader';
|
||||
import type { DashboardControlsInput } from '../../../../controls/types';
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
|
||||
() => ({
|
||||
useDashboardEditContext: (): unknown => ({
|
||||
isEditable: true,
|
||||
editChecks: [],
|
||||
editDisabledTooltip: '',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/PanelTypeSwitcher/usePanelTypeSelectItems',
|
||||
() => ({ usePanelTypeSelectItems: (): unknown[] => [] }),
|
||||
);
|
||||
|
||||
function renderHeader(
|
||||
readOnly: boolean,
|
||||
controls?: DashboardControlsInput,
|
||||
): void {
|
||||
useDashboardStore.getState().setEditContext({
|
||||
dashboardId: 'dash-1',
|
||||
refetch: jest.fn(),
|
||||
readOnly,
|
||||
controls,
|
||||
});
|
||||
render(
|
||||
<ViewPanelModalHeader
|
||||
mode="static"
|
||||
panelKind="signoz/TimeSeriesPanel"
|
||||
onChangePanelKind={jest.fn()}
|
||||
onSwitchToEdit={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ViewPanelModalHeader - controls', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
});
|
||||
|
||||
it('offers Switch to Edit Mode on an editable mount', () => {
|
||||
renderHeader(false);
|
||||
|
||||
expect(screen.getByTestId('view-panel-switch-to-edit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides Switch to Edit Mode on a read-only mount', () => {
|
||||
renderHeader(true);
|
||||
|
||||
expect(screen.getByTestId('view-panel-type-selector')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('view-panel-switch-to-edit'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides Switch to Edit Mode when the host hides it', () => {
|
||||
renderHeader(false, { viewModal: false });
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('view-panel-switch-to-edit'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -169,6 +169,15 @@ describe('useDrilldown', () => {
|
||||
expect(result.current.enableDrillDown).toBe(false);
|
||||
});
|
||||
|
||||
it('is false when every builder query is disabled, leaving only formulas to draw', () => {
|
||||
mockGetBuilderQueries.mockReturnValue([
|
||||
{ name: 'A', disabled: true },
|
||||
{ name: 'B', disabled: true },
|
||||
]);
|
||||
const { result } = renderHook(() => useDrilldown(tsPanel, 'p1'));
|
||||
expect(result.current.enableDrillDown).toBe(false);
|
||||
});
|
||||
|
||||
it.each([EQueryType.PROM, EQueryType.CLICKHOUSE, undefined])(
|
||||
'is false when the query type is %s (not the builder)',
|
||||
(queryType) => {
|
||||
|
||||
@@ -18,17 +18,35 @@ let mockVariables: Array<{
|
||||
let mockSelectionMap: Record<string, { value: unknown; allSelected: boolean }> =
|
||||
{};
|
||||
|
||||
let mockIsEditable = true;
|
||||
const mockSetVariableValue = jest.fn();
|
||||
const mockPatchAsync = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
const DYNAMIC_KIND = 'signoz/DynamicVariable';
|
||||
const QUERY_KIND = 'signoz/QueryVariable';
|
||||
|
||||
jest.mock('api/generated/services/dashboard', () => ({
|
||||
useGetDashboardV2: (): unknown => ({
|
||||
data: { data: { spec: { variables: mockVariables } } },
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardFetchRequired',
|
||||
() => ({
|
||||
useDashboardFetchRequired: (): unknown => ({
|
||||
dashboard: { spec: { variables: mockVariables } },
|
||||
variables: mockVariables,
|
||||
refetch: jest.fn(),
|
||||
}),
|
||||
}),
|
||||
}));
|
||||
);
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
|
||||
() => ({
|
||||
useDashboardEditContext: (): unknown => ({ isEditable: mockIsEditable }),
|
||||
}),
|
||||
);
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
|
||||
() => ({
|
||||
useDashboardEditContext: (): unknown => ({ isEditable: mockIsEditable }),
|
||||
}),
|
||||
);
|
||||
jest.mock(
|
||||
'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch',
|
||||
() => ({
|
||||
@@ -97,6 +115,7 @@ function renderItems(): void {
|
||||
|
||||
describe('useDrilldownDashboardVariables', () => {
|
||||
beforeEach(() => {
|
||||
mockIsEditable = true;
|
||||
jest.clearAllMocks();
|
||||
mockVariables = [];
|
||||
mockSelectionMap = {};
|
||||
@@ -171,6 +190,17 @@ describe('useDrilldownDashboardVariables', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('offers nothing to create on a dashboard the viewer cannot edit', () => {
|
||||
mockVariables = [];
|
||||
mockIsEditable = false;
|
||||
const { result } = renderHook(() =>
|
||||
useDrilldownDashboardVariables({ filters, onClose: jest.fn() }),
|
||||
);
|
||||
|
||||
expect(result.current.actions).toStrictEqual([]);
|
||||
expect(result.current.hasFieldVariables).toBe(false);
|
||||
});
|
||||
|
||||
it('offers Create and persists a new dynamic variable when none matches', async () => {
|
||||
mockVariables = [];
|
||||
renderItems();
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { safeNavigateMock } from '__tests__/safeNavigateMock';
|
||||
import { AllTheProviders, renderHook } from 'tests/test-utils';
|
||||
|
||||
import { CHARTS_ONLY } from '../../../../controls/presets';
|
||||
import type { DashboardControlsInput } from '../../../../controls/types';
|
||||
import { useDashboardStore } from '../../../../store/useDashboardStore';
|
||||
import { usePanelInteractions } from '../usePanelInteractions';
|
||||
|
||||
function dragSelect(controls?: DashboardControlsInput): void {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: 'd1', refetch: jest.fn(), controls });
|
||||
const { result } = renderHook(() => usePanelInteractions(), {
|
||||
wrapper: AllTheProviders,
|
||||
});
|
||||
result.current.onDragSelect(1_000, 2_000);
|
||||
}
|
||||
|
||||
describe('usePanelInteractions drag-to-zoom', () => {
|
||||
afterEach(() => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setEditContext({ dashboardId: '', refetch: jest.fn() });
|
||||
});
|
||||
|
||||
it('writes the dragged range to the URL', () => {
|
||||
dragSelect();
|
||||
|
||||
expect(safeNavigateMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining('startTime=1000&endTime=2000'),
|
||||
);
|
||||
});
|
||||
|
||||
it('does nothing when the host turns zoom off', () => {
|
||||
dragSelect({ panelActions: { zoom: false } });
|
||||
|
||||
expect(safeNavigateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still zooms when the host hides the toolbar but leaves zoom on', () => {
|
||||
dragSelect({ toolbar: false });
|
||||
|
||||
expect(safeNavigateMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still zooms on a charts-only mount', () => {
|
||||
dragSelect(CHARTS_ONLY);
|
||||
|
||||
expect(safeNavigateMock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,7 @@ import { useDrilldownCoordinates } from './useDrilldownCoordinates';
|
||||
import { useDrilldownDashboardVariables } from './useDrilldownDashboardVariables';
|
||||
import { useDrilldownFilter } from './useDrilldownFilter';
|
||||
import { useResolvedDrilldownQuery } from './useResolvedDrilldownQuery';
|
||||
import { useDashboardControl } from 'pages/DashboardPage/DashboardContainer/controls/useDashboardControl';
|
||||
import { useViewPanel } from './useViewPanel';
|
||||
|
||||
/** Which menu the popover shows; extend as submenus are added (e.g. dashboard variables). */
|
||||
@@ -87,16 +88,19 @@ export function useDrilldown(
|
||||
const queries = panel.spec.queries;
|
||||
|
||||
// Drilldown only for builder-authored panels with a query to drill into (PromQL /
|
||||
// ClickHouse have no builder context to refine).
|
||||
// ClickHouse have no builder context to refine). A panel whose builder queries
|
||||
// are all disabled draws only formulas, which have no series to drill into.
|
||||
const showDrilldown = useDashboardControl('panelActions.drilldown');
|
||||
const enableDrillDown = useMemo(() => {
|
||||
const queryType = getPanelQueryType(panel);
|
||||
return (
|
||||
showDrilldown &&
|
||||
getPanelDefinition(kind).actions.drilldown &&
|
||||
!!queryType &&
|
||||
isBuilderQueryType(queryType) &&
|
||||
getBuilderQueries(queries).length > 0
|
||||
getBuilderQueries(queries).some((query) => !query.disabled)
|
||||
);
|
||||
}, [kind, panel, queries]);
|
||||
}, [showDrilldown, kind, panel, queries]);
|
||||
|
||||
const slotQuery = useMemo(
|
||||
() => fromPerses(queries, panelType),
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type VariableFormModel,
|
||||
} from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/variableFormModel';
|
||||
import { buildVariablesPatch } from 'pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/utils/variablePatchOps';
|
||||
import { useDashboardEditContext } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext';
|
||||
import { useDashboardFetchRequired } from 'pages/DashboardPage/DashboardContainer/hooks/useDashboardFetchRequired';
|
||||
import { useOptimisticPatch } from 'pages/DashboardPage/DashboardContainer/hooks/useOptimisticPatch';
|
||||
import { selectVariableValues } from 'pages/DashboardPage/DashboardContainer/store/slices/variableSelectionSlice';
|
||||
@@ -44,7 +45,7 @@ export interface DrilldownVariableAction {
|
||||
}
|
||||
|
||||
export interface UseDrilldownDashboardVariablesApi {
|
||||
/** Whether the clicked point exposes any field to bind to a variable (gates the base-menu entry). */
|
||||
/** Whether the submenu has any entry to offer (gates the base-menu entry). */
|
||||
hasFieldVariables: boolean;
|
||||
/** Resolved menu entries, one per group-by field on the clicked point. */
|
||||
actions: DrilldownVariableAction[];
|
||||
@@ -74,6 +75,8 @@ export function useDrilldownDashboardVariables({
|
||||
const selection = useDashboardStore(selectVariableValues(dashboardId));
|
||||
const setVariableValue = useDashboardStore((state) => state.setVariableValue);
|
||||
const { patchAsync } = useOptimisticPatch();
|
||||
// Create writes the dashboard spec; Set/Unset only change this view's selection.
|
||||
const { isEditable } = useDashboardEditContext();
|
||||
|
||||
const fieldVariables = useMemo<[string, string | number][]>(
|
||||
() =>
|
||||
@@ -141,51 +144,57 @@ export function useDrilldownDashboardVariables({
|
||||
|
||||
const actions = useMemo<DrilldownVariableAction[]>(
|
||||
() =>
|
||||
fieldVariables.map(([fieldName, fieldValue]) => {
|
||||
const existing = dynamicVariables.find(
|
||||
(v) => v.dynamicAttribute === fieldName,
|
||||
);
|
||||
if (!existing) {
|
||||
fieldVariables
|
||||
.map(([fieldName, fieldValue]) => {
|
||||
const existing = dynamicVariables.find(
|
||||
(v) => v.dynamicAttribute === fieldName,
|
||||
);
|
||||
if (!existing) {
|
||||
if (!isEditable) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
fieldName,
|
||||
fieldValue,
|
||||
kind: DrilldownVariableActionKind.Create,
|
||||
onClick: (): void => {
|
||||
void handleCreate(fieldName, fieldValue);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const current = selection[existing.name]?.value;
|
||||
const isSame = Array.isArray(current)
|
||||
? current.length === 1 && current[0] === fieldValue
|
||||
: current === fieldValue;
|
||||
|
||||
// Multi-select values must be arrays (a scalar renders as empty in the selector).
|
||||
const cleared = existing.multiSelect ? [] : '';
|
||||
const assigned = existing.multiSelect ? [fieldValue] : fieldValue;
|
||||
|
||||
return {
|
||||
fieldName,
|
||||
fieldValue,
|
||||
kind: DrilldownVariableActionKind.Create,
|
||||
kind: isSame
|
||||
? DrilldownVariableActionKind.Unset
|
||||
: DrilldownVariableActionKind.Set,
|
||||
onClick: (): void => {
|
||||
void handleCreate(fieldName, fieldValue);
|
||||
void logEvent(DashboardDetailEvents.DrilldownAction, {
|
||||
action: 'setVariable',
|
||||
dashboardId,
|
||||
});
|
||||
setSelection(existing.name, {
|
||||
value: isSame ? cleared : assigned,
|
||||
allSelected: false,
|
||||
});
|
||||
onClose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const current = selection[existing.name]?.value;
|
||||
const isSame = Array.isArray(current)
|
||||
? current.length === 1 && current[0] === fieldValue
|
||||
: current === fieldValue;
|
||||
|
||||
// Multi-select values must be arrays (a scalar renders as empty in the selector).
|
||||
const cleared = existing.multiSelect ? [] : '';
|
||||
const assigned = existing.multiSelect ? [fieldValue] : fieldValue;
|
||||
|
||||
return {
|
||||
fieldName,
|
||||
fieldValue,
|
||||
kind: isSame
|
||||
? DrilldownVariableActionKind.Unset
|
||||
: DrilldownVariableActionKind.Set,
|
||||
onClick: (): void => {
|
||||
void logEvent(DashboardDetailEvents.DrilldownAction, {
|
||||
action: 'setVariable',
|
||||
dashboardId,
|
||||
});
|
||||
setSelection(existing.name, {
|
||||
value: isSame ? cleared : assigned,
|
||||
allSelected: false,
|
||||
});
|
||||
onClose();
|
||||
},
|
||||
};
|
||||
}),
|
||||
})
|
||||
.filter((action): action is DrilldownVariableAction => action !== null),
|
||||
[
|
||||
fieldVariables,
|
||||
isEditable,
|
||||
dynamicVariables,
|
||||
selection,
|
||||
setSelection,
|
||||
@@ -195,5 +204,5 @@ export function useDrilldownDashboardVariables({
|
||||
],
|
||||
);
|
||||
|
||||
return { hasFieldVariables: fieldVariables.length > 0, actions };
|
||||
return { hasFieldVariables: actions.length > 0, actions };
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
|
||||
import { UpdateTimeInterval } from 'store/actions';
|
||||
import { useDashboardControl } from 'pages/DashboardPage/DashboardContainer/controls/useDashboardControl';
|
||||
|
||||
export interface PanelInteractions {
|
||||
/** Drag-select a chart range → write it to the URL + global time so every panel re-fetches the same range. */
|
||||
@@ -43,8 +44,12 @@ export function usePanelInteractions(): PanelInteractions {
|
||||
[syncMode, syncFilterMode, dashboardId],
|
||||
);
|
||||
|
||||
const canZoom = useDashboardControl('panelActions.zoom');
|
||||
const onDragSelect = useCallback(
|
||||
(start: number, end: number): void => {
|
||||
if (!canZoom) {
|
||||
return;
|
||||
}
|
||||
const startTimestamp = Math.trunc(start);
|
||||
const endTimestamp = Math.trunc(end);
|
||||
|
||||
@@ -57,7 +62,7 @@ export function usePanelInteractions(): PanelInteractions {
|
||||
void logEvent(DashboardDetailEvents.PanelZoomed, { context: 'panel' });
|
||||
}
|
||||
},
|
||||
[dispatch, pathname, safeNavigate, urlQuery],
|
||||
[canZoom, dispatch, pathname, safeNavigate, urlQuery],
|
||||
);
|
||||
|
||||
return { onDragSelect, dashboardPreference };
|
||||
|
||||
@@ -8,12 +8,12 @@ import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
|
||||
import { useCreatePanel } from '../../../hooks/useCreatePanel';
|
||||
import type { DashboardSection } from '../../../utils';
|
||||
import PanelTypeSelectionModal from '../../Panel/PanelTypeSelectionModal/PanelTypeSelectionModal';
|
||||
import { useCloneSection } from '../hooks/useCloneSection';
|
||||
import { useDeleteSection } from '../hooks/useDeleteSection';
|
||||
import { usePanelPickerHighlight } from '../hooks/usePanelPickerHighlight';
|
||||
import { usePanelPickerReveal } from '../hooks/usePanelPickerReveal';
|
||||
import { useRenameSection } from '../hooks/useRenameSection';
|
||||
import { useScrollIntoView } from '../hooks/useScrollIntoView';
|
||||
import { useSectionHeaderActions } from '../hooks/useSectionHeaderActions';
|
||||
import { useToggleSectionCollapse } from '../hooks/useToggleSectionCollapse';
|
||||
import SectionTitleModal from '../SectionTitleModal';
|
||||
import SectionGrid from '../SectionGrid/SectionGrid';
|
||||
@@ -66,7 +66,14 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {
|
||||
setIsDeleteOpen(false);
|
||||
}, [deleteSection]);
|
||||
|
||||
const cloneSection = useCloneSection();
|
||||
const openRename = useCallback((): void => setIsRenaming(true), []);
|
||||
const openDelete = useCallback((): void => setIsDeleteOpen(true), []);
|
||||
const actions = useSectionHeaderActions({
|
||||
section,
|
||||
openPicker,
|
||||
openRename,
|
||||
openDelete,
|
||||
});
|
||||
|
||||
const sectionRef = useRef<HTMLDivElement>(null);
|
||||
useScrollIntoView(section.id, sectionRef);
|
||||
@@ -116,35 +123,30 @@ function Section({ section, sections, dragHandle }: SectionProps): JSX.Element {
|
||||
dragHandle={dragHandle}
|
||||
disabledChecks={editChecks}
|
||||
disabledTooltip={editDisabledTooltip}
|
||||
actions={{
|
||||
onRename: (): void => setIsRenaming(true),
|
||||
onAddPanel: (): void => openPicker(section.layoutIndex),
|
||||
onCloneSection: (): void => void cloneSection(section),
|
||||
onDeleteSection: (): void => setIsDeleteOpen(true),
|
||||
}}
|
||||
actions={actions}
|
||||
/>
|
||||
{open &&
|
||||
(section.items.length > 0 || pickerTarget ? (
|
||||
grid
|
||||
) : (
|
||||
<div className={styles.emptySection}>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
size="md"
|
||||
type="button"
|
||||
variant="dashed"
|
||||
color="secondary"
|
||||
prefix={<Plus size="md" />}
|
||||
onClick={
|
||||
isEditable ? (): void => openPicker(section.layoutIndex) : undefined
|
||||
}
|
||||
testId={`section-add-panel-${section.id}`}
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
))}
|
||||
(section.items.length > 0 || pickerTarget
|
||||
? grid
|
||||
: actions.onAddPanel && (
|
||||
<div className={styles.emptySection}>
|
||||
<AuthZTooltip checks={editChecks} disabledTooltip={editDisabledTooltip}>
|
||||
<Button
|
||||
size="md"
|
||||
type="button"
|
||||
variant="dashed"
|
||||
color="secondary"
|
||||
prefix={<Plus size="md" />}
|
||||
onClick={
|
||||
isEditable ? (): void => openPicker(section.layoutIndex) : undefined
|
||||
}
|
||||
testId={`section-add-panel-${section.id}`}
|
||||
>
|
||||
New Panel
|
||||
</Button>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
))}
|
||||
<SectionTitleModal
|
||||
open={isRenaming}
|
||||
heading="Rename section"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user