added role func, fixed some ui
This commit is contained in:
@@ -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 ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
Reference in New Issue
Block a user