Align RBAC API contract
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -71,6 +71,14 @@ src/
|
||||
└── pages/ # Router tarafından çağrılan ana sayfalar
|
||||
```
|
||||
|
||||
## 5. Authorization (RBAC) Contract
|
||||
|
||||
- Permissions use one code per module (`users`, `roles`, `branches`, `provinces`, `activity-logs`, `backups`, `currencies`, `payment-settings`, `cards`, `loans`, and `dashboard`); a granted code allows both reading and writing that module.
|
||||
- `GET /profile` supplies `role.scope` (`own`, `branch`, or `all`), `role.isSuper`, and `permissions: [{ code, name }]`. Do not depend on `guardName` or a `modules` field.
|
||||
- `GET /permissions` is a read-only `{ code, name }[]` catalog. Permission create, update, delete, tree, and detail endpoints are not supported.
|
||||
- Role creation sends `{ code, name, scope, permissions: string[] }`; role updates send `{ name, scope, permissions: string[] }`. Role codes are immutable. A role with `isSystem: true` cannot be deleted or have its scope changed.
|
||||
- User role assignment uses `PUT /users/:id/role` with `{ roleId }`. Create/update user payloads may include both `role` (code) and `roleId`; the backend prioritizes `roleId`.
|
||||
|
||||
## AI / Agent İçin Katı Talimatlar (System Instructions)
|
||||
|
||||
1. Yeni bir bileşen veya özellik ekleneceğinde her zaman önce `src/features/` altına eklenip eklenmeyeceğini değerlendir.
|
||||
|
||||
13
README.md
13
README.md
@@ -25,6 +25,7 @@ A full-featured internal banking administration panel built with **React 19 + Vi
|
||||
7. [Feature Modules](#feature-modules)
|
||||
8. [Shared Components](#shared-components)
|
||||
9. [Route Map](#route-map)
|
||||
- [RBAC API contract](#rbac-api-contract)
|
||||
10. [Development Standards](#development-standards)
|
||||
11. [Known Issues & Gaps](#known-issues--gaps)
|
||||
|
||||
@@ -558,9 +559,6 @@ All authenticated routes are nested under `DashboardLayout`. The full list:
|
||||
/settings/users/roles/:id/edit
|
||||
|
||||
/settings/users/permissions
|
||||
/settings/users/permissions/create
|
||||
/settings/users/permissions/:id
|
||||
/settings/users/permissions/:id/edit
|
||||
|
||||
/settings/loan/loan-types
|
||||
/settings/loan/loan-types/create
|
||||
@@ -595,6 +593,14 @@ All authenticated routes are nested under `DashboardLayout`. The full list:
|
||||
* → NotFoundPage
|
||||
```
|
||||
|
||||
### RBAC API contract
|
||||
|
||||
- `/profile` returns `role: { id, code, name, scope, isSuper }`, permissions as `{ code, name }[]`, and no `guardName` or `modules`.
|
||||
- Permission codes are module-level (`users`, `roles`, `branches`, `provinces`, `activity-logs`, `backups`, `currencies`, `payment-settings`, `cards`, `loans`, `dashboard`); a code grants both read and write access. The permissions screen is a read-only catalog from `GET /permissions`.
|
||||
- Roles contain `scope`, `isSuper`, `isSystem`, permission codes, and user count. Creation sends `{ code, name, scope, permissions }`; updates send `{ name, scope, permissions }`.
|
||||
- System roles cannot be deleted or have their scope changed. Role codes are immutable after creation.
|
||||
- User create/update sends the role code and `roleId` when available; role reassignment uses `PUT /users/:id/role` with `{ roleId }`.
|
||||
|
||||
---
|
||||
|
||||
## Development Standards
|
||||
@@ -640,7 +646,6 @@ These items exist in the sidebar nav or codebase but are **not yet implemented**
|
||||
| **`/settings/language/resources`** | ❌ No route or page | Same as above |
|
||||
| **`/logs`** | ❌ No route or page | Sidebar entry exists |
|
||||
| **`client.ts` uses `any`** | ⚠️ | `failedQueue: any[]` violates the no-`any` rule — should be typed |
|
||||
| **`authStore` role type** | ⚠️ | `role: 'admin' \| 'manager' \| 'viewer'` — actual role enforcement (RBAC) not wired to UI |
|
||||
| **`DashboardLayout` sidebar strings** | ⚠️ | Nav item titles use `t("English", "Fallback")` instead of proper i18n keys — inconsistent with the project standard |
|
||||
| **`AuthLayout`** | ❌ Missing | No dedicated layout for the login page; it renders without a wrapper layout |
|
||||
| **Mock data** | ⚠️ | All API functions currently return **mock in-memory data**. When connecting a real backend, replace the functions in `[feature]Api.ts` with real `apiClient.get/post/put/delete()` calls. |
|
||||
|
||||
@@ -82,9 +82,6 @@ const RoleCreatePage = lazy(() => import("@/pages/settings/users/createRole"));
|
||||
const RoleViewPage = lazy(() => import("@/pages/settings/users/rolesView"));
|
||||
const RoleEditPage = lazy(() => import("@/pages/settings/users/editRole"));
|
||||
const PermissionsPage = lazy(() => import("@/pages/settings/users/permissions"));
|
||||
const PermissionCreatePage = lazy(() => import("@/pages/settings/users/permissionsCreate"));
|
||||
const PermissionsViewPage = lazy(() => import("@/pages/settings/users/permissionsView"));
|
||||
const PermissionEditPage = lazy(() => import("@/pages/settings/users/permissionsEdit"));
|
||||
const LoanTypesPage = lazy(() => import("@/pages/settings/loan/loanTypes"));
|
||||
const LoanTypeCreatePage = lazy(() => import("@/pages/settings/loan/loanTypesCreate"));
|
||||
const LoanTypesViewPage = lazy(() => import("@/pages/settings/loan/loanTypesView"));
|
||||
@@ -654,21 +651,6 @@ const routes: AppRoute[] = [
|
||||
...bc((t) => t("permissions.title", "Rugsatlar"), "/settings/users/permissions"),
|
||||
children: [
|
||||
{ path: "/settings/users/permissions", element: page(PermissionsPage) },
|
||||
{
|
||||
path: "/settings/users/permissions/create",
|
||||
handle: { title: (t) => t("permissions.createTitle", "Rugsat döretmek") },
|
||||
element: page(PermissionCreatePage),
|
||||
},
|
||||
{
|
||||
path: "/settings/users/permissions/:id",
|
||||
handle: { title: (t) => t("permissions.viewTitle", "Rugsat giňişleýin") },
|
||||
element: page(PermissionsViewPage),
|
||||
},
|
||||
{
|
||||
path: "/settings/users/permissions/:id/edit",
|
||||
handle: { title: (t) => t("permissions.editTitle", "Rugsat üýtgetmek") },
|
||||
element: page(PermissionEditPage),
|
||||
},
|
||||
],
|
||||
},
|
||||
// Loan types
|
||||
|
||||
@@ -10,7 +10,8 @@ export interface AuthUserRole {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName?: string;
|
||||
scope: "own" | "branch" | "all";
|
||||
isSuper: boolean;
|
||||
}
|
||||
|
||||
export interface AuthUserBranch {
|
||||
@@ -20,24 +21,8 @@ export interface AuthUserBranch {
|
||||
}
|
||||
|
||||
export interface AuthUserPermission {
|
||||
id: number;
|
||||
code?: string;
|
||||
name?: string;
|
||||
guardName?: string;
|
||||
module?: string;
|
||||
}
|
||||
|
||||
export interface AuthUserModulePermission {
|
||||
id: number;
|
||||
code?: string;
|
||||
name?: string;
|
||||
guardName?: string;
|
||||
module?: string;
|
||||
}
|
||||
|
||||
export interface AuthUserModule {
|
||||
module: string;
|
||||
permissions: AuthUserModulePermission[];
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
@@ -51,7 +36,6 @@ export interface AuthUser {
|
||||
avatar?: string;
|
||||
branches?: AuthUserBranch[];
|
||||
permissions?: AuthUserPermission[];
|
||||
modules?: AuthUserModule[];
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { cn } from "@/lib/utils";
|
||||
|
||||
interface FormActionsProps {
|
||||
isPending?: boolean;
|
||||
submitDisabled?: boolean;
|
||||
onSubmit?: () => void;
|
||||
onCancel?: () => void;
|
||||
submitLabel?: ReactNode;
|
||||
@@ -28,6 +29,7 @@ interface FormActionsProps {
|
||||
|
||||
export function FormActions({
|
||||
isPending = false,
|
||||
submitDisabled = false,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
submitLabel,
|
||||
@@ -67,7 +69,7 @@ export function FormActions({
|
||||
</Button>
|
||||
)}
|
||||
{saveOnEveryStep && onSubmit && !showSubmit && (
|
||||
<Button type="button" onClick={onSubmit} disabled={isPending}>
|
||||
<Button type="button" onClick={onSubmit} disabled={isPending || submitDisabled}>
|
||||
{isPending ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
@@ -79,7 +81,7 @@ export function FormActions({
|
||||
</Button>
|
||||
)}
|
||||
{showSubmit && onSubmit && (
|
||||
<Button type="button" onClick={onSubmit} disabled={isPending}>
|
||||
<Button type="button" onClick={onSubmit} disabled={isPending || submitDisabled}>
|
||||
{isPending ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -1,46 +1,19 @@
|
||||
import type { AuthUser, AuthUserPermission } from "@/app/store/authStore";
|
||||
|
||||
/**
|
||||
* Access model:
|
||||
* - "admin" guard has full access to everything regardless of its permission list.
|
||||
* - "web" guard (public user role) can open the Orders section (loan / card / international payments).
|
||||
* - Any other guard (operator, ...) is limited to the permission codes it holds.
|
||||
*/
|
||||
|
||||
// ─── Guard names ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const ADMIN_GUARD = "admin";
|
||||
export const OPERATOR_GUARD = "operator";
|
||||
export const WEB_GUARD = "web";
|
||||
|
||||
/** True when the user's role is the admin guard (full access). */
|
||||
/** True when the role is the super role with unrestricted access. */
|
||||
export function isAdmin(user?: AuthUser | null): boolean {
|
||||
if (!user?.role) return false;
|
||||
return user.role.guardName === ADMIN_GUARD || user.role.code === "admin";
|
||||
return user?.role?.isSuper === true;
|
||||
}
|
||||
|
||||
/** True when the user's role is the web guard (the public "user" role). */
|
||||
export function isWebUser(user?: AuthUser | null): boolean {
|
||||
if (!user?.role) return false;
|
||||
return user.role.guardName === WEB_GUARD || user.role.code === "user";
|
||||
/** True when the role is limited to the user's own records. */
|
||||
export function hasOwnScope(user?: AuthUser | null): boolean {
|
||||
return user?.role?.scope === "own";
|
||||
}
|
||||
|
||||
/** Returns the list of permission codes the user holds (empty for admin since it is unrestricted). */
|
||||
/** Returns the permission codes exposed by GET /profile. */
|
||||
export function getPermissionCodes(user?: AuthUser | null): string[] {
|
||||
if (isAdmin(user)) return [];
|
||||
const seen = new Set<string>();
|
||||
const codes: string[] = [];
|
||||
const push = (p?: Pick<AuthUserPermission, "code"> | { code?: string }) => {
|
||||
if (p?.code && !seen.has(p.code)) {
|
||||
seen.add(p.code);
|
||||
codes.push(p.code);
|
||||
}
|
||||
};
|
||||
for (const p of user?.permissions ?? []) push(p);
|
||||
for (const m of user?.modules ?? []) {
|
||||
for (const p of m.permissions ?? []) push(p);
|
||||
}
|
||||
return codes;
|
||||
return [...new Set((user?.permissions ?? []).map((permission: AuthUserPermission) => permission.code))];
|
||||
}
|
||||
|
||||
/** Returns true when the user may access the page protected by the given permission code. */
|
||||
@@ -63,18 +36,17 @@ export function hasAnyPermission(user: AuthUser | null | undefined, codes: reado
|
||||
// ─── Permission constants used to gate nav items / pages ──────────────────────
|
||||
|
||||
export const PERM = {
|
||||
DASHBOARD: "dashboard",
|
||||
LOANS: "loans",
|
||||
CARDS: "cards",
|
||||
USERS_VIEW: "users.view",
|
||||
USERS_MANAGE: "users.manage",
|
||||
ROLES_VIEW: "roles.view",
|
||||
BRANCHES_VIEW: "branches.view",
|
||||
PROVINCES_VIEW: "provinces.view",
|
||||
BACKUPS_VIEW: "backups.view",
|
||||
ACTIVITY_LOGS_VIEW: "activity-logs.view",
|
||||
CURRENCIES_VIEW: "currencies.view",
|
||||
/** Sentinel for pages that only the admin guard may access (no permission code exists). */
|
||||
ADMIN_ONLY: "__admin_only__",
|
||||
USERS: "users",
|
||||
ROLES: "roles",
|
||||
BRANCHES: "branches",
|
||||
PROVINCES: "provinces",
|
||||
ACTIVITY_LOGS: "activity-logs",
|
||||
BACKUPS: "backups",
|
||||
CURRENCIES: "currencies",
|
||||
PAYMENT_SETTINGS: "payment-settings",
|
||||
} as const;
|
||||
|
||||
type PermValue = (typeof PERM)[keyof typeof PERM];
|
||||
@@ -84,10 +56,7 @@ type PermValue = (typeof PERM)[keyof typeof PERM];
|
||||
type RouteRule = readonly [prefix: string, codes: readonly PermValue[]];
|
||||
|
||||
const ROUTE_RULES: RouteRule[] = [
|
||||
// System / admin-only
|
||||
["/dashboard", [PERM.ADMIN_ONLY]],
|
||||
// Settings (admin-only)
|
||||
["/settings", [PERM.ADMIN_ONLY]],
|
||||
["/dashboard", [PERM.DASHBOARD]],
|
||||
// Loan department
|
||||
["/loan-orders", [PERM.LOANS]],
|
||||
["/loan-order-mobiles", [PERM.LOANS]],
|
||||
@@ -99,20 +68,28 @@ const ROUTE_RULES: RouteRule[] = [
|
||||
["/card-requisites", [PERM.CARDS]],
|
||||
["/card-balances", [PERM.CARDS]],
|
||||
["/card-pins", [PERM.CARDS]],
|
||||
// International payments + online payment history (no permission yet → admin-only)
|
||||
["/visa-master", [PERM.ADMIN_ONLY]],
|
||||
["/sber-payments", [PERM.ADMIN_ONLY]],
|
||||
["/online-payments-history", [PERM.ADMIN_ONLY]],
|
||||
// Payment operations are covered by the existing cards module permission.
|
||||
["/visa-master", [PERM.CARDS]],
|
||||
["/sber-payments", [PERM.CARDS]],
|
||||
["/online-payments-history", [PERM.CARDS]],
|
||||
// Users (operators / clients / all users)
|
||||
["/operators", [PERM.USERS_VIEW, PERM.USERS_MANAGE]],
|
||||
["/all-users", [PERM.USERS_VIEW, PERM.USERS_MANAGE]],
|
||||
["/clients", [PERM.USERS_VIEW, PERM.USERS_MANAGE]],
|
||||
["/operators", [PERM.USERS]],
|
||||
["/all-users", [PERM.USERS]],
|
||||
["/clients", [PERM.USERS]],
|
||||
// Currencies
|
||||
["/currency-rates", [PERM.CURRENCIES_VIEW]],
|
||||
["/visa-master-sber-settings", [PERM.CURRENCIES_VIEW]],
|
||||
["/currency-rates", [PERM.CURRENCIES]],
|
||||
["/visa-master-sber-settings", [PERM.CURRENCIES]],
|
||||
// System pages
|
||||
["/backups", [PERM.BACKUPS_VIEW]],
|
||||
["/logs", [PERM.ACTIVITY_LOGS_VIEW]],
|
||||
["/backups", [PERM.BACKUPS]],
|
||||
["/logs", [PERM.ACTIVITY_LOGS]],
|
||||
["/settings/users/roles", [PERM.ROLES]],
|
||||
["/settings/users/permissions", [PERM.ROLES]],
|
||||
["/settings/location/branches", [PERM.BRANCHES]],
|
||||
["/settings/location/districts", [PERM.PROVINCES]],
|
||||
["/settings/payment", [PERM.PAYMENT_SETTINGS]],
|
||||
["/settings/loan", [PERM.LOANS]],
|
||||
["/settings/card", [PERM.CARDS]],
|
||||
["/settings/language", [PERM.ROLES]],
|
||||
];
|
||||
|
||||
/** Match a path against the rule prefixes (exact or sub-path). */
|
||||
@@ -138,57 +115,26 @@ export function permissionForUrl(url: string | undefined): readonly PermValue[]
|
||||
export function canAccessUrl(user: AuthUser | null | undefined, url: string | undefined): boolean {
|
||||
if (!url) return false;
|
||||
if (isAdmin(user)) return true;
|
||||
if (isWebUser(user) && isWebAccessiblePath(url)) return true;
|
||||
return hasAnyPermission(user, permissionForUrl(url));
|
||||
}
|
||||
|
||||
// ─── Web (public user) section ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Paths that the "web" guard (public user role) may open regardless of its
|
||||
* permission list. Covers the whole Orders section: loan department,
|
||||
* card department and international payments.
|
||||
*/
|
||||
const WEB_ACCESS_PREFIXES: readonly string[] = [
|
||||
// Loan department
|
||||
"/loan-orders",
|
||||
"/loan-order-mobiles",
|
||||
"/loan-remaining",
|
||||
"/loan-paid-off-letters",
|
||||
// Card department
|
||||
"/order-new-card",
|
||||
"/card-transactions",
|
||||
"/card-requisites",
|
||||
"/card-balances",
|
||||
"/card-pins",
|
||||
// International payments
|
||||
"/visa-master",
|
||||
"/sber-payments",
|
||||
];
|
||||
|
||||
/** True when the path is inside the Orders section available to the web guard. */
|
||||
function isWebAccessiblePath(pathname: string): boolean {
|
||||
const clean = pathname.split("?")[0];
|
||||
return WEB_ACCESS_PREFIXES.some((prefix) => clean === prefix || clean.startsWith(`${prefix}/`));
|
||||
}
|
||||
|
||||
// ─── Home path ────────────────────────────────────────────────────────────────
|
||||
|
||||
const HOME_PRIORITY: readonly (readonly [codes: readonly PermValue[], path: string])[] = [
|
||||
[[PERM.LOANS], "/loan-orders"],
|
||||
[[PERM.CARDS], "/order-new-card"],
|
||||
[[PERM.USERS_VIEW, PERM.USERS_MANAGE], "/operators"],
|
||||
[[PERM.CURRENCIES_VIEW], "/currency-rates"],
|
||||
[[PERM.BACKUPS_VIEW], "/backups"],
|
||||
[[PERM.ACTIVITY_LOGS_VIEW], "/logs"],
|
||||
[[PERM.USERS], "/operators"],
|
||||
[[PERM.CURRENCIES], "/currency-rates"],
|
||||
[[PERM.BACKUPS], "/backups"],
|
||||
[[PERM.ACTIVITY_LOGS], "/logs"],
|
||||
];
|
||||
|
||||
/** Returns the landing page for the user: admin → dashboard, web → orders, else the first page they may open. */
|
||||
/** Returns the landing page for the user based on their role and permissions. */
|
||||
export function getDefaultHomePath(user: AuthUser | null | undefined): string {
|
||||
if (isAdmin(user)) return "/dashboard";
|
||||
if (isWebUser(user)) return "/loan-orders";
|
||||
for (const [codes, path] of HOME_PRIORITY) {
|
||||
if (hasAnyPermission(user, codes)) return path;
|
||||
}
|
||||
if (hasPermission(user, PERM.DASHBOARD)) return "/dashboard";
|
||||
return "/profile";
|
||||
}
|
||||
|
||||
@@ -1079,10 +1079,7 @@
|
||||
"onlinePayments.fields.onlinePaymantableType": "Online payment table type",
|
||||
"onlinePayments.fields.createdAt": "Created at",
|
||||
"onlinePayments.fields.updatedAt": "Updated at",
|
||||
"permissions.createTitle": "Create permission",
|
||||
"permissions.editTitle": "Edit permission",
|
||||
"permissions.title": "Permissions",
|
||||
"permissions.viewTitle": "Permission detail",
|
||||
"requiredDocuments.createTitle": "Create document",
|
||||
"requiredDocuments.editTitle": "Edit document",
|
||||
"requiredDocuments.title": "Required documents",
|
||||
@@ -1429,19 +1426,22 @@
|
||||
"intlPayment.regions.DZ": "Dashoguz",
|
||||
"intlPayment.regions.LB": "Lebap",
|
||||
"intlPayment.regions.MR": "Mary",
|
||||
"permissions.actions.create": "Create permission",
|
||||
"permissions.deleteDialog.description": "Are you sure you want to delete this permission? This action cannot be undone.",
|
||||
"permissions.deleteDialog.title": "Delete permission",
|
||||
"permissions.fields.code": "CODE",
|
||||
"permissions.fields.guardName": "GUARD NAME",
|
||||
"permissions.fields.name": "NAME",
|
||||
"permissions.searchPlaceholder": "Search...",
|
||||
"roles.actions.create": "Create role",
|
||||
"roles.deleteDialog.description": "Are you sure you want to delete this role? This action cannot be undone.",
|
||||
"roles.deleteDialog.title": "Delete role",
|
||||
"roles.fields.code": "CODE",
|
||||
"roles.fields.guardName": "GUARD NAME",
|
||||
"roles.fields.name": "NAME",
|
||||
"roles.fields.scope": "SCOPE",
|
||||
"roles.fields.isSuper": "SUPER ROLE",
|
||||
"roles.fields.isSystem": "SYSTEM ROLE",
|
||||
"roles.fields.permissions": "PERMISSIONS",
|
||||
"roles.fields.usersCount": "USERS",
|
||||
"roles.scope.own": "Own",
|
||||
"roles.scope.branch": "Branch",
|
||||
"roles.scope.all": "All branches",
|
||||
"roles.searchPlaceholder": "Search...",
|
||||
"branches.fields.name": "Branch name",
|
||||
"branches.fields.namePlaceholder": "Branch name",
|
||||
|
||||
@@ -1080,10 +1080,7 @@
|
||||
"onlinePayments.fields.onlinePaymantableType": "Тип онлайн-таблицы",
|
||||
"onlinePayments.fields.createdAt": "Дата создания",
|
||||
"onlinePayments.fields.updatedAt": "Дата обновления",
|
||||
"permissions.createTitle": "Создать разрешение",
|
||||
"permissions.editTitle": "Редактировать разрешение",
|
||||
"permissions.title": "Разрешения",
|
||||
"permissions.viewTitle": "Детали разрешения",
|
||||
"requiredDocuments.createTitle": "Создать документ",
|
||||
"requiredDocuments.editTitle": "Редактировать документ",
|
||||
"requiredDocuments.title": "Необходимые документы",
|
||||
@@ -1430,19 +1427,22 @@
|
||||
"intlPayment.regions.DZ": "Дашогуз",
|
||||
"intlPayment.regions.LB": "Лебап",
|
||||
"intlPayment.regions.MR": "Мары",
|
||||
"permissions.actions.create": "Создать разрешение",
|
||||
"permissions.deleteDialog.description": "Вы уверены, что хотите удалить это разрешение? Это действие необратимо.",
|
||||
"permissions.deleteDialog.title": "Удалить разрешение",
|
||||
"permissions.fields.code": "КОД",
|
||||
"permissions.fields.guardName": "GUARD NAME",
|
||||
"permissions.fields.name": "ИМЯ",
|
||||
"permissions.searchPlaceholder": "Поиск...",
|
||||
"roles.actions.create": "Создать роль",
|
||||
"roles.deleteDialog.description": "Вы уверены, что хотите удалить эту роль? Это действие необратимо.",
|
||||
"roles.deleteDialog.title": "Удалить роль",
|
||||
"roles.fields.code": "КОД",
|
||||
"roles.fields.guardName": "GUARD NAME",
|
||||
"roles.fields.name": "ИМЯ",
|
||||
"roles.fields.scope": "ОБЛАСТЬ",
|
||||
"roles.fields.isSuper": "СУПЕР-РОЛЬ",
|
||||
"roles.fields.isSystem": "СИСТЕМНАЯ РОЛЬ",
|
||||
"roles.fields.permissions": "РАЗРЕШЕНИЯ",
|
||||
"roles.fields.usersCount": "ПОЛЬЗОВАТЕЛИ",
|
||||
"roles.scope.own": "Собственные",
|
||||
"roles.scope.branch": "Филиал",
|
||||
"roles.scope.all": "Все филиалы",
|
||||
"roles.searchPlaceholder": "Поиск...",
|
||||
"branches.fields.name": "Название филиала",
|
||||
"branches.fields.namePlaceholder": "Название филиала",
|
||||
|
||||
@@ -1077,10 +1077,7 @@
|
||||
"onlinePayments.fields.onlinePaymantableType": "Online töleg tablisasynyň görnüşi",
|
||||
"onlinePayments.fields.createdAt": "Döredilen wagty",
|
||||
"onlinePayments.fields.updatedAt": "Üýtgedilen wagty",
|
||||
"permissions.createTitle": "Rugsat döretmek",
|
||||
"permissions.editTitle": "Rugsat üýtgetmek",
|
||||
"permissions.title": "Rugsatlar",
|
||||
"permissions.viewTitle": "Rugsat giňişleýin",
|
||||
"requiredDocuments.createTitle": "Resminama döretmek",
|
||||
"requiredDocuments.editTitle": "Resminama üýtgetmek",
|
||||
"requiredDocuments.title": "Gerekli resminamalar",
|
||||
@@ -1432,15 +1429,18 @@
|
||||
"roles.deleteDialog.description": "Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.",
|
||||
"roles.deleteDialog.title": "Roly pozmak",
|
||||
"roles.fields.code": "KOD",
|
||||
"roles.fields.guardName": "GUARD NAME",
|
||||
"roles.fields.name": "ADY",
|
||||
"roles.fields.scope": "ÇÄK",
|
||||
"roles.fields.isSuper": "SUPER ROL",
|
||||
"roles.fields.isSystem": "ULGAM ROLY",
|
||||
"roles.fields.permissions": "RUGSATLAR",
|
||||
"roles.fields.usersCount": "ULANYJYLAR",
|
||||
"roles.scope.own": "Öz ýazgylary",
|
||||
"roles.scope.branch": "Şahamça",
|
||||
"roles.scope.all": "Ähli şahamçalar",
|
||||
"roles.searchPlaceholder": "Gözlemek...",
|
||||
"permissions.actions.create": "Rugsat dörediň",
|
||||
"permissions.deleteDialog.description": "Bu rugsady pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.",
|
||||
"permissions.deleteDialog.title": "Rugsaty pozmak",
|
||||
"permissions.fields.code": "KOD",
|
||||
"permissions.fields.name": "ADY",
|
||||
"permissions.fields.guardName": "GUARD NAME",
|
||||
"permissions.searchPlaceholder": "Gözlemek...",
|
||||
"branches.fields.name": "Şahamçanyň ady",
|
||||
"branches.fields.namePlaceholder": "Şahamçanyň ady",
|
||||
|
||||
@@ -202,6 +202,13 @@ export default function ProfilePage() {
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
{user.role && <InfoRow label={t("roles.fields.scope", "Scope")} value={user.role.scope} />}
|
||||
{user.role && (
|
||||
<InfoRow
|
||||
label={t("roles.fields.isSuper", "Super role")}
|
||||
value={user.role.isSuper ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
||||
/>
|
||||
)}
|
||||
|
||||
<InfoRow label={t("users.sections.branches", "Şahamçalar")}>
|
||||
{branches.length > 0 ? (
|
||||
@@ -236,23 +243,12 @@ export default function ProfilePage() {
|
||||
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}>
|
||||
{permissions.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{permissions.map((p) =>
|
||||
isAdmin ? (
|
||||
<Link
|
||||
key={p.id}
|
||||
to={`/settings/users/permissions/${p.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
||||
>
|
||||
<KeyRound size={11} className="text-muted-foreground" />
|
||||
<span className="text-foreground font-medium">{p.name || p.code || p.id}</span>
|
||||
</Link>
|
||||
) : (
|
||||
<span key={p.id} className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1">
|
||||
<KeyRound size={11} className="text-muted-foreground" />
|
||||
<span className="text-foreground font-medium">{p.name || p.code || p.id}</span>
|
||||
</span>
|
||||
),
|
||||
)}
|
||||
{permissions.map((permission) => (
|
||||
<span key={permission.code} className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1">
|
||||
<KeyRound size={11} className="text-muted-foreground" />
|
||||
<span className="text-foreground font-medium">{permission.name || permission.code}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
@@ -267,10 +263,6 @@ export default function ProfilePage() {
|
||||
<Shield size={14} />
|
||||
{t("profile.actions.assignRole", "Rol birikdiriň")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("permission")}>
|
||||
<KeyRound size={14} />
|
||||
{t("profile.actions.assignPermissionRole", "Rola rugsat birikdiriň")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("branch")}>
|
||||
<Building2 size={14} />
|
||||
{t("profile.actions.assignBranch", "Şahamça birikdiriň")}
|
||||
@@ -340,7 +332,7 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Assign dialog (role/permission/branch) ─────────────── */}
|
||||
{/* ── Assign dialog (role/branch) ───────────────────────── */}
|
||||
{assignDialog && <AssignDialog kind={assignDialog} onClose={() => setAssignDialog(null)} />}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,163 +1,89 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { usePermissions, useDeletePermission } from "@/features/permissions/hooks/usePermissions";
|
||||
import { usePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||
import type { Permission } from "@/features/permissions/api/permissionsApi";
|
||||
|
||||
// ─── PermissionsPage ──────────────────────────────────────────────────────────
|
||||
|
||||
export default function PermissionsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const columnMeta = useMemo(
|
||||
() => [
|
||||
{ id: "id", label: t("common.id", "ID") },
|
||||
{ id: "code", label: t("permissions.fields.code", "Kod") },
|
||||
{ id: "name", label: t("permissions.fields.name", "Ady") },
|
||||
{ id: "guardName", label: t("permissions.fields.guardName", "Guard name") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
// ── State ──────────────────────────────────────────────────────────────────
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
const { data = [], isLoading, isError } = usePermissions();
|
||||
|
||||
// ── Data ───────────────────────────────────────────────────────────────────
|
||||
const { data, isLoading } = usePermissions({ search, page, limit: perPage });
|
||||
const deletePermission = useDeletePermission();
|
||||
const filteredPermissions = useMemo(() => {
|
||||
const term = search.trim().toLocaleLowerCase();
|
||||
if (!term) return data;
|
||||
return data.filter((permission) => `${permission.code} ${permission.name}`.toLocaleLowerCase().includes(term));
|
||||
}, [data, search]);
|
||||
const pagePermissions = filteredPermissions.slice((page - 1) * perPage, page * perPage);
|
||||
|
||||
// ── Columns ────────────────────────────────────────────────────────────────
|
||||
const columnMeta = [
|
||||
{ id: "code", label: t("permissions.fields.code", "Kod") },
|
||||
{ id: "name", label: t("permissions.fields.name", "Ady") },
|
||||
];
|
||||
const columns: ColumnDef<Permission>[] = [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: t("common.id", "ID"),
|
||||
size: 70,
|
||||
cell: ({ row }) => <span className="text-primary font-semibold">{row.original.id}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "code",
|
||||
header: t("permissions.fields.code", "Kod"),
|
||||
},
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("permissions.fields.name", "Ady"),
|
||||
cell: ({ row }) => <span>{row.original.name ?? "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "guardName",
|
||||
header: t("permissions.fields.guardName", "Guard name"),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
size: 120,
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/settings/users/permissions/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/settings/users/permissions/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deletePermission.isPending}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{ accessorKey: "code", header: t("permissions.fields.code", "Kod") },
|
||||
{ accessorKey: "name", header: t("permissions.fields.name", "Ady") },
|
||||
];
|
||||
|
||||
// ── Handlers ───────────────────────────────────────────────────────────────
|
||||
const handleConfirmDelete = () => {
|
||||
if (deleteId === null) return;
|
||||
deletePermission.mutate(deleteId, {
|
||||
onSuccess: () => setDeleteId(null),
|
||||
onError: () => setDeleteId(null),
|
||||
});
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Page heading */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-foreground">{t("permissions.title", "Rugsatlar")}</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
<TableSearchInput
|
||||
value={search}
|
||||
onChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={t("permissions.searchPlaceholder", "Gözlemek...")}
|
||||
/>
|
||||
<CreateButton
|
||||
label={t("permissions.actions.create", "Rugsat dörediň")}
|
||||
onClick={() => navigate("/settings/users/permissions/create")}
|
||||
/>
|
||||
</div>
|
||||
{/* Toolbar */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.permissions ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={Math.max(1, Math.ceil((data?.count ?? 0) / perPage))}
|
||||
totalCount={data?.count}
|
||||
onPageChange={setPage}
|
||||
toolbar={
|
||||
<DataTableToolbar
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("permissions.searchPlaceholder", "Gözlemek...")}
|
||||
columns={columnMeta}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Delete confirmation dialog */}
|
||||
<DeleteDialog
|
||||
open={deleteId !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDeleteId(null);
|
||||
<h1 className="text-2xl font-bold text-foreground">{t("permissions.title", "Rugsatlar")}</h1>
|
||||
<TableSearchInput
|
||||
value={search}
|
||||
onChange={(value) => {
|
||||
setSearch(value);
|
||||
setPage(1);
|
||||
}}
|
||||
title={t("permissions.deleteDialog.title", "Rugsaty pozmak")}
|
||||
description={t("permissions.deleteDialog.description", "Bu rugsaty pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")}
|
||||
onConfirm={handleConfirmDelete}
|
||||
isLoading={deletePermission.isPending}
|
||||
placeholder={t("permissions.searchPlaceholder", "Gözlemek...")}
|
||||
/>
|
||||
{isError ? (
|
||||
<p className="text-sm text-destructive">{t("common.fetchError", "Maglumat ýüklenmedi.")}</p>
|
||||
) : (
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={pagePermissions}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
getRowId={(permission) => permission.code}
|
||||
currentPage={page}
|
||||
totalPages={Math.max(1, Math.ceil(filteredPermissions.length / perPage))}
|
||||
totalCount={filteredPermissions.length}
|
||||
onPageChange={setPage}
|
||||
toolbar={
|
||||
<DataTableToolbar
|
||||
searchValue={search}
|
||||
onSearchChange={(value) => {
|
||||
setSearch(value);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("permissions.searchPlaceholder", "Gözlemek...")}
|
||||
columns={columnMeta}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(value) => {
|
||||
setPerPage(value);
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { PermissionForm } from '@/features/permissions/components/permissionsForm'
|
||||
|
||||
export default function PermissionCreatePage() {
|
||||
return <PermissionForm mode="create" />
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PageSpinner } from '@/components/pageSpinner'
|
||||
import { PageError } from '@/components/pageError'
|
||||
import { PermissionForm } from '@/features/permissions/components/permissionsForm'
|
||||
import { usePermission } from '@/features/permissions/hooks/usePermissions'
|
||||
|
||||
export default function PermissionEditPage() {
|
||||
const { t } = useTranslation()
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const numericId = Number(id)
|
||||
const { data: permission, isLoading, isError } = usePermission(numericId)
|
||||
|
||||
if (isLoading) return <PageSpinner />
|
||||
if (isError || !permission) return <PageError message={t('common.notFound', 'Tapylmady')} />
|
||||
|
||||
return <PermissionForm mode="edit" initialData={permission} />
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Section, InfoRow, ViewActions } from "@/components/viewPageComponents";
|
||||
import { usePermission, useDeletePermission } from "@/features/permissions/hooks/usePermissions";
|
||||
|
||||
// ─── PermissionViewPage ───────────────────────────────────────────────────────
|
||||
|
||||
export default function PermissionViewPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const permissionId = Number(id);
|
||||
|
||||
const { data: permission, isLoading, isError } = usePermission(permissionId);
|
||||
const deletePermission = useDeletePermission();
|
||||
|
||||
const handleDelete = async () => {
|
||||
await deletePermission.mutateAsync(permissionId);
|
||||
navigate("/settings/users/permissions");
|
||||
};
|
||||
|
||||
// ── Loading skeleton ───────────────────────────────────────────────────────
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div>
|
||||
<Skeleton className="h-8 w-72 mb-6" />
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start sm:items-center py-3 px-4 gap-2 sm:gap-0"
|
||||
>
|
||||
<Skeleton className="h-4 w-20" />
|
||||
<Skeleton className="h-4 w-40" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError || !permission) {
|
||||
return <p className="text-destructive text-sm">{t("common.fetchError", "Maglumat ýüklenmedi.")}</p>;
|
||||
}
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div>
|
||||
{/* Page heading + actions */}
|
||||
<div className="flex items-start justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
{t("permissions.viewTitle", "Rugsat giňişleýin")}: {permission.name}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<ViewActions
|
||||
editTo={`/settings/users/permissions/${permissionId}/edit`}
|
||||
onDelete={handleDelete}
|
||||
deleting={deletePermission.isPending}
|
||||
deleteTitle={t("permissions.deleteDialog.title", "Rugsaty pozmak")}
|
||||
deleteDescription={t("permissions.deleteDialog.description", "Bu rugsaty pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")}
|
||||
deleteConfirmLabel={t("common.delete", "Poz")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Detail section */}
|
||||
<Section>
|
||||
<InfoRow label={t("common.id", "ID")} value={permission.id} />
|
||||
<InfoRow label={t("permissions.fields.code", "Kod")} value={permission.code} />
|
||||
<InfoRow label={t("permissions.fields.name", "Ady")} value={permission.name} />
|
||||
<InfoRow label={t("permissions.fields.guardName", "Guard name")} value={permission.guardName} />
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -22,7 +22,8 @@ export default function RolesPage() {
|
||||
{ id: "id", label: t("common.id", "ID") },
|
||||
{ id: "code", label: t("roles.fields.code", "Kod") },
|
||||
{ id: "name", label: t("roles.fields.name", "Ady") },
|
||||
{ id: "guardName", label: t("roles.fields.guardName", "Guard name") },
|
||||
{ id: "scope", label: t("roles.fields.scope", "Scope") },
|
||||
{ id: "usersCount", label: t("roles.fields.usersCount", "Users") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
@@ -56,10 +57,8 @@ export default function RolesPage() {
|
||||
header: t("roles.fields.name", "Ady"),
|
||||
cell: ({ row }) => <span>{row.original.name ?? "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "guardName",
|
||||
header: t("roles.fields.guardName", "Guard name"),
|
||||
},
|
||||
{ accessorKey: "scope", header: t("roles.fields.scope", "Scope") },
|
||||
{ accessorKey: "usersCount", header: t("roles.fields.usersCount", "Users") },
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
@@ -70,7 +69,7 @@ export default function RolesPage() {
|
||||
<TableActions
|
||||
onView={() => navigate(`/settings/users/roles/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/settings/users/roles/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
onDelete={row.original.isSystem ? undefined : () => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteRole.isPending}
|
||||
/>
|
||||
),
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function RoleViewPage() {
|
||||
<div className="flex items-center gap-2">
|
||||
<ViewActions
|
||||
editTo={`/settings/users/roles/${roleId}/edit`}
|
||||
onDelete={handleDelete}
|
||||
onDelete={role.isSystem ? undefined : handleDelete}
|
||||
deleting={deleteRole.isPending}
|
||||
deleteTitle={t("roles.deleteDialog.title", "Roly pozmak")}
|
||||
deleteDescription={t("roles.deleteDialog.description", "Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")}
|
||||
@@ -69,7 +69,11 @@ export default function RoleViewPage() {
|
||||
<InfoRow label="ID" value={role.id} />
|
||||
<InfoRow label={t("roles.fields.code", "Kod")} value={role.code} />
|
||||
<InfoRow label={t("roles.fields.name", "Ady")} value={role.name} />
|
||||
<InfoRow label={t("roles.fields.guardName", "Guard name")} value={role.guardName} />
|
||||
<InfoRow label={t("roles.fields.scope", "Scope")} value={role.scope} />
|
||||
<InfoRow label={t("roles.fields.isSuper", "Super role")} value={role.isSuper ? t("common.yes", "Yes") : t("common.no", "No")} />
|
||||
<InfoRow label={t("roles.fields.isSystem", "System role")} value={role.isSystem ? t("common.yes", "Yes") : t("common.no", "No")} />
|
||||
<InfoRow label={t("roles.fields.usersCount", "Users")} value={role.usersCount} />
|
||||
<InfoRow label={t("roles.fields.permissions", "Rugsatlar")} value={role.permissions.join(", ")} />
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -126,7 +126,7 @@ export default function ClientDetailPage() {
|
||||
<InfoRow label={t("clients.sections.permissions", "Rugsatlar")}>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{permissions.map((p) => (
|
||||
<Badge key={p.id} variant="secondary">
|
||||
<Badge key={p.code} variant="secondary">
|
||||
{p.name}
|
||||
</Badge>
|
||||
))}
|
||||
|
||||
@@ -125,7 +125,7 @@ export default function OperatorDetailPage() {
|
||||
<InfoRow label={t("operators.sections.permissions", "Rugsatlar")}>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{permissions.map((p) => (
|
||||
<Badge key={p.id} variant="secondary">
|
||||
<Badge key={p.code} variant="secondary">
|
||||
{p.name}
|
||||
</Badge>
|
||||
))}
|
||||
|
||||
Reference in New Issue
Block a user