for merger
This commit is contained in:
1 parent
8dc61d7786
commit
9930a16f5c
19 files changed
+300
-287
No files matched your search
@@ -14,7 +14,7 @@ export const queryClient = new QueryClient({
|
|||||||
onError: (error, query) => {
|
onError: (error, query) => {
|
||||||
if (query.meta?.silent !== true) {
|
if (query.meta?.silent !== true) {
|
||||||
const serverMessage = getErrorMessage(error);
|
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",
|
id: "global-query-error",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ export const queryClient = new QueryClient({
|
|||||||
onError: (error, _variables, _context, mutation) => {
|
onError: (error, _variables, _context, mutation) => {
|
||||||
if (mutation.meta?.silent !== true) {
|
if (mutation.meta?.silent !== true) {
|
||||||
const serverMessage = getErrorMessage(error);
|
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",
|
id: "global-mutation-error",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"));
|
||||||
@@ -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"),
|
...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,9 @@ export interface AuthUserRole {
|
|||||||
id: number;
|
id: number;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName?: string;
|
/** Scope determines data access level: own | branch | all */
|
||||||
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthUserBranch {
|
export interface AuthUserBranch {
|
||||||
@@ -19,25 +21,10 @@ export interface AuthUserBranch {
|
|||||||
name: LocalizedText;
|
name: LocalizedText;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Permission entry from GET /profile — now just { code, name } */
|
||||||
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 +38,6 @@ export interface AuthUser {
|
|||||||
avatar?: string;
|
avatar?: string;
|
||||||
branches?: AuthUserBranch[];
|
branches?: AuthUserBranch[];
|
||||||
permissions?: AuthUserPermission[];
|
permissions?: AuthUserPermission[];
|
||||||
modules?: AuthUserModule[];
|
|
||||||
createdAt?: string;
|
createdAt?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,10 @@ export interface CreateUserPayload {
|
|||||||
name: string;
|
name: string;
|
||||||
password: string;
|
password: string;
|
||||||
phone: 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;
|
socialMedia: SocialMedia;
|
||||||
username: string;
|
username: string;
|
||||||
}
|
}
|
||||||
@@ -61,11 +64,19 @@ export interface UpdateUserPayload {
|
|||||||
lightMode?: number;
|
lightMode?: number;
|
||||||
name?: string;
|
name?: string;
|
||||||
phone?: string;
|
phone?: string;
|
||||||
|
/** Role code. If both role and roleId are provided, roleId takes precedence. */
|
||||||
role?: string;
|
role?: string;
|
||||||
|
/** Role ID. Takes precedence over `role` code when both are present. */
|
||||||
|
roleId?: number;
|
||||||
socialMedia?: SocialMedia;
|
socialMedia?: SocialMedia;
|
||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Payload for PUT /users/:id/role */
|
||||||
|
export interface UpdateUserRolePayload {
|
||||||
|
roleId: number;
|
||||||
|
}
|
||||||
|
|
||||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const usersApi = {
|
export const usersApi = {
|
||||||
@@ -103,4 +114,10 @@ export const usersApi = {
|
|||||||
deleteUser: async (id: number): Promise<void> => {
|
deleteUser: async (id: number): Promise<void> => {
|
||||||
await apiClient.delete(`/users/${id}`);
|
await apiClient.delete(`/users/${id}`);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/** PUT /users/:id/role — dedicated endpoint to change a user's role */
|
||||||
|
updateUserRole: async (id: number, payload: UpdateUserRolePayload): Promise<User> => {
|
||||||
|
const { data } = await apiClient.put<User>(`/users/${id}/role`, payload);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
@@ -39,13 +39,13 @@ export interface ClientRole {
|
|||||||
id: number;
|
id: number;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientPermission {
|
export interface ClientPermission {
|
||||||
id: number;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientBranch {
|
export interface ClientBranch {
|
||||||
|
|||||||
@@ -44,13 +44,13 @@ export interface OperatorRole {
|
|||||||
id: number;
|
id: number;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OperatorPermission {
|
export interface OperatorPermission {
|
||||||
id: number;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OperatorBranch {
|
export interface OperatorBranch {
|
||||||
@@ -104,7 +104,10 @@ export interface CreateOperatorPayload {
|
|||||||
name: string;
|
name: string;
|
||||||
password: string;
|
password: string;
|
||||||
phone: 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;
|
socialMedia: SocialMedia;
|
||||||
username: string;
|
username: string;
|
||||||
}
|
}
|
||||||
@@ -118,11 +121,19 @@ export interface UpdateOperatorPayload {
|
|||||||
lightMode?: number;
|
lightMode?: number;
|
||||||
name?: string;
|
name?: string;
|
||||||
phone?: string;
|
phone?: string;
|
||||||
|
/** Role code. If both role and roleId are provided, roleId takes precedence. */
|
||||||
role?: string;
|
role?: string;
|
||||||
|
/** Role ID. Takes precedence over `role` code when both are present. */
|
||||||
|
roleId?: number;
|
||||||
socialMedia?: SocialMedia;
|
socialMedia?: SocialMedia;
|
||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Payload for PUT /users/:id/role */
|
||||||
|
export interface UpdateOperatorRolePayload {
|
||||||
|
roleId: number;
|
||||||
|
}
|
||||||
|
|
||||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const operatorsApi = {
|
export const operatorsApi = {
|
||||||
@@ -158,4 +169,10 @@ export const operatorsApi = {
|
|||||||
deleteOperator: async (id: number): Promise<void> => {
|
deleteOperator: async (id: number): Promise<void> => {
|
||||||
await apiClient.delete(`/users/${id}`);
|
await apiClient.delete(`/users/${id}`);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/** PUT /users/:id/role — dedicated endpoint to change an operator's role */
|
||||||
|
updateOperatorRole: async (id: number, payload: UpdateOperatorRolePayload): Promise<Operator> => {
|
||||||
|
const { data } = await apiClient.put<Operator>(`/users/${id}/role`, payload);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
@@ -2,13 +2,10 @@ import apiClient from "@/lib/api/client";
|
|||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Simplified permission — just a code+name catalogue entry, no id/guardName. */
|
||||||
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 {
|
export interface PermissionsListResponse {
|
||||||
@@ -22,16 +19,10 @@ export interface PermissionsListParams {
|
|||||||
limit?: 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 — returns a catalogue of [{code, name}] */
|
||||||
getAll: async (params: PermissionsListParams = {}, signal?: AbortSignal): Promise<PermissionsListResponse> => {
|
getAll: async (params: PermissionsListParams = {}, signal?: AbortSignal): Promise<PermissionsListResponse> => {
|
||||||
const { search, page, limit } = params;
|
const { search, page, limit } = params;
|
||||||
const { data } = await apiClient.get<PermissionsListResponse>("/permissions", {
|
const { data } = await apiClient.get<PermissionsListResponse>("/permissions", {
|
||||||
@@ -40,27 +31,4 @@ export const permissionsApi = {
|
|||||||
});
|
});
|
||||||
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,8 +1,6 @@
|
|||||||
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
import { useQuery, useInfiniteQuery } from "@tanstack/react-query";
|
||||||
import { toast } from "sonner";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
import { permissionsApi, type PermissionPayload, type PermissionsListParams } from "../api/permissionsApi";
|
import { permissionsApi, type PermissionsListParams } from "../api/permissionsApi";
|
||||||
|
|
||||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -10,7 +8,6 @@ export const permissionKeys = {
|
|||||||
all: ["permissions"] as const,
|
all: ["permissions"] as const,
|
||||||
lists: () => ["permissions", "list"] as const,
|
lists: () => ["permissions", "list"] as const,
|
||||||
list: (params: PermissionsListParams) => ["permissions", "list", params] 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,
|
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 ───────────────────────────────────────────────────
|
// ─── useInfinitePermissions ───────────────────────────────────────────────────
|
||||||
|
|
||||||
const PERMISSION_PAGE_SIZE = 25;
|
const PERMISSION_PAGE_SIZE = 25;
|
||||||
@@ -63,49 +50,3 @@ export function useInfinitePermissions(search = "", enabled = true) {
|
|||||||
enabled,
|
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!"));
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -2,11 +2,18 @@ import apiClient from "@/lib/api/client";
|
|||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Scope of a role: 'own' | 'branch' | 'all' */
|
||||||
|
export type RoleScope = "own" | "branch" | "all";
|
||||||
|
|
||||||
export interface Role {
|
export interface Role {
|
||||||
id: number;
|
id: number;
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
scope: RoleScope;
|
||||||
|
isSuper: boolean;
|
||||||
|
isSystem: boolean;
|
||||||
|
permissions: string[];
|
||||||
|
usersCount: number;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
@@ -25,7 +32,14 @@ export interface RolesListParams {
|
|||||||
export interface RolePayload {
|
export interface RolePayload {
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
guardName: string;
|
scope: RoleScope;
|
||||||
|
permissions: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateRolePayload {
|
||||||
|
name: string;
|
||||||
|
scope: RoleScope;
|
||||||
|
permissions: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── API functions ────────────────────────────────────────────────────────────
|
// ─── API functions ────────────────────────────────────────────────────────────
|
||||||
@@ -47,19 +61,26 @@ export const rolesApi = {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
/** POST /roles */
|
/** POST /roles — { code, name, scope, permissions: string[] } */
|
||||||
create: async (payload: RolePayload): Promise<Role> => {
|
create: async (payload: RolePayload): 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 */
|
/**
|
||||||
update: async (id: number, payload: RolePayload): Promise<Role> => {
|
* 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<Role> => {
|
||||||
const { data } = await apiClient.put<Role>(`/roles/${id}`, payload);
|
const { data } = await apiClient.put<Role>(`/roles/${id}`, payload);
|
||||||
return data;
|
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<void> => {
|
delete: async (id: number): Promise<void> => {
|
||||||
await apiClient.delete(`/roles/${id}`);
|
await apiClient.delete(`/roles/${id}`);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
import { useMemo, useEffect, useCallback } from "react";
|
import { useMemo, useEffect, useCallback } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
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 { 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 { 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, SCOPE_OPTIONS } 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 } 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 ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -46,10 +51,15 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
|
|
||||||
const schema = useMemo(() => createRoleFormSchema(t), [t, i18n.language]);
|
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 {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
getValues,
|
getValues,
|
||||||
|
control,
|
||||||
formState: { errors: rhfErrors },
|
formState: { errors: rhfErrors },
|
||||||
clearErrors,
|
clearErrors,
|
||||||
trigger,
|
trigger,
|
||||||
@@ -60,7 +70,8 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
...DEFAULT_FORM_VALUES,
|
...DEFAULT_FORM_VALUES,
|
||||||
code: initialData.code,
|
code: initialData.code,
|
||||||
name: initialData.name,
|
name: initialData.name,
|
||||||
guardName: initialData.guardName,
|
scope: initialData.scope,
|
||||||
|
permissions: initialData.permissions ?? [],
|
||||||
}
|
}
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
});
|
});
|
||||||
@@ -82,6 +93,16 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [i18n.language]);
|
}, [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 ─────────────────────────────────────────────────────────────────
|
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
@@ -89,14 +110,13 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
if (!isValid) 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"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -104,12 +124,19 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
|
|
||||||
// ── Render ─────────────────────────────────────────────────────────────────
|
// ── Render ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const scopeLabels: Record<string, string> = {
|
||||||
|
own: t("roles.scope.own", "Öz ýazgylary"),
|
||||||
|
branch: t("roles.scope.branch", "Şahamça"),
|
||||||
|
all: t("roles.scope.all", "Hemmesi"),
|
||||||
|
};
|
||||||
|
|
||||||
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">
|
||||||
{mode === "create" ? t("roles.createTitle", "Rol dörediň") : t("roles.editTitle", "Rol üýtgetmek")}
|
{mode === "create" ? t("roles.createTitle", "Rol dörediň") : t("roles.editTitle", "Rol üýtgetmek")}
|
||||||
</h1>
|
</h1>
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
|
{/* Code — only editable on create */}
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
@@ -118,23 +145,13 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
onChange={setField("code")}
|
onChange={setField("code")}
|
||||||
placeholder={t("roles.fields.code", "Kod")}
|
placeholder={t("roles.fields.code", "Kod")}
|
||||||
error={errors.code}
|
error={errors.code}
|
||||||
disabled={isPending}
|
disabled={isPending || mode === "edit"}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
|
{/* Name */}
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
|
||||||
type="text"
|
|
||||||
label={t("roles.fields.guardName", "Guard name")}
|
|
||||||
value={form.guardName}
|
|
||||||
onChange={setField("guardName")}
|
|
||||||
placeholder="operator"
|
|
||||||
error={errors.guardName}
|
|
||||||
disabled={isPending}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</BentoCard>
|
|
||||||
<BentoCard span="full">
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("roles.fields.name", "Ady")}
|
label={t("roles.fields.name", "Ady")}
|
||||||
@@ -146,7 +163,71 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
|||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
|
{/* Scope */}
|
||||||
|
<BentoCard span="full">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label className="text-sm font-medium">
|
||||||
|
{t("roles.fields.scope", "Scope")}
|
||||||
|
<span className="text-destructive ml-1">*</span>
|
||||||
|
</Label>
|
||||||
|
<Controller
|
||||||
|
control={control}
|
||||||
|
name="scope"
|
||||||
|
render={({ field }) => (
|
||||||
|
<Select value={field.value} onValueChange={field.onChange} disabled={isPending}>
|
||||||
|
<SelectTrigger className={cn(errors.scope && "border-destructive")}>
|
||||||
|
<SelectValue placeholder={t("roles.fields.scope", "Scope")} />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{SCOPE_OPTIONS.map((s) => (
|
||||||
|
<SelectItem key={s} value={s}>
|
||||||
|
{scopeLabels[s]}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{errors.scope && <p className="text-destructive text-xs">{errors.scope}</p>}
|
||||||
|
</div>
|
||||||
|
</BentoCard>
|
||||||
|
|
||||||
|
{/* Permissions multi-select */}
|
||||||
|
<BentoCard span="full">
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label className="text-sm font-medium">{t("roles.fields.permissions", "Rugsatlar")}</Label>
|
||||||
|
{allPermissions.length === 0 ? (
|
||||||
|
<p className="text-muted-foreground text-sm">{t("common.loading", "Ýüklenýär...")}</p>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2">
|
||||||
|
{allPermissions.map((perm) => {
|
||||||
|
const checked = (form.permissions ?? []).includes(perm.code);
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
key={perm.code}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 rounded-lg border p-2.5 cursor-pointer transition-colors",
|
||||||
|
checked ? "border-primary bg-primary/5 text-primary" : "border-border hover:border-primary/50",
|
||||||
|
isPending && "opacity-60 pointer-events-none",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Checkbox
|
||||||
|
checked={checked}
|
||||||
|
onCheckedChange={() => togglePermission(perm.code)}
|
||||||
|
disabled={isPending}
|
||||||
|
id={`perm-${perm.code}`}
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium">{perm.code}</span>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
<FormActions
|
<FormActions
|
||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
|
|||||||
@@ -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 RolePayload, type UpdateRolePayload, type RolesListParams } from "../api/rolesApi";
|
||||||
|
|
||||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -46,6 +46,7 @@ export function useInfiniteRoles(search = "", enabled = true) {
|
|||||||
const count = lastPage?.count ?? 0;
|
const count = lastPage?.count ?? 0;
|
||||||
return loaded < count ? allPages.length + 1 : undefined;
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
},
|
},
|
||||||
|
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||||
enabled,
|
enabled,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -82,7 +83,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,16 @@
|
|||||||
import { z } from "zod";
|
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) {
|
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"], {
|
||||||
|
message: t("validation.required", "validation.required"),
|
||||||
|
}),
|
||||||
|
permissions: z.array(z.string()),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -14,13 +19,25 @@ 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 { SCOPE_OPTIONS };
|
||||||
|
|
||||||
|
export function buildCreatePayload(data: RoleFormData): RolePayload {
|
||||||
return {
|
return {
|
||||||
code: data.code,
|
code: data.code,
|
||||||
name: data.name,
|
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,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+34
-38
@@ -1,31 +1,29 @@
|
|||||||
import type { AuthUser, AuthUserPermission } from "@/app/store/authStore";
|
import type { AuthUser, AuthUserPermission } from "@/app/store/authStore";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Access model:
|
* Access model (new, post-API-v2):
|
||||||
* - "admin" guard has full access to everything regardless of its permission list.
|
* - isSuper roles (scope === 'all' with isSuper=true) have full access to everything.
|
||||||
* - "web" guard (public user role) can open the Orders section (loan / card / international payments).
|
* - "user" role code (web/public user, scope === 'own') can open the Orders section.
|
||||||
* - Any other guard (operator, ...) is limited to the permission codes it holds.
|
* - 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";
|
/** True when the user has a super role (full access). */
|
||||||
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;
|
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 {
|
export function isWebUser(user?: AuthUser | null): boolean {
|
||||||
if (!user?.role) return false;
|
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[] {
|
export function getPermissionCodes(user?: AuthUser | null): string[] {
|
||||||
if (isAdmin(user)) return [];
|
if (isAdmin(user)) return [];
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
@@ -37,9 +35,6 @@ export function getPermissionCodes(user?: AuthUser | null): string[] {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
for (const p of user?.permissions ?? []) push(p);
|
for (const p of user?.permissions ?? []) push(p);
|
||||||
for (const m of user?.modules ?? []) {
|
|
||||||
for (const p of m.permissions ?? []) push(p);
|
|
||||||
}
|
|
||||||
return codes;
|
return codes;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,15 +60,16 @@ export function hasAnyPermission(user: AuthUser | null | undefined, codes: reado
|
|||||||
export const PERM = {
|
export const PERM = {
|
||||||
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",
|
BACKUPS: "backups",
|
||||||
BACKUPS_VIEW: "backups.view",
|
ACTIVITY_LOGS: "activity-logs",
|
||||||
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). */
|
DASHBOARD: "dashboard",
|
||||||
|
/** Sentinel for pages that only the super-admin may access (no permission code exists). */
|
||||||
ADMIN_ONLY: "__admin_only__",
|
ADMIN_ONLY: "__admin_only__",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
@@ -104,15 +100,15 @@ const ROUTE_RULES: RouteRule[] = [
|
|||||||
["/sber-payments", [PERM.ADMIN_ONLY]],
|
["/sber-payments", [PERM.ADMIN_ONLY]],
|
||||||
["/online-payments-history", [PERM.ADMIN_ONLY]],
|
["/online-payments-history", [PERM.ADMIN_ONLY]],
|
||||||
// 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]],
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Match a path against the rule prefixes (exact or sub-path). */
|
/** 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])[] = [
|
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: super-admin → dashboard, web user → orders, else the first page they may open. */
|
||||||
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";
|
if (isWebUser(user)) return "/loan-orders";
|
||||||
|
|||||||
@@ -394,6 +394,8 @@
|
|||||||
"errors.pageNotFoundTitle": "Page not found",
|
"errors.pageNotFoundTitle": "Page not found",
|
||||||
"errors.pageNotFoundDescription": "The page you are looking for does not exist or has been moved.",
|
"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.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",
|
"Phone or username": "Phone or username",
|
||||||
"featureNotImplemented": "Not implemented",
|
"featureNotImplemented": "Not implemented",
|
||||||
"common.search": "Search",
|
"common.search": "Search",
|
||||||
|
|||||||
@@ -394,6 +394,8 @@
|
|||||||
"errors.pageNotFoundTitle": "Страница не найдена",
|
"errors.pageNotFoundTitle": "Страница не найдена",
|
||||||
"errors.pageNotFoundDescription": "Страница, которую вы ищете, не существует или была перемещена.",
|
"errors.pageNotFoundDescription": "Страница, которую вы ищете, не существует или была перемещена.",
|
||||||
"errors.forbidden": "У вас нет разрешения на выполнение этого действия.",
|
"errors.forbidden": "У вас нет разрешения на выполнение этого действия.",
|
||||||
|
"errors.fetchFailed": "Не удалось загрузить данные",
|
||||||
|
"errors.actionFailed": "Не удалось выполнить действие",
|
||||||
"Phone or username": "Телефон или имя пользователя",
|
"Phone or username": "Телефон или имя пользователя",
|
||||||
"featureNotImplemented": "Эта функция еще не реализована",
|
"featureNotImplemented": "Эта функция еще не реализована",
|
||||||
"common.search": "Поиск",
|
"common.search": "Поиск",
|
||||||
|
|||||||
@@ -394,6 +394,8 @@
|
|||||||
"errors.pageNotFoundTitle": "Sahypa tapylmady",
|
"errors.pageNotFoundTitle": "Sahypa tapylmady",
|
||||||
"errors.pageNotFoundDescription": "Gözleýän sahypaňyz ýok ýa-da başga ýere geçirilen bolup biler.",
|
"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.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",
|
"Phone or username": "Telefon ýada ulanyjy ady",
|
||||||
"featureNotImplemented": "Bu funksiýa entek durmuşa geçirilmedi",
|
"featureNotImplemented": "Bu funksiýa entek durmuşa geçirilmedi",
|
||||||
"common.search": "Gözlemek",
|
"common.search": "Gözlemek",
|
||||||
|
|||||||
@@ -1,28 +1,23 @@
|
|||||||
import { useState, useMemo } from "react";
|
import { useState, useMemo } 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 ──────────────────────────────────────────────────────────
|
// ─── 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() {
|
export default function PermissionsPage() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const columnMeta = useMemo(
|
const columnMeta = useMemo(
|
||||||
() => [
|
() => [
|
||||||
{ id: "id", label: t("common.id", "ID") },
|
|
||||||
{ id: "code", label: t("permissions.fields.code", "Kod") },
|
{ id: "code", label: t("permissions.fields.code", "Kod") },
|
||||||
{ id: "name", label: t("permissions.fields.name", "Ady") },
|
{ id: "name", label: t("permissions.fields.name", "Ady") },
|
||||||
{ id: "guardName", label: t("permissions.fields.guardName", "Guard name") },
|
|
||||||
],
|
],
|
||||||
[t],
|
[t],
|
||||||
);
|
);
|
||||||
@@ -33,59 +28,24 @@ export default function PermissionsPage() {
|
|||||||
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);
|
|
||||||
|
|
||||||
// ── Data ───────────────────────────────────────────────────────────────────
|
// ── Data ───────────────────────────────────────────────────────────────────
|
||||||
const { data, isLoading } = usePermissions({ search, page, limit: perPage });
|
const { data, isLoading } = usePermissions({ search, page, limit: perPage });
|
||||||
const deletePermission = useDeletePermission();
|
|
||||||
|
|
||||||
// ── Columns ────────────────────────────────────────────────────────────────
|
// ── Columns ────────────────────────────────────────────────────────────────
|
||||||
const columns: ColumnDef<Permission>[] = [
|
const columns: ColumnDef<Permission>[] = [
|
||||||
{
|
|
||||||
accessorKey: "id",
|
|
||||||
header: t("common.id", "ID"),
|
|
||||||
size: 70,
|
|
||||||
cell: ({ row }) => <span className="text-primary font-semibold">{row.original.id}</span>,
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
accessorKey: "code",
|
accessorKey: "code",
|
||||||
header: t("permissions.fields.code", "Kod"),
|
header: t("permissions.fields.code", "Kod"),
|
||||||
|
cell: ({ row }) => <span className="font-mono text-sm text-primary font-semibold">{row.original.code}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "name",
|
accessorKey: "name",
|
||||||
header: t("permissions.fields.name", "Ady"),
|
header: t("permissions.fields.name", "Ady"),
|
||||||
cell: ({ row }) => <span>{row.original.name ?? "—"}</span>,
|
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 ─────────────────────────────────────────────────────────────────
|
// ── Render ─────────────────────────────────────────────────────────────────
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -102,12 +62,8 @@ export default function PermissionsPage() {
|
|||||||
}}
|
}}
|
||||||
placeholder={t("permissions.searchPlaceholder", "Gözlemek...")}
|
placeholder={t("permissions.searchPlaceholder", "Gözlemek...")}
|
||||||
/>
|
/>
|
||||||
<CreateButton
|
|
||||||
label={t("permissions.actions.create", "Rugsat dörediň")}
|
|
||||||
onClick={() => navigate("/settings/users/permissions/create")}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
{/* Toolbar */}
|
{/* Table */}
|
||||||
<DataTable
|
<DataTable
|
||||||
columns={columns}
|
columns={columns}
|
||||||
data={data?.permissions ?? []}
|
data={data?.permissions ?? []}
|
||||||
@@ -116,8 +72,7 @@ export default function PermissionsPage() {
|
|||||||
onColumnVisibilityChange={setColumnVisibility}
|
onColumnVisibilityChange={setColumnVisibility}
|
||||||
columnOrder={columnOrder}
|
columnOrder={columnOrder}
|
||||||
onColumnOrderChange={setColumnOrder}
|
onColumnOrderChange={setColumnOrder}
|
||||||
enableRowSelection
|
getRowId={(row) => row.code}
|
||||||
getRowId={(row) => String(row.id)}
|
|
||||||
currentPage={page}
|
currentPage={page}
|
||||||
totalPages={Math.max(1, Math.ceil((data?.count ?? 0) / perPage))}
|
totalPages={Math.max(1, Math.ceil((data?.count ?? 0) / perPage))}
|
||||||
totalCount={data?.count}
|
totalCount={data?.count}
|
||||||
@@ -146,18 +101,6 @@ export default function PermissionsPage() {
|
|||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Delete confirmation dialog */}
|
|
||||||
<DeleteDialog
|
|
||||||
open={deleteId !== null}
|
|
||||||
onOpenChange={(o) => {
|
|
||||||
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}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,7 @@ import { TableActions } from "@/components/tableActions";
|
|||||||
import { DeleteDialog } from "@/components/deleteDialog";
|
import { DeleteDialog } from "@/components/deleteDialog";
|
||||||
import { useRoles, useDeleteRole } from "@/features/roles/hooks/useRoles";
|
import { useRoles, useDeleteRole } from "@/features/roles/hooks/useRoles";
|
||||||
import type { Role } from "@/features/roles/api/rolesApi";
|
import type { Role } from "@/features/roles/api/rolesApi";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
|
||||||
// ─── RolesPage ────────────────────────────────────────────────────────────────
|
// ─── RolesPage ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -22,7 +23,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", "Ulanyjylar") },
|
||||||
],
|
],
|
||||||
[t],
|
[t],
|
||||||
);
|
);
|
||||||
@@ -57,8 +59,24 @@ export default function RolesPage() {
|
|||||||
cell: ({ row }) => <span>{row.original.name ?? "—"}</span>,
|
cell: ({ row }) => <span>{row.original.name ?? "—"}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "guardName",
|
accessorKey: "scope",
|
||||||
header: t("roles.fields.guardName", "Guard name"),
|
header: t("roles.fields.scope", "Scope"),
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const scope = row.original.scope;
|
||||||
|
const scopeLabels: Record<string, string> = {
|
||||||
|
own: t("roles.scope.own", "Öz"),
|
||||||
|
branch: t("roles.scope.branch", "Şahamça"),
|
||||||
|
all: t("roles.scope.all", "Hemmesi"),
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Badge variant={scope === "all" ? "default" : scope === "branch" ? "secondary" : "outline"}>{scopeLabels[scope] ?? scope}</Badge>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "usersCount",
|
||||||
|
header: t("roles.fields.usersCount", "Ulanyjylar"),
|
||||||
|
cell: ({ row }) => <span>{row.original.usersCount ?? 0}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "actions",
|
id: "actions",
|
||||||
@@ -70,7 +88,8 @@ 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)}
|
// isSystem roles (superadmin, user) cannot be deleted — hide the delete button
|
||||||
|
onDelete={row.original.isSystem ? undefined : () => setDeleteId(row.original.id)}
|
||||||
isDeleting={deleteRole.isPending}
|
isDeleting={deleteRole.isPending}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useParams, useNavigate } from "react-router-dom";
|
import { useParams, useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Section, InfoRow, ViewActions } from "@/components/viewPageComponents";
|
import { Section, InfoRow, ViewActions } from "@/components/viewPageComponents";
|
||||||
import { useRole, useDeleteRole } from "@/features/roles/hooks/useRoles";
|
import { useRole, useDeleteRole } from "@/features/roles/hooks/useRoles";
|
||||||
|
|
||||||
@@ -26,7 +27,7 @@ export default function RoleViewPage() {
|
|||||||
<div>
|
<div>
|
||||||
<Skeleton className="h-8 w-72 mb-6" />
|
<Skeleton className="h-8 w-72 mb-6" />
|
||||||
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
|
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
|
||||||
{Array.from({ length: 4 }).map((_, i) => (
|
{Array.from({ length: 5 }).map((_, i) => (
|
||||||
<div
|
<div
|
||||||
key={i}
|
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"
|
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"
|
||||||
@@ -44,6 +45,12 @@ export default function RoleViewPage() {
|
|||||||
return <p className="text-destructive text-sm">{t("common.fetchError", "Maglumat ýüklenmedi.")}</p>;
|
return <p className="text-destructive text-sm">{t("common.fetchError", "Maglumat ýüklenmedi.")}</p>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const scopeLabels: Record<string, string> = {
|
||||||
|
own: t("roles.scope.own", "Öz ýazgylary"),
|
||||||
|
branch: t("roles.scope.branch", "Şahamça"),
|
||||||
|
all: t("roles.scope.all", "Hemmesi"),
|
||||||
|
};
|
||||||
|
|
||||||
// ── Render ─────────────────────────────────────────────────────────────────
|
// ── Render ─────────────────────────────────────────────────────────────────
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -55,7 +62,8 @@ 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}
|
// isSystem roles cannot be deleted — hide the button
|
||||||
|
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 +77,19 @@ 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={
|
||||||
|
<Badge variant={role.scope === "all" ? "default" : role.scope === "branch" ? "secondary" : "outline"}>
|
||||||
|
{scopeLabels[role.scope] ?? role.scope}
|
||||||
|
</Badge>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<InfoRow label={t("roles.fields.usersCount", "Ulanyjylar sany")} value={role.usersCount ?? 0} />
|
||||||
|
<InfoRow
|
||||||
|
label={t("roles.fields.permissions", "Rugsatlar")}
|
||||||
|
value={role.permissions?.length ? role.permissions.join(", ") : t("common.none", "—")}
|
||||||
|
/>
|
||||||
</Section>
|
</Section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in new issue
Block a user