Skip to content

feat: filter templates by organization #14254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions coderd/database/modelqueries.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ func (q *sqlQuerier) GetAuthorizedTemplates(ctx context.Context, arg GetTemplate
rows, err := q.db.QueryContext(ctx, query,
arg.Deleted,
arg.OrganizationID,
arg.OrganizationName,
arg.ExactName,
arg.FuzzyName,
pq.Array(arg.IDs),
Expand Down
42 changes: 25 additions & 17 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 11 additions & 5 deletions coderd/database/queries/templates.sql
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,23 @@ WHERE
organization_id = @organization_id
ELSE true
END
-- Filter by organization_name
AND CASE
WHEN @organization_name :: text != '' THEN
LOWER("organization_name") = LOWER(@organization_name)
ELSE true
END
-- Filter by exact name
AND CASE
WHEN @exact_name :: text != '' THEN
LOWER("name") = LOWER(@exact_name)
ELSE true
END
-- Filter by name, matching on substring
AND CASE
WHEN @fuzzy_name :: text != '' THEN
lower(name) ILIKE '%' || lower(@fuzzy_name) || '%'
ELSE true
-- Filter by name, matching on substring
AND CASE
WHEN @fuzzy_name :: text != '' THEN
lower(name) ILIKE '%' || lower(@fuzzy_name) || '%'
ELSE true
END
-- Filter by ids
AND CASE
Expand Down
11 changes: 6 additions & 5 deletions coderd/searchquery/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,12 @@ func Templates(ctx context.Context, db database.Store, query string) (database.G

parser := httpapi.NewQueryParamParser()
filter := database.GetTemplatesWithFilterParams{
FuzzyName: parser.String(values, "", "name"),
Deleted: parser.Boolean(values, false, "deleted"),
ExactName: parser.String(values, "", "exact_name"),
IDs: parser.UUIDs(values, []uuid.UUID{}, "ids"),
Deprecated: parser.NullableBoolean(values, sql.NullBool{}, "deprecated"),
Deleted: parser.Boolean(values, false, "deleted"),
OrganizationName: parser.String(values, "", "organization"),
ExactName: parser.String(values, "", "exact_name"),
FuzzyName: parser.String(values, "", "name"),
IDs: parser.UUIDs(values, []uuid.UUID{}, "ids"),
Deprecated: parser.NullableBoolean(values, sql.NullBool{}, "deprecated"),
}

// Convert the "organization" parameter to an organization uuid. This can require
Expand Down
19 changes: 17 additions & 2 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,9 +304,17 @@ export type GetTemplatesOptions = Readonly<{
readonly deprecated?: boolean;
}>;

export type GetTemplatesQuery = Readonly<{
readonly q: string;
}>;

function normalizeGetTemplatesOptions(
options: GetTemplatesOptions = {},
options: GetTemplatesOptions | GetTemplatesQuery = {},
): Record<string, string> {
if ("q" in options) {
return options;
}

const params: Record<string, string> = {};
if (options.deprecated !== undefined) {
params["deprecated"] = String(options.deprecated);
Expand Down Expand Up @@ -666,6 +674,13 @@ class ApiMethods {
return response.data;
};

getMyOrganizations = async (): Promise<TypesGen.Organization[]> => {
const response = await this.axios.get<TypesGen.Organization[]>(
"/api/v2/users/me/organizations",
);
return response.data;
};

/**
* @param organization Can be the organization's ID or name
*/
Expand All @@ -687,7 +702,7 @@ class ApiMethods {
};

getTemplates = async (
options?: GetTemplatesOptions,
options?: GetTemplatesOptions | GetTemplatesQuery,
): Promise<TypesGen.Template[]> => {
const params = normalizeGetTemplatesOptions(options);
const response = await this.axios.get<TypesGen.Template[]>(
Expand Down
13 changes: 7 additions & 6 deletions site/src/api/queries/templates.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { MutationOptions, QueryClient, QueryOptions } from "react-query";
import { API, type GetTemplatesOptions } from "api/api";
import { API, type GetTemplatesQuery, type GetTemplatesOptions } from "api/api";
import type {
CreateTemplateRequest,
CreateTemplateVersionRequest,
Expand Down Expand Up @@ -38,12 +38,13 @@ export const templateByName = (
};
};

const getTemplatesQueryKey = (options?: GetTemplatesOptions) => [
"templates",
options?.deprecated,
];
const getTemplatesQueryKey = (
options?: GetTemplatesOptions | GetTemplatesQuery,
) => ["templates", options];

export const templates = (options?: GetTemplatesOptions) => {
export const templates = (
options?: GetTemplatesOptions | GetTemplatesQuery,
) => {
return {
queryKey: getTemplatesQueryKey(options),
queryFn: () => API.getTemplates(options),
Expand Down
83 changes: 83 additions & 0 deletions site/src/pages/TemplatesPage/TemplatesFilter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import type { FC } from "react";
import { API } from "api/api";
import type { Organization } from "api/typesGenerated";
import {
Filter,
MenuSkeleton,
SearchFieldSkeleton,
type useFilter,
} from "components/Filter/filter";
import { useFilterMenu } from "components/Filter/menu";
import {
SelectFilter,
type SelectFilterOption,
} from "components/Filter/SelectFilter";
import { UserAvatar } from "components/UserAvatar/UserAvatar";
import { docs } from "utils/docs";

interface TemplatesFilterProps {
filter: ReturnType<typeof useFilter>;
}

export const TemplatesFilter: FC<TemplatesFilterProps> = ({ filter }) => {
const organizationMenu = useFilterMenu({
onChange: (option) =>
filter.update({ ...filter.values, organization: option?.value }),
value: filter.values.organization,
id: "organization",
getSelectedOption: async () => {
if (!filter.values.organization) {
return null;
}

const org = await API.getOrganization(filter.values.organization);
return orgOption(org);
},
getOptions: async () => {
const orgs = await API.getMyOrganizations();
return orgs.map(orgOption);
},
});

return (
<Filter
presets={[
{ query: "", name: "All templates" },
{ query: "deprecated:true", name: "Deprecated templates" },
]}
learnMoreLink={docs("/templates#template-filtering")}
isLoading={false}
filter={filter}
options={
<>
<SelectFilter
placeholder="All organizations"
label="Select an organization"
options={organizationMenu.searchOptions}
selectedOption={organizationMenu.selectedOption ?? undefined}
onSelect={organizationMenu.selectOption}
/>
</>
}
skeleton={
<>
<SearchFieldSkeleton />
<MenuSkeleton />
</>
}
/>
);
};

const orgOption = (org: Organization): SelectFilterOption => ({
label: org.display_name || org.name,
value: org.name,
startIcon: (
<UserAvatar
key={org.id}
size="xs"
username={org.display_name}
avatarURL={org.icon}
/>
),
});
12 changes: 11 additions & 1 deletion site/src/pages/TemplatesPage/TemplatesPage.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { FC } from "react";
import { Helmet } from "react-helmet-async";
import { useQuery } from "react-query";
import { useSearchParams } from "react-router-dom";
import { templateExamples, templates } from "api/queries/templates";
import { useFilter } from "components/Filter/filter";
import { useAuthenticated } from "contexts/auth/RequireAuth";
import { useDashboard } from "modules/dashboard/useDashboard";
import { pageTitle } from "utils/page";
Expand All @@ -11,7 +13,14 @@ export const TemplatesPage: FC = () => {
const { permissions } = useAuthenticated();
const { showOrganizations } = useDashboard();

const templatesQuery = useQuery(templates());
const searchParamsResult = useSearchParams();
const filter = useFilter({
fallbackFilter: "deprecated:false",
searchParamsResult,
onUpdate: () => {}, // reset pagination
});

const templatesQuery = useQuery(templates({ q: filter.query }));
const examplesQuery = useQuery({
...templateExamples(),
enabled: permissions.createTemplates,
Expand All @@ -25,6 +34,7 @@ export const TemplatesPage: FC = () => {
</Helmet>
<TemplatesPageView
error={error}
filter={filter}
showOrganizations={showOrganizations}
canCreateTemplates={permissions.createTemplates}
examples={examplesQuery.data}
Expand Down
6 changes: 6 additions & 0 deletions site/src/pages/TemplatesPage/TemplatesPageView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { ExternalAvatar } from "components/Avatar/Avatar";
import { AvatarData } from "components/AvatarData/AvatarData";
import { AvatarDataSkeleton } from "components/AvatarData/AvatarDataSkeleton";
import { DeprecatedBadge } from "components/Badges/Badges";
import type { useFilter } from "components/Filter/filter";
import {
HelpTooltip,
HelpTooltipContent,
Expand Down Expand Up @@ -46,6 +47,7 @@ import {
formatTemplateActiveDevelopers,
} from "utils/templates";
import { EmptyTemplates } from "./EmptyTemplates";
import { TemplatesFilter } from "./TemplatesFilter";

export const Language = {
developerCount: (activeCount: number): string => {
Expand Down Expand Up @@ -173,6 +175,7 @@ const TemplateRow: FC<TemplateRowProps> = ({ showOrganizations, template }) => {

export interface TemplatesPageViewProps {
error?: unknown;
filter: ReturnType<typeof useFilter>;
showOrganizations: boolean;
canCreateTemplates: boolean;
examples: TemplateExample[] | undefined;
Expand All @@ -181,6 +184,7 @@ export interface TemplatesPageViewProps {

export const TemplatesPageView: FC<TemplatesPageViewProps> = ({
error,
filter,
showOrganizations,
canCreateTemplates,
examples,
Expand Down Expand Up @@ -220,6 +224,8 @@ export const TemplatesPageView: FC<TemplatesPageViewProps> = ({
)}
</PageHeader>

<TemplatesFilter filter={filter} />

{error ? (
<ErrorAlert error={error} />
) : (
Expand Down
6 changes: 3 additions & 3 deletions site/src/pages/WorkspacesPage/WorkspacesPageView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import StopOutlined from "@mui/icons-material/StopOutlined";
import LoadingButton from "@mui/lab/LoadingButton";
import Button from "@mui/material/Button";
import Divider from "@mui/material/Divider";
import type { ComponentProps } from "react";
import type { ComponentProps, FC } from "react";
import type { UseQueryResult } from "react-query";
import { hasError, isApiValidationError } from "api/errors";
import type { Template, Workspace } from "api/typesGenerated";
Expand Down Expand Up @@ -65,7 +65,7 @@ export interface WorkspacesPageViewProps {
canChangeVersions: boolean;
}

export const WorkspacesPageView = ({
export const WorkspacesPageView: FC<WorkspacesPageViewProps> = ({
workspaces,
error,
limit,
Expand All @@ -86,7 +86,7 @@ export const WorkspacesPageView = ({
templatesFetchStatus,
canCreateTemplate,
canChangeVersions,
}: WorkspacesPageViewProps) => {
}) => {
// Let's say the user has 5 workspaces, but tried to hit page 100, which does
// not exist. In this case, the page is not valid and we want to show a better
// error message.
Expand Down
3 changes: 1 addition & 2 deletions site/src/pages/WorkspacesPage/filter/menus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ export const useTemplateFilterMenu = ({
template.display_name.toLowerCase().includes(query.toLowerCase()),
);
return filteredTemplates.map((template) => ({
label:
template.display_name !== "" ? template.display_name : template.name,
label: template.display_name || template.name,
value: template.name,
startIcon: <TemplateAvatar size="xs" template={template} />,
}));
Expand Down
Loading