fixed ui, connected role user, branch user permissions user api
This commit is contained in:
1 parent
d230b12d6a
commit
f00d2abcac
20 files changed
+906
-391
No files matched your search
@@ -2,6 +2,19 @@ import { create } from "zustand";
|
|||||||
import { persist } from "zustand/middleware";
|
import { persist } from "zustand/middleware";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import type { ApiSuccessResponse } from "@/lib/api/client";
|
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 {
|
export interface AuthUser {
|
||||||
id?: string | number;
|
id?: string | number;
|
||||||
@@ -10,8 +23,9 @@ export interface AuthUser {
|
|||||||
firstName?: string;
|
firstName?: string;
|
||||||
lastName?: string;
|
lastName?: string;
|
||||||
phone?: string;
|
phone?: string;
|
||||||
role?: string;
|
role?: AuthUserRole;
|
||||||
avatar?: string;
|
avatar?: string;
|
||||||
|
branches?: AuthUserBranch[];
|
||||||
createdAt?: string;
|
createdAt?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-25
@@ -1,49 +1,38 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { Slot } from "radix-ui"
|
import { Slot } from "radix-ui";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
const badgeVariants = cva(
|
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: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||||
secondary:
|
secondary: "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||||
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
|
||||||
destructive:
|
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",
|
"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:
|
outline: "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||||
"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",
|
||||||
ghost:
|
|
||||||
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: "default",
|
variant: "default",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
function Badge({
|
function Badge({
|
||||||
className,
|
className,
|
||||||
variant = "default",
|
variant = "default",
|
||||||
asChild = false,
|
asChild = false,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"span"> &
|
}: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
const Comp = asChild ? Slot.Root : "span";
|
||||||
const Comp = asChild ? Slot.Root : "span"
|
|
||||||
|
|
||||||
return (
|
return <Comp data-slot="badge" data-variant={variant} className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||||
<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 { useBranches } from "@/features/branches/hooks/useBranches";
|
||||||
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
||||||
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
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 ────────────────────────────────────────────────────────────────────
|
// ─── 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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<BentoGrid cols={3}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
<BentoCard title={t("cardPin.titles.name") || "Ady we familiýasy"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardPin.field.customerName", "Ady")}
|
label={t("cardPin.field.customerName", "Ady")}
|
||||||
@@ -204,8 +225,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
|||||||
placeholder={t("cardPin.field.customerName", "Ady")}
|
placeholder={t("cardPin.field.customerName", "Ady")}
|
||||||
error={errors.customerName}
|
error={errors.customerName}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardPin.field.customerSurname", "Familiýasy")}
|
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")}
|
placeholder={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||||
error={errors.customerSurname}
|
error={errors.customerSurname}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
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")}
|
placeholder={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
|
||||||
|
|
||||||
<BentoGrid cols={3}>
|
<BentoCard title={t("cardPin.titles.contactInfo") || "Şahsy we habarlaşmak"}>
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="date"
|
type="date"
|
||||||
label={t("cardPin.field.bornAt", "Doglan güni")}
|
label={t("cardPin.field.bornAt", "Doglan güni")}
|
||||||
@@ -236,27 +251,29 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
|||||||
onChange={(v) => set("bornAt", v)}
|
onChange={(v) => set("bornAt", v)}
|
||||||
error={errors.bornAt}
|
error={errors.bornAt}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="phone"
|
||||||
label={t("cardPin.field.phone", "Telefon")}
|
label={t("cardPin.field.phone", "Telefon")}
|
||||||
required
|
required
|
||||||
value={form.phone}
|
value={form.phone}
|
||||||
onChange={(v) => set("phone", v)}
|
onChange={(v) => set("phone", v)}
|
||||||
placeholder={t("cardPin.field.phone", "Telefon")}
|
placeholder={t("loanOrderForm.placeholders.phone") || "61 097651"}
|
||||||
error={errors.phone}
|
error={errors.phone}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
<InfiniteSelect
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
|
||||||
type="number"
|
|
||||||
label={t("cardPin.field.userId", "Ulanyjy ID")}
|
label={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||||
required
|
required
|
||||||
value={form.userId}
|
value={form.userId}
|
||||||
onChange={(v) => set("userId", v)}
|
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}
|
error={errors.userId}
|
||||||
|
loading={clientsQuery.isLoading}
|
||||||
|
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||||
|
hasNextPage={!!clientsQuery.hasNextPage}
|
||||||
|
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||||
|
searchValue={clientSearch}
|
||||||
|
onSearchChange={setClientSearch}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
@@ -267,67 +284,70 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
|||||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={1}>
|
||||||
<BentoCard>
|
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Pasport maglumatlary"}>
|
||||||
<FormInput
|
<div className="grid grid-cols-2 gap-4">
|
||||||
type="select"
|
<FormInput
|
||||||
label={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
type="select"
|
||||||
required
|
label={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||||
value={form.passportSerie}
|
required
|
||||||
onChange={(v) => set("passportSerie", v)}
|
value={form.passportSerie}
|
||||||
options={PASSPORT_SERIES_OPTIONS}
|
onChange={(v) => set("passportSerie", v)}
|
||||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
options={PASSPORT_SERIES_OPTIONS}
|
||||||
error={errors.passportSerie}
|
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||||
/>
|
error={errors.passportSerie}
|
||||||
</BentoCard>
|
/>
|
||||||
<BentoCard>
|
<FormInput
|
||||||
<FormInput
|
type="text"
|
||||||
type="text"
|
label={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||||
label={t("cardPin.field.passportId", "Pasport belgisi")}
|
required
|
||||||
required
|
value={form.passportId}
|
||||||
value={form.passportId}
|
onChange={(v) => set("passportId", v)}
|
||||||
onChange={(v) => set("passportId", v)}
|
placeholder={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||||
placeholder={t("cardPin.field.passportId", "Pasport belgisi")}
|
error={errors.passportId}
|
||||||
error={errors.passportId}
|
/>
|
||||||
/>
|
</div>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
<BentoGrid cols={4}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="text"
|
label={t("cardPin.field.passportOne", "Pasport (sahypa 1)")}
|
||||||
label={t("cardPin.field.passportOne", "Pasport 1")}
|
|
||||||
value={form.passportOne}
|
value={form.passportOne}
|
||||||
onChange={(v) => set("passportOne", v)}
|
onChange={(v) => set("passportOne", v)}
|
||||||
placeholder={t("cardPin.field.passportOne", "Pasport 1")}
|
error={errors.passportOne}
|
||||||
|
accept="image/*"
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="text"
|
label={t("cardPin.field.passportTwo", "Pasport (2-3-nji sahypa)")}
|
||||||
label={t("cardPin.field.passportTwo", "Pasport 2")}
|
|
||||||
value={form.passportTwo}
|
value={form.passportTwo}
|
||||||
onChange={(v) => set("passportTwo", v)}
|
onChange={(v) => set("passportTwo", v)}
|
||||||
placeholder={t("cardPin.field.passportTwo", "Pasport 2")}
|
error={errors.passportTwo}
|
||||||
|
accept="image/*"
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="text"
|
label={t("cardPin.field.passportThree", "Pasport (8-9 sahypa)")}
|
||||||
label={t("cardPin.field.passportThree", "Pasport 3")}
|
|
||||||
value={form.passportThree}
|
value={form.passportThree}
|
||||||
onChange={(v) => set("passportThree", v)}
|
onChange={(v) => set("passportThree", v)}
|
||||||
placeholder={t("cardPin.field.passportThree", "Pasport 3")}
|
error={errors.passportThree}
|
||||||
|
accept="image/*"
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="text"
|
label={t("cardPin.field.passportFour", "Pasport (32-nji sahypa)")}
|
||||||
label={t("cardPin.field.passportFour", "Pasport 4")}
|
|
||||||
value={form.passportFour}
|
value={form.passportFour}
|
||||||
onChange={(v) => set("passportFour", v)}
|
onChange={(v) => set("passportFour", v)}
|
||||||
placeholder={t("cardPin.field.passportFour", "Pasport 4")}
|
error={errors.passportFour}
|
||||||
|
accept="image/*"
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
@@ -347,9 +367,9 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
|||||||
const updateMutation = useUpdateCardPin(initialData?.id ?? 0);
|
const updateMutation = useUpdateCardPin(initialData?.id ?? 0);
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 100 });
|
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
||||||
const { data: branchesData } = useBranches({ page: 1, limit: 100 });
|
const { data: branchesData } = useBranches({ page: 1, limit: 25 });
|
||||||
const { data: districtsData } = useDistricts({ page: 1, limit: 100 });
|
const { data: districtsData } = useDistricts({ page: 1, limit: 25 });
|
||||||
|
|
||||||
const cardTypeOptions = useMemo(
|
const cardTypeOptions = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -533,7 +553,7 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
|||||||
|
|
||||||
{/* Step content */}
|
{/* Step content */}
|
||||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
{currentStep === 1 && <StepPersonal {...stepProps} initialData={initialData} />}
|
||||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||||
|
|
||||||
{/* Actions */}
|
{/* Actions */}
|
||||||
@@ -566,7 +586,7 @@ function mapInitial(data: CardPinOrder): Partial<CardPinFormData> {
|
|||||||
customerSurname: data.customerSurname ?? "",
|
customerSurname: data.customerSurname ?? "",
|
||||||
customerPatronicName: data.customerPatronicName ?? "",
|
customerPatronicName: data.customerPatronicName ?? "",
|
||||||
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||||
phone: data.phone ?? "",
|
phone: formatFromApiPhone(data.phone),
|
||||||
passportSerie: data.passportSerie ?? "",
|
passportSerie: data.passportSerie ?? "",
|
||||||
passportId: data.passportId ?? "",
|
passportId: data.passportId ?? "",
|
||||||
passportOne: data.passportOne ?? "",
|
passportOne: data.passportOne ?? "",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import type { CreateCardPinPayload } from "../api/cardPinApi";
|
import type { CreateCardPinPayload } from "../api/cardPinApi";
|
||||||
|
import { formatToApiPhone } from "@/lib/utils";
|
||||||
|
|
||||||
const optional = () => z.string().default("");
|
const optional = () => z.string().default("");
|
||||||
|
|
||||||
@@ -101,7 +102,7 @@ export function buildPayload(data: CardPinFormData): CreateCardPinPayload {
|
|||||||
branchId: Number(data.branchId),
|
branchId: Number(data.branchId),
|
||||||
cardTypeId: Number(data.cardTypeId),
|
cardTypeId: Number(data.cardTypeId),
|
||||||
cardNumber: data.cardNumber.trim(),
|
cardNumber: data.cardNumber.trim(),
|
||||||
phone: data.phone.trim(),
|
phone: formatToApiPhone(data.phone),
|
||||||
passportSerie: data.passportSerie.trim(),
|
passportSerie: data.passportSerie.trim(),
|
||||||
passportId: data.passportId.trim(),
|
passportId: data.passportId.trim(),
|
||||||
passportOne: data.passportOne.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 { useForm } from "react-hook-form";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { FormInput } from "@/components/formInput";
|
import { FormInput } from "@/components/formInput";
|
||||||
import { FormActions } from "@/components/formActions";
|
import { FormActions } from "@/components/formActions";
|
||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||||
import type { Card } from "../api/cardTransactionsApi";
|
import type { Card } from "../api/cardTransactionsApi";
|
||||||
import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions";
|
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 { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema";
|
||||||
import type { CardTransactionFormData } from "../schemas/cardTransaction.schema";
|
import type { CardTransactionFormData } from "../schemas/cardTransaction.schema";
|
||||||
|
|
||||||
@@ -45,9 +49,41 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
// ─── Component ────────────────────────────────────────────────────────────────
|
// ─── Component ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) {
|
export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) {
|
||||||
const { t } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const navigate = useNavigate();
|
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 {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -132,11 +168,12 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
|||||||
|
|
||||||
{/* Type */}
|
{/* Type */}
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="searchable-select"
|
||||||
label={t("Card type", "Kart görnüşi")}
|
label={t("Card type", "Kart görnüşi")}
|
||||||
value={form.type}
|
value={form.type}
|
||||||
onChange={setField("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)}
|
error={errMsg(errors.type)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
@@ -152,15 +189,21 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
|||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* User ID */}
|
{/* User (Client) */}
|
||||||
<FormInput
|
<InfiniteSelect
|
||||||
type="number"
|
|
||||||
label={t("User ID", "Ulanyjy ID")}
|
label={t("User ID", "Ulanyjy ID")}
|
||||||
value={form.userId}
|
|
||||||
onChange={setField("userId")}
|
|
||||||
placeholder={t("User ID", "Ulanyjy ID")}
|
|
||||||
error={errMsg(errors.userId)}
|
|
||||||
required
|
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 */}
|
{/* Expiry Month + Year side by side */}
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ export const clientsApi = {
|
|||||||
getClients: async (params: ClientsListParams = {}, signal?: AbortSignal): Promise<ClientsListResponse> => {
|
getClients: async (params: ClientsListParams = {}, signal?: AbortSignal): Promise<ClientsListResponse> => {
|
||||||
const { page, limit, search, isActive } = params;
|
const { page, limit, search, isActive } = params;
|
||||||
const { data } = await apiClient.get<ClientsListResponse>("/users/clients", {
|
const { data } = await apiClient.get<ClientsListResponse>("/users/clients", {
|
||||||
params: { page, limit, username: search, isActive },
|
params: { page, limit, username: search || undefined, isActive: isActive || undefined },
|
||||||
signal,
|
signal,
|
||||||
});
|
});
|
||||||
return data;
|
return data;
|
||||||
|
|||||||
@@ -120,6 +120,7 @@ export interface LoanOrderPayload {
|
|||||||
loanType: string;
|
loanType: string;
|
||||||
region: string;
|
region: string;
|
||||||
branch: string;
|
branch: string;
|
||||||
|
userId: string;
|
||||||
firstName: string;
|
firstName: string;
|
||||||
lastName: string;
|
lastName: string;
|
||||||
patronicName?: string;
|
patronicName?: string;
|
||||||
@@ -352,6 +353,7 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder {
|
|||||||
guarantor2CardExpMonth: order.guarantor2CardMonth ?? "",
|
guarantor2CardExpMonth: order.guarantor2CardMonth ?? "",
|
||||||
guarantor2CardExpYear: order.guarantor2CardYear ?? "",
|
guarantor2CardExpYear: order.guarantor2CardYear ?? "",
|
||||||
guarantor2Note: order.guarantor2Note ?? "",
|
guarantor2Note: order.guarantor2Note ?? "",
|
||||||
|
loanHistory: order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : "",
|
||||||
createdBy: order.userName ?? "",
|
createdBy: order.userName ?? "",
|
||||||
fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "),
|
fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "),
|
||||||
registeredAddress: order.passportAddress ?? "",
|
registeredAddress: order.passportAddress ?? "",
|
||||||
@@ -433,8 +435,8 @@ function mapPayloadToBackend(payload: LoanOrderPayload | Partial<LoanOrderPayloa
|
|||||||
status: payload.status ?? "pending",
|
status: payload.status ?? "pending",
|
||||||
satisfiable: "yes",
|
satisfiable: "yes",
|
||||||
source: "web",
|
source: "web",
|
||||||
loanOrderRequiredDocId: 0,
|
loanOrderRequiredDocId: payload.loanHistory ? Number(payload.loanHistory) : 0,
|
||||||
userId: 0,
|
userId: toNum(payload.userId) ?? 0,
|
||||||
uniqueId: "",
|
uniqueId: "",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ import { useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
|
|||||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||||
import { formatFromApiDate, formatFromApiPhone } from "@/lib/utils";
|
import { formatFromApiDate, formatFromApiPhone } from "@/lib/utils";
|
||||||
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
||||||
|
import { useGetRequiredDocuments } from "@/features/requiredDocuments/hooks/useRequiredDocuments";
|
||||||
|
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||||
|
|
||||||
// ─── Static options ───────────────────────────────────────────────────────────
|
// ─── 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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<BentoGrid cols={3}>
|
<BentoGrid cols={1}>
|
||||||
<BentoCard>
|
<BentoCard title={t("loanOrderForm.titles.personalName") || "Şahsy maglumatlar"}>
|
||||||
<FormInput
|
<InfiniteSelect
|
||||||
type="text"
|
label={t("loanOrderForm.labels.client") || "Müşderi"}
|
||||||
label={t("Name") || "Ady"}
|
|
||||||
required
|
required
|
||||||
value={form.firstName}
|
value={form.userId}
|
||||||
onChange={(v) => set("firstName", v)}
|
onChange={(v) => set("userId", v)}
|
||||||
placeholder={t("Name") || "Ady"}
|
options={clientOptions}
|
||||||
error={errors.firstName}
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||||
/>
|
error={errors.userId}
|
||||||
</BentoCard>
|
loading={clientsQuery.isLoading}
|
||||||
<BentoCard>
|
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||||
<FormInput
|
hasNextPage={!!clientsQuery.hasNextPage}
|
||||||
type="text"
|
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||||
label={t("Surname") || "Familiýasy"}
|
searchValue={clientSearch}
|
||||||
required
|
onSearchChange={setClientSearch}
|
||||||
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"}
|
|
||||||
/>
|
/>
|
||||||
|
<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>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
<BentoGrid cols={3}>
|
<BentoGrid cols={1}>
|
||||||
<BentoCard>
|
<BentoCard title={t("loanOrderForm.titles.personalDetails") || "Bilim we maşgala ýagdaýy"}>
|
||||||
<FormInput
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||||
type="select"
|
<FormInput
|
||||||
label={t("Education") || "Bilimi"}
|
type="select"
|
||||||
required
|
label={t("Education") || "Bilimi"}
|
||||||
value={form.education}
|
required
|
||||||
onChange={(v) => set("education", v)}
|
value={form.education}
|
||||||
options={EDUCATION_OPTIONS}
|
onChange={(v) => set("education", v)}
|
||||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
options={EDUCATION_OPTIONS}
|
||||||
error={errors.education}
|
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||||
/>
|
error={errors.education}
|
||||||
</BentoCard>
|
/>
|
||||||
<BentoCard>
|
<FormInput
|
||||||
<FormInput
|
type="select"
|
||||||
type="select"
|
label={t("Marriage status") || "Maşgala ýagdaýy"}
|
||||||
label={t("Marriage status") || "Maşgala ýagdaýy"}
|
required
|
||||||
required
|
value={form.marriageStatus}
|
||||||
value={form.marriageStatus}
|
onChange={(v) => set("marriageStatus", v)}
|
||||||
onChange={(v) => set("marriageStatus", v)}
|
options={MARRIAGE_OPTIONS}
|
||||||
options={MARRIAGE_OPTIONS}
|
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
error={errors.marriageStatus}
|
||||||
error={errors.marriageStatus}
|
/>
|
||||||
/>
|
<FormInput
|
||||||
</BentoCard>
|
type="date"
|
||||||
<BentoCard>
|
label={t("Date of birth") || "Doglan güni"}
|
||||||
<FormInput
|
required
|
||||||
type="date"
|
value={form.dateOfBirth}
|
||||||
label={t("Date of birth") || "Doglan güni"}
|
onChange={(v) => set("dateOfBirth", v)}
|
||||||
required
|
error={errors.dateOfBirth}
|
||||||
value={form.dateOfBirth}
|
/>
|
||||||
onChange={(v) => set("dateOfBirth", v)}
|
</div>
|
||||||
error={errors.dateOfBirth}
|
|
||||||
/>
|
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
<BentoCard title={t("loanOrderForm.titles.residence") || "Ýaşaýyş salgysy"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("Residence (passport)") || "Ýazgy edilen salgyňyz"}
|
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"}
|
placeholder={t("loanOrderForm.placeholders.residence") || "Ýazgy edilen salgy"}
|
||||||
error={errors.residence}
|
error={errors.residence}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("Current Residence") || "Häzirki ýaşaýyş ýeri"}
|
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"}
|
placeholder={t("loanOrderForm.placeholders.currentResidence") || "Häzirki ýaşaýyş ýeri"}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard span="full">
|
|
||||||
|
<BentoCard title={t("loanOrderForm.titles.loanHistory") || "Karz taryhy"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="searchable-select"
|
type="select"
|
||||||
label={t("Loan history") || "Karz taryhy"}
|
label={t("Loan history") || "Karz taryhy"}
|
||||||
value={form.loanHistory}
|
value={form.loanHistory}
|
||||||
onChange={(v) => set("loanHistory", v)}
|
onChange={(v) => set("loanHistory", v)}
|
||||||
options={[]}
|
options={loanHistoryOptions}
|
||||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
@@ -1174,7 +1218,7 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) {
|
|||||||
{currentStep === 0 && <StepStatus {...stepProps} />}
|
{currentStep === 0 && <StepStatus {...stepProps} />}
|
||||||
{currentStep === 1 && <StepLoan {...stepProps} initialData={initialData} />}
|
{currentStep === 1 && <StepLoan {...stepProps} initialData={initialData} />}
|
||||||
{currentStep === 2 && <StepLocation {...stepProps} initialData={initialData} />}
|
{currentStep === 2 && <StepLocation {...stepProps} initialData={initialData} />}
|
||||||
{currentStep === 3 && <StepPersonal {...stepProps} />}
|
{currentStep === 3 && <StepPersonal {...stepProps} initialData={initialData} />}
|
||||||
{currentStep === 4 && <StepCard {...stepProps} />}
|
{currentStep === 4 && <StepCard {...stepProps} />}
|
||||||
{currentStep === 5 && <StepPassport {...stepProps} mode={mode} />}
|
{currentStep === 5 && <StepPassport {...stepProps} mode={mode} />}
|
||||||
{currentStep === 6 && <StepContact {...stepProps} />}
|
{currentStep === 6 && <StepContact {...stepProps} />}
|
||||||
@@ -1206,6 +1250,7 @@ function mapInitial(order: LoanOrder): Partial<LoanOrderFormData> {
|
|||||||
loanType: order.loanTypeId != null ? String(order.loanTypeId) : "",
|
loanType: order.loanTypeId != null ? String(order.loanTypeId) : "",
|
||||||
region: order.region ?? "AG",
|
region: order.region ?? "AG",
|
||||||
branch: order.branchId != null ? String(order.branchId) : "",
|
branch: order.branchId != null ? String(order.branchId) : "",
|
||||||
|
userId: order.createdById != null ? String(order.createdById) : "",
|
||||||
firstName: order.firstName ?? "",
|
firstName: order.firstName ?? "",
|
||||||
lastName: order.lastName ?? "",
|
lastName: order.lastName ?? "",
|
||||||
patronicName: order.patronicName ?? "",
|
patronicName: order.patronicName ?? "",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export const loanOrderFormSchema = z.object({
|
|||||||
loanType: z.string().min(1, "validation.required"),
|
loanType: z.string().min(1, "validation.required"),
|
||||||
region: z.string().min(1, "validation.required"),
|
region: z.string().min(1, "validation.required"),
|
||||||
branch: 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"),
|
firstName: z.string().min(1, "validation.required"),
|
||||||
lastName: z.string().min(1, "validation.required"),
|
lastName: z.string().min(1, "validation.required"),
|
||||||
patronicName: z.string().optional(),
|
patronicName: z.string().optional(),
|
||||||
@@ -139,6 +140,7 @@ export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderFormData>>>
|
|||||||
1: loanOrderFormSchema.pick({ loanType: true, loanAmount: true }),
|
1: loanOrderFormSchema.pick({ loanType: true, loanAmount: true }),
|
||||||
2: loanOrderFormSchema.pick({ region: true, branch: true }),
|
2: loanOrderFormSchema.pick({ region: true, branch: true }),
|
||||||
3: loanOrderFormSchema.pick({
|
3: loanOrderFormSchema.pick({
|
||||||
|
userId: true,
|
||||||
firstName: true,
|
firstName: true,
|
||||||
lastName: true,
|
lastName: true,
|
||||||
education: true,
|
education: true,
|
||||||
@@ -228,6 +230,7 @@ export const DEFAULT_FORM_VALUES: LoanOrderFormData = {
|
|||||||
loanType: "",
|
loanType: "",
|
||||||
region: "AG",
|
region: "AG",
|
||||||
branch: "",
|
branch: "",
|
||||||
|
userId: "",
|
||||||
firstName: "",
|
firstName: "",
|
||||||
lastName: "",
|
lastName: "",
|
||||||
patronicName: "",
|
patronicName: "",
|
||||||
@@ -291,6 +294,7 @@ export function buildPayload(data: LoanOrderFormData) {
|
|||||||
loanType: data.loanType,
|
loanType: data.loanType,
|
||||||
region: data.region,
|
region: data.region,
|
||||||
branch: data.branch,
|
branch: data.branch,
|
||||||
|
userId: data.userId,
|
||||||
firstName: data.firstName,
|
firstName: data.firstName,
|
||||||
lastName: data.lastName,
|
lastName: data.lastName,
|
||||||
patronicName: data.patronicName || undefined,
|
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 { toast } from "sonner";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
@@ -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 ────────────────────────────────────────────────────────
|
// ─── useCreateOperator ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateOperator() {
|
export function useCreateOperator() {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import { useForm } from "react-hook-form";
|
|||||||
|
|
||||||
import { FormInput, type SelectOption } from "@/components/formInput";
|
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||||
import { FormActions } from "@/components/formActions";
|
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 { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import type { CardOrder } from "../api/orderNewCardApi";
|
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 { useCardReasons } from "@/features/cardReasons/hooks/useCardReasons";
|
||||||
import { useBranches } from "@/features/branches/hooks/useBranches";
|
import { useBranches } from "@/features/branches/hooks/useBranches";
|
||||||
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
||||||
|
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||||
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
@@ -103,6 +106,7 @@ interface StepContentProps {
|
|||||||
cardStateOptions: SelectOption[];
|
cardStateOptions: SelectOption[];
|
||||||
branchOptions: SelectOption[];
|
branchOptions: SelectOption[];
|
||||||
districtOptions: SelectOption[];
|
districtOptions: SelectOption[];
|
||||||
|
mode: "create" | "edit";
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||||
@@ -222,8 +226,8 @@ function StepCard({ form, errors, set, t, cardTypeOptions, cardStateOptions, bra
|
|||||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<BentoGrid cols={3}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
<BentoCard title={t("cardOrder.titles.name") || "Ady we familiýasy"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.customerName", "Ady")}
|
label={t("cardOrder.field.customerName", "Ady")}
|
||||||
@@ -233,8 +237,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
|||||||
placeholder={t("cardOrder.field.customerName", "Ady")}
|
placeholder={t("cardOrder.field.customerName", "Ady")}
|
||||||
error={errors.customerName}
|
error={errors.customerName}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.customerSurname", "Familiýasy")}
|
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")}
|
placeholder={t("cardOrder.field.customerSurname", "Familiýasy")}
|
||||||
error={errors.customerSurname}
|
error={errors.customerSurname}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
label={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
||||||
@@ -253,11 +253,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
|||||||
onChange={(v) => set("customerPatronicName", v)}
|
onChange={(v) => set("customerPatronicName", v)}
|
||||||
placeholder={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
placeholder={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
</BentoGrid>
|
|
||||||
|
|
||||||
<BentoGrid cols={3}>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.oldSurname", "Köne familiýaňyz (eger üýtgän bolsa)")}
|
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")}
|
placeholder={t("cardOrder.field.oldSurname", "Köne familiýa")}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
|
||||||
|
<BentoCard title={t("cardOrder.titles.birthInfo") || "Doglan maglumaty"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="date"
|
type="date"
|
||||||
label={t("cardOrder.field.bornAt", "Doglan güni")}
|
label={t("cardOrder.field.bornAt", "Doglan güni")}
|
||||||
@@ -274,8 +270,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
|||||||
onChange={(v) => set("bornAt", v)}
|
onChange={(v) => set("bornAt", v)}
|
||||||
error={errors.bornAt}
|
error={errors.bornAt}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
label={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
||||||
@@ -283,11 +277,6 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
|||||||
onChange={(v) => set("bornPlace", v)}
|
onChange={(v) => set("bornPlace", v)}
|
||||||
placeholder={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
placeholder={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
</BentoGrid>
|
|
||||||
|
|
||||||
<BentoGrid cols={3}>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.citizenship", "Raýatlyk")}
|
label={t("cardOrder.field.citizenship", "Raýatlyk")}
|
||||||
@@ -298,36 +287,39 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
|||||||
error={errors.citizenship}
|
error={errors.citizenship}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
</BentoGrid>
|
||||||
<FormInput
|
|
||||||
type="text"
|
<BentoGrid cols={1}>
|
||||||
label={t("cardOrder.field.phone", "Telefon")}
|
<BentoCard title={t("cardOrder.titles.contact") || "Habarlaşmak"}>
|
||||||
required
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
value={form.phone}
|
<FormInput
|
||||||
onChange={(v) => set("phone", v)}
|
type="text"
|
||||||
placeholder={t("cardOrder.field.phone", "Telefon")}
|
label={t("cardOrder.field.phone", "Telefon")}
|
||||||
error={errors.phone}
|
required
|
||||||
/>
|
value={form.phone}
|
||||||
</BentoCard>
|
onChange={(v) => set("phone", v)}
|
||||||
<BentoCard>
|
placeholder={t("cardOrder.field.phone", "Telefon")}
|
||||||
<FormInput
|
error={errors.phone}
|
||||||
type="text"
|
/>
|
||||||
label={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
<FormInput
|
||||||
value={form.phoneAdditional}
|
type="text"
|
||||||
onChange={(v) => set("phoneAdditional", v)}
|
label={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||||
placeholder={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>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
function StepPassport({ form, errors, set, t, mode }: StepContentProps) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<BentoGrid cols={3}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Pasport maglumatlary"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
label={t("cardOrder.field.passportSerie", "Pasport seriýasy")}
|
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ň"}
|
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||||
error={errors.passportSerie}
|
error={errors.passportSerie}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.passportId", "Pasport belgisi")}
|
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")}
|
placeholder={t("cardOrder.field.passportId", "Pasport belgisi")}
|
||||||
error={errors.passportId}
|
error={errors.passportId}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="date"
|
type="date"
|
||||||
label={t("cardOrder.field.passportGivenAt", "Pasport berlen senesi")}
|
label={t("cardOrder.field.passportGivenAt", "Pasport berlen senesi")}
|
||||||
@@ -359,10 +347,8 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
|||||||
error={errors.passportGivenAt}
|
error={errors.passportGivenAt}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
|
||||||
|
|
||||||
<BentoGrid cols={2}>
|
<BentoCard title={t("cardOrder.titles.passportIssuer") || "Berlen ýeri"}>
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
label={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
||||||
@@ -370,8 +356,6 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
|||||||
onChange={(v) => set("passportGivenBy", v)}
|
onChange={(v) => set("passportGivenBy", v)}
|
||||||
placeholder={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
placeholder={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardOrder.field.passportAddress", "Pasport salgysy")}
|
label={t("cardOrder.field.passportAddress", "Pasport salgysy")}
|
||||||
@@ -382,41 +366,52 @@ function StepPassport({ form, errors, set, t }: StepContentProps) {
|
|||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
<BentoGrid cols={4}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="text"
|
label={
|
||||||
label={t("cardOrder.field.passportOne", "Pasport 1")}
|
mode === "edit"
|
||||||
|
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)"
|
||||||
|
: t("Passport (page 1)") || "Pasport (sahypa 1)"
|
||||||
|
}
|
||||||
value={form.passportOne}
|
value={form.passportOne}
|
||||||
onChange={(v) => set("passportOne", v)}
|
onChange={(v) => set("passportOne", v)}
|
||||||
placeholder={t("cardOrder.field.passportOne", "Pasport 1")}
|
error={errors.passportOne}
|
||||||
|
accept="image/*"
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="text"
|
label={
|
||||||
label={t("cardOrder.field.passportTwo", "Pasport 2")}
|
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}
|
value={form.passportTwo}
|
||||||
onChange={(v) => set("passportTwo", v)}
|
onChange={(v) => set("passportTwo", v)}
|
||||||
placeholder={t("cardOrder.field.passportTwo", "Pasport 2")}
|
error={errors.passportTwo}
|
||||||
|
accept="image/*"
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="text"
|
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
|
||||||
label={t("cardOrder.field.passportThree", "Pasport 3")}
|
|
||||||
value={form.passportThree}
|
value={form.passportThree}
|
||||||
onChange={(v) => set("passportThree", v)}
|
onChange={(v) => set("passportThree", v)}
|
||||||
placeholder={t("cardOrder.field.passportThree", "Pasport 3")}
|
error={errors.passportThree}
|
||||||
|
accept="image/*"
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="text"
|
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
|
||||||
label={t("cardOrder.field.passportFour", "Pasport 4")}
|
|
||||||
value={form.passportFour}
|
value={form.passportFour}
|
||||||
onChange={(v) => set("passportFour", v)}
|
onChange={(v) => set("passportFour", v)}
|
||||||
placeholder={t("cardOrder.field.passportFour", "Pasport 4")}
|
error={errors.passportFour}
|
||||||
|
accept="image/*"
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
@@ -450,14 +467,20 @@ function StepContact({ form, errors, set, t }: StepContentProps) {
|
|||||||
|
|
||||||
<BentoGrid cols={1}>
|
<BentoGrid cols={1}>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<InfiniteSelect
|
||||||
type="number"
|
label={t("cardOrder.field.userId", "Ulanyjy")}
|
||||||
label={t("cardOrder.field.userId", "Ulanyjy ID")}
|
|
||||||
required
|
required
|
||||||
value={form.userId}
|
value={form.userId}
|
||||||
onChange={(v) => set("userId", v)}
|
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}
|
error={errors.userId}
|
||||||
|
loading={usersQuery.isLoading}
|
||||||
|
isLoadingMore={usersQuery.isFetchingNextPage}
|
||||||
|
hasNextPage={!!usersQuery.hasNextPage}
|
||||||
|
onLoadMore={() => usersQuery.fetchNextPage()}
|
||||||
|
searchValue={userSearch}
|
||||||
|
onSearchChange={setUserSearch}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
@@ -477,10 +500,10 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
|||||||
const updateMutation = useUpdateCard(initialData?.id ?? 0);
|
const updateMutation = useUpdateCard(initialData?.id ?? 0);
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 100 });
|
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
||||||
const { data: cardReasonsData } = useCardReasons({ page: 1, limit: 100 });
|
const { data: cardReasonsData } = useCardReasons({ page: 1, limit: 25 });
|
||||||
const { data: branchesData } = useBranches({ page: 1, limit: 100 });
|
const { data: branchesData } = useBranches({ page: 1, limit: 25 });
|
||||||
const { data: districtsData } = useDistricts({ page: 1, limit: 100 });
|
const { data: districtsData } = useDistricts({ page: 1, limit: 25 });
|
||||||
|
|
||||||
const cardTypeOptions = useMemo(
|
const cardTypeOptions = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -570,8 +593,8 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
|||||||
}, [rhfErrors, allSubmittedErrors]);
|
}, [rhfErrors, allSubmittedErrors]);
|
||||||
|
|
||||||
const stepProps = useMemo(
|
const stepProps = useMemo(
|
||||||
() => ({ 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],
|
[form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions, mode],
|
||||||
);
|
);
|
||||||
|
|
||||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||||
@@ -684,7 +707,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
|||||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||||
{currentStep === 3 && <StepContact {...stepProps} />}
|
{currentStep === 3 && <StepContact {...stepProps} initialData={initialData} />}
|
||||||
|
|
||||||
{/* Actions */}
|
{/* Actions */}
|
||||||
<FormActions
|
<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 { toast } from "sonner";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
@@ -11,6 +11,7 @@ export const permissionKeys = {
|
|||||||
lists: () => ["permissions", "list"] as const,
|
lists: () => ["permissions", "list"] as const,
|
||||||
list: (params: PermissionsListParams) => ["permissions", "list", params] as const,
|
list: (params: PermissionsListParams) => ["permissions", "list", params] as const,
|
||||||
detail: (id: number) => ["permissions", "detail", id] as const,
|
detail: (id: number) => ["permissions", "detail", id] as const,
|
||||||
|
infinite: (search: string) => ["permissions", "infinite", search] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
// ─── usePermissions (list) ────────────────────────────────────────────────────
|
// ─── 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 ──────────────────────────────────────────────────────
|
// ─── useCreatePermission ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreatePermission() {
|
export function useCreatePermission() {
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ const ROLE_PAGE_SIZE = 25;
|
|||||||
* Paginated roles for infinite-scroll selects.
|
* Paginated roles for infinite-scroll selects.
|
||||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
* `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 debouncedSearch = useDebouncedValue(search);
|
||||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||||
|
|
||||||
@@ -45,6 +45,7 @@ export function useInfiniteRoles(search = "") {
|
|||||||
const count = lastPage?.count ?? 0;
|
const count = lastPage?.count ?? 0;
|
||||||
return loaded < count ? allPages.length + 1 : undefined;
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
},
|
},
|
||||||
|
enabled,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,16 @@ export interface AddBranchUserPayload {
|
|||||||
userId: number;
|
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
|
// Re-export so shared hooks can import from one place
|
||||||
export type { BranchListParams, BranchListResponse };
|
export type { BranchListParams, BranchListResponse };
|
||||||
|
|
||||||
@@ -48,6 +58,22 @@ export async function postBranchUser(payload: AddBranchUserPayload): Promise<voi
|
|||||||
await apiClient.post("/branch-users", payload);
|
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
|
* Proxy for branch list fetching — kept here so shared hooks
|
||||||
* don't import directly from the branches feature.
|
* don't import directly from the branches feature.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const BRANCH_PAGE_SIZE = 25;
|
|||||||
* Infinite-scroll branch list for searchable selects.
|
* Infinite-scroll branch list for searchable selects.
|
||||||
* staleTime = 5 min as required by PROJECT_STANDARDS rule 12.
|
* 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 debouncedSearch = useDebouncedValue(search);
|
||||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||||
|
|
||||||
@@ -34,6 +34,7 @@ export function useInfiniteBranches(search = "") {
|
|||||||
return loaded < count ? allPages.length + 1 : undefined;
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
},
|
},
|
||||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||||
|
enabled,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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.cardExpMonth": "Month",
|
||||||
"loanOrderForm.labels.cardExpYear": "Year",
|
"loanOrderForm.labels.cardExpYear": "Year",
|
||||||
"loanOrderForm.labels.guarantor1Salary": "Average salary",
|
"loanOrderForm.labels.guarantor1Salary": "Average salary",
|
||||||
|
"loanOrderForm.labels.client": "Client",
|
||||||
"loanOrderForm.steps.status.subtitle": "Status & Note",
|
"loanOrderForm.steps.status.subtitle": "Status & Note",
|
||||||
"loanOrderForm.steps.loan.subtitle": "Type & Amount",
|
"loanOrderForm.steps.loan.subtitle": "Type & Amount",
|
||||||
"loanOrderForm.steps.location.subtitle": "Region & Branch",
|
"loanOrderForm.steps.location.subtitle": "Region & Branch",
|
||||||
@@ -1426,5 +1427,10 @@
|
|||||||
"visaMasterSberSettings.editTitle": "Edit setting",
|
"visaMasterSberSettings.editTitle": "Edit setting",
|
||||||
"onlinePayments.viewTitle": "Payment detail",
|
"onlinePayments.viewTitle": "Payment detail",
|
||||||
"cardTypes.viewTitle": "Card type 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.cardExpMonth": "Месяц",
|
||||||
"loanOrderForm.labels.cardExpYear": "Год",
|
"loanOrderForm.labels.cardExpYear": "Год",
|
||||||
"loanOrderForm.labels.guarantor1Salary": "Средняя зарплата",
|
"loanOrderForm.labels.guarantor1Salary": "Средняя зарплата",
|
||||||
|
"loanOrderForm.labels.client": "Клиент",
|
||||||
"loanOrderForm.steps.status.subtitle": "Статус и заметка",
|
"loanOrderForm.steps.status.subtitle": "Статус и заметка",
|
||||||
"loanOrderForm.steps.loan.subtitle": "Тип и сумма",
|
"loanOrderForm.steps.loan.subtitle": "Тип и сумма",
|
||||||
"loanOrderForm.steps.location.subtitle": "Велаят и филиал",
|
"loanOrderForm.steps.location.subtitle": "Велаят и филиал",
|
||||||
@@ -1427,5 +1428,10 @@
|
|||||||
"visaMasterSberSettings.editTitle": "Редактировать настройку",
|
"visaMasterSberSettings.editTitle": "Редактировать настройку",
|
||||||
"onlinePayments.viewTitle": "Детали платежа",
|
"onlinePayments.viewTitle": "Детали платежа",
|
||||||
"cardTypes.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.cardExpMonth": "Aý",
|
||||||
"loanOrderForm.labels.cardExpYear": "Ýyl",
|
"loanOrderForm.labels.cardExpYear": "Ýyl",
|
||||||
"loanOrderForm.labels.guarantor1Salary": "Ortaca zähmet haky",
|
"loanOrderForm.labels.guarantor1Salary": "Ortaca zähmet haky",
|
||||||
|
"loanOrderForm.labels.client": "Müşderi",
|
||||||
"loanOrderForm.steps.status.subtitle": "Ýagdaý we bellik",
|
"loanOrderForm.steps.status.subtitle": "Ýagdaý we bellik",
|
||||||
"loanOrderForm.steps.loan.subtitle": "Görnüş we möçber",
|
"loanOrderForm.steps.loan.subtitle": "Görnüş we möçber",
|
||||||
"loanOrderForm.steps.location.subtitle": "Welaýat we şahamça",
|
"loanOrderForm.steps.location.subtitle": "Welaýat we şahamça",
|
||||||
@@ -1425,5 +1426,10 @@
|
|||||||
"visaMasterSberSettings.editTitle": "Sazlama üýtgetmek",
|
"visaMasterSberSettings.editTitle": "Sazlama üýtgetmek",
|
||||||
"onlinePayments.viewTitle": "Töleg giňišleýin",
|
"onlinePayments.viewTitle": "Töleg giňišleýin",
|
||||||
"cardTypes.viewTitle": "Kart görnüşi 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)"
|
||||||
}
|
}
|
||||||
+323
-128
@@ -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 { 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 { Button } from "@/components/ui/button";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { BentoGrid, BentoCard, InfoRow, CollapsibleSection, EmptyState, AuditLog } from "@/components/viewPageComponents";
|
import {
|
||||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
AlertDialog,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
||||||
import { FormInput } from "@/components/formInput";
|
import { FormInput } from "@/components/formInput";
|
||||||
import { AvatarUpload } from "@/components/avatarUpload";
|
import { AvatarUpload } from "@/components/avatarUpload";
|
||||||
import { FormActions } from "@/components/formActions";
|
import { FormActions } from "@/components/formActions";
|
||||||
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||||
import { useAuthStore } from "@/app/store/authStore";
|
import { useAuthStore } from "@/app/store/authStore";
|
||||||
import { useProfile, useUpdateProfile } from "@/features/auth/hooks/useLogin";
|
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() {
|
export default function ProfilePage() {
|
||||||
const { t } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const { data: profileQueryData, isLoading } = useProfile();
|
const { data: profileQueryData, isLoading } = useProfile();
|
||||||
const authUser = useAuthStore((s) => s.user);
|
const authUser = useAuthStore((s) => s.user);
|
||||||
const user = profileQueryData ?? authUser;
|
const user = profileQueryData ?? authUser;
|
||||||
@@ -20,10 +38,11 @@ export default function ProfilePage() {
|
|||||||
const updateProfileMutation = useUpdateProfile();
|
const updateProfileMutation = useUpdateProfile();
|
||||||
|
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
|
const [assignDialog, setAssignDialog] = useState<AssignDialogKind | null>(null);
|
||||||
|
|
||||||
const [roleSearch, setRoleSearch] = useState("");
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||||
const [permSearch, setPermSearch] = useState("");
|
|
||||||
const [branchSearch, setBranchSearch] = useState("");
|
const branches = user?.branches ?? [];
|
||||||
|
|
||||||
// ── Form State for Editing ──
|
// ── Form State for Editing ──
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
@@ -36,17 +55,18 @@ export default function ProfilePage() {
|
|||||||
|
|
||||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
useEffect(() => {
|
const startEditing = () => {
|
||||||
if (user) {
|
if (!user) return;
|
||||||
setFormData({
|
setFormData({
|
||||||
name: user.name ?? "",
|
name: user.name ?? "",
|
||||||
firstName: user.firstName ?? "",
|
firstName: user.firstName ?? "",
|
||||||
lastName: user.lastName ?? "",
|
lastName: user.lastName ?? "",
|
||||||
phone: user.phone ?? "",
|
phone: user.phone ?? "",
|
||||||
avatar: user.avatar ?? "",
|
avatar: user.avatar ?? "",
|
||||||
});
|
});
|
||||||
}
|
setErrors({});
|
||||||
}, [user, isEditing]);
|
setIsEditing(true);
|
||||||
|
};
|
||||||
|
|
||||||
const handleFieldChange = (field: keyof typeof formData, value: string) => {
|
const handleFieldChange = (field: keyof typeof formData, value: string) => {
|
||||||
setFormData((prev) => ({ ...prev, [field]: value }));
|
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||||
@@ -102,132 +122,138 @@ export default function ProfilePage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* ── Title + actions ──────────────────────────────────────────────── */}
|
{/* ── Profile hero ─────────────────────────────────────────────────── */}
|
||||||
<div className="flex items-center justify-between">
|
{!isEditing ? (
|
||||||
<h1 className="text-xl font-bold text-foreground leading-tight">
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-card border border-border rounded-xl p-5">
|
||||||
{isEditing ? t("profile.editTitle", "Profili üýtgetmek") : `${t("profile.title", "Meniň profilim")}: ${user.name}`}
|
<div className="flex items-center gap-4 min-w-0">
|
||||||
</h1>
|
{user.avatar ? (
|
||||||
<div className="flex items-center gap-2 shrink-0">
|
<img
|
||||||
{!isEditing ? (
|
src={user.avatar}
|
||||||
<Button variant="outline" size="sm" className="gap-2" onClick={() => setIsEditing(true)}>
|
alt="avatar"
|
||||||
<Pencil size={15} />
|
className="w-16 h-16 rounded-full border border-border bg-muted/40 object-cover shrink-0 shadow-sm"
|
||||||
{t("common.edit", "Üýtgetmek")}
|
/>
|
||||||
</Button>
|
) : (
|
||||||
) : (
|
<div className="w-16 h-16 rounded-full border border-border bg-muted/40 flex items-center justify-center shrink-0 shadow-sm">
|
||||||
<Button
|
<UserRound size={28} className="text-muted-foreground/60" />
|
||||||
variant="ghost"
|
</div>
|
||||||
size="sm"
|
)}
|
||||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
<div className="min-w-0">
|
||||||
onClick={() => setIsEditing(false)}
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
disabled={updateProfileMutation.isPending}
|
<h1 className="text-lg font-bold text-foreground truncate">
|
||||||
>
|
{[user.firstName, user.lastName].filter(Boolean).join(" ") || user.name}
|
||||||
<X size={15} />
|
</h1>
|
||||||
{t("common.cancel", "Yza")}
|
<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">
|
||||||
</Button>
|
<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>
|
) : (
|
||||||
|
<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 ─────────────────────────────────────────────────── */}
|
{/* ── Main content ─────────────────────────────────────────────────── */}
|
||||||
{!isEditing ? (
|
{!isEditing ? (
|
||||||
<>
|
<>
|
||||||
<BentoGrid cols={1}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard title={t("profile.sections.basic", "Esasy maglumatlar")}>
|
<BentoCard title={t("profile.sections.account", "Hasap maglumatlary")}>
|
||||||
<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>
|
|
||||||
|
|
||||||
<InfoRow label={t("common.id", "ID")} value={user.id} />
|
<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.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
|
<InfoRow
|
||||||
label={t("users.fields.createdAt", "Döredilen wagty")}
|
label={t("users.fields.createdAt", "Döredilen wagty")}
|
||||||
value={user.createdAt ? new Date(user.createdAt).toLocaleString() : "—"}
|
value={user.createdAt ? new Date(user.createdAt).toLocaleString() : "—"}
|
||||||
/>
|
/>
|
||||||
<InfoRow label={t("users.fields.isActive", "Işjeň")}>
|
{user.email && <InfoRow label={t("users.fields.email", "E-poçta")} value={user.email} />}
|
||||||
<div className="flex items-center gap-1.5 text-emerald-500 font-medium text-sm">
|
</BentoCard>
|
||||||
<CheckCircle2 size={16} />
|
|
||||||
<span>{t("common.active", "Işjeň")}</span>
|
<BentoCard title={t("profile.sections.contact", "Habarlaşmak maglumatlary")}>
|
||||||
</div>
|
<InfoRow label={t("users.fields.firstName", "At ady")} value={user.firstName ?? "—"} />
|
||||||
</InfoRow>
|
<InfoRow label={t("users.fields.lastName", "Familiýasy")} value={user.lastName ?? "—"} />
|
||||||
|
<InfoRow label={t("users.fields.phone", "Telefon belgisi")} value={user.phone ?? "—"} />
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
{/* ── Rollar ───────────────────────────────────────────────────────── */}
|
<BentoGrid cols={2}>
|
||||||
<CollapsibleSection title={t("users.sections.roles", "Rollar")}>
|
<BentoCard title={t("profile.sections.org", "Guramaçylyk maglumatlary")}>
|
||||||
<DataTableToolbar
|
<InfoRow label={t("users.fields.role", "Roly")}>
|
||||||
searchValue={roleSearch}
|
{user.role ? (
|
||||||
onSearchChange={setRoleSearch}
|
<Link
|
||||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
to={`/settings/users/roles/${user.role.id}`}
|
||||||
columns={[]}
|
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
||||||
columnVisibility={{}}
|
>
|
||||||
onColumnVisibilityChange={() => {}}
|
<Shield size={12} />
|
||||||
columnOrder={[]}
|
{user.role.name}
|
||||||
onColumnOrderChange={() => {}}
|
</Link>
|
||||||
actionLabel={t("users.actions.addRole", "Rol birikdiriň")}
|
) : (
|
||||||
onAction={() => {}}
|
<span className="text-sm text-muted-foreground">—</span>
|
||||||
/>
|
)}
|
||||||
<EmptyState label={t("users.empty.roles", "Berlen kriteriýalara Rol gabat gelmedi.")} />
|
</InfoRow>
|
||||||
</CollapsibleSection>
|
|
||||||
|
|
||||||
{/* ── Rugsatlar ────────────────────────────────────────────────────── */}
|
<InfoRow label={t("users.sections.branches", "Şahamçalar")}>
|
||||||
<CollapsibleSection title={t("users.sections.permissions", "Rugsatlar")}>
|
{branches.length > 0 ? (
|
||||||
<DataTableToolbar
|
<div className="flex flex-wrap gap-1.5">
|
||||||
searchValue={permSearch}
|
{branches.map((b) => (
|
||||||
onSearchChange={setPermSearch}
|
<Link
|
||||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
key={b.id}
|
||||||
columns={[]}
|
to={`/settings/location/branches/${b.id}`}
|
||||||
columnVisibility={{}}
|
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
||||||
onColumnVisibilityChange={() => {}}
|
>
|
||||||
columnOrder={[]}
|
<Building2 size={11} className="text-muted-foreground" />
|
||||||
onColumnOrderChange={() => {}}
|
<span className="text-foreground font-medium">
|
||||||
actionLabel={t("users.actions.addPermission", "Rugsat birikdiriň")}
|
{b.name?.[lang] || b.name?.tm || b.name?.en || b.name?.ru || b.uniqueCode || b.id}
|
||||||
onAction={() => {}}
|
</span>
|
||||||
/>
|
</Link>
|
||||||
<EmptyState label={t("users.empty.permissions", "Berlen kriteriýalara Rugsat gabat gelmedi.")} />
|
))}
|
||||||
</CollapsibleSection>
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="text-sm text-muted-foreground">—</span>
|
||||||
|
)}
|
||||||
|
</InfoRow>
|
||||||
|
|
||||||
{/* ── Şahamçalar ───────────────────────────────────────────────────── */}
|
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}>
|
||||||
<CollapsibleSection title={t("users.sections.branches", "Şahamçalar")}>
|
<span className="text-sm text-muted-foreground">—</span>
|
||||||
<DataTableToolbar
|
</InfoRow>
|
||||||
searchValue={branchSearch}
|
</BentoCard>
|
||||||
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>
|
|
||||||
|
|
||||||
{/* ── Ammallar ─────────────────────────────────────────────────────── */}
|
<BentoCard title={t("profile.sections.actions", "Amallar")}>
|
||||||
<CollapsibleSection title={t("users.sections.audit", "Ammallar")}>
|
<div className="flex flex-wrap gap-2 px-4 py-3">
|
||||||
<AuditLog logs={[]} currentPage={1} totalPages={1} totalCount={0} />
|
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("role")}>
|
||||||
</CollapsibleSection>
|
<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">
|
<div className="w-full">
|
||||||
@@ -288,6 +314,175 @@ export default function ProfilePage() {
|
|||||||
</BentoCard>
|
</BentoCard>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* ── Assign dialog (staff user + role/permission/branch) ─────────────── */}
|
||||||
|
{assignDialog && <AssignDialog kind={assignDialog} onClose={() => setAssignDialog(null)} />}
|
||||||
</div>
|
</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