Align RBAC API contract
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
1 parent
8dc61d7786
commit
4c4d037a1e
39 files changed
+410
-1071
No files matched your search
@@ -71,6 +71,14 @@ src/
|
|||||||
└── pages/ # Router tarafından çağrılan ana sayfalar
|
└── 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)
|
## 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.
|
1. Yeni bir bileşen veya özellik ekleneceğinde her zaman önce `src/features/` altına eklenip eklenmeyeceğini değerlendir.
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ A full-featured internal banking administration panel built with **React 19 + Vi
|
|||||||
7. [Feature Modules](#feature-modules)
|
7. [Feature Modules](#feature-modules)
|
||||||
8. [Shared Components](#shared-components)
|
8. [Shared Components](#shared-components)
|
||||||
9. [Route Map](#route-map)
|
9. [Route Map](#route-map)
|
||||||
|
- [RBAC API contract](#rbac-api-contract)
|
||||||
10. [Development Standards](#development-standards)
|
10. [Development Standards](#development-standards)
|
||||||
11. [Known Issues & Gaps](#known-issues--gaps)
|
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/roles/:id/edit
|
||||||
|
|
||||||
/settings/users/permissions
|
/settings/users/permissions
|
||||||
/settings/users/permissions/create
|
|
||||||
/settings/users/permissions/:id
|
|
||||||
/settings/users/permissions/:id/edit
|
|
||||||
|
|
||||||
/settings/loan/loan-types
|
/settings/loan/loan-types
|
||||||
/settings/loan/loan-types/create
|
/settings/loan/loan-types/create
|
||||||
@@ -595,6 +593,14 @@ All authenticated routes are nested under `DashboardLayout`. The full list:
|
|||||||
* → NotFoundPage
|
* → 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
|
## 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 |
|
| **`/settings/language/resources`** | ❌ No route or page | Same as above |
|
||||||
| **`/logs`** | ❌ No route or page | Sidebar entry exists |
|
| **`/logs`** | ❌ No route or page | Sidebar entry exists |
|
||||||
| **`client.ts` uses `any`** | ⚠️ | `failedQueue: any[]` violates the no-`any` rule — should be typed |
|
| **`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 |
|
| **`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 |
|
| **`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. |
|
| **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 RoleViewPage = lazy(() => import("@/pages/settings/users/rolesView"));
|
||||||
const RoleEditPage = lazy(() => import("@/pages/settings/users/editRole"));
|
const RoleEditPage = lazy(() => import("@/pages/settings/users/editRole"));
|
||||||
const PermissionsPage = lazy(() => import("@/pages/settings/users/permissions"));
|
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 LoanTypesPage = lazy(() => import("@/pages/settings/loan/loanTypes"));
|
||||||
const LoanTypeCreatePage = lazy(() => import("@/pages/settings/loan/loanTypesCreate"));
|
const LoanTypeCreatePage = lazy(() => import("@/pages/settings/loan/loanTypesCreate"));
|
||||||
const LoanTypesViewPage = lazy(() => import("@/pages/settings/loan/loanTypesView"));
|
const LoanTypesViewPage = lazy(() => import("@/pages/settings/loan/loanTypesView"));
|
||||||
@@ -654,21 +651,6 @@ const routes: AppRoute[] = [
|
|||||||
...bc((t) => t("permissions.title", "Rugsatlar"), "/settings/users/permissions"),
|
...bc((t) => t("permissions.title", "Rugsatlar"), "/settings/users/permissions"),
|
||||||
children: [
|
children: [
|
||||||
{ path: "/settings/users/permissions", element: page(PermissionsPage) },
|
{ 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
|
// Loan types
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ export interface AuthUserRole {
|
|||||||
id: number;
|
id: number;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName?: string;
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthUserBranch {
|
export interface AuthUserBranch {
|
||||||
@@ -20,24 +21,8 @@ export interface AuthUserBranch {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthUserPermission {
|
export interface AuthUserPermission {
|
||||||
id: number;
|
code: string;
|
||||||
code?: string;
|
name: 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[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthUser {
|
export interface AuthUser {
|
||||||
@@ -51,7 +36,6 @@ export interface AuthUser {
|
|||||||
avatar?: string;
|
avatar?: string;
|
||||||
branches?: AuthUserBranch[];
|
branches?: AuthUserBranch[];
|
||||||
permissions?: AuthUserPermission[];
|
permissions?: AuthUserPermission[];
|
||||||
modules?: AuthUserModule[];
|
|
||||||
createdAt?: string;
|
createdAt?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { cn } from "@/lib/utils";
|
|||||||
|
|
||||||
interface FormActionsProps {
|
interface FormActionsProps {
|
||||||
isPending?: boolean;
|
isPending?: boolean;
|
||||||
|
submitDisabled?: boolean;
|
||||||
onSubmit?: () => void;
|
onSubmit?: () => void;
|
||||||
onCancel?: () => void;
|
onCancel?: () => void;
|
||||||
submitLabel?: ReactNode;
|
submitLabel?: ReactNode;
|
||||||
@@ -28,6 +29,7 @@ interface FormActionsProps {
|
|||||||
|
|
||||||
export function FormActions({
|
export function FormActions({
|
||||||
isPending = false,
|
isPending = false,
|
||||||
|
submitDisabled = false,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onCancel,
|
onCancel,
|
||||||
submitLabel,
|
submitLabel,
|
||||||
@@ -67,7 +69,7 @@ export function FormActions({
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{saveOnEveryStep && onSubmit && !showSubmit && (
|
{saveOnEveryStep && onSubmit && !showSubmit && (
|
||||||
<Button type="button" onClick={onSubmit} disabled={isPending}>
|
<Button type="button" onClick={onSubmit} disabled={isPending || submitDisabled}>
|
||||||
{isPending ? (
|
{isPending ? (
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<Loader2 size={14} className="animate-spin" />
|
<Loader2 size={14} className="animate-spin" />
|
||||||
@@ -79,7 +81,7 @@ export function FormActions({
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{showSubmit && onSubmit && (
|
{showSubmit && onSubmit && (
|
||||||
<Button type="button" onClick={onSubmit} disabled={isPending}>
|
<Button type="button" onClick={onSubmit} disabled={isPending || submitDisabled}>
|
||||||
{isPending ? (
|
{isPending ? (
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<Loader2 size={14} className="animate-spin" />
|
<Loader2 size={14} className="animate-spin" />
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export interface User {
|
|||||||
socialMedia: SocialMedia;
|
socialMedia: SocialMedia;
|
||||||
lightMode: number;
|
lightMode: number;
|
||||||
role: string;
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
@@ -48,6 +49,7 @@ export interface CreateUserPayload {
|
|||||||
password: string;
|
password: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
role: string;
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
socialMedia: SocialMedia;
|
socialMedia: SocialMedia;
|
||||||
username: string;
|
username: string;
|
||||||
}
|
}
|
||||||
@@ -62,6 +64,7 @@ export interface UpdateUserPayload {
|
|||||||
name?: string;
|
name?: string;
|
||||||
phone?: string;
|
phone?: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
|
roleId?: number;
|
||||||
socialMedia?: SocialMedia;
|
socialMedia?: SocialMedia;
|
||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -103,6 +103,7 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
|||||||
email: initialData.email ?? "",
|
email: initialData.email ?? "",
|
||||||
avatar: initialData.avatar ?? "",
|
avatar: initialData.avatar ?? "",
|
||||||
role: initialData.role ?? "",
|
role: initialData.role ?? "",
|
||||||
|
roleId: initialData.roleId ? String(initialData.roleId) : "",
|
||||||
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||||
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||||
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||||
@@ -218,7 +219,13 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
|||||||
<InfiniteSelect
|
<InfiniteSelect
|
||||||
label={t("users.fields.role", "Roly")}
|
label={t("users.fields.role", "Roly")}
|
||||||
value={form.role}
|
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")}
|
placeholder={t("users.fields.role", "Roly")}
|
||||||
error={errors.role}
|
error={errors.role}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fall
|
|||||||
.default(""),
|
.default(""),
|
||||||
avatar: urlSchema(t),
|
avatar: urlSchema(t),
|
||||||
role: z.string().min(1, t("validation.required", "validation.required")),
|
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
roleId: z.string(),
|
||||||
socialFacebook: urlSchema(t),
|
socialFacebook: urlSchema(t),
|
||||||
socialInstagram: urlSchema(t),
|
socialInstagram: urlSchema(t),
|
||||||
socialTelegram: urlSchema(t),
|
socialTelegram: urlSchema(t),
|
||||||
@@ -68,6 +69,7 @@ export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
|||||||
email: "",
|
email: "",
|
||||||
avatar: "",
|
avatar: "",
|
||||||
role: "",
|
role: "",
|
||||||
|
roleId: "",
|
||||||
socialFacebook: "",
|
socialFacebook: "",
|
||||||
socialInstagram: "",
|
socialInstagram: "",
|
||||||
socialTelegram: "",
|
socialTelegram: "",
|
||||||
@@ -86,6 +88,7 @@ export function buildPayload(data: AllUserFormData): CreateUserPayload {
|
|||||||
email: data.email.trim(),
|
email: data.email.trim(),
|
||||||
avatar: data.avatar.trim(),
|
avatar: data.avatar.trim(),
|
||||||
role: data.role.trim(),
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
socialMedia: {
|
socialMedia: {
|
||||||
facebook: data.socialFacebook.trim(),
|
facebook: data.socialFacebook.trim(),
|
||||||
instagram: data.socialInstagram.trim(),
|
instagram: data.socialInstagram.trim(),
|
||||||
@@ -107,6 +110,7 @@ export function buildUpdatePayload(data: AllUserFormData): UpdateUserPayload {
|
|||||||
email: data.email.trim(),
|
email: data.email.trim(),
|
||||||
avatar: data.avatar.trim(),
|
avatar: data.avatar.trim(),
|
||||||
role: data.role.trim(),
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
socialMedia: {
|
socialMedia: {
|
||||||
facebook: data.socialFacebook.trim(),
|
facebook: data.socialFacebook.trim(),
|
||||||
instagram: data.socialInstagram.trim(),
|
instagram: data.socialInstagram.trim(),
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export interface Client {
|
|||||||
socialMedia: SocialMedia;
|
socialMedia: SocialMedia;
|
||||||
lightMode: number;
|
lightMode: number;
|
||||||
role: string;
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
@@ -39,13 +40,14 @@ export interface ClientRole {
|
|||||||
id: number;
|
id: number;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
|
isSystem: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientPermission {
|
export interface ClientPermission {
|
||||||
id: number;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientBranch {
|
export interface ClientBranch {
|
||||||
@@ -108,6 +110,7 @@ export interface CreateClientPayload {
|
|||||||
password: string;
|
password: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
role: string;
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
socialMedia: SocialMedia;
|
socialMedia: SocialMedia;
|
||||||
username: string;
|
username: string;
|
||||||
}
|
}
|
||||||
@@ -122,6 +125,7 @@ export interface UpdateClientPayload {
|
|||||||
name?: string;
|
name?: string;
|
||||||
phone?: string;
|
phone?: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
|
roleId?: number;
|
||||||
socialMedia?: SocialMedia;
|
socialMedia?: SocialMedia;
|
||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -101,6 +101,7 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
email: initialData.email ?? "",
|
email: initialData.email ?? "",
|
||||||
avatar: initialData.avatar ?? "",
|
avatar: initialData.avatar ?? "",
|
||||||
role: initialData.role ?? "",
|
role: initialData.role ?? "",
|
||||||
|
roleId: initialData.roleId ? String(initialData.roleId) : "",
|
||||||
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||||
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||||
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||||
@@ -216,7 +217,13 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
<InfiniteSelect
|
<InfiniteSelect
|
||||||
label={t("users.fields.role", "Roly")}
|
label={t("users.fields.role", "Roly")}
|
||||||
value={form.role}
|
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")}
|
placeholder={t("users.fields.role", "Roly")}
|
||||||
error={errors.role}
|
error={errors.role}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export function clientFormSchema(mode: "create" | "edit", t: (key: string, fallb
|
|||||||
.default(""),
|
.default(""),
|
||||||
avatar: urlSchema(t),
|
avatar: urlSchema(t),
|
||||||
role: z.string().min(1, t("validation.required", "validation.required")),
|
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
roleId: z.string(),
|
||||||
socialFacebook: urlSchema(t),
|
socialFacebook: urlSchema(t),
|
||||||
socialInstagram: urlSchema(t),
|
socialInstagram: urlSchema(t),
|
||||||
socialTelegram: urlSchema(t),
|
socialTelegram: urlSchema(t),
|
||||||
@@ -68,6 +69,7 @@ export const DEFAULT_FORM_VALUES: ClientFormData = {
|
|||||||
email: "",
|
email: "",
|
||||||
avatar: "",
|
avatar: "",
|
||||||
role: "",
|
role: "",
|
||||||
|
roleId: "",
|
||||||
socialFacebook: "",
|
socialFacebook: "",
|
||||||
socialInstagram: "",
|
socialInstagram: "",
|
||||||
socialTelegram: "",
|
socialTelegram: "",
|
||||||
@@ -86,6 +88,7 @@ export function buildPayload(data: ClientFormData): CreateClientPayload {
|
|||||||
email: data.email.trim(),
|
email: data.email.trim(),
|
||||||
avatar: data.avatar.trim(),
|
avatar: data.avatar.trim(),
|
||||||
role: data.role.trim(),
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
socialMedia: {
|
socialMedia: {
|
||||||
facebook: data.socialFacebook.trim(),
|
facebook: data.socialFacebook.trim(),
|
||||||
instagram: data.socialInstagram.trim(),
|
instagram: data.socialInstagram.trim(),
|
||||||
@@ -107,6 +110,7 @@ export function buildUpdatePayload(data: ClientFormData): UpdateClientPayload {
|
|||||||
email: data.email.trim(),
|
email: data.email.trim(),
|
||||||
avatar: data.avatar.trim(),
|
avatar: data.avatar.trim(),
|
||||||
role: data.role.trim(),
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
socialMedia: {
|
socialMedia: {
|
||||||
facebook: data.socialFacebook.trim(),
|
facebook: data.socialFacebook.trim(),
|
||||||
instagram: data.socialInstagram.trim(),
|
instagram: data.socialInstagram.trim(),
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export interface Operator {
|
|||||||
socialMedia: SocialMedia;
|
socialMedia: SocialMedia;
|
||||||
lightMode: number;
|
lightMode: number;
|
||||||
role: string;
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
@@ -44,13 +45,14 @@ export interface OperatorRole {
|
|||||||
id: number;
|
id: number;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
|
isSystem: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OperatorPermission {
|
export interface OperatorPermission {
|
||||||
id: number;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OperatorBranch {
|
export interface OperatorBranch {
|
||||||
@@ -105,6 +107,7 @@ export interface CreateOperatorPayload {
|
|||||||
password: string;
|
password: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
role: string;
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
socialMedia: SocialMedia;
|
socialMedia: SocialMedia;
|
||||||
username: string;
|
username: string;
|
||||||
}
|
}
|
||||||
@@ -119,6 +122,7 @@ export interface UpdateOperatorPayload {
|
|||||||
name?: string;
|
name?: string;
|
||||||
phone?: string;
|
phone?: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
|
roleId?: number;
|
||||||
socialMedia?: SocialMedia;
|
socialMedia?: SocialMedia;
|
||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,13 +8,10 @@ import { FormInput } from "@/components/formInput";
|
|||||||
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { KeyRound } from "lucide-react";
|
|
||||||
import { FormActions } from "@/components/formActions";
|
import { FormActions } from "@/components/formActions";
|
||||||
import { AvatarUpload } from "@/components/avatarUpload";
|
import { AvatarUpload } from "@/components/avatarUpload";
|
||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import { AssignDialog, type AssignDialogKind } from "@/features/shared/components/assignDialog";
|
|
||||||
import { useCreateOperator, useUpdateOperator, operatorKeys } from "../hooks/useOperators";
|
import { useCreateOperator, useUpdateOperator, operatorKeys } from "../hooks/useOperators";
|
||||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||||
@@ -66,7 +63,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
|
|
||||||
const isPending = createOperator.isPending || updateOperator.isPending;
|
const isPending = createOperator.isPending || updateOperator.isPending;
|
||||||
|
|
||||||
const [assignDialog, setAssignDialog] = useState<AssignDialogKind | null>(null);
|
|
||||||
const operatorPermissions = (initialData as OperatorDetail | undefined)?.permissions ?? [];
|
const operatorPermissions = (initialData as OperatorDetail | undefined)?.permissions ?? [];
|
||||||
|
|
||||||
const schema = useMemo(() => operatorFormSchema(mode, t), [mode, t, i18n.language]);
|
const schema = useMemo(() => operatorFormSchema(mode, t), [mode, t, i18n.language]);
|
||||||
@@ -163,6 +159,7 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
email: initialData.email ?? "",
|
email: initialData.email ?? "",
|
||||||
avatar: initialData.avatar ?? "",
|
avatar: initialData.avatar ?? "",
|
||||||
role: initialData.role ?? "",
|
role: initialData.role ?? "",
|
||||||
|
roleId: initialData.roleId ? String(initialData.roleId) : "",
|
||||||
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||||
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||||
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||||
@@ -221,12 +218,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")}
|
{mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")}
|
||||||
</h1>
|
</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>
|
</div>
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
{/* ── Identity ── */}
|
{/* ── Identity ── */}
|
||||||
@@ -294,7 +285,13 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
<InfiniteSelect
|
<InfiniteSelect
|
||||||
label={t("users.fields.role", "Roly")}
|
label={t("users.fields.role", "Roly")}
|
||||||
value={form.role}
|
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")}
|
placeholder={t("users.fields.role", "Roly")}
|
||||||
error={errors.role}
|
error={errors.role}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
@@ -381,7 +378,7 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
<div className="flex flex-wrap gap-1.5 items-center">
|
<div className="flex flex-wrap gap-1.5 items-center">
|
||||||
{operatorPermissions.length > 0 ? (
|
{operatorPermissions.length > 0 ? (
|
||||||
operatorPermissions.map((p) => (
|
operatorPermissions.map((p) => (
|
||||||
<Badge key={p.id} variant="secondary">
|
<Badge key={p.code} variant="secondary">
|
||||||
{p.name}
|
{p.name}
|
||||||
</Badge>
|
</Badge>
|
||||||
))
|
))
|
||||||
@@ -389,10 +386,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
<span className="text-sm text-muted-foreground">{t("common.noData", "Rugsat ýok")}</span>
|
<span className="text-sm text-muted-foreground">{t("common.noData", "Rugsat ýok")}</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</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>
|
</div>
|
||||||
</BentoCard>
|
</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")}
|
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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -31,6 +31,7 @@ export function operatorFormSchema(mode: "create" | "edit", t: (key: string, fal
|
|||||||
.default(""),
|
.default(""),
|
||||||
avatar: urlSchema(t),
|
avatar: urlSchema(t),
|
||||||
role: z.string().min(1, t("validation.required", "validation.required")),
|
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
roleId: z.string(),
|
||||||
socialFacebook: urlSchema(t),
|
socialFacebook: urlSchema(t),
|
||||||
socialInstagram: urlSchema(t),
|
socialInstagram: urlSchema(t),
|
||||||
socialTelegram: urlSchema(t),
|
socialTelegram: urlSchema(t),
|
||||||
@@ -60,6 +61,7 @@ export const DEFAULT_FORM_VALUES: OperatorFormData = {
|
|||||||
email: "",
|
email: "",
|
||||||
avatar: "",
|
avatar: "",
|
||||||
role: "",
|
role: "",
|
||||||
|
roleId: "",
|
||||||
socialFacebook: "",
|
socialFacebook: "",
|
||||||
socialInstagram: "",
|
socialInstagram: "",
|
||||||
socialTelegram: "",
|
socialTelegram: "",
|
||||||
@@ -78,6 +80,7 @@ export function buildPayload(data: OperatorFormData): CreateOperatorPayload {
|
|||||||
email: data.email.trim(),
|
email: data.email.trim(),
|
||||||
avatar: data.avatar.trim(),
|
avatar: data.avatar.trim(),
|
||||||
role: data.role.trim(),
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
socialMedia: {
|
socialMedia: {
|
||||||
facebook: data.socialFacebook.trim(),
|
facebook: data.socialFacebook.trim(),
|
||||||
instagram: data.socialInstagram.trim(),
|
instagram: data.socialInstagram.trim(),
|
||||||
@@ -99,6 +102,7 @@ export function buildUpdatePayload(data: OperatorFormData): UpdateOperatorPayloa
|
|||||||
email: data.email.trim(),
|
email: data.email.trim(),
|
||||||
avatar: data.avatar.trim(),
|
avatar: data.avatar.trim(),
|
||||||
role: data.role.trim(),
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
socialMedia: {
|
socialMedia: {
|
||||||
facebook: data.socialFacebook.trim(),
|
facebook: data.socialFacebook.trim(),
|
||||||
instagram: data.socialInstagram.trim(),
|
instagram: data.socialInstagram.trim(),
|
||||||
|
|||||||
@@ -3,64 +3,16 @@ import apiClient from "@/lib/api/client";
|
|||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface Permission {
|
export interface Permission {
|
||||||
id: number;
|
|
||||||
code: string;
|
code: string;
|
||||||
name: 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 ────────────────────────────────────────────────────────────
|
// ─── API functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const permissionsApi = {
|
export const permissionsApi = {
|
||||||
/** GET /permissions — backend filters by `permission_name` */
|
/** GET /permissions — permission catalog */
|
||||||
getAll: async (params: PermissionsListParams = {}, signal?: AbortSignal): Promise<PermissionsListResponse> => {
|
getAll: async (signal?: AbortSignal): Promise<Permission[]> => {
|
||||||
const { search, page, limit } = params;
|
const { data } = await apiClient.get<Permission[]>("/permissions", { signal });
|
||||||
const { data } = await apiClient.get<PermissionsListResponse>("/permissions", {
|
|
||||||
params: { page, limit, permission_name: search },
|
|
||||||
signal,
|
|
||||||
});
|
|
||||||
return data;
|
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 { useQuery } from "@tanstack/react-query";
|
||||||
import { toast } from "sonner";
|
import { permissionsApi } from "../api/permissionsApi";
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
|
||||||
import { permissionsApi, type PermissionPayload, type PermissionsListParams } from "../api/permissionsApi";
|
|
||||||
|
|
||||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const permissionKeys = {
|
export const permissionKeys = {
|
||||||
all: ["permissions"] as const,
|
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) ────────────────────────────────────────────────────
|
/** Fetches the read-only permission catalog used by roles and the permissions page. */
|
||||||
|
export function usePermissions() {
|
||||||
export function usePermissions(params: PermissionsListParams) {
|
|
||||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
|
||||||
const normalized = normalizeSearch(debouncedSearch);
|
|
||||||
const queryParams: PermissionsListParams = { ...params, search: normalized || undefined };
|
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: permissionKeys.list(queryParams),
|
queryKey: permissionKeys.all,
|
||||||
queryFn: ({ signal }) => permissionsApi.getAll(queryParams, signal),
|
queryFn: ({ signal }) => permissionsApi.getAll(signal),
|
||||||
});
|
staleTime: 5 * 60 * 1000,
|
||||||
}
|
|
||||||
|
|
||||||
// ─── 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!"));
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -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;
|
id: number;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
|
isSystem: boolean;
|
||||||
|
permissions: string[];
|
||||||
|
usersCount: number;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
@@ -22,10 +26,17 @@ export interface RolesListParams {
|
|||||||
limit?: number;
|
limit?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RolePayload {
|
export interface CreateRolePayload {
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
scope: Role["scope"];
|
||||||
|
permissions: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateRolePayload {
|
||||||
|
name: string;
|
||||||
|
scope: Role["scope"];
|
||||||
|
permissions: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── API functions ────────────────────────────────────────────────────────────
|
// ─── API functions ────────────────────────────────────────────────────────────
|
||||||
@@ -48,13 +59,13 @@ export const rolesApi = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** POST /roles */
|
/** POST /roles */
|
||||||
create: async (payload: RolePayload): Promise<Role> => {
|
create: async (payload: CreateRolePayload): Promise<Role> => {
|
||||||
const { data } = await apiClient.post<Role>("/roles", payload);
|
const { data } = await apiClient.post<Role>("/roles", payload);
|
||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
/** PUT /roles/:id */
|
/** 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);
|
const { data } = await apiClient.put<Role>(`/roles/${id}`, payload);
|
||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ import { useForm } from "react-hook-form";
|
|||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { FormActions } from "@/components/formActions";
|
import { FormActions } from "@/components/formActions";
|
||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
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 { 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 { RoleFormData } from "../schemas/role.schema";
|
||||||
import type { Role } from "../api/rolesApi";
|
import type { Role } from "../api/rolesApi";
|
||||||
import { FormInput } from "@/components/formInput";
|
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||||
|
import { usePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
interface RoleFormProps {
|
interface RoleFormProps {
|
||||||
mode: "create" | "edit";
|
mode: "create" | "edit";
|
||||||
@@ -29,7 +30,9 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── RoleForm ─────────────────────────────────────────────────────────────────
|
function isRoleScope(value: string): value is RoleFormData["scope"] {
|
||||||
|
return value === "own" || value === "branch" || value === "all";
|
||||||
|
}
|
||||||
|
|
||||||
export function RoleForm({ mode, initialData }: RoleFormProps) {
|
export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||||
const { t: _t, i18n } = useTranslation();
|
const { t: _t, i18n } = useTranslation();
|
||||||
@@ -38,13 +41,16 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
[_t, i18n.language],
|
[_t, i18n.language],
|
||||||
);
|
);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const permissionQuery = usePermissions();
|
||||||
const createRole = useCreateRole();
|
const createRole = useCreateRole();
|
||||||
const updateRole = useUpdateRole(initialData?.id ?? 0);
|
const updateRole = useUpdateRole(initialData?.id ?? 0);
|
||||||
|
|
||||||
const isPending = createRole.isPending || updateRole.isPending;
|
const isPending = createRole.isPending || updateRole.isPending;
|
||||||
|
|
||||||
const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language]);
|
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 {
|
const {
|
||||||
watch,
|
watch,
|
||||||
@@ -55,55 +61,51 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
trigger,
|
trigger,
|
||||||
} = useForm<RoleFormData>({
|
} = useForm<RoleFormData>({
|
||||||
resolver: zodResolver(schema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData
|
defaultValues: initialData ? getRoleFormValues(initialData) : DEFAULT_FORM_VALUES,
|
||||||
? {
|
|
||||||
...DEFAULT_FORM_VALUES,
|
|
||||||
code: initialData.code,
|
|
||||||
name: initialData.name,
|
|
||||||
guardName: initialData.guardName,
|
|
||||||
}
|
|
||||||
: DEFAULT_FORM_VALUES,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const form = watch();
|
const form = watch();
|
||||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||||
|
const permissionOptions = permissionQuery.data ?? [];
|
||||||
|
|
||||||
const setField = useCallback(
|
const setTextField = useCallback(
|
||||||
(key: keyof RoleFormData) => (value: string) => {
|
(key: "code" | "name") => (value: string) => {
|
||||||
(setValue as (k: keyof RoleFormData, v: string) => void)(key, value);
|
setValue(key, value);
|
||||||
clearErrors(key);
|
clearErrors(key);
|
||||||
},
|
},
|
||||||
[setValue, clearErrors],
|
[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(() => {
|
useEffect(() => {
|
||||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [i18n.language]);
|
}, [i18n.language]);
|
||||||
|
|
||||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger();
|
if (!(await trigger())) return;
|
||||||
if (!isValid) return;
|
|
||||||
|
|
||||||
const values = getValues();
|
const values = getValues();
|
||||||
const payload = buildPayload(values);
|
|
||||||
|
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
createRole.mutate(payload, {
|
createRole.mutate(buildCreatePayload(values), {
|
||||||
onSuccess: () => navigate("/settings/users/roles"),
|
onSuccess: () => navigate("/settings/users/roles"),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
updateRole.mutate(payload, {
|
updateRole.mutate(buildUpdatePayload(values), {
|
||||||
onSuccess: () => navigate("/settings/users/roles"),
|
onSuccess: () => navigate("/settings/users/roles"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Render ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
@@ -115,22 +117,23 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
type="text"
|
type="text"
|
||||||
label={t("roles.fields.code", "Kod")}
|
label={t("roles.fields.code", "Kod")}
|
||||||
value={form.code}
|
value={form.code}
|
||||||
onChange={setField("code")}
|
onChange={setTextField("code")}
|
||||||
placeholder={t("roles.fields.code", "Kod")}
|
placeholder={t("roles.fields.code", "Kod")}
|
||||||
error={errors.code}
|
error={errors.code}
|
||||||
disabled={isPending}
|
disabled={mode === "edit" || isPending}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="select"
|
||||||
label={t("roles.fields.guardName", "Guard name")}
|
label={t("roles.fields.scope", "Scope")}
|
||||||
value={form.guardName}
|
value={form.scope}
|
||||||
onChange={setField("guardName")}
|
options={scopeOptions}
|
||||||
placeholder="operator"
|
onChange={(value) => {
|
||||||
error={errors.guardName}
|
if (isRoleScope(value)) setValue("scope", value, { shouldDirty: true });
|
||||||
disabled={isPending}
|
}}
|
||||||
|
disabled={isPending || (mode === "edit" && initialData?.isSystem === true)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
@@ -139,16 +142,40 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
type="text"
|
type="text"
|
||||||
label={t("roles.fields.name", "Ady")}
|
label={t("roles.fields.name", "Ady")}
|
||||||
value={form.name}
|
value={form.name}
|
||||||
onChange={setField("name")}
|
onChange={setTextField("name")}
|
||||||
placeholder={t("roles.fields.name", "Ady")}
|
placeholder={t("roles.fields.name", "Ady")}
|
||||||
error={errors.name}
|
error={errors.name}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</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>
|
</BentoGrid>
|
||||||
<FormActions
|
<FormActions
|
||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
|
submitDisabled={permissionQuery.isLoading || permissionQuery.isError}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
onCancel={() => navigate("/settings/users/roles")}
|
onCancel={() => navigate("/settings/users/roles")}
|
||||||
loadingLabel={t("common.saving", "Ýüklenýär...")}
|
loadingLabel={t("common.saving", "Ýüklenýär...")}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tansta
|
|||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
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 ───────────────────────────────────────────────────────────────
|
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -67,7 +67,7 @@ export function useCreateRole() {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: RolePayload) => rolesApi.create(payload),
|
mutationFn: (payload: CreateRolePayload) => rolesApi.create(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
||||||
toast.success(t("roles.toast.created", "Rol üstünlikli döredildi!"));
|
toast.success(t("roles.toast.created", "Rol üstünlikli döredildi!"));
|
||||||
@@ -82,7 +82,7 @@ export function useUpdateRole(id: number) {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: RolePayload) => rolesApi.update(id, payload),
|
mutationFn: (payload: UpdateRolePayload) => rolesApi.update(id, payload),
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
||||||
queryClient.invalidateQueries({ queryKey: roleKeys.detail(data.id) });
|
queryClient.invalidateQueries({ queryKey: roleKeys.detail(data.id) });
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { z } from "zod";
|
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) {
|
export function createRoleFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
return z.object({
|
return z.object({
|
||||||
code: z.string().min(1, t("validation.required", "validation.required")),
|
code: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
name: 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 = {
|
export const DEFAULT_FORM_VALUES: RoleFormData = {
|
||||||
code: "",
|
code: "",
|
||||||
name: "",
|
name: "",
|
||||||
guardName: "operator",
|
scope: "branch",
|
||||||
|
permissions: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
export function buildPayload(data: RoleFormData): RolePayload {
|
export function buildCreatePayload(data: RoleFormData): CreateRolePayload {
|
||||||
return {
|
return {
|
||||||
code: data.code,
|
code: data.code.trim(),
|
||||||
name: data.name,
|
name: data.name.trim(),
|
||||||
guardName: data.guardName,
|
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;
|
userId: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AddRoleUserPayload {
|
export interface AssignUserRolePayload {
|
||||||
roleId: number;
|
roleId: number;
|
||||||
userId: 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
|
// Re-export so shared hooks can import from one place
|
||||||
export type { BranchListParams, BranchListResponse };
|
export type { BranchListParams, BranchListResponse };
|
||||||
|
|
||||||
@@ -64,34 +53,11 @@ export async function postBranchUser(payload: AddBranchUserPayload): Promise<voi
|
|||||||
await apiClient.post("/branch-users", payload);
|
await apiClient.post("/branch-users", payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** PUT /users/:id/role — assigns a role by ID. */
|
||||||
* POST /role-users
|
export async function putUserRole({ userId, roleId }: AssignUserRolePayload): Promise<void> {
|
||||||
* Assigns a role to a user.
|
await apiClient.put(`/users/${userId}/role`, { roleId });
|
||||||
*/
|
|
||||||
export async function postRoleUser(payload: AddRoleUserPayload): Promise<void> {
|
|
||||||
await apiClient.post("/role-users", payload);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 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
|
* Proxy for branch list fetching — kept here so shared hooks
|
||||||
* don't import directly from the branches feature.
|
* don't import directly from the branches feature.
|
||||||
|
|||||||
@@ -13,143 +13,74 @@ import {
|
|||||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||||
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
|
|
||||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
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";
|
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||||
|
|
||||||
export type AssignDialogKind = "role" | "permission" | "branch";
|
export type AssignDialogKind = "role" | "branch";
|
||||||
|
|
||||||
export interface AssignDialogProps {
|
export interface AssignDialogProps {
|
||||||
kind: AssignDialogKind;
|
kind: AssignDialogKind;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
targetUserId?: number;
|
targetUserId?: number;
|
||||||
targetUserName?: string;
|
targetUserName?: string;
|
||||||
targetRoleId?: number;
|
|
||||||
targetRoleName?: string;
|
|
||||||
onAssigned?: () => void;
|
onAssigned?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ASSIGN_DIALOG_TITLES: Record<AssignDialogKind, string> = {
|
const ASSIGN_DIALOG_TITLES: Record<AssignDialogKind, string> = {
|
||||||
role: "profile.actions.assignRole",
|
role: "profile.actions.assignRole",
|
||||||
permission: "profile.actions.assignPermission",
|
|
||||||
branch: "profile.actions.assignBranch",
|
branch: "profile.actions.assignBranch",
|
||||||
};
|
};
|
||||||
|
|
||||||
const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
||||||
role: "users.fields.role",
|
role: "users.fields.role",
|
||||||
permission: "users.sections.permissions",
|
|
||||||
branch: "users.sections.branches",
|
branch: "users.sections.branches",
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
export function AssignDialog({ kind, onClose, targetUserId, targetUserName, onAssigned }: AssignDialogProps) {
|
||||||
* 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) {
|
|
||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||||
|
|
||||||
const isPermission = kind === "permission";
|
|
||||||
|
|
||||||
const [targetSearch, setTargetSearch] = useState("");
|
const [targetSearch, setTargetSearch] = useState("");
|
||||||
const [targetValue, setTargetValue] = useState<string>(() => {
|
const [targetValue, setTargetValue] = useState(() => (targetUserId ? String(targetUserId) : ""));
|
||||||
if (isPermission && targetRoleId) return String(targetRoleId);
|
|
||||||
if (!isPermission && targetUserId) return String(targetUserId);
|
|
||||||
return "";
|
|
||||||
});
|
|
||||||
const [resourceSearch, setResourceSearch] = useState("");
|
const [resourceSearch, setResourceSearch] = useState("");
|
||||||
const [resourceValue, setResourceValue] = useState("");
|
const [resourceValue, setResourceValue] = useState("");
|
||||||
const [error, setError] = useState<string | undefined>();
|
const [error, setError] = useState<string | undefined>();
|
||||||
|
|
||||||
// Target query: admin users list for role/branch; roles list for permission
|
const staffQuery = useInfiniteUsers(targetSearch);
|
||||||
const staffQuery = useInfiniteUsers(targetSearch, !isPermission);
|
|
||||||
const targetRolesQuery = useInfiniteRoles(targetSearch, isPermission);
|
|
||||||
|
|
||||||
// Resource queries
|
|
||||||
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
||||||
const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission");
|
|
||||||
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
||||||
|
|
||||||
const roleMutation = useAssignRoleToUser();
|
const roleMutation = useAssignRoleToUser();
|
||||||
const permissionRoleMutation = useAssignPermissionToRole();
|
|
||||||
const branchMutation = useAssignBranchToUser();
|
const branchMutation = useAssignBranchToUser();
|
||||||
const isPending = roleMutation.isPending || permissionRoleMutation.isPending || branchMutation.isPending;
|
const isPending = roleMutation.isPending || branchMutation.isPending;
|
||||||
|
|
||||||
const targetOptions: InfiniteSelectOption[] = useMemo(() => {
|
const targetOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||||
if (isPermission) {
|
const options = (staffQuery.data?.pages ?? [])
|
||||||
const opts: InfiniteSelectOption[] = (targetRolesQuery.data?.pages ?? [])
|
.flatMap((page) => page?.users ?? [])
|
||||||
.flatMap((p) => p?.roles ?? [])
|
.map((user) => ({
|
||||||
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) }));
|
value: String(user.id),
|
||||||
|
label: [user.firstName, user.lastName].filter(Boolean).join(" ") || user.name || user.username || String(user.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),
|
|
||||||
}));
|
}));
|
||||||
|
if (targetUserId && !options.some((option) => option.value === String(targetUserId))) {
|
||||||
if (targetUserId) {
|
options.unshift({ value: String(targetUserId), label: targetUserName || String(targetUserId) });
|
||||||
const valStr = String(targetUserId);
|
|
||||||
if (!opts.some((o) => o.value === valStr)) {
|
|
||||||
opts.unshift({ value: valStr, label: targetUserName || valStr });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return opts;
|
return options;
|
||||||
}, [isPermission, targetRolesQuery.data, targetRoleId, targetRoleName, staffQuery.data, targetUserId, targetUserName]);
|
}, [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();
|
|
||||||
};
|
|
||||||
|
|
||||||
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||||
if (kind === "role") {
|
if (kind === "role") {
|
||||||
return (rolesQuery.data?.pages ?? [])
|
return (rolesQuery.data?.pages ?? [])
|
||||||
.flatMap((p) => p?.roles ?? [])
|
.flatMap((page) => page?.roles ?? [])
|
||||||
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) }));
|
.map((role) => ({ value: String(role.id), label: role.name || role.code || String(role.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) }));
|
|
||||||
}
|
}
|
||||||
return (branchesQuery.data?.pages ?? [])
|
return (branchesQuery.data?.pages ?? [])
|
||||||
.flatMap((p) => p?.branches ?? [])
|
.flatMap((page) => page?.branches ?? [])
|
||||||
.map((b) => ({
|
.map((branch) => ({
|
||||||
value: String(b.id),
|
value: String(branch.id),
|
||||||
label: b.name?.[lang] || b.name?.tm || b.name?.en || b.name?.ru || b.uniqueCode || String(b.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 =
|
const resourceQuery = kind === "role" ? rolesQuery : branchesQuery;
|
||||||
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 handleSubmit = () => {
|
const handleSubmit = () => {
|
||||||
if (!targetValue || !resourceValue) {
|
if (!targetValue || !resourceValue) {
|
||||||
@@ -157,24 +88,14 @@ export function AssignDialog({ kind, onClose, targetUserId, targetUserName, targ
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setError(undefined);
|
setError(undefined);
|
||||||
|
const payload = { userId: Number(targetValue), roleId: Number(resourceValue) };
|
||||||
const firstId = Number(targetValue);
|
|
||||||
const secondId = Number(resourceValue);
|
|
||||||
const onSuccess = () => {
|
const onSuccess = () => {
|
||||||
setResourceValue("");
|
setResourceValue("");
|
||||||
onAssigned?.();
|
onAssigned?.();
|
||||||
onClose();
|
onClose();
|
||||||
};
|
};
|
||||||
|
if (kind === "role") roleMutation.mutate(payload, { onSuccess });
|
||||||
if (kind === "role") {
|
else branchMutation.mutate({ userId: payload.userId, branchId: payload.roleId }, { onSuccess });
|
||||||
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 });
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -186,48 +107,45 @@ export function AssignDialog({ kind, onClose, targetUserId, targetUserName, targ
|
|||||||
<AlertDialogDescription>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogDescription>
|
<AlertDialogDescription>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogDescription>
|
||||||
</VisuallyHidden.Root>
|
</VisuallyHidden.Root>
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<InfiniteSelect
|
<InfiniteSelect
|
||||||
required
|
required
|
||||||
label={targetLabel}
|
label={t("profile.assign.userLabel", "Ulanyjy")}
|
||||||
value={targetValue}
|
value={targetValue}
|
||||||
onChange={(v) => {
|
onChange={(value) => {
|
||||||
setTargetValue(v);
|
setTargetValue(value);
|
||||||
if (error) setError(undefined);
|
if (error) setError(undefined);
|
||||||
}}
|
}}
|
||||||
disabled={!!targetUserId || isPending}
|
disabled={!!targetUserId || isPending}
|
||||||
options={targetOptions}
|
options={targetOptions}
|
||||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||||
loading={targetLoading}
|
loading={staffQuery.isLoading}
|
||||||
isLoadingMore={targetLoadingMore}
|
isLoadingMore={staffQuery.isFetchingNextPage}
|
||||||
hasNextPage={targetHasNextPage}
|
hasNextPage={!!staffQuery.hasNextPage}
|
||||||
onLoadMore={loadMoreTargets}
|
onLoadMore={() => staffQuery.fetchNextPage()}
|
||||||
searchValue={targetSearch}
|
searchValue={targetSearch}
|
||||||
onSearchChange={setTargetSearch}
|
onSearchChange={setTargetSearch}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<InfiniteSelect
|
<InfiniteSelect
|
||||||
required
|
required
|
||||||
label={t(ASSIGN_DIALOG_FIELD_LABELS[kind])}
|
label={t(ASSIGN_DIALOG_FIELD_LABELS[kind])}
|
||||||
value={resourceValue}
|
value={resourceValue}
|
||||||
onChange={(v) => {
|
onChange={(value) => {
|
||||||
setResourceValue(v);
|
setResourceValue(value);
|
||||||
if (error) setError(undefined);
|
if (error) setError(undefined);
|
||||||
}}
|
}}
|
||||||
error={error}
|
error={error}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
options={resourceOptions}
|
options={resourceOptions}
|
||||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||||
loading={resourceLoading}
|
loading={resourceQuery.isLoading}
|
||||||
isLoadingMore={resourceLoadingMore}
|
isLoadingMore={resourceQuery.isFetchingNextPage}
|
||||||
hasNextPage={resourceHasNextPage}
|
hasNextPage={!!resourceQuery.hasNextPage}
|
||||||
onLoadMore={loadMoreResources}
|
onLoadMore={() => resourceQuery.fetchNextPage()}
|
||||||
searchValue={resourceSearch}
|
searchValue={resourceSearch}
|
||||||
onSearchChange={setResourceSearch}
|
onSearchChange={setResourceSearch}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
|
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
|
||||||
{t("common.cancel", "Yza")}
|
{t("common.cancel", "Yza")}
|
||||||
|
|||||||
@@ -3,13 +3,9 @@ import { toast } from "sonner";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
postBranchUser,
|
postBranchUser,
|
||||||
postRoleUser,
|
putUserRole,
|
||||||
postPermissionRole,
|
|
||||||
// postPermissionUser,
|
|
||||||
type AddBranchUserPayload,
|
type AddBranchUserPayload,
|
||||||
type AddRoleUserPayload,
|
type AssignUserRolePayload,
|
||||||
type AddPermissionRolePayload,
|
|
||||||
// type AddPermissionUserPayload,
|
|
||||||
} from "../api/sharedApi";
|
} from "../api/sharedApi";
|
||||||
|
|
||||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
@@ -33,7 +29,7 @@ function useInvalidateProfile() {
|
|||||||
// ─── useAssignRoleToUser ──────────────────────────────────────────────────────
|
// ─── 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).
|
* `userId` is supplied at mutate time (picked from the staff select).
|
||||||
*/
|
*/
|
||||||
export function useAssignRoleToUser() {
|
export function useAssignRoleToUser() {
|
||||||
@@ -41,7 +37,7 @@ export function useAssignRoleToUser() {
|
|||||||
const invalidateProfile = useInvalidateProfile();
|
const invalidateProfile = useInvalidateProfile();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: AddRoleUserPayload) => postRoleUser(payload),
|
mutationFn: (payload: AssignUserRolePayload) => putUserRole(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
invalidateProfile();
|
invalidateProfile();
|
||||||
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
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 ────────────────────────────────────────────────────
|
// ─── useAssignBranchToUser ────────────────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,19 +1,18 @@
|
|||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { useAuthStore } from "@/app/store/authStore";
|
import { useAuthStore } from "@/app/store/authStore";
|
||||||
import { isWebUser } from "@/lib/auth/permissions";
|
import { hasOwnScope } from "@/lib/auth/permissions";
|
||||||
import type { InfiniteSelectOption } from "@/components/infiniteSelect";
|
import type { InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* When the current user belongs to the "web" guard ("user" role) and is creating
|
* Users with own-record scope must be locked to themselves when creating a
|
||||||
* a record, the client / "created by" field must be locked to the user itself:
|
* record: their ID is pre-filled and no other users are shown.
|
||||||
* it is pre-filled with the current user's id and no other users are shown.
|
* Branch/all-scope users keep the ability to pick another user.
|
||||||
* Admin / operator users keep the ability to pick another user.
|
|
||||||
*/
|
*/
|
||||||
export function useWebSelfLock(active: boolean) {
|
export function useWebSelfLock(active: boolean) {
|
||||||
const user = useAuthStore((s) => s.user);
|
const user = useAuthStore((s) => s.user);
|
||||||
|
|
||||||
return useMemo(() => {
|
return useMemo(() => {
|
||||||
const locked = active && isWebUser(user);
|
const locked = active && hasOwnScope(user);
|
||||||
const userId = locked && user?.id != null ? String(user.id) : "";
|
const userId = locked && user?.id != null ? String(user.id) : "";
|
||||||
const userName = [user?.firstName, user?.lastName].filter(Boolean).join(" ") || user?.name || user?.email || userId;
|
const userName = [user?.firstName, user?.lastName].filter(Boolean).join(" ") || user?.name || user?.email || userId;
|
||||||
|
|
||||||
|
|||||||
+42
-96
@@ -1,46 +1,19 @@
|
|||||||
import type { AuthUser, AuthUserPermission } from "@/app/store/authStore";
|
import type { AuthUser, AuthUserPermission } from "@/app/store/authStore";
|
||||||
|
|
||||||
/**
|
/** True when the role is the super role with unrestricted access. */
|
||||||
* 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). */
|
|
||||||
export function isAdmin(user?: AuthUser | null): boolean {
|
export function isAdmin(user?: AuthUser | null): boolean {
|
||||||
if (!user?.role) return false;
|
return user?.role?.isSuper === true;
|
||||||
return user.role.guardName === ADMIN_GUARD || user.role.code === "admin";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** True when the user's role is the web guard (the public "user" role). */
|
/** True when the role is limited to the user's own records. */
|
||||||
export function isWebUser(user?: AuthUser | null): boolean {
|
export function hasOwnScope(user?: AuthUser | null): boolean {
|
||||||
if (!user?.role) return false;
|
return user?.role?.scope === "own";
|
||||||
return user.role.guardName === WEB_GUARD || user.role.code === "user";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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[] {
|
export function getPermissionCodes(user?: AuthUser | null): string[] {
|
||||||
if (isAdmin(user)) return [];
|
if (isAdmin(user)) return [];
|
||||||
const seen = new Set<string>();
|
return [...new Set((user?.permissions ?? []).map((permission: AuthUserPermission) => permission.code))];
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns true when the user may access the page protected by the given 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 ──────────────────────
|
// ─── Permission constants used to gate nav items / pages ──────────────────────
|
||||||
|
|
||||||
export const PERM = {
|
export const PERM = {
|
||||||
|
DASHBOARD: "dashboard",
|
||||||
LOANS: "loans",
|
LOANS: "loans",
|
||||||
CARDS: "cards",
|
CARDS: "cards",
|
||||||
USERS_VIEW: "users.view",
|
USERS: "users",
|
||||||
USERS_MANAGE: "users.manage",
|
ROLES: "roles",
|
||||||
ROLES_VIEW: "roles.view",
|
BRANCHES: "branches",
|
||||||
BRANCHES_VIEW: "branches.view",
|
PROVINCES: "provinces",
|
||||||
PROVINCES_VIEW: "provinces.view",
|
ACTIVITY_LOGS: "activity-logs",
|
||||||
BACKUPS_VIEW: "backups.view",
|
BACKUPS: "backups",
|
||||||
ACTIVITY_LOGS_VIEW: "activity-logs.view",
|
CURRENCIES: "currencies",
|
||||||
CURRENCIES_VIEW: "currencies.view",
|
PAYMENT_SETTINGS: "payment-settings",
|
||||||
/** Sentinel for pages that only the admin guard may access (no permission code exists). */
|
|
||||||
ADMIN_ONLY: "__admin_only__",
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
type PermValue = (typeof PERM)[keyof typeof PERM];
|
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[]];
|
type RouteRule = readonly [prefix: string, codes: readonly PermValue[]];
|
||||||
|
|
||||||
const ROUTE_RULES: RouteRule[] = [
|
const ROUTE_RULES: RouteRule[] = [
|
||||||
// System / admin-only
|
["/dashboard", [PERM.DASHBOARD]],
|
||||||
["/dashboard", [PERM.ADMIN_ONLY]],
|
|
||||||
// Settings (admin-only)
|
|
||||||
["/settings", [PERM.ADMIN_ONLY]],
|
|
||||||
// Loan department
|
// Loan department
|
||||||
["/loan-orders", [PERM.LOANS]],
|
["/loan-orders", [PERM.LOANS]],
|
||||||
["/loan-order-mobiles", [PERM.LOANS]],
|
["/loan-order-mobiles", [PERM.LOANS]],
|
||||||
@@ -99,20 +68,28 @@ const ROUTE_RULES: RouteRule[] = [
|
|||||||
["/card-requisites", [PERM.CARDS]],
|
["/card-requisites", [PERM.CARDS]],
|
||||||
["/card-balances", [PERM.CARDS]],
|
["/card-balances", [PERM.CARDS]],
|
||||||
["/card-pins", [PERM.CARDS]],
|
["/card-pins", [PERM.CARDS]],
|
||||||
// International payments + online payment history (no permission yet → admin-only)
|
// Payment operations are covered by the existing cards module permission.
|
||||||
["/visa-master", [PERM.ADMIN_ONLY]],
|
["/visa-master", [PERM.CARDS]],
|
||||||
["/sber-payments", [PERM.ADMIN_ONLY]],
|
["/sber-payments", [PERM.CARDS]],
|
||||||
["/online-payments-history", [PERM.ADMIN_ONLY]],
|
["/online-payments-history", [PERM.CARDS]],
|
||||||
// Users (operators / clients / all users)
|
// Users (operators / clients / all users)
|
||||||
["/operators", [PERM.USERS_VIEW, PERM.USERS_MANAGE]],
|
["/operators", [PERM.USERS]],
|
||||||
["/all-users", [PERM.USERS_VIEW, PERM.USERS_MANAGE]],
|
["/all-users", [PERM.USERS]],
|
||||||
["/clients", [PERM.USERS_VIEW, PERM.USERS_MANAGE]],
|
["/clients", [PERM.USERS]],
|
||||||
// Currencies
|
// Currencies
|
||||||
["/currency-rates", [PERM.CURRENCIES_VIEW]],
|
["/currency-rates", [PERM.CURRENCIES]],
|
||||||
["/visa-master-sber-settings", [PERM.CURRENCIES_VIEW]],
|
["/visa-master-sber-settings", [PERM.CURRENCIES]],
|
||||||
// System pages
|
// System pages
|
||||||
["/backups", [PERM.BACKUPS_VIEW]],
|
["/backups", [PERM.BACKUPS]],
|
||||||
["/logs", [PERM.ACTIVITY_LOGS_VIEW]],
|
["/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). */
|
/** 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 {
|
export function canAccessUrl(user: AuthUser | null | undefined, url: string | undefined): boolean {
|
||||||
if (!url) return false;
|
if (!url) return false;
|
||||||
if (isAdmin(user)) return true;
|
if (isAdmin(user)) return true;
|
||||||
if (isWebUser(user) && isWebAccessiblePath(url)) return true;
|
|
||||||
return hasAnyPermission(user, permissionForUrl(url));
|
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 ────────────────────────────────────────────────────────────────
|
// ─── Home path ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const HOME_PRIORITY: readonly (readonly [codes: readonly PermValue[], path: string])[] = [
|
const HOME_PRIORITY: readonly (readonly [codes: readonly PermValue[], path: string])[] = [
|
||||||
[[PERM.LOANS], "/loan-orders"],
|
[[PERM.LOANS], "/loan-orders"],
|
||||||
[[PERM.CARDS], "/order-new-card"],
|
[[PERM.CARDS], "/order-new-card"],
|
||||||
[[PERM.USERS_VIEW, PERM.USERS_MANAGE], "/operators"],
|
[[PERM.USERS], "/operators"],
|
||||||
[[PERM.CURRENCIES_VIEW], "/currency-rates"],
|
[[PERM.CURRENCIES], "/currency-rates"],
|
||||||
[[PERM.BACKUPS_VIEW], "/backups"],
|
[[PERM.BACKUPS], "/backups"],
|
||||||
[[PERM.ACTIVITY_LOGS_VIEW], "/logs"],
|
[[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 {
|
export function getDefaultHomePath(user: AuthUser | null | undefined): string {
|
||||||
if (isAdmin(user)) return "/dashboard";
|
if (isAdmin(user)) return "/dashboard";
|
||||||
if (isWebUser(user)) return "/loan-orders";
|
|
||||||
for (const [codes, path] of HOME_PRIORITY) {
|
for (const [codes, path] of HOME_PRIORITY) {
|
||||||
if (hasAnyPermission(user, codes)) return path;
|
if (hasAnyPermission(user, codes)) return path;
|
||||||
}
|
}
|
||||||
|
if (hasPermission(user, PERM.DASHBOARD)) return "/dashboard";
|
||||||
return "/profile";
|
return "/profile";
|
||||||
}
|
}
|
||||||
@@ -1079,10 +1079,7 @@
|
|||||||
"onlinePayments.fields.onlinePaymantableType": "Online payment table type",
|
"onlinePayments.fields.onlinePaymantableType": "Online payment table type",
|
||||||
"onlinePayments.fields.createdAt": "Created at",
|
"onlinePayments.fields.createdAt": "Created at",
|
||||||
"onlinePayments.fields.updatedAt": "Updated at",
|
"onlinePayments.fields.updatedAt": "Updated at",
|
||||||
"permissions.createTitle": "Create permission",
|
|
||||||
"permissions.editTitle": "Edit permission",
|
|
||||||
"permissions.title": "Permissions",
|
"permissions.title": "Permissions",
|
||||||
"permissions.viewTitle": "Permission detail",
|
|
||||||
"requiredDocuments.createTitle": "Create document",
|
"requiredDocuments.createTitle": "Create document",
|
||||||
"requiredDocuments.editTitle": "Edit document",
|
"requiredDocuments.editTitle": "Edit document",
|
||||||
"requiredDocuments.title": "Required documents",
|
"requiredDocuments.title": "Required documents",
|
||||||
@@ -1429,19 +1426,22 @@
|
|||||||
"intlPayment.regions.DZ": "Dashoguz",
|
"intlPayment.regions.DZ": "Dashoguz",
|
||||||
"intlPayment.regions.LB": "Lebap",
|
"intlPayment.regions.LB": "Lebap",
|
||||||
"intlPayment.regions.MR": "Mary",
|
"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.code": "CODE",
|
||||||
"permissions.fields.guardName": "GUARD NAME",
|
|
||||||
"permissions.fields.name": "NAME",
|
"permissions.fields.name": "NAME",
|
||||||
"permissions.searchPlaceholder": "Search...",
|
"permissions.searchPlaceholder": "Search...",
|
||||||
"roles.actions.create": "Create role",
|
"roles.actions.create": "Create role",
|
||||||
"roles.deleteDialog.description": "Are you sure you want to delete this role? This action cannot be undone.",
|
"roles.deleteDialog.description": "Are you sure you want to delete this role? This action cannot be undone.",
|
||||||
"roles.deleteDialog.title": "Delete role",
|
"roles.deleteDialog.title": "Delete role",
|
||||||
"roles.fields.code": "CODE",
|
"roles.fields.code": "CODE",
|
||||||
"roles.fields.guardName": "GUARD NAME",
|
|
||||||
"roles.fields.name": "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...",
|
"roles.searchPlaceholder": "Search...",
|
||||||
"branches.fields.name": "Branch name",
|
"branches.fields.name": "Branch name",
|
||||||
"branches.fields.namePlaceholder": "Branch name",
|
"branches.fields.namePlaceholder": "Branch name",
|
||||||
|
|||||||
@@ -1080,10 +1080,7 @@
|
|||||||
"onlinePayments.fields.onlinePaymantableType": "Тип онлайн-таблицы",
|
"onlinePayments.fields.onlinePaymantableType": "Тип онлайн-таблицы",
|
||||||
"onlinePayments.fields.createdAt": "Дата создания",
|
"onlinePayments.fields.createdAt": "Дата создания",
|
||||||
"onlinePayments.fields.updatedAt": "Дата обновления",
|
"onlinePayments.fields.updatedAt": "Дата обновления",
|
||||||
"permissions.createTitle": "Создать разрешение",
|
|
||||||
"permissions.editTitle": "Редактировать разрешение",
|
|
||||||
"permissions.title": "Разрешения",
|
"permissions.title": "Разрешения",
|
||||||
"permissions.viewTitle": "Детали разрешения",
|
|
||||||
"requiredDocuments.createTitle": "Создать документ",
|
"requiredDocuments.createTitle": "Создать документ",
|
||||||
"requiredDocuments.editTitle": "Редактировать документ",
|
"requiredDocuments.editTitle": "Редактировать документ",
|
||||||
"requiredDocuments.title": "Необходимые документы",
|
"requiredDocuments.title": "Необходимые документы",
|
||||||
@@ -1430,19 +1427,22 @@
|
|||||||
"intlPayment.regions.DZ": "Дашогуз",
|
"intlPayment.regions.DZ": "Дашогуз",
|
||||||
"intlPayment.regions.LB": "Лебап",
|
"intlPayment.regions.LB": "Лебап",
|
||||||
"intlPayment.regions.MR": "Мары",
|
"intlPayment.regions.MR": "Мары",
|
||||||
"permissions.actions.create": "Создать разрешение",
|
|
||||||
"permissions.deleteDialog.description": "Вы уверены, что хотите удалить это разрешение? Это действие необратимо.",
|
|
||||||
"permissions.deleteDialog.title": "Удалить разрешение",
|
|
||||||
"permissions.fields.code": "КОД",
|
"permissions.fields.code": "КОД",
|
||||||
"permissions.fields.guardName": "GUARD NAME",
|
|
||||||
"permissions.fields.name": "ИМЯ",
|
"permissions.fields.name": "ИМЯ",
|
||||||
"permissions.searchPlaceholder": "Поиск...",
|
"permissions.searchPlaceholder": "Поиск...",
|
||||||
"roles.actions.create": "Создать роль",
|
"roles.actions.create": "Создать роль",
|
||||||
"roles.deleteDialog.description": "Вы уверены, что хотите удалить эту роль? Это действие необратимо.",
|
"roles.deleteDialog.description": "Вы уверены, что хотите удалить эту роль? Это действие необратимо.",
|
||||||
"roles.deleteDialog.title": "Удалить роль",
|
"roles.deleteDialog.title": "Удалить роль",
|
||||||
"roles.fields.code": "КОД",
|
"roles.fields.code": "КОД",
|
||||||
"roles.fields.guardName": "GUARD NAME",
|
|
||||||
"roles.fields.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": "Поиск...",
|
"roles.searchPlaceholder": "Поиск...",
|
||||||
"branches.fields.name": "Название филиала",
|
"branches.fields.name": "Название филиала",
|
||||||
"branches.fields.namePlaceholder": "Название филиала",
|
"branches.fields.namePlaceholder": "Название филиала",
|
||||||
|
|||||||
@@ -1077,10 +1077,7 @@
|
|||||||
"onlinePayments.fields.onlinePaymantableType": "Online töleg tablisasynyň görnüşi",
|
"onlinePayments.fields.onlinePaymantableType": "Online töleg tablisasynyň görnüşi",
|
||||||
"onlinePayments.fields.createdAt": "Döredilen wagty",
|
"onlinePayments.fields.createdAt": "Döredilen wagty",
|
||||||
"onlinePayments.fields.updatedAt": "Üýtgedilen wagty",
|
"onlinePayments.fields.updatedAt": "Üýtgedilen wagty",
|
||||||
"permissions.createTitle": "Rugsat döretmek",
|
|
||||||
"permissions.editTitle": "Rugsat üýtgetmek",
|
|
||||||
"permissions.title": "Rugsatlar",
|
"permissions.title": "Rugsatlar",
|
||||||
"permissions.viewTitle": "Rugsat giňişleýin",
|
|
||||||
"requiredDocuments.createTitle": "Resminama döretmek",
|
"requiredDocuments.createTitle": "Resminama döretmek",
|
||||||
"requiredDocuments.editTitle": "Resminama üýtgetmek",
|
"requiredDocuments.editTitle": "Resminama üýtgetmek",
|
||||||
"requiredDocuments.title": "Gerekli resminamalar",
|
"requiredDocuments.title": "Gerekli resminamalar",
|
||||||
@@ -1432,15 +1429,18 @@
|
|||||||
"roles.deleteDialog.description": "Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.",
|
"roles.deleteDialog.description": "Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.",
|
||||||
"roles.deleteDialog.title": "Roly pozmak",
|
"roles.deleteDialog.title": "Roly pozmak",
|
||||||
"roles.fields.code": "KOD",
|
"roles.fields.code": "KOD",
|
||||||
"roles.fields.guardName": "GUARD NAME",
|
|
||||||
"roles.fields.name": "ADY",
|
"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...",
|
"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.code": "KOD",
|
||||||
"permissions.fields.name": "ADY",
|
"permissions.fields.name": "ADY",
|
||||||
"permissions.fields.guardName": "GUARD NAME",
|
|
||||||
"permissions.searchPlaceholder": "Gözlemek...",
|
"permissions.searchPlaceholder": "Gözlemek...",
|
||||||
"branches.fields.name": "Şahamçanyň ady",
|
"branches.fields.name": "Şahamçanyň ady",
|
||||||
"branches.fields.namePlaceholder": "Şahamçanyň ady",
|
"branches.fields.namePlaceholder": "Şahamçanyň ady",
|
||||||
|
|||||||
+14
-22
@@ -202,6 +202,13 @@ export default function ProfilePage() {
|
|||||||
<span className="text-sm text-muted-foreground">—</span>
|
<span className="text-sm text-muted-foreground">—</span>
|
||||||
)}
|
)}
|
||||||
</InfoRow>
|
</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")}>
|
<InfoRow label={t("users.sections.branches", "Şahamçalar")}>
|
||||||
{branches.length > 0 ? (
|
{branches.length > 0 ? (
|
||||||
@@ -236,23 +243,12 @@ export default function ProfilePage() {
|
|||||||
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}>
|
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}>
|
||||||
{permissions.length > 0 ? (
|
{permissions.length > 0 ? (
|
||||||
<div className="flex flex-wrap gap-1.5">
|
<div className="flex flex-wrap gap-1.5">
|
||||||
{permissions.map((p) =>
|
{permissions.map((permission) => (
|
||||||
isAdmin ? (
|
<span key={permission.code} className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1">
|
||||||
<Link
|
<KeyRound size={11} className="text-muted-foreground" />
|
||||||
key={p.id}
|
<span className="text-foreground font-medium">{permission.name || permission.code}</span>
|
||||||
to={`/settings/users/permissions/${p.id}`}
|
</span>
|
||||||
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>
|
|
||||||
),
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-sm text-muted-foreground">—</span>
|
<span className="text-sm text-muted-foreground">—</span>
|
||||||
@@ -267,10 +263,6 @@ export default function ProfilePage() {
|
|||||||
<Shield size={14} />
|
<Shield size={14} />
|
||||||
{t("profile.actions.assignRole", "Rol birikdiriň")}
|
{t("profile.actions.assignRole", "Rol birikdiriň")}
|
||||||
</Button>
|
</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")}>
|
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("branch")}>
|
||||||
<Building2 size={14} />
|
<Building2 size={14} />
|
||||||
{t("profile.actions.assignBranch", "Şahamça birikdiriň")}
|
{t("profile.actions.assignBranch", "Şahamça birikdiriň")}
|
||||||
@@ -340,7 +332,7 @@ export default function ProfilePage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* ── Assign dialog (role/permission/branch) ─────────────── */}
|
{/* ── Assign dialog (role/branch) ───────────────────────── */}
|
||||||
{assignDialog && <AssignDialog kind={assignDialog} onClose={() => setAssignDialog(null)} />}
|
{assignDialog && <AssignDialog kind={assignDialog} onClose={() => setAssignDialog(null)} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,163 +1,89 @@
|
|||||||
import { useState, useMemo } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||||
import { DataTable } from "@/components/dataTable";
|
import { DataTable } from "@/components/dataTable";
|
||||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||||
import { TableSearchInput } from "@/components/tableSearch";
|
import { TableSearchInput } from "@/components/tableSearch";
|
||||||
import { CreateButton } from "@/components/createButton";
|
import { usePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||||
import { TableActions } from "@/components/tableActions";
|
|
||||||
import { DeleteDialog } from "@/components/deleteDialog";
|
|
||||||
import { usePermissions, useDeletePermission } from "@/features/permissions/hooks/usePermissions";
|
|
||||||
import type { Permission } from "@/features/permissions/api/permissionsApi";
|
import type { Permission } from "@/features/permissions/api/permissionsApi";
|
||||||
|
|
||||||
// ─── PermissionsPage ──────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export default function PermissionsPage() {
|
export default function PermissionsPage() {
|
||||||
const { t } = useTranslation();
|
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 [search, setSearch] = useState("");
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [perPage, setPerPage] = useState(25);
|
const [perPage, setPerPage] = useState(25);
|
||||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
const { data = [], isLoading, isError } = usePermissions();
|
||||||
|
|
||||||
// ── Data ───────────────────────────────────────────────────────────────────
|
const filteredPermissions = useMemo(() => {
|
||||||
const { data, isLoading } = usePermissions({ search, page, limit: perPage });
|
const term = search.trim().toLocaleLowerCase();
|
||||||
const deletePermission = useDeletePermission();
|
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>[] = [
|
const columns: ColumnDef<Permission>[] = [
|
||||||
{
|
{ accessorKey: "code", header: t("permissions.fields.code", "Kod") },
|
||||||
accessorKey: "id",
|
{ accessorKey: "name", header: t("permissions.fields.name", "Ady") },
|
||||||
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}
|
|
||||||
/>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
|
|
||||||
// ── Handlers ───────────────────────────────────────────────────────────────
|
|
||||||
const handleConfirmDelete = () => {
|
|
||||||
if (deleteId === null) return;
|
|
||||||
deletePermission.mutate(deleteId, {
|
|
||||||
onSuccess: () => setDeleteId(null),
|
|
||||||
onError: () => setDeleteId(null),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// ── Render ─────────────────────────────────────────────────────────────────
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{/* Page heading */}
|
<h1 className="text-2xl font-bold text-foreground">{t("permissions.title", "Rugsatlar")}</h1>
|
||||||
<div className="flex items-center justify-between mb-6">
|
<TableSearchInput
|
||||||
<h1 className="text-2xl font-bold text-foreground">{t("permissions.title", "Rugsatlar")}</h1>
|
value={search}
|
||||||
</div>
|
onChange={(value) => {
|
||||||
<div className="flex items-center gap-3 justify-between">
|
setSearch(value);
|
||||||
<TableSearchInput
|
setPage(1);
|
||||||
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);
|
|
||||||
}}
|
}}
|
||||||
title={t("permissions.deleteDialog.title", "Rugsaty pozmak")}
|
placeholder={t("permissions.searchPlaceholder", "Gözlemek...")}
|
||||||
description={t("permissions.deleteDialog.description", "Bu rugsaty pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")}
|
|
||||||
onConfirm={handleConfirmDelete}
|
|
||||||
isLoading={deletePermission.isPending}
|
|
||||||
/>
|
/>
|
||||||
|
{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>
|
</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: "id", label: t("common.id", "ID") },
|
||||||
{ id: "code", label: t("roles.fields.code", "Kod") },
|
{ id: "code", label: t("roles.fields.code", "Kod") },
|
||||||
{ id: "name", label: t("roles.fields.name", "Ady") },
|
{ 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],
|
[t],
|
||||||
);
|
);
|
||||||
@@ -56,10 +57,8 @@ export default function RolesPage() {
|
|||||||
header: t("roles.fields.name", "Ady"),
|
header: t("roles.fields.name", "Ady"),
|
||||||
cell: ({ row }) => <span>{row.original.name ?? "—"}</span>,
|
cell: ({ row }) => <span>{row.original.name ?? "—"}</span>,
|
||||||
},
|
},
|
||||||
{
|
{ accessorKey: "scope", header: t("roles.fields.scope", "Scope") },
|
||||||
accessorKey: "guardName",
|
{ accessorKey: "usersCount", header: t("roles.fields.usersCount", "Users") },
|
||||||
header: t("roles.fields.guardName", "Guard name"),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
id: "actions",
|
id: "actions",
|
||||||
header: "",
|
header: "",
|
||||||
@@ -70,7 +69,7 @@ export default function RolesPage() {
|
|||||||
<TableActions
|
<TableActions
|
||||||
onView={() => navigate(`/settings/users/roles/${row.original.id}`)}
|
onView={() => navigate(`/settings/users/roles/${row.original.id}`)}
|
||||||
onEdit={() => navigate(`/settings/users/roles/${row.original.id}/edit`)}
|
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}
|
isDeleting={deleteRole.isPending}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ export default function RoleViewPage() {
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<ViewActions
|
<ViewActions
|
||||||
editTo={`/settings/users/roles/${roleId}/edit`}
|
editTo={`/settings/users/roles/${roleId}/edit`}
|
||||||
onDelete={handleDelete}
|
onDelete={role.isSystem ? undefined : handleDelete}
|
||||||
deleting={deleteRole.isPending}
|
deleting={deleteRole.isPending}
|
||||||
deleteTitle={t("roles.deleteDialog.title", "Roly pozmak")}
|
deleteTitle={t("roles.deleteDialog.title", "Roly pozmak")}
|
||||||
deleteDescription={t("roles.deleteDialog.description", "Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")}
|
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="ID" value={role.id} />
|
||||||
<InfoRow label={t("roles.fields.code", "Kod")} value={role.code} />
|
<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.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>
|
</Section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ export default function ClientDetailPage() {
|
|||||||
<InfoRow label={t("clients.sections.permissions", "Rugsatlar")}>
|
<InfoRow label={t("clients.sections.permissions", "Rugsatlar")}>
|
||||||
<div className="flex flex-wrap gap-1.5">
|
<div className="flex flex-wrap gap-1.5">
|
||||||
{permissions.map((p) => (
|
{permissions.map((p) => (
|
||||||
<Badge key={p.id} variant="secondary">
|
<Badge key={p.code} variant="secondary">
|
||||||
{p.name}
|
{p.name}
|
||||||
</Badge>
|
</Badge>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ export default function OperatorDetailPage() {
|
|||||||
<InfoRow label={t("operators.sections.permissions", "Rugsatlar")}>
|
<InfoRow label={t("operators.sections.permissions", "Rugsatlar")}>
|
||||||
<div className="flex flex-wrap gap-1.5">
|
<div className="flex flex-wrap gap-1.5">
|
||||||
{permissions.map((p) => (
|
{permissions.map((p) => (
|
||||||
<Badge key={p.id} variant="secondary">
|
<Badge key={p.code} variant="secondary">
|
||||||
{p.name}
|
{p.name}
|
||||||
</Badge>
|
</Badge>
|
||||||
))}
|
))}
|
||||||
|
|||||||
Reference in new issue
Block a user