for merger

This commit is contained in:
Jelaletdin12
2026-09-28 13:15:43 +05:00
parent 8dc61d7786
commit 9930a16f5c
19 changed files with 300 additions and 287 deletions

View File

@@ -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",
});
}

View File

@@ -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
{

View File

@@ -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;
}

View File

@@ -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<void> => {
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;
},
};

View File

@@ -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 {

View File

@@ -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<void> => {
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;
},
};

View File

@@ -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<PermissionsListResponse> => {
const { search, page, limit } = params;
const { data } = await apiClient.get<PermissionsListResponse>("/permissions", {
@@ -40,27 +31,4 @@ export const permissionsApi = {
});
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}`);
},
};

View File

@@ -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!"));
},
});
}

View File

@@ -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<Role> => {
const { data } = await apiClient.post<Role>("/roles", payload);
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);
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> => {
await apiClient.delete(`/roles/${id}`);
},

View File

@@ -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<string, string> = {
own: t("roles.scope.own", "Öz ýazgylary"),
branch: t("roles.scope.branch", "Şahamça"),
all: t("roles.scope.all", "Hemmesi"),
};
return (
<div className="flex flex-col gap-5">
<h1 className="text-xl font-semibold text-foreground">
{mode === "create" ? t("roles.createTitle", "Rol dörediň") : t("roles.editTitle", "Rol üýtgetmek")}
</h1>
<BentoGrid cols={2}>
{/* Code — only editable on create */}
<BentoCard>
<FormInput
type="text"
@@ -118,23 +145,13 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
onChange={setField("code")}
placeholder={t("roles.fields.code", "Kod")}
error={errors.code}
disabled={isPending}
disabled={isPending || mode === "edit"}
required
/>
</BentoCard>
{/* Name */}
<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
type="text"
label={t("roles.fields.name", "Ady")}
@@ -146,7 +163,71 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
required
/>
</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>
<FormActions
isPending={isPending}
onSubmit={handleSubmit}

View File

@@ -2,7 +2,7 @@ import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tansta
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
import { rolesApi, type RolePayload, type RolesListParams } from "../api/rolesApi";
import { rolesApi, type RolePayload, type UpdateRolePayload, type RolesListParams } from "../api/rolesApi";
// ─── Query keys ───────────────────────────────────────────────────────────────
@@ -46,6 +46,7 @@ export function useInfiniteRoles(search = "", enabled = true) {
const count = lastPage?.count ?? 0;
return loaded < count ? allPages.length + 1 : undefined;
},
staleTime: 5 * 60 * 1000, // 5 minutes
enabled,
});
}
@@ -82,7 +83,7 @@ export function useUpdateRole(id: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: RolePayload) => rolesApi.update(id, payload),
mutationFn: (payload: UpdateRolePayload) => rolesApi.update(id, payload),
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: roleKeys.all });
queryClient.invalidateQueries({ queryKey: roleKeys.detail(data.id) });

View File

@@ -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<ReturnType<typeof createRoleFormSchema>>;
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,
};
}

View File

@@ -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<string>();
@@ -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";

View File

@@ -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",

View File

@@ -394,6 +394,8 @@
"errors.pageNotFoundTitle": "Страница не найдена",
"errors.pageNotFoundDescription": "Страница, которую вы ищете, не существует или была перемещена.",
"errors.forbidden": "У вас нет разрешения на выполнение этого действия.",
"errors.fetchFailed": "Не удалось загрузить данные",
"errors.actionFailed": "Не удалось выполнить действие",
"Phone or username": "Телефон или имя пользователя",
"featureNotImplemented": "Эта функция еще не реализована",
"common.search": "Поиск",

View File

@@ -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",

View File

@@ -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<VisibilityState>({});
const [columnOrder, setColumnOrder] = useState<string[]>([]);
const [deleteId, setDeleteId] = useState<number | null>(null);
// ── Data ───────────────────────────────────────────────────────────────────
const { data, isLoading } = usePermissions({ search, page, limit: perPage });
const deletePermission = useDeletePermission();
// ── Columns ────────────────────────────────────────────────────────────────
const columns: ColumnDef<Permission>[] = [
{
accessorKey: "id",
header: t("common.id", "ID"),
size: 70,
cell: ({ row }) => <span className="text-primary font-semibold">{row.original.id}</span>,
},
{
accessorKey: "code",
header: t("permissions.fields.code", "Kod"),
cell: ({ row }) => <span className="font-mono text-sm text-primary font-semibold">{row.original.code}</span>,
},
{
accessorKey: "name",
header: t("permissions.fields.name", "Ady"),
cell: ({ row }) => <span>{row.original.name ?? "—"}</span>,
},
{
accessorKey: "guardName",
header: t("permissions.fields.guardName", "Guard name"),
},
{
id: "actions",
header: "",
size: 120,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
<TableActions
onView={() => navigate(`/settings/users/permissions/${row.original.id}`)}
onEdit={() => navigate(`/settings/users/permissions/${row.original.id}/edit`)}
onDelete={() => setDeleteId(row.original.id)}
isDeleting={deletePermission.isPending}
/>
),
},
];
// ── Handlers ───────────────────────────────────────────────────────────────
const handleConfirmDelete = () => {
if (deleteId === null) return;
deletePermission.mutate(deleteId, {
onSuccess: () => setDeleteId(null),
onError: () => setDeleteId(null),
});
};
// ── Render ─────────────────────────────────────────────────────────────────
return (
<div className="space-y-4">
@@ -102,12 +62,8 @@ export default function PermissionsPage() {
}}
placeholder={t("permissions.searchPlaceholder", "Gözlemek...")}
/>
<CreateButton
label={t("permissions.actions.create", "Rugsat dörediň")}
onClick={() => navigate("/settings/users/permissions/create")}
/>
</div>
{/* Toolbar */}
{/* Table */}
<DataTable
columns={columns}
data={data?.permissions ?? []}
@@ -116,8 +72,7 @@ export default function PermissionsPage() {
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => 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 */}
<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>
);
}

View File

@@ -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 }) => <span>{row.original.name ?? "—"}</span>,
},
{
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<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",
@@ -70,7 +88,8 @@ export default function RolesPage() {
<TableActions
onView={() => navigate(`/settings/users/roles/${row.original.id}`)}
onEdit={() => navigate(`/settings/users/roles/${row.original.id}/edit`)}
onDelete={() => setDeleteId(row.original.id)}
// isSystem roles (superadmin, user) cannot be deleted — hide the delete button
onDelete={row.original.isSystem ? undefined : () => setDeleteId(row.original.id)}
isDeleting={deleteRole.isPending}
/>
),

View File

@@ -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() {
<div>
<Skeleton className="h-8 w-72 mb-6" />
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
{Array.from({ length: 4 }).map((_, i) => (
{Array.from({ length: 5 }).map((_, i) => (
<div
key={i}
className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start sm:items-center py-3 px-4 gap-2 sm:gap-0"
@@ -44,6 +45,12 @@ export default function RoleViewPage() {
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 ─────────────────────────────────────────────────────────────────
return (
<div>
@@ -55,7 +62,8 @@ export default function RoleViewPage() {
<div className="flex items-center gap-2">
<ViewActions
editTo={`/settings/users/roles/${roleId}/edit`}
onDelete={handleDelete}
// isSystem roles cannot be deleted — hide the button
onDelete={role.isSystem ? undefined : handleDelete}
deleting={deleteRole.isPending}
deleteTitle={t("roles.deleteDialog.title", "Roly pozmak")}
deleteDescription={t("roles.deleteDialog.description", "Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")}
@@ -69,7 +77,19 @@ export default function RoleViewPage() {
<InfoRow label="ID" value={role.id} />
<InfoRow label={t("roles.fields.code", "Kod")} value={role.code} />
<InfoRow label={t("roles.fields.name", "Ady")} value={role.name} />
<InfoRow label={t("roles.fields.guardName", "Guard name")} value={role.guardName} />
<InfoRow
label={t("roles.fields.scope", "Scope")}
value={
<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>
</div>
);