From f00d2abcac1fe28dc6508824afd5e9d9c6868507 Mon Sep 17 00:00:00 2001 From: Jelaletdin12 Date: Sun, 23 Aug 2026 19:09:06 +0500 Subject: [PATCH] fixed ui, connected role user, branch user permissions user api --- src/app/store/authStore.ts | 16 +- src/components/ui/badge.tsx | 39 +- .../cardPins/components/cardPinForm.tsx | 148 +++--- .../cardPins/schemas/cardPin.schema.ts | 3 +- .../components/cardTransactionForm.tsx | 65 ++- src/features/clients/api/clientsApi.ts | 2 +- src/features/loanOrders/api/loanOrdersApi.ts | 6 +- .../loanOrders/components/loanOrderForm.tsx | 189 +++++--- .../loanOrders/schemas/loanOrder.schema.ts | 4 + src/features/operators/hooks/useOperators.ts | 25 +- .../components/orderNewCardForm.tsx | 181 ++++--- .../permissions/hooks/usePermissions.ts | 30 +- src/features/roles/hooks/useRoles.ts | 3 +- src/features/shared/api/sharedApi.ts | 26 + .../shared/hooks/useSharedBranchUsers.ts | 3 +- .../shared/hooks/useSharedUserAssignments.ts | 82 ++++ src/lib/i18n/locales/en.json | 8 +- src/lib/i18n/locales/ru.json | 8 +- src/lib/i18n/locales/tk.json | 8 +- src/pages/profile/index.tsx | 451 +++++++++++++----- 20 files changed, 906 insertions(+), 391 deletions(-) create mode 100644 src/features/shared/hooks/useSharedUserAssignments.ts diff --git a/src/app/store/authStore.ts b/src/app/store/authStore.ts index 2227dd1..ee43f75 100644 --- a/src/app/store/authStore.ts +++ b/src/app/store/authStore.ts @@ -2,6 +2,19 @@ import { create } from "zustand"; import { persist } from "zustand/middleware"; import axios from "axios"; import type { ApiSuccessResponse } from "@/lib/api/client"; +import type { LocalizedText } from "@/features/branches/api/branchesApi"; + +export interface AuthUserRole { + id: number; + code: string; + name: string; +} + +export interface AuthUserBranch { + id: number; + uniqueCode: string; + name: LocalizedText; +} export interface AuthUser { id?: string | number; @@ -10,8 +23,9 @@ export interface AuthUser { firstName?: string; lastName?: string; phone?: string; - role?: string; + role?: AuthUserRole; avatar?: string; + branches?: AuthUserBranch[]; createdAt?: string; } diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsx index 0b21a2b..b107117 100644 --- a/src/components/ui/badge.tsx +++ b/src/components/ui/badge.tsx @@ -1,49 +1,38 @@ -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" -import { Slot } from "radix-ui" +import * as React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; +import { Slot } from "radix-ui"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; const badgeVariants = cva( - "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-3xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!", + "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-md border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!", { variants: { variant: { default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80", - secondary: - "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80", + secondary: "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80", destructive: "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20", - outline: - "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground", - ghost: - "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50", + outline: "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground", + ghost: "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50", link: "text-primary underline-offset-4 hover:underline", }, }, defaultVariants: { variant: "default", }, - } -) + }, +); function Badge({ className, variant = "default", asChild = false, ...props -}: React.ComponentProps<"span"> & - VariantProps & { asChild?: boolean }) { - const Comp = asChild ? Slot.Root : "span" +}: React.ComponentProps<"span"> & VariantProps & { asChild?: boolean }) { + const Comp = asChild ? Slot.Root : "span"; - return ( - - ) + return ; } -export { Badge, badgeVariants } +export { Badge, badgeVariants }; diff --git a/src/features/cardPins/components/cardPinForm.tsx b/src/features/cardPins/components/cardPinForm.tsx index 0ea43fd..4a8fc7d 100644 --- a/src/features/cardPins/components/cardPinForm.tsx +++ b/src/features/cardPins/components/cardPinForm.tsx @@ -19,6 +19,10 @@ import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes"; import { useBranches } from "@/features/branches/hooks/useBranches"; import { useDistricts } from "@/features/districts/hooks/useDistricts"; import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants"; +import { DocumentUpload } from "@/components/documentUpload"; +import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect"; +import { useInfiniteClients } from "@/features/clients/hooks/useClients"; +import { formatFromApiPhone } from "@/lib/utils"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -190,11 +194,28 @@ function StepCard({ form, errors, set, t, cardTypeOptions, branchOptions, distri ); } -function StepPersonal({ form, errors, set, t }: StepContentProps) { +function StepPersonal({ form, errors, set, t, initialData }: StepContentProps & { initialData?: CardPinOrder }) { + const [clientSearch, setClientSearch] = useState(""); + const clientsQuery = useInfiniteClients(clientSearch); + + const clientOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? []) + .flatMap((p) => p?.users ?? []) + .map((u) => ({ + value: String(u.id), + label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id), + })); + + if (initialData?.userId && !opts.some((o) => o.value === String(initialData.userId))) { + opts.unshift({ value: String(initialData.userId), label: String(initialData.userId) }); + } + return opts; + }, [clientsQuery.data, initialData]); + return (
- - + + - - - - - - - + set("bornAt", v)} error={errors.bornAt} /> - - set("phone", v)} - placeholder={t("cardPin.field.phone", "Telefon")} + placeholder={t("loanOrderForm.placeholders.phone") || "61 097651"} error={errors.phone} /> - - - set("userId", v)} - placeholder={t("cardPin.field.userId", "Ulanyjy ID")} + options={clientOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.userId} + loading={clientsQuery.isLoading} + isLoadingMore={clientsQuery.isFetchingNextPage} + hasNextPage={!!clientsQuery.hasNextPage} + onLoadMore={() => clientsQuery.fetchNextPage()} + searchValue={clientSearch} + onSearchChange={setClientSearch} /> @@ -267,67 +284,70 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) { function StepPassport({ form, errors, set, t }: StepContentProps) { return (
- - - set("passportSerie", v)} - options={PASSPORT_SERIES_OPTIONS} - placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} - error={errors.passportSerie} - /> - - - set("passportId", v)} - placeholder={t("cardPin.field.passportId", "Pasport belgisi")} - error={errors.passportId} - /> + + +
+ set("passportSerie", v)} + options={PASSPORT_SERIES_OPTIONS} + placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} + error={errors.passportSerie} + /> + set("passportId", v)} + placeholder={t("cardPin.field.passportId", "Pasport belgisi")} + error={errors.passportId} + /> +
- + - set("passportOne", v)} - placeholder={t("cardPin.field.passportOne", "Pasport 1")} + error={errors.passportOne} + accept="image/*" /> + - set("passportTwo", v)} - placeholder={t("cardPin.field.passportTwo", "Pasport 2")} + error={errors.passportTwo} + accept="image/*" /> + - set("passportThree", v)} - placeholder={t("cardPin.field.passportThree", "Pasport 3")} + error={errors.passportThree} + accept="image/*" /> + - set("passportFour", v)} - placeholder={t("cardPin.field.passportFour", "Pasport 4")} + error={errors.passportFour} + accept="image/*" /> @@ -347,9 +367,9 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) { const updateMutation = useUpdateCardPin(initialData?.id ?? 0); const isPending = createMutation.isPending || updateMutation.isPending; - const { data: cardTypesData } = useCardTypes({ page: 1, limit: 100 }); - const { data: branchesData } = useBranches({ page: 1, limit: 100 }); - const { data: districtsData } = useDistricts({ page: 1, limit: 100 }); + const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 }); + const { data: branchesData } = useBranches({ page: 1, limit: 25 }); + const { data: districtsData } = useDistricts({ page: 1, limit: 25 }); const cardTypeOptions = useMemo( () => @@ -533,7 +553,7 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) { {/* Step content */} {currentStep === 0 && } - {currentStep === 1 && } + {currentStep === 1 && } {currentStep === 2 && } {/* Actions */} @@ -566,7 +586,7 @@ function mapInitial(data: CardPinOrder): Partial { customerSurname: data.customerSurname ?? "", customerPatronicName: data.customerPatronicName ?? "", bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "", - phone: data.phone ?? "", + phone: formatFromApiPhone(data.phone), passportSerie: data.passportSerie ?? "", passportId: data.passportId ?? "", passportOne: data.passportOne ?? "", diff --git a/src/features/cardPins/schemas/cardPin.schema.ts b/src/features/cardPins/schemas/cardPin.schema.ts index 7c40d0a..6007227 100644 --- a/src/features/cardPins/schemas/cardPin.schema.ts +++ b/src/features/cardPins/schemas/cardPin.schema.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import i18next from "i18next"; import type { CreateCardPinPayload } from "../api/cardPinApi"; +import { formatToApiPhone } from "@/lib/utils"; const optional = () => z.string().default(""); @@ -101,7 +102,7 @@ export function buildPayload(data: CardPinFormData): CreateCardPinPayload { branchId: Number(data.branchId), cardTypeId: Number(data.cardTypeId), cardNumber: data.cardNumber.trim(), - phone: data.phone.trim(), + phone: formatToApiPhone(data.phone), passportSerie: data.passportSerie.trim(), passportId: data.passportId.trim(), passportOne: data.passportOne.trim(), diff --git a/src/features/cardTransactions/components/cardTransactionForm.tsx b/src/features/cardTransactions/components/cardTransactionForm.tsx index 19e67d1..df28f41 100644 --- a/src/features/cardTransactions/components/cardTransactionForm.tsx +++ b/src/features/cardTransactions/components/cardTransactionForm.tsx @@ -1,12 +1,16 @@ -import { useMemo } from "react"; +import { useMemo, useState } from "react"; import { useForm } from "react-hook-form"; import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { FormInput } from "@/components/formInput"; import { FormActions } from "@/components/formActions"; import { BentoGrid, BentoCard } from "@/components/bento"; +import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect"; import type { Card } from "../api/cardTransactionsApi"; import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions"; +import { useInfiniteClients } from "@/features/clients/hooks/useClients"; +import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes"; +import type { LocalizedTitle } from "@/features/cardTypes/api/cardTypesApi"; import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema"; import type { CardTransactionFormData } from "../schemas/cardTransaction.schema"; @@ -45,9 +49,41 @@ function flattenErrors(errors: Record) // ─── Component ──────────────────────────────────────────────────────────────── export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) { - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); const navigate = useNavigate(); + const [clientSearch, setClientSearch] = useState(""); + const clientsQuery = useInfiniteClients(clientSearch); + const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 }); + + const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedTitle; + + const clientOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? []) + .flatMap((p) => p?.users ?? []) + .map((u) => ({ + value: String(u.id), + label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id), + })); + + if (initialData?.userId && !opts.some((o) => o.value === String(initialData.userId))) { + opts.unshift({ value: String(initialData.userId), label: String(initialData.userId) }); + } + return opts; + }, [clientsQuery.data, initialData]); + + const cardTypeOptions = useMemo(() => { + const opts = (cardTypesData?.paymentCards ?? []).map((ct) => ({ + value: String(ct.id), + label: ct.title[lang] || ct.title.tm, + })); + + if (initialData?.type && !opts.some((o) => o.value === initialData.type)) { + opts.unshift({ value: initialData.type, label: initialData.type }); + } + return opts; + }, [cardTypesData, lang, initialData]); + const { watch, setValue, @@ -132,11 +168,12 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr {/* Type */} @@ -152,15 +189,21 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr required /> - {/* User ID */} - 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 */} diff --git a/src/features/clients/api/clientsApi.ts b/src/features/clients/api/clientsApi.ts index a7b8fae..d0ea2e6 100644 --- a/src/features/clients/api/clientsApi.ts +++ b/src/features/clients/api/clientsApi.ts @@ -132,7 +132,7 @@ export const clientsApi = { getClients: async (params: ClientsListParams = {}, signal?: AbortSignal): Promise => { const { page, limit, search, isActive } = params; const { data } = await apiClient.get("/users/clients", { - params: { page, limit, username: search, isActive }, + params: { page, limit, username: search || undefined, isActive: isActive || undefined }, signal, }); return data; diff --git a/src/features/loanOrders/api/loanOrdersApi.ts b/src/features/loanOrders/api/loanOrdersApi.ts index 18854d1..95a06f6 100644 --- a/src/features/loanOrders/api/loanOrdersApi.ts +++ b/src/features/loanOrders/api/loanOrdersApi.ts @@ -120,6 +120,7 @@ export interface LoanOrderPayload { loanType: string; region: string; branch: string; + userId: string; firstName: string; lastName: string; patronicName?: string; @@ -352,6 +353,7 @@ function mapBackendToUI(order: BackendLoanOrder): LoanOrder { guarantor2CardExpMonth: order.guarantor2CardMonth ?? "", guarantor2CardExpYear: order.guarantor2CardYear ?? "", guarantor2Note: order.guarantor2Note ?? "", + loanHistory: order.loanOrderRequiredDocId ? String(order.loanOrderRequiredDocId) : "", createdBy: order.userName ?? "", fullName: [order.customerName, order.customerSurname].filter(Boolean).join(" "), registeredAddress: order.passportAddress ?? "", @@ -433,8 +435,8 @@ function mapPayloadToBackend(payload: LoanOrderPayload | Partial { + 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( + () => + (requiredDocsData?.loansDocuments ?? []).map((doc) => ({ + value: String(doc.id), + label: doc.name, + })), + [requiredDocsData], + ); + return (
- - - + + set("firstName", v)} - placeholder={t("Name") || "Ady"} - error={errors.firstName} - /> - - - set("lastName", v)} - placeholder={t("Surname") || "Familiýasy"} - error={errors.lastName} - /> - - - set("patronicName", v)} - placeholder={t("Patronic name") || "Atasynyň ady"} + value={form.userId} + onChange={(v) => set("userId", v)} + options={clientOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + error={errors.userId} + loading={clientsQuery.isLoading} + isLoadingMore={clientsQuery.isFetchingNextPage} + hasNextPage={!!clientsQuery.hasNextPage} + onLoadMore={() => clientsQuery.fetchNextPage()} + searchValue={clientSearch} + onSearchChange={setClientSearch} /> +
+ set("firstName", v)} + placeholder={t("Name") || "Ady"} + error={errors.firstName} + /> + set("lastName", v)} + placeholder={t("Surname") || "Familiýasy"} + error={errors.lastName} + /> + set("patronicName", v)} + placeholder={t("Patronic name") || "Atasynyň ady"} + /> +
- - - set("education", v)} - options={EDUCATION_OPTIONS} - placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} - error={errors.education} - /> - - - set("marriageStatus", v)} - options={MARRIAGE_OPTIONS} - placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} - error={errors.marriageStatus} - /> - - - set("dateOfBirth", v)} - error={errors.dateOfBirth} - /> + + +
+ set("education", v)} + options={EDUCATION_OPTIONS} + placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} + error={errors.education} + /> + set("marriageStatus", v)} + options={MARRIAGE_OPTIONS} + placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} + error={errors.marriageStatus} + /> + set("dateOfBirth", v)} + error={errors.dateOfBirth} + /> +
+ - + - - - + + set("loanHistory", v)} - options={[]} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + options={loanHistoryOptions} + placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"} /> @@ -1174,7 +1218,7 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) { {currentStep === 0 && } {currentStep === 1 && } {currentStep === 2 && } - {currentStep === 3 && } + {currentStep === 3 && } {currentStep === 4 && } {currentStep === 5 && } {currentStep === 6 && } @@ -1206,6 +1250,7 @@ function mapInitial(order: LoanOrder): Partial { loanType: order.loanTypeId != null ? String(order.loanTypeId) : "", region: order.region ?? "AG", branch: order.branchId != null ? String(order.branchId) : "", + userId: order.createdById != null ? String(order.createdById) : "", firstName: order.firstName ?? "", lastName: order.lastName ?? "", patronicName: order.patronicName ?? "", diff --git a/src/features/loanOrders/schemas/loanOrder.schema.ts b/src/features/loanOrders/schemas/loanOrder.schema.ts index 53600ef..4e32425 100644 --- a/src/features/loanOrders/schemas/loanOrder.schema.ts +++ b/src/features/loanOrders/schemas/loanOrder.schema.ts @@ -7,6 +7,7 @@ export const loanOrderFormSchema = z.object({ loanType: z.string().min(1, "validation.required"), region: z.string().min(1, "validation.required"), branch: z.string().min(1, "validation.required"), + userId: z.string().min(1, "validation.required"), firstName: z.string().min(1, "validation.required"), lastName: z.string().min(1, "validation.required"), patronicName: z.string().optional(), @@ -139,6 +140,7 @@ export const stepSchemas: Record>> 1: loanOrderFormSchema.pick({ loanType: true, loanAmount: true }), 2: loanOrderFormSchema.pick({ region: true, branch: true }), 3: loanOrderFormSchema.pick({ + userId: true, firstName: true, lastName: true, education: true, @@ -228,6 +230,7 @@ export const DEFAULT_FORM_VALUES: LoanOrderFormData = { loanType: "", region: "AG", branch: "", + userId: "", firstName: "", lastName: "", patronicName: "", @@ -291,6 +294,7 @@ export function buildPayload(data: LoanOrderFormData) { loanType: data.loanType, region: data.region, branch: data.branch, + userId: data.userId, firstName: data.firstName, lastName: data.lastName, patronicName: data.patronicName || undefined, diff --git a/src/features/operators/hooks/useOperators.ts b/src/features/operators/hooks/useOperators.ts index 7cc6f19..1f04ce5 100644 --- a/src/features/operators/hooks/useOperators.ts +++ b/src/features/operators/hooks/useOperators.ts @@ -1,4 +1,4 @@ -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query"; import { toast } from "sonner"; import { useTranslation } from "react-i18next"; import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch"; @@ -37,6 +37,29 @@ export function useOperator(id: number) { }); } +const STAFF_PAGE_SIZE = 25; + +/** + * Paginated staff users (GET /users/staff) for infinite-scroll selects. + * `search` is debounced server-side search; each keystroke resets to page 1. + */ +export function useInfiniteStaff(search = "") { + const debouncedSearch = useDebouncedValue(search); + const effectiveSearch = normalizeSearch(debouncedSearch); + + return useInfiniteQuery({ + queryKey: [...operatorKeys.all, "infinite", effectiveSearch] as const, + initialPageParam: 1, + queryFn: ({ pageParam, signal }) => + operatorsApi.getOperators({ page: pageParam, limit: STAFF_PAGE_SIZE, search: effectiveSearch }, signal), + getNextPageParam: (lastPage, allPages) => { + const loaded = allPages.reduce((sum, p) => sum + (p?.users?.length ?? 0), 0); + const count = lastPage?.count ?? 0; + return loaded < count ? allPages.length + 1 : undefined; + }, + }); +} + // ─── useCreateOperator ──────────────────────────────────────────────────────── export function useCreateOperator() { diff --git a/src/features/orderNewCard/components/orderNewCardForm.tsx b/src/features/orderNewCard/components/orderNewCardForm.tsx index bf4f6d9..2771642 100644 --- a/src/features/orderNewCard/components/orderNewCardForm.tsx +++ b/src/features/orderNewCard/components/orderNewCardForm.tsx @@ -9,6 +9,8 @@ import { useForm } from "react-hook-form"; import { FormInput, type SelectOption } from "@/components/formInput"; import { FormActions } from "@/components/formActions"; +import { DocumentUpload } from "@/components/documentUpload"; +import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect"; import { StepBarCards, type StepCardItem } from "@/components/stepBarV2"; import { BentoGrid, BentoCard } from "@/components/bento"; import type { CardOrder } from "../api/orderNewCardApi"; @@ -19,6 +21,7 @@ import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes"; import { useCardReasons } from "@/features/cardReasons/hooks/useCardReasons"; import { useBranches } from "@/features/branches/hooks/useBranches"; import { useDistricts } from "@/features/districts/hooks/useDistricts"; +import { useInfiniteClients } from "@/features/clients/hooks/useClients"; import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -103,6 +106,7 @@ interface StepContentProps { cardStateOptions: SelectOption[]; branchOptions: SelectOption[]; districtOptions: SelectOption[]; + mode: "create" | "edit"; } // ─── Step panels ────────────────────────────────────────────────────────────── @@ -222,8 +226,8 @@ function StepCard({ form, errors, set, t, cardTypeOptions, cardStateOptions, bra function StepPersonal({ form, errors, set, t }: StepContentProps) { return (
- - + + - - - - set("customerPatronicName", v)} placeholder={t("cardOrder.field.customerPatronicName", "Atasynyň ady")} /> - - - - - - + + set("bornAt", v)} error={errors.bornAt} /> - - set("bornPlace", v)} placeholder={t("cardOrder.field.bornPlace", "Doglan ýeri")} /> - - - - - - - set("phone", v)} - placeholder={t("cardOrder.field.phone", "Telefon")} - error={errors.phone} - /> - - - set("phoneAdditional", v)} - placeholder={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")} - /> + + + + +
+ set("phone", v)} + placeholder={t("cardOrder.field.phone", "Telefon")} + error={errors.phone} + /> + set("phoneAdditional", v)} + placeholder={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")} + /> +
); } -function StepPassport({ form, errors, set, t }: StepContentProps) { +function StepPassport({ form, errors, set, t, mode }: StepContentProps) { return (
- - + + - - - - - - - + set("passportGivenBy", v)} placeholder={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")} /> - - - + - set("passportOne", v)} - placeholder={t("cardOrder.field.passportOne", "Pasport 1")} + error={errors.passportOne} + accept="image/*" /> + - set("passportTwo", v)} - placeholder={t("cardOrder.field.passportTwo", "Pasport 2")} + error={errors.passportTwo} + accept="image/*" /> + - set("passportThree", v)} - placeholder={t("cardOrder.field.passportThree", "Pasport 3")} + error={errors.passportThree} + accept="image/*" /> + - set("passportFour", v)} - placeholder={t("cardOrder.field.passportFour", "Pasport 4")} + error={errors.passportFour} + accept="image/*" /> @@ -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 (
@@ -450,14 +467,20 @@ function StepContact({ form, errors, set, t }: StepContentProps) { - set("userId", v)} - placeholder={t("cardOrder.field.userId", "Ulanyjy ID")} + options={userOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} error={errors.userId} + loading={usersQuery.isLoading} + isLoadingMore={usersQuery.isFetchingNextPage} + hasNextPage={!!usersQuery.hasNextPage} + onLoadMore={() => usersQuery.fetchNextPage()} + searchValue={userSearch} + onSearchChange={setUserSearch} /> @@ -477,10 +500,10 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) { const updateMutation = useUpdateCard(initialData?.id ?? 0); const isPending = createMutation.isPending || updateMutation.isPending; - const { data: cardTypesData } = useCardTypes({ page: 1, limit: 100 }); - const { data: cardReasonsData } = useCardReasons({ page: 1, limit: 100 }); - const { data: branchesData } = useBranches({ page: 1, limit: 100 }); - const { data: districtsData } = useDistricts({ page: 1, limit: 100 }); + const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 }); + const { data: cardReasonsData } = useCardReasons({ page: 1, limit: 25 }); + const { data: branchesData } = useBranches({ page: 1, limit: 25 }); + const { data: districtsData } = useDistricts({ page: 1, limit: 25 }); const cardTypeOptions = useMemo( () => @@ -570,8 +593,8 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) { }, [rhfErrors, allSubmittedErrors]); const stepProps = useMemo( - () => ({ form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions }), - [form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions], + () => ({ form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions, mode }), + [form, errors, set, t, cardTypeOptions, cardStateOptions, branchOptions, districtOptions, mode], ); // ── Navigation ────────────────────────────────────────────────────────────── @@ -684,7 +707,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) { {currentStep === 0 && } {currentStep === 1 && } {currentStep === 2 && } - {currentStep === 3 && } + {currentStep === 3 && } {/* Actions */} ["permissions", "list"] as const, list: (params: PermissionsListParams) => ["permissions", "list", params] as const, detail: (id: number) => ["permissions", "detail", id] as const, + infinite: (search: string) => ["permissions", "infinite", search] as const, }; // ─── usePermissions (list) ──────────────────────────────────────────────────── @@ -35,6 +36,33 @@ export function usePermission(id: number) { }); } +// ─── useInfinitePermissions ─────────────────────────────────────────────────── + +const PERMISSION_PAGE_SIZE = 25; + +/** + * Infinite-scroll permission list for searchable selects. + * staleTime = 5 min as required by PROJECT_STANDARDS rule 12. + */ +export function useInfinitePermissions(search = "", enabled = true) { + const debouncedSearch = useDebouncedValue(search); + const effectiveSearch = normalizeSearch(debouncedSearch); + + return useInfiniteQuery({ + queryKey: permissionKeys.infinite(effectiveSearch), + initialPageParam: 1, + queryFn: ({ pageParam, signal }) => + permissionsApi.getAll({ page: pageParam, limit: PERMISSION_PAGE_SIZE, search: effectiveSearch }, signal), + getNextPageParam: (lastPage, allPages) => { + const loaded = allPages.reduce((sum, p) => sum + (p?.permissions?.length ?? 0), 0); + const count = lastPage?.count ?? 0; + return loaded < count ? allPages.length + 1 : undefined; + }, + staleTime: 5 * 60 * 1000, // 5 minutes + enabled, + }); +} + // ─── useCreatePermission ────────────────────────────────────────────────────── export function useCreatePermission() { diff --git a/src/features/roles/hooks/useRoles.ts b/src/features/roles/hooks/useRoles.ts index 3fda18d..69cc6df 100644 --- a/src/features/roles/hooks/useRoles.ts +++ b/src/features/roles/hooks/useRoles.ts @@ -32,7 +32,7 @@ const ROLE_PAGE_SIZE = 25; * Paginated roles for infinite-scroll selects. * `search` is debounced server-side search; each keystroke resets to page 1. */ -export function useInfiniteRoles(search = "") { +export function useInfiniteRoles(search = "", enabled = true) { const debouncedSearch = useDebouncedValue(search); const effectiveSearch = normalizeSearch(debouncedSearch); @@ -45,6 +45,7 @@ export function useInfiniteRoles(search = "") { const count = lastPage?.count ?? 0; return loaded < count ? allPages.length + 1 : undefined; }, + enabled, }); } diff --git a/src/features/shared/api/sharedApi.ts b/src/features/shared/api/sharedApi.ts index 53e17b8..3767355 100644 --- a/src/features/shared/api/sharedApi.ts +++ b/src/features/shared/api/sharedApi.ts @@ -8,6 +8,16 @@ export interface AddBranchUserPayload { userId: number; } +export interface AddRoleUserPayload { + roleId: number; + userId: number; +} + +export interface AddPermissionUserPayload { + permissionId: number; + userId: number; +} + // Re-export so shared hooks can import from one place export type { BranchListParams, BranchListResponse }; @@ -48,6 +58,22 @@ export async function postBranchUser(payload: AddBranchUserPayload): Promise { + await apiClient.post("/role-users", payload); +} + +/** + * POST /permission-users + * Assigns a permission to a user. + */ +export async function postPermissionUser(payload: AddPermissionUserPayload): Promise { + await apiClient.post("/permission-users", payload); +} + /** * Proxy for branch list fetching — kept here so shared hooks * don't import directly from the branches feature. diff --git a/src/features/shared/hooks/useSharedBranchUsers.ts b/src/features/shared/hooks/useSharedBranchUsers.ts index f47a76e..9c39b52 100644 --- a/src/features/shared/hooks/useSharedBranchUsers.ts +++ b/src/features/shared/hooks/useSharedBranchUsers.ts @@ -20,7 +20,7 @@ const BRANCH_PAGE_SIZE = 25; * Infinite-scroll branch list for searchable selects. * staleTime = 5 min as required by PROJECT_STANDARDS rule 12. */ -export function useInfiniteBranches(search = "") { +export function useInfiniteBranches(search = "", enabled = true) { const debouncedSearch = useDebouncedValue(search); const effectiveSearch = normalizeSearch(debouncedSearch); @@ -34,6 +34,7 @@ export function useInfiniteBranches(search = "") { return loaded < count ? allPages.length + 1 : undefined; }, staleTime: 5 * 60 * 1000, // 5 minutes + enabled, }); } diff --git a/src/features/shared/hooks/useSharedUserAssignments.ts b/src/features/shared/hooks/useSharedUserAssignments.ts new file mode 100644 index 0000000..02e6274 --- /dev/null +++ b/src/features/shared/hooks/useSharedUserAssignments.ts @@ -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")); + }, + }); +} diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 70e8a7a..e769909 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -552,6 +552,7 @@ "loanOrderForm.labels.cardExpMonth": "Month", "loanOrderForm.labels.cardExpYear": "Year", "loanOrderForm.labels.guarantor1Salary": "Average salary", + "loanOrderForm.labels.client": "Client", "loanOrderForm.steps.status.subtitle": "Status & Note", "loanOrderForm.steps.loan.subtitle": "Type & Amount", "loanOrderForm.steps.location.subtitle": "Region & Branch", @@ -1426,5 +1427,10 @@ "visaMasterSberSettings.editTitle": "Edit setting", "onlinePayments.viewTitle": "Payment detail", "cardTypes.viewTitle": "Card type detail", - "profile.title": "My Profile" + "profile.title": "My Profile", + "profile.actions.assignRole": "Assign role", + "profile.actions.assignPermission": "Assign permission", + "profile.actions.assignBranch": "Assign branch", + "profile.assign.success": "Assigned successfully", + "profile.assign.userLabel": "User (staff)" } diff --git a/src/lib/i18n/locales/ru.json b/src/lib/i18n/locales/ru.json index 3586094..a17b965 100644 --- a/src/lib/i18n/locales/ru.json +++ b/src/lib/i18n/locales/ru.json @@ -552,6 +552,7 @@ "loanOrderForm.labels.cardExpMonth": "Месяц", "loanOrderForm.labels.cardExpYear": "Год", "loanOrderForm.labels.guarantor1Salary": "Средняя зарплата", + "loanOrderForm.labels.client": "Клиент", "loanOrderForm.steps.status.subtitle": "Статус и заметка", "loanOrderForm.steps.loan.subtitle": "Тип и сумма", "loanOrderForm.steps.location.subtitle": "Велаят и филиал", @@ -1427,5 +1428,10 @@ "visaMasterSberSettings.editTitle": "Редактировать настройку", "onlinePayments.viewTitle": "Детали платежа", "cardTypes.viewTitle": "Детали типа карты", - "profile.title": "Мой профиль" + "profile.title": "Мой профиль", + "profile.actions.assignRole": "Назначить роль", + "profile.actions.assignPermission": "Назначить разрешение", + "profile.actions.assignBranch": "Назначить филиал", + "profile.assign.success": "Успешно назначено", + "profile.assign.userLabel": "Пользователь (staff)" } diff --git a/src/lib/i18n/locales/tk.json b/src/lib/i18n/locales/tk.json index 54d21c2..6f61ad9 100644 --- a/src/lib/i18n/locales/tk.json +++ b/src/lib/i18n/locales/tk.json @@ -551,6 +551,7 @@ "loanOrderForm.labels.cardExpMonth": "Aý", "loanOrderForm.labels.cardExpYear": "Ýyl", "loanOrderForm.labels.guarantor1Salary": "Ortaca zähmet haky", + "loanOrderForm.labels.client": "Müşderi", "loanOrderForm.steps.status.subtitle": "Ýagdaý we bellik", "loanOrderForm.steps.loan.subtitle": "Görnüş we möçber", "loanOrderForm.steps.location.subtitle": "Welaýat we şahamça", @@ -1425,5 +1426,10 @@ "visaMasterSberSettings.editTitle": "Sazlama üýtgetmek", "onlinePayments.viewTitle": "Töleg giňišleýin", "cardTypes.viewTitle": "Kart görnüşi giňişleýin", - "profile.title": "Meniň profilim" + "profile.title": "Meniň profilim", + "profile.actions.assignRole": "Rol birikdiriň", + "profile.actions.assignPermission": "Rugsat birikdiriň", + "profile.actions.assignBranch": "Şahamça birikdiriň", + "profile.assign.success": "Üstünlikli birikdirildi", + "profile.assign.userLabel": "Ulanyjy (staff)" } diff --git a/src/pages/profile/index.tsx b/src/pages/profile/index.tsx index 198e57b..35b7efb 100644 --- a/src/pages/profile/index.tsx +++ b/src/pages/profile/index.tsx @@ -1,18 +1,36 @@ -import { useState, useEffect } from "react"; +import { useState, useMemo } from "react"; +import { Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, CheckCircle2, UserRound, X } from "lucide-react"; +import * as VisuallyHidden from "@radix-ui/react-visually-hidden"; +import { Pencil, CheckCircle2, UserRound, X, Shield, KeyRound, Building2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; -import { BentoGrid, BentoCard, InfoRow, CollapsibleSection, EmptyState, AuditLog } from "@/components/viewPageComponents"; -import { DataTableToolbar } from "@/components/dataTableToolbar"; +import { + AlertDialog, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; import { FormInput } from "@/components/formInput"; import { AvatarUpload } from "@/components/avatarUpload"; import { FormActions } from "@/components/formActions"; +import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect"; import { useAuthStore } from "@/app/store/authStore"; import { useProfile, useUpdateProfile } from "@/features/auth/hooks/useLogin"; +import { useInfiniteRoles } from "@/features/roles/hooks/useRoles"; +import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions"; +import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers"; +import { useInfiniteStaff } from "@/features/operators/hooks/useOperators"; +import { useAssignRoleToUser, useAssignPermissionToUser, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments"; +import type { LocalizedText } from "@/features/branches/api/branchesApi"; + +type AssignDialogKind = "role" | "permission" | "branch"; export default function ProfilePage() { - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); const { data: profileQueryData, isLoading } = useProfile(); const authUser = useAuthStore((s) => s.user); const user = profileQueryData ?? authUser; @@ -20,10 +38,11 @@ export default function ProfilePage() { const updateProfileMutation = useUpdateProfile(); const [isEditing, setIsEditing] = useState(false); + const [assignDialog, setAssignDialog] = useState(null); - const [roleSearch, setRoleSearch] = useState(""); - const [permSearch, setPermSearch] = useState(""); - const [branchSearch, setBranchSearch] = useState(""); + const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText; + + const branches = user?.branches ?? []; // ── Form State for Editing ── const [formData, setFormData] = useState({ @@ -36,17 +55,18 @@ export default function ProfilePage() { const [errors, setErrors] = useState>({}); - useEffect(() => { - if (user) { - setFormData({ - name: user.name ?? "", - firstName: user.firstName ?? "", - lastName: user.lastName ?? "", - phone: user.phone ?? "", - avatar: user.avatar ?? "", - }); - } - }, [user, isEditing]); + const startEditing = () => { + if (!user) return; + setFormData({ + name: user.name ?? "", + firstName: user.firstName ?? "", + lastName: user.lastName ?? "", + phone: user.phone ?? "", + avatar: user.avatar ?? "", + }); + setErrors({}); + setIsEditing(true); + }; const handleFieldChange = (field: keyof typeof formData, value: string) => { setFormData((prev) => ({ ...prev, [field]: value })); @@ -102,132 +122,138 @@ export default function ProfilePage() { return (
- {/* ── Title + actions ──────────────────────────────────────────────── */} -
-

- {isEditing ? t("profile.editTitle", "Profili üýtgetmek") : `${t("profile.title", "Meniň profilim")}: ${user.name}`} -

-
- {!isEditing ? ( - - ) : ( - - )} + {/* ── Profile hero ─────────────────────────────────────────────────── */} + {!isEditing ? ( +
+
+ {user.avatar ? ( + avatar + ) : ( +
+ +
+ )} +
+
+

+ {[user.firstName, user.lastName].filter(Boolean).join(" ") || user.name} +

+ + + {t("common.active", "Işjeň")} + +
+

+ @{user.name} + {user.phone ? ` · ${user.phone}` : ""} +

+
+
+
-
+ ) : ( +
+

{t("profile.editTitle", "Profili üýtgetmek")}

+ +
+ )} {/* ── Main content ─────────────────────────────────────────────────── */} {!isEditing ? ( <> - - -
- {user.avatar ? ( - avatar - ) : ( -
- -
- )} -
-

- {[user.firstName, user.lastName].filter(Boolean).join(" ") || user.name} -

- {user.phone &&

{user.phone}

} -
-
- + + - - - - {user.role && } - {user.email && } - -
- - {t("common.active", "Işjeň")} -
-
+ {user.email && } +
+ + + + +
- {/* ── Rollar ───────────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("users.actions.addRole", "Rol birikdiriň")} - onAction={() => {}} - /> - - + + + + {user.role ? ( + + + {user.role.name} + + ) : ( + — + )} + - {/* ── Rugsatlar ────────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("users.actions.addPermission", "Rugsat birikdiriň")} - onAction={() => {}} - /> - - + + {branches.length > 0 ? ( +
+ {branches.map((b) => ( + + + + {b.name?.[lang] || b.name?.tm || b.name?.en || b.name?.ru || b.uniqueCode || b.id} + + + ))} +
+ ) : ( + — + )} +
- {/* ── Şahamçalar ───────────────────────────────────────────────────── */} - - {}} - columnOrder={[]} - onColumnOrderChange={() => {}} - actionLabel={t("users.actions.addBranch", "Şahamça birikdiriň")} - onAction={() => {}} - /> - - + + — + +
- {/* ── Ammallar ─────────────────────────────────────────────────────── */} - - - + +
+ + + +
+
+
) : (
@@ -288,6 +314,175 @@ export default function ProfilePage() {
)} + + {/* ── Assign dialog (staff user + role/permission/branch) ─────────────── */} + {assignDialog && setAssignDialog(null)} />}
); } + +// ─── Assign dialog ──────────────────────────────────────────────────────────── + +const ASSIGN_DIALOG_TITLES: Record = { + role: "profile.actions.assignRole", + permission: "profile.actions.assignPermission", + branch: "profile.actions.assignBranch", +}; + +const ASSIGN_DIALOG_FIELD_LABELS: Record = { + 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(); + + 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 ( + !open && onClose()}> + + + {t(ASSIGN_DIALOG_TITLES[kind])} + + {t(ASSIGN_DIALOG_TITLES[kind])} + + + +
+ { + 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} + /> + + { + 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} + /> +
+ + + + + +
+
+ ); +}