From 5ed4c9a8ec96616069e77030816437f0bde6d514 Mon Sep 17 00:00:00 2001 From: Jelaletdin12 Date: Thu, 3 Sep 2026 20:31:34 +0500 Subject: [PATCH] fixed some ui, upgrade functionalitym added permission to operator --- src/components/formActions.tsx | 71 +++--- src/components/formInput.tsx | 196 +++++++++++++++- src/components/viewPageComponents.tsx | 94 +++++++- src/features/allUsers/api/allUsersApi.ts | 4 +- .../components/cardBalanceForm.tsx | 4 +- .../cardPins/components/cardPinForm.tsx | 8 +- .../components/cardRequisiteForm.tsx | 9 +- .../components/cardTransactionForm.tsx | 52 ++++- src/features/clients/api/clientsApi.ts | 3 +- .../components/loanOrderMobileForm.tsx | 39 ++-- .../loanOrders/components/loanOrderForm.tsx | 45 ++-- .../loanOrders/schemas/loanOrder.schema.ts | 7 +- .../components/LoanPaidOffLetterForm.tsx | 23 +- .../operators/components/operatorForms.tsx | 59 ++++- .../components/orderNewCardForm.tsx | 4 +- src/features/shared/api/sharedApi.ts | 18 +- .../shared/components/assignDialog.tsx | 214 ++++++++++++++++++ .../shared/hooks/useSharedUserAssignments.ts | 26 ++- src/lib/i18n/locales/en.json | 2 +- src/lib/i18n/locales/ru.json | 2 +- src/lib/i18n/locales/tk.json | 4 +- src/pages/backupsView/index.tsx | 48 +--- .../cardDepartment/cardBalanceView/index.tsx | 57 +---- .../cardDepartment/cardPinsView/index.tsx | 67 +----- .../cardRequisitesView/index.tsx | 59 +---- .../cardTransactionsView/index.tsx | 64 +----- .../cardDepartment/orderNewCardView/index.tsx | 65 +----- .../currencies/currencyRatesView/index.tsx | 49 ++-- .../sberPaymentsView/index.tsx | 37 +-- .../visaMasterPaymentsView/index.tsx | 44 ++-- .../loanOrderMobileView/index.tsx | 48 +--- .../loanDepartment/loanOrderView/index.tsx | 48 +--- .../loanPaidOffLettersView/index.tsx | 45 +--- .../loanRemainingView/index.tsx | 48 +--- src/pages/profile/index.tsx | 208 +---------------- .../settings/card/cardTypesView/index.tsx | 64 +----- src/pages/settings/card/reasonsView/index.tsx | 66 +----- .../settings/loan/loanTypesView/index.tsx | 69 ++---- .../loan/requiredDocumentsView/index.tsx | 40 +--- .../settings/location/branchesView/index.tsx | 64 +----- .../settings/location/districtsView/index.tsx | 64 +----- .../settings/users/permissionsView/index.tsx | 67 +----- src/pages/settings/users/rolesView/index.tsx | 67 +----- src/pages/users/allUsersView/index.tsx | 55 ++--- src/pages/users/clientsView/index.tsx | 70 +++--- src/pages/users/operatorsView/index.tsx | 62 ++--- 46 files changed, 1058 insertions(+), 1401 deletions(-) create mode 100644 src/features/shared/components/assignDialog.tsx diff --git a/src/components/formActions.tsx b/src/components/formActions.tsx index 0bd9158..e787215 100644 --- a/src/components/formActions.tsx +++ b/src/components/formActions.tsx @@ -1,23 +1,29 @@ -import type { ReactNode } from 'react' -import { useTranslation } from 'react-i18next' -import { Loader2 } from 'lucide-react' -import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import type { ReactNode } from "react"; +import { useTranslation } from "react-i18next"; +import { Loader2 } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; interface FormActionsProps { - isPending?: boolean - onSubmit?: () => void - onCancel?: () => void - submitLabel?: ReactNode - cancelLabel?: ReactNode - loadingLabel?: ReactNode - cancelVariant?: 'outline' | 'ghost' - className?: string - onNext?: () => void - onPrev?: () => void - nextLabel?: ReactNode - prevLabel?: ReactNode - showSubmit?: boolean + isPending?: boolean; + onSubmit?: () => void; + onCancel?: () => void; + submitLabel?: ReactNode; + cancelLabel?: ReactNode; + loadingLabel?: ReactNode; + cancelVariant?: "outline" | "ghost"; + className?: string; + onNext?: () => void; + onPrev?: () => void; + nextLabel?: ReactNode; + prevLabel?: ReactNode; + showSubmit?: boolean; + /** + * When true and not on the last step, render an extra "Save" button so an + * edit can be persisted without navigating through every step. Suppressed + * on the last step to avoid a duplicate submit button. + */ + saveOnEveryStep?: boolean; } export function FormActions({ @@ -27,23 +33,24 @@ export function FormActions({ submitLabel, cancelLabel, loadingLabel, - cancelVariant = 'outline', + cancelVariant = "outline", className, onNext, onPrev, nextLabel, prevLabel, showSubmit = true, + saveOnEveryStep = false, }: FormActionsProps) { - const { t } = useTranslation() + const { t } = useTranslation(); - const cancelText = cancelLabel ?? t('common.cancel', 'Ýatyr') - const loadingText = loadingLabel ?? t('common.saving', 'Saklanýar...') - const prevText = prevLabel ?? t('common.prev', 'Yza') - const nextText = nextLabel ?? t('common.next', 'Indiki') + const cancelText = cancelLabel ?? t("common.cancel", "Ýatyr"); + const loadingText = loadingLabel ?? t("common.saving", "Saklanýar..."); + const prevText = prevLabel ?? t("common.prev", "Yza"); + const nextText = nextLabel ?? t("common.next", "Indiki"); return ( -
+
{onCancel && ( )} + {saveOnEveryStep && onSubmit && !showSubmit && ( + + )} {showSubmit && onSubmit && ( )}
- ) + ); } diff --git a/src/components/formInput.tsx b/src/components/formInput.tsx index 9d8e186..788c442 100644 --- a/src/components/formInput.tsx +++ b/src/components/formInput.tsx @@ -1,6 +1,6 @@ import { useState, useRef, useEffect } from "react"; import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"; -import { Check, ChevronsUpDown, Search, X, Eye, EyeOff, Upload, Hash } from "lucide-react"; +import { Check, ChevronsUpDown, Search, X, Eye, EyeOff, Upload, Hash, CreditCard } from "lucide-react"; import { cn, cleanPhoneNumber } from "@/lib/utils"; import { Input } from "@/components/ui/input"; @@ -29,7 +29,11 @@ export type FormInputType = | "select" | "searchable-select" | "file" - | "textarea"; + | "textarea" + | "card-number" + | "card-name" + | "passport-id" + | "digits"; export interface SelectOption { value: string; @@ -54,6 +58,7 @@ export interface FormInputProps { rows?: number; name?: string; readOnly?: boolean; + maxLength?: number; } // ─── FieldLabel ─────────────────────────────────────────────────────────────── @@ -277,6 +282,189 @@ function PhoneInput({ ); } +// ─── formatCardNumber helper ────────────────────────────────────────────────── + +export function formatCardNumber(value?: string | null): string { + if (!value) return ""; + const digits = value.replace(/\D/g, "").slice(0, 16); + return digits.replace(/(\d{4})(?=\d)/g, "$1 "); +} + +// ─── CardNumberInput ────────────────────────────────────────────────────────── + +export function CardNumberInput({ + value = "", + onChange, + placeholder = "9999 9999 9999 9999", + error, + disabled, + required, + label, + className, + name, + readOnly, +}: FormInputProps) { + const handleChange = (e: React.ChangeEvent) => { + const formatted = formatCardNumber(e.target.value); + onChange?.(formatted); + }; + + const display = formatCardNumber(value); + + return ( +
+ +
+ + +
+ +
+ ); +} + +// ─── CardNameInput ──────────────────────────────────────────────────────────── + +export function CardNameInput({ + value = "", + onChange, + placeholder, + error, + disabled, + required, + label, + className, + name, + readOnly, +}: FormInputProps) { + const handleChange = (e: React.ChangeEvent) => { + // Only characters (letters in any alphabet) and spaces + const sanitized = e.target.value.replace(/[^\p{L}\s]/gu, ""); + onChange?.(sanitized); + }; + + const display = (value || "").replace(/[^\p{L}\s]/gu, ""); + + return ( +
+ +
+ +
+ +
+ ); +} + +// ─── PassportIdInput ────────────────────────────────────────────────────────── + +export function PassportIdInput({ + value = "", + onChange, + placeholder = "999999", + error, + disabled, + required, + label, + className, + name, + readOnly, +}: FormInputProps) { + const handleChange = (e: React.ChangeEvent) => { + const digits = e.target.value.replace(/\D/g, "").slice(0, 6); + onChange?.(digits); + }; + + const display = (value || "").replace(/\D/g, "").slice(0, 6); + + return ( +
+ +
+ +
+ +
+ ); +} + +// ─── DigitsInput ────────────────────────────────────────────────────────────── + +export function DigitsInput({ + value = "", + onChange, + placeholder, + error, + disabled, + required, + label, + className, + name, + readOnly, + maxLength, +}: FormInputProps) { + const handleChange = (e: React.ChangeEvent) => { + const raw = e.target.value.replace(/\D/g, ""); + const digits = maxLength ? raw.slice(0, maxLength) : raw; + onChange?.(digits); + }; + + const rawDisplay = (value || "").replace(/\D/g, ""); + const display = maxLength ? rawDisplay.slice(0, maxLength) : rawDisplay; + + return ( +
+ +
+ +
+ +
+ ); +} + // ─── DateInput (shadcn Popover + Calendar) ─────────────────────────────────── function DateInput({ value = "", onChange, error, disabled, required, label, className, placeholder = "Sene saýlaň" }: FormInputProps) { @@ -726,6 +914,10 @@ export function FormInput(props: FormInputProps) { if (type === "number") return ; if (type === "phone") return ; + if (type === "card-number") return ; + if (type === "card-name") return ; + if (type === "passport-id") return ; + if (type === "digits") return ; if (type === "date") return ; if (type === "select") return ; if (type === "searchable-select") return ; diff --git a/src/components/viewPageComponents.tsx b/src/components/viewPageComponents.tsx index 0f67cf5..ecf8868 100644 --- a/src/components/viewPageComponents.tsx +++ b/src/components/viewPageComponents.tsx @@ -1,7 +1,18 @@ import { useMemo, useState } from "react"; -import { Download, Eye, ChevronDown, Inbox } from "lucide-react"; +import { Download, Eye, ChevronDown, Inbox, Pencil, Trash2 } from "lucide-react"; import { useTranslation } from "react-i18next"; import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; import { DataTable, type ColumnDef } from "@/components/dataTable"; import { Link } from "react-router-dom"; @@ -320,6 +331,87 @@ export function EmptyState({ label }: EmptyStateProps) { ); } +// ─── ViewActions ────────────────────────────────────────────────────────────── +// Standard edit (→ `/edit` route) + delete (with confirmation AlertDialog) +// action buttons rendered in a view page header. Delete validation and the +// destructive mutation itself live in the caller's `onDelete`; this component +// only handles the dialog flow (open → confirm → close). + +export interface ViewActionsProps { + editTo?: string; + onDelete?: () => void | Promise; + deleteTitle?: string; + deleteDescription?: string; + deleting?: boolean; + deleteConfirmLabel?: string; + editDisabled?: boolean; + deleteDisabled?: boolean; +} + +export function ViewActions({ + editTo, + onDelete, + deleteTitle, + deleteDescription, + deleting, + deleteConfirmLabel, + editDisabled, + deleteDisabled, +}: ViewActionsProps) { + const { t } = useTranslation(); + const [deleteOpen, setDeleteOpen] = useState(false); + + const handleConfirm = async () => { + await onDelete?.(); + setDeleteOpen(false); + }; + + return ( +
+ {editTo && ( + + )} + + {onDelete && ( + + )} + + + + + {deleteTitle ?? t("Are you sure?", "Eminsiňizmi?")} + + {deleteDescription ?? t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz.")} + + + + {t("Cancel", "Ýatyr")} + + {deleting ? t("Deleting...", "Öçürilýär...") : (deleteConfirmLabel ?? t("Delete", "Öçür"))} + + + + +
+ ); +} + // ─── AuditLog ───────────────────────────────────────────────────────────────── export function AuditLog({ logs, currentPage, totalPages, totalCount, onPageChange, isLoading, onView }: AuditLogProps) { diff --git a/src/features/allUsers/api/allUsersApi.ts b/src/features/allUsers/api/allUsersApi.ts index be82823..8c72d76 100644 --- a/src/features/allUsers/api/allUsersApi.ts +++ b/src/features/allUsers/api/allUsersApi.ts @@ -72,8 +72,10 @@ export const usersApi = { /** GET /users — backend filters by `username` */ getUsers: async (params: UsersListParams = {}, signal?: AbortSignal): Promise => { const { page, limit, search, isActive } = params; + const queryParams: Record = { page, limit, isActive }; + if (search) queryParams.username = search; const { data } = await apiClient.get("/users", { - params: { page, limit, username: search, isActive }, + params: queryParams, signal, }); return data; diff --git a/src/features/cardBalance/components/cardBalanceForm.tsx b/src/features/cardBalance/components/cardBalanceForm.tsx index 3454f75..6be45a3 100644 --- a/src/features/cardBalance/components/cardBalanceForm.tsx +++ b/src/features/cardBalance/components/cardBalanceForm.tsx @@ -151,13 +151,13 @@ export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) { label={t("Passport number", "Pasport belgisi")} value={form.passportNumber} onChange={setString("passportNumber")} - placeholder={t("Passport number", "Pasport belgisi")} + placeholder="999999" error={errMsg(errors.passportNumber)} required /> set("cardNumber", v)} - placeholder={t("cardPin.field.cardNumber", "Kart belgisi")} + placeholder="9999 9999 9999 9999" error={errors.cardNumber} /> set("passportId", v)} - placeholder={t("cardPin.field.passportId", "Pasport belgisi")} + placeholder="999999" error={errors.passportId} />
diff --git a/src/features/cardRequisites/components/cardRequisiteForm.tsx b/src/features/cardRequisites/components/cardRequisiteForm.tsx index cf24d81..82a36dc 100644 --- a/src/features/cardRequisites/components/cardRequisiteForm.tsx +++ b/src/features/cardRequisites/components/cardRequisiteForm.tsx @@ -258,7 +258,7 @@ function StepCard({ form, errors, set, t, initialData, userLocked, selfUserId, u set("cardNumber", v)} @@ -439,12 +439,12 @@ function StepPassport({ form, errors, set, t }: StepContentProps) { set("passportId", v)} - placeholder={t("Passport id") || "Pasport belgisi"} + placeholder="999999" error={errors.passportId} /> @@ -683,7 +683,8 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps) onNext={!isLastStep ? handleNext : undefined} nextLabel={t("Next", "Indiki")} showSubmit={isLastStep} - onSubmit={isLastStep ? handleSubmit : undefined} + saveOnEveryStep={mode === "edit"} + onSubmit={handleSubmit} submitLabel={ mode === "create" ? t("Create card requisite order", "Kart rekwiziti üçin sargyt dörediň") diff --git a/src/features/cardTransactions/components/cardTransactionForm.tsx b/src/features/cardTransactions/components/cardTransactionForm.tsx index 8ef268c..af39684 100644 --- a/src/features/cardTransactions/components/cardTransactionForm.tsx +++ b/src/features/cardTransactions/components/cardTransactionForm.tsx @@ -27,6 +27,8 @@ interface CardTransactionFormProps { type FlatErrors = Partial>; +type CardiacTransactionLoose = Partial>; + function flattenErrors(errors: Record): FlatErrors { const result: FlatErrors = {}; for (const key of Object.keys(errors)) { @@ -92,18 +94,43 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, - number: initialData.number, - name: initialData.name, - type: initialData.type, - month: initialData.month, - year: initialData.year, + number: initialData.number ?? "", + name: initialData.name ?? "", + type: initialData.type ?? "", + month: initialData.month ?? "", + year: initialData.year ?? "", userId: userLocked ? selfUserId : String(initialData.user?.id ?? ""), } : { ...DEFAULT_FORM_VALUES, userId: selfUserId }, }); const form = watch(); - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); + + // Live schema errors, only surfaced once the user attempts to submit, so + // required-field warnings reliably show under fields (avoids RHF setError + // snapshot timing; mirrors the step-based forms' submitted validation). + const [submitAttempted, setSubmitAttempted] = useState(false); + + const liveErrors = useMemo(() => { + if (!submitAttempted) return {}; + const normalized: CardiacTransactionLoose = { ...DEFAULT_FORM_VALUES, ...form }; + for (const key of Object.keys(DEFAULT_FORM_VALUES) as (keyof CardTransactionFormData)[]) { + if (normalized[key] == null) normalized[key] = ""; + } + const parsed = cardTransactionFormSchema.safeParse(normalized); + if (parsed.success) return {}; + const result: FlatErrors = {}; + for (const issue of parsed.error.issues) { + const key = issue.path[0] as keyof CardTransactionFormData; + result[key] = issue.message; + } + return result; + }, [submitAttempted, form]); + + const errors = useMemo(() => { + const fromRHF = flattenErrors(rhfErrors as Record); + return { ...fromRHF, ...liveErrors }; + }, [rhfErrors, liveErrors]); const createMutation = useCreateCardTransaction(); const updateMutation = useUpdateCardTransaction(initialData?.id ?? 0); @@ -118,8 +145,13 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg); const handleSubmit = async () => { - const result = cardTransactionFormSchema.safeParse(getValues()); + const raw: CardiacTransactionLoose = { ...DEFAULT_FORM_VALUES, ...getValues() }; + for (const key of Object.keys(DEFAULT_FORM_VALUES) as (keyof CardTransactionFormData)[]) { + if (raw[key] == null) raw[key] = ""; + } + const result = cardTransactionFormSchema.safeParse(raw); if (!result.success) { + setSubmitAttempted(true); for (const issue of result.error.issues) { const key = issue.path[0] as keyof CardTransactionFormData; setError(key, { message: issue.message }); @@ -154,7 +186,7 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
{/* Name */} diff --git a/src/features/clients/api/clientsApi.ts b/src/features/clients/api/clientsApi.ts index d0ea2e6..2c1ad4f 100644 --- a/src/features/clients/api/clientsApi.ts +++ b/src/features/clients/api/clientsApi.ts @@ -1,4 +1,5 @@ import apiClient from "@/lib/api/client"; +import type { LocalizedText } from "@/features/branches/api/branchesApi"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -49,7 +50,7 @@ export interface ClientPermission { export interface ClientBranch { id: number; - name: string; + name: LocalizedText | string; region: string; district: string; uniqueCode: string; diff --git a/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx b/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx index 791a048..5ea68f0 100644 --- a/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx +++ b/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx @@ -483,16 +483,16 @@ function StepCard({ form, errors, set, t }: StepContentProps) { set("cardNumber", v)} - placeholder={t("Card number") || "Kart belgisi"} + placeholder="9999 9999 9999 9999" error={errors.cardNumber} /> set("passportId", v)} - placeholder={t("Passport id") || "Pasport belgisi"} + placeholder="999999" error={errors.passportId} /> @@ -675,11 +675,11 @@ function StepContact({ form, errors, set, t }: StepContentProps) { error={errors.phoneAdditional} /> set("phoneHome", v)} - placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} + placeholder={t("Home phone") || "Öý telefony"} error={errors.phoneHome} /> @@ -842,12 +842,12 @@ function StepGuarantor({ form, errors, set, t }: StepContentProps) { set("guarantorPassportId", v)} - placeholder={t("Passport id") || "Pasport belgisi"} + placeholder="999999" error={errors.guarantorPassportId} /> @@ -856,16 +856,16 @@ function StepGuarantor({ form, errors, set, t }: StepContentProps) { set("guarantorCardNumber", v)} - placeholder={t("Card number") || "Kart belgisi"} + placeholder="9999 9999 9999 9999" error={errors.guarantorCardNumber} /> set("guarantor2PassportId", v)} - placeholder={t("Passport id") || "Pasport belgisi"} + placeholder="999999" error={errors.guarantor2PassportId} /> @@ -964,15 +964,15 @@ function StepGuarantor2({ form, errors, set, t }: StepContentProps) { set("guarantor2CardNumber", v)} - placeholder={t("Card number") || "Kart belgisi"} + placeholder="9999 9999 9999 9999" error={errors.guarantor2CardNumber} /> set("guarantor2CardName", v)} @@ -1198,7 +1198,8 @@ export function LoanOrderMobileForm({ initialData, mode }: LoanOrderMobileFormPr onPrev={currentStep > 0 ? handleBack : undefined} onNext={!isLastStep ? handleNext : undefined} showSubmit={isLastStep} - onSubmit={isLastStep ? doSubmit : undefined} + saveOnEveryStep={mode === "edit"} + onSubmit={doSubmit} submitLabel={mode === "create" ? t("loanOrders.create") || "Karz sargyt döredüň" : t("common.save") || "Ýatda sakla"} loadingLabel={t("common.loading") || "Ýüklenilýär..."} cancelLabel={t("common.cancel") || "Ýatyr"} @@ -1236,7 +1237,7 @@ function mapInitial(order: LoanOrderMobile): Partial { email: order.email ?? "", phone: formatFromApiPhone(order.phone), phoneAdditional: formatFromApiPhone(order.phoneAdditional), - phoneHome: formatFromApiPhone(order.phoneHome), + phoneHome: (order.phoneHome ?? order.homePhone ?? "").replace(/\D/g, ""), workCompany: order.workCompany ?? "", workCompanyAccountantNumber: formatFromApiPhone(order.workCompanyAccountantNumber), workRegion: order.workRegion ?? "AG", diff --git a/src/features/loanOrders/components/loanOrderForm.tsx b/src/features/loanOrders/components/loanOrderForm.tsx index c56137b..8b8ae5f 100644 --- a/src/features/loanOrders/components/loanOrderForm.tsx +++ b/src/features/loanOrders/components/loanOrderForm.tsx @@ -279,14 +279,14 @@ function StepLoan({ form, errors, set, t, initialData }: StepContentProps & { in set("loanCardNumber", v)} - placeholder={t("Loan card number") || "Karz kart belgisi"} + placeholder="9999 9999 9999 9999" /> set("loanCardName", v)} @@ -538,16 +538,16 @@ function StepCard({ form, errors, set, t }: StepContentProps) { set("cardNumber", v)} - placeholder={t("Card number") || "Kart belgisi"} + placeholder="9999 9999 9999 9999" error={errors.cardNumber} /> set("passportId", v)} - placeholder={t("Passport id") || "Pasport belgisi"} + placeholder="999999" error={errors.passportId} /> @@ -721,11 +721,11 @@ function StepContact({ form, errors, set, t }: StepContentProps) { error={errors.phoneAdditional} /> set("phoneHome", v)} - placeholder={t("loanOrderForm.placeholders.phone") || "61 097 651"} + placeholder={t("Home phone") || "Öý telefony"} error={errors.phoneHome} /> @@ -890,12 +890,12 @@ function StepGuarantor({ form, errors, set, t }: StepContentProps) { set("guarantorPassportId", v)} - placeholder={t("Passport id") || "Pasport belgisi"} + placeholder="999999" error={errors.guarantorPassportId} /> @@ -904,16 +904,16 @@ function StepGuarantor({ form, errors, set, t }: StepContentProps) { set("guarantorCardNumber", v)} - placeholder={t("Card number") || "Kart belgisi"} + placeholder="9999 9999 9999 9999" error={errors.guarantorCardNumber} /> set("guarantor2PassportId", v)} - placeholder={t("Passport id") || "Pasport belgisi"} + placeholder="999999" error={errors.guarantor2PassportId} /> @@ -1022,15 +1022,15 @@ function StepGuarantor2({ form, errors, set, t }: StepContentProps) { set("guarantor2CardNumber", v)} - placeholder={t("Card number") || "Kart belgisi"} + placeholder="9999 9999 9999 9999" error={errors.guarantor2CardNumber} /> set("guarantor2CardName", v)} @@ -1270,7 +1270,8 @@ export function LoanOrderForm({ mode, initialData }: LoanOrderFormProps) { onPrev={currentStep > 0 ? handleBack : undefined} onNext={!isLastStep ? handleNext : undefined} showSubmit={isLastStep} - onSubmit={isLastStep ? doSubmit : undefined} + saveOnEveryStep={mode === "edit"} + onSubmit={doSubmit} submitLabel={mode === "create" ? t("loanOrders.create") || "Karz sargyt döredüň" : t("common.save") || "Ýatda sakla"} loadingLabel={t("common.loading") || "Ýüklenilýär..."} cancelLabel={t("common.cancel") || "Ýatyr"} @@ -1325,7 +1326,7 @@ function mapInitial(order: LoanOrder): Partial { passportFour: order.passportFour ?? order.passportPage32Url ?? "", phone: formatFromApiPhone(order.phone), phoneAdditional: formatFromApiPhone(order.phoneAdditional), - phoneHome: formatFromApiPhone(order.phoneHome ?? order.homePhone), + phoneHome: (order.phoneHome ?? order.homePhone ?? "").replace(/\D/g, ""), email: order.email ?? "", workCompany: order.workCompany ?? "", workCompanyAccountantNumber: formatFromApiPhone(order.workCompanyAccountantNumber ?? order.workHrPhone), diff --git a/src/features/loanOrders/schemas/loanOrder.schema.ts b/src/features/loanOrders/schemas/loanOrder.schema.ts index ffcaa92..539464b 100644 --- a/src/features/loanOrders/schemas/loanOrder.schema.ts +++ b/src/features/loanOrders/schemas/loanOrder.schema.ts @@ -68,11 +68,8 @@ export const loanOrderFormSchema = z.object({ .optional(), phoneHome: z .string() - .refine((val) => !val || val.replace(/\D/g, "").length === 0 || val.replace(/\D/g, "").length === 8, { - message: "validation.invalidPhone", - }) - .refine((val) => !val || val.replace(/\D/g, "").length === 0 || VALID_PHONE_PREFIXES.includes(val.replace(/\D/g, "").slice(0, 2)), { - message: "validation.invalidPhonePrefix", + .refine((val) => !val || /^\d+$/.test(val.replace(/\s/g, "")), { + message: "validation.invalidNumber", }) .optional(), email: z.string().optional(), diff --git a/src/features/loanPaidOffLetters/components/LoanPaidOffLetterForm.tsx b/src/features/loanPaidOffLetters/components/LoanPaidOffLetterForm.tsx index eafc666..28fe1a2 100644 --- a/src/features/loanPaidOffLetters/components/LoanPaidOffLetterForm.tsx +++ b/src/features/loanPaidOffLetters/components/LoanPaidOffLetterForm.tsx @@ -182,11 +182,11 @@ function StepPassport({ form, errors, set, t }: StepContentProps) { required /> @@ -427,7 +427,21 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo }); const form = watch(); - const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]); + + // Live-recomputed validation errors for submitted steps, so required-field + // warnings stay visible under fields (mirrors loanOrderForm behavior). + const allSubmittedErrors = useMemo(() => { + const result: FlatErrors = {}; + for (const stepIdx of submittedSteps) { + Object.assign(result, STEPS[stepIdx].validate(form)); + } + return result; + }, [form, submittedSteps]); + + const errors = useMemo(() => { + const fromRHF = flattenErrors(rhfErrors as Record); + return { ...fromRHF, ...allSubmittedErrors }; + }, [rhfErrors, allSubmittedErrors]); const set = useCallback( (key: K) => @@ -586,7 +600,8 @@ export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFo onPrev={currentStep > 0 ? handleBack : undefined} onNext={!isLastStep ? handleNext : undefined} showSubmit={isLastStep} - onSubmit={isLastStep ? doSubmit : undefined} + saveOnEveryStep={mode === "edit"} + onSubmit={doSubmit} submitLabel={mode === "create" ? t("common.create", "Döret") : t("common.save", "Ýatda sakla")} loadingLabel={t("common.loading", "Ýüklenilýär...")} cancelLabel={t("common.cancel", "Ýatyr")} diff --git a/src/features/operators/components/operatorForms.tsx b/src/features/operators/components/operatorForms.tsx index 24821da..835c4ea 100644 --- a/src/features/operators/components/operatorForms.tsx +++ b/src/features/operators/components/operatorForms.tsx @@ -8,9 +8,13 @@ import { FormInput } from "@/components/formInput"; import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect"; import { Checkbox } from "@/components/ui/checkbox"; import { Label } from "@/components/ui/label"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { KeyRound } from "lucide-react"; import { FormActions } from "@/components/formActions"; import { AvatarUpload } from "@/components/avatarUpload"; import { BentoGrid, BentoCard } from "@/components/bento"; +import { AssignDialog, type AssignDialogKind } from "@/features/shared/components/assignDialog"; import { useCreateOperator, useUpdateOperator, operatorKeys } from "../hooks/useOperators"; import { useInfiniteRoles } from "@/features/roles/hooks/useRoles"; import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers"; @@ -62,6 +66,9 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) { const isPending = createOperator.isPending || updateOperator.isPending; + const [assignDialog, setAssignDialog] = useState(null); + const operatorPermissions = (initialData as OperatorDetail | undefined)?.permissions ?? []; + const schema = useMemo(() => operatorFormSchema(mode, t), [mode, t, i18n.language]); // ── Role infinite-scroll select ── @@ -210,9 +217,17 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) { return (
-

- {mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")} -

+
+

+ {mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")} +

+ {mode === "edit" && ( + + )} +
{/* ── Identity ── */} @@ -358,6 +373,29 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) { />
+ + {/* ── Permissions (Edit mode only) ── */} + {mode === "edit" && ( + +
+
+ {operatorPermissions.length > 0 ? ( + operatorPermissions.map((p) => ( + + {p.name} + + )) + ) : ( + {t("common.noData", "Rugsat ýok")} + )} +
+ +
+
+ )}
navigate(-1)} submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")} /> + + {/* ── Assign dialog (edit mode only) ── */} + {mode === "edit" && assignDialog && initialData?.id && ( + { + queryClient.invalidateQueries({ queryKey: operatorKeys.detail(initialData.id) }); + }} + onClose={() => setAssignDialog(null)} + /> + )}
); } diff --git a/src/features/orderNewCard/components/orderNewCardForm.tsx b/src/features/orderNewCard/components/orderNewCardForm.tsx index ae9f3ad..c4d2e60 100644 --- a/src/features/orderNewCard/components/orderNewCardForm.tsx +++ b/src/features/orderNewCard/components/orderNewCardForm.tsx @@ -335,12 +335,12 @@ function StepPassport({ form, errors, set, t, mode }: StepContentProps) { error={errors.passportSerie} /> set("passportId", v)} - placeholder={t("cardOrder.field.passportId", "Pasport belgisi")} + placeholder="999999" error={errors.passportId} /> { + await apiClient.post("/permission-users", { + permissionId: payload.permissionId, + userId: payload.userId, + effect: payload.effect ?? "allow", + }); +} /** * Proxy for branch list fetching — kept here so shared hooks diff --git a/src/features/shared/components/assignDialog.tsx b/src/features/shared/components/assignDialog.tsx new file mode 100644 index 0000000..2ceeb63 --- /dev/null +++ b/src/features/shared/components/assignDialog.tsx @@ -0,0 +1,214 @@ +import { useState, useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import * as VisuallyHidden from "@radix-ui/react-visually-hidden"; +import { Button } from "@/components/ui/button"; +import { + AlertDialog, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect"; +import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers"; +import { useInfiniteRoles } from "@/features/roles/hooks/useRoles"; +import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions"; +import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers"; +import { useAssignRoleToUser, useAssignPermissionToUser, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments"; +import type { LocalizedText } from "@/features/branches/api/branchesApi"; + +export type AssignDialogKind = "role" | "permission" | "branch"; + +export interface AssignDialogProps { + kind: AssignDialogKind; + onClose: () => void; + targetUserId?: number; + targetUserName?: string; + onAssigned?: () => void; +} + +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, or branch to a user (staff). + * Permissions are assigned directly to users via POST /permission-users. + */ +export function AssignDialog({ kind, onClose, targetUserId, targetUserName, onAssigned }: AssignDialogProps) { + const { t, i18n } = useTranslation(); + const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText; + + const [targetSearch, setTargetSearch] = useState(""); + const [targetValue, setTargetValue] = useState(() => (targetUserId ? String(targetUserId) : "")); + const [resourceSearch, setResourceSearch] = useState(""); + const [resourceValue, setResourceValue] = useState(""); + const [error, setError] = useState(); + + // Target query: admin users list (GET /users) + const staffQuery = useInfiniteUsers(targetSearch); + + // Resource queries + 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 targetOptions: InfiniteSelectOption[] = useMemo(() => { + const opts: InfiniteSelectOption[] = (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), + })); + + if (targetUserId) { + const valStr = String(targetUserId); + if (!opts.some((o) => o.value === valStr)) { + opts.unshift({ value: valStr, label: targetUserName || valStr }); + } + } + return opts; + }, [staffQuery.data, targetUserId, targetUserName]); + + const targetLabel = t("profile.assign.userLabel", "Ulanyjy"); + const targetLoading = staffQuery.isLoading; + const targetLoadingMore = staffQuery.isFetchingNextPage; + const targetHasNextPage = !!staffQuery.hasNextPage; + const loadMoreTargets = () => staffQuery.fetchNextPage(); + + 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 (!targetValue || !resourceValue) { + setError(t("common.errors.required", "Meýdança hökmany doldurylmaly")); + return; + } + setError(undefined); + + const userId = Number(targetValue); + const secondId = Number(resourceValue); + const onSuccess = () => { + setResourceValue(""); + onAssigned?.(); + onClose(); + }; + + if (kind === "role") { + roleMutation.mutate({ userId, roleId: secondId }, { onSuccess }); + } else if (kind === "permission") { + permissionMutation.mutate({ userId, permissionId: secondId, effect: "allow" }, { onSuccess }); + } else { + branchMutation.mutate({ userId, branchId: secondId }, { onSuccess }); + } + }; + + return ( + !open && onClose()}> + + + {t(ASSIGN_DIALOG_TITLES[kind])} + + {t(ASSIGN_DIALOG_TITLES[kind])} + + + +
+ { + setTargetValue(v); + if (error) setError(undefined); + }} + disabled={!!targetUserId || isPending} + options={targetOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + loading={targetLoading} + isLoadingMore={targetLoadingMore} + hasNextPage={targetHasNextPage} + onLoadMore={loadMoreTargets} + searchValue={targetSearch} + onSearchChange={setTargetSearch} + /> + + { + setResourceValue(v); + if (error) setError(undefined); + }} + error={error} + disabled={isPending} + options={resourceOptions} + placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} + loading={resourceLoading} + isLoadingMore={resourceLoadingMore} + hasNextPage={resourceHasNextPage} + onLoadMore={loadMoreResources} + searchValue={resourceSearch} + onSearchChange={setResourceSearch} + /> +
+ + + + + +
+
+ ); +} diff --git a/src/features/shared/hooks/useSharedUserAssignments.ts b/src/features/shared/hooks/useSharedUserAssignments.ts index c1736f4..d175083 100644 --- a/src/features/shared/hooks/useSharedUserAssignments.ts +++ b/src/features/shared/hooks/useSharedUserAssignments.ts @@ -5,9 +5,11 @@ import { postBranchUser, postRoleUser, postPermissionRole, + postPermissionUser, type AddBranchUserPayload, type AddRoleUserPayload, type AddPermissionRolePayload, + type AddPermissionUserPayload, } from "../api/sharedApi"; // ─── Query Keys ─────────────────────────────────────────────────────────────── @@ -21,7 +23,11 @@ export const userProfileKeys = { */ function useInvalidateProfile() { const queryClient = useQueryClient(); - return () => queryClient.invalidateQueries({ queryKey: userProfileKeys.profile }); + return () => { + queryClient.invalidateQueries({ queryKey: userProfileKeys.profile }); + queryClient.invalidateQueries({ queryKey: ["operators"] }); + queryClient.invalidateQueries({ queryKey: ["users"] }); + }; } // ─── useAssignRoleToUser ────────────────────────────────────────────────────── @@ -61,7 +67,23 @@ export function useAssignPermissionToRole() { }); } -export const useAssignPermissionToUser = useAssignPermissionToRole; +// ─── useAssignPermissionToUser ──────────────────────────────────────────────── + +/** + * POST /permission-users — assigns a permission to the given staff user and refreshes the caches. + */ +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 ──────────────────────────────────────────────────── diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 9aa1ec8..45d5a6b 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -1565,5 +1565,5 @@ "profile.sections.org": "Organization details", "profile.actions.assignBranch": "Assign branch", "profile.assign.success": "Assigned successfully", - "profile.assign.userLabel": "User (staff)" + "profile.assign.userLabel": "User" } diff --git a/src/lib/i18n/locales/ru.json b/src/lib/i18n/locales/ru.json index 180450d..89e26f0 100644 --- a/src/lib/i18n/locales/ru.json +++ b/src/lib/i18n/locales/ru.json @@ -1566,5 +1566,5 @@ "profile.sections.org": "Организационные данные", "profile.actions.assignBranch": "Назначить филиал", "profile.assign.success": "Успешно назначено", - "profile.assign.userLabel": "Пользователь (staff)" + "profile.assign.userLabel": "Пользователь" } diff --git a/src/lib/i18n/locales/tk.json b/src/lib/i18n/locales/tk.json index 79f81db..597460e 100644 --- a/src/lib/i18n/locales/tk.json +++ b/src/lib/i18n/locales/tk.json @@ -1457,7 +1457,7 @@ "users.fields.passwordHint": "Iň az 6 harp", "users.fields.phoneVerified": "Telefon tassyklanan", "users.fields.phoneVerifiedHint": "SMS arkaly tassyklandy", - "users.fields.avatar": "Awatar", + "users.fields.avatar": "Avatar", "users.fields.avatarUpload": "Surat saýlaň", "users.fields.avatarUploading": "Ýüklenýär...", "users.fields.avatarRemove": "Aýyr", @@ -1564,5 +1564,5 @@ "profile.sections.org": "Guramaçylyk maglumatlary", "profile.actions.assignBranch": "Şahamça birikdiriň", "profile.assign.success": "Üstünlikli birikdirildi", - "profile.assign.userLabel": "Ulanyjy (staff)" + "profile.assign.userLabel": "Ulanyjy" } diff --git a/src/pages/backupsView/index.tsx b/src/pages/backupsView/index.tsx index 38a2356..9cc17f2 100644 --- a/src/pages/backupsView/index.tsx +++ b/src/pages/backupsView/index.tsx @@ -1,21 +1,10 @@ -import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Download, Trash2, Database, CheckCircle2, XCircle, Clock, AlertCircle } from "lucide-react"; +import { Download, Database, CheckCircle2, XCircle, Clock, AlertCircle } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { useBackup, useDeleteBackup, useDownloadBackup } from "@/features/backups/hooks/useBackups"; -import { InfoRow } from "@/components/viewPageComponents"; +import { InfoRow, ViewActions } from "@/components/viewPageComponents"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; import type { BackupStatus } from "@/features/backups/api/backupsApi"; import { formatFromApiDate } from "@/lib/utils"; @@ -43,8 +32,6 @@ export default function BackupViewPage() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); - const [deleteOpen, setDeleteOpen] = useState(false); - const numericId = Number(id); const { data, isLoading } = useBackup(numericId); const deleteMutation = useDeleteBackup(); @@ -92,14 +79,11 @@ export default function BackupViewPage() { > - + @@ -120,24 +104,6 @@ export default function BackupViewPage() { - - {/* Delete dialog */} - - - - {t("Are you sure?", "Eminsiňizmi?")} - - {t("backups.deleteConfirm.description", "Bu backup pozulsynmy? Bu amal yzyna gaýtarylmaz.")} - - - - {t("Cancel", "Ýatyr")} - - {deleteMutation.isPending ? t("Deleting...", "Öçürilýär...") : t("Delete", "Öçür")} - - - - ); } diff --git a/src/pages/cardDepartment/cardBalanceView/index.tsx b/src/pages/cardDepartment/cardBalanceView/index.tsx index 43101ba..ada8b91 100644 --- a/src/pages/cardDepartment/cardBalanceView/index.tsx +++ b/src/pages/cardDepartment/cardBalanceView/index.tsx @@ -1,21 +1,9 @@ -import { useState } from "react"; -import { useParams, useNavigate, Link } from "react-router-dom"; +import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Trash2, Pencil, AlertCircle, CheckCircle2, XCircle } from "lucide-react"; -import { Button } from "@/components/ui/button"; +import { AlertCircle, CheckCircle2, XCircle } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { useCardBalance, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance"; -import { InfoRow } from "@/components/viewPageComponents"; +import { InfoRow, ViewActions } from "@/components/viewPageComponents"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; import type { CardBalanceStatus } from "@/features/cardBalance/api/cardBalanceApi"; import { formatFromApiDate } from "@/lib/utils"; @@ -44,8 +32,6 @@ export default function CardBalanceViewPage() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); - const [deleteOpen, setDeleteOpen] = useState(false); - const numericId = Number(id); const { data, isLoading } = useCardBalance(numericId); const deleteMutation = useDeleteCardBalance(); @@ -83,19 +69,12 @@ export default function CardBalanceViewPage() { {t("Card balance detail", "Kart galyndysy giňişleýin")}: #{data.id}
- - +
@@ -119,24 +98,6 @@ export default function CardBalanceViewPage() { - - {/* Delete dialog */} - - - - {t("Are you sure?", "Eminsiňizmi?")} - - {t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")} - - - - {t("Cancel", "Ýatyr")} - - {deleteMutation.isPending ? t("Deleting...", "Öçürilýär...") : t("Delete", "Öçür")} - - - - ); } diff --git a/src/pages/cardDepartment/cardPinsView/index.tsx b/src/pages/cardDepartment/cardPinsView/index.tsx index 8b09dc0..086d3f6 100644 --- a/src/pages/cardDepartment/cardPinsView/index.tsx +++ b/src/pages/cardDepartment/cardPinsView/index.tsx @@ -1,24 +1,10 @@ -import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { useCardPin, useDeleteCardPin } from "@/features/cardPins/hooks/useCardPins"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; -import { Button } from "@/components/ui/button"; -import { Pencil, Trash2 } from "lucide-react"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, - AlertDialogTrigger, -} from "@/components/ui/alert-dialog"; -import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, PassportImage, ViewActions } from "@/components/viewPageComponents"; import { getStatusLabel, isStatusValue, STATUS_BADGE_VARIANTS, type StatusValue } from "@/constants"; import type { LocalizedText } from "@/features/branches/api/branchesApi"; import { formatFromApiDate } from "@/lib/utils"; @@ -84,11 +70,9 @@ export default function CardPinViewPage() { const navigate = useNavigate(); const { t, i18n } = useTranslation(); - const [deleteOpen, setDeleteOpen] = useState(false); - const numericId = Number(id); const { data, isLoading, isError } = useCardPin(numericId); - const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin(); + const deleteMutation = useDeleteCardPin(); if (isLoading) return ; @@ -103,46 +87,13 @@ export default function CardPinViewPage() {

{t("cardPin.viewTitle", "Kart pin bukja giňişleýin")}: {data.uniqueId}

-
- - - - - - - {t("cardPin.deleteTitle", "Pozmak isleýärsiňizmi?")} - {t("cardPin.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")} - - - {t("common.cancel", "Ýatyr")} - deletePin(data.id, { onSuccess: () => navigate("/card-pins") })} - > - {isDeleting ? t("common.deleting", "Pozulýar...") : t("common.delete", "Poz")} - - - - - - -
+ deleteMutation.mutateAsync(data.id).then(() => navigate("/card-pins"))} + deleting={deleteMutation.isPending} + deleteTitle={t("cardPin.deleteTitle", "Pozmak isleýärsiňizmi?")} + deleteDescription={t("cardPin.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")} + /> {/* ── Row 1: Meta + Kart + Lokasiýa ───────────────────────────────── */} diff --git a/src/pages/cardDepartment/cardRequisitesView/index.tsx b/src/pages/cardDepartment/cardRequisitesView/index.tsx index 674bd3a..c47816a 100644 --- a/src/pages/cardDepartment/cardRequisitesView/index.tsx +++ b/src/pages/cardDepartment/cardRequisitesView/index.tsx @@ -1,25 +1,14 @@ -import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { ArrowLeft, Pencil, Trash2 } from "lucide-react"; +import { ArrowLeft } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { useCardRequisite, useDeleteCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites"; import type { CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi"; import { resolveLocalizedName } from "@/features/cardRequisites/api/cardRequisitesApi"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; import { AlertCircle, CheckCircle2, XCircle } from "lucide-react"; -import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, PassportImage, ViewActions } from "@/components/viewPageComponents"; import { formatFromApiDate } from "@/lib/utils"; // ─── Status config ──────────────────────────────────────────────────────────── @@ -75,7 +64,6 @@ export default function CardRequisiteViewPage() { const numericId = Number(id); const { data, isLoading, isError } = useCardRequisite(numericId); const deleteMutation = useDeleteCardRequisite(); - const [deleteOpen, setDeleteOpen] = useState(false); if (isLoading) { return ; @@ -99,42 +87,13 @@ export default function CardRequisiteViewPage() { {t("cardRequisite.viewTitle", "Kart rekwizit giňişleýin")}: {data.id} -
- - - - - - - {t("cardRequisite.deleteTitle", "Pozmak isleýärsiňizmi?")} - - {t("cardRequisite.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")} {data.id} - - - - {t("common.cancel", "Ýatyr")} - deleteMutation.mutate(data.id, { onSuccess: () => navigate("/card-requisites") })} - > - {t("common.delete", "Poz")} - - - - - - -
+ deleteMutation.mutateAsync(data.id).then(() => navigate("/card-requisites"))} + deleting={deleteMutation.isPending} + deleteTitle={t("cardRequisite.deleteTitle", "Pozmak isleýärsiňizmi?")} + deleteDescription={`${t("cardRequisite.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")} ${data.id}`} + /> {/* ── Row 1: Meta + Kart + Lokasiýa ────────────────────────────────── */} diff --git a/src/pages/cardDepartment/cardTransactionsView/index.tsx b/src/pages/cardDepartment/cardTransactionsView/index.tsx index 5cf377f..21a7fad 100644 --- a/src/pages/cardDepartment/cardTransactionsView/index.tsx +++ b/src/pages/cardDepartment/cardTransactionsView/index.tsx @@ -1,21 +1,8 @@ -import { useState } from "react"; -import { useParams, useNavigate, Link } from "react-router-dom"; +import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Trash2, Pencil } from "lucide-react"; -import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { useCardTransaction, useDeleteCardTransaction } from "@/features/cardTransactions/hooks/useCardTransactions"; -import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, ViewActions } from "@/components/viewPageComponents"; import i18n from "@/lib/i18n"; import { formatFromApiDate } from "@/lib/utils"; @@ -26,8 +13,6 @@ export default function CardTransactionViewPage() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); - const [deleteOpen, setDeleteOpen] = useState(false); - const numericId = Number(id); const { data, isLoading } = useCardTransaction(numericId); const deleteMutation = useDeleteCardTransaction(); @@ -64,21 +49,15 @@ export default function CardTransactionViewPage() {

{t("Card transaction detail", "Kart giňişleýin")}: {data.number}

-
- - -
+ {/* Detail cards */} @@ -115,27 +94,6 @@ export default function CardTransactionViewPage() { /> - - {/* Delete dialog */} - - - - {t("Are you sure?", "Eminsiňizmi?")} - - {t( - "This action cannot be undone. This will permanently delete the card.", - "Bu amal yzyna gaýtarylmaz. Kart hemişelik öçüriler.", - )} - - - - {t("Cancel", "Ýatyr")} - - {deleteMutation.isPending ? t("Deleting...", "Öçürilýär...") : t("Delete", "Öçür")} - - - - ); } diff --git a/src/pages/cardDepartment/orderNewCardView/index.tsx b/src/pages/cardDepartment/orderNewCardView/index.tsx index d47fd93..b72ed61 100644 --- a/src/pages/cardDepartment/orderNewCardView/index.tsx +++ b/src/pages/cardDepartment/orderNewCardView/index.tsx @@ -1,21 +1,8 @@ -import { useState } from "react"; -import { useParams, useNavigate, Link } from "react-router-dom"; +import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Printer, Download, Trash2, Pencil } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { Skeleton } from "@/components/ui/skeleton"; import { useCardById, useDeleteCard } from "@/features/orderNewCard/hooks/useOrderNewCard"; -import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, PassportImage, ViewActions } from "@/components/viewPageComponents"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react"; import { getStatusLabel, isStatusValue, STATUS_BADGE_VARIANTS, type StatusValue } from "@/constants"; @@ -83,8 +70,6 @@ export default function CardOrderDetailPage() { const navigate = useNavigate(); const { t, i18n } = useTranslation(); - const [deleteOpen, setDeleteOpen] = useState(false); - const { data: order, isLoading } = useCardById(Number(id)); const deleteMutation = useDeleteCard(); @@ -106,27 +91,13 @@ export default function CardOrderDetailPage() {
- - - - +
@@ -225,24 +196,6 @@ export default function CardOrderDetailPage() { - - {/* ── Delete confirm dialog ─────────────────────────────────────────── */} - - - - {t("cardOrder.deleteTitle", "Pozmak isleýärsiňizmi?")} - - {t("cardOrder.deleteDescription", "Bu kart sargyt hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.")} - - - - {t("common.cancel", "Ýatyr")} - - {deleteMutation.isPending ? t("common.deleting", "Pozulýar...") : t("common.delete", "Pozmak")} - - - - ); } diff --git a/src/pages/currencies/currencyRatesView/index.tsx b/src/pages/currencies/currencyRatesView/index.tsx index 480f590..8c11c8d 100644 --- a/src/pages/currencies/currencyRatesView/index.tsx +++ b/src/pages/currencies/currencyRatesView/index.tsx @@ -1,14 +1,10 @@ // pages/CurrencyRateDetailPage.tsx -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2 } from "lucide-react"; -import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; -import { Section, InfoRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { useGetCurrencyRateById, useDeleteCurrencyRate } from "@/features/currencyRates/hooks/useCurrencyRates"; -import { ConfirmDialog } from "@/components/confirmDialog"; import { formatFromApiDate } from "@/lib/utils"; // ─── CurrencyRateDetailPage ─────────────────────────────────────────────────── @@ -19,12 +15,10 @@ export default function CurrencyRateDetailPage() { const { t } = useTranslation(); const navigate = useNavigate(); - const [deleteOpen, setDeleteOpen] = useState(false); - const { data: rate, isLoading } = useGetCurrencyRateById(numericId); const deleteMutation = useDeleteCurrencyRate(); - const handleDeleteConfirm = async () => { + const handleDelete = async () => { await deleteMutation.mutateAsync(numericId); navigate("/currency-rates"); }; @@ -58,24 +52,17 @@ export default function CurrencyRateDetailPage() { {t("currencyRates.detail.title", "Walýuta kursy giňişleýin")}: {rate.id}
- - +
@@ -100,16 +87,6 @@ export default function CurrencyRateDetailPage() { - - ); } diff --git a/src/pages/internationalPayments/sberPaymentsView/index.tsx b/src/pages/internationalPayments/sberPaymentsView/index.tsx index a44c101..1d4a67b 100644 --- a/src/pages/internationalPayments/sberPaymentsView/index.tsx +++ b/src/pages/internationalPayments/sberPaymentsView/index.tsx @@ -1,14 +1,13 @@ import { format } from "date-fns"; -import { Trash2, Edit, Search, Download, XCircle, CheckCircle2, AlertCircle } from "lucide-react"; +import { Search, Download, XCircle, CheckCircle2, AlertCircle } from "lucide-react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { Skeleton } from "@/components/ui/skeleton"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; -import { BentoGrid, BentoCard, InfoRow, AuditLog, type AuditRowProps } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, AuditLog, ViewActions, type AuditRowProps } from "@/components/viewPageComponents"; import { useSberPaymentOrder, useDeleteSberPayment } from "@/features/sberPayments/hooks/useSberPayments"; import type { PaymentPaidStatus, PaymentStatus } from "@/features/sberPayments/api/sberPaymentsApi"; import { useState } from "react"; -import { ConfirmDialog } from "@/components/confirmDialog"; // ─── Status config ──────────────────────────────────────────────────────────── @@ -119,7 +118,6 @@ export default function SberPaymentViewPage() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const [historySearch, setHistorySearch] = useState(""); - const [deleteOpen, setDeleteOpen] = useState(false); const { data: order, isLoading } = useSberPaymentOrder(id!); const deleteMutation = useDeleteSberPayment(); @@ -160,21 +158,13 @@ export default function SberPaymentViewPage() { {t("sberPayments.viewTitle", "Sberbank töleg")}: {order.id}
- - +
@@ -281,15 +271,6 @@ export default function SberPaymentViewPage() { {/* ── Audit log ────────────────────────────────────────────────────── */} - - ); } diff --git a/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx b/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx index b3c78b9..44bab1a 100644 --- a/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx +++ b/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx @@ -1,11 +1,10 @@ import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, Download, Search, AlertCircle, CheckCircle2, XCircle } from "lucide-react"; -import { ConfirmDialog } from "@/components/confirmDialog"; +import { Download, Search, AlertCircle, CheckCircle2, XCircle } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge"; -import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { useIntlPayment, useDeleteIntlPayment } from "@/features/visaMasterPayments/hooks/useVisaMasterPayments"; import type { IntlPaymentStatus } from "@/features/visaMasterPayments/api/visaMasterPaymentsApi"; import { formatFromApiDate } from "@/lib/utils/dateUtils"; @@ -98,13 +97,13 @@ export default function IntlPaymentViewPage() { const navigate = useNavigate(); const { t } = useTranslation(); const [historySearch, setHistorySearch] = useState(""); - const [deleteOpen, setDeleteOpen] = useState(false); const { data, isLoading, isError } = useIntlPayment(id!); const { mutate: deletePayment, isPending: isDeleting } = useDeleteIntlPayment(); - const confirmDelete = () => { - deletePayment(data!.id, { onSuccess: () => navigate("/visa-master") }); + const handleDelete = async () => { + await deletePayment(data!.id); + navigate("/visa-master"); }; if (isLoading) return ; @@ -171,21 +170,14 @@ export default function IntlPaymentViewPage() { {t("intlPayment.viewTitle", "Halkara töleg")}: {data.id}
- - - +
@@ -285,16 +277,6 @@ export default function IntlPaymentViewPage() { - - ); } diff --git a/src/pages/loanDepartment/loanOrderMobileView/index.tsx b/src/pages/loanDepartment/loanOrderMobileView/index.tsx index b7ab04d..4229ea2 100644 --- a/src/pages/loanDepartment/loanOrderMobileView/index.tsx +++ b/src/pages/loanDepartment/loanOrderMobileView/index.tsx @@ -1,15 +1,12 @@ -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Trash2, Pencil } from "lucide-react"; import { useLoanOrderMobileById, useDeleteLoanOrderMobile } from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles"; import { CreditCardVisual } from "@/components/creditCardVisual"; import { Skeleton } from "@/components/ui/skeleton"; import type { LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi"; import { StatusBadge } from "@/components/ui/statusBadge"; import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react"; -import { BentoGrid, BentoCard, InfoRow, PassportImage, AuditLog, type AuditRowProps } from "@/components/viewPageComponents"; -import { ConfirmDialog } from "@/components/confirmDialog"; +import { BentoGrid, BentoCard, InfoRow, PassportImage, AuditLog, ViewActions, type AuditRowProps } from "@/components/viewPageComponents"; import { getStatusLabel, STATUS_BADGE_VARIANTS, type StatusValue } from "@/constants"; import { formatFromApiDate } from "@/lib/utils"; @@ -56,18 +53,12 @@ export default function LoanOrderMobilesViewPage() { const navigate = useNavigate(); const { id } = useParams<{ id: string }>(); const deleteMutation = useDeleteLoanOrderMobile(); - const [showDeleteDialog, setShowDeleteDialog] = useState(false); const { data: order, isLoading } = useLoanOrderMobileById(id!); - const handleDelete = () => { - setShowDeleteDialog(true); - }; - - const confirmDelete = () => { - deleteMutation.mutate(id!, { - onSuccess: () => navigate("/loan-order-mobiles"), - }); + const handleDelete = async () => { + await deleteMutation.mutateAsync(id!); + navigate("/loan-order-mobiles"); }; if (isLoading) return ; @@ -100,21 +91,13 @@ export default function LoanOrderMobilesViewPage() { {t("loanOrderMobiles.view.title", "Karz sargyt giriş")}: {order.id}
- - +
@@ -384,15 +367,6 @@ export default function LoanOrderMobilesViewPage() { {/* ── Audit log ────────────────────────────────────────────────────── */} - - ); } diff --git a/src/pages/loanDepartment/loanOrderView/index.tsx b/src/pages/loanDepartment/loanOrderView/index.tsx index 198d9ca..ddc0155 100644 --- a/src/pages/loanDepartment/loanOrderView/index.tsx +++ b/src/pages/loanDepartment/loanOrderView/index.tsx @@ -1,14 +1,11 @@ -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Trash2, Pencil } from "lucide-react"; import { useLoanOrderById, useDeleteLoanOrder } from "@/features/loanOrders/hooks/useLoanOrders"; import { Skeleton } from "@/components/ui/skeleton"; import { StatusBadge } from "@/components/ui/statusBadge"; import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react"; import type { LoanOrderStatus } from "@/features/loanOrders/api/loanOrdersApi"; -import { BentoGrid, BentoCard, InfoRow, PassportImage, AuditLog, type AuditRowProps } from "@/components/viewPageComponents"; -import { ConfirmDialog } from "@/components/confirmDialog"; +import { BentoGrid, BentoCard, InfoRow, PassportImage, AuditLog, ViewActions, type AuditRowProps } from "@/components/viewPageComponents"; import { getStatusLabel, STATUS_BADGE_VARIANTS, type StatusValue } from "@/constants"; import { formatFromApiDate } from "@/lib/utils"; @@ -63,18 +60,12 @@ export default function LoanOrderViewPage() { const navigate = useNavigate(); const { id } = useParams<{ id: string }>(); const deleteMutation = useDeleteLoanOrder(); - const [showDeleteDialog, setShowDeleteDialog] = useState(false); const { data: order, isLoading } = useLoanOrderById(id!); - const handleDelete = () => { - setShowDeleteDialog(true); - }; - - const confirmDelete = () => { - deleteMutation.mutate(id!, { - onSuccess: () => navigate("/loan-orders"), - }); + const handleDelete = async () => { + await deleteMutation.mutateAsync(id!); + navigate("/loan-orders"); }; if (isLoading) return ; @@ -107,21 +98,13 @@ export default function LoanOrderViewPage() { {t("loanOrders.view.title", "Karz sargyt giriş")}: {order.id}
- - +
@@ -326,15 +309,6 @@ export default function LoanOrderViewPage() { {/* ── Audit log ────────────────────────────────────────────────────── */} - - ); } diff --git a/src/pages/loanDepartment/loanPaidOffLettersView/index.tsx b/src/pages/loanDepartment/loanPaidOffLettersView/index.tsx index 4b0779a..29a29ff 100644 --- a/src/pages/loanDepartment/loanPaidOffLettersView/index.tsx +++ b/src/pages/loanDepartment/loanPaidOffLettersView/index.tsx @@ -1,12 +1,10 @@ -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Trash2, Pencil, FileText, ExternalLink } from "lucide-react"; +import { FileText, ExternalLink } from "lucide-react"; import { useLoanPaidOffLetterById, useDeleteLoanPaidOffLetter } from "@/features/loanPaidOffLetters/hooks/useLoanPaidOffLetters"; import { StatusBadge } from "@/components/ui/statusBadge"; import { Skeleton } from "@/components/ui/skeleton"; -import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; -import { ConfirmDialog } from "@/components/confirmDialog"; +import { BentoGrid, BentoCard, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { STATUS_BADGE_VARIANTS } from "@/constants"; import { buildFileUrl } from "@/features/shared/api/sharedApi"; import type { LocalizedText } from "@/features/branches/api/branchesApi"; @@ -45,14 +43,12 @@ export default function LoanPaidOffLettersViewPage() { const navigate = useNavigate(); const { id } = useParams<{ id: string }>(); const deleteMutation = useDeleteLoanPaidOffLetter(); - const [showDeleteDialog, setShowDeleteDialog] = useState(false); const { data: record, isLoading } = useLoanPaidOffLetterById(id!); - const confirmDelete = () => { - deleteMutation.mutate(Number(id!), { - onSuccess: () => navigate("/loan-paid-off-letters"), - }); + const handleDelete = async () => { + await deleteMutation.mutateAsync(Number(id!)); + navigate("/loan-paid-off-letters"); }; if (isLoading) return ; @@ -71,21 +67,13 @@ export default function LoanPaidOffLettersViewPage() { {t("loanPaidOffLetters.view.title", "Güwanama maglumaty")}: {record.uniqueId}
- - +
@@ -167,15 +155,6 @@ export default function LoanPaidOffLettersViewPage() { - - ); } diff --git a/src/pages/loanDepartment/loanRemainingView/index.tsx b/src/pages/loanDepartment/loanRemainingView/index.tsx index a392ccc..56b4b96 100644 --- a/src/pages/loanDepartment/loanRemainingView/index.tsx +++ b/src/pages/loanDepartment/loanRemainingView/index.tsx @@ -1,11 +1,8 @@ -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Trash2, Pencil } from "lucide-react"; import { useLoanRemainingById, useDeleteLoanRemaining } from "@/features/loanRemaining/hooks/useLoanRemaining"; import { Skeleton } from "@/components/ui/skeleton"; -import { InfoRow, Section } from "@/components/viewPageComponents"; -import { ConfirmDialog } from "@/components/confirmDialog"; +import { InfoRow, Section, ViewActions } from "@/components/viewPageComponents"; import { formatFromApiDate } from "@/lib/utils"; @@ -31,18 +28,12 @@ export default function LoanRemainingViewPage() { const navigate = useNavigate(); const { id } = useParams<{ id: string }>(); const deleteMutation = useDeleteLoanRemaining(); - const [showDeleteDialog, setShowDeleteDialog] = useState(false); const { data: record, isLoading } = useLoanRemainingById(id!); - const handleDelete = () => { - setShowDeleteDialog(true); - }; - - const confirmDelete = () => { - deleteMutation.mutate(Number(id!), { - onSuccess: () => navigate("/loan-remaining"), - }); + const handleDelete = async () => { + await deleteMutation.mutateAsync(Number(id!)); + navigate("/loan-remaining"); }; if (isLoading) return ; @@ -59,21 +50,13 @@ export default function LoanRemainingViewPage() { {t("loanRemaining.view.title", "Karz galyndysy maglumaty")}: {record.id}
- - +
@@ -97,15 +80,6 @@ export default function LoanRemainingViewPage() { )} - - ); } diff --git a/src/pages/profile/index.tsx b/src/pages/profile/index.tsx index 428128f..1024936 100644 --- a/src/pages/profile/index.tsx +++ b/src/pages/profile/index.tsx @@ -1,34 +1,19 @@ -import { useState, useMemo } from "react"; +import { useState } from "react"; import { Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; -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 { - 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 { isAdmin as isAdminUser } from "@/lib/auth/permissions"; import { useProfile, useUpdateProfile } from "@/features/auth/hooks/useLogin"; -import { useInfiniteRoles } from "@/features/roles/hooks/useRoles"; -import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions"; -import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers"; -import { useInfiniteStaff } from "@/features/operators/hooks/useOperators"; -import { useAssignRoleToUser, useAssignPermissionToRole, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments"; +import { AssignDialog, type AssignDialogKind } from "@/features/shared/components/assignDialog"; import type { LocalizedText } from "@/features/branches/api/branchesApi"; import { formatFromApiDate } from "@/lib/utils/dateUtils"; -type AssignDialogKind = "role" | "permission" | "branch"; export default function ProfilePage() { const { t, i18n } = useTranslation(); @@ -360,192 +345,3 @@ export default function ProfilePage() { ); } - -// ─── 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 / branch to a staff user, or assigning a permission to a role. - */ -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 isPermission = kind === "permission"; - - const [targetSearch, setTargetSearch] = useState(""); - const [targetValue, setTargetValue] = useState(""); - const [resourceSearch, setResourceSearch] = useState(""); - const [resourceValue, setResourceValue] = useState(""); - const [error, setError] = useState(); - - // Target query: Staff users when assigning role/branch to a user; Roles when assigning permission to a role. - const staffQuery = useInfiniteStaff(targetSearch); - const targetRolesQuery = useInfiniteRoles(targetSearch, isPermission); - - // Resource query: - const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role"); - const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission"); - const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch"); - - const roleMutation = useAssignRoleToUser(); - const permissionMutation = useAssignPermissionToRole(); - 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 targetRoleOptions: InfiniteSelectOption[] = useMemo( - () => - (targetRolesQuery.data?.pages ?? []) - .flatMap((p) => p?.roles ?? []) - .map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) })), - [targetRolesQuery.data], - ); - - const targetOptions = isPermission ? targetRoleOptions : staffOptions; - const targetLabel = isPermission ? t("users.fields.role", "Rol") : t("profile.assign.userLabel", "Ulanyjy (staff)"); - const targetLoading = isPermission ? targetRolesQuery.isLoading : staffQuery.isLoading; - const targetLoadingMore = isPermission ? targetRolesQuery.isFetchingNextPage : staffQuery.isFetchingNextPage; - const targetHasNextPage = isPermission ? !!targetRolesQuery.hasNextPage : !!staffQuery.hasNextPage; - const loadMoreTargets = () => { - if (isPermission) targetRolesQuery.fetchNextPage(); - else staffQuery.fetchNextPage(); - }; - - 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 (!targetValue || !resourceValue) { - setError(t("common.errors.required", "Meýdança hökmany doldurylmaly")); - return; - } - setError(undefined); - - const firstId = Number(targetValue); - const secondId = Number(resourceValue); - const onSuccess = () => { - setTargetValue(""); - setResourceValue(""); - onClose(); - }; - - if (kind === "role") roleMutation.mutate({ userId: firstId, roleId: secondId }, { onSuccess }); - else if (kind === "permission") permissionMutation.mutate({ roleId: firstId, permissionId: secondId }, { onSuccess }); - else branchMutation.mutate({ userId: firstId, branchId: secondId }, { onSuccess }); - }; - - return ( - !open && onClose()}> - - - {t(ASSIGN_DIALOG_TITLES[kind])} - - {t(ASSIGN_DIALOG_TITLES[kind])} - - - -
- { - setTargetValue(v); - if (error) setError(undefined); - }} - options={targetOptions} - placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"} - loading={targetLoading} - isLoadingMore={targetLoadingMore} - hasNextPage={targetHasNextPage} - onLoadMore={loadMoreTargets} - searchValue={targetSearch} - onSearchChange={setTargetSearch} - /> - - { - 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} - /> -
- - - - - -
-
- ); -} diff --git a/src/pages/settings/card/cardTypesView/index.tsx b/src/pages/settings/card/cardTypesView/index.tsx index 91983fb..1d3eae1 100644 --- a/src/pages/settings/card/cardTypesView/index.tsx +++ b/src/pages/settings/card/cardTypesView/index.tsx @@ -1,20 +1,7 @@ -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2 } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { Skeleton } from "@/components/ui/skeleton"; -import { Section, InfoRow, MultiLangRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, MultiLangRow, ViewActions } from "@/components/viewPageComponents"; import { StatusBadge } from "@/components/ui/statusBadge"; import { useCardTypeById, useDeleteCardType } from "@/features/cardTypes/hooks/useCardTypes"; @@ -27,7 +14,6 @@ export function CardTypeViewPage() { const { data, isLoading } = useCardTypeById(numericId); const deleteMutation = useDeleteCardType(); - const [deleteOpen, setDeleteOpen] = useState(false); return (
@@ -39,23 +25,14 @@ export function CardTypeViewPage() {
- - + deleteMutation.mutateAsync(numericId).then(() => navigate("/settings/card/card-types"))} + deleting={deleteMutation.isPending} + deleteTitle={t("common.confirmDelete", "Öçürmegi tassyklaň")} + deleteDescription={t("cardTypes.deleteConfirm", "Bu kart görnüşini öçürmek isleýärsiňizmi?")} + deleteConfirmLabel={t("common.delete", "Öçürmek")} + />
@@ -92,29 +69,6 @@ export function CardTypeViewPage() { ) : (

{t("common.noData", "Maglumat ýok")}

)} - - {/* Delete dialog */} - - - - {t("common.confirmDelete", "Öçürmegi tassyklaň")} - {t("cardTypes.deleteConfirm", "Bu kart görnüşini öçürmek isleýärsiňizmi?")} - - - {t("common.cancel", "Ýatyr")} - - deleteMutation.mutate(numericId, { - onSuccess: () => navigate("/settings/card/card-types"), - }) - } - > - {deleteMutation.isPending ? t("common.deleting", "Öçürilýär...") : t("common.delete", "Öçürmek")} - - - - ); } diff --git a/src/pages/settings/card/reasonsView/index.tsx b/src/pages/settings/card/reasonsView/index.tsx index 9bbc4e2..f27efd8 100644 --- a/src/pages/settings/card/reasonsView/index.tsx +++ b/src/pages/settings/card/reasonsView/index.tsx @@ -1,21 +1,8 @@ import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2 } from "lucide-react"; -import { useState } from "react"; -import { Button } from "@/components/ui/button"; import { CheckCircle2, XCircle } from "lucide-react"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { Skeleton } from "@/components/ui/skeleton"; -import { Section, InfoRow, MultiLangRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, MultiLangRow, ViewActions } from "@/components/viewPageComponents"; import { useCardReasonById, useDeleteCardReason } from "@/features/cardReasons/hooks/useCardReasons"; // ─── CardReasonViewPage ──────────────────────────────────────────────────────── @@ -30,7 +17,6 @@ export function CardReasonViewPage() { const { data, isLoading } = useCardReasonById(numericId); const deleteMutation = useDeleteCardReason(); - const [deleteOpen, setDeleteOpen] = useState(false); return (
@@ -42,23 +28,14 @@ export function CardReasonViewPage() {
- - + deleteMutation.mutateAsync(numericId).then(() => navigate("/settings/card/card-reasons"))} + deleting={deleteMutation.isPending} + deleteTitle={t("common.confirmDelete", "Öçürmegi tassyklaň")} + deleteDescription={t("cardReasons.deleteConfirm", "Bu kartyň çykarylmagynyň sebäbini öçürmek isleýärsiňizmi?")} + deleteConfirmLabel={t("common.delete", "Öçürmek")} + />
@@ -92,31 +69,6 @@ export function CardReasonViewPage() { ) : (

{t("common.noData", "Maglumat ýok")}

)} - - {/* Delete dialog */} - - - - {t("common.confirmDelete", "Öçürmegi tassyklaň")} - - {t("cardReasons.deleteConfirm", "Bu kartyň çykarylmagynyň sebäbini öçürmek isleýärsiňizmi?")} - - - - {t("common.cancel", "Ýatyr")} - - deleteMutation.mutate(numericId, { - onSuccess: () => navigate("/settings/card/card-reasons"), - }) - } - > - {deleteMutation.isPending ? t("common.deleting", "Öçürilýär...") : t("common.delete", "Öçürmek")} - - - - ); } diff --git a/src/pages/settings/loan/loanTypesView/index.tsx b/src/pages/settings/loan/loanTypesView/index.tsx index b0b41ed..9d7c339 100644 --- a/src/pages/settings/loan/loanTypesView/index.tsx +++ b/src/pages/settings/loan/loanTypesView/index.tsx @@ -1,22 +1,10 @@ // pages/LoanTypeViewPage.tsx -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, CheckCircle2, XCircle } from "lucide-react"; -import { Button } from "@/components/ui/button"; +import { CheckCircle2, XCircle } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; -import { Section, InfoRow, MultiLangRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, MultiLangRow, ViewActions } from "@/components/viewPageComponents"; import { useGetLoanTypeById, useDeleteLoanType } from "@/features/loanTypes/hooks/useLoanTypes"; // ─── LoanTypeViewPage ───────────────────────────────────────────────────────── @@ -27,8 +15,6 @@ export default function LoanTypeViewPage() { const { id } = useParams<{ id: string }>(); const loanTypeId = Number(id); - const [showDeleteDialog, setShowDeleteDialog] = useState(false); - const { data, isLoading, isError } = useGetLoanTypeById(loanTypeId); const deleteMutation = useDeleteLoanType(); @@ -76,24 +62,17 @@ export default function LoanTypeViewPage() { {t("loanTypes.viewTitle", "Karz görnüşi giňişleýin")}: {data.title[lang]}
- - +
@@ -117,28 +96,6 @@ export default function LoanTypeViewPage() { {data.active ? : } - - {/* Delete dialog */} - - - - {t("loanTypes.deleteDialog.title", "Pozmak")} - - {t("loanTypes.deleteDialog.description", "Bu karz görnüşini pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylyp bilinmez.")} - - - - {t("common.cancel", "Ýatyr")} - - {deleteMutation.isPending ? t("common.deleting", "Pozulýar...") : t("common.delete", "Pozmak")} - - - - ); } diff --git a/src/pages/settings/loan/requiredDocumentsView/index.tsx b/src/pages/settings/loan/requiredDocumentsView/index.tsx index 8db8cfb..d3ac24f 100644 --- a/src/pages/settings/loan/requiredDocumentsView/index.tsx +++ b/src/pages/settings/loan/requiredDocumentsView/index.tsx @@ -1,19 +1,14 @@ -import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2 } from "lucide-react"; -import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; -import { Section, InfoRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { StatusBadge } from "@/components/ui/statusBadge"; import { useGetRequiredDocumentById, useDeleteRequiredDocument } from "@/features/requiredDocuments/hooks/useRequiredDocuments"; -import { ConfirmDialog } from "@/components/confirmDialog"; export default function RequiredDocumentsViewPage() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const { t } = useTranslation(); - const [deleteOpen, setDeleteOpen] = useState(false); const docId = Number(id); const { data, isLoading } = useGetRequiredDocumentById(docId); @@ -46,23 +41,13 @@ export default function RequiredDocumentsViewPage() { {t("loanDocuments.viewTitle", "Karz gerekli resminamalary giňişleýin")}: {data.name}
- - +
@@ -81,15 +66,6 @@ export default function RequiredDocumentsViewPage() { )} - - ); } diff --git a/src/pages/settings/location/branchesView/index.tsx b/src/pages/settings/location/branchesView/index.tsx index 3ca893e..55d53a2 100644 --- a/src/pages/settings/location/branchesView/index.tsx +++ b/src/pages/settings/location/branchesView/index.tsx @@ -1,20 +1,8 @@ -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, CheckCircle2, XCircle } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; +import { CheckCircle2, XCircle } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; -import { Section, InfoRow, MultiLangRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, MultiLangRow, ViewActions } from "@/components/viewPageComponents"; import { useBranchById, useDeleteBranch } from "@/features/branches/hooks/useBranches"; export function BranchViewPage() { @@ -26,7 +14,6 @@ export function BranchViewPage() { const { data, isLoading } = useBranchById(numericId); const deleteMutation = useDeleteBranch(); - const [deleteOpen, setDeleteOpen] = useState(false); const lang = ((i18n.language?.slice(0, 2) === "tk" ? "tm" : i18n.language?.slice(0, 2)) ?? "tm") as "tm" | "ru" | "en"; @@ -40,23 +27,14 @@ export function BranchViewPage() {
- - + deleteMutation.mutateAsync(numericId).then(() => navigate("/settings/location/branches"))} + deleting={deleteMutation.isPending} + deleteTitle={t("common.confirmDelete", "Öçürmegi tassyklaň")} + deleteDescription={t("branches.deleteConfirm", "Bu şahamçany öçürmek isleýärsiňizmi?")} + deleteConfirmLabel={t("common.delete", "Öçürmek")} + />
@@ -102,28 +80,6 @@ export function BranchViewPage() { ) : (

{t("common.noData", "Maglumat ýok")}

)} - - - - - {t("common.confirmDelete", "Öçürmegi tassyklaň")} - {t("branches.deleteConfirm", "Bu şahamçany öçürmek isleýärsiňizmi?")} - - - {t("common.cancel", "Ýatyr")} - - deleteMutation.mutate(numericId, { - onSuccess: () => navigate("/settings/location/branches"), - }) - } - > - {deleteMutation.isPending ? t("common.deleting", "Öçürilýär...") : t("common.delete", "Öçürmek")} - - - - ); } diff --git a/src/pages/settings/location/districtsView/index.tsx b/src/pages/settings/location/districtsView/index.tsx index 6896785..4ccc0b0 100644 --- a/src/pages/settings/location/districtsView/index.tsx +++ b/src/pages/settings/location/districtsView/index.tsx @@ -1,20 +1,8 @@ -import { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, CheckCircle2, XCircle } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; +import { CheckCircle2, XCircle } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; -import { Section, InfoRow, MultiLangRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, MultiLangRow, ViewActions } from "@/components/viewPageComponents"; import { useDistrictById, useDeleteDistrict } from "@/features/districts/hooks/useDistricts"; export function DistrictViewPage() { @@ -26,7 +14,6 @@ export function DistrictViewPage() { const { data, isLoading } = useDistrictById(numericId); const deleteMutation = useDeleteDistrict(); - const [deleteOpen, setDeleteOpen] = useState(false); const lang = ((i18n.language?.slice(0, 2) === "tk" ? "tm" : i18n.language?.slice(0, 2)) ?? "tm") as "tm" | "ru" | "en"; @@ -40,23 +27,14 @@ export function DistrictViewPage() {
- - + deleteMutation.mutateAsync(numericId).then(() => navigate("/settings/location/districts"))} + deleting={deleteMutation.isPending} + deleteTitle={t("common.confirmDelete", "Öçürmegi tassyklaň")} + deleteDescription={t("districts.deleteConfirm", "Bu etrapy öçürmek isleýärsiňizmi?")} + deleteConfirmLabel={t("common.delete", "Öçürmek")} + />
@@ -85,28 +63,6 @@ export function DistrictViewPage() { ) : (

{t("common.noData", "Maglumat ýok")}

)} - - - - - {t("common.confirmDelete", "Öçürmegi tassyklaň")} - {t("districts.deleteConfirm", "Bu etrapy öçürmek isleýärsiňizmi?")} - - - {t("common.cancel", "Ýatyr")} - - deleteMutation.mutate(numericId, { - onSuccess: () => navigate("/settings/location/districts"), - }) - } - > - {deleteMutation.isPending ? t("common.deleting", "Öçürilýär...") : t("common.delete", "Öçürmek")} - - - - ); } diff --git a/src/pages/settings/users/permissionsView/index.tsx b/src/pages/settings/users/permissionsView/index.tsx index 38c6e8e..714a3c4 100644 --- a/src/pages/settings/users/permissionsView/index.tsx +++ b/src/pages/settings/users/permissionsView/index.tsx @@ -1,20 +1,7 @@ -import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2 } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { Skeleton } from "@/components/ui/skeleton"; -import { Section, InfoRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { usePermission, useDeletePermission } from "@/features/permissions/hooks/usePermissions"; // ─── PermissionViewPage ─────────────────────────────────────────────────────── @@ -25,16 +12,12 @@ export default function PermissionViewPage() { const navigate = useNavigate(); const permissionId = Number(id); - const [showDelete, setShowDelete] = useState(false); - const { data: permission, isLoading, isError } = usePermission(permissionId); const deletePermission = useDeletePermission(); - const handleConfirmDelete = () => { - deletePermission.mutate(permissionId, { - onSuccess: () => navigate("/settings/users/permissions"), - onError: () => setShowDelete(false), - }); + const handleDelete = async () => { + await deletePermission.mutateAsync(permissionId); + navigate("/settings/users/permissions"); }; // ── Loading skeleton ─────────────────────────────────────────────────────── @@ -70,22 +53,14 @@ export default function PermissionViewPage() { {t("permissions.viewTitle", "Rugsat giňişleýin")}: {permission.name}
- - +
@@ -96,24 +71,6 @@ export default function PermissionViewPage() { - - {/* Delete dialog */} - - - - {t("permissions.deleteDialog.title", "Rugsaty pozmak")} - - {t("permissions.deleteDialog.description", "Bu rugsaty pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")} - - - - {t("common.cancel", "Ýatyr")} - - {deletePermission.isPending ? t("common.deleting", "Pozulýar...") : t("common.delete", "Poz")} - - - - ); } diff --git a/src/pages/settings/users/rolesView/index.tsx b/src/pages/settings/users/rolesView/index.tsx index 69e90df..eba9acd 100644 --- a/src/pages/settings/users/rolesView/index.tsx +++ b/src/pages/settings/users/rolesView/index.tsx @@ -1,20 +1,7 @@ -import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2 } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; import { Skeleton } from "@/components/ui/skeleton"; -import { Section, InfoRow } from "@/components/viewPageComponents"; +import { Section, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { useRole, useDeleteRole } from "@/features/roles/hooks/useRoles"; // ─── RoleViewPage ───────────────────────────────────────────────────────────── @@ -25,16 +12,12 @@ export default function RoleViewPage() { const navigate = useNavigate(); const roleId = Number(id); - const [showDelete, setShowDelete] = useState(false); - const { data: role, isLoading, isError } = useRole(roleId); const deleteRole = useDeleteRole(); - const handleConfirmDelete = () => { - deleteRole.mutate(roleId, { - onSuccess: () => navigate("/settings/users/roles"), - onError: () => setShowDelete(false), - }); + const handleDelete = async () => { + await deleteRole.mutateAsync(roleId); + navigate("/settings/users/roles"); }; // ── Loading skeleton ─────────────────────────────────────────────────────── @@ -70,22 +53,14 @@ export default function RoleViewPage() { {t("roles.viewTitle", "Rol giňişleýin")}: {role.name}
- - +
@@ -96,24 +71,6 @@ export default function RoleViewPage() { - - {/* Delete dialog */} - - - - {t("roles.deleteDialog.title", "Roly pozmak")} - - {t("roles.deleteDialog.description", "Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.")} - - - - {t("common.cancel", "Ýatyr")} - - {deleteRole.isPending ? t("common.deleting", "Pozulýar...") : t("common.delete", "Poz")} - - - - ); } diff --git a/src/pages/users/allUsersView/index.tsx b/src/pages/users/allUsersView/index.tsx index 965bb39..0280c80 100644 --- a/src/pages/users/allUsersView/index.tsx +++ b/src/pages/users/allUsersView/index.tsx @@ -1,11 +1,8 @@ -import { useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, XCircle, CheckCircle2, UserRound, Link2 } from "lucide-react"; -import { Button } from "@/components/ui/button"; +import { XCircle, CheckCircle2, UserRound, Link2 } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; -import { ConfirmDialog } from "@/components/confirmDialog"; -import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { useUser, useDeleteUser } from "@/features/allUsers/hooks/useAllUsers"; // ─── ActiveIndicator ────────────────────────────────────────────────────────── @@ -25,8 +22,6 @@ export default function UserViewPage() { const { data: user, isLoading, isError } = useUser(userId); - const [deleteOpen, setDeleteOpen] = useState(false); - // ── Loading ─────────────────────────────────────────────────────────────── if (isLoading) { @@ -63,22 +58,20 @@ export default function UserViewPage() { {t("users.viewTitle", "Ulanyjy giňişleýin")}: {user.name}
- - + { + await deleteUser.mutateAsync(userId); + navigate("/all-users"); + }} + deleting={deleteUser.isPending} + deleteTitle={t("users.deleteDialog.title", "Ulanyjyny öçürmek")} + deleteDescription={t( + "users.deleteDialog.description", + 'Siz "{name}" ulanyjysyny öçürjekmi? Bu amal yzyna gaýtarylyp bilinmez.', + ).replace("{name}", user.username)} + deleteConfirmLabel={t("common.delete", "Öçür")} + />
@@ -140,22 +133,6 @@ export default function UserViewPage() { )} - - { - await deleteUser.mutateAsync(userId); - navigate("/all-users"); - }} - isLoading={deleteUser.isPending} - /> ); } diff --git a/src/pages/users/clientsView/index.tsx b/src/pages/users/clientsView/index.tsx index 176d645..5395f3b 100644 --- a/src/pages/users/clientsView/index.tsx +++ b/src/pages/users/clientsView/index.tsx @@ -1,13 +1,20 @@ -import { useState } from "react"; import { useParams, useNavigate, Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, XCircle, CheckCircle2, UserRound } from "lucide-react"; -import { Button } from "@/components/ui/button"; +import { XCircle, CheckCircle2, UserRound } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; -import { ConfirmDialog } from "@/components/confirmDialog"; -import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { Badge } from "@/components/ui/badge"; import { useClient, useDeleteClient } from "@/features/clients/hooks/useClients"; +import type { LocalizedText } from "@/features/branches/api/branchesApi"; +import { formatFromApiDate } from "@/lib/utils/dateUtils"; + +// ─── Helper: resolve LocalizedText | string ─────────────────────────────────── + +function resolveLocalizedName(name: LocalizedText | string | undefined | null, lang = "en"): string { + if (!name) return ""; + if (typeof name === "string") return name; + return name[lang as keyof LocalizedText] ?? name.en ?? name.tm ?? name.ru ?? ""; +} // ─── ActiveIndicator ────────────────────────────────────────────────────────── @@ -20,14 +27,13 @@ function ActiveIndicator({ active }: { active: boolean }) { export default function ClientDetailPage() { const { id } = useParams<{ id: string }>(); const clientId = Number(id); - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); + const lang = i18n.language ?? "en"; const navigate = useNavigate(); const deleteMutation = useDeleteClient(); const { data: client, isLoading } = useClient(clientId); - const [deleteOpen, setDeleteOpen] = useState(false); - // ── Loading ─────────────────────────────────────────────────────────────── if (isLoading) { @@ -53,31 +59,24 @@ export default function ClientDetailPage() { const roles = client.roles ?? []; const permissions = client.permissions ?? []; const branches = client.branches ?? []; + const displayName = [client.firstName, client.lastName].filter(Boolean).join(" ") || client.name; return (
{/* ── Page header ──────────────────────────────────────────────────── */}

