added role func, fixed some ui
This commit is contained in:
@@ -1,32 +1,32 @@
|
||||
import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import i18next from 'i18next'
|
||||
import { isAxiosError } from 'axios'
|
||||
import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from "@tanstack/react-query";
|
||||
import type { ReactNode } from "react";
|
||||
import { toast } from "sonner";
|
||||
import i18next from "i18next";
|
||||
import { isAxiosError } from "axios";
|
||||
|
||||
function getErrorMessage(error: Error): string | undefined {
|
||||
if (isAxiosError(error)) return error.response?.data?.message
|
||||
return error.message
|
||||
if (isAxiosError(error)) return error.response?.data?.message;
|
||||
return error.message;
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
export const queryClient = new QueryClient({
|
||||
queryCache: new QueryCache({
|
||||
onError: (error, query) => {
|
||||
if (query.meta?.silent !== true) {
|
||||
const serverMessage = getErrorMessage(error)
|
||||
toast.error(serverMessage || i18next.t('errors.fetchFailed'), {
|
||||
id: 'global-query-error',
|
||||
})
|
||||
const serverMessage = getErrorMessage(error);
|
||||
toast.error(serverMessage || i18next.t("errors.fetchFailed"), {
|
||||
id: "global-query-error",
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
mutationCache: new MutationCache({
|
||||
onError: (error, _variables, _context, mutation) => {
|
||||
if (mutation.meta?.silent !== true) {
|
||||
const serverMessage = getErrorMessage(error)
|
||||
toast.error(serverMessage || i18next.t('errors.actionFailed'), {
|
||||
id: 'global-mutation-error',
|
||||
})
|
||||
const serverMessage = getErrorMessage(error);
|
||||
toast.error(serverMessage || i18next.t("errors.actionFailed"), {
|
||||
id: "global-mutation-error",
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
@@ -35,8 +35,8 @@ const queryClient = new QueryClient({
|
||||
staleTime: 1000 * 60 * 5,
|
||||
gcTime: 1000 * 60 * 10,
|
||||
retry: (failureCount, error) => {
|
||||
if (isAxiosError(error) && [401, 403, 404].includes(error.response?.status ?? 0)) return false
|
||||
return failureCount < 1
|
||||
if (isAxiosError(error) && [401, 403, 404].includes(error.response?.status ?? 0)) return false;
|
||||
return failureCount < 1;
|
||||
},
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
@@ -44,16 +44,12 @@ const queryClient = new QueryClient({
|
||||
retry: 0,
|
||||
},
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
interface QueryProviderProps {
|
||||
children: ReactNode
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function QueryProvider({ children }: QueryProviderProps) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,11 +3,14 @@ import { persist } from "zustand/middleware";
|
||||
import axios from "axios";
|
||||
import type { ApiSuccessResponse } from "@/lib/api/client";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
import { getDefaultHomePath } from "@/lib/auth/permissions";
|
||||
import { queryClient } from "@/app/providers/QueryProvider";
|
||||
|
||||
export interface AuthUserRole {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName?: string;
|
||||
}
|
||||
|
||||
export interface AuthUserBranch {
|
||||
@@ -20,6 +23,21 @@ 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[];
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
@@ -33,14 +51,14 @@ export interface AuthUser {
|
||||
avatar?: string;
|
||||
branches?: AuthUserBranch[];
|
||||
permissions?: AuthUserPermission[];
|
||||
modules?: AuthUserModule[];
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
/** Returns the role-appropriate landing page for the current user. */
|
||||
export function getHomePath(): string {
|
||||
const user = useAuthStore.getState().user;
|
||||
const isAdmin = user?.role?.code === "admin";
|
||||
return isAdmin ? "/dashboard" : "/loan-orders";
|
||||
return getDefaultHomePath(user);
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
@@ -73,7 +91,10 @@ export const useAuthStore = create<AuthState>()(
|
||||
|
||||
setUser: (user) => set({ user }),
|
||||
|
||||
clearAuth: () => set({ token: null, refreshTokenValue: null, user: null, isAuthenticated: false }),
|
||||
clearAuth: () => {
|
||||
set({ token: null, refreshTokenValue: null, user: null, isAuthenticated: false });
|
||||
queryClient.clear();
|
||||
},
|
||||
|
||||
logout: () => {
|
||||
get().clearAuth();
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState, useRef, useEffect } from "react";
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
|
||||
import { Check, ChevronsUpDown, Search, X, Eye, EyeOff, Upload, Hash } from "lucide-react";
|
||||
|
||||
import { cn, cleanPhoneNumber, formatFromApiDate } from "@/lib/utils";
|
||||
import { cn, cleanPhoneNumber } from "@/lib/utils";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -283,8 +283,9 @@ function DateInput({ value = "", onChange, error, disabled, required, label, cla
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
// value backend'den 'yyyy-MM-dd' veya 'yyyy-MM-ddTHH:mm:ssZ' gelebilir
|
||||
const dateStr = formatFromApiDate(value);
|
||||
const parsed = dateStr ? parse(dateStr, "yyyy-MM-dd", new Date()) : undefined;
|
||||
// Sadece ilk 10 karakteri (yyyy-MM-dd) alarak parse et
|
||||
const rawDate = value ? value.trim().slice(0, 10) : "";
|
||||
const parsed = rawDate ? parse(rawDate, "yyyy-MM-dd", new Date()) : undefined;
|
||||
const selected = parsed && isValid(parsed) ? parsed : undefined;
|
||||
|
||||
const handleSelect = (day: Date | undefined) => {
|
||||
|
||||
@@ -27,7 +27,7 @@ export function useUsers(params: UsersListParams = {}) {
|
||||
|
||||
const USER_PAGE_SIZE = 25;
|
||||
|
||||
export function useInfiniteUsers(search = "") {
|
||||
export function useInfiniteUsers(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
@@ -40,6 +40,7 @@ export function useInfiniteUsers(search = "") {
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -16,10 +16,8 @@ export function useLogin() {
|
||||
onSuccess: async (data) => {
|
||||
setAuth(data.accessToken, data.refreshToken, data.user ?? null);
|
||||
|
||||
if (!data.user) {
|
||||
const profile = await getProfileApi();
|
||||
setUser(profile);
|
||||
}
|
||||
const profile = await getProfileApi();
|
||||
setUser(profile);
|
||||
|
||||
navigate(getHomePath(), { replace: true });
|
||||
},
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useCreateCardBalance, useUpdateCardBalance } from "@/features/cardBalan
|
||||
import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, mapInitial, buildPayload } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||
import type { CardBalanceFormData } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
import { MONTH_OPTIONS, CARD_YEAR_OPTIONS } from "@/constants";
|
||||
|
||||
interface CardBalanceFormProps {
|
||||
@@ -54,12 +55,17 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const userQuery = useInfiniteUsers(userSearch);
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
const userQuery = useInfiniteUsers(userSearch, !userLocked);
|
||||
|
||||
const userOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (userQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) }));
|
||||
.map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) }))
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName });
|
||||
}
|
||||
if (initialData?.createdBy?.id && !opts.some((o) => o.value === String(initialData.createdBy.id))) {
|
||||
opts.unshift({
|
||||
value: String(initialData.createdBy.id),
|
||||
@@ -67,7 +73,7 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [userQuery, initialData]);
|
||||
}, [userQuery, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
@@ -77,7 +83,9 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardBalanceFormData>({
|
||||
defaultValues: initialData ? mapInitial(initialData) : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData
|
||||
? { ...mapInitial(initialData), ...(userLocked ? { createdBy: selfUserId } : {}) }
|
||||
: { ...DEFAULT_FORM_VALUES, createdBy: selfUserId },
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -214,6 +222,7 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||
onChange={(v) => set("createdBy", v)}
|
||||
options={userOptions}
|
||||
placeholder={t("Select user", "Ulanyjyny saýlaň")}
|
||||
disabled={userLocked}
|
||||
loading={userQuery.isLoading}
|
||||
isLoadingMore={userQuery.isFetchingNextPage}
|
||||
hasNextPage={!!userQuery.hasNextPage}
|
||||
|
||||
@@ -22,6 +22,7 @@ import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
||||
import { DocumentUpload } from "@/components/documentUpload";
|
||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
import { formatFromApiPhone } from "@/lib/utils";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
@@ -96,6 +97,9 @@ interface StepContentProps {
|
||||
cardTypeOptions: SelectOption[];
|
||||
branchOptions: SelectOption[];
|
||||
districtOptions: SelectOption[];
|
||||
userLocked: boolean;
|
||||
selfUserId: string;
|
||||
userName: string;
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
@@ -194,9 +198,18 @@ function StepCard({ form, errors, set, t, cardTypeOptions, branchOptions, distri
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t, initialData }: StepContentProps & { initialData?: CardPinOrder }) {
|
||||
function StepPersonal({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
initialData,
|
||||
userLocked,
|
||||
selfUserId,
|
||||
userName,
|
||||
}: StepContentProps & { initialData?: CardPinOrder }) {
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
const clientsQuery = useInfiniteClients(clientSearch);
|
||||
const clientsQuery = useInfiniteClients(clientSearch, !userLocked);
|
||||
|
||||
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
||||
@@ -204,13 +217,18 @@ function StepPersonal({ form, errors, set, t, initialData }: StepContentProps &
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
}))
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName });
|
||||
}
|
||||
|
||||
if (initialData?.user?.id && !opts.some((o) => o.value === String(initialData.user!.id))) {
|
||||
opts.unshift({ value: String(initialData.user!.id), label: initialData.user!.name || String(initialData.user!.id) });
|
||||
}
|
||||
return opts;
|
||||
}, [clientsQuery.data, initialData]);
|
||||
}, [clientsQuery.data, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -268,6 +286,7 @@ function StepPersonal({ form, errors, set, t, initialData }: StepContentProps &
|
||||
options={clientOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.userId}
|
||||
disabled={userLocked}
|
||||
loading={clientsQuery.isLoading}
|
||||
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||
hasNextPage={!!clientsQuery.hasNextPage}
|
||||
@@ -363,6 +382,8 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
|
||||
const createMutation = useCreateCardPin();
|
||||
const updateMutation = useUpdateCardPin(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
@@ -406,7 +427,9 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardPinFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData), ...(userLocked ? { userId: selfUserId } : {}) }
|
||||
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -447,8 +470,8 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(
|
||||
() => ({ form, errors, set, t, cardTypeOptions, branchOptions, districtOptions }),
|
||||
[form, errors, set, t, cardTypeOptions, branchOptions, districtOptions],
|
||||
() => ({ form, errors, set, t, cardTypeOptions, branchOptions, districtOptions, userLocked, selfUserId, userName }),
|
||||
[form, errors, set, t, cardTypeOptions, branchOptions, districtOptions, userLocked, selfUserId, userName],
|
||||
);
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -9,6 +9,7 @@ import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infinite
|
||||
import type { Card } from "../api/cardTransactionsApi";
|
||||
import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
import type { LocalizedTitle } from "@/features/cardTypes/api/cardTypesApi";
|
||||
import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema";
|
||||
@@ -41,8 +42,10 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
const clientsQuery = useInfiniteClients(clientSearch);
|
||||
const clientsQuery = useInfiniteClients(clientSearch, !userLocked);
|
||||
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
||||
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedTitle;
|
||||
@@ -53,13 +56,18 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
}))
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName });
|
||||
}
|
||||
|
||||
if (initialData?.user?.id && !opts.some((o) => o.value === String(initialData.user!.id))) {
|
||||
opts.unshift({ value: String(initialData.user!.id), label: initialData.user!.name || String(initialData.user!.id) });
|
||||
}
|
||||
return opts;
|
||||
}, [clientsQuery.data, initialData]);
|
||||
}, [clientsQuery.data, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
const cardTypeOptions = useMemo(() => {
|
||||
const opts = (cardTypesData?.paymentCards ?? []).map((ct) => ({
|
||||
@@ -89,9 +97,9 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
type: initialData.type,
|
||||
month: initialData.month,
|
||||
year: initialData.year,
|
||||
userId: String(initialData.user?.id ?? ""),
|
||||
userId: userLocked ? selfUserId : String(initialData.user?.id ?? ""),
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -187,6 +195,7 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
options={clientOptions}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.userId)}
|
||||
disabled={userLocked}
|
||||
loading={clientsQuery.isLoading}
|
||||
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||
hasNextPage={!!clientsQuery.hasNextPage}
|
||||
|
||||
@@ -37,7 +37,7 @@ const CLIENT_PAGE_SIZE = 25;
|
||||
* Infinite-scroll client list for searchable selects.
|
||||
* Backed by `clientsApi.getClients` (GET /users/clients).
|
||||
*/
|
||||
export function useInfiniteClients(search = "") {
|
||||
export function useInfiniteClients(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
@@ -52,6 +52,7 @@ export function useInfiniteClients(search = "") {
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ import { useInfiniteBranches, useInfiniteProvinces } from "@/features/branches/h
|
||||
import { useInfiniteLoanTypes } from "@/features/loanTypes/hooks/useLoanTypes";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
import { useGetRequiredDocuments } from "@/features/requiredDocuments/hooks/useRequiredDocuments";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
|
||||
import {
|
||||
PASSPORT_SERIES_OPTIONS,
|
||||
@@ -38,7 +39,7 @@ import {
|
||||
MONTH_OPTIONS,
|
||||
YEAR_OPTIONS,
|
||||
} from "@/constants";
|
||||
import { formatFromApiDate, formatFromApiPhone } from "@/lib/utils";
|
||||
import { formatFromApiDateInput, formatFromApiPhone } from "@/lib/utils";
|
||||
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -311,11 +312,20 @@ function StepLocation({ form, errors, set, t, initialData }: StepContentProps &
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrderMobile }) {
|
||||
function StepPersonal({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
initialData,
|
||||
userLocked,
|
||||
selfUserId,
|
||||
userName,
|
||||
}: StepContentProps & { initialData?: LoanOrderMobile; userLocked?: boolean; selfUserId?: string; userName?: string }) {
|
||||
const { data: requiredDocsData } = useGetRequiredDocuments({ page: 1, limit: 100 });
|
||||
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
const clientsQuery = useInfiniteClients(clientSearch);
|
||||
const clientsQuery = useInfiniteClients(clientSearch, !userLocked);
|
||||
|
||||
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
||||
@@ -323,7 +333,12 @@ function StepPersonal({ form, errors, set, t, initialData }: StepContentProps &
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
}))
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName || selfUserId });
|
||||
}
|
||||
|
||||
if (initialData?.createdById && !opts.some((o) => o.value === String(initialData.createdById))) {
|
||||
opts.unshift({
|
||||
@@ -332,7 +347,7 @@ function StepPersonal({ form, errors, set, t, initialData }: StepContentProps &
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [clientsQuery.data, initialData]);
|
||||
}, [clientsQuery.data, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
const loanHistoryOptions = useMemo<SelectOption[]>(
|
||||
() =>
|
||||
@@ -361,6 +376,7 @@ function StepPersonal({ form, errors, set, t, initialData }: StepContentProps &
|
||||
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||
searchValue={clientSearch}
|
||||
onSearchChange={setClientSearch}
|
||||
disabled={userLocked}
|
||||
/>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<FormInput
|
||||
@@ -1016,6 +1032,8 @@ export function LoanOrderMobileForm({ initialData, mode }: LoanOrderMobileFormPr
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set([0])));
|
||||
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
|
||||
const createMutation = useCreateLoanOrderMobile();
|
||||
const updateMutation = useUpdateLoanOrderMobile();
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
@@ -1028,7 +1046,9 @@ export function LoanOrderMobileForm({ initialData, mode }: LoanOrderMobileFormPr
|
||||
formState: { errors: rawErrors },
|
||||
getValues,
|
||||
} = useForm<LoanOrderMobileFormData>({
|
||||
defaultValues: initialData ? mapInitial(initialData) : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData
|
||||
? { ...mapInitial(initialData), ...(userLocked ? { userId: selfUserId } : {}) }
|
||||
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -1161,7 +1181,9 @@ export function LoanOrderMobileForm({ initialData, mode }: LoanOrderMobileFormPr
|
||||
{currentStep === 0 && <StepStatus {...stepProps} />}
|
||||
{currentStep === 1 && <StepLoan {...stepProps} initialData={initialData} />}
|
||||
{currentStep === 2 && <StepLocation {...stepProps} initialData={initialData} />}
|
||||
{currentStep === 3 && <StepPersonal {...stepProps} initialData={initialData} />}
|
||||
{currentStep === 3 && (
|
||||
<StepPersonal {...stepProps} initialData={initialData} userLocked={userLocked} selfUserId={selfUserId} userName={userName} />
|
||||
)}
|
||||
{currentStep === 4 && <StepCard {...stepProps} />}
|
||||
{currentStep === 5 && <StepPassport {...stepProps} mode={mode} />}
|
||||
{currentStep === 6 && <StepContact {...stepProps} />}
|
||||
@@ -1199,12 +1221,12 @@ function mapInitial(order: LoanOrderMobile): Partial<LoanOrderMobileFormData> {
|
||||
customerPatronicName: order.customerPatronicName ?? "",
|
||||
education: order.education ?? "",
|
||||
marriageStatus: order.marriageStatus ?? "",
|
||||
bornAt: formatFromApiDate(order.bornAt),
|
||||
bornAt: formatFromApiDateInput(order.bornAt),
|
||||
passportAddress: order.passportAddress ?? order.residence ?? "",
|
||||
realAddress: order.realAddress ?? order.currentResidence ?? "",
|
||||
passportSerie: order.passportSerie ?? "",
|
||||
passportId: order.passportId ?? "",
|
||||
passportGivenAt: formatFromApiDate(order.passportGivenAt),
|
||||
passportGivenAt: formatFromApiDateInput(order.passportGivenAt),
|
||||
passportGivenBy: order.passportGivenBy ?? "",
|
||||
passportOne: order.passportPage1Url ?? "",
|
||||
passportTwo: order.passportPage23Url ?? "",
|
||||
@@ -1221,7 +1243,7 @@ function mapInitial(order: LoanOrderMobile): Partial<LoanOrderMobileFormData> {
|
||||
workProvinceId: order.workCityId != null ? String(order.workCityId) : "",
|
||||
workPosition: order.workPosition ?? "",
|
||||
workSalary: order.workSalary != null ? String(order.workSalary) : "",
|
||||
workStartedAt: formatFromApiDate(order.workStartedAt),
|
||||
workStartedAt: formatFromApiDateInput(order.workStartedAt),
|
||||
notes: order.notes ?? order.note ?? "",
|
||||
loanAmount: order.loanAmount != null ? String(order.loanAmount) : "",
|
||||
loanOrderRequiredDocId: order.loanOrderRequiredDocId != null ? String(order.loanOrderRequiredDocId) : (order.loanHistory ?? ""),
|
||||
|
||||
@@ -21,7 +21,7 @@ import { useInfiniteLoanTypes } from "@/features/loanTypes/hooks/useLoanTypes";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
import { formatFromApiDate, formatFromApiPhone } from "@/lib/utils";
|
||||
import { formatFromApiDateInput, formatFromApiPhone } from "@/lib/utils";
|
||||
import {
|
||||
PASSPORT_SERIES_OPTIONS,
|
||||
getStatusOptions,
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
} from "@/constants";
|
||||
import { useGetRequiredDocuments } from "@/features/requiredDocuments/hooks/useRequiredDocuments";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
|
||||
// ─── Static options ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -378,9 +379,18 @@ function StepLocation({ form, errors, set, t, initialData }: StepContentProps &
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrder }) {
|
||||
function StepPersonal({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
initialData,
|
||||
userLocked,
|
||||
selfUserId,
|
||||
userName,
|
||||
}: StepContentProps & { initialData?: LoanOrder; userLocked?: boolean; selfUserId?: string; userName?: string }) {
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
const clientsQuery = useInfiniteClients(clientSearch);
|
||||
const clientsQuery = useInfiniteClients(clientSearch, !userLocked);
|
||||
|
||||
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
||||
@@ -388,7 +398,12 @@ function StepPersonal({ form, errors, set, t, initialData }: StepContentProps &
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
}))
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName || selfUserId });
|
||||
}
|
||||
|
||||
if (initialData?.createdById && !opts.some((o) => o.value === String(initialData.createdById))) {
|
||||
opts.unshift({
|
||||
@@ -397,7 +412,7 @@ function StepPersonal({ form, errors, set, t, initialData }: StepContentProps &
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [clientsQuery.data, initialData]);
|
||||
}, [clientsQuery.data, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -417,6 +432,7 @@ function StepPersonal({ form, errors, set, t, initialData }: StepContentProps &
|
||||
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||
searchValue={clientSearch}
|
||||
onSearchChange={setClientSearch}
|
||||
disabled={userLocked}
|
||||
/>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<FormInput
|
||||
@@ -1075,6 +1091,8 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
|
||||
const updateMutation = useUpdateLoanOrder();
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -1083,7 +1101,9 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<LoanOrderFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData), ...(userLocked ? { userId: selfUserId } : {}) }
|
||||
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -1233,7 +1253,9 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
|
||||
{currentStep === 0 && <StepStatus {...stepProps} />}
|
||||
{currentStep === 1 && <StepLoan {...stepProps} initialData={initialData} />}
|
||||
{currentStep === 2 && <StepLocation {...stepProps} initialData={initialData} />}
|
||||
{currentStep === 3 && <StepPersonal {...stepProps} initialData={initialData} />}
|
||||
{currentStep === 3 && (
|
||||
<StepPersonal {...stepProps} initialData={initialData} userLocked={userLocked} selfUserId={selfUserId} userName={userName} />
|
||||
)}
|
||||
{currentStep === 4 && <StepCard {...stepProps} />}
|
||||
{currentStep === 5 && <StepPassport {...stepProps} mode={mode} />}
|
||||
{currentStep === 6 && <StepContact {...stepProps} />}
|
||||
@@ -1285,7 +1307,7 @@ function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
|
||||
customerPatronicName: order.customerPatronicName ?? order.patronicName ?? "",
|
||||
education: order.education ?? "",
|
||||
marriageStatus: order.marriageStatus ?? "",
|
||||
bornAt: formatFromApiDate(order.bornAt ?? order.dateOfBirth),
|
||||
bornAt: formatFromApiDateInput(order.bornAt ?? order.dateOfBirth),
|
||||
bornPlace: order.bornPlace ?? "",
|
||||
passportAddress: order.passportAddress ?? order.residence ?? "",
|
||||
realAddress: order.realAddress ?? order.currentResidence ?? "",
|
||||
@@ -1295,7 +1317,7 @@ function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
|
||||
cardYear: order.cardYear ?? order.cardExpYear ?? "",
|
||||
passportSerie: order.passportSerie ?? "",
|
||||
passportId: order.passportId ?? order.passportNumber ?? "",
|
||||
passportGivenAt: formatFromApiDate(order.passportGivenAt ?? order.passportDateOfIssue),
|
||||
passportGivenAt: formatFromApiDateInput(order.passportGivenAt ?? order.passportDateOfIssue),
|
||||
passportGivenBy: order.passportGivenBy ?? "",
|
||||
passportOne: order.passportOne ?? order.passportPage1Url ?? "",
|
||||
passportTwo: order.passportTwo ?? order.passportPage23Url ?? "",
|
||||
@@ -1311,7 +1333,7 @@ function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
|
||||
workProvinceId: order.workProvinceId != null ? String(order.workProvinceId) : order.workCityId != null ? String(order.workCityId) : "",
|
||||
workPosition: order.workPosition ?? order.position ?? "",
|
||||
workSalary: order.workSalary != null ? String(order.workSalary) : order.salary != null ? String(order.salary) : "",
|
||||
workStartedAt: formatFromApiDate(order.workStartedAt),
|
||||
workStartedAt: formatFromApiDateInput(order.workStartedAt),
|
||||
guarantorName: order.guarantorName ?? order.guarantor1Name ?? "",
|
||||
guarantorSurname: order.guarantorSurname ?? order.guarantor1Surname ?? "",
|
||||
guarantorPatronicName: order.guarantorPatronicName ?? order.guarantor1Patronic ?? "",
|
||||
|
||||
@@ -16,6 +16,7 @@ import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { PASSPORT_SERIES_OPTIONS, getStatusOptions, getRegionOptions, LOAN_PAID_OFF_REGION_CODES } from "@/constants";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
import { useCreateLoanPaidOffLetter, useUpdateLoanPaidOffLetter } from "../hooks/useLoanPaidOffLetters";
|
||||
@@ -245,11 +246,13 @@ function StepLocation({
|
||||
statusOptions,
|
||||
branchSelectProps,
|
||||
userSelectProps,
|
||||
userLocked,
|
||||
}: StepContentProps & {
|
||||
regionOptions: SelectOption[];
|
||||
statusOptions: SelectOption[];
|
||||
branchSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder">;
|
||||
userSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder">;
|
||||
userLocked?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
@@ -279,6 +282,7 @@ function StepLocation({
|
||||
onChange={set("userId")}
|
||||
error={errors.userId}
|
||||
placeholder={t("loanPaidOffLetters.placeholders.user", "Ulanyjy saýlaň")}
|
||||
disabled={userLocked}
|
||||
{...userSelectProps}
|
||||
/>
|
||||
<FormInput
|
||||
@@ -332,6 +336,8 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo
|
||||
const updateMutation = useUpdateLoanPaidOffLetter(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>([0])));
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(() => new Set());
|
||||
@@ -370,7 +376,7 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo
|
||||
|
||||
// ── User infinite-scroll select ──
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const usersQuery = useInfiniteUsers(userSearch);
|
||||
const usersQuery = useInfiniteUsers(userSearch, !userLocked);
|
||||
|
||||
const userSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (usersQuery.data?.pages ?? [])
|
||||
@@ -381,7 +387,12 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo
|
||||
value: String(u.id),
|
||||
label: `${displayName}${u.phone ? ` (${u.phone})` : ""}`,
|
||||
};
|
||||
});
|
||||
})
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName });
|
||||
}
|
||||
|
||||
if (initialData?.user?.id) {
|
||||
const uId = String(initialData.user.id);
|
||||
@@ -400,7 +411,7 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo
|
||||
searchValue: userSearch,
|
||||
onSearchChange: setUserSearch,
|
||||
};
|
||||
}, [usersQuery, userSearch, initialData]);
|
||||
}, [usersQuery, userSearch, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
@@ -410,7 +421,9 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo
|
||||
setError,
|
||||
getValues,
|
||||
} = useForm<LoanPaidOffLetterFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData), ...(userLocked ? { userId: selfUserId } : {}) }
|
||||
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -562,6 +575,7 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo
|
||||
statusOptions={statusOptions}
|
||||
branchSelectProps={branchSelectProps}
|
||||
userSelectProps={userSelectProps}
|
||||
userLocked={userLocked}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
import { formatToApiDate, formatFromApiDate, formatToApiPhone, formatFromApiPhone } from "@/lib/utils";
|
||||
import { formatToApiDate, formatFromApiDateInput, formatToApiPhone, formatFromApiPhone } from "@/lib/utils";
|
||||
import type { LoanPaidOffLetter, LoanPaidOffLetterPayload } from "../api/loanPaidOffLettersApi";
|
||||
|
||||
export function createLoanPaidOffLetterFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
@@ -143,7 +143,7 @@ export function mapInitial(data: LoanPaidOffLetter): LoanPaidOffLetterFormData {
|
||||
customerName: data.customerName ?? "",
|
||||
customerSurname: data.customerSurname ?? "",
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
bornAt: formatFromApiDate(data.bornAt),
|
||||
bornAt: formatFromApiDateInput(data.bornAt),
|
||||
phone: formatFromApiPhone(data.phone),
|
||||
passportSerie: data.passportSerie ?? "",
|
||||
passportId: data.passportId ?? "",
|
||||
@@ -153,7 +153,7 @@ export function mapInitial(data: LoanPaidOffLetter): LoanPaidOffLetterFormData {
|
||||
status: data.status ?? "pending",
|
||||
notes: data.notes ?? "",
|
||||
loanContractNumber: data.loanContractNumber ?? "",
|
||||
loanContractDate: formatFromApiDate(data.loanContractDate),
|
||||
loanContractDate: formatFromApiDateInput(data.loanContractDate),
|
||||
loanAmount: data.loanAmount ?? "",
|
||||
loanReason: data.loanReason ?? "",
|
||||
uniqueId: data.uniqueId ?? "",
|
||||
|
||||
@@ -11,6 +11,7 @@ import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } f
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { PASSPORT_SERIES_OPTIONS } from "@/constants/passportSeries";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
|
||||
import { useCreateLoanRemaining, useUpdateLoanRemaining } from "../hooks/useLoanRemaining";
|
||||
import type { LoanRemaining } from "../api/loanRemainingApi";
|
||||
@@ -30,9 +31,11 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
|
||||
// ── Infinite Users Searchable Select ──
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const usersQuery = useInfiniteUsers(userSearch);
|
||||
const usersQuery = useInfiniteUsers(userSearch, !userLocked);
|
||||
|
||||
const userSelectProps: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (usersQuery.data?.pages ?? [])
|
||||
@@ -43,7 +46,12 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
value: String(u.id),
|
||||
label: `${displayName}${u.phone ? ` (${u.phone})` : ""}`,
|
||||
};
|
||||
});
|
||||
})
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName });
|
||||
}
|
||||
|
||||
const effectiveUserId = initialData?.user?.id ?? initialData?.userId;
|
||||
if (effectiveUserId) {
|
||||
@@ -65,7 +73,7 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
searchValue: userSearch,
|
||||
onSearchChange: setUserSearch,
|
||||
};
|
||||
}, [usersQuery, userSearch, initialData]);
|
||||
}, [usersQuery, userSearch, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
const {
|
||||
handleSubmit,
|
||||
@@ -75,13 +83,13 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
formState: { errors },
|
||||
} = useForm<LoanRemainingFormData>({
|
||||
resolver: zodResolver(loanRemainingFormSchema),
|
||||
defaultValues: DEFAULT_FORM_VALUES,
|
||||
defaultValues: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||
mode: "onSubmit",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === "edit" && initialData) {
|
||||
const uId = initialData.user?.id ?? initialData.userId;
|
||||
const uId = userLocked ? selfUserId : (initialData.user?.id ?? initialData.userId);
|
||||
reset({
|
||||
passportSerie: initialData.passportSerie,
|
||||
passportId: initialData.passportId,
|
||||
@@ -89,7 +97,7 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
userId: uId != null ? String(uId) : "",
|
||||
});
|
||||
}
|
||||
}, [mode, initialData, reset]);
|
||||
}, [mode, initialData, reset, userLocked, selfUserId]);
|
||||
|
||||
const onSubmit = (data: LoanRemainingFormData) => {
|
||||
const payload = buildPayload(data);
|
||||
@@ -165,7 +173,7 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
onChange={(v) => setValue("userId", v, { shouldValidate: true })}
|
||||
placeholder={t("loanRemaining.placeholders.userId", "Ulanyjy saýlaň")}
|
||||
error={errMsg(errors.userId?.message)}
|
||||
disabled={isPending}
|
||||
disabled={isPending || userLocked}
|
||||
{...userSelectProps}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -22,6 +22,7 @@ import { useCardReasons } from "@/features/cardReasons/hooks/useCardReasons";
|
||||
import { useBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
@@ -107,6 +108,9 @@ interface StepContentProps {
|
||||
branchOptions: SelectOption[];
|
||||
districtOptions: SelectOption[];
|
||||
mode: "create" | "edit";
|
||||
userLocked: boolean;
|
||||
selfUserId: string;
|
||||
userName: string;
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
@@ -419,9 +423,18 @@ function StepPassport({ form, errors, set, t, mode }: StepContentProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function StepContact({ form, errors, set, t, initialData }: StepContentProps & { initialData?: CardOrder }) {
|
||||
function StepContact({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
initialData,
|
||||
userLocked,
|
||||
selfUserId,
|
||||
userName,
|
||||
}: StepContentProps & { initialData?: CardOrder }) {
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const usersQuery = useInfiniteClients(userSearch);
|
||||
const usersQuery = useInfiniteClients(userSearch, !userLocked);
|
||||
|
||||
const userOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (usersQuery.data?.pages ?? [])
|
||||
@@ -429,7 +442,12 @@ function StepContact({ form, errors, set, t, initialData }: StepContentProps & {
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
}))
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName });
|
||||
}
|
||||
|
||||
if (initialData?.user?.id && !opts.some((o) => o.value === String(initialData.user!.id))) {
|
||||
opts.unshift({
|
||||
@@ -440,7 +458,7 @@ function StepContact({ form, errors, set, t, initialData }: StepContentProps & {
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [usersQuery.data, initialData]);
|
||||
}, [usersQuery.data, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -475,6 +493,7 @@ function StepContact({ form, errors, set, t, initialData }: StepContentProps & {
|
||||
options={userOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.userId}
|
||||
disabled={userLocked}
|
||||
loading={usersQuery.isLoading}
|
||||
isLoadingMore={usersQuery.isFetchingNextPage}
|
||||
hasNextPage={!!usersQuery.hasNextPage}
|
||||
@@ -496,6 +515,8 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
|
||||
const createMutation = useCreateCard();
|
||||
const updateMutation = useUpdateCard(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
@@ -549,7 +570,9 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<OrderNewCardFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData), ...(userLocked ? { userId: selfUserId } : {}) }
|
||||
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -593,8 +616,21 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(
|
||||
() => ({ form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions, mode }),
|
||||
[form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions, mode],
|
||||
() => ({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
cardTypeOptions,
|
||||
cardStateOptions,
|
||||
branchOptions,
|
||||
districtOptions,
|
||||
mode,
|
||||
userLocked,
|
||||
selfUserId,
|
||||
userName,
|
||||
}),
|
||||
[form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions, mode, userLocked, selfUserId, userName],
|
||||
);
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||
|
||||
24
src/features/shared/hooks/useWebSelfLock.ts
Normal file
24
src/features/shared/hooks/useWebSelfLock.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { useMemo } from "react";
|
||||
import { useAuthStore } from "@/app/store/authStore";
|
||||
import { isWebUser } from "@/lib/auth/permissions";
|
||||
import type { InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
|
||||
/**
|
||||
* When the current user belongs to the "web" guard ("user" role) and is creating
|
||||
* a record, the client / "created by" field must be locked to the user itself:
|
||||
* it is pre-filled with the current user's id and no other users are shown.
|
||||
* Admin / operator users keep the ability to pick another user.
|
||||
*/
|
||||
export function useWebSelfLock(active: boolean) {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
|
||||
return useMemo(() => {
|
||||
const locked = active && isWebUser(user);
|
||||
const userId = locked && user?.id != null ? String(user.id) : "";
|
||||
const userName = [user?.firstName, user?.lastName].filter(Boolean).join(" ") || user?.name || user?.email || userId;
|
||||
|
||||
const selfOptions: InfiniteSelectOption[] = locked && user?.id != null ? [{ value: String(user.id), label: userName }] : [];
|
||||
|
||||
return { locked, userId, userName, selfOptions };
|
||||
}, [active, user]);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/visa
|
||||
import type { IntlPaymentFormData } from "../schemas/visaMasterPayment.schema";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
import { PASSPORT_SERIES_OPTIONS, getStatusOptions, getRegionOptions, REGION_CODES, REGION_LABELS } from "@/constants";
|
||||
|
||||
@@ -148,11 +149,14 @@ interface StepContentProps {
|
||||
t: TFunction;
|
||||
mode: "create" | "edit";
|
||||
initialData?: IntlPaymentItem;
|
||||
userLocked: boolean;
|
||||
selfUserId: string;
|
||||
userName: string;
|
||||
}
|
||||
|
||||
function StepGeneral({ form, errors, set, t, initialData }: StepContentProps) {
|
||||
function StepGeneral({ form, errors, set, t, initialData, userLocked, selfUserId, userName }: StepContentProps) {
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
const clientQuery = useInfiniteClients(clientSearch);
|
||||
const clientQuery = useInfiniteClients(clientSearch, !userLocked);
|
||||
|
||||
const statusOptions = useMemo(() => getStatusOptions(t, "intlPayment.status"), [t]);
|
||||
|
||||
@@ -162,13 +166,18 @@ function StepGeneral({ form, errors, set, t, initialData }: StepContentProps) {
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || u.username || String(u.id),
|
||||
}));
|
||||
}))
|
||||
.filter((o) => !userLocked || o.value === selfUserId);
|
||||
|
||||
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||
opts.unshift({ value: selfUserId, label: userName });
|
||||
}
|
||||
|
||||
if (initialData?.client_id && !opts.some((o) => o.value === String(initialData.client_id))) {
|
||||
opts.unshift({ value: String(initialData.client_id), label: initialData.client_label || String(initialData.client_id) });
|
||||
}
|
||||
return opts;
|
||||
}, [clientQuery.data, initialData]);
|
||||
}, [clientQuery.data, initialData, userLocked, selfUserId, userName]);
|
||||
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
@@ -181,6 +190,7 @@ function StepGeneral({ form, errors, set, t, initialData }: StepContentProps) {
|
||||
options={clientOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.client_id}
|
||||
disabled={userLocked}
|
||||
loading={clientQuery.isLoading}
|
||||
isLoadingMore={clientQuery.isFetchingNextPage}
|
||||
hasNextPage={!!clientQuery.hasNextPage}
|
||||
@@ -486,6 +496,8 @@ export function IntlPaymentForm({ mode, initialData }: IntlPaymentFormProps) {
|
||||
const updateMutation = useUpdateIntlPayment(initialData?.id ?? "");
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -494,7 +506,13 @@ export function IntlPaymentForm({ mode, initialData }: IntlPaymentFormProps) {
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<IntlPaymentFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
...mapInitial(initialData),
|
||||
...(userLocked ? { client_id: selfUserId } : {}),
|
||||
}
|
||||
: { ...DEFAULT_FORM_VALUES, client_id: selfUserId },
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -531,7 +549,10 @@ export function IntlPaymentForm({ mode, initialData }: IntlPaymentFormProps) {
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t, mode, initialData }), [form, errors, set, t, mode, initialData]);
|
||||
const stepProps = useMemo(
|
||||
() => ({ form, errors, set, t, mode, initialData, userLocked, selfUserId, userName }),
|
||||
[form, errors, set, t, mode, initialData, userLocked, selfUserId, userName],
|
||||
);
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
} from "@/components/ui/breadcrumb";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { canAccessUrl } from "@/lib/auth/permissions";
|
||||
import Icon from "@/assets/icon.svg";
|
||||
|
||||
// ─── Collapsible wrappers ──────────────────────────────────────────────────────
|
||||
@@ -423,11 +424,42 @@ function AppSidebar() {
|
||||
},
|
||||
];
|
||||
|
||||
const isAdmin = user?.role?.code === "admin";
|
||||
// Recursively prune nav groups so only leaf links the user may open remain.
|
||||
const filterNavGroups = (groups: NavGroup[]): NavGroup[] => {
|
||||
const filterLeaf = (url?: string) => canAccessUrl(user, url);
|
||||
|
||||
const filteredNavGroups = isAdmin
|
||||
? navGroups
|
||||
: (navGroups.filter((_, i) => i === 1).map((group) => ({ ...group, items: [group.items[0]] })) as NavGroup[]);
|
||||
const filterSubSub = (items?: NavSubSubItem[]): NavSubSubItem[] => (items ?? []).filter((s) => filterLeaf(s.url));
|
||||
|
||||
const filterSubs = (subs?: NavSubItem[]): NavSubItem[] => {
|
||||
const out: NavSubItem[] = [];
|
||||
for (const s of subs ?? []) {
|
||||
if (s.url) {
|
||||
if (filterLeaf(s.url)) out.push(s);
|
||||
} else {
|
||||
const items = filterSubSub(s.items);
|
||||
if (items.length > 0) out.push({ ...s, items });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const filterItems = (items?: NavItem[]): NavItem[] => {
|
||||
const out: NavItem[] = [];
|
||||
for (const item of items ?? []) {
|
||||
if (item.url) {
|
||||
if (filterLeaf(item.url)) out.push(item);
|
||||
} else {
|
||||
const subs = filterSubs(item.items);
|
||||
if (subs.length > 0) out.push({ ...item, items: subs });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
return groups.map((group) => ({ ...group, items: filterItems(group.items) })).filter((group) => group.items.length > 0);
|
||||
};
|
||||
|
||||
const filteredNavGroups = filterNavGroups(navGroups);
|
||||
|
||||
return (
|
||||
<Sidebar collapsible="icon">
|
||||
|
||||
194
src/lib/auth/permissions.ts
Normal file
194
src/lib/auth/permissions.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import type { AuthUser, AuthUserPermission } from "@/app/store/authStore";
|
||||
|
||||
/**
|
||||
* Access model:
|
||||
* - "admin" guard has full access to everything regardless of its permission list.
|
||||
* - "web" guard (public user role) can open the Orders section (loan / card / international payments).
|
||||
* - Any other guard (operator, ...) is limited to the permission codes it holds.
|
||||
*/
|
||||
|
||||
// ─── Guard names ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const ADMIN_GUARD = "admin";
|
||||
export const OPERATOR_GUARD = "operator";
|
||||
export const WEB_GUARD = "web";
|
||||
|
||||
/** True when the user's role is the admin guard (full access). */
|
||||
export function isAdmin(user?: AuthUser | null): boolean {
|
||||
if (!user?.role) return false;
|
||||
return user.role.guardName === ADMIN_GUARD || user.role.code === "admin";
|
||||
}
|
||||
|
||||
/** True when the user's role is the web guard (the public "user" role). */
|
||||
export function isWebUser(user?: AuthUser | null): boolean {
|
||||
if (!user?.role) return false;
|
||||
return user.role.guardName === WEB_GUARD || user.role.code === "user";
|
||||
}
|
||||
|
||||
/** Returns the list of permission codes the user holds (empty for admin since it is unrestricted). */
|
||||
export function getPermissionCodes(user?: AuthUser | null): string[] {
|
||||
if (isAdmin(user)) return [];
|
||||
const seen = new Set<string>();
|
||||
const codes: string[] = [];
|
||||
const push = (p?: Pick<AuthUserPermission, "code"> | { code?: string }) => {
|
||||
if (p?.code && !seen.has(p.code)) {
|
||||
seen.add(p.code);
|
||||
codes.push(p.code);
|
||||
}
|
||||
};
|
||||
for (const p of user?.permissions ?? []) push(p);
|
||||
for (const m of user?.modules ?? []) {
|
||||
for (const p of m.permissions ?? []) push(p);
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
/** Returns true when the user may access the page protected by the given permission code. */
|
||||
export function hasPermission(user: AuthUser | null | undefined, code: string): boolean {
|
||||
if (isAdmin(user)) return true;
|
||||
return getPermissionCodes(user).includes(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the user holds at least one of the given permission codes
|
||||
* (or is an admin / there are no required codes).
|
||||
*/
|
||||
export function hasAnyPermission(user: AuthUser | null | undefined, codes: readonly string[]): boolean {
|
||||
if (codes.length === 0) return true;
|
||||
if (isAdmin(user)) return true;
|
||||
const held = new Set(getPermissionCodes(user));
|
||||
return codes.some((c) => held.has(c));
|
||||
}
|
||||
|
||||
// ─── Permission constants used to gate nav items / pages ──────────────────────
|
||||
|
||||
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). */
|
||||
ADMIN_ONLY: "__admin_only__",
|
||||
} as const;
|
||||
|
||||
type PermValue = (typeof PERM)[keyof typeof PERM];
|
||||
|
||||
// ─── Route → required permission(s) ───────────────────────────────────────────
|
||||
|
||||
type RouteRule = readonly [prefix: string, codes: readonly PermValue[]];
|
||||
|
||||
const ROUTE_RULES: RouteRule[] = [
|
||||
// System / admin-only
|
||||
["/dashboard", [PERM.ADMIN_ONLY]],
|
||||
// Settings (admin-only)
|
||||
["/settings", [PERM.ADMIN_ONLY]],
|
||||
// Loan department
|
||||
["/loan-orders", [PERM.LOANS]],
|
||||
["/loan-order-mobiles", [PERM.LOANS]],
|
||||
["/loan-remaining", [PERM.LOANS]],
|
||||
["/loan-paid-off-letters", [PERM.LOANS]],
|
||||
// Card department + international payments + online payment history
|
||||
["/order-new-card", [PERM.CARDS]],
|
||||
["/card-transactions", [PERM.CARDS]],
|
||||
["/card-requisites", [PERM.CARDS]],
|
||||
["/card-balances", [PERM.CARDS]],
|
||||
["/card-pins", [PERM.CARDS]],
|
||||
// International payments + online payment history (no permission yet → admin-only)
|
||||
["/visa-master", [PERM.ADMIN_ONLY]],
|
||||
["/sber-payments", [PERM.ADMIN_ONLY]],
|
||||
["/online-payments-history", [PERM.ADMIN_ONLY]],
|
||||
// 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]],
|
||||
// Currencies
|
||||
["/currency-rates", [PERM.CURRENCIES_VIEW]],
|
||||
["/visa-master-sber-settings", [PERM.CURRENCIES_VIEW]],
|
||||
// System pages
|
||||
["/backups", [PERM.BACKUPS_VIEW]],
|
||||
["/logs", [PERM.ACTIVITY_LOGS_VIEW]],
|
||||
];
|
||||
|
||||
/** Match a path against the rule prefixes (exact or sub-path). */
|
||||
function matchRule(pathname: string): readonly PermValue[] {
|
||||
const clean = pathname.split("?")[0];
|
||||
for (const [prefix, codes] of ROUTE_RULES) {
|
||||
if (clean === prefix || clean.startsWith(`${prefix}/`)) return codes;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Permission codes required to access a route path. Empty = unrestricted (any authenticated user). */
|
||||
export function getRequiredPermissions(pathname: string): readonly PermValue[] {
|
||||
return matchRule(pathname);
|
||||
}
|
||||
|
||||
/** Resolve the permission(s) required to show a sidebar leaf link. */
|
||||
export function permissionForUrl(url: string | undefined): readonly PermValue[] {
|
||||
return url ? matchRule(url) : [];
|
||||
}
|
||||
|
||||
/** True when the sidebar leaf for `url` is accessible to the user. */
|
||||
export function canAccessUrl(user: AuthUser | null | undefined, url: string | undefined): boolean {
|
||||
if (!url) return false;
|
||||
if (isAdmin(user)) return true;
|
||||
if (isWebUser(user) && isWebAccessiblePath(url)) return true;
|
||||
return hasAnyPermission(user, permissionForUrl(url));
|
||||
}
|
||||
|
||||
// ─── Web (public user) section ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Paths that the "web" guard (public user role) may open regardless of its
|
||||
* permission list. Covers the whole Orders section: loan department,
|
||||
* card department and international payments.
|
||||
*/
|
||||
const WEB_ACCESS_PREFIXES: readonly string[] = [
|
||||
// Loan department
|
||||
"/loan-orders",
|
||||
"/loan-order-mobiles",
|
||||
"/loan-remaining",
|
||||
"/loan-paid-off-letters",
|
||||
// Card department
|
||||
"/order-new-card",
|
||||
"/card-transactions",
|
||||
"/card-requisites",
|
||||
"/card-balances",
|
||||
"/card-pins",
|
||||
// International payments
|
||||
"/visa-master",
|
||||
"/sber-payments",
|
||||
];
|
||||
|
||||
/** True when the path is inside the Orders section available to the web guard. */
|
||||
function isWebAccessiblePath(pathname: string): boolean {
|
||||
const clean = pathname.split("?")[0];
|
||||
return WEB_ACCESS_PREFIXES.some((prefix) => clean === prefix || clean.startsWith(`${prefix}/`));
|
||||
}
|
||||
|
||||
// ─── Home path ────────────────────────────────────────────────────────────────
|
||||
|
||||
const HOME_PRIORITY: readonly (readonly [codes: readonly PermValue[], path: string])[] = [
|
||||
[[PERM.LOANS], "/loan-orders"],
|
||||
[[PERM.CARDS], "/order-new-card"],
|
||||
[[PERM.USERS_VIEW, PERM.USERS_MANAGE], "/operators"],
|
||||
[[PERM.CURRENCIES_VIEW], "/currency-rates"],
|
||||
[[PERM.BACKUPS_VIEW], "/backups"],
|
||||
[[PERM.ACTIVITY_LOGS_VIEW], "/logs"],
|
||||
];
|
||||
|
||||
/** Returns the landing page for the user: admin → dashboard, web → 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";
|
||||
for (const [codes, path] of HOME_PRIORITY) {
|
||||
if (hasAnyPermission(user, codes)) return path;
|
||||
}
|
||||
return "/profile";
|
||||
}
|
||||
@@ -40,6 +40,24 @@ export function formatToApiDate(dateStr?: string | Date | null): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Backend'den gelen ISO UTC tarihini formun `<input type="date">` / DateInput'un
|
||||
* beklediği 'YYYY-MM-DD' formatına çevirir. Örn: '1987-04-08T14:35:00Z' -> '1987-04-08'
|
||||
*/
|
||||
export function formatFromApiDateInput(isoStr?: string | null): string {
|
||||
if (!isoStr) return "";
|
||||
const trimmed = isoStr.trim();
|
||||
if (!trimmed) return "";
|
||||
|
||||
const d = new Date(trimmed);
|
||||
if (isNaN(d.getTime())) return trimmed.slice(0, 10);
|
||||
|
||||
const year = d.getUTCFullYear();
|
||||
const month = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backend'den gelen ISO UTC tarih formatını 'hh:mm, dd.mm.yyyy' formatına çevirir.
|
||||
* Örn: '1987-04-08T14:35:00Z' -> '14:35, 08.04.1987'
|
||||
|
||||
@@ -19,6 +19,7 @@ import { AvatarUpload } from "@/components/avatarUpload";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
import { useAuthStore } from "@/app/store/authStore";
|
||||
import { isAdmin as isAdminUser } from "@/lib/auth/permissions";
|
||||
import { useProfile, useUpdateProfile } from "@/features/auth/hooks/useLogin";
|
||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||
@@ -44,7 +45,7 @@ export default function ProfilePage() {
|
||||
|
||||
const branches = user?.branches ?? [];
|
||||
const permissions = user?.permissions ?? [];
|
||||
const isAdmin = authUser?.role?.code === "admin";
|
||||
const isAdmin = isAdminUser(authUser);
|
||||
|
||||
// ── Form State for Editing ──
|
||||
const [formData, setFormData] = useState({
|
||||
|
||||
Reference in New Issue
Block a user