161 lines
6.6 KiB
TypeScript
161 lines
6.6 KiB
TypeScript
import { useState, useMemo } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
AlertDialog,
|
|
AlertDialogContent,
|
|
AlertDialogDescription,
|
|
AlertDialogFooter,
|
|
AlertDialogHeader,
|
|
AlertDialogTitle,
|
|
} from "@/components/ui/alert-dialog";
|
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
|
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
|
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
|
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
|
import { useAssignRoleToUser, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
|
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
|
|
|
export type AssignDialogKind = "role" | "branch";
|
|
|
|
export interface AssignDialogProps {
|
|
kind: AssignDialogKind;
|
|
onClose: () => void;
|
|
targetUserId?: number;
|
|
targetUserName?: string;
|
|
onAssigned?: () => void;
|
|
}
|
|
|
|
const ASSIGN_DIALOG_TITLES: Record<AssignDialogKind, string> = {
|
|
role: "profile.actions.assignRole",
|
|
branch: "profile.actions.assignBranch",
|
|
};
|
|
|
|
const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
|
role: "users.fields.role",
|
|
branch: "users.sections.branches",
|
|
};
|
|
|
|
export function AssignDialog({ kind, onClose, targetUserId, targetUserName, onAssigned }: AssignDialogProps) {
|
|
const { t, i18n } = useTranslation();
|
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
|
const [targetSearch, setTargetSearch] = useState("");
|
|
const [targetValue, setTargetValue] = useState(() => (targetUserId ? String(targetUserId) : ""));
|
|
const [resourceSearch, setResourceSearch] = useState("");
|
|
const [resourceValue, setResourceValue] = useState("");
|
|
const [error, setError] = useState<string | undefined>();
|
|
|
|
const staffQuery = useInfiniteUsers(targetSearch);
|
|
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
|
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
|
const roleMutation = useAssignRoleToUser();
|
|
const branchMutation = useAssignBranchToUser();
|
|
const isPending = roleMutation.isPending || branchMutation.isPending;
|
|
|
|
const targetOptions: InfiniteSelectOption[] = useMemo(() => {
|
|
const options = (staffQuery.data?.pages ?? [])
|
|
.flatMap((page) => page?.users ?? [])
|
|
.map((user) => ({
|
|
value: String(user.id),
|
|
label: [user.firstName, user.lastName].filter(Boolean).join(" ") || user.name || user.username || String(user.id),
|
|
}));
|
|
if (targetUserId && !options.some((option) => option.value === String(targetUserId))) {
|
|
options.unshift({ value: String(targetUserId), label: targetUserName || String(targetUserId) });
|
|
}
|
|
return options;
|
|
}, [staffQuery.data, targetUserId, targetUserName]);
|
|
|
|
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
|
if (kind === "role") {
|
|
return (rolesQuery.data?.pages ?? [])
|
|
.flatMap((page) => page?.roles ?? [])
|
|
.map((role) => ({ value: String(role.id), label: role.name || role.code || String(role.id) }));
|
|
}
|
|
return (branchesQuery.data?.pages ?? [])
|
|
.flatMap((page) => page?.branches ?? [])
|
|
.map((branch) => ({
|
|
value: String(branch.id),
|
|
label: branch.name?.[lang] || branch.name?.tm || branch.name?.en || branch.name?.ru || branch.uniqueCode || String(branch.id),
|
|
}));
|
|
}, [kind, rolesQuery.data, branchesQuery.data, lang]);
|
|
|
|
const resourceQuery = kind === "role" ? rolesQuery : branchesQuery;
|
|
|
|
const handleSubmit = () => {
|
|
if (!targetValue || !resourceValue) {
|
|
setError(t("common.errors.required", "Meýdança hökmany doldurylmaly"));
|
|
return;
|
|
}
|
|
setError(undefined);
|
|
const payload = { userId: Number(targetValue), roleId: Number(resourceValue) };
|
|
const onSuccess = () => {
|
|
setResourceValue("");
|
|
onAssigned?.();
|
|
onClose();
|
|
};
|
|
if (kind === "role") roleMutation.mutate(payload, { onSuccess });
|
|
else branchMutation.mutate({ userId: payload.userId, branchId: payload.roleId }, { onSuccess });
|
|
};
|
|
|
|
return (
|
|
<AlertDialog open onOpenChange={(open) => !open && onClose()}>
|
|
<AlertDialogContent className="max-w-md sm:max-w-md">
|
|
<AlertDialogHeader>
|
|
<AlertDialogTitle>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogTitle>
|
|
<VisuallyHidden.Root>
|
|
<AlertDialogDescription>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogDescription>
|
|
</VisuallyHidden.Root>
|
|
</AlertDialogHeader>
|
|
<div className="space-y-3">
|
|
<InfiniteSelect
|
|
required
|
|
label={t("profile.assign.userLabel", "Ulanyjy")}
|
|
value={targetValue}
|
|
onChange={(value) => {
|
|
setTargetValue(value);
|
|
if (error) setError(undefined);
|
|
}}
|
|
disabled={!!targetUserId || isPending}
|
|
options={targetOptions}
|
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
|
loading={staffQuery.isLoading}
|
|
isLoadingMore={staffQuery.isFetchingNextPage}
|
|
hasNextPage={!!staffQuery.hasNextPage}
|
|
onLoadMore={() => staffQuery.fetchNextPage()}
|
|
searchValue={targetSearch}
|
|
onSearchChange={setTargetSearch}
|
|
/>
|
|
<InfiniteSelect
|
|
required
|
|
label={t(ASSIGN_DIALOG_FIELD_LABELS[kind])}
|
|
value={resourceValue}
|
|
onChange={(value) => {
|
|
setResourceValue(value);
|
|
if (error) setError(undefined);
|
|
}}
|
|
error={error}
|
|
disabled={isPending}
|
|
options={resourceOptions}
|
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
|
loading={resourceQuery.isLoading}
|
|
isLoadingMore={resourceQuery.isFetchingNextPage}
|
|
hasNextPage={!!resourceQuery.hasNextPage}
|
|
onLoadMore={() => resourceQuery.fetchNextPage()}
|
|
searchValue={resourceSearch}
|
|
onSearchChange={setResourceSearch}
|
|
/>
|
|
</div>
|
|
<AlertDialogFooter>
|
|
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
|
|
{t("common.cancel", "Yza")}
|
|
</Button>
|
|
<Button size="sm" onClick={handleSubmit} disabled={!targetValue || !resourceValue || isPending}>
|
|
{t("common.save", "Ýatda sakla")}
|
|
</Button>
|
|
</AlertDialogFooter>
|
|
</AlertDialogContent>
|
|
</AlertDialog>
|
|
);
|
|
}
|