fixed ui, connected role user, branch user permissions user api
This commit is contained in:
@@ -2,6 +2,19 @@ import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import axios from "axios";
|
||||
import type { ApiSuccessResponse } from "@/lib/api/client";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
export interface AuthUserRole {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AuthUserBranch {
|
||||
id: number;
|
||||
uniqueCode: string;
|
||||
name: LocalizedText;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id?: string | number;
|
||||
@@ -10,8 +23,9 @@ export interface AuthUser {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
phone?: string;
|
||||
role?: string;
|
||||
role?: AuthUserRole;
|
||||
avatar?: string;
|
||||
branches?: AuthUserBranch[];
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,49 +1,38 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { Slot } from "radix-ui";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-3xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
||||
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-md border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||
secondary: "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||
destructive:
|
||||
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
|
||||
outline:
|
||||
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||
ghost:
|
||||
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
||||
outline: "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||
ghost: "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot.Root : "span"
|
||||
}: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot.Root : "span";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
data-variant={variant}
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
return <Comp data-slot="badge" data-variant={variant} className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
export { Badge, badgeVariants };
|
||||
|
||||
@@ -19,6 +19,10 @@ import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
import { useBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
||||
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 { formatFromApiPhone } from "@/lib/utils";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -190,11 +194,28 @@ function StepCard({ form, errors, set, t, cardTypeOptions, branchOptions, distri
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
function StepPersonal({ form, errors, set, t, initialData }: StepContentProps & { initialData?: CardPinOrder }) {
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
const clientsQuery = useInfiniteClients(clientSearch);
|
||||
|
||||
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
|
||||
if (initialData?.userId && !opts.some((o) => o.value === String(initialData.userId))) {
|
||||
opts.unshift({ value: String(initialData.userId), label: String(initialData.userId) });
|
||||
}
|
||||
return opts;
|
||||
}, [clientsQuery.data, initialData]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("cardPin.titles.name") || "Ady we familiýasy"}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.customerName", "Ady")}
|
||||
@@ -204,8 +225,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("cardPin.field.customerName", "Ady")}
|
||||
error={errors.customerName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||
@@ -215,8 +234,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||
error={errors.customerSurname}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||
@@ -225,10 +242,8 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<BentoCard title={t("cardPin.titles.contactInfo") || "Şahsy we habarlaşmak"}>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("cardPin.field.bornAt", "Doglan güni")}
|
||||
@@ -236,27 +251,29 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
onChange={(v) => set("bornAt", v)}
|
||||
error={errors.bornAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
type="phone"
|
||||
label={t("cardPin.field.phone", "Telefon")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder={t("cardPin.field.phone", "Telefon")}
|
||||
placeholder={t("loanOrderForm.placeholders.phone") || "61 097651"}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
<InfiniteSelect
|
||||
label={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||
required
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
placeholder={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||
options={clientOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.userId}
|
||||
loading={clientsQuery.isLoading}
|
||||
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||
hasNextPage={!!clientsQuery.hasNextPage}
|
||||
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||
searchValue={clientSearch}
|
||||
onSearchChange={setClientSearch}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -267,67 +284,70 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||
required
|
||||
value={form.passportSerie}
|
||||
onChange={(v) => set("passportSerie", v)}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
required
|
||||
value={form.passportId}
|
||||
onChange={(v) => set("passportId", v)}
|
||||
placeholder={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Pasport maglumatlary"}>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||
required
|
||||
value={form.passportSerie}
|
||||
onChange={(v) => set("passportSerie", v)}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
required
|
||||
value={form.passportId}
|
||||
onChange={(v) => set("passportId", v)}
|
||||
placeholder={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={4}>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportOne", "Pasport 1")}
|
||||
<DocumentUpload
|
||||
label={t("cardPin.field.passportOne", "Pasport (sahypa 1)")}
|
||||
value={form.passportOne}
|
||||
onChange={(v) => set("passportOne", v)}
|
||||
placeholder={t("cardPin.field.passportOne", "Pasport 1")}
|
||||
error={errors.passportOne}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportTwo", "Pasport 2")}
|
||||
<DocumentUpload
|
||||
label={t("cardPin.field.passportTwo", "Pasport (2-3-nji sahypa)")}
|
||||
value={form.passportTwo}
|
||||
onChange={(v) => set("passportTwo", v)}
|
||||
placeholder={t("cardPin.field.passportTwo", "Pasport 2")}
|
||||
error={errors.passportTwo}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportThree", "Pasport 3")}
|
||||
<DocumentUpload
|
||||
label={t("cardPin.field.passportThree", "Pasport (8-9 sahypa)")}
|
||||
value={form.passportThree}
|
||||
onChange={(v) => set("passportThree", v)}
|
||||
placeholder={t("cardPin.field.passportThree", "Pasport 3")}
|
||||
error={errors.passportThree}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportFour", "Pasport 4")}
|
||||
<DocumentUpload
|
||||
label={t("cardPin.field.passportFour", "Pasport (32-nji sahypa)")}
|
||||
value={form.passportFour}
|
||||
onChange={(v) => set("passportFour", v)}
|
||||
placeholder={t("cardPin.field.passportFour", "Pasport 4")}
|
||||
error={errors.passportFour}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -347,9 +367,9 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
const updateMutation = useUpdateCardPin(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 100 });
|
||||
const { data: branchesData } = useBranches({ page: 1, limit: 100 });
|
||||
const { data: districtsData } = useDistricts({ page: 1, limit: 100 });
|
||||
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
||||
const { data: branchesData } = useBranches({ page: 1, limit: 25 });
|
||||
const { data: districtsData } = useDistricts({ page: 1, limit: 25 });
|
||||
|
||||
const cardTypeOptions = useMemo(
|
||||
() =>
|
||||
@@ -533,7 +553,7 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
|
||||
{/* Step content */}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} initialData={initialData} />}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||
|
||||
{/* Actions */}
|
||||
@@ -566,7 +586,7 @@ function mapInitial(data: CardPinOrder): Partial<CardPinFormData> {
|
||||
customerSurname: data.customerSurname ?? "",
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||
phone: data.phone ?? "",
|
||||
phone: formatFromApiPhone(data.phone),
|
||||
passportSerie: data.passportSerie ?? "",
|
||||
passportId: data.passportId ?? "",
|
||||
passportOne: data.passportOne ?? "",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
import type { CreateCardPinPayload } from "../api/cardPinApi";
|
||||
import { formatToApiPhone } from "@/lib/utils";
|
||||
|
||||
const optional = () => z.string().default("");
|
||||
|
||||
@@ -101,7 +102,7 @@ export function buildPayload(data: CardPinFormData): CreateCardPinPayload {
|
||||
branchId: Number(data.branchId),
|
||||
cardTypeId: Number(data.cardTypeId),
|
||||
cardNumber: data.cardNumber.trim(),
|
||||
phone: data.phone.trim(),
|
||||
phone: formatToApiPhone(data.phone),
|
||||
passportSerie: data.passportSerie.trim(),
|
||||
passportId: data.passportId.trim(),
|
||||
passportOne: data.passportOne.trim(),
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { useMemo } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
import type { Card } from "../api/cardTransactionsApi";
|
||||
import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
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";
|
||||
import type { CardTransactionFormData } from "../schemas/cardTransaction.schema";
|
||||
|
||||
@@ -45,9 +49,41 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
const clientsQuery = useInfiniteClients(clientSearch);
|
||||
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
||||
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedTitle;
|
||||
|
||||
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
|
||||
if (initialData?.userId && !opts.some((o) => o.value === String(initialData.userId))) {
|
||||
opts.unshift({ value: String(initialData.userId), label: String(initialData.userId) });
|
||||
}
|
||||
return opts;
|
||||
}, [clientsQuery.data, initialData]);
|
||||
|
||||
const cardTypeOptions = useMemo(() => {
|
||||
const opts = (cardTypesData?.paymentCards ?? []).map((ct) => ({
|
||||
value: String(ct.id),
|
||||
label: ct.title[lang] || ct.title.tm,
|
||||
}));
|
||||
|
||||
if (initialData?.type && !opts.some((o) => o.value === initialData.type)) {
|
||||
opts.unshift({ value: initialData.type, label: initialData.type });
|
||||
}
|
||||
return opts;
|
||||
}, [cardTypesData, lang, initialData]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -132,11 +168,12 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
|
||||
{/* Type */}
|
||||
<FormInput
|
||||
type="text"
|
||||
type="searchable-select"
|
||||
label={t("Card type", "Kart görnüşi")}
|
||||
value={form.type}
|
||||
onChange={setField("type")}
|
||||
placeholder={t("Card type", "Kart görnüşi")}
|
||||
options={cardTypeOptions}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.type)}
|
||||
required
|
||||
/>
|
||||
@@ -152,15 +189,21 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
required
|
||||
/>
|
||||
|
||||
{/* User ID */}
|
||||
<FormInput
|
||||
type="number"
|
||||
{/* User (Client) */}
|
||||
<InfiniteSelect
|
||||
label={t("User ID", "Ulanyjy ID")}
|
||||
value={form.userId}
|
||||
onChange={setField("userId")}
|
||||
placeholder={t("User ID", "Ulanyjy ID")}
|
||||
error={errMsg(errors.userId)}
|
||||
required
|
||||
value={form.userId}
|
||||
onChange={(v) => setField("userId")(v)}
|
||||
options={clientOptions}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.userId)}
|
||||
loading={clientsQuery.isLoading}
|
||||
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||
hasNextPage={!!clientsQuery.hasNextPage}
|
||||
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||
searchValue={clientSearch}
|
||||
onSearchChange={setClientSearch}
|
||||
/>
|
||||
|
||||
{/* Expiry Month + Year side by side */}
|
||||
|
||||
@@ -132,7 +132,7 @@ export const clientsApi = {
|
||||
getClients: async (params: ClientsListParams = {}, signal?: AbortSignal): Promise<ClientsListResponse> => {
|
||||
const { page, limit, search, isActive } = params;
|
||||
const { data } = await apiClient.get<ClientsListResponse>("/users/clients", {
|
||||
params: { page, limit, username: search, isActive },
|
||||
params: { page, limit, username: search || undefined, isActive: isActive || undefined },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
|
||||
@@ -120,6 +120,7 @@ export interface LoanOrderPayload {
|
||||
loanType: string;
|
||||
region: string;
|
||||
branch: string;
|
||||
userId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
patronicName?: string;
|
||||
@@ -352,6 +353,7 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
|
||||
guarantor2CardExpMonth: order.guarantor2CardMonth ?? "",
|
||||
guarantor2CardExpYear: order.guarantor2CardYear ?? "",
|
||||
guarantor2Note: order.guarantor2Note ?? "",
|
||||
loanHistory: order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : "",
|
||||
createdBy: order.userName ?? "",
|
||||
fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "),
|
||||
registeredAddress: order.passportAddress ?? "",
|
||||
@@ -433,8 +435,8 @@ function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayloa
|
||||
status: payload.status ?? "pending",
|
||||
satisfiable: "yes",
|
||||
source: "web",
|
||||
loanOrderRequiredDocId: 0,
|
||||
userId: 0,
|
||||
loanOrderRequiredDocId: payload.loanHistory ? Number(payload.loanHistory) : 0,
|
||||
userId: toNum(payload.userId) ?? 0,
|
||||
uniqueId: "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ import { useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
import { formatFromApiDate, formatFromApiPhone } from "@/lib/utils";
|
||||
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
||||
import { useGetRequiredDocuments } from "@/features/requiredDocuments/hooks/useRequiredDocuments";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
|
||||
// ─── Static options ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -344,81 +346,124 @@ function StepLocation({ form, errors, set, t, initialData }: StepContentProps &
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
function StepPersonal({ form, errors, set, t, initialData }: StepContentProps & { initialData?: LoanOrder }) {
|
||||
const { data: requiredDocsData } = useGetRequiredDocuments({ page: 1, limit: 100 });
|
||||
|
||||
const [clientSearch, setClientSearch] = useState("");
|
||||
const clientsQuery = useInfiniteClients(clientSearch);
|
||||
|
||||
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
|
||||
if (initialData?.createdById && !opts.some((o) => o.value === String(initialData.createdById))) {
|
||||
opts.unshift({
|
||||
value: String(initialData.createdById),
|
||||
label: initialData.createdBy || String(initialData.createdById),
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [clientsQuery.data, initialData]);
|
||||
|
||||
const loanHistoryOptions = useMemo<SelectOption[]>(
|
||||
() =>
|
||||
(requiredDocsData?.loansDocuments ?? []).map((doc) => ({
|
||||
value: String(doc.id),
|
||||
label: doc.name,
|
||||
})),
|
||||
[requiredDocsData],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Name") || "Ady"}
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("loanOrderForm.titles.personalName") || "Şahsy maglumatlar"}>
|
||||
<InfiniteSelect
|
||||
label={t("loanOrderForm.labels.client") || "Müşderi"}
|
||||
required
|
||||
value={form.firstName}
|
||||
onChange={(v) => set("firstName", v)}
|
||||
placeholder={t("Name") || "Ady"}
|
||||
error={errors.firstName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Surname") || "Familiýasy"}
|
||||
required
|
||||
value={form.lastName}
|
||||
onChange={(v) => set("lastName", v)}
|
||||
placeholder={t("Surname") || "Familiýasy"}
|
||||
error={errors.lastName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Patronic name") || "Atasynyň ady"}
|
||||
value={form.patronicName}
|
||||
onChange={(v) => set("patronicName", v)}
|
||||
placeholder={t("Patronic name") || "Atasynyň ady"}
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
options={clientOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.userId}
|
||||
loading={clientsQuery.isLoading}
|
||||
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||
hasNextPage={!!clientsQuery.hasNextPage}
|
||||
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||
searchValue={clientSearch}
|
||||
onSearchChange={setClientSearch}
|
||||
/>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Name") || "Ady"}
|
||||
required
|
||||
value={form.firstName}
|
||||
onChange={(v) => set("firstName", v)}
|
||||
placeholder={t("Name") || "Ady"}
|
||||
error={errors.firstName}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Surname") || "Familiýasy"}
|
||||
required
|
||||
value={form.lastName}
|
||||
onChange={(v) => set("lastName", v)}
|
||||
placeholder={t("Surname") || "Familiýasy"}
|
||||
error={errors.lastName}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Patronic name") || "Atasynyň ady"}
|
||||
value={form.patronicName}
|
||||
onChange={(v) => set("patronicName", v)}
|
||||
placeholder={t("Patronic name") || "Atasynyň ady"}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Education") || "Bilimi"}
|
||||
required
|
||||
value={form.education}
|
||||
onChange={(v) => set("education", v)}
|
||||
options={EDUCATION_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.education}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Marriage status") || "Maşgala ýagdaýy"}
|
||||
required
|
||||
value={form.marriageStatus}
|
||||
onChange={(v) => set("marriageStatus", v)}
|
||||
options={MARRIAGE_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.marriageStatus}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("Date of birth") || "Doglan güni"}
|
||||
required
|
||||
value={form.dateOfBirth}
|
||||
onChange={(v) => set("dateOfBirth", v)}
|
||||
error={errors.dateOfBirth}
|
||||
/>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("loanOrderForm.titles.personalDetails") || "Bilim we maşgala ýagdaýy"}>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Education") || "Bilimi"}
|
||||
required
|
||||
value={form.education}
|
||||
onChange={(v) => set("education", v)}
|
||||
options={EDUCATION_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.education}
|
||||
/>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Marriage status") || "Maşgala ýagdaýy"}
|
||||
required
|
||||
value={form.marriageStatus}
|
||||
onChange={(v) => set("marriageStatus", v)}
|
||||
options={MARRIAGE_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.marriageStatus}
|
||||
/>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("Date of birth") || "Doglan güni"}
|
||||
required
|
||||
value={form.dateOfBirth}
|
||||
onChange={(v) => set("dateOfBirth", v)}
|
||||
error={errors.dateOfBirth}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<BentoCard title={t("loanOrderForm.titles.residence") || "Ýaşaýyş salgysy"}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Residence (passport)") || "Ýazgy edilen salgyňyz"}
|
||||
@@ -428,8 +473,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("loanOrderForm.placeholders.residence") || "Ýazgy edilen salgy"}
|
||||
error={errors.residence}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Current Residence") || "Häzirki ýaşaýyş ýeri"}
|
||||
@@ -438,14 +481,15 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("loanOrderForm.placeholders.currentResidence") || "Häzirki ýaşaýyş ýeri"}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
|
||||
<BentoCard title={t("loanOrderForm.titles.loanHistory") || "Karz taryhy"}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
type="select"
|
||||
label={t("Loan history") || "Karz taryhy"}
|
||||
value={form.loanHistory}
|
||||
onChange={(v) => set("loanHistory", v)}
|
||||
options={[]}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
options={loanHistoryOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -1174,7 +1218,7 @@ 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} />}
|
||||
{currentStep === 3 && <StepPersonal {...stepProps} initialData={initialData} />}
|
||||
{currentStep === 4 && <StepCard {...stepProps} />}
|
||||
{currentStep === 5 && <StepPassport {...stepProps} mode={mode} />}
|
||||
{currentStep === 6 && <StepContact {...stepProps} />}
|
||||
@@ -1206,6 +1250,7 @@ function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
|
||||
loanType: order.loanTypeId != null ? String(order.loanTypeId) : "",
|
||||
region: order.region ?? "AG",
|
||||
branch: order.branchId != null ? String(order.branchId) : "",
|
||||
userId: order.createdById != null ? String(order.createdById) : "",
|
||||
firstName: order.firstName ?? "",
|
||||
lastName: order.lastName ?? "",
|
||||
patronicName: order.patronicName ?? "",
|
||||
|
||||
@@ -7,6 +7,7 @@ export const loanOrderFormSchema = z.object({
|
||||
loanType: z.string().min(1, "validation.required"),
|
||||
region: z.string().min(1, "validation.required"),
|
||||
branch: z.string().min(1, "validation.required"),
|
||||
userId: z.string().min(1, "validation.required"),
|
||||
firstName: z.string().min(1, "validation.required"),
|
||||
lastName: z.string().min(1, "validation.required"),
|
||||
patronicName: z.string().optional(),
|
||||
@@ -139,6 +140,7 @@ export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderFormData>>>
|
||||
1: loanOrderFormSchema.pick({ loanType: true, loanAmount: true }),
|
||||
2: loanOrderFormSchema.pick({ region: true, branch: true }),
|
||||
3: loanOrderFormSchema.pick({
|
||||
userId: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
education: true,
|
||||
@@ -228,6 +230,7 @@ export const DEFAULT_FORM_VALUES: LoanOrderFormData = {
|
||||
loanType: "",
|
||||
region: "AG",
|
||||
branch: "",
|
||||
userId: "",
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
patronicName: "",
|
||||
@@ -291,6 +294,7 @@ export function buildPayload(data: LoanOrderFormData) {
|
||||
loanType: data.loanType,
|
||||
region: data.region,
|
||||
branch: data.branch,
|
||||
userId: data.userId,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
patronicName: data.patronicName || undefined,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
@@ -37,6 +37,29 @@ export function useOperator(id: number) {
|
||||
});
|
||||
}
|
||||
|
||||
const STAFF_PAGE_SIZE = 25;
|
||||
|
||||
/**
|
||||
* Paginated staff users (GET /users/staff) for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteStaff(search = "") {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: [...operatorKeys.all, "infinite", effectiveSearch] as const,
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
operatorsApi.getOperators({ page: pageParam, limit: STAFF_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce((sum, p) => sum + (p?.users?.length ?? 0), 0);
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreateOperator ────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateOperator() {
|
||||
|
||||
@@ -9,6 +9,8 @@ import { useForm } from "react-hook-form";
|
||||
|
||||
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { DocumentUpload } from "@/components/documentUpload";
|
||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { CardOrder } from "../api/orderNewCardApi";
|
||||
@@ -19,6 +21,7 @@ import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
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 { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
@@ -103,6 +106,7 @@ interface StepContentProps {
|
||||
cardStateOptions: SelectOption[];
|
||||
branchOptions: SelectOption[];
|
||||
districtOptions: SelectOption[];
|
||||
mode: "create" | "edit";
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
@@ -222,8 +226,8 @@ function StepCard({ form, errors, set, t, cardTypeOptions, cardStateOptions, bra
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("cardOrder.titles.name") || "Ady we familiýasy"}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.customerName", "Ady")}
|
||||
@@ -233,8 +237,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("cardOrder.field.customerName", "Ady")}
|
||||
error={errors.customerName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.customerSurname", "Familiýasy")}
|
||||
@@ -244,8 +246,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("cardOrder.field.customerSurname", "Familiýasy")}
|
||||
error={errors.customerSurname}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
||||
@@ -253,11 +253,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
onChange={(v) => set("customerPatronicName", v)}
|
||||
placeholder={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.oldSurname", "Köne familiýaňyz (eger üýtgän bolsa)")}
|
||||
@@ -266,7 +261,8 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("cardOrder.field.oldSurname", "Köne familiýa")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
|
||||
<BentoCard title={t("cardOrder.titles.birthInfo") || "Doglan maglumaty"}>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("cardOrder.field.bornAt", "Doglan güni")}
|
||||
@@ -274,8 +270,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
onChange={(v) => set("bornAt", v)}
|
||||
error={errors.bornAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
||||
@@ -283,11 +277,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
onChange={(v) => set("bornPlace", v)}
|
||||
placeholder={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.citizenship", "Raýatlyk")}
|
||||
@@ -298,36 +287,39 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
error={errors.citizenship}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.phone", "Telefon")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder={t("cardOrder.field.phone", "Telefon")}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||
value={form.phoneAdditional}
|
||||
onChange={(v) => set("phoneAdditional", v)}
|
||||
placeholder={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||
/>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("cardOrder.titles.contact") || "Habarlaşmak"}>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.phone", "Telefon")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder={t("cardOrder.field.phone", "Telefon")}
|
||||
error={errors.phone}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||
value={form.phoneAdditional}
|
||||
onChange={(v) => set("phoneAdditional", v)}
|
||||
placeholder={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
function StepPassport({ form, errors, set, t, mode }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Pasport maglumatlary"}>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("cardOrder.field.passportSerie", "Pasport seriýasy")}
|
||||
@@ -338,8 +330,6 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportId", "Pasport belgisi")}
|
||||
@@ -349,8 +339,6 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
placeholder={t("cardOrder.field.passportId", "Pasport belgisi")}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("cardOrder.field.passportGivenAt", "Pasport berlen senesi")}
|
||||
@@ -359,10 +347,8 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
error={errors.passportGivenAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<BentoCard title={t("cardOrder.titles.passportIssuer") || "Berlen ýeri"}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
||||
@@ -370,8 +356,6 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
onChange={(v) => set("passportGivenBy", v)}
|
||||
placeholder={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportAddress", "Pasport salgysy")}
|
||||
@@ -382,41 +366,52 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={4}>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportOne", "Pasport 1")}
|
||||
<DocumentUpload
|
||||
label={
|
||||
mode === "edit"
|
||||
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)"
|
||||
: t("Passport (page 1)") || "Pasport (sahypa 1)"
|
||||
}
|
||||
value={form.passportOne}
|
||||
onChange={(v) => set("passportOne", v)}
|
||||
placeholder={t("cardOrder.field.passportOne", "Pasport 1")}
|
||||
error={errors.passportOne}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportTwo", "Pasport 2")}
|
||||
<DocumentUpload
|
||||
label={
|
||||
mode === "edit"
|
||||
? t("loanOrderForm.fileLabels.replacePage23") || "Pasport (2-3-nji sahypa) (çalyşmak)"
|
||||
: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"
|
||||
}
|
||||
value={form.passportTwo}
|
||||
onChange={(v) => set("passportTwo", v)}
|
||||
placeholder={t("cardOrder.field.passportTwo", "Pasport 2")}
|
||||
error={errors.passportTwo}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportThree", "Pasport 3")}
|
||||
<DocumentUpload
|
||||
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
|
||||
value={form.passportThree}
|
||||
onChange={(v) => set("passportThree", v)}
|
||||
placeholder={t("cardOrder.field.passportThree", "Pasport 3")}
|
||||
error={errors.passportThree}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportFour", "Pasport 4")}
|
||||
<DocumentUpload
|
||||
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
|
||||
value={form.passportFour}
|
||||
onChange={(v) => set("passportFour", v)}
|
||||
placeholder={t("cardOrder.field.passportFour", "Pasport 4")}
|
||||
error={errors.passportFour}
|
||||
accept="image/*"
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -424,7 +419,29 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function StepContact({ form, errors, set, t }: StepContentProps) {
|
||||
function StepContact({ form, errors, set, t, initialData }: StepContentProps & { initialData?: CardOrder }) {
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const usersQuery = useInfiniteClients(userSearch);
|
||||
|
||||
const userOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (usersQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||
}));
|
||||
|
||||
if (initialData?.userId && !opts.some((o) => o.value === String(initialData.userId))) {
|
||||
opts.unshift({
|
||||
value: String(initialData.userId),
|
||||
label: initialData.customerName
|
||||
? `${initialData.customerName} ${initialData.customerSurname || ""}`.trim()
|
||||
: String(initialData.userId),
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}, [usersQuery.data, initialData]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
@@ -450,14 +467,20 @@ function StepContact({ form, errors, set, t }: StepContentProps) {
|
||||
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardOrder.field.userId", "Ulanyjy ID")}
|
||||
<InfiniteSelect
|
||||
label={t("cardOrder.field.userId", "Ulanyjy")}
|
||||
required
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
placeholder={t("cardOrder.field.userId", "Ulanyjy ID")}
|
||||
options={userOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.userId}
|
||||
loading={usersQuery.isLoading}
|
||||
isLoadingMore={usersQuery.isFetchingNextPage}
|
||||
hasNextPage={!!usersQuery.hasNextPage}
|
||||
onLoadMore={() => usersQuery.fetchNextPage()}
|
||||
searchValue={userSearch}
|
||||
onSearchChange={setUserSearch}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -477,10 +500,10 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
const updateMutation = useUpdateCard(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 100 });
|
||||
const { data: cardReasonsData } = useCardReasons({ page: 1, limit: 100 });
|
||||
const { data: branchesData } = useBranches({ page: 1, limit: 100 });
|
||||
const { data: districtsData } = useDistricts({ page: 1, limit: 100 });
|
||||
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
||||
const { data: cardReasonsData } = useCardReasons({ page: 1, limit: 25 });
|
||||
const { data: branchesData } = useBranches({ page: 1, limit: 25 });
|
||||
const { data: districtsData } = useDistricts({ page: 1, limit: 25 });
|
||||
|
||||
const cardTypeOptions = useMemo(
|
||||
() =>
|
||||
@@ -570,8 +593,8 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(
|
||||
() => ({ form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions }),
|
||||
[form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions],
|
||||
() => ({ form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions, mode }),
|
||||
[form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions, mode],
|
||||
);
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||
@@ -684,7 +707,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||
{currentStep === 3 && <StepContact {...stepProps} />}
|
||||
{currentStep === 3 && <StepContact {...stepProps} initialData={initialData} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
@@ -11,6 +11,7 @@ export const permissionKeys = {
|
||||
lists: () => ["permissions", "list"] as const,
|
||||
list: (params: PermissionsListParams) => ["permissions", "list", params] as const,
|
||||
detail: (id: number) => ["permissions", "detail", id] as const,
|
||||
infinite: (search: string) => ["permissions", "infinite", search] as const,
|
||||
};
|
||||
|
||||
// ─── usePermissions (list) ────────────────────────────────────────────────────
|
||||
@@ -35,6 +36,33 @@ export function usePermission(id: number) {
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useInfinitePermissions ───────────────────────────────────────────────────
|
||||
|
||||
const PERMISSION_PAGE_SIZE = 25;
|
||||
|
||||
/**
|
||||
* Infinite-scroll permission list for searchable selects.
|
||||
* staleTime = 5 min as required by PROJECT_STANDARDS rule 12.
|
||||
*/
|
||||
export function useInfinitePermissions(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: permissionKeys.infinite(effectiveSearch),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
permissionsApi.getAll({ page: pageParam, limit: PERMISSION_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce((sum, p) => sum + (p?.permissions?.length ?? 0), 0);
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreatePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useCreatePermission() {
|
||||
|
||||
@@ -32,7 +32,7 @@ const ROLE_PAGE_SIZE = 25;
|
||||
* Paginated roles for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteRoles(search = "") {
|
||||
export function useInfiniteRoles(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
@@ -45,6 +45,7 @@ export function useInfiniteRoles(search = "") {
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,16 @@ export interface AddBranchUserPayload {
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface AddRoleUserPayload {
|
||||
roleId: number;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface AddPermissionUserPayload {
|
||||
permissionId: number;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
// Re-export so shared hooks can import from one place
|
||||
export type { BranchListParams, BranchListResponse };
|
||||
|
||||
@@ -48,6 +58,22 @@ export async function postBranchUser(payload: AddBranchUserPayload): Promise<voi
|
||||
await apiClient.post("/branch-users", payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /role-users
|
||||
* Assigns a role to a user.
|
||||
*/
|
||||
export async function postRoleUser(payload: AddRoleUserPayload): Promise<void> {
|
||||
await apiClient.post("/role-users", payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /permission-users
|
||||
* Assigns a permission to a user.
|
||||
*/
|
||||
export async function postPermissionUser(payload: AddPermissionUserPayload): Promise<void> {
|
||||
await apiClient.post("/permission-users", payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxy for branch list fetching — kept here so shared hooks
|
||||
* don't import directly from the branches feature.
|
||||
|
||||
@@ -20,7 +20,7 @@ const BRANCH_PAGE_SIZE = 25;
|
||||
* Infinite-scroll branch list for searchable selects.
|
||||
* staleTime = 5 min as required by PROJECT_STANDARDS rule 12.
|
||||
*/
|
||||
export function useInfiniteBranches(search = "") {
|
||||
export function useInfiniteBranches(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
@@ -34,6 +34,7 @@ export function useInfiniteBranches(search = "") {
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
82
src/features/shared/hooks/useSharedUserAssignments.ts
Normal file
82
src/features/shared/hooks/useSharedUserAssignments.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
postBranchUser,
|
||||
postRoleUser,
|
||||
postPermissionUser,
|
||||
type AddBranchUserPayload,
|
||||
type AddRoleUserPayload,
|
||||
type AddPermissionUserPayload,
|
||||
} from "../api/sharedApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const userProfileKeys = {
|
||||
profile: ["auth", "profile"] as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Refreshes the profile cache after any user-assignment change.
|
||||
*/
|
||||
function useInvalidateProfile() {
|
||||
const queryClient = useQueryClient();
|
||||
return () => queryClient.invalidateQueries({ queryKey: userProfileKeys.profile });
|
||||
}
|
||||
|
||||
// ─── useAssignRoleToUser ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* POST /role-users — assigns a role to the given staff user and refreshes the profile cache.
|
||||
* `userId` is supplied at mutate time (picked from the staff select).
|
||||
*/
|
||||
export function useAssignRoleToUser() {
|
||||
const { t } = useTranslation();
|
||||
const invalidateProfile = useInvalidateProfile();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: AddRoleUserPayload) => postRoleUser(payload),
|
||||
onSuccess: () => {
|
||||
invalidateProfile();
|
||||
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useAssignPermissionToUser ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* POST /permission-users — assigns a permission to the given staff user and refreshes the profile cache.
|
||||
* `userId` is supplied at mutate time (picked from the staff select).
|
||||
*/
|
||||
export function useAssignPermissionToUser() {
|
||||
const { t } = useTranslation();
|
||||
const invalidateProfile = useInvalidateProfile();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: AddPermissionUserPayload) => postPermissionUser(payload),
|
||||
onSuccess: () => {
|
||||
invalidateProfile();
|
||||
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useAssignBranchToUser ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* POST /branch-users — assigns a branch to the given staff user and refreshes the profile cache.
|
||||
* `userId` is supplied at mutate time (picked from the staff select).
|
||||
*/
|
||||
export function useAssignBranchToUser() {
|
||||
const { t } = useTranslation();
|
||||
const invalidateProfile = useInvalidateProfile();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: AddBranchUserPayload) => postBranchUser(payload),
|
||||
onSuccess: () => {
|
||||
invalidateProfile();
|
||||
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -552,6 +552,7 @@
|
||||
"loanOrderForm.labels.cardExpMonth": "Month",
|
||||
"loanOrderForm.labels.cardExpYear": "Year",
|
||||
"loanOrderForm.labels.guarantor1Salary": "Average salary",
|
||||
"loanOrderForm.labels.client": "Client",
|
||||
"loanOrderForm.steps.status.subtitle": "Status & Note",
|
||||
"loanOrderForm.steps.loan.subtitle": "Type & Amount",
|
||||
"loanOrderForm.steps.location.subtitle": "Region & Branch",
|
||||
@@ -1426,5 +1427,10 @@
|
||||
"visaMasterSberSettings.editTitle": "Edit setting",
|
||||
"onlinePayments.viewTitle": "Payment detail",
|
||||
"cardTypes.viewTitle": "Card type detail",
|
||||
"profile.title": "My Profile"
|
||||
"profile.title": "My Profile",
|
||||
"profile.actions.assignRole": "Assign role",
|
||||
"profile.actions.assignPermission": "Assign permission",
|
||||
"profile.actions.assignBranch": "Assign branch",
|
||||
"profile.assign.success": "Assigned successfully",
|
||||
"profile.assign.userLabel": "User (staff)"
|
||||
}
|
||||
|
||||
@@ -552,6 +552,7 @@
|
||||
"loanOrderForm.labels.cardExpMonth": "Месяц",
|
||||
"loanOrderForm.labels.cardExpYear": "Год",
|
||||
"loanOrderForm.labels.guarantor1Salary": "Средняя зарплата",
|
||||
"loanOrderForm.labels.client": "Клиент",
|
||||
"loanOrderForm.steps.status.subtitle": "Статус и заметка",
|
||||
"loanOrderForm.steps.loan.subtitle": "Тип и сумма",
|
||||
"loanOrderForm.steps.location.subtitle": "Велаят и филиал",
|
||||
@@ -1427,5 +1428,10 @@
|
||||
"visaMasterSberSettings.editTitle": "Редактировать настройку",
|
||||
"onlinePayments.viewTitle": "Детали платежа",
|
||||
"cardTypes.viewTitle": "Детали типа карты",
|
||||
"profile.title": "Мой профиль"
|
||||
"profile.title": "Мой профиль",
|
||||
"profile.actions.assignRole": "Назначить роль",
|
||||
"profile.actions.assignPermission": "Назначить разрешение",
|
||||
"profile.actions.assignBranch": "Назначить филиал",
|
||||
"profile.assign.success": "Успешно назначено",
|
||||
"profile.assign.userLabel": "Пользователь (staff)"
|
||||
}
|
||||
|
||||
@@ -551,6 +551,7 @@
|
||||
"loanOrderForm.labels.cardExpMonth": "Aý",
|
||||
"loanOrderForm.labels.cardExpYear": "Ýyl",
|
||||
"loanOrderForm.labels.guarantor1Salary": "Ortaca zähmet haky",
|
||||
"loanOrderForm.labels.client": "Müşderi",
|
||||
"loanOrderForm.steps.status.subtitle": "Ýagdaý we bellik",
|
||||
"loanOrderForm.steps.loan.subtitle": "Görnüş we möçber",
|
||||
"loanOrderForm.steps.location.subtitle": "Welaýat we şahamça",
|
||||
@@ -1425,5 +1426,10 @@
|
||||
"visaMasterSberSettings.editTitle": "Sazlama üýtgetmek",
|
||||
"onlinePayments.viewTitle": "Töleg giňišleýin",
|
||||
"cardTypes.viewTitle": "Kart görnüşi giňişleýin",
|
||||
"profile.title": "Meniň profilim"
|
||||
"profile.title": "Meniň profilim",
|
||||
"profile.actions.assignRole": "Rol birikdiriň",
|
||||
"profile.actions.assignPermission": "Rugsat birikdiriň",
|
||||
"profile.actions.assignBranch": "Şahamça birikdiriň",
|
||||
"profile.assign.success": "Üstünlikli birikdirildi",
|
||||
"profile.assign.userLabel": "Ulanyjy (staff)"
|
||||
}
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useMemo } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Pencil, CheckCircle2, UserRound, X } from "lucide-react";
|
||||
import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
|
||||
import { Pencil, CheckCircle2, UserRound, X, Shield, KeyRound, Building2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { BentoGrid, BentoCard, InfoRow, CollapsibleSection, EmptyState, AuditLog } from "@/components/viewPageComponents";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { AvatarUpload } from "@/components/avatarUpload";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||
import { useAuthStore } from "@/app/store/authStore";
|
||||
import { useProfile, useUpdateProfile } from "@/features/auth/hooks/useLogin";
|
||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useInfiniteStaff } from "@/features/operators/hooks/useOperators";
|
||||
import { useAssignRoleToUser, useAssignPermissionToUser, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
type AssignDialogKind = "role" | "permission" | "branch";
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { data: profileQueryData, isLoading } = useProfile();
|
||||
const authUser = useAuthStore((s) => s.user);
|
||||
const user = profileQueryData ?? authUser;
|
||||
@@ -20,10 +38,11 @@ export default function ProfilePage() {
|
||||
const updateProfileMutation = useUpdateProfile();
|
||||
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [assignDialog, setAssignDialog] = useState<AssignDialogKind | null>(null);
|
||||
|
||||
const [roleSearch, setRoleSearch] = useState("");
|
||||
const [permSearch, setPermSearch] = useState("");
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||
|
||||
const branches = user?.branches ?? [];
|
||||
|
||||
// ── Form State for Editing ──
|
||||
const [formData, setFormData] = useState({
|
||||
@@ -36,17 +55,18 @@ export default function ProfilePage() {
|
||||
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setFormData({
|
||||
name: user.name ?? "",
|
||||
firstName: user.firstName ?? "",
|
||||
lastName: user.lastName ?? "",
|
||||
phone: user.phone ?? "",
|
||||
avatar: user.avatar ?? "",
|
||||
});
|
||||
}
|
||||
}, [user, isEditing]);
|
||||
const startEditing = () => {
|
||||
if (!user) return;
|
||||
setFormData({
|
||||
name: user.name ?? "",
|
||||
firstName: user.firstName ?? "",
|
||||
lastName: user.lastName ?? "",
|
||||
phone: user.phone ?? "",
|
||||
avatar: user.avatar ?? "",
|
||||
});
|
||||
setErrors({});
|
||||
setIsEditing(true);
|
||||
};
|
||||
|
||||
const handleFieldChange = (field: keyof typeof formData, value: string) => {
|
||||
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||
@@ -102,132 +122,138 @@ export default function ProfilePage() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* ── Title + actions ──────────────────────────────────────────────── */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-bold text-foreground leading-tight">
|
||||
{isEditing ? t("profile.editTitle", "Profili üýtgetmek") : `${t("profile.title", "Meniň profilim")}: ${user.name}`}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{!isEditing ? (
|
||||
<Button variant="outline" size="sm" className="gap-2" onClick={() => setIsEditing(true)}>
|
||||
<Pencil size={15} />
|
||||
{t("common.edit", "Üýtgetmek")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setIsEditing(false)}
|
||||
disabled={updateProfileMutation.isPending}
|
||||
>
|
||||
<X size={15} />
|
||||
{t("common.cancel", "Yza")}
|
||||
</Button>
|
||||
)}
|
||||
{/* ── Profile hero ─────────────────────────────────────────────────── */}
|
||||
{!isEditing ? (
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-card border border-border rounded-xl p-5">
|
||||
<div className="flex items-center gap-4 min-w-0">
|
||||
{user.avatar ? (
|
||||
<img
|
||||
src={user.avatar}
|
||||
alt="avatar"
|
||||
className="w-16 h-16 rounded-full border border-border bg-muted/40 object-cover shrink-0 shadow-sm"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-16 h-16 rounded-full border border-border bg-muted/40 flex items-center justify-center shrink-0 shadow-sm">
|
||||
<UserRound size={28} className="text-muted-foreground/60" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h1 className="text-lg font-bold text-foreground truncate">
|
||||
{[user.firstName, user.lastName].filter(Boolean).join(" ") || user.name}
|
||||
</h1>
|
||||
<span className="inline-flex items-center gap-1 text-xs font-medium text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full shrink-0">
|
||||
<CheckCircle2 size={12} />
|
||||
{t("common.active", "Işjeň")}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-0.5 truncate">
|
||||
@{user.name}
|
||||
{user.phone ? ` · ${user.phone}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="gap-2 shrink-0" onClick={startEditing}>
|
||||
<Pencil size={15} />
|
||||
{t("common.edit", "Üýtgetmek")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-bold text-foreground leading-tight">{t("profile.editTitle", "Profili üýtgetmek")}</h1>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setIsEditing(false)}
|
||||
disabled={updateProfileMutation.isPending}
|
||||
>
|
||||
<X size={15} />
|
||||
{t("common.cancel", "Yza")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Main content ─────────────────────────────────────────────────── */}
|
||||
{!isEditing ? (
|
||||
<>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("profile.sections.basic", "Esasy maglumatlar")}>
|
||||
<div className="flex flex-col items-center gap-4 px-4 pt-4 pb-2">
|
||||
{user.avatar ? (
|
||||
<img
|
||||
src={user.avatar}
|
||||
alt="avatar"
|
||||
className="w-20 h-20 rounded-full border border-border bg-muted/40 object-cover shrink-0 shadow-sm"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-20 h-20 rounded-full border border-border bg-muted/40 flex items-center justify-center shrink-0 shadow-sm">
|
||||
<UserRound size={32} className="text-muted-foreground/60" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 text-center">
|
||||
<p className="text-base font-semibold text-foreground truncate">
|
||||
{[user.firstName, user.lastName].filter(Boolean).join(" ") || user.name}
|
||||
</p>
|
||||
{user.phone && <p className="text-xs text-muted-foreground mt-0.5">{user.phone}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("profile.sections.account", "Hasap maglumatlary")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={user.id} />
|
||||
<InfoRow label={t("users.fields.username", "Ulanyjy ady")} value={user.name} />
|
||||
<InfoRow label={t("users.fields.firstName", "At ady")} value={user.firstName ?? "—"} />
|
||||
<InfoRow label={t("users.fields.lastName", "Familiýasy")} value={user.lastName ?? "—"} />
|
||||
<InfoRow label={t("users.fields.phone", "Telefon belgisi")} value={user.phone ?? "—"} />
|
||||
{user.role && <InfoRow label={t("users.fields.role", "Roly")} value={user.role} />}
|
||||
{user.email && <InfoRow label={t("users.fields.email", "E-poçta")} value={user.email} />}
|
||||
<InfoRow
|
||||
label={t("users.fields.createdAt", "Döredilen wagty")}
|
||||
value={user.createdAt ? new Date(user.createdAt).toLocaleString() : "—"}
|
||||
/>
|
||||
<InfoRow label={t("users.fields.isActive", "Işjeň")}>
|
||||
<div className="flex items-center gap-1.5 text-emerald-500 font-medium text-sm">
|
||||
<CheckCircle2 size={16} />
|
||||
<span>{t("common.active", "Işjeň")}</span>
|
||||
</div>
|
||||
</InfoRow>
|
||||
{user.email && <InfoRow label={t("users.fields.email", "E-poçta")} value={user.email} />}
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("profile.sections.contact", "Habarlaşmak maglumatlary")}>
|
||||
<InfoRow label={t("users.fields.firstName", "At ady")} value={user.firstName ?? "—"} />
|
||||
<InfoRow label={t("users.fields.lastName", "Familiýasy")} value={user.lastName ?? "—"} />
|
||||
<InfoRow label={t("users.fields.phone", "Telefon belgisi")} value={user.phone ?? "—"} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Rollar ───────────────────────────────────────────────────────── */}
|
||||
<CollapsibleSection title={t("users.sections.roles", "Rollar")}>
|
||||
<DataTableToolbar
|
||||
searchValue={roleSearch}
|
||||
onSearchChange={setRoleSearch}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={[]}
|
||||
columnVisibility={{}}
|
||||
onColumnVisibilityChange={() => {}}
|
||||
columnOrder={[]}
|
||||
onColumnOrderChange={() => {}}
|
||||
actionLabel={t("users.actions.addRole", "Rol birikdiriň")}
|
||||
onAction={() => {}}
|
||||
/>
|
||||
<EmptyState label={t("users.empty.roles", "Berlen kriteriýalara Rol gabat gelmedi.")} />
|
||||
</CollapsibleSection>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("profile.sections.org", "Guramaçylyk maglumatlary")}>
|
||||
<InfoRow label={t("users.fields.role", "Roly")}>
|
||||
{user.role ? (
|
||||
<Link
|
||||
to={`/settings/users/roles/${user.role.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
||||
>
|
||||
<Shield size={12} />
|
||||
{user.role.name}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
|
||||
{/* ── Rugsatlar ────────────────────────────────────────────────────── */}
|
||||
<CollapsibleSection title={t("users.sections.permissions", "Rugsatlar")}>
|
||||
<DataTableToolbar
|
||||
searchValue={permSearch}
|
||||
onSearchChange={setPermSearch}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={[]}
|
||||
columnVisibility={{}}
|
||||
onColumnVisibilityChange={() => {}}
|
||||
columnOrder={[]}
|
||||
onColumnOrderChange={() => {}}
|
||||
actionLabel={t("users.actions.addPermission", "Rugsat birikdiriň")}
|
||||
onAction={() => {}}
|
||||
/>
|
||||
<EmptyState label={t("users.empty.permissions", "Berlen kriteriýalara Rugsat gabat gelmedi.")} />
|
||||
</CollapsibleSection>
|
||||
<InfoRow label={t("users.sections.branches", "Şahamçalar")}>
|
||||
{branches.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{branches.map((b) => (
|
||||
<Link
|
||||
key={b.id}
|
||||
to={`/settings/location/branches/${b.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
||||
>
|
||||
<Building2 size={11} className="text-muted-foreground" />
|
||||
<span className="text-foreground font-medium">
|
||||
{b.name?.[lang] || b.name?.tm || b.name?.en || b.name?.ru || b.uniqueCode || b.id}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
|
||||
{/* ── Şahamçalar ───────────────────────────────────────────────────── */}
|
||||
<CollapsibleSection title={t("users.sections.branches", "Şahamçalar")}>
|
||||
<DataTableToolbar
|
||||
searchValue={branchSearch}
|
||||
onSearchChange={setBranchSearch}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={[]}
|
||||
columnVisibility={{}}
|
||||
onColumnVisibilityChange={() => {}}
|
||||
columnOrder={[]}
|
||||
onColumnOrderChange={() => {}}
|
||||
actionLabel={t("users.actions.addBranch", "Şahamça birikdiriň")}
|
||||
onAction={() => {}}
|
||||
/>
|
||||
<EmptyState label={t("users.empty.branches", "Berlen kriteriýalara Şahamça gabat gelmedi.")} />
|
||||
</CollapsibleSection>
|
||||
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}>
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
</InfoRow>
|
||||
</BentoCard>
|
||||
|
||||
{/* ── Ammallar ─────────────────────────────────────────────────────── */}
|
||||
<CollapsibleSection title={t("users.sections.audit", "Ammallar")}>
|
||||
<AuditLog logs={[]} currentPage={1} totalPages={1} totalCount={0} />
|
||||
</CollapsibleSection>
|
||||
<BentoCard title={t("profile.sections.actions", "Amallar")}>
|
||||
<div className="flex flex-wrap gap-2 px-4 py-3">
|
||||
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("role")}>
|
||||
<Shield size={14} />
|
||||
{t("profile.actions.assignRole", "Rol birikdiriň")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("permission")}>
|
||||
<KeyRound size={14} />
|
||||
{t("profile.actions.assignPermission", "Rugsat birikdiriň")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("branch")}>
|
||||
<Building2 size={14} />
|
||||
{t("profile.actions.assignBranch", "Şahamça birikdiriň")}
|
||||
</Button>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</>
|
||||
) : (
|
||||
<div className="w-full">
|
||||
@@ -288,6 +314,175 @@ export default function ProfilePage() {
|
||||
</BentoCard>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Assign dialog (staff user + role/permission/branch) ─────────────── */}
|
||||
{assignDialog && <AssignDialog kind={assignDialog} onClose={() => setAssignDialog(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Assign dialog ────────────────────────────────────────────────────────────
|
||||
|
||||
const ASSIGN_DIALOG_TITLES: Record<AssignDialogKind, string> = {
|
||||
role: "profile.actions.assignRole",
|
||||
permission: "profile.actions.assignPermission",
|
||||
branch: "profile.actions.assignBranch",
|
||||
};
|
||||
|
||||
const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
||||
role: "users.fields.role",
|
||||
permission: "users.sections.permissions",
|
||||
branch: "users.sections.branches",
|
||||
};
|
||||
|
||||
/**
|
||||
* Dialog for assigning a role / permission / branch to a staff user.
|
||||
* Two selects: target user (GET /users/staff) and the resource to assign.
|
||||
*/
|
||||
function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () => void }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const [userValue, setUserValue] = useState("");
|
||||
const [resourceSearch, setResourceSearch] = useState("");
|
||||
const [resourceValue, setResourceValue] = useState("");
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
|
||||
const staffQuery = useInfiniteStaff(userSearch);
|
||||
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
||||
const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission");
|
||||
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
||||
|
||||
const roleMutation = useAssignRoleToUser();
|
||||
const permissionMutation = useAssignPermissionToUser();
|
||||
const branchMutation = useAssignBranchToUser();
|
||||
const isPending = roleMutation.isPending || permissionMutation.isPending || branchMutation.isPending;
|
||||
|
||||
const staffOptions: InfiniteSelectOption[] = useMemo(
|
||||
() =>
|
||||
(staffQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({
|
||||
value: String(u.id),
|
||||
label: [u.firstName, u.lastName].filter(Boolean).join(" ") || u.name || u.username || String(u.id),
|
||||
})),
|
||||
[staffQuery.data],
|
||||
);
|
||||
|
||||
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
if (kind === "role") {
|
||||
return (rolesQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.roles ?? [])
|
||||
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) }));
|
||||
}
|
||||
if (kind === "permission") {
|
||||
return (permissionsQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.permissions ?? [])
|
||||
.map((perm) => ({ value: String(perm.id), label: perm.name || perm.code || String(perm.id) }));
|
||||
}
|
||||
return (branchesQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.branches ?? [])
|
||||
.map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name?.[lang] || b.name?.tm || b.name?.en || b.name?.ru || b.uniqueCode || String(b.id),
|
||||
}));
|
||||
}, [kind, rolesQuery.data, permissionsQuery.data, branchesQuery.data, lang]);
|
||||
|
||||
const resourceLoading =
|
||||
kind === "role" ? rolesQuery.isLoading : kind === "permission" ? permissionsQuery.isLoading : branchesQuery.isLoading;
|
||||
const resourceLoadingMore =
|
||||
kind === "role"
|
||||
? rolesQuery.isFetchingNextPage
|
||||
: kind === "permission"
|
||||
? permissionsQuery.isFetchingNextPage
|
||||
: branchesQuery.isFetchingNextPage;
|
||||
const resourceHasNextPage =
|
||||
kind === "role" ? !!rolesQuery.hasNextPage : kind === "permission" ? !!permissionsQuery.hasNextPage : !!branchesQuery.hasNextPage;
|
||||
const loadMoreResources = () => {
|
||||
if (kind === "role") rolesQuery.fetchNextPage();
|
||||
else if (kind === "permission") permissionsQuery.fetchNextPage();
|
||||
else branchesQuery.fetchNextPage();
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!userValue || !resourceValue) {
|
||||
setError(t("common.errors.required", "Meýdança hökmany doldurylmaly"));
|
||||
return;
|
||||
}
|
||||
setError(undefined);
|
||||
|
||||
const userId = Number(userValue);
|
||||
const resourceId = Number(resourceValue);
|
||||
const onSuccess = () => {
|
||||
setUserValue("");
|
||||
setResourceValue("");
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (kind === "role") roleMutation.mutate({ userId, roleId: resourceId }, { onSuccess });
|
||||
else if (kind === "permission") permissionMutation.mutate({ userId, permissionId: resourceId }, { onSuccess });
|
||||
else branchMutation.mutate({ userId, branchId: resourceId }, { onSuccess });
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<AlertDialogContent className="max-w-md sm:max-w-md">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogTitle>
|
||||
<VisuallyHidden.Root>
|
||||
<AlertDialogDescription>{t(ASSIGN_DIALOG_TITLES[kind])}</AlertDialogDescription>
|
||||
</VisuallyHidden.Root>
|
||||
</AlertDialogHeader>
|
||||
|
||||
<div className="space-y-3">
|
||||
<InfiniteSelect
|
||||
required
|
||||
label={t("profile.assign.userLabel", "Ulanyjy (staff)")}
|
||||
value={userValue}
|
||||
onChange={(v) => {
|
||||
setUserValue(v);
|
||||
if (error) setError(undefined);
|
||||
}}
|
||||
options={staffOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={staffQuery.isLoading}
|
||||
isLoadingMore={staffQuery.isFetchingNextPage}
|
||||
hasNextPage={!!staffQuery.hasNextPage}
|
||||
onLoadMore={() => staffQuery.fetchNextPage()}
|
||||
searchValue={userSearch}
|
||||
onSearchChange={setUserSearch}
|
||||
/>
|
||||
|
||||
<InfiniteSelect
|
||||
required
|
||||
label={t(ASSIGN_DIALOG_FIELD_LABELS[kind])}
|
||||
value={resourceValue}
|
||||
onChange={(v) => {
|
||||
setResourceValue(v);
|
||||
if (error) setError(undefined);
|
||||
}}
|
||||
error={error}
|
||||
options={resourceOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={resourceLoading}
|
||||
isLoadingMore={resourceLoadingMore}
|
||||
hasNextPage={resourceHasNextPage}
|
||||
onLoadMore={loadMoreResources}
|
||||
searchValue={resourceSearch}
|
||||
onSearchChange={setResourceSearch}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AlertDialogFooter>
|
||||
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
|
||||
{t("common.cancel", "Yza")}
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleSubmit} disabled={!userValue || !resourceValue || isPending}>
|
||||
{t("common.save", "Ýatda sakla")}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user