Align RBAC API contract
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -20,6 +20,7 @@ export interface User {
|
||||
socialMedia: SocialMedia;
|
||||
lightMode: number;
|
||||
role: string;
|
||||
roleId?: number;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -48,6 +49,7 @@ export interface CreateUserPayload {
|
||||
password: string;
|
||||
phone: string;
|
||||
role: string;
|
||||
roleId?: number;
|
||||
socialMedia: SocialMedia;
|
||||
username: string;
|
||||
}
|
||||
@@ -62,6 +64,7 @@ export interface UpdateUserPayload {
|
||||
name?: string;
|
||||
phone?: string;
|
||||
role?: string;
|
||||
roleId?: number;
|
||||
socialMedia?: SocialMedia;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
@@ -103,6 +103,7 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
email: initialData.email ?? "",
|
||||
avatar: initialData.avatar ?? "",
|
||||
role: initialData.role ?? "",
|
||||
roleId: initialData.roleId ? String(initialData.roleId) : "",
|
||||
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||
@@ -218,7 +219,13 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
<InfiniteSelect
|
||||
label={t("users.fields.role", "Roly")}
|
||||
value={form.role}
|
||||
onChange={(v) => setField("role", v)}
|
||||
onChange={(v) => {
|
||||
setField("role", v);
|
||||
const selectedRole = (roleQuery.data?.pages ?? [])
|
||||
.flatMap((page) => page?.roles ?? [])
|
||||
.find((role) => role.code === v);
|
||||
setField("roleId", selectedRole ? String(selectedRole.id) : "");
|
||||
}}
|
||||
placeholder={t("users.fields.role", "Roly")}
|
||||
error={errors.role}
|
||||
disabled={isPending}
|
||||
|
||||
@@ -39,6 +39,7 @@ export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fall
|
||||
.default(""),
|
||||
avatar: urlSchema(t),
|
||||
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||
roleId: z.string(),
|
||||
socialFacebook: urlSchema(t),
|
||||
socialInstagram: urlSchema(t),
|
||||
socialTelegram: urlSchema(t),
|
||||
@@ -68,6 +69,7 @@ export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
||||
email: "",
|
||||
avatar: "",
|
||||
role: "",
|
||||
roleId: "",
|
||||
socialFacebook: "",
|
||||
socialInstagram: "",
|
||||
socialTelegram: "",
|
||||
@@ -86,6 +88,7 @@ export function buildPayload(data: AllUserFormData): CreateUserPayload {
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
@@ -107,6 +110,7 @@ export function buildUpdatePayload(data: AllUserFormData): UpdateUserPayload {
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface Client {
|
||||
socialMedia: SocialMedia;
|
||||
lightMode: number;
|
||||
role: string;
|
||||
roleId?: number;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -39,13 +40,14 @@ export interface ClientRole {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
scope: "own" | "branch" | "all";
|
||||
isSuper: boolean;
|
||||
isSystem: boolean;
|
||||
}
|
||||
|
||||
export interface ClientPermission {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
}
|
||||
|
||||
export interface ClientBranch {
|
||||
@@ -108,6 +110,7 @@ export interface CreateClientPayload {
|
||||
password: string;
|
||||
phone: string;
|
||||
role: string;
|
||||
roleId?: number;
|
||||
socialMedia: SocialMedia;
|
||||
username: string;
|
||||
}
|
||||
@@ -122,6 +125,7 @@ export interface UpdateClientPayload {
|
||||
name?: string;
|
||||
phone?: string;
|
||||
role?: string;
|
||||
roleId?: number;
|
||||
socialMedia?: SocialMedia;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
||||
email: initialData.email ?? "",
|
||||
avatar: initialData.avatar ?? "",
|
||||
role: initialData.role ?? "",
|
||||
roleId: initialData.roleId ? String(initialData.roleId) : "",
|
||||
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||
@@ -216,7 +217,13 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
||||
<InfiniteSelect
|
||||
label={t("users.fields.role", "Roly")}
|
||||
value={form.role}
|
||||
onChange={(v) => setField("role", v)}
|
||||
onChange={(v) => {
|
||||
setField("role", v);
|
||||
const selectedRole = (roleQuery.data?.pages ?? [])
|
||||
.flatMap((page) => page?.roles ?? [])
|
||||
.find((role) => role.code === v);
|
||||
setField("roleId", selectedRole ? String(selectedRole.id) : "");
|
||||
}}
|
||||
placeholder={t("users.fields.role", "Roly")}
|
||||
error={errors.role}
|
||||
disabled={isPending}
|
||||
|
||||
@@ -39,6 +39,7 @@ export function clientFormSchema(mode: "create" | "edit", t: (key: string, fallb
|
||||
.default(""),
|
||||
avatar: urlSchema(t),
|
||||
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||
roleId: z.string(),
|
||||
socialFacebook: urlSchema(t),
|
||||
socialInstagram: urlSchema(t),
|
||||
socialTelegram: urlSchema(t),
|
||||
@@ -68,6 +69,7 @@ export const DEFAULT_FORM_VALUES: ClientFormData = {
|
||||
email: "",
|
||||
avatar: "",
|
||||
role: "",
|
||||
roleId: "",
|
||||
socialFacebook: "",
|
||||
socialInstagram: "",
|
||||
socialTelegram: "",
|
||||
@@ -86,6 +88,7 @@ export function buildPayload(data: ClientFormData): CreateClientPayload {
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
@@ -107,6 +110,7 @@ export function buildUpdatePayload(data: ClientFormData): UpdateClientPayload {
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface Operator {
|
||||
socialMedia: SocialMedia;
|
||||
lightMode: number;
|
||||
role: string;
|
||||
roleId?: number;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -44,13 +45,14 @@ export interface OperatorRole {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
scope: "own" | "branch" | "all";
|
||||
isSuper: boolean;
|
||||
isSystem: boolean;
|
||||
}
|
||||
|
||||
export interface OperatorPermission {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
}
|
||||
|
||||
export interface OperatorBranch {
|
||||
@@ -105,6 +107,7 @@ export interface CreateOperatorPayload {
|
||||
password: string;
|
||||
phone: string;
|
||||
role: string;
|
||||
roleId?: number;
|
||||
socialMedia: SocialMedia;
|
||||
username: string;
|
||||
}
|
||||
@@ -119,6 +122,7 @@ export interface UpdateOperatorPayload {
|
||||
name?: string;
|
||||
phone?: string;
|
||||
role?: string;
|
||||
roleId?: number;
|
||||
socialMedia?: SocialMedia;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
@@ -8,13 +8,10 @@ import { FormInput } from "@/components/formInput";
|
||||
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { KeyRound } from "lucide-react";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { AvatarUpload } from "@/components/avatarUpload";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { AssignDialog, type AssignDialogKind } from "@/features/shared/components/assignDialog";
|
||||
import { useCreateOperator, useUpdateOperator, operatorKeys } from "../hooks/useOperators";
|
||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
@@ -66,7 +63,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
||||
|
||||
const isPending = createOperator.isPending || updateOperator.isPending;
|
||||
|
||||
const [assignDialog, setAssignDialog] = useState<AssignDialogKind | null>(null);
|
||||
const operatorPermissions = (initialData as OperatorDetail | undefined)?.permissions ?? [];
|
||||
|
||||
const schema = useMemo(() => operatorFormSchema(mode, t), [mode, t, i18n.language]);
|
||||
@@ -163,6 +159,7 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
||||
email: initialData.email ?? "",
|
||||
avatar: initialData.avatar ?? "",
|
||||
role: initialData.role ?? "",
|
||||
roleId: initialData.roleId ? String(initialData.roleId) : "",
|
||||
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||
@@ -221,12 +218,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")}
|
||||
</h1>
|
||||
{mode === "edit" && (
|
||||
<Button type="button" variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("permission")}>
|
||||
<KeyRound size={14} />
|
||||
{t("profile.actions.assignPermission", "Rugsat birikdiriň")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<BentoGrid cols={2}>
|
||||
{/* ── Identity ── */}
|
||||
@@ -294,7 +285,13 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
||||
<InfiniteSelect
|
||||
label={t("users.fields.role", "Roly")}
|
||||
value={form.role}
|
||||
onChange={(v) => setField("role", v)}
|
||||
onChange={(v) => {
|
||||
setField("role", v);
|
||||
const selectedRole = (roleQuery.data?.pages ?? [])
|
||||
.flatMap((page) => page?.roles ?? [])
|
||||
.find((role) => role.code === v);
|
||||
setField("roleId", selectedRole ? String(selectedRole.id) : "");
|
||||
}}
|
||||
placeholder={t("users.fields.role", "Roly")}
|
||||
error={errors.role}
|
||||
disabled={isPending}
|
||||
@@ -381,7 +378,7 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
||||
<div className="flex flex-wrap gap-1.5 items-center">
|
||||
{operatorPermissions.length > 0 ? (
|
||||
operatorPermissions.map((p) => (
|
||||
<Badge key={p.id} variant="secondary">
|
||||
<Badge key={p.code} variant="secondary">
|
||||
{p.name}
|
||||
</Badge>
|
||||
))
|
||||
@@ -389,10 +386,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
||||
<span className="text-sm text-muted-foreground">{t("common.noData", "Rugsat ýok")}</span>
|
||||
)}
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" className="gap-1.5 shrink-0" onClick={() => setAssignDialog("permission")}>
|
||||
<KeyRound size={14} />
|
||||
{t("profile.actions.assignPermission", "Rugsat birikdiriň")}
|
||||
</Button>
|
||||
</div>
|
||||
</BentoCard>
|
||||
)}
|
||||
@@ -405,20 +398,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
||||
submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")}
|
||||
/>
|
||||
|
||||
{/* ── Assign dialog (edit mode only) ── */}
|
||||
{mode === "edit" && assignDialog && initialData?.id && (
|
||||
<AssignDialog
|
||||
kind={assignDialog}
|
||||
targetUserId={initialData.id}
|
||||
targetUserName={
|
||||
[initialData.firstName, initialData.lastName].filter(Boolean).join(" ") || initialData.name || initialData.username
|
||||
}
|
||||
onAssigned={() => {
|
||||
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(initialData.id) });
|
||||
}}
|
||||
onClose={() => setAssignDialog(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ export function operatorFormSchema(mode: "create" | "edit", t: (key: string, fal
|
||||
.default(""),
|
||||
avatar: urlSchema(t),
|
||||
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||
roleId: z.string(),
|
||||
socialFacebook: urlSchema(t),
|
||||
socialInstagram: urlSchema(t),
|
||||
socialTelegram: urlSchema(t),
|
||||
@@ -60,6 +61,7 @@ export const DEFAULT_FORM_VALUES: OperatorFormData = {
|
||||
email: "",
|
||||
avatar: "",
|
||||
role: "",
|
||||
roleId: "",
|
||||
socialFacebook: "",
|
||||
socialInstagram: "",
|
||||
socialTelegram: "",
|
||||
@@ -78,6 +80,7 @@ export function buildPayload(data: OperatorFormData): CreateOperatorPayload {
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
@@ -99,6 +102,7 @@ export function buildUpdatePayload(data: OperatorFormData): UpdateOperatorPayloa
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
|
||||
@@ -3,64 +3,16 @@ import apiClient from "@/lib/api/client";
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Permission {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface PermissionsListResponse {
|
||||
count: number;
|
||||
permissions: Permission[];
|
||||
}
|
||||
|
||||
export interface PermissionsListParams {
|
||||
search?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface PermissionPayload {
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
}
|
||||
|
||||
// ─── API functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export const permissionsApi = {
|
||||
/** GET /permissions — backend filters by `permission_name` */
|
||||
getAll: async (params: PermissionsListParams = {}, signal?: AbortSignal): Promise<PermissionsListResponse> => {
|
||||
const { search, page, limit } = params;
|
||||
const { data } = await apiClient.get<PermissionsListResponse>("/permissions", {
|
||||
params: { page, limit, permission_name: search },
|
||||
signal,
|
||||
});
|
||||
/** GET /permissions — permission catalog */
|
||||
getAll: async (signal?: AbortSignal): Promise<Permission[]> => {
|
||||
const { data } = await apiClient.get<Permission[]>("/permissions", { signal });
|
||||
return data;
|
||||
},
|
||||
|
||||
/** GET /permissions/:id */
|
||||
getById: async (id: number): Promise<Permission> => {
|
||||
const { data } = await apiClient.get<Permission>(`/permissions/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** POST /permissions */
|
||||
create: async (payload: PermissionPayload): Promise<Permission> => {
|
||||
const { data } = await apiClient.post<Permission>("/permissions", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** PUT /permissions/:id */
|
||||
update: async (id: number, payload: PermissionPayload): Promise<Permission> => {
|
||||
const { data } = await apiClient.put<Permission>(`/permissions/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** DELETE /permissions/:id */
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`/permissions/${id}`);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
import { useMemo, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreatePermission, useUpdatePermission } from "../hooks/usePermissions";
|
||||
import { createPermissionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/permission.schema";
|
||||
import type { PermissionFormData } from "../schemas/permission.schema";
|
||||
import type { Permission } from "../api/permissionsApi";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface PermissionFormProps {
|
||||
mode: "create" | "edit";
|
||||
initialData?: Permission;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof PermissionFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof PermissionFormData] = msg;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── PermissionForm ───────────────────────────────────────────────────────────
|
||||
|
||||
export function PermissionForm({ mode, initialData }: PermissionFormProps) {
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t, i18n.language],
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createPermission = useCreatePermission();
|
||||
const updatePermission = useUpdatePermission(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createPermission.isPending || updatePermission.isPending;
|
||||
|
||||
const schema = useMemo(() => createPermissionFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<PermissionFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
code: initialData.code,
|
||||
name: initialData.name,
|
||||
guardName: initialData.guardName,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const setField = useCallback(
|
||||
(key: keyof PermissionFormData) => (value: string) => {
|
||||
(setValue as (k: keyof PermissionFormData, v: string) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language]);
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const values = getValues();
|
||||
const payload = buildPayload(values);
|
||||
|
||||
if (mode === "create") {
|
||||
createPermission.mutate(payload, {
|
||||
onSuccess: () => navigate("/settings/users/permissions"),
|
||||
});
|
||||
} else {
|
||||
updatePermission.mutate(payload, {
|
||||
onSuccess: () => navigate("/settings/users/permissions"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === "create" ? t("permissions.createTitle", "Rugsat dörediň") : t("permissions.editTitle", "Rugsat üýtgetmek")}
|
||||
</h1>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("permissions.fields.code", "Kod")}
|
||||
value={form.code}
|
||||
onChange={setField("code")}
|
||||
placeholder={t("permissions.fields.code", "Kod")}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("permissions.fields.guardName", "Guard name")}
|
||||
value={form.guardName}
|
||||
onChange={setField("guardName")}
|
||||
placeholder="operator"
|
||||
error={errors.guardName}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("permissions.fields.name", "Ady")}
|
||||
value={form.name}
|
||||
onChange={setField("name")}
|
||||
placeholder={t("permissions.fields.name", "Ady")}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate("/settings/users/permissions")}
|
||||
submitLabel={mode === "create" ? t("permissions.actions.create", "Rugsat dörediň") : t("permissions.actions.save", "Ýatda sakla")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,111 +1,17 @@
|
||||
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { permissionsApi, type PermissionPayload, type PermissionsListParams } from "../api/permissionsApi";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { permissionsApi } from "../api/permissionsApi";
|
||||
|
||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const permissionKeys = {
|
||||
all: ["permissions"] as const,
|
||||
lists: () => ["permissions", "list"] as const,
|
||||
list: (params: PermissionsListParams) => ["permissions", "list", params] as const,
|
||||
detail: (id: number) => ["permissions", "detail", id] as const,
|
||||
infinite: (search: string) => ["permissions", "infinite", search] as const,
|
||||
};
|
||||
|
||||
// ─── usePermissions (list) ────────────────────────────────────────────────────
|
||||
|
||||
export function usePermissions(params: PermissionsListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const normalized = normalizeSearch(debouncedSearch);
|
||||
const queryParams: PermissionsListParams = { ...params, search: normalized || undefined };
|
||||
|
||||
/** Fetches the read-only permission catalog used by roles and the permissions page. */
|
||||
export function usePermissions() {
|
||||
return useQuery({
|
||||
queryKey: permissionKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => permissionsApi.getAll(queryParams, signal),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── usePermission (single) ───────────────────────────────────────────────────
|
||||
|
||||
export function usePermission(id: number) {
|
||||
return useQuery({
|
||||
queryKey: permissionKeys.detail(id),
|
||||
queryFn: () => permissionsApi.getById(id),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useInfinitePermissions ───────────────────────────────────────────────────
|
||||
|
||||
const PERMISSION_PAGE_SIZE = 25;
|
||||
|
||||
/**
|
||||
* Infinite-scroll permission list for searchable selects.
|
||||
* staleTime = 5 min as required by PROJECT_STANDARDS rule 12.
|
||||
*/
|
||||
export function useInfinitePermissions(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: permissionKeys.infinite(effectiveSearch),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
permissionsApi.getAll({ page: pageParam, limit: PERMISSION_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce((sum, p) => sum + (p?.permissions?.length ?? 0), 0);
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreatePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useCreatePermission() {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: PermissionPayload) => permissionsApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all });
|
||||
toast.success(t("permissions.toast.created", "Rugsat üstünlikli döredildi!"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdatePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdatePermission(id: number) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: PermissionPayload) => permissionsApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all });
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.detail(id) });
|
||||
toast.success(t("permissions.toast.updated", "Rugsat üstünlikli üýtgedildi!"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeletePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useDeletePermission() {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => permissionsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all });
|
||||
toast.success(t("permissions.toast.deleted", "Rugsat üstünlikli pozuldy!"));
|
||||
},
|
||||
queryKey: permissionKeys.all,
|
||||
queryFn: ({ signal }) => permissionsApi.getAll(signal),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import type { PermissionPayload } from "../api/permissionsApi";
|
||||
|
||||
export function createPermissionFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
code: z.string().min(1, t("validation.required", "validation.required")),
|
||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||
guardName: z.string().min(1, t("validation.required", "validation.required")),
|
||||
});
|
||||
}
|
||||
|
||||
export type PermissionFormData = z.infer<ReturnType<typeof createPermissionFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: PermissionFormData = {
|
||||
code: "",
|
||||
name: "",
|
||||
guardName: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: PermissionFormData): PermissionPayload {
|
||||
return {
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
guardName: data.guardName,
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,11 @@ export interface Role {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
scope: "own" | "branch" | "all";
|
||||
isSuper: boolean;
|
||||
isSystem: boolean;
|
||||
permissions: string[];
|
||||
usersCount: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -22,10 +26,17 @@ export interface RolesListParams {
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface RolePayload {
|
||||
export interface CreateRolePayload {
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
scope: Role["scope"];
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export interface UpdateRolePayload {
|
||||
name: string;
|
||||
scope: Role["scope"];
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
// ─── API functions ────────────────────────────────────────────────────────────
|
||||
@@ -48,13 +59,13 @@ export const rolesApi = {
|
||||
},
|
||||
|
||||
/** POST /roles */
|
||||
create: async (payload: RolePayload): Promise<Role> => {
|
||||
create: async (payload: CreateRolePayload): Promise<Role> => {
|
||||
const { data } = await apiClient.post<Role>("/roles", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** PUT /roles/:id */
|
||||
update: async (id: number, payload: RolePayload): Promise<Role> => {
|
||||
update: async (id: number, payload: UpdateRolePayload): Promise<Role> => {
|
||||
const { data } = await apiClient.put<Role>(`/roles/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
@@ -5,13 +5,14 @@ import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useCreateRole, useUpdateRole } from "../hooks/useRoles";
|
||||
import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/role.schema";
|
||||
import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildCreatePayload, buildUpdatePayload, getRoleFormValues } from "../schemas/role.schema";
|
||||
import type { RoleFormData } from "../schemas/role.schema";
|
||||
import type { Role } from "../api/rolesApi";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||
import { usePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||
|
||||
interface RoleFormProps {
|
||||
mode: "create" | "edit";
|
||||
@@ -29,7 +30,9 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── RoleForm ─────────────────────────────────────────────────────────────────
|
||||
function isRoleScope(value: string): value is RoleFormData["scope"] {
|
||||
return value === "own" || value === "branch" || value === "all";
|
||||
}
|
||||
|
||||
export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
@@ -38,13 +41,16 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
[_t, i18n.language],
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const permissionQuery = usePermissions();
|
||||
const createRole = useCreateRole();
|
||||
const updateRole = useUpdateRole(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createRole.isPending || updateRole.isPending;
|
||||
|
||||
const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language]);
|
||||
const scopeOptions: SelectOption[] = [
|
||||
{ value: "own", label: t("roles.scope.own", "Own") },
|
||||
{ value: "branch", label: t("roles.scope.branch", "Branch") },
|
||||
{ value: "all", label: t("roles.scope.all", "All branches") },
|
||||
];
|
||||
|
||||
const {
|
||||
watch,
|
||||
@@ -55,55 +61,51 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
trigger,
|
||||
} = useForm<RoleFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
code: initialData.code,
|
||||
name: initialData.name,
|
||||
guardName: initialData.guardName,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData ? getRoleFormValues(initialData) : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
const permissionOptions = permissionQuery.data ?? [];
|
||||
|
||||
const setField = useCallback(
|
||||
(key: keyof RoleFormData) => (value: string) => {
|
||||
(setValue as (k: keyof RoleFormData, v: string) => void)(key, value);
|
||||
const setTextField = useCallback(
|
||||
(key: "code" | "name") => (value: string) => {
|
||||
setValue(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
const togglePermission = useCallback(
|
||||
(code: string, checked: boolean) => {
|
||||
const selected = new Set(getValues("permissions"));
|
||||
if (checked) selected.add(code);
|
||||
else selected.delete(code);
|
||||
setValue("permissions", [...selected], { shouldDirty: true });
|
||||
},
|
||||
[getValues, setValue],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language]);
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
if (!(await trigger())) return;
|
||||
|
||||
const values = getValues();
|
||||
const payload = buildPayload(values);
|
||||
|
||||
if (mode === "create") {
|
||||
createRole.mutate(payload, {
|
||||
createRole.mutate(buildCreatePayload(values), {
|
||||
onSuccess: () => navigate("/settings/users/roles"),
|
||||
});
|
||||
} else {
|
||||
updateRole.mutate(payload, {
|
||||
updateRole.mutate(buildUpdatePayload(values), {
|
||||
onSuccess: () => navigate("/settings/users/roles"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
@@ -115,22 +117,23 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
type="text"
|
||||
label={t("roles.fields.code", "Kod")}
|
||||
value={form.code}
|
||||
onChange={setField("code")}
|
||||
onChange={setTextField("code")}
|
||||
placeholder={t("roles.fields.code", "Kod")}
|
||||
error={errors.code}
|
||||
disabled={isPending}
|
||||
disabled={mode === "edit" || isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("roles.fields.guardName", "Guard name")}
|
||||
value={form.guardName}
|
||||
onChange={setField("guardName")}
|
||||
placeholder="operator"
|
||||
error={errors.guardName}
|
||||
disabled={isPending}
|
||||
type="select"
|
||||
label={t("roles.fields.scope", "Scope")}
|
||||
value={form.scope}
|
||||
options={scopeOptions}
|
||||
onChange={(value) => {
|
||||
if (isRoleScope(value)) setValue("scope", value, { shouldDirty: true });
|
||||
}}
|
||||
disabled={isPending || (mode === "edit" && initialData?.isSystem === true)}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -139,16 +142,40 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
type="text"
|
||||
label={t("roles.fields.name", "Ady")}
|
||||
value={form.name}
|
||||
onChange={setField("name")}
|
||||
onChange={setTextField("name")}
|
||||
placeholder={t("roles.fields.name", "Ady")}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard span="full" title={t("roles.fields.permissions", "Rugsatlar")}>
|
||||
{permissionQuery.isLoading ? (
|
||||
<p className="text-sm text-muted-foreground">{t("common.loading", "Ýüklenýär...")}</p>
|
||||
) : permissionQuery.isError ? (
|
||||
<p className="text-sm text-destructive">{t("common.fetchError", "Maglumat ýüklenmedi.")}</p>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{permissionOptions.map((permission) => (
|
||||
<label key={permission.code} className="flex items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
id={`permission-${permission.code}`}
|
||||
checked={form.permissions.includes(permission.code)}
|
||||
onCheckedChange={(checked) => togglePermission(permission.code, checked === true)}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<Label htmlFor={`permission-${permission.code}`} className="cursor-pointer">
|
||||
{permission.name} <span className="text-muted-foreground">({permission.code})</span>
|
||||
</Label>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
submitDisabled={permissionQuery.isLoading || permissionQuery.isError}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate("/settings/users/roles")}
|
||||
loadingLabel={t("common.saving", "Ýüklenýär...")}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tansta
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { rolesApi, type RolePayload, type RolesListParams } from "../api/rolesApi";
|
||||
import { rolesApi, type CreateRolePayload, type UpdateRolePayload, type RolesListParams } from "../api/rolesApi";
|
||||
|
||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -67,7 +67,7 @@ export function useCreateRole() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: RolePayload) => rolesApi.create(payload),
|
||||
mutationFn: (payload: CreateRolePayload) => rolesApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
||||
toast.success(t("roles.toast.created", "Rol üstünlikli döredildi!"));
|
||||
@@ -82,7 +82,7 @@ export function useUpdateRole(id: number) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: RolePayload) => rolesApi.update(id, payload),
|
||||
mutationFn: (payload: UpdateRolePayload) => rolesApi.update(id, payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.detail(data.id) });
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { z } from "zod";
|
||||
import type { RolePayload } from "../api/rolesApi";
|
||||
import type { CreateRolePayload, Role, UpdateRolePayload } from "../api/rolesApi";
|
||||
|
||||
export function createRoleFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
code: z.string().min(1, t("validation.required", "validation.required")),
|
||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||
guardName: z.string().min(1, t("validation.required", "validation.required")),
|
||||
scope: z.enum(["own", "branch", "all"]),
|
||||
permissions: z.array(z.string()),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -14,13 +15,32 @@ export type RoleFormData = z.infer<ReturnType<typeof createRoleFormSchema>>;
|
||||
export const DEFAULT_FORM_VALUES: RoleFormData = {
|
||||
code: "",
|
||||
name: "",
|
||||
guardName: "operator",
|
||||
scope: "branch",
|
||||
permissions: [],
|
||||
};
|
||||
|
||||
export function buildPayload(data: RoleFormData): RolePayload {
|
||||
export function buildCreatePayload(data: RoleFormData): CreateRolePayload {
|
||||
return {
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
guardName: data.guardName,
|
||||
code: data.code.trim(),
|
||||
name: data.name.trim(),
|
||||
scope: data.scope,
|
||||
permissions: data.permissions,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildUpdatePayload(data: RoleFormData): UpdateRolePayload {
|
||||
return {
|
||||
name: data.name.trim(),
|
||||
scope: data.scope,
|
||||
permissions: data.permissions,
|
||||
};
|
||||
}
|
||||
|
||||
export function getRoleFormValues(role: Role): RoleFormData {
|
||||
return {
|
||||
code: role.code,
|
||||
name: role.name,
|
||||
scope: role.scope,
|
||||
permissions: role.permissions ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,22 +8,11 @@ export interface AddBranchUserPayload {
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface AddRoleUserPayload {
|
||||
export interface AssignUserRolePayload {
|
||||
roleId: number;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface AddPermissionRolePayload {
|
||||
permissionIds: number[];
|
||||
roleId: number;
|
||||
}
|
||||
|
||||
// export interface AddPermissionUserPayload {
|
||||
// permissionId: number;
|
||||
// userId: number;
|
||||
// effect?: string;
|
||||
// }
|
||||
|
||||
// Re-export so shared hooks can import from one place
|
||||
export type { BranchListParams, BranchListResponse };
|
||||
|
||||
@@ -64,34 +53,11 @@ export async function postBranchUser(payload: AddBranchUserPayload): Promise<voi
|
||||
await apiClient.post("/branch-users", payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /role-users
|
||||
* Assigns a role to a user.
|
||||
*/
|
||||
export async function postRoleUser(payload: AddRoleUserPayload): Promise<void> {
|
||||
await apiClient.post("/role-users", payload);
|
||||
/** PUT /users/:id/role — assigns a role by ID. */
|
||||
export async function putUserRole({ userId, roleId }: AssignUserRolePayload): Promise<void> {
|
||||
await apiClient.put(`/users/${userId}/role`, { roleId });
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /permission-roles/bulk
|
||||
* Assigns permissions to a role.
|
||||
*/
|
||||
export async function postPermissionRole(payload: AddPermissionRolePayload): Promise<void> {
|
||||
await apiClient.post("/permission-roles/bulk", payload);
|
||||
}
|
||||
|
||||
// /**
|
||||
// * POST /permission-users
|
||||
// * Assigns a permission to a user.
|
||||
// */
|
||||
// export async function postPermissionUser(payload: AddPermissionUserPayload): Promise<void> {
|
||||
// await apiClient.post("/permission-users", {
|
||||
// permissionId: payload.permissionId,
|
||||
// userId: payload.userId,
|
||||
// effect: payload.effect ?? "allow",
|
||||
// });
|
||||
// }
|
||||
|
||||
/**
|
||||
* Proxy for branch list fetching — kept here so shared hooks
|
||||
* don't import directly from the branches feature.
|
||||
|
||||
@@ -13,143 +13,74 @@ import {
|
||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useAssignRoleToUser, useAssignPermissionToRole, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import { useAssignRoleToUser, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
export type AssignDialogKind = "role" | "permission" | "branch";
|
||||
export type AssignDialogKind = "role" | "branch";
|
||||
|
||||
export interface AssignDialogProps {
|
||||
kind: AssignDialogKind;
|
||||
onClose: () => void;
|
||||
targetUserId?: number;
|
||||
targetUserName?: string;
|
||||
targetRoleId?: number;
|
||||
targetRoleName?: string;
|
||||
onAssigned?: () => void;
|
||||
}
|
||||
|
||||
const ASSIGN_DIALOG_TITLES: Record<AssignDialogKind, string> = {
|
||||
role: "profile.actions.assignRole",
|
||||
permission: "profile.actions.assignPermission",
|
||||
branch: "profile.actions.assignBranch",
|
||||
};
|
||||
|
||||
const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
||||
role: "users.fields.role",
|
||||
permission: "users.sections.permissions",
|
||||
branch: "users.sections.branches",
|
||||
};
|
||||
|
||||
/**
|
||||
* Dialog for assigning a role / branch to a staff user, or assigning a permission to a role.
|
||||
* Permissions are assigned to roles via POST /permission-roles/bulk: { permissionIds: [...], roleId }.
|
||||
*/
|
||||
export function AssignDialog({ kind, onClose, targetUserId, targetUserName, targetRoleId, targetRoleName, onAssigned }: AssignDialogProps) {
|
||||
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 isPermission = kind === "permission";
|
||||
|
||||
const [targetSearch, setTargetSearch] = useState("");
|
||||
const [targetValue, setTargetValue] = useState<string>(() => {
|
||||
if (isPermission && targetRoleId) return String(targetRoleId);
|
||||
if (!isPermission && targetUserId) return String(targetUserId);
|
||||
return "";
|
||||
});
|
||||
const [targetValue, setTargetValue] = useState(() => (targetUserId ? String(targetUserId) : ""));
|
||||
const [resourceSearch, setResourceSearch] = useState("");
|
||||
const [resourceValue, setResourceValue] = useState("");
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
|
||||
// Target query: admin users list for role/branch; roles list for permission
|
||||
const staffQuery = useInfiniteUsers(targetSearch, !isPermission);
|
||||
const targetRolesQuery = useInfiniteRoles(targetSearch, isPermission);
|
||||
|
||||
// Resource queries
|
||||
const staffQuery = useInfiniteUsers(targetSearch);
|
||||
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
||||
const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission");
|
||||
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
||||
|
||||
const roleMutation = useAssignRoleToUser();
|
||||
const permissionRoleMutation = useAssignPermissionToRole();
|
||||
const branchMutation = useAssignBranchToUser();
|
||||
const isPending = roleMutation.isPending || permissionRoleMutation.isPending || branchMutation.isPending;
|
||||
const isPending = roleMutation.isPending || branchMutation.isPending;
|
||||
|
||||
const targetOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
if (isPermission) {
|
||||
const opts: InfiniteSelectOption[] = (targetRolesQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.roles ?? [])
|
||||
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) }));
|
||||
|
||||
if (targetRoleId) {
|
||||
const valStr = String(targetRoleId);
|
||||
if (!opts.some((o) => o.value === valStr)) {
|
||||
opts.unshift({ value: valStr, label: targetRoleName || valStr });
|
||||
}
|
||||
}
|
||||
return opts;
|
||||
}
|
||||
|
||||
const opts: InfiniteSelectOption[] = (staffQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: [u.firstName, u.lastName].filter(Boolean).join(" ") || u.name || u.username || String(u.id),
|
||||
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) {
|
||||
const valStr = String(targetUserId);
|
||||
if (!opts.some((o) => o.value === valStr)) {
|
||||
opts.unshift({ value: valStr, label: targetUserName || valStr });
|
||||
}
|
||||
if (targetUserId && !options.some((option) => option.value === String(targetUserId))) {
|
||||
options.unshift({ value: String(targetUserId), label: targetUserName || String(targetUserId) });
|
||||
}
|
||||
return opts;
|
||||
}, [isPermission, targetRolesQuery.data, targetRoleId, targetRoleName, staffQuery.data, targetUserId, targetUserName]);
|
||||
|
||||
const targetLabel = isPermission ? t("users.fields.role", "Rol") : t("profile.assign.userLabel", "Ulanyjy");
|
||||
const targetLoading = isPermission ? targetRolesQuery.isLoading : staffQuery.isLoading;
|
||||
const targetLoadingMore = isPermission ? targetRolesQuery.isFetchingNextPage : staffQuery.isFetchingNextPage;
|
||||
const targetHasNextPage = isPermission ? !!targetRolesQuery.hasNextPage : !!staffQuery.hasNextPage;
|
||||
const loadMoreTargets = () => {
|
||||
if (isPermission) targetRolesQuery.fetchNextPage();
|
||||
else staffQuery.fetchNextPage();
|
||||
};
|
||||
return options;
|
||||
}, [staffQuery.data, targetUserId, targetUserName]);
|
||||
|
||||
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
if (kind === "role") {
|
||||
return (rolesQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.roles ?? [])
|
||||
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) }));
|
||||
}
|
||||
if (kind === "permission") {
|
||||
return (permissionsQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.permissions ?? [])
|
||||
.map((perm) => ({ value: String(perm.id), label: perm.name || perm.code || String(perm.id) }));
|
||||
.flatMap((page) => page?.roles ?? [])
|
||||
.map((role) => ({ value: String(role.id), label: role.name || role.code || String(role.id) }));
|
||||
}
|
||||
return (branchesQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.branches ?? [])
|
||||
.map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name?.[lang] || b.name?.tm || b.name?.en || b.name?.ru || b.uniqueCode || String(b.id),
|
||||
.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, permissionsQuery.data, branchesQuery.data, lang]);
|
||||
}, [kind, rolesQuery.data, branchesQuery.data, lang]);
|
||||
|
||||
const resourceLoading =
|
||||
kind === "role" ? rolesQuery.isLoading : kind === "permission" ? permissionsQuery.isLoading : branchesQuery.isLoading;
|
||||
const resourceLoadingMore =
|
||||
kind === "role"
|
||||
? rolesQuery.isFetchingNextPage
|
||||
: kind === "permission"
|
||||
? permissionsQuery.isFetchingNextPage
|
||||
: branchesQuery.isFetchingNextPage;
|
||||
const resourceHasNextPage =
|
||||
kind === "role" ? !!rolesQuery.hasNextPage : kind === "permission" ? !!permissionsQuery.hasNextPage : !!branchesQuery.hasNextPage;
|
||||
const loadMoreResources = () => {
|
||||
if (kind === "role") rolesQuery.fetchNextPage();
|
||||
else if (kind === "permission") permissionsQuery.fetchNextPage();
|
||||
else branchesQuery.fetchNextPage();
|
||||
};
|
||||
const resourceQuery = kind === "role" ? rolesQuery : branchesQuery;
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!targetValue || !resourceValue) {
|
||||
@@ -157,24 +88,14 @@ export function AssignDialog({ kind, onClose, targetUserId, targetUserName, targ
|
||||
return;
|
||||
}
|
||||
setError(undefined);
|
||||
|
||||
const firstId = Number(targetValue);
|
||||
const secondId = Number(resourceValue);
|
||||
const payload = { userId: Number(targetValue), roleId: Number(resourceValue) };
|
||||
const onSuccess = () => {
|
||||
setResourceValue("");
|
||||
onAssigned?.();
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (kind === "role") {
|
||||
roleMutation.mutate({ userId: firstId, roleId: secondId }, { onSuccess });
|
||||
} else if (kind === "permission") {
|
||||
// Usere permission berilýän ýeri comment-e alyndy: permission user-e däl, role-a assign edilýär ({ permissionIds: [id], roleId })
|
||||
// permissionMutation.mutate({ userId: firstId, permissionId: secondId, effect: "allow" }, { onSuccess });
|
||||
permissionRoleMutation.mutate({ roleId: firstId, permissionIds: [secondId] }, { onSuccess });
|
||||
} else {
|
||||
branchMutation.mutate({ userId: firstId, branchId: secondId }, { onSuccess });
|
||||
}
|
||||
if (kind === "role") roleMutation.mutate(payload, { onSuccess });
|
||||
else branchMutation.mutate({ userId: payload.userId, branchId: payload.roleId }, { onSuccess });
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -186,48 +107,45 @@ export function AssignDialog({ kind, onClose, targetUserId, targetUserName, targ
|
||||
<AlertDialogDescription>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogDescription>
|
||||
</VisuallyHidden.Root>
|
||||
</AlertDialogHeader>
|
||||
|
||||
<div className="space-y-3">
|
||||
<InfiniteSelect
|
||||
required
|
||||
label={targetLabel}
|
||||
label={t("profile.assign.userLabel", "Ulanyjy")}
|
||||
value={targetValue}
|
||||
onChange={(v) => {
|
||||
setTargetValue(v);
|
||||
onChange={(value) => {
|
||||
setTargetValue(value);
|
||||
if (error) setError(undefined);
|
||||
}}
|
||||
disabled={!!targetUserId || isPending}
|
||||
options={targetOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={targetLoading}
|
||||
isLoadingMore={targetLoadingMore}
|
||||
hasNextPage={targetHasNextPage}
|
||||
onLoadMore={loadMoreTargets}
|
||||
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={(v) => {
|
||||
setResourceValue(v);
|
||||
onChange={(value) => {
|
||||
setResourceValue(value);
|
||||
if (error) setError(undefined);
|
||||
}}
|
||||
error={error}
|
||||
disabled={isPending}
|
||||
options={resourceOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={resourceLoading}
|
||||
isLoadingMore={resourceLoadingMore}
|
||||
hasNextPage={resourceHasNextPage}
|
||||
onLoadMore={loadMoreResources}
|
||||
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")}
|
||||
|
||||
@@ -3,13 +3,9 @@ import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
postBranchUser,
|
||||
postRoleUser,
|
||||
postPermissionRole,
|
||||
// postPermissionUser,
|
||||
putUserRole,
|
||||
type AddBranchUserPayload,
|
||||
type AddRoleUserPayload,
|
||||
type AddPermissionRolePayload,
|
||||
// type AddPermissionUserPayload,
|
||||
type AssignUserRolePayload,
|
||||
} from "../api/sharedApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
@@ -33,7 +29,7 @@ function useInvalidateProfile() {
|
||||
// ─── useAssignRoleToUser ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* POST /role-users — assigns a role to the given staff user and refreshes the profile cache.
|
||||
* PUT /users/:id/role — assigns a role to the given staff user and refreshes the profile cache.
|
||||
* `userId` is supplied at mutate time (picked from the staff select).
|
||||
*/
|
||||
export function useAssignRoleToUser() {
|
||||
@@ -41,7 +37,7 @@ export function useAssignRoleToUser() {
|
||||
const invalidateProfile = useInvalidateProfile();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: AddRoleUserPayload) => postRoleUser(payload),
|
||||
mutationFn: (payload: AssignUserRolePayload) => putUserRole(payload),
|
||||
onSuccess: () => {
|
||||
invalidateProfile();
|
||||
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
@@ -49,43 +45,6 @@ export function useAssignRoleToUser() {
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useAssignPermissionToRole ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* POST /permission-roles — assigns a permission to the given role and refreshes the profile cache.
|
||||
*/
|
||||
export function useAssignPermissionToRole() {
|
||||
const { t } = useTranslation();
|
||||
const invalidateProfile = useInvalidateProfile();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: AddPermissionRolePayload) => postPermissionRole(payload),
|
||||
onSuccess: () => {
|
||||
invalidateProfile();
|
||||
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// // ─── useAssignPermissionToUser ────────────────────────────────────────────────
|
||||
//
|
||||
// /**
|
||||
// * POST /permission-users — assigns a permission to the given staff user and refreshes the caches.
|
||||
// * Commented out: permissions are assigned to roles, not users.
|
||||
// */
|
||||
// export function useAssignPermissionToUser() {
|
||||
// const { t } = useTranslation();
|
||||
// const invalidateProfile = useInvalidateProfile();
|
||||
//
|
||||
// return useMutation({
|
||||
// mutationFn: (payload: AddPermissionUserPayload) => postPermissionUser(payload),
|
||||
// onSuccess: () => {
|
||||
// invalidateProfile();
|
||||
// toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
|
||||
// ─── useAssignBranchToUser ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import { useMemo } from "react";
|
||||
import { useAuthStore } from "@/app/store/authStore";
|
||||
import { isWebUser } from "@/lib/auth/permissions";
|
||||
import { hasOwnScope } from "@/lib/auth/permissions";
|
||||
import type { InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
|
||||
/**
|
||||
* When the current user belongs to the "web" guard ("user" role) and is creating
|
||||
* a record, the client / "created by" field must be locked to the user itself:
|
||||
* it is pre-filled with the current user's id and no other users are shown.
|
||||
* Admin / operator users keep the ability to pick another user.
|
||||
* Users with own-record scope must be locked to themselves when creating a
|
||||
* record: their ID is pre-filled and no other users are shown.
|
||||
* Branch/all-scope users keep the ability to pick another user.
|
||||
*/
|
||||
export function useWebSelfLock(active: boolean) {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
|
||||
return useMemo(() => {
|
||||
const locked = active && isWebUser(user);
|
||||
const locked = active && hasOwnScope(user);
|
||||
const userId = locked && user?.id != null ? String(user.id) : "";
|
||||
const userName = [user?.firstName, user?.lastName].filter(Boolean).join(" ") || user?.name || user?.email || userId;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user