- {t("clients.detailTitle", "Müşderi giňişleýin")}: {client.name} + {t("clients.detailTitle", "Müşderi giňişleýin")}: {displayName}

- - + deleteMutation.mutateAsync(clientId).then(() => navigate("/clients"))} + deleting={deleteMutation.isPending} + deleteTitle={t("clients.deleteTitle", "Müşderini pozmak")} + deleteDescription={t("clients.deleteConfirm", "{{name}} müşderisini pozmak isleýärsiňizmi?", { name: client.name })} + deleteConfirmLabel={t("common.delete", "Poz")} + />
@@ -96,13 +95,16 @@ export default function ClientDetailPage() {
)} -
-

{client.name}

+
+

{displayName}

+ {client.username &&

@{client.username}

}
+ + + + {roles.length > 0 && (
@@ -140,7 +144,7 @@ export default function ClientDetailPage() { {branches.map((b) => ( - {b.name} + {resolveLocalizedName(b.name, lang) || b.uniqueCode || b.id} {b.region ? ( <> @@ -162,16 +166,6 @@ export default function ClientDetailPage() { - - deleteMutation.mutate(clientId, { onSuccess: () => navigate("/clients") })} - isLoading={deleteMutation.isPending} - />
); } diff --git a/src/pages/users/operatorsView/index.tsx b/src/pages/users/operatorsView/index.tsx index f6a6c68..5561870 100644 --- a/src/pages/users/operatorsView/index.tsx +++ b/src/pages/users/operatorsView/index.tsx @@ -1,14 +1,12 @@ import { useParams, useNavigate, Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Pencil, Trash2, CheckCircle2, XCircle, UserRound } from "lucide-react"; -import { useState } from "react"; -import { Button } from "@/components/ui/button"; +import { CheckCircle2, XCircle, UserRound } from "lucide-react"; import { Skeleton } from "@/components/ui/skeleton"; -import { ConfirmDialog } from "@/components/confirmDialog"; -import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents"; +import { BentoGrid, BentoCard, InfoRow, ViewActions } from "@/components/viewPageComponents"; import { Badge } from "@/components/ui/badge"; import { useOperator, useDeleteOperator } from "@/features/operators/hooks/useOperators"; import type { LocalizedText } from "@/features/branches/api/branchesApi"; +import { formatFromApiDate } from "@/lib/utils/dateUtils"; // ─── Helper: resolve LocalizedText | string ─────────────────────────────────── @@ -35,8 +33,6 @@ export default function OperatorDetailPage() { const { data: operator, isLoading } = useOperator(operatorId); - const [deleteOpen, setDeleteOpen] = useState(false); - // ── Loading ─────────────────────────────────────────────────────────────── if (isLoading) { @@ -62,31 +58,24 @@ export default function OperatorDetailPage() { const roles = operator.roles ?? []; const permissions = operator.permissions ?? []; const branches = operator.branches ?? []; + const displayName = [operator.firstName, operator.lastName].filter(Boolean).join(" ") || operator.name; return (
{/* ── Page header ──────────────────────────────────────────────────── */}

- {t("operators.detailTitle", "Operator giňişleýin")}: {operator.name} + {t("operators.detailTitle", "Operator giňişleýin")}: {displayName}

- - + deleteMutation.mutateAsync(operatorId).then(() => navigate("/operators"))} + deleting={deleteMutation.isPending} + deleteTitle={t("operators.deleteTitle", "Operatory pozmak")} + deleteDescription={t("operators.deleteConfirm", "{{name}} operatoryny pozmak isleýärsiňizmi?", { name: operator.name })} + deleteConfirmLabel={t("common.delete", "Poz")} + />
@@ -105,13 +94,16 @@ export default function OperatorDetailPage() {
)} -
-

{operator.name}

+
+

{displayName}

+ {operator.username &&

@{operator.username}

}
+ + + + {roles.length > 0 && (
@@ -149,7 +143,7 @@ export default function OperatorDetailPage() { {branches.map((b) => ( - {resolveLocalizedName(b.name, lang)} + {resolveLocalizedName(b.name, lang) || b.uniqueCode || b.id} {b.region ? ( <> @@ -171,20 +165,6 @@ export default function OperatorDetailPage() { - - - deleteMutation.mutate(operatorId, { - onSuccess: () => navigate("/operators"), - }) - } - isLoading={deleteMutation.isPending} - />
); }