diff --git a/src/app/providers/QueryProvider.tsx b/src/app/providers/QueryProvider.tsx index 8f5ea35..d69f7b8 100644 --- a/src/app/providers/QueryProvider.tsx +++ b/src/app/providers/QueryProvider.tsx @@ -14,7 +14,7 @@ export const queryClient = new QueryClient({ onError: (error, query) => { if (query.meta?.silent !== true) { const serverMessage = getErrorMessage(error); - toast.error(serverMessage || i18next.t("errors.fetchFailed"), { + toast.error(serverMessage || i18next.t("errors.fetchFailed", "Maglumatlary ýükläp bolmady"), { id: "global-query-error", }); } @@ -24,7 +24,7 @@ export const queryClient = new QueryClient({ onError: (error, _variables, _context, mutation) => { if (mutation.meta?.silent !== true) { const serverMessage = getErrorMessage(error); - toast.error(serverMessage || i18next.t("errors.actionFailed"), { + toast.error(serverMessage || i18next.t("errors.actionFailed", "Amaly ýerine ýetirip bolmady"), { id: "global-mutation-error", }); } diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index a373f80..83ac317 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -82,9 +82,6 @@ const RoleCreatePage = lazy(() => import("@/pages/settings/users/createRole")); const RoleViewPage = lazy(() => import("@/pages/settings/users/rolesView")); const RoleEditPage = lazy(() => import("@/pages/settings/users/editRole")); const PermissionsPage = lazy(() => import("@/pages/settings/users/permissions")); -const PermissionCreatePage = lazy(() => import("@/pages/settings/users/permissionsCreate")); -const PermissionsViewPage = lazy(() => import("@/pages/settings/users/permissionsView")); -const PermissionEditPage = lazy(() => import("@/pages/settings/users/permissionsEdit")); const LoanTypesPage = lazy(() => import("@/pages/settings/loan/loanTypes")); const LoanTypeCreatePage = lazy(() => import("@/pages/settings/loan/loanTypesCreate")); const LoanTypesViewPage = lazy(() => import("@/pages/settings/loan/loanTypesView")); @@ -649,27 +646,10 @@ const routes: AppRoute[] = [ }, ], }, - // Permissions + // Permissions (read-only catalogue — no create/edit/delete) { ...bc((t) => t("permissions.title", "Rugsatlar"), "/settings/users/permissions"), - children: [ - { path: "/settings/users/permissions", element: page(PermissionsPage) }, - { - path: "/settings/users/permissions/create", - handle: { title: (t) => t("permissions.createTitle", "Rugsat döretmek") }, - element: page(PermissionCreatePage), - }, - { - path: "/settings/users/permissions/:id", - handle: { title: (t) => t("permissions.viewTitle", "Rugsat giňişleýin") }, - element: page(PermissionsViewPage), - }, - { - path: "/settings/users/permissions/:id/edit", - handle: { title: (t) => t("permissions.editTitle", "Rugsat üýtgetmek") }, - element: page(PermissionEditPage), - }, - ], + children: [{ path: "/settings/users/permissions", element: page(PermissionsPage) }], }, // Loan types { diff --git a/src/app/store/authStore.ts b/src/app/store/authStore.ts index 91fc70b..1f4cb48 100644 --- a/src/app/store/authStore.ts +++ b/src/app/store/authStore.ts @@ -10,7 +10,9 @@ export interface AuthUserRole { id: number; code: string; name: string; - guardName?: string; + /** Scope determines data access level: own | branch | all */ + scope: "own" | "branch" | "all"; + isSuper: boolean; } export interface AuthUserBranch { @@ -19,25 +21,10 @@ export interface AuthUserBranch { name: LocalizedText; } +/** Permission entry from GET /profile — now just { code, name } */ export interface AuthUserPermission { - id: number; - code?: string; - name?: string; - guardName?: string; - module?: string; -} - -export interface AuthUserModulePermission { - id: number; - code?: string; - name?: string; - guardName?: string; - module?: string; -} - -export interface AuthUserModule { - module: string; - permissions: AuthUserModulePermission[]; + code: string; + name: string; } export interface AuthUser { @@ -51,7 +38,6 @@ export interface AuthUser { avatar?: string; branches?: AuthUserBranch[]; permissions?: AuthUserPermission[]; - modules?: AuthUserModule[]; createdAt?: string; } diff --git a/src/features/allUsers/api/allUsersApi.ts b/src/features/allUsers/api/allUsersApi.ts index 8c72d76..056a8fe 100644 --- a/src/features/allUsers/api/allUsersApi.ts +++ b/src/features/allUsers/api/allUsersApi.ts @@ -47,7 +47,10 @@ export interface CreateUserPayload { name: string; password: string; phone: string; - role: string; + /** Role code (e.g. "operator"). If both role and roleId are provided, roleId takes precedence. */ + role?: string; + /** Role ID. Takes precedence over `role` code when both are present. */ + roleId?: number; socialMedia: SocialMedia; username: string; } @@ -61,11 +64,19 @@ export interface UpdateUserPayload { lightMode?: number; name?: string; phone?: string; + /** Role code. If both role and roleId are provided, roleId takes precedence. */ role?: string; + /** Role ID. Takes precedence over `role` code when both are present. */ + roleId?: number; socialMedia?: SocialMedia; username?: string; } +/** Payload for PUT /users/:id/role */ +export interface UpdateUserRolePayload { + roleId: number; +} + // ─── API Functions ──────────────────────────────────────────────────────────── export const usersApi = { @@ -103,4 +114,10 @@ export const usersApi = { deleteUser: async (id: number): Promise => { await apiClient.delete(`/users/${id}`); }, + + /** PUT /users/:id/role — dedicated endpoint to change a user's role */ + updateUserRole: async (id: number, payload: UpdateUserRolePayload): Promise => { + const { data } = await apiClient.put(`/users/${id}/role`, payload); + return data; + }, }; diff --git a/src/features/clients/api/clientsApi.ts b/src/features/clients/api/clientsApi.ts index 2c1ad4f..7bec98f 100644 --- a/src/features/clients/api/clientsApi.ts +++ b/src/features/clients/api/clientsApi.ts @@ -39,13 +39,13 @@ export interface ClientRole { id: number; code: string; name: string; - guardName: string; + scope: "own" | "branch" | "all"; + isSuper: boolean; } export interface ClientPermission { - id: number; + code: string; name: string; - guardName: string; } export interface ClientBranch { diff --git a/src/features/operators/api/operatorsApi.ts b/src/features/operators/api/operatorsApi.ts index e429705..2d4d05b 100644 --- a/src/features/operators/api/operatorsApi.ts +++ b/src/features/operators/api/operatorsApi.ts @@ -44,13 +44,13 @@ export interface OperatorRole { id: number; code: string; name: string; - guardName: string; + scope: "own" | "branch" | "all"; + isSuper: boolean; } export interface OperatorPermission { - id: number; + code: string; name: string; - guardName: string; } export interface OperatorBranch { @@ -104,7 +104,10 @@ export interface CreateOperatorPayload { name: string; password: string; phone: string; - role: string; + /** Role code. If both role and roleId are provided, roleId takes precedence. */ + role?: string; + /** Role ID. Takes precedence over `role` code when both are present. */ + roleId?: number; socialMedia: SocialMedia; username: string; } @@ -118,11 +121,19 @@ export interface UpdateOperatorPayload { lightMode?: number; name?: string; phone?: string; + /** Role code. If both role and roleId are provided, roleId takes precedence. */ role?: string; + /** Role ID. Takes precedence over `role` code when both are present. */ + roleId?: number; socialMedia?: SocialMedia; username?: string; } +/** Payload for PUT /users/:id/role */ +export interface UpdateOperatorRolePayload { + roleId: number; +} + // ─── API Functions ──────────────────────────────────────────────────────────── export const operatorsApi = { @@ -158,4 +169,10 @@ export const operatorsApi = { deleteOperator: async (id: number): Promise => { await apiClient.delete(`/users/${id}`); }, + + /** PUT /users/:id/role — dedicated endpoint to change an operator's role */ + updateOperatorRole: async (id: number, payload: UpdateOperatorRolePayload): Promise => { + const { data } = await apiClient.put(`/users/${id}/role`, payload); + return data; + }, }; diff --git a/src/features/permissions/api/permissionsApi.ts b/src/features/permissions/api/permissionsApi.ts index 5d1ce9f..20c27e8 100644 --- a/src/features/permissions/api/permissionsApi.ts +++ b/src/features/permissions/api/permissionsApi.ts @@ -2,13 +2,10 @@ import apiClient from "@/lib/api/client"; // ─── Types ──────────────────────────────────────────────────────────────────── +/** Simplified permission — just a code+name catalogue entry, no id/guardName. */ export interface Permission { - id: number; code: string; name: string; - guardName: string; - createdAt: string; - updatedAt: string; } export interface PermissionsListResponse { @@ -22,16 +19,10 @@ export interface PermissionsListParams { limit?: number; } -export interface PermissionPayload { - code: string; - name: string; - guardName: string; -} - // ─── API functions ──────────────────────────────────────────────────────────── export const permissionsApi = { - /** GET /permissions — backend filters by `permission_name` */ + /** GET /permissions — returns a catalogue of [{code, name}] */ getAll: async (params: PermissionsListParams = {}, signal?: AbortSignal): Promise => { const { search, page, limit } = params; const { data } = await apiClient.get("/permissions", { @@ -40,27 +31,4 @@ export const permissionsApi = { }); return data; }, - - /** GET /permissions/:id */ - getById: async (id: number): Promise => { - const { data } = await apiClient.get(`/permissions/${id}`); - return data; - }, - - /** POST /permissions */ - create: async (payload: PermissionPayload): Promise => { - const { data } = await apiClient.post("/permissions", payload); - return data; - }, - - /** PUT /permissions/:id */ - update: async (id: number, payload: PermissionPayload): Promise => { - const { data } = await apiClient.put(`/permissions/${id}`, payload); - return data; - }, - - /** DELETE /permissions/:id */ - delete: async (id: number): Promise => { - await apiClient.delete(`/permissions/${id}`); - }, }; diff --git a/src/features/permissions/hooks/usePermissions.ts b/src/features/permissions/hooks/usePermissions.ts index 1823122..70bd43c 100644 --- a/src/features/permissions/hooks/usePermissions.ts +++ b/src/features/permissions/hooks/usePermissions.ts @@ -1,8 +1,6 @@ -import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query"; -import { toast } from "sonner"; -import { useTranslation } from "react-i18next"; +import { useQuery, useInfiniteQuery } from "@tanstack/react-query"; import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch"; -import { permissionsApi, type PermissionPayload, type PermissionsListParams } from "../api/permissionsApi"; +import { permissionsApi, type PermissionsListParams } from "../api/permissionsApi"; // ─── Query keys ─────────────────────────────────────────────────────────────── @@ -10,7 +8,6 @@ export const permissionKeys = { all: ["permissions"] as const, lists: () => ["permissions", "list"] as const, list: (params: PermissionsListParams) => ["permissions", "list", params] as const, - detail: (id: number) => ["permissions", "detail", id] as const, infinite: (search: string) => ["permissions", "infinite", search] as const, }; @@ -27,16 +24,6 @@ export function usePermissions(params: PermissionsListParams) { }); } -// ─── 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; @@ -63,49 +50,3 @@ export function useInfinitePermissions(search = "", enabled = true) { 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!")); - }, - }); -} diff --git a/src/features/roles/api/rolesApi.ts b/src/features/roles/api/rolesApi.ts index 0988876..dba9e40 100644 --- a/src/features/roles/api/rolesApi.ts +++ b/src/features/roles/api/rolesApi.ts @@ -2,11 +2,18 @@ import apiClient from "@/lib/api/client"; // ─── Types ──────────────────────────────────────────────────────────────────── +/** Scope of a role: 'own' | 'branch' | 'all' */ +export type RoleScope = "own" | "branch" | "all"; + export interface Role { id: number; code: string; name: string; - guardName: string; + scope: RoleScope; + isSuper: boolean; + isSystem: boolean; + permissions: string[]; + usersCount: number; createdAt: string; updatedAt: string; } @@ -25,7 +32,14 @@ export interface RolesListParams { export interface RolePayload { code: string; name: string; - guardName: string; + scope: RoleScope; + permissions: string[]; +} + +export interface UpdateRolePayload { + name: string; + scope: RoleScope; + permissions: string[]; } // ─── API functions ──────────────────────────────────────────────────────────── @@ -47,19 +61,26 @@ export const rolesApi = { return data; }, - /** POST /roles */ + /** POST /roles — { code, name, scope, permissions: string[] } */ create: async (payload: RolePayload): Promise => { const { data } = await apiClient.post("/roles", payload); return data; }, - /** PUT /roles/:id */ - update: async (id: number, payload: RolePayload): Promise => { + /** + * PUT /roles/:id — { name, scope, permissions } + * Note: `code` cannot be changed via update. + * `isSystem: true` roles cannot have their scope changed (enforce in UI). + */ + update: async (id: number, payload: UpdateRolePayload): Promise => { const { data } = await apiClient.put(`/roles/${id}`, payload); return data; }, - /** DELETE /roles/:id */ + /** + * DELETE /roles/:id + * Note: `isSystem: true` roles (e.g. superadmin, user) cannot be deleted (enforce in UI). + */ delete: async (id: number): Promise => { await apiClient.delete(`/roles/${id}`); }, diff --git a/src/features/roles/components/roleForm.tsx b/src/features/roles/components/roleForm.tsx index 03c6573..6ad905b 100644 --- a/src/features/roles/components/roleForm.tsx +++ b/src/features/roles/components/roleForm.tsx @@ -1,15 +1,20 @@ import { useMemo, useEffect, useCallback } from "react"; import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { useForm } from "react-hook-form"; +import { useForm, Controller } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { FormActions } from "@/components/formActions"; import { BentoGrid, BentoCard } from "@/components/bento"; import { useCreateRole, useUpdateRole } from "../hooks/useRoles"; -import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/role.schema"; +import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildCreatePayload, buildUpdatePayload, SCOPE_OPTIONS } from "../schemas/role.schema"; import type { RoleFormData } from "../schemas/role.schema"; import type { Role } from "../api/rolesApi"; import { FormInput } from "@/components/formInput"; +import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions"; +import { Label } from "@/components/ui/label"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { cn } from "@/lib/utils"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -46,10 +51,15 @@ export function RoleForm({ mode, initialData }: RoleFormProps) { const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language]); + // ── All available permissions (for the multi-select) ─────────────────────── + const { data: permInfinite } = useInfinitePermissions("", true); + const allPermissions = useMemo(() => permInfinite?.pages.flatMap((p) => p.permissions) ?? [], [permInfinite]); + const { watch, setValue, getValues, + control, formState: { errors: rhfErrors }, clearErrors, trigger, @@ -60,7 +70,8 @@ export function RoleForm({ mode, initialData }: RoleFormProps) { ...DEFAULT_FORM_VALUES, code: initialData.code, name: initialData.name, - guardName: initialData.guardName, + scope: initialData.scope, + permissions: initialData.permissions ?? [], } : DEFAULT_FORM_VALUES, }); @@ -82,6 +93,16 @@ export function RoleForm({ mode, initialData }: RoleFormProps) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [i18n.language]); + // ── Toggle a permission code in/out of the selected list ── + const togglePermission = useCallback( + (code: string) => { + const current = getValues("permissions") ?? []; + const next = current.includes(code) ? current.filter((c) => c !== code) : [...current, code]; + setValue("permissions", next); + }, + [getValues, setValue], + ); + // ── Submit ───────────────────────────────────────────────────────────────── const handleSubmit = async () => { @@ -89,14 +110,13 @@ export function RoleForm({ mode, initialData }: RoleFormProps) { if (!isValid) return; const values = getValues(); - const payload = buildPayload(values); if (mode === "create") { - createRole.mutate(payload, { + createRole.mutate(buildCreatePayload(values), { onSuccess: () => navigate("/settings/users/roles"), }); } else { - updateRole.mutate(payload, { + updateRole.mutate(buildUpdatePayload(values), { onSuccess: () => navigate("/settings/users/roles"), }); } @@ -104,12 +124,19 @@ export function RoleForm({ mode, initialData }: RoleFormProps) { // ── Render ───────────────────────────────────────────────────────────────── + const scopeLabels: Record = { + own: t("roles.scope.own", "Öz ýazgylary"), + branch: t("roles.scope.branch", "Şahamça"), + all: t("roles.scope.all", "Hemmesi"), + }; + return (

{mode === "create" ? t("roles.createTitle", "Rol dörediň") : t("roles.editTitle", "Rol üýtgetmek")}

+ {/* Code — only editable on create */} + + {/* Name */} - - - + + {/* Scope */} + +
+ + ( + + )} + /> + {errors.scope &&

{errors.scope}

} +
+
+ + {/* Permissions multi-select */} + +
+ + {allPermissions.length === 0 ? ( +

{t("common.loading", "Ýüklenýär...")}

+ ) : ( +
+ {allPermissions.map((perm) => { + const checked = (form.permissions ?? []).includes(perm.code); + return ( + + ); + })} +
+ )} +
+
+ rolesApi.update(id, payload), + mutationFn: (payload: UpdateRolePayload) => rolesApi.update(id, payload), onSuccess: (data) => { queryClient.invalidateQueries({ queryKey: roleKeys.all }); queryClient.invalidateQueries({ queryKey: roleKeys.detail(data.id) }); diff --git a/src/features/roles/schemas/role.schema.ts b/src/features/roles/schemas/role.schema.ts index 5b841c2..98a2af7 100644 --- a/src/features/roles/schemas/role.schema.ts +++ b/src/features/roles/schemas/role.schema.ts @@ -1,11 +1,16 @@ import { z } from "zod"; -import type { RolePayload } from "../api/rolesApi"; +import type { RolePayload, UpdateRolePayload, RoleScope } from "../api/rolesApi"; + +const SCOPE_OPTIONS: RoleScope[] = ["own", "branch", "all"]; export function createRoleFormSchema(t: (key: string, fallback?: string) => string) { return z.object({ code: z.string().min(1, t("validation.required", "validation.required")), name: z.string().min(1, t("validation.required", "validation.required")), - guardName: z.string().min(1, t("validation.required", "validation.required")), + scope: z.enum(["own", "branch", "all"], { + message: t("validation.required", "validation.required"), + }), + permissions: z.array(z.string()), }); } @@ -14,13 +19,25 @@ export type RoleFormData = z.infer>; export const DEFAULT_FORM_VALUES: RoleFormData = { code: "", name: "", - guardName: "operator", + scope: "branch", + permissions: [], }; -export function buildPayload(data: RoleFormData): RolePayload { +export { SCOPE_OPTIONS }; + +export function buildCreatePayload(data: RoleFormData): RolePayload { return { code: data.code, name: data.name, - guardName: data.guardName, + scope: data.scope, + permissions: data.permissions, + }; +} + +export function buildUpdatePayload(data: RoleFormData): UpdateRolePayload { + return { + name: data.name, + scope: data.scope, + permissions: data.permissions, }; } diff --git a/src/lib/auth/permissions.ts b/src/lib/auth/permissions.ts index 381a997..1ed8c48 100644 --- a/src/lib/auth/permissions.ts +++ b/src/lib/auth/permissions.ts @@ -1,31 +1,29 @@ import type { AuthUser, AuthUserPermission } from "@/app/store/authStore"; /** - * Access model: - * - "admin" guard has full access to everything regardless of its permission list. - * - "web" guard (public user role) can open the Orders section (loan / card / international payments). - * - Any other guard (operator, ...) is limited to the permission codes it holds. + * Access model (new, post-API-v2): + * - isSuper roles (scope === 'all' with isSuper=true) have full access to everything. + * - "user" role code (web/public user, scope === 'own') can open the Orders section. + * - Any other role is limited to the permission codes it holds. + * + * guardName is no longer returned by the API. Use role.scope and role.isSuper instead. */ -// ─── Guard names ────────────────────────────────────────────────────────────── +// ─── Role helpers ───────────────────────────────────────────────────────────── -export const ADMIN_GUARD = "admin"; -export const OPERATOR_GUARD = "operator"; -export const WEB_GUARD = "web"; - -/** True when the user's role is the admin guard (full access). */ +/** True when the user has a super role (full access). */ export function isAdmin(user?: AuthUser | null): boolean { if (!user?.role) return false; - return user.role.guardName === ADMIN_GUARD || user.role.code === "admin"; + return user.role.isSuper === true || user.role.code === "superadmin"; } -/** True when the user's role is the web guard (the public "user" role). */ +/** True when the user is a public "web" user (role code === 'user', scope === 'own'). */ export function isWebUser(user?: AuthUser | null): boolean { if (!user?.role) return false; - return user.role.guardName === WEB_GUARD || user.role.code === "user"; + return user.role.code === "user" || user.role.scope === "own"; } -/** Returns the list of permission codes the user holds (empty for admin since it is unrestricted). */ +/** Returns the list of permission codes the user holds (empty for super-admin since it is unrestricted). */ export function getPermissionCodes(user?: AuthUser | null): string[] { if (isAdmin(user)) return []; const seen = new Set(); @@ -37,9 +35,6 @@ export function getPermissionCodes(user?: AuthUser | null): string[] { } }; for (const p of user?.permissions ?? []) push(p); - for (const m of user?.modules ?? []) { - for (const p of m.permissions ?? []) push(p); - } return codes; } @@ -65,15 +60,16 @@ export function hasAnyPermission(user: AuthUser | null | undefined, codes: reado export const PERM = { LOANS: "loans", CARDS: "cards", - USERS_VIEW: "users.view", - USERS_MANAGE: "users.manage", - ROLES_VIEW: "roles.view", - BRANCHES_VIEW: "branches.view", - PROVINCES_VIEW: "provinces.view", - BACKUPS_VIEW: "backups.view", - ACTIVITY_LOGS_VIEW: "activity-logs.view", - CURRENCIES_VIEW: "currencies.view", - /** Sentinel for pages that only the admin guard may access (no permission code exists). */ + USERS: "users", + ROLES: "roles", + BRANCHES: "branches", + PROVINCES: "provinces", + BACKUPS: "backups", + ACTIVITY_LOGS: "activity-logs", + CURRENCIES: "currencies", + PAYMENT_SETTINGS: "payment-settings", + DASHBOARD: "dashboard", + /** Sentinel for pages that only the super-admin may access (no permission code exists). */ ADMIN_ONLY: "__admin_only__", } as const; @@ -104,15 +100,15 @@ const ROUTE_RULES: RouteRule[] = [ ["/sber-payments", [PERM.ADMIN_ONLY]], ["/online-payments-history", [PERM.ADMIN_ONLY]], // Users (operators / clients / all users) - ["/operators", [PERM.USERS_VIEW, PERM.USERS_MANAGE]], - ["/all-users", [PERM.USERS_VIEW, PERM.USERS_MANAGE]], - ["/clients", [PERM.USERS_VIEW, PERM.USERS_MANAGE]], + ["/operators", [PERM.USERS]], + ["/all-users", [PERM.USERS]], + ["/clients", [PERM.USERS]], // Currencies - ["/currency-rates", [PERM.CURRENCIES_VIEW]], - ["/visa-master-sber-settings", [PERM.CURRENCIES_VIEW]], + ["/currency-rates", [PERM.CURRENCIES]], + ["/visa-master-sber-settings", [PERM.CURRENCIES]], // System pages - ["/backups", [PERM.BACKUPS_VIEW]], - ["/logs", [PERM.ACTIVITY_LOGS_VIEW]], + ["/backups", [PERM.BACKUPS]], + ["/logs", [PERM.ACTIVITY_LOGS]], ]; /** Match a path against the rule prefixes (exact or sub-path). */ @@ -177,13 +173,13 @@ function isWebAccessiblePath(pathname: string): boolean { const HOME_PRIORITY: readonly (readonly [codes: readonly PermValue[], path: string])[] = [ [[PERM.LOANS], "/loan-orders"], [[PERM.CARDS], "/order-new-card"], - [[PERM.USERS_VIEW, PERM.USERS_MANAGE], "/operators"], - [[PERM.CURRENCIES_VIEW], "/currency-rates"], - [[PERM.BACKUPS_VIEW], "/backups"], - [[PERM.ACTIVITY_LOGS_VIEW], "/logs"], + [[PERM.USERS], "/operators"], + [[PERM.CURRENCIES], "/currency-rates"], + [[PERM.BACKUPS], "/backups"], + [[PERM.ACTIVITY_LOGS], "/logs"], ]; -/** Returns the landing page for the user: admin → dashboard, web → orders, else the first page they may open. */ +/** Returns the landing page for the user: super-admin → dashboard, web user → orders, else the first page they may open. */ export function getDefaultHomePath(user: AuthUser | null | undefined): string { if (isAdmin(user)) return "/dashboard"; if (isWebUser(user)) return "/loan-orders"; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index bb6c7ea..5577f1b 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -394,6 +394,8 @@ "errors.pageNotFoundTitle": "Page not found", "errors.pageNotFoundDescription": "The page you are looking for does not exist or has been moved.", "errors.forbidden": "You do not have permission to perform this action.", + "errors.fetchFailed": "Failed to load data", + "errors.actionFailed": "Failed to perform action", "Phone or username": "Phone or username", "featureNotImplemented": "Not implemented", "common.search": "Search", diff --git a/src/lib/i18n/locales/ru.json b/src/lib/i18n/locales/ru.json index 61eb531..f47de12 100644 --- a/src/lib/i18n/locales/ru.json +++ b/src/lib/i18n/locales/ru.json @@ -394,6 +394,8 @@ "errors.pageNotFoundTitle": "Страница не найдена", "errors.pageNotFoundDescription": "Страница, которую вы ищете, не существует или была перемещена.", "errors.forbidden": "У вас нет разрешения на выполнение этого действия.", + "errors.fetchFailed": "Не удалось загрузить данные", + "errors.actionFailed": "Не удалось выполнить действие", "Phone or username": "Телефон или имя пользователя", "featureNotImplemented": "Эта функция еще не реализована", "common.search": "Поиск", diff --git a/src/lib/i18n/locales/tk.json b/src/lib/i18n/locales/tk.json index 49132f9..3b66627 100644 --- a/src/lib/i18n/locales/tk.json +++ b/src/lib/i18n/locales/tk.json @@ -394,6 +394,8 @@ "errors.pageNotFoundTitle": "Sahypa tapylmady", "errors.pageNotFoundDescription": "Gözleýän sahypaňyz ýok ýa-da başga ýere geçirilen bolup biler.", "errors.forbidden": "Bu amaly ýerine ýetirmäge rugsadyňyz ýok.", + "errors.fetchFailed": "Maglumatlary ýükläp bolmady", + "errors.actionFailed": "Amaly ýerine ýetirip bolmady", "Phone or username": "Telefon ýada ulanyjy ady", "featureNotImplemented": "Bu funksiýa entek durmuşa geçirilmedi", "common.search": "Gözlemek", diff --git a/src/pages/settings/users/permissions/index.tsx b/src/pages/settings/users/permissions/index.tsx index 8b32828..7e970ca 100644 --- a/src/pages/settings/users/permissions/index.tsx +++ b/src/pages/settings/users/permissions/index.tsx @@ -1,28 +1,23 @@ import { useState, useMemo } from "react"; -import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import type { ColumnDef, VisibilityState } from "@tanstack/react-table"; import { DataTable } from "@/components/dataTable"; import { DataTableToolbar } from "@/components/dataTableToolbar"; import { TableSearchInput } from "@/components/tableSearch"; -import { CreateButton } from "@/components/createButton"; -import { TableActions } from "@/components/tableActions"; -import { DeleteDialog } from "@/components/deleteDialog"; -import { usePermissions, useDeletePermission } from "@/features/permissions/hooks/usePermissions"; +import { usePermissions } from "@/features/permissions/hooks/usePermissions"; import type { Permission } from "@/features/permissions/api/permissionsApi"; // ─── PermissionsPage ────────────────────────────────────────────────────────── +// Permissions are now a read-only catalogue (only GET /permissions is available). +// Creating / editing / deleting permissions via the UI is no longer supported. export default function PermissionsPage() { const { t } = useTranslation(); - const navigate = useNavigate(); const columnMeta = useMemo( () => [ - { id: "id", label: t("common.id", "ID") }, { id: "code", label: t("permissions.fields.code", "Kod") }, { id: "name", label: t("permissions.fields.name", "Ady") }, - { id: "guardName", label: t("permissions.fields.guardName", "Guard name") }, ], [t], ); @@ -33,59 +28,24 @@ export default function PermissionsPage() { const [perPage, setPerPage] = useState(25); const [columnVisibility, setColumnVisibility] = useState({}); const [columnOrder, setColumnOrder] = useState([]); - const [deleteId, setDeleteId] = useState(null); // ── Data ─────────────────────────────────────────────────────────────────── const { data, isLoading } = usePermissions({ search, page, limit: perPage }); - const deletePermission = useDeletePermission(); // ── Columns ──────────────────────────────────────────────────────────────── const columns: ColumnDef[] = [ - { - accessorKey: "id", - header: t("common.id", "ID"), - size: 70, - cell: ({ row }) => {row.original.id}, - }, { accessorKey: "code", header: t("permissions.fields.code", "Kod"), + cell: ({ row }) => {row.original.code}, }, { accessorKey: "name", header: t("permissions.fields.name", "Ady"), cell: ({ row }) => {row.original.name ?? "—"}, }, - { - accessorKey: "guardName", - header: t("permissions.fields.guardName", "Guard name"), - }, - { - id: "actions", - header: "", - size: 120, - enableSorting: false, - enableHiding: false, - cell: ({ row }) => ( - 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 (
@@ -102,12 +62,8 @@ export default function PermissionsPage() { }} placeholder={t("permissions.searchPlaceholder", "Gözlemek...")} /> - navigate("/settings/users/permissions/create")} - />
- {/* Toolbar */} + {/* Table */} String(row.id)} + getRowId={(row) => row.code} currentPage={page} totalPages={Math.max(1, Math.ceil((data?.count ?? 0) / perPage))} totalCount={data?.count} @@ -146,18 +101,6 @@ export default function PermissionsPage() { /> } /> - - {/* Delete confirmation dialog */} - { - if (!o) setDeleteId(null); - }} - title={t("permissions.deleteDialog.title", "Rugsaty pozmak")} - description={t("permissions.deleteDialog.description", "Bu rugsaty pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")} - onConfirm={handleConfirmDelete} - isLoading={deletePermission.isPending} - />
); } diff --git a/src/pages/settings/users/roles/index.tsx b/src/pages/settings/users/roles/index.tsx index edb6ea1..c9f41cf 100644 --- a/src/pages/settings/users/roles/index.tsx +++ b/src/pages/settings/users/roles/index.tsx @@ -10,6 +10,7 @@ import { TableActions } from "@/components/tableActions"; import { DeleteDialog } from "@/components/deleteDialog"; import { useRoles, useDeleteRole } from "@/features/roles/hooks/useRoles"; import type { Role } from "@/features/roles/api/rolesApi"; +import { Badge } from "@/components/ui/badge"; // ─── RolesPage ──────────────────────────────────────────────────────────────── @@ -22,7 +23,8 @@ export default function RolesPage() { { id: "id", label: t("common.id", "ID") }, { id: "code", label: t("roles.fields.code", "Kod") }, { id: "name", label: t("roles.fields.name", "Ady") }, - { id: "guardName", label: t("roles.fields.guardName", "Guard name") }, + { id: "scope", label: t("roles.fields.scope", "Scope") }, + { id: "usersCount", label: t("roles.fields.usersCount", "Ulanyjylar") }, ], [t], ); @@ -57,8 +59,24 @@ export default function RolesPage() { cell: ({ row }) => {row.original.name ?? "—"}, }, { - accessorKey: "guardName", - header: t("roles.fields.guardName", "Guard name"), + accessorKey: "scope", + header: t("roles.fields.scope", "Scope"), + cell: ({ row }) => { + const scope = row.original.scope; + const scopeLabels: Record = { + own: t("roles.scope.own", "Öz"), + branch: t("roles.scope.branch", "Şahamça"), + all: t("roles.scope.all", "Hemmesi"), + }; + return ( + {scopeLabels[scope] ?? scope} + ); + }, + }, + { + accessorKey: "usersCount", + header: t("roles.fields.usersCount", "Ulanyjylar"), + cell: ({ row }) => {row.original.usersCount ?? 0}, }, { id: "actions", @@ -70,7 +88,8 @@ export default function RolesPage() { navigate(`/settings/users/roles/${row.original.id}`)} onEdit={() => navigate(`/settings/users/roles/${row.original.id}/edit`)} - onDelete={() => setDeleteId(row.original.id)} + // isSystem roles (superadmin, user) cannot be deleted — hide the delete button + onDelete={row.original.isSystem ? undefined : () => setDeleteId(row.original.id)} isDeleting={deleteRole.isPending} /> ), diff --git a/src/pages/settings/users/rolesView/index.tsx b/src/pages/settings/users/rolesView/index.tsx index eba9acd..71793d7 100644 --- a/src/pages/settings/users/rolesView/index.tsx +++ b/src/pages/settings/users/rolesView/index.tsx @@ -1,6 +1,7 @@ import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { Skeleton } from "@/components/ui/skeleton"; +import { Badge } from "@/components/ui/badge"; import { Section, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { useRole, useDeleteRole } from "@/features/roles/hooks/useRoles"; @@ -26,7 +27,7 @@ export default function RoleViewPage() {
- {Array.from({ length: 4 }).map((_, i) => ( + {Array.from({ length: 5 }).map((_, i) => (
{t("common.fetchError", "Maglumat ýüklenmedi.")}

; } + const scopeLabels: Record = { + own: t("roles.scope.own", "Öz ýazgylary"), + branch: t("roles.scope.branch", "Şahamça"), + all: t("roles.scope.all", "Hemmesi"), + }; + // ── Render ───────────────────────────────────────────────────────────────── return (
@@ -55,7 +62,8 @@ export default function RoleViewPage() {
- + + {scopeLabels[role.scope] ?? role.scope} + + } + /> + +
);