added some pages

This commit is contained in:
Jelaletdin12
2026-05-07 12:21:55 +05:00
parent c2548280a2
commit c7797c3e31
61 changed files with 8309 additions and 35 deletions

View File

@@ -3,23 +3,96 @@ import { createBrowserRouter, Navigate, Outlet } from "react-router-dom";
import { useAuthStore } from "../store/authStore";
import { Spinner } from "@/components/ui/spinner";
import { DashboardLayout } from "@/layouts/DashboardLayout";
import LoanOrderEditPage from "@/pages/loanOrderEdit";
const LoginPage = lazy(() => import("@/pages/login"));
const DashboardPage = lazy(() => import("@/pages/dashboard"));
const LoanOrdersPage = lazy(() => import("@/pages/loanOrders"));
const LoanOrderMobilesPage = lazy(() => import("@/pages/loanOrderMobile"));
const LoanRemainingPage = lazy(() => import("@/pages/loanRemaining"));
const LoanRemainingCreatePage = lazy(() => import("@/pages/loanRemainingCreate"));
const LoanRemainingViewPage = lazy(() => import("@/pages/loanRemainingView"));
const LoanRemainingEditPage = lazy(() => import("@/pages/loanRemainingEdit"));
const LoanPaidOffLettersPage = lazy(() => import("@/pages/loanPaidOffLetters"));
const LoanOrderCreatePage = lazy(() => import("@/pages/loanOrderCreate"));
const LoanOrderViewPage = lazy(() => import("@/pages/loanOrderView"));
const LoanOrderMobileViewPage = lazy(() => import("@/pages/loanOrderMobileView"));
const LoanOrderMobileEditPage = lazy(() => import("@/pages/loanOrderMobileEdit"));
const LoanOrderMobileCreatePage = lazy(() => import("@/pages/loanOrderMobileCreate"));
const LoanOrdersPage = lazy(() => import("@/pages/loanDepartment/loanOrders"));
const LoanOrderMobilesPage = lazy(
() => import("@/pages/loanDepartment/loanOrderMobile"),
);
const LoanRemainingPage = lazy(
() => import("@/pages/loanDepartment/loanRemaining"),
);
const LoanRemainingCreatePage = lazy(
() => import("@/pages/loanDepartment/loanRemainingCreate"),
);
const LoanRemainingViewPage = lazy(
() => import("@/pages/loanDepartment/loanRemainingView"),
);
const LoanRemainingEditPage = lazy(
() => import("@/pages/loanDepartment/loanRemainingEdit"),
);
const LoanPaidOffLettersPage = lazy(
() => import("@/pages/loanDepartment/loanPaidOffLetters"),
);
const LoanOrderCreatePage = lazy(
() => import("@/pages/loanDepartment/loanOrderCreate"),
);
const LoanOrderViewPage = lazy(
() => import("@/pages/loanDepartment/loanOrderView"),
);
const LoanOrderMobileViewPage = lazy(
() => import("@/pages/loanDepartment/loanOrderMobileView"),
);
const LoanOrderMobileEditPage = lazy(
() => import("@/pages/loanDepartment/loanOrderMobileEdit"),
);
const LoanOrderMobileCreatePage = lazy(
() => import("@/pages/loanDepartment/loanOrderMobileCreate"),
);
const LoanOrderEditPage = lazy(
() => import("@/pages/loanDepartment/loanOrderEdit"),
);
const OrderNewCardPage = lazy(
() => import("@/pages/cardDepartment/orderNewCard"),
);
const OrderNewCardCreatePage = lazy(
() => import("@/pages/cardDepartment/orderNewCardCreate"),
);
const OrderNewCardViewPage = lazy(
() => import("@/pages/cardDepartment/orderNewCardView"),
);
const OrderNewCardEditPage = lazy(
() => import("@/pages/cardDepartment/orderNewCardEdit"),
);
const CardTransactionsPage = lazy(
() => import("@/pages/cardDepartment/cardTransactions"),
);
const CardTransactionViewPage = lazy(
() => import("@/pages/cardDepartment/cardTransactionsView"),
);
const CardTransactionCreatePage = lazy(
() => import("@/pages/cardDepartment/cardTransactionsCreate"),
);
const CardTransactionEditPage = lazy(
() => import("@/pages/cardDepartment/cardTransactionsEdit"),
);
const CardRequisitesPage = lazy(
() => import("@/pages/cardDepartment/cardRequisites"),
);
const CardRequisiteViewPage = lazy(
() => import("@/pages/cardDepartment/cardRequisitesView"),
);
const CardRequisiteCreatePage = lazy(
() => import("@/pages/cardDepartment/cardRequisitesCreate"),
);
const CardRequisiteEditPage = lazy(
() => import("@/pages/cardDepartment/cardRequisitesEdit"),
);
const CardBalancePage = lazy(() => import("@/pages/cardDepartment/cardBalance"));
const CardBalanceCreatePage = lazy(() => import("@/pages/cardDepartment/cardBalanceCreate"));
const CardBalanceViewPage = lazy(() => import("@/pages/cardDepartment/cardBalanceView"));
const CardBalanceEditPage = lazy(() => import("@/pages/cardDepartment/cardBalanceEdit"));
const CardPinsPage = lazy(() => import("@/pages/cardDepartment/cardPins"));
const CardPinsCreatePage = lazy(() => import("@/pages/cardDepartment/cardPinsCreate"));
const CardPinsViewPage = lazy(() => import("@/pages/cardDepartment/cardPinsView"));
const CardPinsEditPage = lazy(() => import("@/pages/cardDepartment/cardPinsEdit"));
const VisaMasterPaymentsPage = lazy(() => import("@/pages/internationalPayments/visaMasterPayments"));
const VisaMasterPaymentCreatePage = lazy(() => import("@/pages/internationalPayments/visaMasterPaymentsCreate"));
const VisaMasterPaymentViewPage = lazy(() => import("@/pages/internationalPayments/visaMasterPaymentsView"));
const VisaMasterPaymentEditPage = lazy(() => import("@/pages/internationalPayments/visaMasterPaymentsEdit"));
function AuthGuard() {
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
if (!isAuthenticated) return <Navigate to="/login" replace />;
@@ -179,6 +252,199 @@ export const router = createBrowserRouter([
</Suspense>
),
},
{
// Sidebar: /order-new-card
path: "/order-new-card",
element: (
<Suspense fallback={<PageLoader />}>
<OrderNewCardPage />
</Suspense>
),
},
{
path: "/order-new-card/create",
element: (
<Suspense fallback={<PageLoader />}>
<OrderNewCardCreatePage />
</Suspense>
),
},
{
path: "/order-new-card/:id",
element: (
<Suspense fallback={<PageLoader />}>
<OrderNewCardViewPage />
</Suspense>
),
},
{
path: "/order-new-card/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<OrderNewCardEditPage />
</Suspense>
),
},
{
path: "/card-transactions",
element: (
<Suspense fallback={<PageLoader />}>
<CardTransactionsPage />
</Suspense>
),
},
{
path: "/card-transactions/create",
element: (
<Suspense fallback={<PageLoader />}>
<CardTransactionCreatePage />
</Suspense>
),
},
{
path: "/card-transactions/:id",
element: (
<Suspense fallback={<PageLoader />}>
<CardTransactionViewPage />
</Suspense>
),
},
{
path: "/card-transactions/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<CardTransactionEditPage />
</Suspense>
),
},
{
path: "/card-requisites",
element: (
<Suspense fallback={<PageLoader />}>
<CardRequisitesPage />
</Suspense>
),
},
{
path: "/card-requisites/create",
element: (
<Suspense fallback={<PageLoader />}>
<CardRequisiteCreatePage />
</Suspense>
),
},
{
path: "/card-requisites/:id",
element: (
<Suspense fallback={<PageLoader />}>
<CardRequisiteViewPage />
</Suspense>
),
},
{
path: "/card-requisites/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<CardRequisiteEditPage />
</Suspense>
),
},
{
path: "/card-balances",
element: (
<Suspense fallback={<PageLoader />}>
<CardBalancePage />
</Suspense>
),
},
{
path: "/card-balances/create",
element: (
<Suspense fallback={<PageLoader />}>
<CardBalanceCreatePage />
</Suspense>
),
},
{
path: "/card-balances/:id",
element: (
<Suspense fallback={<PageLoader />}>
<CardBalanceViewPage />
</Suspense>
),
},
{
path: "/card-balances/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<CardBalanceEditPage />
</Suspense>
),
},
{
path: "/card-pins",
element: (
<Suspense fallback={<PageLoader />}>
<CardPinsPage />
</Suspense>
),
},
{
path: "/card-pins/create",
element: (
<Suspense fallback={<PageLoader />}>
<CardPinsCreatePage />
</Suspense>
),
},
{
path: "/card-pins/:id",
element: (
<Suspense fallback={<PageLoader />}>
<CardPinsViewPage />
</Suspense>
),
},
{
path: "/card-pins/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<CardPinsEditPage />
</Suspense>
),
},
{ // Sidebar: /visa-master-payments
path: "/visa-master",
element: (
<Suspense fallback={<PageLoader />}>
<VisaMasterPaymentsPage />
</Suspense>
),
},
{
path: "/visa-master-payments/create",
element: (
<Suspense fallback={<PageLoader />}>
<VisaMasterPaymentCreatePage />
</Suspense>
),
},
{
path: "/visa-master-payments/:id",
element: (
<Suspense fallback={<PageLoader />}>
<VisaMasterPaymentViewPage />
</Suspense>
),
},
{
path: "/visa-master-payments/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<VisaMasterPaymentEditPage />
</Suspense>
),
},
],
},
],

View File

@@ -0,0 +1,197 @@
import * as React from "react"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm"
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className
)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"mb-2 inline-flex size-10 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"font-heading text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn(
"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
)
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}

View File

@@ -0,0 +1,104 @@
import {apiClient} from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export interface CardBalance {
id: number
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export interface CardBalanceListResponse {
data: CardBalance[]
total: number
page: number
per_page: number
}
export interface CreateCardBalancePayload {
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export type UpdateCardBalancePayload = CreateCardBalancePayload
export interface CardBalanceListParams {
page?: number
per_page?: number
search?: string
}
// ─── API ─────────────────────────────────────────────────────────────────────
const MOCK_CARD_BALANCES: CardBalance[] = [
{
id: 1,
passport_series: 'AA',
passport_number: '1112223',
card_number: '8600123412341234',
card_expiry_month: '10',
card_expiry_year: '2028',
},
{
id: 2,
passport_series: 'I-MR',
passport_number: '9988776',
card_number: '9860123456789012',
card_expiry_month: '05',
card_expiry_year: '2027',
},
{
id: 3,
passport_series: 'II-LB',
passport_number: '4455667',
card_number: '4400556677889900',
card_expiry_month: '12',
card_expiry_year: '2026',
},
]
export const cardBalancesApi = {
getAll: async (params?: CardBalanceListParams): Promise<CardBalanceListResponse> => {
// Mock data kullanmak için:
return { data: MOCK_CARD_BALANCES, total: MOCK_CARD_BALANCES.length, page: params?.page || 1, per_page: params?.per_page || 25 }
const { data } = await apiClient.get('/card-balances', { params })
return data
},
getById: async (id: number): Promise<CardBalance> => {
// Mock data kullanmak için:
const mock = MOCK_CARD_BALANCES.find(b => b.id === id)
if (mock) return mock
const { data } = await apiClient.get(`/card-balances/${id}`)
return data
},
create: async (payload: CreateCardBalancePayload): Promise<CardBalance> => {
const { data } = await apiClient.post('/card-balances', payload)
return data
},
update: async (id: number, payload: UpdateCardBalancePayload): Promise<CardBalance> => {
const { data } = await apiClient.put(`/card-balances/${id}`, payload)
return data
},
delete: async (id: number): Promise<void> => {
await apiClient.delete(`/card-balances/${id}`)
},
download: async (id: number): Promise<Blob> => {
const { data } = await apiClient.get(`/card-balances/${id}/download`, {
responseType: 'blob',
})
return data
},
}

View File

@@ -0,0 +1,204 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { FormInput } from '@/components/formInput'
import { type CardBalance } from '@/features/cardBalance/api/cardBalanceApi'
import { useCreateCardBalance, useUpdateCardBalance } from '@/features/cardBalance/hooks/useCardBalance'
interface CardBalanceFormProps {
mode: 'create' | 'edit'
initialData?: CardBalance
cardBalanceId?: number
}
interface FormState {
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
interface FormErrors {
passport_series?: string
passport_number?: string
card_number?: string
card_expiry_month?: string
card_expiry_year?: string
}
// ─── Constants ────────────────────────────────────────────────────────────────
const PASSPORT_SERIES_OPTIONS = [
{ value: 'I-MR', label: 'I-MR' },
{ value: 'II-MR', label: 'II-MR' },
{ value: 'I-LB', label: 'I-LB' },
{ value: 'II-LB', label: 'II-LB' },
{ value: 'III-LB', label: 'III-LB' },
{ value: 'I-BN', label: 'I-BN' },
{ value: 'II-BN', label: 'II-BN' },
{ value: 'I-AH', label: 'I-AH' },
{ value: 'I-AS', label: 'I-AS' },
{ value: 'I-DZ', label: 'I-DZ' },
{ value: 'II-DZ', label: 'II-DZ' },
{ value: 'A', label: 'A' },
{ value: 'B', label: 'B' },
]
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
const val = String(i + 1).padStart(2, '0')
return { value: val, label: val }
})
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
const year = String(new Date().getFullYear() + i)
return { value: year, label: year }
})
const EMPTY_FORM: FormState = {
passport_series: '',
passport_number: '',
card_number: '',
card_expiry_month: '',
card_expiry_year: '',
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState, t: (k: string, fallback: string) => string): FormErrors {
const errors: FormErrors = {}
if (!form.passport_series) errors.passport_series = t('Required', 'Pasport seriýasy hökmanydyr')
if (!form.passport_number) errors.passport_number = t('Required', 'Pasport belgisi hökmanydyr')
if (!form.card_number) errors.card_number = t('Required', 'Kart belgisi hökmanydyr')
if (!form.card_expiry_month) errors.card_expiry_month = t('Required', 'Möhleti (aý) hökmanydyr')
if (!form.card_expiry_year) errors.card_expiry_year = t('Required', 'Möhleti (ýyl) hökmanydyr')
return errors
}
// ─── Component ────────────────────────────────────────────────────────────────
export function CardBalanceForm({ mode, initialData, cardBalanceId }: CardBalanceFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(EMPTY_FORM)
const [errors, setErrors] = useState<FormErrors>({})
const createMutation = useCreateCardBalance()
const updateMutation = useUpdateCardBalance(cardBalanceId ?? 0)
const isPending = createMutation.isPending || updateMutation.isPending
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
passport_series: initialData.passport_series,
passport_number: initialData.passport_number,
card_number: initialData.card_number,
card_expiry_month: initialData.card_expiry_month,
card_expiry_year: initialData.card_expiry_year,
})
}
}, [mode, initialData])
const setField = (field: keyof FormState) => (value: string) => {
setForm((prev) => ({ ...prev, [field]: value }))
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
}
const handleSubmit = async () => {
const validationErrors = validate(form, t)
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
return
}
if (mode === 'create') {
await createMutation.mutateAsync(form)
navigate('/card-balances')
} else {
await updateMutation.mutateAsync(form)
navigate(`/card-balances/${cardBalanceId}`)
}
}
const handleCancel = () => {
if (mode === 'create') navigate('/card-balances')
else navigate(`/card-balances/${cardBalanceId}`)
}
return (
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Row 1 */}
<FormInput
type="searchable-select"
label={t('Passport series', 'Pasport seriýasy')}
value={form.passport_series}
onChange={setField('passport_series')}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
error={errors.passport_series}
required
/>
<FormInput
type="text"
label={t('Passport number', 'Pasport belgisi')}
value={form.passport_number}
onChange={setField('passport_number')}
placeholder={t('Passport number', 'Pasport belgisi')}
error={errors.passport_number}
required
/>
{/* Row 2 — card number full width + 2 selects */}
<FormInput
type="text"
label={t('Card number', 'Kart belgisi')}
value={form.card_number}
onChange={setField('card_number')}
placeholder={t('Card number', 'Kart belgisi')}
error={errors.card_number}
required
/>
<div className="grid grid-cols-2 gap-3">
<FormInput
type="select"
label={t('Card expiry month', 'Kart Möhleti (aý)')}
value={form.card_expiry_month}
onChange={setField('card_expiry_month')}
options={MONTH_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.card_expiry_month}
required
/>
<FormInput
type="select"
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
value={form.card_expiry_year}
onChange={setField('card_expiry_year')}
options={YEAR_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.card_expiry_year}
required
/>
</div>
</div>
{/* Actions */}
<div className="flex justify-end gap-3 mt-6">
<Button variant="ghost" onClick={handleCancel} disabled={isPending}>
{t('Cancel', 'Ýatyr')}
</Button>
<Button onClick={handleSubmit} disabled={isPending}>
{isPending
? t('Saving...', 'Saklanýar...')
: mode === 'create'
? t('Create card balance', 'Kart galyndysy dörediň')
: t('Save changes', 'Üýtgetmeleri sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,96 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
cardBalancesApi,
type CardBalanceListParams,
type CreateCardBalancePayload,
type UpdateCardBalancePayload,
} from '../api/cardBalanceApi'
const QUERY_KEY = 'card-balances'
export function useCardBalances(params?: CardBalanceListParams) {
return useQuery({
queryKey: [QUERY_KEY, params],
queryFn: () => cardBalancesApi.getAll(params),
})
}
export function useCardBalance(id: number) {
return useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => cardBalancesApi.getById(id),
enabled: !!id,
})
}
export function useCreateCardBalance() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CreateCardBalancePayload) => cardBalancesApi.create(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card balance created successfully', 'Kart galyndysy üstünlikli döredildi'))
},
onError: () => {
toast.error(t('Failed to create card balance', 'Kart galyndysy döredilmedi'))
},
})
}
export function useUpdateCardBalance(id: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: UpdateCardBalancePayload) => cardBalancesApi.update(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card balance updated successfully', 'Kart galyndysy üstünlikli üýtgedildi'))
},
onError: () => {
toast.error(t('Failed to update card balance', 'Kart galyndysy üýtgedilmedi'))
},
})
}
export function useDeleteCardBalance() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: number) => cardBalancesApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card balance deleted successfully', 'Kart galyndysy üstünlikli öçürildi'))
},
onError: () => {
toast.error(t('Failed to delete card balance', 'Kart galyndysy öçürilmedi'))
},
})
}
export function useDownloadCardBalance() {
const { t } = useTranslation()
return useMutation({
mutationFn: async (id: number) => {
const blob = await cardBalancesApi.download(id)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `card-balance-${id}.pdf`
a.click()
URL.revokeObjectURL(url)
},
onSuccess: () => {
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
},
onError: () => {
toast.error(t('Download failed', 'Ýüklemek başartmady'))
},
})
}

View File

@@ -0,0 +1,205 @@
import { apiClient } from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export type CardPinStatus = 'pending' | 'approved' | 'rejected'
export interface CardPinItem {
id: string
card_type: string
card_type_label: string
card_number: string
created_at: string
province: string
province_label: string
branch: string
branch_label: string
first_name: string
last_name: string
father_name: string
birth_date: string
phone: string
status: CardPinStatus
note: string | null
passport_series: string
passport_number: string
passport_file_1: string | null
passport_file_2: string | null
passport_file_3: string | null
passport_file_4: string | null
created_by: string
created_by_label: string
}
export interface CardPinListParams {
page?: number
per_page?: number
search?: string
status?: CardPinStatus | ''
province?: string
}
export interface CardPinListResponse {
data: CardPinItem[]
meta: {
current_page: number
last_page: number
per_page: number
total: number
}
}
export interface CardPinCreatePayload {
status: CardPinStatus
note: string
card_type: string
card_number: string
province: string
branch: string
first_name: string
last_name: string
father_name: string
birth_date: string
phone: string
passport_series: string
passport_number: string
passport_file_1: File | null
passport_file_2: File | null
passport_file_3: File | null
passport_file_4: File | null
}
export type CardPinUpdatePayload = CardPinCreatePayload
// ─── API Functions ────────────────────────────────────────────────────────────
const MOCK_CARD_PINS: CardPinItem[] = [
{
id: '1',
card_type: 'altyn_asyr',
card_type_label: 'Altyn Asyr',
card_number: '8600123456789012',
created_at: '2024-05-07 10:00',
province: 'ashgabat',
province_label: 'Aşgabat',
branch: '1',
branch_label: 'Merkezi şahamça',
first_name: 'Aman',
last_name: 'Amanow',
father_name: 'Amanowiç',
birth_date: '1990-01-01',
phone: '99365123456',
status: 'pending',
note: 'Test bellik',
passport_series: 'I-MR',
passport_number: '123456',
passport_file_1: null,
passport_file_2: null,
passport_file_3: null,
passport_file_4: null,
created_by: '1',
created_by_label: 'Admin',
},
{
id: '2',
card_type: 'visa',
card_type_label: 'Visa',
card_number: '4400123456789012',
created_at: '2024-05-07 11:30',
province: 'mary',
province_label: 'Mary',
branch: '2',
branch_label: 'Mary şahamçasy',
first_name: 'Berdi',
last_name: 'Berdiyew',
father_name: 'Berdiyewiç',
birth_date: '1995-05-05',
phone: '99361112233',
status: 'approved',
note: null,
passport_series: 'I-LB',
passport_number: '654321',
passport_file_1: null,
passport_file_2: null,
passport_file_3: null,
passport_file_4: null,
created_by: '1',
created_by_label: 'Admin',
},
]
export const cardPinApi = {
list: async (params: CardPinListParams): Promise<CardPinListResponse> => {
// Mock data return
return {
data: MOCK_CARD_PINS,
meta: {
current_page: params.page || 1,
last_page: 1,
per_page: params.per_page || 25,
total: MOCK_CARD_PINS.length,
}
}
const { data } = await apiClient.get('/card-pins', { params })
return data
},
getById: async (id: string): Promise<CardPinItem> => {
const mock = MOCK_CARD_PINS.find(p => p.id === id)
if (mock) return mock
const { data } = await apiClient.get(`/card-pins/${id}`)
return data
},
create: (payload: CardPinCreatePayload): Promise<CardPinItem> => {
const form = buildFormData(payload)
return apiClient.post('/card-pins', form, {
headers: { 'Content-Type': 'multipart/form-data' },
}).then((r) => r.data)
},
update: (id: string, payload: CardPinUpdatePayload): Promise<CardPinItem> => {
const form = buildFormData(payload)
form.append('_method', 'PUT')
return apiClient.post(`/card-pins/${id}`, form, {
headers: { 'Content-Type': 'multipart/form-data' },
}).then((r) => r.data)
},
delete: (id: string): Promise<void> =>
apiClient.delete(`/card-pins/${id}`).then((r) => r.data),
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function buildFormData(payload: CardPinCreatePayload): FormData {
const form = new FormData()
const textFields: (keyof CardPinCreatePayload)[] = [
'status', 'note', 'card_type', 'card_number',
'province', 'branch',
'first_name', 'last_name', 'father_name',
'birth_date', 'phone',
'passport_series', 'passport_number',
]
for (const key of textFields) {
const val = payload[key]
if (val !== null && val !== undefined) {
form.append(key, String(val))
}
}
const fileFields: (keyof CardPinCreatePayload)[] = [
'passport_file_1', 'passport_file_2', 'passport_file_3', 'passport_file_4',
]
for (const key of fileFields) {
const file = payload[key]
if (file instanceof File) form.append(key, file)
}
return form
}

View File

@@ -0,0 +1,416 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import type { CardPinItem, CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi'
// ─── Types ────────────────────────────────────────────────────────────────────
interface CardPinFormProps {
mode: 'create' | 'edit'
initialData?: CardPinItem
onSubmit: (payload: CardPinCreatePayload) => void
isSubmitting: boolean
}
interface FormState {
status: string
note: string
card_type: string
card_number: string
province: string
branch: string
first_name: string
last_name: string
father_name: string
birth_date: string
phone: string
passport_series: string
passport_number: string
passport_file_1: File | null
passport_file_2: File | null
passport_file_3: File | null
passport_file_4: File | null
}
type FormErrors = Partial<Record<keyof FormState, string>>
// ─── Constants ────────────────────────────────────────────────────────────────
const STATUS_OPTIONS = [
{ value: 'pending', label: 'Garaşylýar' },
{ value: 'approved', label: 'Tassyklandy' },
{ value: 'rejected', label: 'Ret edildi' },
]
// These would typically come from API — using static options as placeholder
const CARD_TYPE_OPTIONS = [
{ value: 'altyn_asyr', label: 'Altyn Asyr' },
{ value: 'visa', label: 'Visa' },
{ value: 'mastercard', label: 'MasterCard' },
]
const PASSPORT_SERIES_OPTIONS = [
{ value: 'I', label: 'I' },
{ value: 'II', label: 'II' },
{ value: 'I-MR', label: 'I-MR' },
{ value: 'II-MR',label: 'II-MR' },
]
const PROVINCE_OPTIONS = [
{ value: 'ashgabat', label: 'Aşgabat' },
{ value: 'mary', label: 'Mary' },
{ value: 'dasoguz', label: 'Daşoguz' },
{ value: 'lebap', label: 'Lebap' },
{ value: 'balkan', label: 'Balkan' },
{ value: 'ahal', label: 'Ahal' },
]
// ─── Default state ────────────────────────────────────────────────────────────
const defaultState: FormState = {
status: 'pending',
note: '',
card_type: '',
card_number: '',
province: '',
branch: '',
first_name: '',
last_name: '',
father_name: '',
birth_date: '',
phone: '',
passport_series: '',
passport_number: '',
passport_file_1: null,
passport_file_2: null,
passport_file_3: null,
passport_file_4: null,
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState, mode: 'create' | 'edit'): FormErrors {
const errors: FormErrors = {}
if (!form.status) errors.status = 'Status hökmany'
if (!form.card_type) errors.card_type = 'Kart görnüşi hökmany'
if (!form.card_number) errors.card_number = 'Kart belgisi hökmany'
if (!form.province) errors.province = 'Welaýat hökmany'
if (!form.branch) errors.branch = 'Şahamça hökmany'
if (!form.first_name) errors.first_name = 'Ady hökmany'
if (!form.last_name) errors.last_name = 'Familiýasy hökmany'
if (!form.birth_date) errors.birth_date = 'Doglan güni hökmany'
if (!form.phone) errors.phone = 'Telefon hökmany'
if (!form.passport_series) errors.passport_series = 'Pasport seriýasy hökmany'
if (!form.passport_number) errors.passport_number = 'Pasport belgisi hökmany'
if (mode === 'create') {
if (!form.passport_file_1) errors.passport_file_1 = 'Pasport (sahypa 1) hökmany'
if (!form.passport_file_2) errors.passport_file_2 = 'Pasport (2-3-nji sahypa) hökmany'
if (!form.passport_file_3) errors.passport_file_3 = 'Pasport (8-9 sahypa) hökmany'
if (!form.passport_file_4) errors.passport_file_4 = 'Pasport (32-nji sahypa) hökmany'
}
return errors
}
// ─── Component ────────────────────────────────────────────────────────────────
export function CardPinForm({ mode, initialData, onSubmit, isSubmitting }: CardPinFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(defaultState)
const [errors, setErrors] = useState<FormErrors>({})
// Hydrate form when editing
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
status: initialData.status,
note: initialData.note ?? '',
card_type: initialData.card_type,
card_number: initialData.card_number,
province: initialData.province,
branch: initialData.branch,
first_name: initialData.first_name,
last_name: initialData.last_name,
father_name: initialData.father_name,
birth_date: initialData.birth_date,
phone: initialData.phone,
passport_series: initialData.passport_series,
passport_number: initialData.passport_number,
passport_file_1: null,
passport_file_2: null,
passport_file_3: null,
passport_file_4: null,
})
}
}, [mode, initialData])
const set = <K extends keyof FormState>(key: K, value: FormState[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined }))
}
const handleSubmit = () => {
const errs = validate(form, mode)
if (Object.keys(errs).length > 0) {
setErrors(errs)
return
}
onSubmit({
status: form.status as CardPinCreatePayload['status'],
note: form.note,
card_type: form.card_type,
card_number: form.card_number,
province: form.province,
branch: form.branch,
first_name: form.first_name,
last_name: form.last_name,
father_name: form.father_name,
birth_date: form.birth_date,
phone: form.phone,
passport_series: form.passport_series,
passport_number: form.passport_number,
passport_file_1: form.passport_file_1,
passport_file_2: form.passport_file_2,
passport_file_3: form.passport_file_3,
passport_file_4: form.passport_file_4,
})
}
const title = mode === 'create'
? t('cardPin.create', 'Kart pin bukja dörediň')
: t('cardPin.edit', 'Kart pin bukja redaktirläň')
const submitLabel = mode === 'create'
? t('cardPin.createBtn', 'Kart pin bukja dörediň')
: t('cardPin.editBtn', 'Kart pin bukja redaktirläň')
return (
<div className="max-w-4xl mx-auto space-y-6">
<h1 className="text-2xl font-bold text-foreground">{title}</h1>
{/* ── Status & Note ────────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<FormInput
type="select"
label={t('cardPin.status', 'Status')}
value={form.status}
onChange={(v) => set('status', v)}
options={STATUS_OPTIONS}
error={errors.status}
required
/>
<FormInput
type="text"
label={t('cardPin.note', 'Bellik')}
value={form.note}
onChange={(v) => set('note', v)}
placeholder={t('cardPin.notePlaceholder', 'Bellik')}
/>
</section>
{/* ── Kart ─────────────────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6">
<h2 className="text-base font-semibold text-foreground mb-4">
{t('cardPin.cardSection', 'Kart')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('cardPin.cardType', 'Kart görnüşi')}
value={form.card_type}
onChange={(v) => set('card_type', v)}
options={CARD_TYPE_OPTIONS}
error={errors.card_type}
required
/>
<FormInput
type="text"
label={t('cardPin.cardNumber', 'Kart belgisi')}
value={form.card_number}
onChange={(v) => set('card_number', v)}
placeholder={t('cardPin.cardNumberPlaceholder', 'Kart belgisi')}
error={errors.card_number}
required
/>
</div>
</section>
{/* ── Lokasiýa ─────────────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6">
<h2 className="text-base font-semibold text-foreground mb-4">
{t('cardPin.locationSection', 'Lokasiýa')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('cardPin.province', 'Welaýat')}
value={form.province}
onChange={(v) => { set('province', v); set('branch', '') }}
options={PROVINCE_OPTIONS}
error={errors.province}
required
/>
<FormInput
type="searchable-select"
label={t('cardPin.branch', 'Şahamça')}
value={form.branch}
onChange={(v) => set('branch', v)}
options={[]} // Populated dynamically based on province from API
placeholder={t('cardPin.branchPlaceholder', 'Saýlamak üçin basyň')}
error={errors.branch}
required
/>
</div>
</section>
{/* ── Şahsy maglumatlar ─────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6">
<h2 className="text-base font-semibold text-foreground mb-4">
{t('cardPin.personalSection', 'Şahsy maglumatlar')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
type="text"
label={t('cardPin.firstName', 'Ady')}
value={form.first_name}
onChange={(v) => set('first_name', v)}
placeholder={t('cardPin.firstName', 'Ady')}
error={errors.first_name}
required
/>
<FormInput
type="text"
label={t('cardPin.lastName', 'Familiýasy')}
value={form.last_name}
onChange={(v) => set('last_name', v)}
placeholder={t('cardPin.lastName', 'Familiýasy')}
error={errors.last_name}
required
/>
<FormInput
type="text"
label={t('cardPin.fatherName', 'Atasynyň ady')}
value={form.father_name}
onChange={(v) => set('father_name', v)}
placeholder={t('cardPin.fatherName', 'Atasynyň ady')}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4">
<FormInput
type="date"
label={t('cardPin.birthDate', 'Doglan güni')}
value={form.birth_date}
onChange={(v) => set('birth_date', v)}
error={errors.birth_date}
required
/>
<FormInput
type="phone"
label={t('cardPin.phone', 'Telefon')}
value={form.phone}
onChange={(v) => set('phone', v)}
error={errors.phone}
required
/>
</div>
</section>
{/* ── Pasport ───────────────────────────────────────────────────────── */}
<section className="bg-card border border-border rounded-lg p-6">
<h2 className="text-base font-semibold text-foreground mb-4">
{t('cardPin.passportSection', 'Pasport')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
<FormInput
type="searchable-select"
label={t('cardPin.passportSeries', 'Pasport seriýasy')}
value={form.passport_series}
onChange={(v) => set('passport_series', v)}
options={PASSPORT_SERIES_OPTIONS}
error={errors.passport_series}
required
/>
<FormInput
type="text"
label={t('cardPin.passportNumber', 'Pasport belgisi')}
value={form.passport_number}
onChange={(v) => set('passport_number', v)}
placeholder={t('cardPin.passportNumber', 'Pasport belgisi')}
error={errors.passport_number}
required
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="file"
label={t('cardPin.passportFile1', 'Pasport (sahypa 1)')}
onFileChange={(f) => set('passport_file_1', f)}
fileValue={form.passport_file_1}
accept="image/*,.pdf"
error={errors.passport_file_1}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('cardPin.passportFile2', 'Pasport (2-3-nji sahypa)')}
onFileChange={(f) => set('passport_file_2', f)}
fileValue={form.passport_file_2}
accept="image/*,.pdf"
error={errors.passport_file_2}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('cardPin.passportFile3', 'Pasport (8-9 sahypa)')}
onFileChange={(f) => set('passport_file_3', f)}
fileValue={form.passport_file_3}
accept="image/*,.pdf"
error={errors.passport_file_3}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('cardPin.passportFile4', 'Pasport (32-nji sahypa)')}
onFileChange={(f) => set('passport_file_4', f)}
fileValue={form.passport_file_4}
accept="image/*,.pdf"
error={errors.passport_file_4}
required={mode === 'create'}
/>
</div>
</section>
{/* ── Actions ───────────────────────────────────────────────────────── */}
<div className="flex items-center justify-end gap-3 pb-6">
<Button
type="button"
variant="outline"
onClick={() => navigate('/card-pins')}
disabled={isSubmitting}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isSubmitting}
className="min-w-[180px]"
>
{isSubmitting ? (
<Spinner className="size-4" />
) : (
submitLabel
)}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,86 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import { cardPinApi, type CardPinListParams, type CardPinCreatePayload, type CardPinUpdatePayload } from '../api/cardPinApi'
export const CARD_PIN_KEYS = {
all: ['card-pins'] as const,
lists: () => [...CARD_PIN_KEYS.all, 'list'] as const,
list: (p: CardPinListParams) => [...CARD_PIN_KEYS.lists(), p] as const,
detail: (id: string) => [...CARD_PIN_KEYS.all, 'detail', id] as const,
}
// ─── List ─────────────────────────────────────────────────────────────────────
export function useCardPins(params: CardPinListParams) {
return useQuery({
queryKey: CARD_PIN_KEYS.list(params),
queryFn: () => cardPinApi.list(params),
placeholderData: (prev) => prev,
})
}
// ─── Detail ───────────────────────────────────────────────────────────────────
export function useCardPin(id: string) {
return useQuery({
queryKey: CARD_PIN_KEYS.detail(id),
queryFn: () => cardPinApi.getById(id),
enabled: !!id,
})
}
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardPin() {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CardPinCreatePayload) => cardPinApi.create(payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
toast.success(t('cardPin.createSuccess', 'Kart pin bukja döredildi'))
},
onError: () => {
toast.error(t('cardPin.createError', 'Döretmek başartmady'))
},
})
}
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardPin(id: string) {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CardPinUpdatePayload) => cardPinApi.update(id, payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.detail(id) })
toast.success(t('cardPin.updateSuccess', 'Kart pin bukja üýtgedildi'))
},
onError: () => {
toast.error(t('cardPin.updateError', 'Üýtgetmek başartmady'))
},
})
}
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardPin() {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: string) => cardPinApi.delete(id),
onSuccess: () => {
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
toast.success(t('cardPin.deleteSuccess', 'Kart pin bukja pozuldy'))
},
onError: () => {
toast.error(t('cardPin.deleteError', 'Pozmak başartmady'))
},
})
}

View File

@@ -0,0 +1,142 @@
import {apiClient} from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export type CardRequisiteStatus = 'pending' | 'approved' | 'rejected'
export interface CardRequisite {
id: string
status: CardRequisiteStatus
note: string
created_at: string
// Card
card_type: string
card_number: string
card_expiry_month: string
card_expiry_year: string
// Location
province_id: string
branch_id: string
province_name?: string
branch_name?: string
// Personal
first_name: string
last_name: string
middle_name: string
birth_date: string
phone: string
// Passport
passport_series: string
passport_number: string
passport_page1_url?: string
passport_page2_3_url?: string
passport_page8_9_url?: string
passport_page32_url?: string
}
export interface CardRequisiteListResponse {
data: CardRequisite[]
total: number
page: number
per_page: number
}
export interface CreateCardRequisitePayload {
status: CardRequisiteStatus
note: string
card_type: string
card_number: string
card_expiry_month: string
card_expiry_year: string
province_id: string
branch_id: string
first_name: string
last_name: string
middle_name: string
birth_date: string
phone: string
passport_series: string
passport_number: string
passport_page1?: File
passport_page2_3?: File
passport_page8_9?: File
passport_page32?: File
}
export type UpdateCardRequisitePayload = CreateCardRequisitePayload
export interface CardRequisiteListParams {
page?: number
per_page?: number
search?: string
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function buildFormData(payload: CreateCardRequisitePayload): FormData {
const fd = new FormData()
const textFields: (keyof Omit<
CreateCardRequisitePayload,
'passport_page1' | 'passport_page2_3' | 'passport_page8_9' | 'passport_page32'
>)[] = [
'status', 'note', 'card_type', 'card_number', 'card_expiry_month',
'card_expiry_year', 'province_id', 'branch_id', 'first_name', 'last_name',
'middle_name', 'birth_date', 'phone', 'passport_series', 'passport_number',
]
textFields.forEach((key) => {
const val = payload[key]
if (val !== undefined && val !== null) fd.append(key, val)
})
if (payload.passport_page1) fd.append('passport_page1', payload.passport_page1)
if (payload.passport_page2_3) fd.append('passport_page2_3', payload.passport_page2_3)
if (payload.passport_page8_9) fd.append('passport_page8_9', payload.passport_page8_9)
if (payload.passport_page32) fd.append('passport_page32', payload.passport_page32)
return fd
}
// ─── API functions ────────────────────────────────────────────────────────────
export const cardRequisitesApi = {
getAll: async (params?: CardRequisiteListParams): Promise<CardRequisiteListResponse> => {
const { data } = await apiClient.get('/card-requisites', { params })
return data
},
getById: async (id: string): Promise<CardRequisite> => {
const { data } = await apiClient.get(`/card-requisites/${id}`)
return data
},
create: async (payload: CreateCardRequisitePayload): Promise<CardRequisite> => {
const { data } = await apiClient.post('/card-requisites', buildFormData(payload), {
headers: { 'Content-Type': 'multipart/form-data' },
})
return data
},
update: async (id: string, payload: UpdateCardRequisitePayload): Promise<CardRequisite> => {
const { data } = await apiClient.post(`/card-requisites/${id}`, buildFormData(payload), {
headers: { 'Content-Type': 'multipart/form-data' },
})
return data
},
delete: async (id: string): Promise<void> => {
await apiClient.delete(`/card-requisites/${id}`)
},
download: async (id: string): Promise<Blob> => {
const { data } = await apiClient.get(`/card-requisites/${id}/download`, {
responseType: 'blob',
})
return data
},
}

View File

@@ -0,0 +1,501 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { FormInput } from '@/components/formInput'
import type { CardRequisite, CardRequisiteStatus, CreateCardRequisitePayload } from '../api/cardRequisitesApi'
import { useCreateCardRequisite, useUpdateCardRequisite } from '../hooks/useCardRequisites'
// ─── Types ────────────────────────────────────────────────────────────────────
interface CardRequisiteFormProps {
mode: 'create' | 'edit'
initialData?: CardRequisite
cardRequisiteId?: string
}
interface FormState {
status: string
note: string
card_type: string
card_number: string
card_expiry_month: string
card_expiry_year: string
province_id: string
branch_id: string
first_name: string
last_name: string
middle_name: string
birth_date: string
phone: string
passport_series: string
passport_number: string
}
interface FileState {
passport_page1: File | null
passport_page2_3: File | null
passport_page8_9: File | null
passport_page32: File | null
}
interface FormErrors {
status?: string
card_type?: string
card_number?: string
card_expiry_month?: string
card_expiry_year?: string
province_id?: string
branch_id?: string
first_name?: string
last_name?: string
birth_date?: string
phone?: string
passport_series?: string
passport_number?: string
passport_page1?: string
passport_page2_3?: string
passport_page8_9?: string
passport_page32?: string
}
// ─── Constants ────────────────────────────────────────────────────────────────
const STATUS_OPTIONS = [
{ value: 'pending', label: 'Garaşylýar' },
{ value: 'approved', label: 'Tassyklanan' },
{ value: 'rejected', label: 'Ret edilen' },
]
const CARD_TYPE_OPTIONS = [
{ value: 'altyn_asyr', label: 'Altyn Asyr' },
{ value: 'visa', label: 'Visa' },
{ value: 'mastercard', label: 'MasterCard' },
]
const PASSPORT_SERIES_OPTIONS = [
{ value: 'I-MR', label: 'I-MR' },
{ value: 'II-MR', label: 'II-MR' },
{ value: 'I-LB', label: 'I-LB' },
{ value: 'II-LB', label: 'II-LB' },
{ value: 'III-LB', label: 'III-LB' },
{ value: 'A', label: 'A' },
{ value: 'B', label: 'B' },
]
const PROVINCE_OPTIONS = [
{ value: '1', label: 'Aşgabat' },
{ value: '2', label: 'Ahal' },
{ value: '3', label: 'Balkan' },
{ value: '4', label: 'Daşoguz' },
{ value: '5', label: 'Lebap' },
{ value: '6', label: 'Mary' },
]
const BRANCH_OPTIONS: Record<string, { value: string; label: string }[]> = {
'1': [{ value: '11', label: 'Köpetdag' }, { value: '12', label: 'Çandybil' }, { value: '13', label: 'Büzmeyin' }],
'2': [{ value: '21', label: 'Änew' }, { value: '22', label: 'Tejen' }],
'3': [{ value: '31', label: 'Balkanabat' }, { value: '32', label: 'Türkmenbaşy' }],
'4': [{ value: '41', label: 'Daşoguz ş.' }, { value: '42', label: 'Köneürgenç' }],
'5': [{ value: '51', label: 'Türkmenabat' }, { value: '52', label: 'Hazar' }],
'6': [{ value: '61', label: 'Mary ş.' }, { value: '62', label: 'Ýolöten' }, { value: '63', label: 'Şatlyk' }],
}
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
const val = String(i + 1).padStart(2, '0')
return { value: val, label: val }
})
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
const year = String(new Date().getFullYear() + i)
return { value: year, label: year }
})
const EMPTY_FORM: FormState = {
status: 'pending',
note: '',
card_type: '',
card_number: '',
card_expiry_month: '',
card_expiry_year: '',
province_id: '',
branch_id: '',
first_name: '',
last_name: '',
middle_name: '',
birth_date: '',
phone: '',
passport_series: '',
passport_number: '',
}
const EMPTY_FILES: FileState = {
passport_page1: null,
passport_page2_3: null,
passport_page8_9: null,
passport_page32: null,
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(
form: FormState,
files: FileState,
mode: 'create' | 'edit',
t: (k: string, fallback: string) => string,
): FormErrors {
const errors: FormErrors = {}
if (!form.status) errors.status = t('Status is required', 'Status hökmanydyr')
if (!form.card_type) errors.card_type = t('Card type is required', 'Görnüşi hökmanydyr')
if (!form.card_number) errors.card_number = t('Card number is required', 'Kart belgisi hökmanydyr')
if (!form.card_expiry_month) errors.card_expiry_month = t('Expiry month is required', 'Möhleti (aý) hökmanydyr')
if (!form.card_expiry_year) errors.card_expiry_year = t('Expiry year is required', 'Möhleti (ýyl) hökmanydyr')
if (!form.province_id) errors.province_id = t('Province is required', 'Welaýat hökmanydyr')
if (!form.branch_id) errors.branch_id = t('Branch is required', 'Şahamça hökmanydyr')
if (!form.first_name) errors.first_name = t('First name is required', 'Ady hökmanydyr')
if (!form.last_name) errors.last_name = t('Last name is required', 'Familiýasy hökmanydyr')
if (!form.birth_date) errors.birth_date = t('Birth date is required', 'Doglan güni hökmanydyr')
if (!form.phone) errors.phone = t('Phone is required', 'Telefon hökmanydyr')
if (!form.passport_series) errors.passport_series = t('Passport series is required', 'Pasport seriýasy hökmanydyr')
if (!form.passport_number) errors.passport_number = t('Passport number is required', 'Pasport belgisi hökmanydyr')
// Files only required on create
if (mode === 'create') {
if (!files.passport_page1) errors.passport_page1 = t('Required', 'Hökmanydyr')
if (!files.passport_page2_3) errors.passport_page2_3 = t('Required', 'Hökmanydyr')
if (!files.passport_page8_9) errors.passport_page8_9 = t('Required', 'Hökmanydyr')
if (!files.passport_page32) errors.passport_page32 = t('Required', 'Hökmanydyr')
}
return errors
}
// ─── Section header ───────────────────────────────────────────────────────────
function SectionTitle({ children }: { children: React.ReactNode }) {
return (
<h2 className="text-base font-semibold text-foreground mt-6 mb-3">{children}</h2>
)
}
// ─── Component ────────────────────────────────────────────────────────────────
export function CardRequisiteForm({
mode,
initialData,
cardRequisiteId,
}: CardRequisiteFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(EMPTY_FORM)
const [files, setFiles] = useState<FileState>(EMPTY_FILES)
const [errors, setErrors] = useState<FormErrors>({})
const createMutation = useCreateCardRequisite()
const updateMutation = useUpdateCardRequisite(cardRequisiteId ?? '')
const isPending = createMutation.isPending || updateMutation.isPending
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
status: initialData.status,
note: initialData.note,
card_type: initialData.card_type,
card_number: initialData.card_number,
card_expiry_month: initialData.card_expiry_month,
card_expiry_year: initialData.card_expiry_year,
province_id: initialData.province_id,
branch_id: initialData.branch_id,
first_name: initialData.first_name,
last_name: initialData.last_name,
middle_name: initialData.middle_name,
birth_date: initialData.birth_date,
phone: initialData.phone,
passport_series: initialData.passport_series,
passport_number: initialData.passport_number,
})
}
}, [mode, initialData])
const setField = (field: keyof FormState) => (value: string) => {
setForm((prev) => {
const next = { ...prev, [field]: value }
// Reset branch when province changes
if (field === 'province_id') next.branch_id = ''
return next
})
if (errors[field as keyof FormErrors])
setErrors((prev) => ({ ...prev, [field]: undefined }))
}
const setFile = (field: keyof FileState) => (file: File | null) => {
setFiles((prev) => ({ ...prev, [field]: file }))
if (errors[field as keyof FormErrors])
setErrors((prev) => ({ ...prev, [field]: undefined }))
}
const handleSubmit = async () => {
const validationErrors = validate(form, files, mode, t)
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
return
}
const payload: CreateCardRequisitePayload = {
...(form as unknown as CreateCardRequisitePayload),
status: form.status as CardRequisiteStatus,
...(files.passport_page1 && { passport_page1: files.passport_page1 }),
...(files.passport_page2_3 && { passport_page2_3: files.passport_page2_3 }),
...(files.passport_page8_9 && { passport_page8_9: files.passport_page8_9 }),
...(files.passport_page32 && { passport_page32: files.passport_page32 }),
}
if (mode === 'create') {
await createMutation.mutateAsync(payload)
navigate('/card-requisites')
} else {
await updateMutation.mutateAsync(payload)
navigate(`/card-requisites/${cardRequisiteId}`)
}
}
const handleCancel = () => {
if (mode === 'create') navigate('/card-requisites')
else navigate(`/card-requisites/${cardRequisiteId}`)
}
const branchOptions = BRANCH_OPTIONS[form.province_id] ?? []
return (
<div className="space-y-0">
{/* ── General ── */}
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="select"
label={t('Status', 'Status')}
value={form.status}
onChange={setField('status')}
options={STATUS_OPTIONS}
error={errors.status}
required
/>
<FormInput
type="text"
label={t('Note', 'Bellik')}
value={form.note}
onChange={setField('note')}
placeholder={t('Note', 'Bellik')}
/>
</div>
</div>
{/* ── Kart ── */}
<SectionTitle>{t('Card', 'Kart')}</SectionTitle>
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<FormInput
type="select"
label={t('Card type', 'Görnüşi')}
value={form.card_type}
onChange={setField('card_type')}
options={CARD_TYPE_OPTIONS}
placeholder="—"
error={errors.card_type}
required
/>
<FormInput
type="text"
label={t('Card number', 'Kart belgisi')}
value={form.card_number}
onChange={setField('card_number')}
placeholder={t('Card number', 'Kart belgisi')}
error={errors.card_number}
required
/>
<FormInput
type="select"
label={t('Card expiry month', 'Kart Möhleti (aý)')}
value={form.card_expiry_month}
onChange={setField('card_expiry_month')}
options={MONTH_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.card_expiry_month}
required
/>
<FormInput
type="select"
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
value={form.card_expiry_year}
onChange={setField('card_expiry_year')}
options={YEAR_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.card_expiry_year}
required
/>
</div>
</div>
{/* ── Lokasiýa ── */}
<SectionTitle>{t('Location', 'Lokasiýa')}</SectionTitle>
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="select"
label={t('Province', 'Welaýat')}
value={form.province_id}
onChange={setField('province_id')}
options={PROVINCE_OPTIONS}
placeholder={t('Ashgabat', 'Aşgabat')}
error={errors.province_id}
required
/>
<FormInput
type="searchable-select"
label={t('Branch', 'Şahamça')}
value={form.branch_id}
onChange={setField('branch_id')}
options={branchOptions}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.branch_id}
disabled={!form.province_id}
required
/>
</div>
</div>
{/* ── Şahsy maglumatlar ── */}
<SectionTitle>{t('Personal information', 'Şahsy maglumatlar')}</SectionTitle>
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<FormInput
type="text"
label={t('First name', 'Ady')}
value={form.first_name}
onChange={setField('first_name')}
placeholder={t('First name', 'Ady')}
error={errors.first_name}
required
/>
<FormInput
type="text"
label={t('Last name', 'Familiýasy')}
value={form.last_name}
onChange={setField('last_name')}
placeholder={t('Last name', 'Familiýasy')}
error={errors.last_name}
required
/>
<FormInput
type="text"
label={t("Father's name", 'Atasynyň ady')}
value={form.middle_name}
onChange={setField('middle_name')}
placeholder={t("Father's name", 'Atasynyň ady')}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
<FormInput
type="date"
label={t('Birth date', 'Doglan güni')}
value={form.birth_date}
onChange={setField('birth_date')}
error={errors.birth_date}
required
/>
<FormInput
type="phone"
label={t('Phone', 'Telefon')}
value={form.phone}
onChange={setField('phone')}
placeholder="63 21 87 04"
error={errors.phone}
required
/>
</div>
</div>
{/* ── Pasport ── */}
<SectionTitle>{t('Passport', 'Pasport')}</SectionTitle>
<div className="rounded-lg border border-border bg-card p-6 space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('Passport series', 'Pasport seriýasy')}
value={form.passport_series}
onChange={setField('passport_series')}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t('Select', 'Saýlamak üçin basyň')}
error={errors.passport_series}
required
/>
<FormInput
type="text"
label={t('Passport number', 'Pasport belgisi')}
value={form.passport_number}
onChange={setField('passport_number')}
placeholder={t('Passport number', 'Pasport belgisi')}
error={errors.passport_number}
required
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormInput
type="file"
label={t('Passport (page 1)', 'Pasport (sahypa 1)')}
accept="image/*,.pdf"
fileValue={files.passport_page1}
onFileChange={setFile('passport_page1')}
error={errors.passport_page1}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('Passport (pages 2-3)', 'Pasport (2-3-nji sahypa)')}
accept="image/*,.pdf"
fileValue={files.passport_page2_3}
onFileChange={setFile('passport_page2_3')}
error={errors.passport_page2_3}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('Passport (pages 8-9)', 'Pasport (8-9 sahypa)')}
accept="image/*,.pdf"
fileValue={files.passport_page8_9}
onFileChange={setFile('passport_page8_9')}
error={errors.passport_page8_9}
required={mode === 'create'}
/>
<FormInput
type="file"
label={t('Passport (page 32)', 'Pasport (32-nji sahypa)')}
accept="image/*,.pdf"
fileValue={files.passport_page32}
onFileChange={setFile('passport_page32')}
error={errors.passport_page32}
required={mode === 'create'}
/>
</div>
</div>
{/* ── Actions ── */}
<div className="flex justify-end gap-3 mt-6">
<Button variant="ghost" onClick={handleCancel} disabled={isPending}>
{t('Cancel', 'Ýatyr')}
</Button>
<Button onClick={handleSubmit} disabled={isPending}>
{isPending
? t('Saving...', 'Saklanýar...')
: mode === 'create'
? t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň')
: t('Save changes', 'Üýtgetmeleri sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,108 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
cardRequisitesApi,
type CardRequisiteListParams,
type CreateCardRequisitePayload,
type UpdateCardRequisitePayload,
} from '../api/cardRequisitesApi'
const QUERY_KEY = 'card-requisites'
// ─── List ─────────────────────────────────────────────────────────────────────
export function useCardRequisites(params?: CardRequisiteListParams) {
return useQuery({
queryKey: [QUERY_KEY, params],
queryFn: () => cardRequisitesApi.getAll(params),
})
}
// ─── Single ───────────────────────────────────────────────────────────────────
export function useCardRequisite(id: string) {
return useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => cardRequisitesApi.getById(id),
enabled: !!id,
})
}
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardRequisite() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CreateCardRequisitePayload) => cardRequisitesApi.create(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card requisite created successfully', 'Kart rekwiziti üstünlikli döredildi'))
},
onError: () => {
toast.error(t('Failed to create card requisite', 'Kart rekwiziti döredilmedi'))
},
})
}
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardRequisite(id: string) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: UpdateCardRequisitePayload) => cardRequisitesApi.update(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card requisite updated successfully', 'Kart rekwiziti üstünlikli üýtgedildi'))
},
onError: () => {
toast.error(t('Failed to update card requisite', 'Kart rekwiziti üýtgedilmedi'))
},
})
}
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardRequisite() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: string) => cardRequisitesApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card requisite deleted successfully', 'Kart rekwiziti üstünlikli öçürildi'))
},
onError: () => {
toast.error(t('Failed to delete card requisite', 'Kart rekwiziti öçürilmedi'))
},
})
}
// ─── Download ─────────────────────────────────────────────────────────────────
export function useDownloadCardRequisite() {
const { t } = useTranslation()
return useMutation({
mutationFn: async (id: string) => {
const blob = await cardRequisitesApi.download(id)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `card-requisite-${id}.pdf`
a.click()
URL.revokeObjectURL(url)
},
onSuccess: () => {
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
},
onError: () => {
toast.error(t('Download failed', 'Ýüklemek başartmady'))
},
})
}

View File

@@ -0,0 +1,120 @@
import {apiClient} from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export interface CardTransaction {
id: number
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export interface CardTransactionListResponse {
data: CardTransaction[]
total: number
page: number
per_page: number
}
export interface CreateCardTransactionPayload {
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
export type UpdateCardTransactionPayload = CreateCardTransactionPayload
export interface CardTransactionListParams {
page?: number
per_page?: number
search?: string
}
// ─── API functions ────────────────────────────────────────────────────────────
const MOCK_CARD_TRANSACTIONS: CardTransaction[] = [
{
id: 1,
passport_series: 'AA',
passport_number: '1234567',
card_number: '8600123456789012',
card_expiry_month: '12',
card_expiry_year: '28',
},
{
id: 2,
passport_series: 'AB',
passport_number: '7654321',
card_number: '9860123456789012',
card_expiry_month: '05',
card_expiry_year: '27',
},
{
id: 3,
passport_series: 'AC',
passport_number: '1122334',
card_number: '4400123456789012',
card_expiry_month: '08',
card_expiry_year: '26',
},
{
id: 4,
passport_series: 'KA',
passport_number: '9988776',
card_number: '5300123456789012',
card_expiry_month: '01',
card_expiry_year: '30',
},
{
id: 5,
passport_series: 'KB',
passport_number: '5566778',
card_number: '6200123456789012',
card_expiry_month: '03',
card_expiry_year: '29',
},
]
export const cardTransactionsApi = {
getAll: async (params?: CardTransactionListParams): Promise<CardTransactionListResponse> => {
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
return { data: MOCK_CARD_TRANSACTIONS, total: MOCK_CARD_TRANSACTIONS.length, page: params?.page || 1, per_page: params?.per_page || 10 }
const { data } = await apiClient.get('/card-transactions', { params })
return data
},
getById: async (id: number): Promise<CardTransaction> => {
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
const mock = MOCK_CARD_TRANSACTIONS.find(t => t.id === id)
if (mock) return mock
const { data } = await apiClient.get(`/card-transactions/${id}`)
return data
},
create: async (payload: CreateCardTransactionPayload): Promise<CardTransaction> => {
const { data } = await apiClient.post('/card-transactions', payload)
return data
},
update: async (id: number, payload: UpdateCardTransactionPayload): Promise<CardTransaction> => {
const { data } = await apiClient.put(`/card-transactions/${id}`, payload)
return data
},
delete: async (id: number): Promise<void> => {
await apiClient.delete(`/card-transactions/${id}`)
},
download: async (id: number): Promise<Blob> => {
const { data } = await apiClient.get(`/card-transactions/${id}/download`, {
responseType: 'blob',
})
return data
},
}

View File

@@ -0,0 +1,218 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { FormInput } from '@/components/formInput'
import type { CardTransaction } from '../api/cardTransactionsApi'
import { useCreateCardTransaction, useUpdateCardTransaction } from '../hooks/useCardTransactions'
// ─── Types ────────────────────────────────────────────────────────────────────
interface CardTransactionFormProps {
mode: 'create' | 'edit'
initialData?: CardTransaction
cardTransactionId?: number
}
interface FormState {
passport_series: string
passport_number: string
card_number: string
card_expiry_month: string
card_expiry_year: string
}
interface FormErrors {
passport_series?: string
passport_number?: string
card_number?: string
card_expiry_month?: string
card_expiry_year?: string
}
// ─── Constants ────────────────────────────────────────────────────────────────
const PASSPORT_SERIES_OPTIONS = [
{ value: 'I-LB', label: 'I-LB' },
{ value: 'II-LB', label: 'II-LB' },
{ value: 'III-LB', label: 'III-LB' },
{ value: 'A', label: 'A' },
{ value: 'B', label: 'B' },
]
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
const val = String(i + 1).padStart(2, '0')
return { value: val, label: val }
})
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
const year = String(new Date().getFullYear() + i)
return { value: year, label: year }
})
const EMPTY_FORM: FormState = {
passport_series: '',
passport_number: '',
card_number: '',
card_expiry_month: '',
card_expiry_year: '',
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState, t: (k: string, fallback: string) => string): FormErrors {
const errors: FormErrors = {}
if (!form.passport_series)
errors.passport_series = t('Passport series is required', 'Pasport seriýasy hökmanydyr')
if (!form.passport_number)
errors.passport_number = t('Passport number is required', 'Pasport belgisi hökmanydyr')
if (!form.card_number)
errors.card_number = t('Card number is required', 'Kart belgisi hökmanydyr')
if (!form.card_expiry_month)
errors.card_expiry_month = t('Expiry month is required', 'Möhleti (aý) hökmanydyr')
if (!form.card_expiry_year)
errors.card_expiry_year = t('Expiry year is required', 'Möhleti (ýyl) hökmanydyr')
return errors
}
// ─── Component ────────────────────────────────────────────────────────────────
export function CardTransactionForm({
mode,
initialData,
cardTransactionId,
}: CardTransactionFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(EMPTY_FORM)
const [errors, setErrors] = useState<FormErrors>({})
const createMutation = useCreateCardTransaction()
const updateMutation = useUpdateCardTransaction(cardTransactionId ?? 0)
const isPending = createMutation.isPending || updateMutation.isPending
// Populate form when editing
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
passport_series: initialData.passport_series,
passport_number: initialData.passport_number,
card_number: initialData.card_number,
card_expiry_month: initialData.card_expiry_month,
card_expiry_year: initialData.card_expiry_year,
})
}
}, [mode, initialData])
const setField = (field: keyof FormState) => (value: string) => {
setForm((prev) => ({ ...prev, [field]: value }))
if (errors[field]) setErrors((prev) => ({ ...prev, [field]: undefined }))
}
const handleSubmit = async () => {
const validationErrors = validate(form, t)
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors)
return
}
if (mode === 'create') {
await createMutation.mutateAsync(form)
navigate('/card-transactions')
} else {
await updateMutation.mutateAsync(form)
navigate(`/card-transactions/${cardTransactionId}`)
}
}
const handleCancel = () => {
if (mode === 'create') {
navigate('/card-transactions')
} else {
navigate(`/card-transactions/${cardTransactionId}`)
}
}
return (
<div className="rounded-lg border border-border bg-card p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Passport Series */}
<FormInput
type="searchable-select"
label={t('Passport series', 'Pasport seriýasy')}
value={form.passport_series}
onChange={setField('passport_series')}
options={PASSPORT_SERIES_OPTIONS}
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
error={errors.passport_series}
required
/>
{/* Passport Number */}
<FormInput
type="text"
label={t('Passport number', 'Pasport belgisi')}
value={form.passport_number}
onChange={setField('passport_number')}
placeholder={t('Passport number', 'Pasport belgisi')}
error={errors.passport_number}
required
/>
{/* Card Number */}
<FormInput
type="text"
label={t('Card number', 'Kart belgisi')}
value={form.card_number}
onChange={setField('card_number')}
placeholder={t('Card number', 'Kart belgisi')}
error={errors.card_number}
required
/>
{/* Expiry Month + Year side by side */}
<div className="grid grid-cols-2 gap-3">
<FormInput
type="select"
label={t('Card expiry month', 'Kart Möhleti (aý)')}
value={form.card_expiry_month}
onChange={setField('card_expiry_month')}
options={MONTH_OPTIONS}
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
error={errors.card_expiry_month}
required
/>
<FormInput
type="select"
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
value={form.card_expiry_year}
onChange={setField('card_expiry_year')}
options={YEAR_OPTIONS}
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
error={errors.card_expiry_year}
required
/>
</div>
</div>
{/* Actions */}
<div className="flex justify-end gap-3 mt-6">
<Button variant="ghost" onClick={handleCancel} disabled={isPending}>
{t('Cancel', 'Ýatyr')}
</Button>
<Button onClick={handleSubmit} disabled={isPending}>
{isPending
? t('Saving...', 'Saklanýar...')
: mode === 'create'
? t('Create card transaction', 'Kart herekedi dörediň')
: t('Save changes', 'Üýtgetmeleri sakla')}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,110 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
cardTransactionsApi,
type CardTransactionListParams,
type CreateCardTransactionPayload,
type UpdateCardTransactionPayload,
} from '../api/cardTransactionsApi'
const QUERY_KEY = 'card-transactions'
// ─── List ─────────────────────────────────────────────────────────────────────
export function useCardTransactions(params?: CardTransactionListParams) {
return useQuery({
queryKey: [QUERY_KEY, params],
queryFn: () => cardTransactionsApi.getAll(params),
})
}
// ─── Single ───────────────────────────────────────────────────────────────────
export function useCardTransaction(id: number) {
return useQuery({
queryKey: [QUERY_KEY, id],
queryFn: () => cardTransactionsApi.getById(id),
enabled: !!id,
})
}
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardTransaction() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: CreateCardTransactionPayload) =>
cardTransactionsApi.create(payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card transaction created successfully', 'Kart herekedi üstünlikli döredildi'))
},
onError: () => {
toast.error(t('Failed to create card transaction', 'Kart herekedi döredilmedi'))
},
})
}
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardTransaction(id: number) {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: UpdateCardTransactionPayload) =>
cardTransactionsApi.update(id, payload),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card transaction updated successfully', 'Kart herekedi üstünlikli üýtgedildi'))
},
onError: () => {
toast.error(t('Failed to update card transaction', 'Kart herekedi üýtgedilmedi'))
},
})
}
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardTransaction() {
const queryClient = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: number) => cardTransactionsApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
toast.success(t('Card transaction deleted successfully', 'Kart herekedi üstünlikli öçürildi'))
},
onError: () => {
toast.error(t('Failed to delete card transaction', 'Kart herekedi öçürilmedi'))
},
})
}
// ─── Download ─────────────────────────────────────────────────────────────────
export function useDownloadCardTransaction() {
const { t } = useTranslation()
return useMutation({
mutationFn: async (id: number) => {
const blob = await cardTransactionsApi.download(id)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `card-transaction-${id}.pdf`
a.click()
URL.revokeObjectURL(url)
},
onSuccess: () => {
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
},
onError: () => {
toast.error(t('Download failed', 'Ýüklemek başartmady'))
},
})
}

View File

@@ -0,0 +1,425 @@
// ─── Enums / Unions ───────────────────────────────────────────────────────────
export type CardOrderStatus = 'PENDING' | 'APPROVED' | 'REJECTED'
export type CardOrderSortField =
| 'id'
| 'createdAt'
| 'status'
| 'welayat'
| 'sahamca'
// ─── Lookup entities ──────────────────────────────────────────────────────────
export interface CardIssuanceReason {
id: number
name: string
}
export interface CardType {
id: number
name: string
}
export interface Province {
id: number
name: string
}
export interface Branch {
id: number
name: string
provinceId: number
}
// ─── Passport ────────────────────────────────────────────────────────────────
export interface PassportFiles {
page1: string | null // URL
page23: string | null
page89: string | null
page32: string | null
}
// ─── Card Order ───────────────────────────────────────────────────────────────
export interface CardOrder {
id: string
createdAt: string // ISO datetime string
isPaid: boolean
status: CardOrderStatus
note: string | null
createdBy: string // user display name
// Card
issuanceReasonId: number
issuanceReasonName: string
cardTypeId: number
cardTypeName: string
// Location
provinceId: number
provinceName: string
branchId: number
branchName: string
// Personal info
firstName: string
lastName: string
middleName: string | null
formerLastName: string | null
birthDate: string // yyyy-MM-dd
phone: string
phoneExtra: string | null
citizenship: string
registeredAddress: string
currentAddress: string
workplace: string
// Passport
passportSeriesId: number
passportSeriesName: string
passportNumber: string
passportIssueDate: string // yyyy-MM-dd
passportIssuedBy: string
passportBirthPlace: string
passportFiles: PassportFiles
}
// ─── List item (lighter shape for table rows) ─────────────────────────────────
export interface CardOrderListItem {
id: string
createdAt: string
issuanceReasonName: string
cardTypeName: string
provinceName: string
branchName: string
firstName: string
lastName: string
status: CardOrderStatus
}
// ─── Pagination ───────────────────────────────────────────────────────────────
export interface PaginatedResponse<T> {
data: T[]
totalCount: number
page: number
perPage: number
totalPages: number
}
// ─── API Payloads ─────────────────────────────────────────────────────────────
export interface CardOrderFilters {
search?: string
status?: CardOrderStatus | ''
provinceId?: number | ''
branchId?: number | ''
page?: number
perPage?: number
}
export interface CreateCardOrderPayload {
isPaid: boolean
status: CardOrderStatus
note: string | null
issuanceReasonId: number
cardTypeId: number
provinceId: number
branchId: number
firstName: string
lastName: string
middleName: string | null
formerLastName: string | null
birthDate: string
phone: string
phoneExtra: string | null
citizenship: string
registeredAddress: string
currentAddress: string
workplace: string
passportSeriesId: number
passportNumber: string
passportIssueDate: string
passportIssuedBy: string
passportBirthPlace: string
passportPage1: File
passportPage23: File
passportPage89: File
passportPage32: File
}
export interface UpdateCardOrderPayload extends Partial<CreateCardOrderPayload> {}
import {apiClient} from '@/lib/api/client'
// ─── Mock Data ────────────────────────────────────────────────────────────────
const USE_MOCK = true
const MOCK_REASONS: CardIssuanceReason[] = [
{ id: 1, name: 'Möhleti gutardy' },
{ id: 2, name: 'Täze kart açmak' },
{ id: 3, name: 'Kartyň ýitmegi' },
{ id: 4, name: 'Adyň üýtgemegi' },
]
const MOCK_TYPES: CardType[] = [
{ id: 1, name: 'Altyn Asyr' },
{ id: 2, name: 'Maşgala' },
{ id: 3, name: 'Goýum' },
{ id: 4, name: 'Milli' },
]
const MOCK_PROVINCES: Province[] = [
{ id: 1, name: 'Aşgabat ş.' },
{ id: 2, name: 'Ahal' },
{ id: 3, name: 'Balkan' },
{ id: 4, name: 'Daşoguz' },
{ id: 5, name: 'Lebap' },
{ id: 6, name: 'Mary' },
]
const MOCK_BRANCHES: Branch[] = [
{ id: 1, name: 'Aşgabat Baş şahamça', provinceId: 1 },
{ id: 2, name: 'Köpetdag şahamçasy', provinceId: 1 },
{ id: 3, name: 'Abadan şahamçasy', provinceId: 2 },
{ id: 4, name: 'Balkanabat şahamçasy', provinceId: 3 },
{ id: 5, name: 'Mary şahamçasy', provinceId: 6 },
]
const MOCK_ORDERS: CardOrder[] = [
{
id: 'CRD-10254',
createdAt: '2026-05-01T10:00:00Z',
isPaid: true,
status: 'APPROVED',
note: 'Hemme zat ýerinde',
createdBy: 'Jumaýew Aman',
issuanceReasonId: 2,
issuanceReasonName: 'Täze kart açmak',
cardTypeId: 1,
cardTypeName: 'Altyn Asyr',
provinceId: 1,
provinceName: 'Aşgabat ş.',
branchId: 1,
branchName: 'Aşgabat Baş şahamça',
firstName: 'Berdi',
lastName: 'Myradow',
middleName: 'Gurbanowiç',
formerLastName: null,
birthDate: '1995-04-12',
phone: '+99365123456',
phoneExtra: null,
citizenship: 'Türkmenistan',
registeredAddress: 'Aşgabat, Magtymguly şaýoly 12',
currentAddress: 'Aşgabat, Magtymguly şaýoly 12',
workplace: 'TDB, IT hünärmen',
passportSeriesId: 1,
passportSeriesName: 'I-AS',
passportNumber: '123456',
passportIssueDate: '2015-05-20',
passportIssuedBy: 'Aşgabat ş. Polisiýa müdirligi',
passportBirthPlace: 'Aşgabat',
passportFiles: {
page1: 'https://placehold.co/600x400?text=Passport+P1',
page23: 'https://placehold.co/600x400?text=Passport+P23',
page89: 'https://placehold.co/600x400?text=Passport+P89',
page32: 'https://placehold.co/600x400?text=Passport+P32',
},
},
{
id: 'CRD-10255',
createdAt: '2026-05-02T14:30:00Z',
isPaid: false,
status: 'PENDING',
note: null,
createdBy: 'Saparow Batyr',
issuanceReasonId: 1,
issuanceReasonName: 'Möhleti gutardy',
cardTypeId: 2,
cardTypeName: 'Maşgala',
provinceId: 6,
provinceName: 'Mary',
branchId: 5,
branchName: 'Mary şahamçasy',
firstName: 'Gyzylgül',
lastName: 'Annageldiýewa',
middleName: 'Begliýewna',
formerLastName: 'Saparowa',
birthDate: '1998-08-25',
phone: '+99361987654',
phoneExtra: '+99312444234',
citizenship: 'Türkmenistan',
registeredAddress: 'Mary ş., Gurbansoltan eje köç. 45',
currentAddress: 'Mary ş., Gurbansoltan eje köç. 45',
workplace: 'Mekdep müdiri',
passportSeriesId: 2,
passportSeriesName: 'I-MR',
passportNumber: '654321',
passportIssueDate: '2018-10-10',
passportIssuedBy: 'Mary w. Polisiýa müdirligi',
passportBirthPlace: 'Mary',
passportFiles: {
page1: 'https://placehold.co/600x400?text=Passport+P1',
page23: 'https://placehold.co/600x400?text=Passport+P23',
page89: 'https://placehold.co/600x400?text=Passport+P89',
page32: 'https://placehold.co/600x400?text=Passport+P32',
},
},
]
// ─── Card Orders CRUD ─────────────────────────────────────────────────────────
export async function fetchCardOrders(
filters: CardOrderFilters,
): Promise<PaginatedResponse<CardOrderListItem>> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 500))
const list: CardOrderListItem[] = MOCK_ORDERS.map((o) => ({
id: o.id,
createdAt: o.createdAt,
issuanceReasonName: o.issuanceReasonName,
cardTypeName: o.cardTypeName,
provinceName: o.provinceName,
branchName: o.branchName,
firstName: o.firstName,
lastName: o.lastName,
status: o.status,
}))
return {
data: list,
totalCount: list.length,
page: filters.page ?? 1,
perPage: filters.perPage ?? 25,
totalPages: 1,
}
}
const params = new URLSearchParams()
if (filters.search) params.set('search', filters.search)
if (filters.status) params.set('status', filters.status)
if (filters.provinceId) params.set('provinceId', String(filters.provinceId))
if (filters.branchId) params.set('branchId', String(filters.branchId))
params.set('page', String(filters.page ?? 1))
params.set('perPage', String(filters.perPage ?? 25))
const { data } = await apiClient.get<PaginatedResponse<CardOrderListItem>>(
`/card-orders?${params.toString()}`,
)
return data
}
export async function fetchCardOrderById(id: string): Promise<CardOrder> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 500))
const order = MOCK_ORDERS.find((o) => o.id === id) || MOCK_ORDERS[0]
return { ...order, id }
}
const { data } = await apiClient.get<CardOrder>(`/card-orders/${id}`)
return data
}
export async function createCardOrder(
payload: CreateCardOrderPayload,
): Promise<CardOrder> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 1000))
return { ...MOCK_ORDERS[0], id: `CRD-${Math.floor(Math.random() * 10000)}` }
}
const formData = buildFormData(payload)
const { data } = await apiClient.post<CardOrder>('/card-orders', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
return data
}
export async function updateCardOrder(
id: string,
payload: UpdateCardOrderPayload,
): Promise<CardOrder> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 1000))
return { ...MOCK_ORDERS[0], id }
}
const formData = buildFormData(payload)
const { data } = await apiClient.put<CardOrder>(`/card-orders/${id}`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
return data
}
export async function deleteCardOrder(id: string): Promise<void> {
if (USE_MOCK) {
await new Promise((r) => setTimeout(r, 500))
return
}
await apiClient.delete(`/card-orders/${id}`)
}
// ─── Lookup lists ─────────────────────────────────────────────────────────────
export async function fetchCardIssuanceReasons(): Promise<CardIssuanceReason[]> {
if (USE_MOCK) return MOCK_REASONS
const { data } = await apiClient.get<CardIssuanceReason[]>('/settings/card/reasons')
return data
}
export async function fetchCardTypes(): Promise<CardType[]> {
if (USE_MOCK) return MOCK_TYPES
const { data } = await apiClient.get<CardType[]>('/settings/card/types')
return data
}
export async function fetchProvinces(): Promise<Province[]> {
if (USE_MOCK) return MOCK_PROVINCES
const { data } = await apiClient.get<Province[]>('/settings/location/districts')
return data
}
export async function fetchBranches(provinceId?: number): Promise<Branch[]> {
if (USE_MOCK) {
if (!provinceId) return MOCK_BRANCHES
return MOCK_BRANCHES.filter((b) => b.provinceId === provinceId)
}
const params = provinceId ? `?provinceId=${provinceId}` : ''
const { data } = await apiClient.get<Branch[]>(`/settings/location/branches${params}`)
return data
}
// ─── Helper ───────────────────────────────────────────────────────────────────
function buildFormData(
payload: CreateCardOrderPayload | UpdateCardOrderPayload,
): FormData {
const fd = new FormData()
const fileKeys = new Set([
'passportPage1',
'passportPage23',
'passportPage89',
'passportPage32',
])
for (const [key, value] of Object.entries(payload)) {
if (value === undefined) continue
if (fileKeys.has(key) && value instanceof File) {
fd.append(key, value)
} else if (value === null) {
fd.append(key, '')
} else {
fd.append(key, String(value))
}
}
return fd
}

View File

@@ -0,0 +1,619 @@
import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import type { SelectOption } from '@/components/formInput'
import type {
CardOrder,
CardOrderStatus,
CreateCardOrderPayload,
} from '../api/orderNewCardApi'
import {
useCardIssuanceReasons,
useCardTypes,
useProvinces,
useBranches,
useCreateCardOrder,
useUpdateCardOrder,
} from '../hooks/useOrderNewCard'
// ─── Types ────────────────────────────────────────────────────────────────────
interface CardOrderFormProps {
mode: 'create' | 'edit'
initialData?: CardOrder
cardOrderId?: string
onSuccess?: () => void
onCancel?: () => void
}
interface FormState {
isPaid: boolean
status: CardOrderStatus | ''
note: string
issuanceReasonId: string
cardTypeId: string
provinceId: string
branchId: string
firstName: string
lastName: string
middleName: string
formerLastName: string
birthDate: string
phone: string
phoneExtra: string
citizenship: string
registeredAddress: string
currentAddress: string
workplace: string
passportSeriesId: string
passportNumber: string
passportIssueDate: string
passportIssuedBy: string
passportBirthPlace: string
passportPage1: File | null
passportPage23: File | null
passportPage89: File | null
passportPage32: File | null
termsAccepted: boolean
}
type FormErrors = Partial<Record<keyof FormState, string>>
// ─── Initial state ────────────────────────────────────────────────────────────
function getInitialState(data?: CardOrder): FormState {
return {
isPaid: data?.isPaid ?? false,
status: data?.status ?? '',
note: data?.note ?? '',
issuanceReasonId: data?.issuanceReasonId ? String(data.issuanceReasonId) : '',
cardTypeId: data?.cardTypeId ? String(data.cardTypeId) : '',
provinceId: data?.provinceId ? String(data.provinceId) : '',
branchId: data?.branchId ? String(data.branchId) : '',
firstName: data?.firstName ?? '',
lastName: data?.lastName ?? '',
middleName: data?.middleName ?? '',
formerLastName: data?.formerLastName ?? '',
birthDate: data?.birthDate ?? '',
phone: data?.phone ?? '',
phoneExtra: data?.phoneExtra ?? '',
citizenship: data?.citizenship ?? 'Turkmenistan',
registeredAddress: data?.registeredAddress ?? '',
currentAddress: data?.currentAddress ?? '',
workplace: data?.workplace ?? '',
passportSeriesId: data?.passportSeriesId ? String(data.passportSeriesId) : '',
passportNumber: data?.passportNumber ?? '',
passportIssueDate: data?.passportIssueDate ?? '',
passportIssuedBy: data?.passportIssuedBy ?? '',
passportBirthPlace:data?.passportBirthPlace?? '',
passportPage1: null,
passportPage23: null,
passportPage89: null,
passportPage32: null,
termsAccepted: false,
}
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState, mode: 'create' | 'edit', t: (k: string, fb: string) => string): FormErrors {
const errors: FormErrors = {}
const req = (field: keyof FormState, msg: string) => {
const v = form[field]
if (!v || (typeof v === 'string' && !v.trim())) errors[field] = msg
}
req('status', t('validation.required', 'Bu meýdan hökmanydyr'))
req('issuanceReasonId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('cardTypeId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('provinceId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('branchId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('firstName', t('validation.required', 'Bu meýdan hökmanydyr'))
req('lastName', t('validation.required', 'Bu meýdan hökmanydyr'))
req('birthDate', t('validation.required', 'Bu meýdan hökmanydyr'))
req('phone', t('validation.required', 'Bu meýdan hökmanydyr'))
req('citizenship', t('validation.required', 'Bu meýdan hökmanydyr'))
req('registeredAddress', t('validation.required', 'Bu meýdan hökmanydyr'))
req('currentAddress', t('validation.required', 'Bu meýdan hökmanydyr'))
req('workplace', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportSeriesId', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportNumber', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportIssueDate', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportIssuedBy', t('validation.required', 'Bu meýdan hökmanydyr'))
req('passportBirthPlace',t('validation.required', 'Bu meýdan hökmanydyr'))
if (mode === 'create') {
if (!form.passportPage1) errors.passportPage1 = t('validation.required', 'Bu meýdan hökmanydyr')
if (!form.passportPage23) errors.passportPage23 = t('validation.required', 'Bu meýdan hökmanydyr')
if (!form.passportPage89) errors.passportPage89 = t('validation.required', 'Bu meýdan hökmanydyr')
if (!form.passportPage32) errors.passportPage32 = t('validation.required', 'Bu meýdan hökmanydyr')
if (!form.termsAccepted) errors.termsAccepted = t('validation.terms', 'Şertnama bilen razylaşmaly')
}
return errors
}
// ─── Section wrapper ──────────────────────────────────────────────────────────
function FormSection({ title, children }: { title?: string; children: React.ReactNode }) {
return (
<div className="mb-6">
{title && (
<h3 className="text-base font-semibold text-foreground mb-3">{title}</h3>
)}
<div className="bg-card border border-border rounded-xl p-5 space-y-4">
{children}
</div>
</div>
)
}
// ─── CardOrderForm ────────────────────────────────────────────────────────────
export function CardOrderForm({
mode,
initialData,
cardOrderId,
onSuccess,
onCancel,
}: CardOrderFormProps) {
const { t } = useTranslation()
const isEdit = mode === 'edit'
const [form, setForm] = useState<FormState>(() => getInitialState(initialData))
const [errors, setErrors] = useState<FormErrors>({})
const [touched, setTouched] = useState(false)
// Reset form when initialData loads (edit mode)
useEffect(() => {
if (initialData) setForm(getInitialState(initialData))
}, [initialData])
// Lookup data
const { data: reasons = [] } = useCardIssuanceReasons()
const { data: cardTypes = [] } = useCardTypes()
const { data: provinces = [] } = useProvinces()
const { data: branches = [] } = useBranches(
form.provinceId ? Number(form.provinceId) : undefined,
)
// Mutations
const createMutation = useCreateCardOrder()
const updateMutation = useUpdateCardOrder(cardOrderId ?? '')
const isPending = createMutation.isPending || updateMutation.isPending
// Helpers
const set = (key: keyof FormState) => (value: string) =>
setForm((f) => ({ ...f, [key]: value }))
const setFile = (key: keyof FormState) => (file: File | null) =>
setForm((f) => ({ ...f, [key]: file }))
const toOptions = (arr: { id: number; name: string }[]): SelectOption[] =>
arr.map((x) => ({ value: String(x.id), label: x.name }))
// Validate on every change if user has already submitted once
useEffect(() => {
if (touched) setErrors(validate(form, mode, t))
}, [form, touched, mode])
// ── Submit ─────────────────────────────────────────────────────────────────
const handleSubmit = async () => {
setTouched(true)
const errs = validate(form, mode, t)
if (Object.keys(errs).length > 0) {
setErrors(errs)
return
}
const payload = {
isPaid: form.isPaid,
status: form.status as CardOrderStatus,
note: form.note || null,
issuanceReasonId: Number(form.issuanceReasonId),
cardTypeId: Number(form.cardTypeId),
provinceId: Number(form.provinceId),
branchId: Number(form.branchId),
firstName: form.firstName,
lastName: form.lastName,
middleName: form.middleName || null,
formerLastName: form.formerLastName || null,
birthDate: form.birthDate,
phone: form.phone,
phoneExtra: form.phoneExtra || null,
citizenship: form.citizenship,
registeredAddress: form.registeredAddress,
currentAddress: form.currentAddress,
workplace: form.workplace,
passportSeriesId: Number(form.passportSeriesId),
passportNumber: form.passportNumber,
passportIssueDate: form.passportIssueDate,
passportIssuedBy: form.passportIssuedBy,
passportBirthPlace: form.passportBirthPlace,
...(form.passportPage1 && { passportPage1: form.passportPage1 }),
...(form.passportPage23 && { passportPage23: form.passportPage23 }),
...(form.passportPage89 && { passportPage89: form.passportPage89 }),
...(form.passportPage32 && { passportPage32: form.passportPage32 }),
}
try {
if (isEdit) {
await updateMutation.mutateAsync(payload)
} else {
await createMutation.mutateAsync(payload as CreateCardOrderPayload)
}
onSuccess?.()
} catch {
// errors handled in hooks via toast
}
}
// ── Status options ─────────────────────────────────────────────────────────
const statusOptions: SelectOption[] = [
{ value: 'PENDING', label: t('cardOrder.status.pending', 'Garaşylýar') },
{ value: 'APPROVED', label: t('cardOrder.status.approved', 'Tassyklandy') },
{ value: 'REJECTED', label: t('cardOrder.status.rejected', 'Ýatyryldy') },
]
const citizenshipOptions: SelectOption[] = [
{ value: 'Turkmenistan', label: t('citizenship.tm', 'Turkmenistan') },
{ value: 'Russia', label: t('citizenship.ru', 'Russiýa') },
{ value: 'Other', label: t('citizenship.other', 'Beýlekiler') },
]
// ── Render ────────────────────────────────────────────────────────────────
return (
<div>
{/* ── Status section ── */}
<FormSection>
<div className="flex items-center gap-2 mb-1">
<input
id="isPaid"
type="checkbox"
checked={form.isPaid}
onChange={(e) => setForm((f) => ({ ...f, isPaid: e.target.checked }))}
className="w-4 h-4 accent-primary cursor-pointer"
/>
<label
htmlFor="isPaid"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider cursor-pointer select-none"
>
{t('cardOrder.field.isPaid', 'Tölenen')}
</label>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="select"
label={t('cardOrder.field.status', 'Status')}
required
value={form.status}
onChange={set('status')}
options={statusOptions}
placeholder={t('common.selectPlaceholder', 'Saýlamak üçin basyň')}
error={errors.status}
/>
<FormInput
type="textarea"
label={t('cardOrder.field.note', 'Bellik')}
value={form.note}
onChange={set('note')}
placeholder={t('cardOrder.field.note', 'Bellik')}
rows={2}
/>
</div>
</FormSection>
{/* ── Kart ── */}
<FormSection title={t('cardOrder.section.card', 'Kart')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('cardOrder.field.issuanceReason', 'Kartyň çykarylmagynyň sebäbi')}
required
value={form.issuanceReasonId}
onChange={set('issuanceReasonId')}
options={toOptions(reasons)}
error={errors.issuanceReasonId}
/>
<FormInput
type="searchable-select"
label={t('cardOrder.field.cardType', 'Kart görnüşi')}
required
value={form.cardTypeId}
onChange={set('cardTypeId')}
options={toOptions(cardTypes)}
error={errors.cardTypeId}
/>
</div>
</FormSection>
{/* ── Lokasiýa ── */}
<FormSection title={t('cardOrder.section.location', 'Lokasiýa')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="select"
label={t('cardOrder.field.province', 'Welaýat')}
required
value={form.provinceId}
onChange={(v) => {
setForm((f) => ({ ...f, provinceId: v, branchId: '' }))
}}
options={toOptions(provinces)}
error={errors.provinceId}
/>
<FormInput
type="searchable-select"
label={t('cardOrder.field.branch', 'Şahamça')}
required
value={form.branchId}
onChange={set('branchId')}
options={toOptions(branches)}
disabled={!form.provinceId}
error={errors.branchId}
/>
</div>
</FormSection>
{/* ── Şahsy maglumatlar ── */}
<FormSection title={t('cardOrder.section.personal', 'Şahsy maglumatlar')}>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
label={t('cardOrder.field.firstName', 'Ady')}
required
value={form.firstName}
onChange={set('firstName')}
placeholder={t('cardOrder.field.firstName', 'Ady')}
error={errors.firstName}
/>
<FormInput
label={t('cardOrder.field.lastName', 'Familiýasy')}
required
value={form.lastName}
onChange={set('lastName')}
placeholder={t('cardOrder.field.lastName', 'Familiýasy')}
error={errors.lastName}
/>
<FormInput
label={t('cardOrder.field.middleName', 'Atasynyn ady')}
value={form.middleName}
onChange={set('middleName')}
placeholder={t('cardOrder.field.middleName', 'Atasynyn ady')}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
label={t('cardOrder.field.formerLastName', 'Köne familiýaňyz (eger üýtgän bolsa)')}
value={form.formerLastName}
onChange={set('formerLastName')}
placeholder={t('cardOrder.field.formerLastName', 'Köne familiýaňyz (eger üýtgän bolsa)')}
/>
<FormInput
type="date"
label={t('cardOrder.field.birthDate', 'Doglan güni')}
required
value={form.birthDate}
onChange={set('birthDate')}
error={errors.birthDate}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
type="phone"
label={t('cardOrder.field.phone', 'Telefon')}
required
value={form.phone}
onChange={set('phone')}
error={errors.phone}
/>
<FormInput
type="phone"
label={t('cardOrder.field.phoneExtra', 'Telefon goşmaça')}
value={form.phoneExtra}
onChange={set('phoneExtra')}
/>
<FormInput
type="select"
label={t('cardOrder.field.citizenship', 'Raýatlyk')}
required
value={form.citizenship}
onChange={set('citizenship')}
options={citizenshipOptions}
error={errors.citizenship}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
label={t('cardOrder.field.registeredAddress', 'Ýazgy edilen salgyňyz')}
required
value={form.registeredAddress}
onChange={set('registeredAddress')}
placeholder={t('cardOrder.field.registeredAddress', 'Ýazgy edilen salgyňyz')}
error={errors.registeredAddress}
/>
<FormInput
label={t('cardOrder.field.currentAddress', 'Häzirki ýaşaýyş ýeri')}
required
value={form.currentAddress}
onChange={set('currentAddress')}
placeholder={t('cardOrder.field.currentAddress', 'Häzirki ýaşaýyş ýeri')}
error={errors.currentAddress}
/>
</div>
<FormInput
label={t('cardOrder.field.workplace', 'Işleýän ýeriňiz we wezipäňiz')}
required
value={form.workplace}
onChange={set('workplace')}
placeholder={t('cardOrder.field.workplace', 'Işleýän ýeriňiz we wezipäňiz')}
error={errors.workplace}
/>
</FormSection>
{/* ── Pasport ── */}
<FormSection title={t('cardOrder.section.passport', 'Pasport')}>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<FormInput
type="select"
label={t('cardOrder.field.passportSeries', 'Pasport seriýasy')}
required
value={form.passportSeriesId}
onChange={set('passportSeriesId')}
options={[
{ value: '1', label: 'I' },
{ value: '2', label: 'II' },
{ value: '3', label: 'III' },
]}
error={errors.passportSeriesId}
/>
<FormInput
label={t('cardOrder.field.passportNumber', 'Pasport belgisi')}
required
value={form.passportNumber}
onChange={set('passportNumber')}
placeholder={t('cardOrder.field.passportNumber', 'Pasport belgisi')}
error={errors.passportNumber}
/>
<FormInput
type="date"
label={t('cardOrder.field.passportIssueDate', 'Pasport berlen senesi')}
required
value={form.passportIssueDate}
onChange={set('passportIssueDate')}
error={errors.passportIssueDate}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
label={t('cardOrder.field.passportIssuedBy', 'Kim tarapyndan berildi')}
required
value={form.passportIssuedBy}
onChange={set('passportIssuedBy')}
placeholder={t('cardOrder.field.passportIssuedBy', 'Kim tarapyndan berildi')}
error={errors.passportIssuedBy}
/>
<FormInput
label={t('cardOrder.field.passportBirthPlace', 'Doglan ýeri (pasport)')}
required
value={form.passportBirthPlace}
onChange={set('passportBirthPlace')}
placeholder={t('cardOrder.field.passportBirthPlace', 'Doglan ýeri (pasport)')}
error={errors.passportBirthPlace}
/>
</div>
</FormSection>
{/* ── Pasport faýýlar ── */}
<FormSection title={t('cardOrder.section.passportFiles', 'Pasport faýýlar')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="file"
label={t('cardOrder.field.passportPage1', 'Pasport (sahypa 1)')}
required
accept="image/*,.pdf"
fileValue={form.passportPage1}
onFileChange={setFile('passportPage1')}
error={errors.passportPage1}
/>
<FormInput
type="file"
label={t('cardOrder.field.passportPage23', 'Pasport (2-3-nji sahypa)')}
required
accept="image/*,.pdf"
fileValue={form.passportPage23}
onFileChange={setFile('passportPage23')}
error={errors.passportPage23}
/>
<FormInput
type="file"
label={t('cardOrder.field.passportPage89', 'Pasport (8-9 sahypa)')}
required
accept="image/*,.pdf"
fileValue={form.passportPage89}
onFileChange={setFile('passportPage89')}
error={errors.passportPage89}
/>
<FormInput
type="file"
label={t('cardOrder.field.passportPage32', 'Pasport (32-nji sahypa)')}
required
accept="image/*,.pdf"
fileValue={form.passportPage32}
onFileChange={setFile('passportPage32')}
error={errors.passportPage32}
/>
</div>
</FormSection>
{/* ── Terms ── */}
{!isEdit && (
<div
className={`flex items-center gap-3 p-3 rounded-lg mb-6 cursor-pointer transition-colors
${errors.termsAccepted
? 'bg-destructive/10 border border-destructive/30'
: 'bg-primary/5 border border-primary/20'
}`}
onClick={() => setForm((f) => ({ ...f, termsAccepted: !f.termsAccepted }))}
>
<div className={`w-5 h-5 rounded flex items-center justify-center shrink-0 transition-colors
${form.termsAccepted ? 'bg-primary text-primary-foreground' : 'border border-border bg-background'}`}
>
{form.termsAccepted && (
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6L5 9L10 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
)}
</div>
<span className={`text-sm font-medium ${errors.termsAccepted ? 'text-destructive' : 'text-primary'}`}>
{t('cardOrder.terms', 'Şertnama bilen razylaşýaryn (Okamak üçin bas)')}
</span>
</div>
)}
{/* ── Actions ── */}
<div className="flex items-center justify-end gap-3">
{onCancel && (
<Button
variant="outline"
onClick={onCancel}
disabled={isPending}
>
{t('common.cancel', 'Ýatyr')}
</Button>
)}
<Button
onClick={handleSubmit}
disabled={isPending}
className="min-w-[160px]"
>
{isPending
? t('common.saving', 'Saklanylýar...')
: isEdit
? t('common.save', 'Ýatda sakla')
: t('cardOrder.submit', 'Kart sargyt dörediň')
}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,155 @@
import { Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import type { ColumnDef } from '@/components/dataTable'
import type { CardOrderListItem, CardOrderStatus } from '../api/orderNewCardApi'
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_CONFIG: Record<
CardOrderStatus,
{ label: string; className: string }
> = {
PENDING: {
label: 'Garaşylýar',
className:
'inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide ' +
'bg-amber-500/10 text-amber-400 border border-amber-500/20',
},
APPROVED: {
label: 'Tassyklandy',
className:
'inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide ' +
'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20',
},
REJECTED: {
label: 'Ýatyryldy',
className:
'inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold tracking-wide ' +
'bg-red-500/10 text-red-400 border border-red-500/20',
},
}
function StatusBadge({ status }: { status: CardOrderStatus }) {
const cfg = STATUS_CONFIG[status]
const icons: Record<CardOrderStatus, string> = {
PENDING: '⏳',
APPROVED: '✓',
REJECTED: '✕',
}
return (
<span className={cfg.className}>
<span className="text-[10px]">{icons[status]}</span>
{cfg.label}
</span>
)
}
// ─── Coloured text helper ─────────────────────────────────────────────────────
function HighlightText({
value,
variant,
}: {
value: string
variant: 'teal' | 'cyan' | 'muted'
}) {
const cls =
variant === 'teal' ? 'text-teal-400 font-semibold' :
variant === 'cyan' ? 'text-cyan-400 font-semibold' :
'text-muted-foreground'
return <span className={cls}>{value}</span>
}
// ─── useCardOrderColumns ──────────────────────────────────────────────────────
export function useCardOrderColumns(): ColumnDef<CardOrderListItem>[] {
const { t } = useTranslation()
return [
{
accessorKey: 'id',
header: t('cardOrder.col.id', 'ID'),
cell: ({ row }) => (
<Link
to={`/order-new-card/${row.original.id}`}
className="font-mono text-xs text-primary hover:underline"
>
{row.original.id}
</Link>
),
size: 130,
},
{
accessorKey: 'issuanceReasonName',
header: t('cardOrder.col.reason', 'Sebäp'),
cell: ({ row }) => (
<span className="text-sm text-foreground">
{row.original.issuanceReasonName}
</span>
),
},
{
accessorKey: 'createdAt',
header: t('cardOrder.col.createdAt', 'Döredilen wagty'),
cell: ({ row }) => (
<span className="text-sm text-muted-foreground whitespace-nowrap">
{row.original.createdAt}
</span>
),
size: 160,
},
{
accessorKey: 'cardTypeName',
header: t('cardOrder.col.cardType', 'Görnüşi'),
cell: ({ row }) => {
const isAltyn = row.original.cardTypeName === 'Altyn Asyr'
return (
<HighlightText
value={row.original.cardTypeName}
variant={isAltyn ? 'cyan' : 'teal'}
/>
)
},
},
{
accessorKey: 'provinceName',
header: t('cardOrder.col.province', 'Welaýat'),
cell: ({ row }) => (
<span className="text-sm text-foreground">{row.original.provinceName}</span>
),
},
{
accessorKey: 'branchName',
header: t('cardOrder.col.branch', 'Şahamça'),
cell: ({ row }) => {
const specialBranches = [
'Köpetdag', 'Türkmenabat', 'Türkmenbaşy',
'Seýdi', 'Çandybil', 'Balkan', 'Baş bank',
]
const isSpecial = specialBranches.includes(row.original.branchName)
return (
<HighlightText
value={row.original.branchName}
variant={isSpecial ? 'cyan' : 'muted'}
/>
)
},
},
{
id: 'fullName',
header: t('cardOrder.col.name', 'Ady'),
cell: ({ row }) => (
<span className="text-sm text-foreground">
{row.original.lastName} {row.original.firstName}
</span>
),
},
{
accessorKey: 'status',
header: t('cardOrder.col.status', 'Status'),
cell: ({ row }) => <StatusBadge status={row.original.status} />,
size: 130,
},
]
}

View File

@@ -0,0 +1,150 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
fetchCardOrders,
fetchCardOrderById,
createCardOrder,
updateCardOrder,
deleteCardOrder,
fetchCardIssuanceReasons,
fetchCardTypes,
fetchProvinces,
fetchBranches,
} from '../api/orderNewCardApi'
import type {
CardOrderFilters,
CreateCardOrderPayload,
UpdateCardOrderPayload,
} from '../api/orderNewCardApi'
// ─── Query keys ───────────────────────────────────────────────────────────────
export const cardOrderKeys = {
all: ['card-orders'] as const,
lists: () => [...cardOrderKeys.all, 'list'] as const,
list: (f: CardOrderFilters) => [...cardOrderKeys.lists(), f] as const,
details: () => [...cardOrderKeys.all, 'detail'] as const,
detail: (id: string) => [...cardOrderKeys.details(), id] as const,
reasons: ['card-order-reasons'] as const,
types: ['card-order-types'] as const,
provinces: ['provinces'] as const,
branches: (provinceId?: number) => ['branches', provinceId] as const,
}
// ─── List ─────────────────────────────────────────────────────────────────────
export function useCardOrders(filters: CardOrderFilters) {
return useQuery({
queryKey: cardOrderKeys.list(filters),
queryFn: () => fetchCardOrders(filters),
placeholderData: (prev) => prev,
})
}
// ─── Single ───────────────────────────────────────────────────────────────────
export function useCardOrderById(id: string) {
return useQuery({
queryKey: cardOrderKeys.detail(id),
queryFn: () => fetchCardOrderById(id),
enabled: Boolean(id),
})
}
// ─── Create ───────────────────────────────────────────────────────────────────
export function useCreateCardOrder() {
const { t } = useTranslation()
const qc = useQueryClient()
return useMutation({
mutationFn: (payload: CreateCardOrderPayload) => createCardOrder(payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
toast.success(t('cardOrder.createSuccess', 'Kart sargyt üstünlikli döredildi'))
},
onError: () => {
toast.error(t('cardOrder.createError', 'Kart sargyt döredilende ýalňyşlyk ýüze çykdy'))
},
})
}
// ─── Update ───────────────────────────────────────────────────────────────────
export function useUpdateCardOrder(id: string) {
const { t } = useTranslation()
const qc = useQueryClient()
return useMutation({
mutationFn: (payload: UpdateCardOrderPayload) => updateCardOrder(id, payload),
onSuccess: (updated) => {
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
qc.setQueryData(cardOrderKeys.detail(id), updated)
toast.success(t('cardOrder.updateSuccess', 'Kart sargyt üstünlikli täzelendi'))
},
onError: () => {
toast.error(t('cardOrder.updateError', 'Kart sargyt täzelende ýalňyşlyk ýüze çykdy'))
},
})
}
// ─── Delete ───────────────────────────────────────────────────────────────────
export function useDeleteCardOrder() {
const { t } = useTranslation()
const qc = useQueryClient()
return useMutation({
mutationFn: (id: string) => deleteCardOrder(id),
onSuccess: (_, id) => {
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
qc.removeQueries({ queryKey: cardOrderKeys.detail(id) })
toast.success(t('cardOrder.deleteSuccess', 'Kart sargyt üstünlikli pozuldy'))
},
onError: () => {
toast.error(t('cardOrder.deleteError', 'Kart sargyt pozulanda ýalňyşlyk ýüze çykdy'))
},
})
}
// ─── Lookup hooks ─────────────────────────────────────────────────────────────
export function useCardIssuanceReasons() {
return useQuery({
queryKey: cardOrderKeys.reasons,
queryFn: fetchCardIssuanceReasons,
staleTime: Infinity,
})
}
export function useCardTypes() {
return useQuery({
queryKey: cardOrderKeys.types,
queryFn: fetchCardTypes,
staleTime: Infinity,
})
}
export function useProvinces() {
return useQuery({
queryKey: cardOrderKeys.provinces,
queryFn: fetchProvinces,
staleTime: Infinity,
})
}
export function useBranches(provinceId?: number) {
return useQuery({
queryKey: cardOrderKeys.branches(provinceId),
queryFn: () => fetchBranches(provinceId),
enabled: provinceId !== undefined && provinceId !== 0,
staleTime: Infinity,
})
}

View File

@@ -0,0 +1,244 @@
import { apiClient } from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export type IntlPaymentStatus = 'pending' | 'approved' | 'rejected'
export type CurrencyType = 'visa' | 'mastercard'
export interface IntlPaymentItem {
id: string
client_id: string
client_label: string
currency_type: CurrencyType
currency_type_label: string
created_at: string
province: string
province_label: string
branch: string
branch_label: string
status: IntlPaymentStatus
note: string | null
// Şahsy maglumatlar
passport_first_name: string
passport_last_name: string
phone: string
email: string | null
home_address: string | null
// Töleg upgradyjynyň maglumatlary
passport_series: string
passport_number: string
payer_full_name: string
payer_account_number: string
// Töleg kabul edijiniň maglumatlary
receiver_info: string
// Kabul ediji talyp boyunca resminamalar (9 sany)
doc_sberbank_account: string | null // file url
doc_school_enrollment: string | null
doc_summons: string | null
doc_passport_tm: string | null
doc_foreign_passport: string | null
doc_foreign_passport_copy: string | null
doc_exit_permission: string | null
doc_school_foreign_info: string | null
doc_school_departure_info: string | null
// Upgradyý boyunca resminamalar (6 sany)
upd_doc_passport_tm: string | null
upd_doc_foreign_passport: string | null
upd_doc_visa: string | null
upd_doc_acceptance_letter: string | null
upd_doc_passport_biometric: string | null
upd_doc_passport_old: string | null
created_by: string
created_by_label: string
}
export interface IntlPaymentListParams {
page?: number
per_page?: number
search?: string
status?: IntlPaymentStatus | ''
month?: string
province?: string
}
export interface IntlPaymentListResponse {
data: IntlPaymentItem[]
meta: {
current_page: number
last_page: number
per_page: number
total: number
}
}
export type IntlPaymentCreatePayload = {
client_id: string
status: IntlPaymentStatus
note: string
currency_type: CurrencyType
province: string
branch: string
passport_first_name: string
passport_last_name: string
phone: string
email: string
home_address: string
passport_series: string
passport_number: string
payer_full_name: string
payer_account_number: string
receiver_info: string
// kabul ediji docs
doc_sberbank_account: File | null
doc_school_enrollment: File | null
doc_summons: File | null
doc_passport_tm: File | null
doc_foreign_passport: File | null
doc_foreign_passport_copy: File | null
doc_exit_permission: File | null
doc_school_foreign_info: File | null
doc_school_departure_info: File | null
// upgradyý docs
upd_doc_passport_tm: File | null
upd_doc_foreign_passport: File | null
upd_doc_visa: File | null
upd_doc_acceptance_letter: File | null
upd_doc_passport_biometric: File | null
upd_doc_passport_old: File | null
}
export type IntlPaymentUpdatePayload = IntlPaymentCreatePayload
// ─── API Functions ────────────────────────────────────────────────────────────
const MOCK_INTL_PAYMENTS: IntlPaymentItem[] = [
{
id: '1',
client_id: '1',
client_label: 'Jelaletdin',
currency_type: 'visa',
currency_type_label: 'Visa',
created_at: '2024-05-07 12:00',
province: 'ashgabat',
province_label: 'Aşgabat',
branch: '1',
branch_label: 'Merkezi şahamça',
status: 'pending',
note: 'Test sargyt',
passport_first_name: 'Aman',
passport_last_name: 'Amanow',
phone: '99365123456',
email: 'aman@example.com',
home_address: 'Aşgabat ş., Magtymguly şaýoly 1',
passport_series: 'I-MR',
passport_number: '123456',
payer_full_name: 'Aman Amanow',
payer_account_number: '1234567890123456',
receiver_info: 'Test Receiver',
doc_sberbank_account: null,
doc_school_enrollment: null,
doc_summons: null,
doc_passport_tm: null,
doc_foreign_passport: null,
doc_foreign_passport_copy: null,
doc_exit_permission: null,
doc_school_foreign_info: null,
doc_school_departure_info: null,
upd_doc_passport_tm: null,
upd_doc_foreign_passport: null,
upd_doc_visa: null,
upd_doc_acceptance_letter: null,
upd_doc_passport_biometric: null,
upd_doc_passport_old: null,
created_by: '1',
created_by_label: 'Admin',
},
]
export const intlPaymentApi = {
list: async (params: IntlPaymentListParams): Promise<IntlPaymentListResponse> => {
return {
data: MOCK_INTL_PAYMENTS,
meta: {
current_page: params.page || 1,
last_page: 1,
per_page: params.per_page || 25,
total: MOCK_INTL_PAYMENTS.length,
}
}
const { data } = await apiClient.get('/intl-payments/visa-master', { params })
return data
},
getById: async (id: string): Promise<IntlPaymentItem> => {
const mock = MOCK_INTL_PAYMENTS.find(p => p.id === id)
if (mock) return mock
const { data } = await apiClient.get(`/intl-payments/visa-master/${id}`)
return data
},
create: (payload: IntlPaymentCreatePayload): Promise<IntlPaymentItem> => {
const form = buildFormData(payload)
return apiClient
.post('/intl-payments/visa-master', form, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((r) => r.data)
},
update: (id: string, payload: IntlPaymentUpdatePayload): Promise<IntlPaymentItem> => {
const form = buildFormData(payload)
form.append('_method', 'PUT')
return apiClient
.post(`/intl-payments/visa-master/${id}`, form, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((r) => r.data)
},
delete: (id: string): Promise<void> =>
apiClient.delete(`/intl-payments/visa-master/${id}`).then((r) => r.data),
}
// ─── Helper ───────────────────────────────────────────────────────────────────
const TEXT_FIELDS: (keyof IntlPaymentCreatePayload)[] = [
'client_id', 'status', 'note', 'currency_type', 'province', 'branch',
'passport_first_name', 'passport_last_name', 'phone', 'email', 'home_address',
'passport_series', 'passport_number', 'payer_full_name', 'payer_account_number',
'receiver_info',
]
const FILE_FIELDS: (keyof IntlPaymentCreatePayload)[] = [
'doc_sberbank_account', 'doc_school_enrollment', 'doc_summons',
'doc_passport_tm', 'doc_foreign_passport', 'doc_foreign_passport_copy',
'doc_exit_permission', 'doc_school_foreign_info', 'doc_school_departure_info',
'upd_doc_passport_tm', 'upd_doc_foreign_passport', 'upd_doc_visa',
'upd_doc_acceptance_letter', 'upd_doc_passport_biometric', 'upd_doc_passport_old',
]
function buildFormData(payload: IntlPaymentCreatePayload): FormData {
const form = new FormData()
for (const key of TEXT_FIELDS) {
const val = payload[key]
if (val !== null && val !== undefined) form.append(key, String(val))
}
for (const key of FILE_FIELDS) {
const file = payload[key]
if (file instanceof File) form.append(key, file)
}
return form
}

View File

@@ -0,0 +1,463 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import type { IntlPaymentItem, IntlPaymentCreatePayload, IntlPaymentStatus, CurrencyType } from '../api/visaMasterPaymentsApi'
// ─── Types ────────────────────────────────────────────────────────────────────
interface IntlPaymentFormProps {
mode: 'create' | 'edit'
initialData?: IntlPaymentItem
onSubmit: (payload: IntlPaymentCreatePayload) => void
isSubmitting: boolean
}
type FileKey =
| 'doc_sberbank_account' | 'doc_school_enrollment' | 'doc_summons'
| 'doc_passport_tm' | 'doc_foreign_passport' | 'doc_foreign_passport_copy'
| 'doc_exit_permission' | 'doc_school_foreign_info' | 'doc_school_departure_info'
| 'upd_doc_passport_tm' | 'upd_doc_foreign_passport' | 'upd_doc_visa'
| 'upd_doc_acceptance_letter' | 'upd_doc_passport_biometric' | 'upd_doc_passport_old'
interface FormState {
client_id: string
status: string
note: string
currency_type: string
province: string
branch: string
passport_first_name: string
passport_last_name: string
phone: string
email: string
home_address: string
passport_series: string
passport_number: string
payer_full_name: string
payer_account_number: string
receiver_info: string
doc_sberbank_account: File | null
doc_school_enrollment: File | null
doc_summons: File | null
doc_passport_tm: File | null
doc_foreign_passport: File | null
doc_foreign_passport_copy: File | null
doc_exit_permission: File | null
doc_school_foreign_info: File | null
doc_school_departure_info: File | null
upd_doc_passport_tm: File | null
upd_doc_foreign_passport: File | null
upd_doc_visa: File | null
upd_doc_acceptance_letter: File | null
upd_doc_passport_biometric: File | null
upd_doc_passport_old: File | null
}
type FormErrors = Partial<Record<keyof FormState, string>>
// ─── Constants ────────────────────────────────────────────────────────────────
const STATUS_OPTIONS = [
{ value: 'pending', label: 'Garaşylýar' },
{ value: 'approved', label: 'Tassyklandy' },
{ value: 'rejected', label: 'Ret edildi' },
]
const CURRENCY_OPTIONS = [
{ value: 'visa', label: 'Visa' },
{ value: 'mastercard', label: 'MasterCard' },
]
const PASSPORT_SERIES_OPTIONS = [
{ value: 'I', label: 'I' },
{ value: 'II', label: 'II' },
{ value: 'I-MR', label: 'I-MR' },
{ value: 'II-MR', label: 'II-MR' },
]
const PROVINCE_OPTIONS = [
{ value: 'ashgabat', label: 'Aşgabat' },
{ value: 'ahal', label: 'Ahal' },
{ value: 'mary', label: 'Mary' },
{ value: 'dasoguz', label: 'Daşoguz' },
{ value: 'lebap', label: 'Lebap' },
{ value: 'balkan', label: 'Balkan' },
]
// Kabul ediji docs — 9 sany
const KABUL_DOCS: { key: FileKey; label: string }[] = [
{ key: 'doc_sberbank_account', label: 'Talypyň degişli welaýata "SBERBANK" kartyň rekwizitleri' },
{ key: 'doc_school_enrollment', label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamasy' },
{ key: 'doc_summons', label: 'Talypyň bilendiriň göçürmesi' },
{ key: 'doc_passport_tm', label: 'Talypyň degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi' },
{ key: 'doc_foreign_passport', label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi' },
{ key: 'doc_foreign_passport_copy',label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurtda galan döwründe bakýan döwleti baradaky bellenen sahypasynyň göçürmesi' },
{ key: 'doc_exit_permission', label: 'Talypyň Türkmenistandan çykmak — we Türkmenistana girmek üçin pasportynyň dowletiniň girmesiz baradaky bellenen (goşmaç şaýmynyň) bellenen sahypasynyň göçürmesi' },
{ key: 'doc_school_foreign_info', label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy barada doly takyk dil ulgaýynda takyk dil maglumatly sebäpleri daşary ýurt döwletiniň ýokary okuw mekdebinden haty' },
{ key: 'doc_school_departure_info',label: 'Talypyň daşary ýurt döwletinde döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamany döwlet dili maglumatlaryny talabap doly takyk dil ulgaýynda talaby daşary ýurt döwletiniň ýokary okuw mekdebinden haty' },
]
// Upgradyý docs — 6 sany
const UPGRAD_DOCS: { key: FileKey; label: string }[] = [
{ key: 'upd_doc_passport_tm', label: 'Upgradyý degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi' },
{ key: 'upd_doc_foreign_passport', label: 'Upgradyý degişli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi' },
{ key: 'upd_doc_visa', label: 'Upgradyý Türkmenistandan — çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurt döwletinde galýandygy we daşary ýurt döwleti baradaky şaýmynyň bellenen sahypasynyň göçürmesi' },
{ key: 'upd_doc_acceptance_letter', label: 'Upgradyýyň we kabul edijiniň Batalyý töräre garyşdyryjy resminamalarynyň göçürmesi' },
{ key: 'upd_doc_passport_biometric', label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra Türkmenistanyň raýatynyň pasportynyň tässy göreli alan bolsa, osta üstü görli 1 pasportynyň seriýasy baradaky maglumatlary' },
{ key: 'upd_doc_passport_old', label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra Türkmenistanyň raýatynyň pasportynyň köp göreli alanlar soňra birleşi göreli alan bolsa, biri miwe möhüründen doglan doglan ata-enelerden biriniň alan pasportynyň seriýasy baradaky göwnamasy' },
]
// ─── Default state ────────────────────────────────────────────────────────────
const defaultState: FormState = {
client_id: '', status: 'pending', note: '',
currency_type: '', province: '', branch: '',
passport_first_name: '', passport_last_name: '',
phone: '', email: '', home_address: '',
passport_series: '', passport_number: '',
payer_full_name: '', payer_account_number: '',
receiver_info: '',
doc_sberbank_account: null, doc_school_enrollment: null,
doc_summons: null, doc_passport_tm: null,
doc_foreign_passport: null, doc_foreign_passport_copy: null,
doc_exit_permission: null, doc_school_foreign_info: null,
doc_school_departure_info: null,
upd_doc_passport_tm: null, upd_doc_foreign_passport: null,
upd_doc_visa: null, upd_doc_acceptance_letter: null,
upd_doc_passport_biometric: null, upd_doc_passport_old: null,
}
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(form: FormState): FormErrors {
const errors: FormErrors = {}
if (!form.client_id) errors.client_id = 'Ulanyjy hökmany'
if (!form.status) errors.status = 'Status hökmany'
if (!form.currency_type) errors.currency_type = 'Ýüztumanyň görnüşi hökmany'
if (!form.province) errors.province = 'Welaýat hökmany'
if (!form.branch) errors.branch = 'Şahamça hökmany'
if (!form.passport_first_name) errors.passport_first_name = 'Ady hökmany'
if (!form.passport_last_name) errors.passport_last_name = 'Familiýasy hökmany'
if (!form.phone) errors.phone = 'Telefon hökmany'
if (!form.passport_series) errors.passport_series = 'Pasport seriýasy hökmany'
if (!form.passport_number) errors.passport_number = 'Pasport nomeri hökmany'
if (!form.payer_full_name) errors.payer_full_name = 'Ady Familiýasy Atasnyň ady hökmany'
if (!form.payer_account_number)errors.payer_account_number= 'Goşun hasaby hökmany'
if (!form.receiver_info) errors.receiver_info = 'Töleg kabul edijiniň maglumatlary hökmany'
return errors
}
// ─── Section wrapper ──────────────────────────────────────────────────────────
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
{title && (
<h2 className="text-base font-semibold text-foreground">{title}</h2>
)}
{children}
</section>
)
}
// ─── Component ────────────────────────────────────────────────────────────────
export function IntlPaymentForm({ mode, initialData, onSubmit, isSubmitting }: IntlPaymentFormProps) {
const { t } = useTranslation()
const navigate = useNavigate()
const [form, setForm] = useState<FormState>(defaultState)
const [errors, setErrors] = useState<FormErrors>({})
useEffect(() => {
if (mode === 'edit' && initialData) {
setForm({
client_id: initialData.client_id,
status: initialData.status,
note: initialData.note ?? '',
currency_type: initialData.currency_type,
province: initialData.province,
branch: initialData.branch,
passport_first_name: initialData.passport_first_name,
passport_last_name: initialData.passport_last_name,
phone: initialData.phone,
email: initialData.email ?? '',
home_address: initialData.home_address ?? '',
passport_series: initialData.passport_series,
passport_number: initialData.passport_number,
payer_full_name: initialData.payer_full_name,
payer_account_number: initialData.payer_account_number,
receiver_info: initialData.receiver_info,
doc_sberbank_account: null, doc_school_enrollment: null,
doc_summons: null, doc_passport_tm: null,
doc_foreign_passport: null, doc_foreign_passport_copy: null,
doc_exit_permission: null, doc_school_foreign_info: null,
doc_school_departure_info: null,
upd_doc_passport_tm: null, upd_doc_foreign_passport: null,
upd_doc_visa: null, upd_doc_acceptance_letter: null,
upd_doc_passport_biometric: null, upd_doc_passport_old: null,
})
}
}, [mode, initialData])
const set = <K extends keyof FormState>(key: K, value: FormState[K]) => {
setForm((prev) => ({ ...prev, [key]: value }))
if (errors[key]) setErrors((prev) => ({ ...prev, [key]: undefined }))
}
const handleSubmit = () => {
const errs = validate(form)
if (Object.keys(errs).length > 0) {
setErrors(errs)
return
}
onSubmit({
...form,
status: form.status as IntlPaymentStatus,
currency_type: form.currency_type as CurrencyType,
})
}
const title = mode === 'create'
? t('intlPayment.createTitle', 'Visa/Master tölegler (talyplar üçin) dörediň')
: t('intlPayment.editTitle', 'Visa/Master tölegler (talyplar üçin) redaktirläň')
const submitLabel = mode === 'create'
? t('intlPayment.createBtn', 'Visa/Master tölegler (talyplar üçin) dörediň')
: t('intlPayment.editBtn', 'Visa/Master tölegler (talyplar üçin) redaktirläň')
return (
<div className="max-w-4xl mx-auto space-y-6">
<h1 className="text-2xl font-bold text-foreground">{title}</h1>
{/* ── Status ────────────────────────────────────────────────────────── */}
<Section title="">
<FormInput
type="searchable-select"
label={t('intlPayment.client', 'Ulanyjy')}
value={form.client_id}
onChange={(v) => set('client_id', v)}
options={[]} // Fetched from clients API
placeholder="Saýlamak üçin basyň"
error={errors.client_id}
required
/>
<FormInput
type="select"
label={t('intlPayment.status', 'Status')}
value={form.status}
onChange={(v) => set('status', v)}
options={STATUS_OPTIONS}
error={errors.status}
required
/>
<FormInput
type="textarea"
label={t('intlPayment.note', 'Bellik')}
value={form.note}
onChange={(v) => set('note', v)}
placeholder="Bellik"
rows={2}
/>
</Section>
{/* ── Ýüztumanyň görnüşi ───────────────────────────────────────────── */}
<Section title={t('intlPayment.currencySection', 'Ýüztumanyň görnüşi')}>
<FormInput
type="select"
label={t('intlPayment.currencyType', 'Ýüztumanyň görnüşi')}
value={form.currency_type}
onChange={(v) => set('currency_type', v)}
options={CURRENCY_OPTIONS}
error={errors.currency_type}
required
/>
</Section>
{/* ── Lokasiýa ─────────────────────────────────────────────────────── */}
<Section title={t('intlPayment.locationSection', 'Lokasiýa')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('intlPayment.province', 'Welaýat')}
value={form.province}
onChange={(v) => { set('province', v); set('branch', '') }}
options={PROVINCE_OPTIONS}
error={errors.province}
required
/>
<FormInput
type="searchable-select"
label={t('intlPayment.branch', 'Şahamça')}
value={form.branch}
onChange={(v) => set('branch', v)}
options={[]} // Fetched from branches API filtered by province
placeholder="Saýlamak üçin basyň"
error={errors.branch}
required
/>
</div>
</Section>
{/* ── Şahsy maglumatlar ─────────────────────────────────────────────── */}
<Section title={t('intlPayment.personalSection', 'Şahsy maglumatlar')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('intlPayment.passportLastName', 'Pasportdaky familýa')}
value={form.passport_last_name}
onChange={(v) => set('passport_last_name', v)}
options={[]}
placeholder="Pasportdaky familýa"
error={errors.passport_last_name}
required
/>
<FormInput
type="text"
label={t('intlPayment.passportFirstName', 'Pasportdaky ady')}
value={form.passport_first_name}
onChange={(v) => set('passport_first_name', v)}
placeholder="Pasportdaky ady"
error={errors.passport_first_name}
required
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="phone"
label={t('intlPayment.phone', 'Telefon')}
value={form.phone}
onChange={(v) => set('phone', v)}
error={errors.phone}
required
/>
<FormInput
type="email"
label={t('intlPayment.email', 'E-poçta')}
value={form.email}
onChange={(v) => set('email', v)}
placeholder="E-poçta"
/>
</div>
<FormInput
type="text"
label={t('intlPayment.homeAddress', 'Häzirki ýaşyş ýeri')}
value={form.home_address}
onChange={(v) => set('home_address', v)}
placeholder="Häzirki ýaşyş ýeri"
/>
</Section>
{/* ── Töleg upgradyjynyň maglumatlary ──────────────────────────────── */}
<Section title={t('intlPayment.payerSection', 'Töleg upgradyjynyň maglumatlary')}>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormInput
type="searchable-select"
label={t('intlPayment.passportSeries', 'Pasport seriýasy')}
value={form.passport_series}
onChange={(v) => set('passport_series', v)}
options={PASSPORT_SERIES_OPTIONS}
error={errors.passport_series}
required
/>
<FormInput
type="text"
label={t('intlPayment.passportNumber', 'Pasport nomeri')}
value={form.passport_number}
onChange={(v) => set('passport_number', v)}
placeholder="Pasport nomeri"
error={errors.passport_number}
required
/>
</div>
<FormInput
type="text"
label={t('intlPayment.payerFullName', 'Ady Familiýasy Atasnyň ady')}
value={form.payer_full_name}
onChange={(v) => set('payer_full_name', v)}
placeholder="Ady Familiýasy Atasnyň ady"
error={errors.payer_full_name}
required
/>
<FormInput
type="text"
label={t('intlPayment.payerAccount', 'Goşun hasaby')}
value={form.payer_account_number}
onChange={(v) => set('payer_account_number', v)}
placeholder="Goşun hasaby"
error={errors.payer_account_number}
required
/>
</Section>
{/* ── Töleg kabul edijiniň maglumatlary ────────────────────────────── */}
<Section title={t('intlPayment.receiverSection', 'Töleg kabul edijiniň maglumatlary')}>
<FormInput
type="textarea"
label={t('intlPayment.receiverInfo', 'Saňa ger')}
value={form.receiver_info}
onChange={(v) => set('receiver_info', v)}
placeholder="Saňa ger"
rows={3}
error={errors.receiver_info}
required
/>
</Section>
{/* ── Kabul ediji talyp boyunca resminamalar ────────────────────────── */}
<Section title={t('intlPayment.kabulDocsSection', 'Kabul ediji talyp boyunca resminamalar')}>
<div className="space-y-4">
{KABUL_DOCS.map(({ key, label }) => (
<FormInput
key={key}
type="file"
label={label}
onFileChange={(f) => set(key, f)}
fileValue={form[key] as File | null}
accept="image/*,.pdf"
/>
))}
</div>
</Section>
{/* ── Upgradyý boyunca resminamalar ─────────────────────────────────── */}
<Section title={t('intlPayment.upgradDocsSection', 'Upgradyý boyunca resminamalar')}>
<div className="space-y-4">
{UPGRAD_DOCS.map(({ key, label }) => (
<FormInput
key={key}
type="file"
label={label}
onFileChange={(f) => set(key, f)}
fileValue={form[key] as File | null}
accept="image/*,.pdf"
/>
))}
</div>
</Section>
{/* ── Actions ───────────────────────────────────────────────────────── */}
<div className="flex items-center justify-end gap-3 pb-6">
<Button
type="button"
variant="outline"
onClick={() => navigate('/intl-payments/visa-master')}
disabled={isSubmitting}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isSubmitting}
className="min-w-[240px]"
>
{isSubmitting ? <Spinner className="size-4" /> : submitLabel}
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,78 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import {
intlPaymentApi,
type IntlPaymentListParams,
type IntlPaymentCreatePayload,
type IntlPaymentUpdatePayload,
} from '../api/visaMasterPaymentsApi'
export const INTL_PAYMENT_KEYS = {
all: ['intl-payments-visa'] as const,
lists: () => [...INTL_PAYMENT_KEYS.all, 'list'] as const,
list: (p: IntlPaymentListParams) => [...INTL_PAYMENT_KEYS.lists(), p] as const,
detail: (id: string) => [...INTL_PAYMENT_KEYS.all, 'detail', id] as const,
}
export function useIntlPayments(params: IntlPaymentListParams) {
return useQuery({
queryKey: INTL_PAYMENT_KEYS.list(params),
queryFn: () => intlPaymentApi.list(params),
placeholderData: (prev) => prev,
})
}
export function useIntlPayment(id: string) {
return useQuery({
queryKey: INTL_PAYMENT_KEYS.detail(id),
queryFn: () => intlPaymentApi.getById(id),
enabled: !!id,
})
}
export function useCreateIntlPayment() {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: IntlPaymentCreatePayload) => intlPaymentApi.create(payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() })
toast.success(t('intlPayment.createSuccess', 'Töleg döredildi'))
},
onError: () => {
toast.error(t('intlPayment.createError', 'Döretmek başartmady'))
},
})
}
export function useUpdateIntlPayment(id: string) {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (payload: IntlPaymentUpdatePayload) => intlPaymentApi.update(id, payload),
onSuccess: () => {
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() })
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.detail(id) })
toast.success(t('intlPayment.updateSuccess', 'Töleg üýtgedildi'))
},
onError: () => {
toast.error(t('intlPayment.updateError', 'Üýtgetmek başartmady'))
},
})
}
export function useDeleteIntlPayment() {
const qc = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: (id: string) => intlPaymentApi.delete(id),
onSuccess: () => {
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() })
toast.success(t('intlPayment.deleteSuccess', 'Töleg pozuldy'))
},
onError: () => {
toast.error(t('intlPayment.deleteError', 'Pozmak başartmady'))
},
})
}

View File

@@ -204,7 +204,7 @@ function AppSidebar() {
{
title: t('Card department', 'KART BÖLÜMI'),
items: [
{ title: t('Order new card', 'Täze kart açmak'), url: '/card-new' },
{ title: t('Order new card', 'Täze kart açmak'), url: '/order-new-card' },
{ title: t('Card transactions', 'Kart hereketleri'), url: '/card-transactions' },
{ title: t('Card requisites', 'Kart rekwizitler'), url: '/card-requisites' },
{ title: t('Card balances', 'Kart galyndylary'), url: '/card-balances' },
@@ -214,8 +214,8 @@ function AppSidebar() {
{
title: t('International payments', 'HALKARA TÖLEGLER'),
items: [
{ title: t('Visa/Master payments', 'Visa/Master tölegleri'), url: '/intl-payments/visa-master' },
{ title: t('Sber payments', 'Sber tölegleri'), url: '/intl-payments/sber' },
{ title: t('Visa/Master payments', 'Visa/Master tölegleri'), url: '/visa-master' },
{ title: t('Sber payments', 'Sber tölegleri'), url: '/sber' },
],
},
],

View File

@@ -0,0 +1,209 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Download, Eye, 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 { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar, type ColumnMeta } from '@/components/dataTableToolbar'
import type { VisibilityState } from '@tanstack/react-table'
import {
useCardBalances,
useDeleteCardBalance,
useDownloadCardBalance,
} from '@/features/cardBalance/hooks/useCardBalance'
import { type CardBalance } from '@/features/cardBalance/api/cardBalanceApi'
const PER_PAGE = 25
export default function CardBalancesPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(PER_PAGE)
const [search, setSearch] = useState('')
const [deleteId, setDeleteId] = useState<number | null>(null)
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>([])
const { data, isLoading } = useCardBalances({ page, per_page: perPage, search })
const deleteMutation = useDeleteCardBalance()
const downloadMutation = useDownloadCardBalance()
// ── Columns ───────────────────────────────────────────────────────────────
const columns: ColumnDef<CardBalance>[] = [
{
id: 'id',
accessorKey: 'id',
header: t('ID', 'ID'),
cell: ({ row }) => (
<button
className="text-primary font-medium hover:underline"
onClick={() => navigate(`/card-balances/${row.original.id}`)}
>
{row.original.id}
</button>
),
},
{
id: 'passport_series',
accessorKey: 'passport_series',
header: t('Passport series', 'PASPORT SERIYASY'),
cell: ({ row }) => <span>{row.original.passport_series}</span>,
},
{
id: 'passport_number',
accessorKey: 'passport_number',
header: t('Passport number', 'PASPORT BELGISI'),
cell: ({ row }) => <span>{row.original.passport_number}</span>,
},
{
id: 'card_number',
accessorKey: 'card_number',
header: t('Card number', 'KART BELGISI'),
cell: ({ row }) => <span className="font-mono">{row.original.card_number}</span>,
},
{
id: 'card_expiry_month',
accessorKey: 'card_expiry_month',
header: t('Expiry month', 'KART MÖHLETI (AÝ)'),
cell: ({ row }) => <span>{row.original.card_expiry_month}</span>,
},
{
id: 'card_expiry_year',
accessorKey: 'card_expiry_year',
header: t('Expiry year', 'KART MÖHLETI (ÝYL)'),
cell: ({ row }) => <span>{row.original.card_expiry_year}</span>,
},
{
id: 'actions',
header: '',
enableHiding: false,
cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end">
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => downloadMutation.mutate(row.original.id)}
title={t('Download', 'Ýükle')}
>
<Download size={14} />
</Button>
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => navigate(`/card-balances/${row.original.id}`)}
title={t('View', 'Görmek')}
>
<Eye size={14} />
</Button>
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => navigate(`/card-balances/${row.original.id}/edit`)}
title={t('Edit', 'Üýtgetmek')}
>
<Pencil size={14} />
</Button>
<Button
variant="ghost" size="icon"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteId(row.original.id)}
title={t('Delete', 'Öçürmek')}
>
<Trash2 size={14} />
</Button>
</div>
),
},
]
const columnMeta: ColumnMeta[] = columns
.filter((c) => c.id !== 'actions')
.map((c) => ({
id: c.id!,
label: typeof c.header === 'string' ? c.header : c.id!,
}))
const total = data?.total ?? 0
const totalPages = Math.ceil(total / perPage)
const handleDelete = async () => {
if (deleteId === null) return
await deleteMutation.mutateAsync(deleteId)
setDeleteId(null)
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t('Card balances', 'Kart galyndylary')}
</h1>
</div>
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { setSearch(v); setPage(1) }}
searchPlaceholder={t('Search', 'Gözlemek')}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
actionLabel={t('Create card balance', 'Kart galyndysy dörediň')}
onAction={() => navigate('/card-balances/create')}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => String(row.id)}
currentPage={page}
totalPages={totalPages}
totalCount={total}
onPageChange={setPage}
/>
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Are you sure?', 'Eminsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t(
'This action cannot be undone.',
'Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.',
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,16 @@
import { useTranslation } from 'react-i18next'
import { CardBalanceForm } from '@/features/cardBalance/components/cardBalanceForm'
export default function CardBalanceCreatePage() {
const { t } = useTranslation()
return (
<div className="space-y-4">
<h1 className="text-xl font-semibold text-foreground tracking-tight">
{t('Create card balance', 'Kart galyndysy dörediň')}
</h1>
<CardBalanceForm mode="create" />
</div>
)
}

View File

@@ -0,0 +1,47 @@
import { useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Skeleton } from '@/components/ui/skeleton'
import { CardBalanceForm } from '@/features/cardBalance/components/cardBalanceForm'
import { useCardBalance } from '@/features/cardBalance/hooks/useCardBalance'
export default function CardBalanceEditPage() {
const { t } = useTranslation()
const { id } = useParams<{ id: string }>()
const numericId = Number(id)
const { data, isLoading } = useCardBalance(numericId)
if (isLoading) {
return (
<div className="space-y-4 max-w-3xl">
<Skeleton className="h-8 w-48" />
{Array.from({ length: 8 }).map((_, i) => (
<Skeleton key={i} className="h-10 w-full" />
))}
</div>
)
}
if (!data) {
return (
<div className="text-center py-24 text-muted-foreground">
{t('Not found', 'Tapylmady')}
</div>
)
}
return (
<div className="space-y-4">
<h1 className="text-xl font-semibold text-foreground tracking-tight">
{t('Edit card balance', 'Kart galyndysyny düzetmek')}:{' '}
<span className="text-primary font-mono">{data.id}</span>
</h1>
<CardBalanceForm
mode="edit"
initialData={data}
cardBalanceId={numericId}
/>
</div>
)
}

View File

@@ -0,0 +1,248 @@
import { useState } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Download, Trash2, Pencil, ChevronDown } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
useCardBalance,
useDeleteCardBalance,
useDownloadCardBalance,
} from '@/features/cardBalance/hooks/useCardBalance'
// ─── Types for operations table ───────────────────────────────────────────────
interface Operation {
id: number
action_name: string
performed_by: string
target: string
status: 'FINISHED' | 'PENDING' | 'FAILED'
date: string
}
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_STYLES: Record<string, string> = {
FINISHED: 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/30',
PENDING: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30',
FAILED: 'bg-red-500/20 text-red-400 border border-red-500/30',
}
function OpStatusBadge({ status }: { status: string }) {
return (
<span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold ${STATUS_STYLES[status] ?? STATUS_STYLES.PENDING}`}>
<span className="w-1.5 h-1.5 rounded-full bg-current" />
{status}
</span>
)
}
// ─── Detail row ───────────────────────────────────────────────────────────────
function DetailRow({ label, value }: { label: string; value: string | number }) {
return (
<div className="grid grid-cols-[220px_1fr] border-b border-border/50 last:border-0">
<div className="px-4 py-3 text-sm text-muted-foreground font-medium bg-muted/10">
{label}
</div>
<div className="px-4 py-3 text-sm text-foreground">{value}</div>
</div>
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardBalanceViewPage() {
const { t } = useTranslation()
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const [deleteOpen, setDeleteOpen] = useState(false)
const [opsExpanded, setOpsExpanded] = useState(true)
const [opsPage, setOpsPage] = useState(1)
const numericId = Number(id)
const { data, isLoading } = useCardBalance(numericId)
const deleteMutation = useDeleteCardBalance()
const downloadMutation = useDownloadCardBalance()
// Placeholder operations — in real app fetch from API using numericId
const operations: Operation[] = []
const opsTotal = operations.length
const handleDelete = async () => {
await deleteMutation.mutateAsync(numericId)
navigate('/card-balances')
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-7 text-primary" />
</div>
)
}
if (!data) {
return (
<div className="text-center py-24 text-muted-foreground">
{t('Not found', 'Tapylmady')}
</div>
)
}
return (
<div className="space-y-5">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t('Card balance detail', 'Kart galyndysy giňişleýin')}:
</h1>
<div className="flex items-center gap-2">
<Button
variant="outline" size="sm"
onClick={() => downloadMutation.mutate(numericId)}
disabled={downloadMutation.isPending}
>
<Download size={14} />
</Button>
<Button
variant="outline" size="sm"
className="text-destructive border-destructive/30 hover:bg-destructive/10"
onClick={() => setDeleteOpen(true)}
>
<Trash2 size={14} />
</Button>
<Button variant="outline" size="sm" asChild>
<Link to={`/card-balances/${numericId}/edit`}>
<Pencil size={14} />
</Link>
</Button>
</div>
</div>
{/* Detail card */}
<div className="rounded-lg border border-border bg-card overflow-hidden">
<DetailRow label={t('ID', 'ID')} value={data.id} />
<DetailRow label={t('Passport series', 'Pasport seriýasy')} value={data.passport_series} />
<DetailRow label={t('Passport number', 'Pasport belgisi')} value={data.passport_number} />
<DetailRow label={t('Card number', 'Kart belgisi')} value={data.card_number} />
<DetailRow label={t('Card expiry month', 'Kart Möhleti (aý)')} value={data.card_expiry_month} />
<DetailRow label={t('Card expiry year', 'Kart Möhleti (ýyl)')} value={data.card_expiry_year} />
</div>
{/* Ammallar (Operations) collapsible section */}
<div className="rounded-lg border border-border bg-card overflow-hidden">
{/* Section toggle header */}
<button
className="w-full flex items-center gap-2 px-4 py-3 text-left hover:bg-muted/20 transition-colors"
onClick={() => setOpsExpanded((v) => !v)}
>
<span className="font-semibold text-foreground text-sm">
{t('Operations', 'Ammallar')}
</span>
<ChevronDown
size={15}
className={`text-muted-foreground transition-transform duration-200 ${opsExpanded ? 'rotate-180' : ''}`}
/>
</button>
{opsExpanded && (
<>
<div className="overflow-x-auto border-t border-border">
<table className="w-full text-sm">
<thead>
<tr className="bg-muted/30 border-b border-border">
{[
t('ID', 'ID'),
t('Action name', 'AMALYŇ ADY'),
t('Performed by', 'KIM TARAPYNDAN'),
t('Target', 'AMALYŇ NYŞANY (TARGEDI)'),
t('Status', 'AMALYŇ STATUSY'),
t('Date', 'SENE'),
].map((h) => (
<th
key={h}
className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase tracking-wide whitespace-nowrap"
>
{h}
</th>
))}
</tr>
</thead>
<tbody>
{operations.length === 0 ? (
<tr>
<td colSpan={6} className="text-center py-10 text-muted-foreground text-sm">
{t('No operations found', 'Amal tapylmady')}
</td>
</tr>
) : (
operations.map((op) => (
<tr key={op.id} className="border-b border-border/50 hover:bg-muted/20 transition-colors">
<td className="px-4 py-3 text-primary font-medium">{op.id}</td>
<td className="px-4 py-3">{op.action_name}</td>
<td className="px-4 py-3">{op.performed_by}</td>
<td className="px-4 py-3">{op.target}</td>
<td className="px-4 py-3"><OpStatusBadge status={op.status} /></td>
<td className="px-4 py-3 text-muted-foreground">{op.date}</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Ops pagination */}
<div className="flex items-center justify-between px-4 py-2.5 border-t border-border text-sm text-muted-foreground">
<Button variant="ghost" size="sm" disabled={opsPage <= 1} onClick={() => setOpsPage((p) => p - 1)}>
{t('Previous', 'Öňki')}
</Button>
<span>
{opsTotal === 0 ? '0' : `1–${opsTotal}`} {t('of', 'of')} {opsTotal}
</span>
<Button variant="ghost" size="sm" disabled={true}>
{t('Next', 'Indiki')}
</Button>
</div>
</>
)}
</div>
{/* Delete dialog */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Are you sure?', 'Eminsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t(
'This action cannot be undone.',
'Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.',
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,287 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
import { DataTable } from "@/components/dataTable";
import { DataTableToolbar } from "@/components/dataTableToolbar";
import { useCardPins } from "@/features/cardPins/hooks/useCardPins";
import { useDeleteCardPin } from "@/features/cardPins/hooks/useCardPins";
import type {
CardPinItem,
CardPinStatus,
} from "@/features/cardPins/api/cardPinApi";
import { Button } from "@/components/ui/button";
import { Eye, Pencil, Trash2 } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { cn } from "@/lib/utils";
// ─── Status Badge ─────────────────────────────────────────────────────────────
const STATUS_MAP: Record<CardPinStatus, { label: string; className: string }> =
{
pending: {
label: "Garaşylýar",
className: "bg-yellow-500/20 text-yellow-400 border-yellow-500/30",
},
approved: {
label: "Tassyklandy",
className: "bg-green-500/20 text-green-400 border-green-500/30",
},
rejected: {
label: "Ret edildi",
className: "bg-red-500/20 text-red-400 border-red-500/30",
},
};
function StatusBadge({ status }: { status: CardPinStatus }) {
const cfg = STATUS_MAP[status] ?? STATUS_MAP.pending;
return (
<span
className={cn(
"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold border",
cfg.className,
)}
>
{cfg.label}
</span>
);
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardPinsPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(25);
const [search, setSearch] = useState("");
const [statusFilter, setStatusFilter] = useState<CardPinStatus | "">("");
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
const [columnOrder, setColumnOrder] = useState<string[]>([]);
const [deleteTarget, setDeleteTarget] = useState<CardPinItem | null>(null);
const { data, isLoading } = useCardPins({
page,
per_page: perPage,
search,
status: statusFilter,
});
const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin();
const columns: ColumnDef<CardPinItem>[] = [
{
accessorKey: "id",
header: "ID",
cell: ({ row }) => (
<span className="font-mono text-xs text-muted-foreground">
{row.original.id}
</span>
),
},
{
accessorKey: "card_type_label",
header: t("cardPin.cardType", "Görnüşi"),
cell: ({ row }) => (
<span className="text-sm font-medium text-primary">
{row.original.card_type_label}
</span>
),
},
{
accessorKey: "created_at",
header: t("cardPin.createdAt", "Döredilen wagty"),
cell: ({ row }) => (
<span className="text-sm text-muted-foreground whitespace-nowrap">
{row.original.created_at}
</span>
),
},
{
accessorKey: "province_label",
header: t("cardPin.province", "Welaýat"),
},
{
accessorKey: "branch_label",
header: t("cardPin.branch", "Şahamça"),
cell: ({ row }) => (
<span className="text-primary font-medium">
{row.original.branch_label}
</span>
),
},
{
accessorKey: "first_name",
header: t("cardPin.firstName", "Ady"),
},
{
accessorKey: "last_name",
header: t("cardPin.lastName", "Familiýasy"),
},
{
accessorKey: "phone",
header: t("cardPin.phone", "Telefon"),
cell: ({ row }) => (
<span className="font-mono text-sm">{row.original.phone}</span>
),
},
{
accessorKey: "status",
header: t("cardPin.status", "Status"),
cell: ({ row }) => <StatusBadge status={row.original.status} />,
},
{
id: "actions",
enableHiding: false,
cell: ({ row }) => (
<div className="flex items-center gap-1">
<Button
size="icon"
variant="ghost"
className="h-7 w-7"
onClick={() => navigate(`/card-pins/${row.original.id}`)}
>
<Eye size={14} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7"
onClick={() => navigate(`/card-pins/${row.original.id}/edit`)}
>
<Pencil size={14} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteTarget(row.original)}
>
<Trash2 size={14} />
</Button>
</div>
),
},
];
const columnMeta = columns
.filter((c) => "accessorKey" in c && c.id !== "actions")
.map((c) => ({
id: ("accessorKey" in c ? String(c.accessorKey) : c.id) as string,
label:
typeof c.header === "string" ? c.header : String(c.accessorKey ?? ""),
}));
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t("Card pins", "Kart pin bukjalary")}
</h1>
</div>
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => {
setSearch(v);
setPage(1);
}}
searchPlaceholder={t("cardPin.search", "Gözlemek")}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
filterFields={[
{
id: "status",
label: t("cardPin.status", "Status"),
options: [
{ value: "pending", label: "Garaşylýar" },
{ value: "approved", label: "Tassyklandy" },
{ value: "rejected", label: "Ret edildi" },
],
},
]}
activeFilters={[{ fieldId: "status", value: statusFilter }]}
onFilterChange={(fieldId, value) => {
if (fieldId === "status")
setStatusFilter(value as CardPinStatus | "");
setPage(1);
}}
onFilterReset={() => {
setStatusFilter("");
setPage(1);
}}
perPage={perPage}
onPerPageChange={(v) => {
setPerPage(v);
setPage(1);
}}
actionLabel={t("cardPin.createBtn", "Kart pin bukja dörediň")}
onAction={() => navigate("/card-pins/create")}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
currentPage={data?.meta?.current_page ?? 1}
totalPages={data?.meta?.last_page ?? 1}
totalCount={data?.meta?.total}
onPageChange={setPage}
/>
{/* Delete confirmation */}
<AlertDialog
open={!!deleteTarget}
onOpenChange={(o) => !o && setDeleteTarget(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("cardPin.deleteTitle", "Pozmak isleýärsiňizmi?")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("cardPin.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")}{" "}
{deleteTarget?.id}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>
{t("common.cancel", "Ýatyr")}
</AlertDialogCancel>
<AlertDialogAction
disabled={isDeleting}
className="bg-destructive hover:bg-destructive/90"
onClick={() => {
if (deleteTarget) {
deletePin(deleteTarget.id, {
onSuccess: () => setDeleteTarget(null),
});
}
}}
>
{t("common.delete", "Poz")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -0,0 +1,23 @@
import { useNavigate } from 'react-router-dom'
import { CardPinForm } from '@/features/cardPins/components/cardPinForm'
import { useCreateCardPin } from '@/features/cardPins/hooks/useCardPins'
import type { CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi'
export default function CardPinCreatePage() {
const navigate = useNavigate()
const { mutate: createPin, isPending } = useCreateCardPin()
const handleSubmit = (payload: CardPinCreatePayload) => {
createPin(payload, {
onSuccess: (data) => navigate(`/card-pins/${data.id}`),
})
}
return (
<CardPinForm
mode="create"
onSubmit={handleSubmit}
isSubmitting={isPending}
/>
)
}

View File

@@ -0,0 +1,46 @@
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { CardPinForm } from '@/features/cardPins/components/cardPinForm'
import { useCardPin, useUpdateCardPin } from '@/features/cardPins/hooks/useCardPins'
import type { CardPinUpdatePayload } from '@/features/cardPins/api/cardPinApi'
import { Spinner } from '@/components/ui/spinner'
export default function CardPinEditPage() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { t } = useTranslation()
const { data, isLoading, isError } = useCardPin(id!)
const { mutate: updatePin, isPending } = useUpdateCardPin(id!)
const handleSubmit = (payload: CardPinUpdatePayload) => {
updatePin(payload, {
onSuccess: () => navigate(`/card-pins/${id}`),
})
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-8 text-primary" />
</div>
)
}
if (isError || !data) {
return (
<div className="flex items-center justify-center py-24 text-muted-foreground">
{t('common.notFound', 'Maglumat tapylmady')}
</div>
)
}
return (
<CardPinForm
mode="edit"
initialData={data}
onSubmit={handleSubmit}
isSubmitting={isPending}
/>
)
}

View File

@@ -0,0 +1,245 @@
import { useParams, useNavigate, Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useCardPin, useDeleteCardPin } from '@/features/cardPins/hooks/useCardPins'
import type { CardPinStatus } from '@/features/cardPins/api/cardPinApi'
import { Spinner } from '@/components/ui/spinner'
import { Button } from '@/components/ui/button'
import { Pencil, Trash2, Download } from 'lucide-react'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { cn } from '@/lib/utils'
// ─── Status Badge ─────────────────────────────────────────────────────────────
const STATUS_MAP: Record<CardPinStatus, { label: string; className: string }> = {
pending: { label: 'Garaşylýar', className: 'bg-yellow-500/20 text-yellow-500 border-yellow-500/30' },
approved: { label: 'Tassyklandy', className: 'bg-green-500/20 text-green-500 border-green-500/30' },
rejected: { label: 'Ret edildi', className: 'bg-red-500/20 text-red-500 border-red-500/30' },
}
function StatusBadge({ status }: { status: CardPinStatus }) {
const cfg = STATUS_MAP[status] ?? STATUS_MAP.pending
return (
<span className={cn('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold border', cfg.className)}>
<span className="w-1.5 h-1.5 rounded-full bg-current" />
{cfg.label}
</span>
)
}
// ─── Field row ────────────────────────────────────────────────────────────────
function FieldRow({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="grid grid-cols-[200px_1fr] items-start py-3 border-b border-border last:border-0 gap-4">
<span className="text-sm text-muted-foreground">{label}</span>
<span className="text-sm text-foreground">{children}</span>
</div>
)
}
// ─── Passport image ───────────────────────────────────────────────────────────
function PassportImage({ label, url }: { label: string; url: string | null }) {
if (!url) return null
return (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">{label}</p>
<div className="border border-border rounded-lg overflow-hidden inline-block">
<img
src={url}
alt={label}
className="max-w-[200px] max-h-[160px] object-cover block"
/>
<div className="px-3 py-2 bg-muted/40 border-t border-border">
<a
href={url}
download
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
<Download size={12} />
Göçürip al
</a>
</div>
</div>
</div>
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardPinViewPage() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { t } = useTranslation()
const { data, isLoading, isError } = useCardPin(id!)
const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin()
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-8 text-primary" />
</div>
)
}
if (isError || !data) {
return (
<div className="flex items-center justify-center py-24 text-muted-foreground">
{t('common.notFound', 'Maglumat tapylmady')}
</div>
)
}
return (
<div className="max-w-4xl mx-auto space-y-6">
{/* Header */}
<div className="flex items-start justify-between">
<h1 className="text-xl font-bold text-foreground">
{t('cardPin.viewTitle', 'Kart pin bukja giňişleýin')}: {data.id}
</h1>
<div className="flex items-center gap-2">
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="icon" variant="ghost" className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10">
<Trash2 size={15} />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('cardPin.deleteTitle', 'Pozmak isleýärsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t('cardPin.deleteDesc', 'Bu amal yzyna dolanyp bolmaz.')} {data.id}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>
{t('common.cancel', 'Ýatyr')}
</AlertDialogCancel>
<AlertDialogAction
disabled={isDeleting}
className="bg-destructive hover:bg-destructive/90"
onClick={() => deletePin(data.id, { onSuccess: () => navigate('/card-pins') })}
>
{t('common.delete', 'Poz')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Button
size="icon"
variant="ghost"
className="h-8 w-8"
onClick={() => navigate(`/card-pins/${id}/edit`)}
>
<Pencil size={15} />
</Button>
</div>
</div>
{/* Main Info */}
<section className="bg-card border border-border rounded-lg px-6">
<FieldRow label="ID">
<span className="font-mono">{data.id}</span>
</FieldRow>
<FieldRow label={t('cardPin.createdAt', 'Döredilen wagty')}>
{data.created_at}
</FieldRow>
<FieldRow label={t('cardPin.status', 'Status')}>
<StatusBadge status={data.status} />
</FieldRow>
<FieldRow label={t('cardPin.note', 'Bellik')}>
{data.note || '—'}
</FieldRow>
<FieldRow label={t('cardPin.createdBy', 'Sargyt eden')}>
<span className="text-primary font-medium">{data.created_by_label}</span>
</FieldRow>
</section>
{/* Kart */}
<section className="bg-card border border-border rounded-lg px-6 py-4">
<h2 className="text-base font-semibold text-foreground mb-2">
{t('cardPin.cardSection', 'Kart')}
</h2>
<div className="divide-y divide-border">
<FieldRow label={t('cardPin.cardNumber', 'Kart belgisi')}>
<span className="font-mono tracking-wider">{data.card_number}</span>
</FieldRow>
<FieldRow label={t('cardPin.cardExpireMonth', 'Kart Möhleti (aý)')}>—</FieldRow>
<FieldRow label={t('cardPin.cardExpireYear', 'Kart Möhleti (ýyl)')}>—</FieldRow>
</div>
</section>
{/* Lokasiýa */}
<section className="bg-card border border-border rounded-lg px-6 py-4">
<h2 className="text-base font-semibold text-foreground mb-2">
{t('cardPin.locationSection', 'Lokasiýa')}
</h2>
<div className="divide-y divide-border">
<FieldRow label={t('cardPin.province', 'Welaýat')}>{data.province_label}</FieldRow>
<FieldRow label={t('cardPin.branch', 'Şahamça')}>
<span className="text-primary font-medium">{data.branch_label}</span>
</FieldRow>
</div>
</section>
{/* Şahsy maglumatlar */}
<section className="bg-card border border-border rounded-lg px-6 py-4">
<h2 className="text-base font-semibold text-foreground mb-2">
{t('cardPin.personalSection', 'Şahsy maglumatlar')}
</h2>
<div className="divide-y divide-border">
<FieldRow label={t('cardPin.fullName', 'Doly ady')}>
{`${data.last_name} ${data.first_name} ${data.father_name}`}
</FieldRow>
<FieldRow label={t('cardPin.birthDate', 'Doglan güni')}>{data.birth_date}</FieldRow>
<FieldRow label={t('cardPin.phone', 'Telefon')}>+{data.phone}</FieldRow>
</div>
</section>
{/* Pasport */}
<section className="bg-card border border-border rounded-lg px-6 py-4">
<h2 className="text-base font-semibold text-foreground mb-2">
{t('cardPin.passportSection', 'Pasport')}
</h2>
<div className="divide-y divide-border mb-4">
<FieldRow label={t('cardPin.passportSeries', 'Pasport seriýasy')}>
{data.passport_series}
</FieldRow>
<FieldRow label={t('cardPin.passportNumber', 'Pasport belgisi')}>
{data.passport_number}
</FieldRow>
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
<PassportImage
label={t('cardPin.passportFile1', 'Pasport (sahypa 1)')}
url={data.passport_file_1}
/>
<PassportImage
label={t('cardPin.passportFile2', 'Pasport (2-3-nji sahypa)')}
url={data.passport_file_2}
/>
<PassportImage
label={t('cardPin.passportFile3', 'Pasport (8-9 sahypa)')}
url={data.passport_file_3}
/>
<PassportImage
label={t('cardPin.passportFile4', 'Pasport (32-nji sahypa)')}
url={data.passport_file_4}
/>
</div>
</section>
</div>
)
}

View File

@@ -0,0 +1,252 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Download, Eye, 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 { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar, type ColumnMeta } from '@/components/dataTableToolbar'
import type { VisibilityState } from '@tanstack/react-table'
import {
useCardRequisites,
useDeleteCardRequisite,
useDownloadCardRequisite,
} from '@/features/cardRequisites/hooks/useCardRequisites'
import type { CardRequisite, CardRequisiteStatus } from '@/features/cardRequisites/api/cardRequisitesApi'
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_BADGE: Record<CardRequisiteStatus, { label: string; className: string }> = {
pending: { label: 'Garaşylýar', className: 'bg-yellow-500/15 text-yellow-500 border-yellow-500/20' },
approved: { label: 'Tassyklanan', className: 'bg-emerald-500/15 text-emerald-500 border-emerald-500/20' },
rejected: { label: 'Ret edilen', className: 'bg-red-500/15 text-red-500 border-red-500/20' },
}
function StatusBadge({ status }: { status: CardRequisiteStatus }) {
const cfg = STATUS_BADGE[status] ?? STATUS_BADGE.pending
return (
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${cfg.className}`}>
{cfg.label}
</span>
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
const PER_PAGE = 25
export default function CardRequisitesPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(PER_PAGE)
const [search, setSearch] = useState('')
const [deleteId, setDeleteId] = useState<string | null>(null)
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>([])
const { data, isLoading } = useCardRequisites({ page, per_page: perPage, search })
const deleteMutation = useDeleteCardRequisite()
const downloadMutation = useDownloadCardRequisite()
// ── Columns ──────────────────────────────────────────────────────────────────
const columns: ColumnDef<CardRequisite>[] = [
{
id: 'id',
accessorKey: 'id',
header: t('ID', 'ID'),
cell: ({ row }) => (
<button
className="text-primary font-medium hover:underline text-left"
onClick={() => navigate(`/card-requisites/${row.original.id}`)}
>
{row.original.id}
</button>
),
},
{
id: 'card_type',
accessorKey: 'card_type',
header: t('Card type', 'GÖRNÜŞI'),
cell: ({ row }) => (
<span className="text-primary font-medium">{row.original.card_type}</span>
),
},
{
id: 'created_at',
accessorKey: 'created_at',
header: t('Created at', 'DÖREDILEN WAGTY'),
cell: ({ row }) => (
<span className="text-foreground">{row.original.created_at}</span>
),
},
{
id: 'province_name',
accessorKey: 'province_name',
header: t('Province', 'WELAÝAT'),
cell: ({ row }) => (
<span className="text-foreground">{row.original.province_name ?? '—'}</span>
),
},
{
id: 'branch_name',
accessorKey: 'branch_name',
header: t('Branch', 'ŞAHAMÇA'),
cell: ({ row }) => (
<span className="text-primary font-medium">{row.original.branch_name ?? '—'}</span>
),
},
{
id: 'first_name',
accessorKey: 'first_name',
header: t('First name', 'ADY'),
cell: ({ row }) => <span>{row.original.first_name}</span>,
},
{
id: 'last_name',
accessorKey: 'last_name',
header: t('Last name', 'FAMILIÝASY'),
cell: ({ row }) => <span>{row.original.last_name}</span>,
},
{
id: 'status',
accessorKey: 'status',
header: t('Status', 'STATUS'),
cell: ({ row }) => <StatusBadge status={row.original.status} />,
},
{
id: 'actions',
header: '',
enableHiding: false,
cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end">
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => downloadMutation.mutate(row.original.id)}
>
<Download size={14} />
</Button>
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => navigate(`/card-requisites/${row.original.id}`)}
>
<Eye size={14} />
</Button>
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => navigate(`/card-requisites/${row.original.id}/edit`)}
>
<Pencil size={14} />
</Button>
<Button
variant="ghost" size="icon"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteId(row.original.id)}
>
<Trash2 size={14} />
</Button>
</div>
),
},
]
// ── Column meta for toolbar ───────────────────────────────────────────────────
const columnMeta: ColumnMeta[] = columns
.filter((c) => c.id !== 'actions')
.map((c) => ({
id: c.id!,
label: typeof c.header === 'string' ? c.header : c.id!,
}))
// ── Pagination ────────────────────────────────────────────────────────────────
const total = data?.total ?? 0
const totalPages = Math.ceil(total / perPage)
const handleDelete = async () => {
if (!deleteId) return
await deleteMutation.mutateAsync(deleteId)
setDeleteId(null)
}
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t('Card requisites', 'Kart rekwizitler')}
</h1>
</div>
{/* Toolbar */}
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { setSearch(v); setPage(1) }}
searchPlaceholder={t('Search', 'Gözlemek')}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
actionLabel={t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň')}
onAction={() => navigate('/card-requisites/create')}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
/>
{/* Table */}
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => row.id}
currentPage={page}
totalPages={totalPages}
totalCount={total}
onPageChange={setPage}
/>
{/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Are you sure?', 'Eminsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t(
'This action cannot be undone.',
'Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.',
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,15 @@
import { useTranslation } from 'react-i18next'
import { CardRequisiteForm } from '@/features/cardRequisites/components/cardRequisiteForm'
export default function CardRequisiteCreatePage() {
const { t } = useTranslation()
return (
<div className="space-y-4">
<h1 className="text-xl font-semibold text-foreground">
{t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň dörediň')}
</h1>
<CardRequisiteForm mode="create" />
</div>
)
}

View File

@@ -0,0 +1,41 @@
import { useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Spinner } from '@/components/ui/spinner'
import { CardRequisiteForm } from '@/features/cardRequisites/components/cardRequisiteForm'
import { useCardRequisite } from '@/features/cardRequisites/hooks/useCardRequisites'
export default function CardRequisiteEditPage() {
const { t } = useTranslation()
const { id } = useParams<{ id: string }>()
const { data, isLoading } = useCardRequisite(id ?? '')
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-7 text-primary" />
</div>
)
}
if (!data) {
return (
<div className="text-center py-24 text-muted-foreground">
{t('Not found', 'Tapylmady')}
</div>
)
}
return (
<div className="space-y-4">
<h1 className="text-xl font-semibold text-foreground">
{t('Edit card requisite', 'Kart rekwizitini üýtget')}
</h1>
<CardRequisiteForm
mode="edit"
initialData={data}
cardRequisiteId={data.id}
/>
</div>
)
}

View File

@@ -0,0 +1,254 @@
import { useState } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Download, Trash2, Pencil, DownloadCloud } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
useCardRequisite,
useDeleteCardRequisite,
useDownloadCardRequisite,
} from '@/features/cardRequisites/hooks/useCardRequisites'
import type { CardRequisiteStatus } from '@/features/cardRequisites/api/cardRequisitesApi'
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_BADGE: Record<CardRequisiteStatus, { label: string; className: string }> = {
pending: { label: 'GARAŞYLÝAR', className: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30' },
approved: { label: 'TASSYKLANAN', className: 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/30' },
rejected: { label: 'RET EDILEN', className: 'bg-red-500/20 text-red-400 border border-red-500/30' },
}
// ─── Detail row ───────────────────────────────────────────────────────────────
function DetailRow({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
return (
<div className="grid grid-cols-[220px_1fr] border-b border-border/50 last:border-0">
<div className="px-4 py-3 text-sm text-muted-foreground font-medium bg-muted/10">
{label}
</div>
<div className="px-4 py-3 text-sm text-foreground">{children}</div>
</div>
)
}
// ─── Section header ───────────────────────────────────────────────────────────
function SectionTitle({ children }: { children: React.ReactNode }) {
return (
<h2 className="text-base font-semibold text-foreground mt-6 mb-3">{children}</h2>
)
}
// ─── Passport image row ───────────────────────────────────────────────────────
function PassportImageRow({ label, url }: { label: string; url?: string }) {
return (
<div className="grid grid-cols-[220px_1fr] border-b border-border/50 last:border-0">
<div className="px-4 py-3 text-sm text-muted-foreground font-medium bg-muted/10">
{label}
</div>
<div className="px-4 py-4 flex flex-col gap-2">
{url ? (
<>
<img
src={url}
alt={label}
className="max-w-[200px] rounded-md border border-border object-cover"
/>
<a
href={url}
download
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors w-fit"
>
<DownloadCloud size={13} />
{('Download', 'Göçürip al')}
</a>
</>
) : (
<span className="text-muted-foreground text-sm">—</span>
)}
</div>
</div>
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardRequisiteViewPage() {
const { t } = useTranslation()
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const [deleteOpen, setDeleteOpen] = useState(false)
const { data, isLoading } = useCardRequisite(id ?? '')
const deleteMutation = useDeleteCardRequisite()
const downloadMutation = useDownloadCardRequisite()
const handleDelete = async () => {
await deleteMutation.mutateAsync(id ?? '')
navigate('/card-requisites')
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-7 text-primary" />
</div>
)
}
if (!data) {
return (
<div className="text-center py-24 text-muted-foreground">
{t('Not found', 'Tapylmady')}
</div>
)
}
const statusCfg = STATUS_BADGE[data.status] ?? STATUS_BADGE.pending
return (
<div className="space-y-0">
{/* Header */}
<div className="flex items-center justify-between mb-4">
<h1 className="text-xl font-semibold text-foreground">
{t('Card requisite detail', 'Kart rekwizit giňişleýin')}: {data.id}
</h1>
<div className="flex items-center gap-2">
<Button
variant="outline" size="sm"
onClick={() => downloadMutation.mutate(data.id)}
disabled={downloadMutation.isPending}
>
<Download size={14} />
</Button>
<Button
variant="outline" size="sm"
className="text-destructive border-destructive/30 hover:bg-destructive/10"
onClick={() => setDeleteOpen(true)}
>
<Trash2 size={14} />
</Button>
<Button variant="outline" size="sm" asChild>
<Link to={`/card-requisites/${data.id}/edit`}>
<Pencil size={14} />
</Link>
</Button>
</div>
</div>
{/* General info */}
<div className="rounded-lg border border-border bg-card overflow-hidden">
<DetailRow label={t('ID', 'ID')}>{data.id}</DetailRow>
<DetailRow label={t('Created at', 'Döredilen wagty')}>{data.created_at}</DetailRow>
<DetailRow label={t('Status', 'Status')}>
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold ${statusCfg.className}`}>
{statusCfg.label}
</span>
</DetailRow>
<DetailRow label={t('Note', 'Bellik')}>
{data.note || '—'}
</DetailRow>
<DetailRow label={t('Requested by', 'Sargyt eden:')}>
{data.first_name && data.last_name ? (
<span className="text-primary font-medium">
{data.last_name}_{data.first_name} ({data.first_name})
</span>
) : '—'}
</DetailRow>
</div>
{/* Card */}
<SectionTitle>{t('Card', 'Kart')}</SectionTitle>
<div className="rounded-lg border border-border bg-card overflow-hidden">
<DetailRow label={t('Card number', 'Kart belgisi')}>{data.card_number}</DetailRow>
<DetailRow label={t('Card expiry month', 'Kart Möhleti (aý)')}>{data.card_expiry_month}</DetailRow>
<DetailRow label={t('Card expiry year', 'Kart Möhleti (ýyl)')}>{data.card_expiry_year}</DetailRow>
</div>
{/* Location */}
<SectionTitle>{t('Location', 'Lokasiýa')}</SectionTitle>
<div className="rounded-lg border border-border bg-card overflow-hidden">
<DetailRow label={t('Province', 'Welaýat')}>{data.province_name ?? '—'}</DetailRow>
<DetailRow label={t('Branch', 'Şahamça')}>
<span className="text-primary font-medium">{data.branch_name ?? '—'}</span>
</DetailRow>
</div>
{/* Personal */}
<SectionTitle>{t('Personal information', 'Şahsy maglumatlar')}</SectionTitle>
<div className="rounded-lg border border-border bg-card overflow-hidden">
<DetailRow label={t('Full name', 'Doly ady')}>
{[data.first_name, data.last_name, data.middle_name].filter(Boolean).join(' ')}
</DetailRow>
<DetailRow label={t('Birth date', 'Doglan güni')}>{data.birth_date}</DetailRow>
<DetailRow label={t('Phone', 'Telefon')}>{data.phone}</DetailRow>
</div>
{/* Passport */}
<SectionTitle>{t('Passport', 'Pasport')}</SectionTitle>
<div className="rounded-lg border border-border bg-card overflow-hidden">
<DetailRow label={t('Passport series', 'Pasport seriýasy')}>{data.passport_series}</DetailRow>
<DetailRow label={t('Passport number', 'Pasport belgisi')}>{data.passport_number}</DetailRow>
<PassportImageRow
label={t('Passport (page 1)', 'Pasport (sahypa 1)')}
url={data.passport_page1_url}
/>
<PassportImageRow
label={t('Passport (pages 2-3)', 'Pasport (2-3-nji sahypa)')}
url={data.passport_page2_3_url}
/>
<PassportImageRow
label={t('Passport (pages 8-9)', 'Pasport (8-9 sahypa)')}
url={data.passport_page8_9_url}
/>
<PassportImageRow
label={t('Passport (page 32)', 'Pasport (32-nji sahypa)')}
url={data.passport_page32_url}
/>
</div>
{/* Delete dialog */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Are you sure?', 'Eminsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t(
'This action cannot be undone.',
'Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.',
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,219 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Download, Eye, 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 { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar, type ColumnMeta } from '@/components/dataTableToolbar'
import type { VisibilityState } from '@tanstack/react-table'
import {
useCardTransactions,
useDeleteCardTransaction,
useDownloadCardTransaction,
} from '@/features/cardTransactions/hooks/useCardTransactions'
import type { CardTransaction } from '@/features/cardTransactions/api/cardTransactionsApi'
// ─── Page ─────────────────────────────────────────────────────────────────────
const PER_PAGE = 25
export default function CardTransactionsPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(PER_PAGE)
const [search, setSearch] = useState('')
const [deleteId, setDeleteId] = useState<number | null>(null)
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>([])
const { data, isLoading } = useCardTransactions({ page, per_page: perPage, search })
const deleteMutation = useDeleteCardTransaction()
const downloadMutation = useDownloadCardTransaction()
// ── Columns ──────────────────────────────────────────────────────────────────
const columns: ColumnDef<CardTransaction>[] = [
{
id: 'id',
accessorKey: 'id',
header: t('ID', 'ID'),
cell: ({ row }) => (
<button
className="text-primary font-medium hover:underline text-left"
onClick={() => navigate(`/card-transactions/${row.original.id}`)}
>
{row.original.id}
</button>
),
},
{
id: 'passport_series',
accessorKey: 'passport_series',
header: t('Passport series', 'PASPORT SERIYASY'),
cell: ({ row }) => <span>{row.original.passport_series}</span>,
},
{
id: 'passport_number',
accessorKey: 'passport_number',
header: t('Passport number', 'PASPORT BELGISI'),
cell: ({ row }) => <span>{row.original.passport_number}</span>,
},
{
id: 'card_number',
accessorKey: 'card_number',
header: t('Card number', 'KART BELGISI'),
cell: ({ row }) => <span className="font-mono">{row.original.card_number}</span>,
},
{
id: 'card_expiry_month',
accessorKey: 'card_expiry_month',
header: t('Expiry month', 'KART MÖHLETI (AÝ)'),
cell: ({ row }) => <span>{row.original.card_expiry_month}</span>,
},
{
id: 'card_expiry_year',
accessorKey: 'card_expiry_year',
header: t('Expiry year', 'KART MÖHLETI (ÝYL)'),
cell: ({ row }) => <span>{row.original.card_expiry_year}</span>,
},
{
id: 'actions',
header: '',
enableHiding: false,
cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end">
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => downloadMutation.mutate(row.original.id)}
title={t('Download', 'Ýükle')}
>
<Download size={14} />
</Button>
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => navigate(`/card-transactions/${row.original.id}`)}
title={t('View', 'Görmek')}
>
<Eye size={14} />
</Button>
<Button
variant="ghost" size="icon" className="h-7 w-7"
onClick={() => navigate(`/card-transactions/${row.original.id}/edit`)}
title={t('Edit', 'Üýtgetmek')}
>
<Pencil size={14} />
</Button>
<Button
variant="ghost" size="icon"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteId(row.original.id)}
title={t('Delete', 'Öçürmek')}
>
<Trash2 size={14} />
</Button>
</div>
),
},
]
// ── Column meta for toolbar ───────────────────────────────────────────────────
const columnMeta: ColumnMeta[] = columns
.filter((c) => c.id !== 'actions')
.map((c) => ({
id: c.id!,
label: typeof c.header === 'string' ? c.header : c.id!,
}))
// ── Pagination ────────────────────────────────────────────────────────────────
const total = data?.total ?? 0
const totalPages = Math.ceil(total / perPage)
const handleDelete = async () => {
if (deleteId === null) return
await deleteMutation.mutateAsync(deleteId)
setDeleteId(null)
}
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t('Card transactions', 'Kart hereketleri')}
</h1>
</div>
{/* Toolbar */}
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { setSearch(v); setPage(1) }}
searchPlaceholder={t('Search', 'Gözlemek')}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
actionLabel={t('Create card transaction', 'Kart herekedi dörediň')}
onAction={() => navigate('/card-transactions/create')}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
/>
{/* Table */}
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => row.id.toString()}
currentPage={page}
totalPages={totalPages}
totalCount={total}
onPageChange={setPage}
/>
{/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Are you sure?', 'Eminsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t(
'This action cannot be undone. This will permanently delete the card transaction.',
'Bu amal yzyna gaýtarylmaz. Kart herekedi hemişelik öçüriler.',
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,15 @@
import { useTranslation } from 'react-i18next'
import { CardTransactionForm } from '@/features/cardTransactions/components/cardTransactionForm'
export default function CardTransactionCreatePage() {
const { t } = useTranslation()
return (
<div className="space-y-4">
<h1 className="text-xl font-semibold text-foreground">
{t('Create card transaction', 'Kart herekedi dörediň')}
</h1>
<CardTransactionForm mode="create" />
</div>
)
}

View File

@@ -0,0 +1,42 @@
import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Spinner } from "@/components/ui/spinner";
import { CardTransactionForm } from "@/features/cardTransactions/components/cardTransactionForm";
import { useCardTransaction } from "@/features/cardTransactions/hooks/useCardTransactions";
export default function CardTransactionEditPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const numericId = Number(id);
const { data, isLoading } = useCardTransaction(numericId);
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-7 text-primary" />
</div>
);
}
if (!data) {
return (
<div className="text-center py-24 text-muted-foreground">
{t("Not found", "Tapylmady")}
</div>
);
}
return (
<div className="space-y-4">
<h1 className="text-xl font-semibold text-foreground">
{t("Edit card transaction", "Kart herekedini üýtget")}
</h1>
<CardTransactionForm
mode="edit"
initialData={data}
cardTransactionId={numericId}
/>
</div>
);
}

View File

@@ -0,0 +1,146 @@
import { useState } from 'react'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Download, Trash2, Pencil } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
useCardTransaction,
useDeleteCardTransaction,
useDownloadCardTransaction,
} from '@/features/cardTransactions/hooks/useCardTransactions'
// ─── Detail row ───────────────────────────────────────────────────────────────
function DetailRow({ label, value }: { label: string; value: string | number }) {
return (
<div className="grid grid-cols-[220px_1fr] border-b border-border/50 last:border-0">
<div className="px-4 py-3 text-sm text-muted-foreground font-medium bg-muted/10">
{label}
</div>
<div className="px-4 py-3 text-sm text-foreground">{value}</div>
</div>
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardTransactionViewPage() {
const { t } = useTranslation()
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()
const downloadMutation = useDownloadCardTransaction()
const handleDelete = async () => {
await deleteMutation.mutateAsync(numericId)
navigate('/card-transactions')
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-7 text-primary" />
</div>
)
}
if (!data) {
return (
<div className="text-center py-24 text-muted-foreground">
{t('Not found', 'Tapylmady')}
</div>
)
}
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t('Card transaction detail', 'Kart herekedi giňişleýin')}:
</h1>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="gap-1.5"
onClick={() => downloadMutation.mutate(numericId)}
disabled={downloadMutation.isPending}
>
<Download size={14} />
</Button>
<Button
variant="outline"
size="sm"
className="gap-1.5 text-destructive border-destructive/30 hover:bg-destructive/10"
onClick={() => setDeleteOpen(true)}
>
<Trash2 size={14} />
</Button>
<Button
variant="outline"
size="sm"
className="gap-1.5"
asChild
>
<Link to={`/card-transactions/${numericId}/edit`}>
<Pencil size={14} />
</Link>
</Button>
</div>
</div>
{/* Detail card */}
<div className="rounded-lg border border-border bg-card overflow-hidden">
<DetailRow label={t('ID', 'ID')} value={data.id} />
<DetailRow label={t('Passport series', 'Pasport seriýasy')} value={data.passport_series} />
<DetailRow label={t('Passport number', 'Pasport belgisi')} value={data.passport_number} />
<DetailRow label={t('Card number', 'Kart belgisi')} value={data.card_number} />
<DetailRow label={t('Card expiry month', 'Kart Möhleti (aý)')} value={data.card_expiry_month} />
<DetailRow label={t('Card expiry year', 'Kart Möhleti (ýyl)')} value={data.card_expiry_year} />
</div>
{/* Delete dialog */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Are you sure?', 'Eminsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t(
'This action cannot be undone. This will permanently delete the card transaction.',
'Bu amal yzyna gaýtarylmaz. Kart herekedi hemişelik öçüriler.',
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending
? t('Deleting...', 'Öçürilýär...')
: t('Delete', 'Öçür')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,213 @@
import { useState, useMemo, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Eye, Pencil, Trash2 } from 'lucide-react'
import type { VisibilityState } from '@tanstack/react-table'
import { DataTable } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import type { ActiveFilter, FilterField } from '@/components/dataTableToolbar'
import {
useCardOrders,
useDeleteCardOrder,
useProvinces,
useBranches,
} from '@/features/orderNewCard/hooks/useOrderNewCard'
import { useCardOrderColumns } from '@/features/orderNewCard/components/orderNewCardTable'
import type { CardOrderStatus } from '@/features/orderNewCard/api/orderNewCardApi'
// ─── Column meta list (for toolbar toggle) ────────────────────────────────────
const COLUMN_META = [
{ id: 'id', label: 'ID' },
{ id: 'issuanceReasonName', label: 'Sebäp' },
{ id: 'createdAt', label: 'Döredilen wagty' },
{ id: 'cardTypeName', label: 'Görnüşi' },
{ id: 'provinceName', label: 'Welaýat' },
{ id: 'branchName', label: 'Şahamça' },
{ id: 'fullName', label: 'Ady' },
{ id: 'status', label: 'Status' },
]
const DEFAULT_ORDER = COLUMN_META.map((c) => c.id)
// ─── CardOrdersPage ───────────────────────────────────────────────────────────
export default function CardOrdersPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const deleteMutation = useDeleteCardOrder()
// ── State ──────────────────────────────────────────────────────────────────
const [search, setSearch] = useState('')
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(10)
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>(DEFAULT_ORDER)
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
{ fieldId: 'status', value: '' },
{ fieldId: 'provinceId', value: '' },
{ fieldId: 'branchId', value: '' },
])
// ── Lookup data ────────────────────────────────────────────────────────────
const provinceId = activeFilters.find((f) => f.fieldId === 'provinceId')?.value
const { data: provincesData } = useProvinces()
const { data: branchesData } = useBranches(provinceId ? Number(provinceId) : undefined)
// ── Data ───────────────────────────────────────────────────────────────────
const queryParams = useMemo(() => {
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]))
return {
search: search || undefined,
status: (filterMap.status as CardOrderStatus) || undefined,
provinceId: filterMap.provinceId ? Number(filterMap.provinceId) : undefined,
branchId: filterMap.branchId ? Number(filterMap.branchId) : undefined,
page,
perPage,
}
}, [search, activeFilters, page, perPage])
const { data, isLoading } = useCardOrders(queryParams)
// ── Handlers ───────────────────────────────────────────────────────────────
const handleFilterChange = useCallback((fieldId: string, value: string) => {
setActiveFilters((prev) => {
const newFilters = prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f))
// Reset branch if province changes
if (fieldId === 'provinceId') {
return newFilters.map((f) => (f.fieldId === 'branchId' ? { ...f, value: '' } : f))
}
return newFilters
})
setPage(1)
}, [])
const handleFilterReset = useCallback(() => {
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: '' })))
setPage(1)
}, [])
const handleDelete = useCallback(
(id: string) => {
if (!window.confirm(t('cardOrder.deleteConfirm', 'Bu sargyt pozulsynmy?'))) return
deleteMutation.mutate(id)
},
[deleteMutation, t]
)
// ── Columns ────────────────────────────────────────────────────────────────
const baseColumns = useCardOrderColumns()
const columns = useMemo(
() => [
...baseColumns,
{
id: 'actions',
header: '',
enableHiding: false,
cell: ({ row }: { row: any }) => (
<div className="flex items-center gap-1.5 justify-end">
<button
className="p-1.5 cursor-pointer rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors"
title={t('common.view', 'Görkez')}
onClick={() => navigate(`/order-new-card/${row.original.id}`)}
>
<Eye size={15} />
</button>
<button
className="p-1.5 cursor-pointer rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors"
title={t('common.edit', 'Düzet')}
onClick={() => navigate(`/order-new-card/${row.original.id}/edit`)}
>
<Pencil size={15} />
</button>
<button
onClick={() => handleDelete(row.original.id)}
disabled={deleteMutation.isPending}
className="p-1.5 cursor-pointer rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50"
title={t('common.delete', 'Poz')}
>
<Trash2 size={15} />
</button>
</div>
),
size: 100,
},
],
[baseColumns, t, navigate, handleDelete, deleteMutation.isPending]
)
// ── Filter fields ──────────────────────────────────────────────────────────
const filterFields: FilterField[] = useMemo(() => [
{
id: 'status',
label: t('cardOrder.col.status', 'Status'),
options: [
{ value: 'PENDING', label: t('cardOrder.status.pending', 'Garaşylýar') },
{ value: 'APPROVED', label: t('cardOrder.status.approved', 'Tassyklandy') },
{ value: 'REJECTED', label: t('cardOrder.status.rejected', 'Ýatyryldy') },
],
},
{
id: 'provinceId',
label: t('cardOrder.col.province', 'Welaýat'),
options: provincesData?.map(p => ({ value: String(p.id), label: p.name })) || [],
},
{
id: 'branchId',
label: t('cardOrder.col.branch', 'Şahamça'),
options: branchesData?.map(b => ({ value: String(b.id), label: b.name })) || [],
},
], [t, provincesData, branchesData])
// ── Render ────────────────────────────────────────────────────────────────
return (
<div className="flex flex-col gap-4">
{/* Page Header */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground tracking-tight">
{t('cardOrder.title', 'Kart sargytlary')}
</h1>
</div>
{/* Table Card */}
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { setSearch(v); setPage(1) }}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={COLUMN_META}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
filterFields={filterFields}
activeFilters={activeFilters}
onFilterChange={handleFilterChange}
onFilterReset={handleFilterReset}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('cardOrder.create', 'Kart sargyt dörediň')}
onAction={() => navigate('/order-new-card/create')}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
getRowId={(row) => row.id}
currentPage={page}
totalPages={data?.totalPages ?? 1}
totalCount={data?.totalCount}
onPageChange={setPage}
/>
</div>
</div>
)
}

View File

@@ -0,0 +1,24 @@
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { CardOrderForm } from '@/features/orderNewCard/components/orderNewCardForm'
export default function CardOrderCreatePage() {
const navigate = useNavigate()
const { t } = useTranslation()
return (
<div>
<div className="mb-6">
<h1 className="text-xl font-semibold text-foreground tracking-tight">
{t('cardOrder.createTitle', 'Kart sargyt dörediň')}
</h1>
</div>
<CardOrderForm
mode="create"
onSuccess={() => navigate('/order-new-card')}
onCancel={() => navigate('/order-new-card')}
/>
</div>
)
}

View File

@@ -0,0 +1,51 @@
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Skeleton } from '@/components/ui/skeleton'
import { CardOrderForm } from '@/features/orderNewCard/components/orderNewCardForm'
import { useCardOrderById } from '@/features/orderNewCard/hooks/useOrderNewCard'
export default function CardOrderEditPage() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { t } = useTranslation()
const { data: order, isLoading } = useCardOrderById(id ?? '')
if (isLoading) {
return (
<div className="space-y-4 max-w-3xl">
<Skeleton className="h-8 w-48" />
{Array.from({ length: 8 }).map((_, i) => (
<Skeleton key={i} className="h-10 w-full" />
))}
</div>
)
}
if (!order) {
return (
<p className="text-muted-foreground text-sm">
{t('common.notFound', 'Tapylmady')}
</p>
)
}
return (
<div>
<div className="mb-6">
<h1 className="text-xl font-semibold text-foreground tracking-tight">
{t('cardOrder.editTitle', 'Düzetmek')}:{' '}
<span className="text-primary font-mono">{order.id}</span>
</h1>
</div>
<CardOrderForm
mode="edit"
initialData={order}
cardOrderId={id}
onSuccess={() => navigate(`/order-new-card/${id}`)}
onCancel={() => navigate(`/order-new-card/${id}`)}
/>
</div>
)
}

View File

@@ -0,0 +1,314 @@
import { useState } from 'react'
import { useParams, useNavigate, Link } 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 { useCardOrderById, useDeleteCardOrder } from '@/features/orderNewCard/hooks/useOrderNewCard'
import type { CardOrderStatus } from '@/features/orderNewCard/api/orderNewCardApi'
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_CFG: Record<CardOrderStatus, { label: string; className: string; icon: string }> = {
PENDING: { label: 'Garaşylýar', icon: '⏳', className: 'bg-amber-500/10 text-amber-400 border border-amber-500/20' },
APPROVED: { label: 'Tassyklandy', icon: '✓', className: 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' },
REJECTED: { label: 'Ýatyryldy', icon: '✕', className: 'bg-red-500/10 text-red-400 border border-red-500/20' },
}
function StatusBadge({ status }: { status: CardOrderStatus }) {
const cfg = STATUS_CFG[status]
return (
<span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-bold tracking-wide ${cfg.className}`}>
<span className="text-[10px]">{cfg.icon}</span>
{cfg.label}
</span>
)
}
// ─── Info row ─────────────────────────────────────────────────────────────────
function InfoRow({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
return (
<div className="grid grid-cols-[200px_1fr] gap-4 py-2.5 px-4 border-b border-border/60 last:border-0 items-start">
<span className="text-sm text-muted-foreground">{label}</span>
<span className="text-sm text-foreground">{children}</span>
</div>
)
}
// ─── Section ──────────────────────────────────────────────────────────────────
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<div className="mb-6">
<h3 className="text-base font-semibold text-foreground mb-3">{title}</h3>
<div className="bg-card border border-border rounded-xl overflow-hidden">
{children}
</div>
</div>
)
}
// ─── Passport file card ───────────────────────────────────────────────────────
function PassportFileCard({ label, url }: { label: string; url: string | null }) {
const { t } = useTranslation()
return (
<div className="grid grid-cols-[200px_1fr] gap-4 py-3 px-4 border-b border-border/60 last:border-0 items-start">
<span className="text-sm text-muted-foreground">{label}</span>
<div className="flex flex-col gap-2">
{url ? (
<>
<div className="w-20 h-14 rounded-lg overflow-hidden bg-muted border border-border">
<img
src={url}
alt={label}
className="w-full h-full object-cover"
onError={(e) => {
;(e.currentTarget as HTMLImageElement).style.display = 'none'
}}
/>
</div>
<a
href={url}
download
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 text-xs text-primary hover:text-primary/80 transition-colors w-fit"
>
<Download size={12} />
{t('common.download', 'Göçürip al')}
</a>
</>
) : (
<span className="text-sm text-muted-foreground">—</span>
)}
</div>
</div>
)
}
// ─── Loading skeleton ─────────────────────────────────────────────────────────
function DetailSkeleton() {
return (
<div className="space-y-6">
<Skeleton className="h-8 w-64" />
<div className="space-y-3">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-10 w-full" />
))}
</div>
</div>
)
}
// ─── CardOrderDetailPage ──────────────────────────────────────────────────────
export default function CardOrderDetailPage() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { t } = useTranslation()
const [deleteOpen, setDeleteOpen] = useState(false)
const { data: order, isLoading } = useCardOrderById(id ?? '')
const deleteMutation = useDeleteCardOrder()
const handleDelete = async () => {
if (!id) return
await deleteMutation.mutateAsync(id)
navigate('/order-new-card')
}
if (isLoading) return <DetailSkeleton />
if (!order) return (
<p className="text-muted-foreground text-sm">
{t('common.notFound', 'Tapylmady')}
</p>
)
return (
<div>
{/* Header */}
<div className="flex items-start justify-between mb-6 gap-4">
<div>
<h1 className="text-xl font-semibold text-foreground">
{t('cardOrder.detailTitle', 'Kart sargyt giriş üçin')}:{' '}
<span className="text-primary font-mono">{order.id}</span>
</h1>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button variant="outline" size="icon" title={t('common.print', 'Çap etmek')}>
<Printer size={15} />
</Button>
<Button variant="outline" size="icon" title={t('common.export', 'Eksport')}>
<Download size={15} />
</Button>
<Button
variant="outline"
size="icon"
className="text-destructive hover:text-destructive hover:bg-destructive/10 border-destructive/20"
title={t('common.delete', 'Pozmak')}
onClick={() => setDeleteOpen(true)}
>
<Trash2 size={15} />
</Button>
<Button
size="sm"
asChild
>
<Link to={`/order-new-card/${order.id}/edit`}>
<Pencil size={14} className="mr-1.5" />
{t('common.edit', 'Düzetmek')}
</Link>
</Button>
</div>
</div>
{/* Main info */}
<Section title="">
<InfoRow label="ID">{order.id}</InfoRow>
<InfoRow label={t('cardOrder.field.createdAt', 'Döredilen wagty')}>
{order.createdAt}
</InfoRow>
<InfoRow label={t('cardOrder.field.isPaid', 'Tölenen')}>
<span className={`inline-flex items-center justify-center w-5 h-5 rounded-full text-xs font-bold
${order.isPaid
? 'bg-emerald-500/15 text-emerald-400'
: 'bg-red-500/15 text-red-400'
}`}
>
{order.isPaid ? '✓' : '✕'}
</span>
</InfoRow>
<InfoRow label={t('cardOrder.field.status', 'Status')}>
<StatusBadge status={order.status} />
</InfoRow>
<InfoRow label={t('cardOrder.field.note', 'Bellik')}>
{order.note ?? '—'}
</InfoRow>
<InfoRow label={t('cardOrder.field.createdBy', 'Sargyt eden')}>
<span className="text-primary font-medium">{order.createdBy}</span>
</InfoRow>
</Section>
{/* Kart */}
<Section title={t('cardOrder.section.card', 'Kart')}>
<InfoRow label={t('cardOrder.field.issuanceReason', 'Kartyň çykarylmagynyň sebäbi')}>
<span className="text-primary font-medium">{order.issuanceReasonName}</span>
</InfoRow>
<InfoRow label={t('cardOrder.field.cardType', 'Kart görnüşi')}>
<span className="text-cyan-400 font-medium">{order.cardTypeName}</span>
</InfoRow>
</Section>
{/* Lokasiýa */}
<Section title={t('cardOrder.section.location', 'Lokasiýa')}>
<InfoRow label={t('cardOrder.field.province', 'Welaýat')}>
{order.provinceName}
</InfoRow>
<InfoRow label={t('cardOrder.field.branch', 'Şahamça')}>
<span className="text-cyan-400 font-medium">{order.branchName}</span>
</InfoRow>
</Section>
{/* Şahsy maglumatlar */}
<Section title={t('cardOrder.section.personal', 'Şahsy maglumatlar')}>
<InfoRow label={t('cardOrder.field.fullName', 'Doly ady')}>
{[order.lastName, order.firstName, order.middleName].filter(Boolean).join(' ')}
</InfoRow>
<InfoRow label={t('cardOrder.field.birthDate', 'Doglan güni')}>
{order.birthDate}
</InfoRow>
<InfoRow label={t('cardOrder.field.phone', 'Telefon')}>
{order.phone}
</InfoRow>
<InfoRow label={t('cardOrder.field.phoneExtra', 'Telefon goşmaça')}>
{order.phoneExtra ?? '—'}
</InfoRow>
<InfoRow label={t('cardOrder.field.citizenship', 'Raýatlyk')}>
{order.citizenship}
</InfoRow>
<InfoRow label={t('cardOrder.field.registeredAddress', 'Ýazgy edilen salgyňyz')}>
{order.registeredAddress}
</InfoRow>
<InfoRow label={t('cardOrder.field.currentAddress', 'Häzirki ýaşaýyş ýeri')}>
{order.currentAddress}
</InfoRow>
<InfoRow label={t('cardOrder.field.workplace', 'Işleýän ýeriňiz we wezipäňiz')}>
{order.workplace}
</InfoRow>
</Section>
{/* Pasport faýýlar */}
<Section title={t('cardOrder.section.passportFiles', 'Pasport faýýlar')}>
<PassportFileCard
label={t('cardOrder.field.passportPage1', 'Pasport (sahypa 1)')}
url={order.passportFiles.page1}
/>
<PassportFileCard
label={t('cardOrder.field.passportPage23', 'Pasport (2-3-nji sahypa)')}
url={order.passportFiles.page23}
/>
<PassportFileCard
label={t('cardOrder.field.passportPage89', 'Pasport (8-9 sahypa)')}
url={order.passportFiles.page89}
/>
<PassportFileCard
label={t('cardOrder.field.passportPage32', 'Pasport (32-nji sahypa)')}
url={order.passportFiles.page32}
/>
</Section>
{/* Delete confirm dialog */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t('cardOrder.deleteTitle', 'Pozmak isleýärsiňizmi?')}
</AlertDialogTitle>
<AlertDialogDescription>
{t(
'cardOrder.deleteDescription',
'Bu kart sargyt hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.',
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>
{t('common.cancel', 'Ýatyr')}
</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending
? t('common.deleting', 'Pozulýar...')
: t('common.delete', 'Pozmak')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,276 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import type { ColumnDef, VisibilityState } from '@tanstack/react-table'
import { DataTable } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import { useIntlPayments, useDeleteIntlPayment } from '@/features/visaMasterPayments/hooks/useVisaMasterPayments'
import type { IntlPaymentItem, IntlPaymentStatus } from '@/features/visaMasterPayments/api/visaMasterPaymentsApi'
import { Button } from '@/components/ui/button'
import { Eye, Pencil, Trash2, ChevronDown } from 'lucide-react'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { cn } from '@/lib/utils'
// ─── Status Badge ─────────────────────────────────────────────────────────────
const STATUS_MAP: Record<IntlPaymentStatus, { label: string; className: string }> = {
pending: { label: 'Garaşylýar', className: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30' },
approved: { label: 'Tassyklandy', className: 'bg-green-500/20 text-green-400 border-green-500/30' },
rejected: { label: 'Ret edildi', className: 'bg-red-500/20 text-red-400 border-red-500/30' },
}
function StatusBadge({ status }: { status: IntlPaymentStatus }) {
const cfg = STATUS_MAP[status] ?? STATUS_MAP.pending
return (
<span className={cn('inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold border', cfg.className)}>
{cfg.label}
</span>
)
}
// ─── Month selector (AÝ TOLEGI) ───────────────────────────────────────────────
const MONTHS = [
{ value: '01', label: 'Ýanwar' },
{ value: '02', label: 'Fewral' },
{ value: '03', label: 'Mart' },
{ value: '04', label: 'Aprel' },
{ value: '05', label: 'Maý' },
{ value: '06', label: 'Iýun' },
{ value: '07', label: 'Iýul' },
{ value: '08', label: 'Awgust' },
{ value: '09', label: 'Sentýabr' },
{ value: '10', label: 'Oktýabr' },
{ value: '11', label: 'Noýabr' },
{ value: '12', label: 'Dekabr' },
]
function MonthSelector({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const { t } = useTranslation()
return (
<div className="bg-card border border-border rounded-lg p-4 mb-4 inline-flex flex-col gap-2">
<span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
{t('intlPayment.monthFilter', 'AÝ TÖLEGI')}
</span>
<div className="relative">
<select
value={value}
onChange={(e) => onChange(e.target.value)}
className={cn(
'h-9 pl-3 pr-8 rounded-md border border-border bg-background',
'text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring',
'appearance-none cursor-pointer min-w-[120px]',
)}
>
<option value="">—</option>
{MONTHS.map((m) => (
<option key={m.value} value={m.value}>{m.label}</option>
))}
</select>
<ChevronDown size={13} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
</div>
</div>
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function IntlPaymentsPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(25)
const [search, setSearch] = useState('')
const [month, setMonth] = useState('')
const [statusFilter, setStatusFilter] = useState<IntlPaymentStatus | ''>('')
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>([])
const [deleteTarget, setDeleteTarget] = useState<IntlPaymentItem | null>(null)
const { data, isLoading } = useIntlPayments({ page, per_page: perPage, search, status: statusFilter, month })
const { mutate: deletePayment, isPending: isDeleting } = useDeleteIntlPayment()
const columns: ColumnDef<IntlPaymentItem>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="font-mono text-xs text-muted-foreground">{row.original.id}</span>
),
},
{
accessorKey: 'currency_type_label',
header: t('intlPayment.currencyType', 'Ýüztumanyň görnüşi'),
cell: ({ row }) => (
<span className="text-sm font-medium">{row.original.currency_type_label}</span>
),
},
{
accessorKey: 'created_at',
header: t('intlPayment.createdAt', 'Döredilen wagty'),
cell: ({ row }) => (
<span className="text-sm text-muted-foreground whitespace-nowrap">{row.original.created_at}</span>
),
},
{
accessorKey: 'province_label',
header: t('intlPayment.province', 'Welaýat'),
},
{
accessorKey: 'branch_label',
header: t('intlPayment.branch', 'Şahamça'),
cell: ({ row }) => (
<span className="text-primary font-medium">{row.original.branch_label}</span>
),
},
{
accessorKey: 'passport_first_name',
header: t('intlPayment.firstName', 'Ady'),
},
{
accessorKey: 'passport_last_name',
header: t('intlPayment.lastName', 'Familiýasy'),
},
{
accessorKey: 'phone',
header: t('intlPayment.phone', 'Telefon'),
cell: ({ row }) => (
<span className="font-mono text-sm">{row.original.phone}</span>
),
},
{
accessorKey: 'status',
header: t('intlPayment.status', 'Status'),
cell: ({ row }) => <StatusBadge status={row.original.status} />,
},
{
id: 'actions',
enableHiding: false,
cell: ({ row }) => (
<div className="flex items-center gap-1">
<Button
size="icon" variant="ghost" className="h-7 w-7"
onClick={() => navigate(`/visa-master-payments/${row.original.id}`)}
>
<Eye size={14} />
</Button>
<Button
size="icon" variant="ghost" className="h-7 w-7"
onClick={() => navigate(`/visa-master-payments/${row.original.id}/edit`)}
>
<Pencil size={14} />
</Button>
<Button
size="icon" variant="ghost"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteTarget(row.original)}
>
<Trash2 size={14} />
</Button>
</div>
),
},
]
const columnMeta = columns
.filter((c) => 'accessorKey' in c)
.map((c) => ({
id: ('accessorKey' in c ? String(c.accessorKey) : c.id) as string,
label: typeof c.header === 'string' ? c.header : String(('accessorKey' in c ? c.accessorKey : '') ?? ''),
}))
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t("intlPayment.title", "Halkara tölegler (Visa/Mastercard)")}
</h1>
</div>
<MonthSelector value={month} onChange={(v) => { setMonth(v); setPage(1) }} />
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { setSearch(v); setPage(1) }}
searchPlaceholder={t('intlPayment.search', 'Gözlemek')}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
filterFields={[
{
id: 'status',
label: t('intlPayment.status', 'Status'),
options: [
{ value: 'pending', label: 'Garaşylýar' },
{ value: 'approved', label: 'Tassyklandy' },
{ value: 'rejected', label: 'Ret edildi' },
],
},
]}
activeFilters={[{ fieldId: 'status', value: statusFilter }]}
onFilterChange={(fieldId, value) => {
if (fieldId === 'status') setStatusFilter(value as IntlPaymentStatus | '')
setPage(1)
}}
onFilterReset={() => { setStatusFilter(''); setPage(1) }}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('intlPayment.createBtn', 'Visa/Master tölegler (talyplar üçin) dörediň')}
onAction={() => navigate('/visa-master-payments/create')}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
currentPage={data?.meta?.current_page ?? 1}
totalPages={data?.meta?.last_page ?? 1}
totalCount={data?.meta?.total}
onPageChange={setPage}
/>
<AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('intlPayment.deleteTitle', 'Pozmak isleýärsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t('intlPayment.deleteDesc', 'Bu amal yzyna dolanyp bolmaz.')} {deleteTarget?.id}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
disabled={isDeleting}
className="bg-destructive hover:bg-destructive/90"
onClick={() => {
if (deleteTarget) {
deletePayment(deleteTarget.id, { onSuccess: () => setDeleteTarget(null) })
}
}}
>
{t('common.delete', 'Poz')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,23 @@
import { useNavigate } from 'react-router-dom'
import { IntlPaymentForm } from '@/features/visaMasterPayments/components/IntlPaymentForm'
import { useCreateIntlPayment } from '@/features/visaMasterPayments/hooks/useVisaMasterPayments'
import type { IntlPaymentCreatePayload } from '@/features/visaMasterPayments/api/visaMasterPaymentsApi'
export default function IntlPaymentCreatePage() {
const navigate = useNavigate()
const { mutate: createPayment, isPending } = useCreateIntlPayment()
const handleSubmit = (payload: IntlPaymentCreatePayload) => {
createPayment(payload, {
onSuccess: (data) => navigate(`/intl-payments/visa-master/${data.id}`),
})
}
return (
<IntlPaymentForm
mode="create"
onSubmit={handleSubmit}
isSubmitting={isPending}
/>
)
}

View File

@@ -0,0 +1,46 @@
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { IntlPaymentForm } from '@/features/visaMasterPayments/components/IntlPaymentForm'
import { useIntlPayment, useUpdateIntlPayment } from '@/features/visaMasterPayments/hooks/useVisaMasterPayments'
import type { IntlPaymentUpdatePayload } from '@/features/visaMasterPayments/api/visaMasterPaymentsApi'
import { Spinner } from '@/components/ui/spinner'
export default function IntlPaymentEditPage() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { t } = useTranslation()
const { data, isLoading, isError } = useIntlPayment(id!)
const { mutate: updatePayment, isPending } = useUpdateIntlPayment(id!)
const handleSubmit = (payload: IntlPaymentUpdatePayload) => {
updatePayment(payload, {
onSuccess: () => navigate(`/intl-payments/visa-master/${id}`),
})
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-8 text-primary" />
</div>
)
}
if (isError || !data) {
return (
<div className="flex items-center justify-center py-24 text-muted-foreground">
{t('common.notFound', 'Maglumat tapylmady')}
</div>
)
}
return (
<IntlPaymentForm
mode="edit"
initialData={data}
onSubmit={handleSubmit}
isSubmitting={isPending}
/>
)
}

View File

@@ -0,0 +1,319 @@
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useIntlPayment, useDeleteIntlPayment } from '@/features/visaMasterPayments/hooks/useVisaMasterPayments'
import type { IntlPaymentStatus } from '@/features/visaMasterPayments/api/visaMasterPaymentsApi'
import { Spinner } from '@/components/ui/spinner'
import { Button } from '@/components/ui/button'
import { Pencil, Trash2, Download, Search } from 'lucide-react'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { cn } from '@/lib/utils'
import { useState } from 'react'
// ─── Status Badge ─────────────────────────────────────────────────────────────
const STATUS_MAP: Record<IntlPaymentStatus, { label: string; className: string }> = {
pending: { label: 'Garaşylýar', className: 'bg-yellow-500/20 text-yellow-500 border-yellow-500/30' },
approved: { label: 'Tassyklandy', className: 'bg-green-500/20 text-green-500 border-green-500/30' },
rejected: { label: 'Ret edildi', className: 'bg-red-500/20 text-red-500 border-red-500/30' },
}
function StatusBadge({ status }: { status: IntlPaymentStatus }) {
const cfg = STATUS_MAP[status] ?? STATUS_MAP.pending
return (
<span className={cn('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold border', cfg.className)}>
<span className="w-1.5 h-1.5 rounded-full bg-current" />
{cfg.label}
</span>
)
}
// ─── FieldRow ─────────────────────────────────────────────────────────────────
function FieldRow({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="grid grid-cols-[240px_1fr] items-start py-3 border-b border-border last:border-0 gap-4">
<span className="text-sm text-muted-foreground shrink-0">{label}</span>
<span className="text-sm text-foreground">{children ?? '—'}</span>
</div>
)
}
// ─── Section ──────────────────────────────────────────────────────────────────
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section className="bg-card border border-border rounded-lg">
<h2 className="text-base font-semibold text-foreground px-6 pt-5 pb-3">{title}</h2>
<div className="px-6 pb-4">{children}</div>
</section>
)
}
// ─── DocFile row ─────────────────────────────────────────────────────────────
function DocFileRow({ label, url }: { label: string; url: string | null }) {
if (!url) return (
<div className="flex items-start gap-4 py-3 border-b border-border last:border-0">
<span className="text-sm text-muted-foreground flex-1 leading-snug">{label}</span>
<span className="text-sm text-muted-foreground/50">—</span>
</div>
)
const filename = url.split('/').pop() ?? 'faýl'
const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
return (
<div className="flex items-start gap-4 py-3 border-b border-border last:border-0">
<span className="text-sm text-muted-foreground flex-1 leading-snug">{label}</span>
<div className="flex items-center gap-2 shrink-0">
{isImage && (
<a href={url} target="_blank" rel="noreferrer"
className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-muted/50 hover:bg-muted text-xs text-foreground transition-colors"
>
<Search size={12} />
<span className="max-w-[140px] truncate">{filename}</span>
</a>
)}
<a href={url} download
className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-primary/10 hover:bg-primary/20 text-xs text-primary transition-colors"
>
<Download size={12} />
<span className="max-w-[140px] truncate">{filename}</span>
</a>
</div>
</div>
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function IntlPaymentViewPage() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { t } = useTranslation()
const { data, isLoading, isError } = useIntlPayment(id!)
const { mutate: deletePayment, isPending: isDeleting } = useDeleteIntlPayment()
const [historySearch, setHistorySearch] = useState('')
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-8 text-primary" />
</div>
)
}
if (isError || !data) {
return (
<div className="flex items-center justify-center py-24 text-muted-foreground">
{t('common.notFound', 'Maglumat tapylmady')}
</div>
)
}
const KABUL_DOCS = [
{ label: 'Talypyň degişli welaýata "SBERBANK" kartyň rekwizitleri', url: data.doc_sberbank_account },
{ label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamasy', url: data.doc_school_enrollment },
{ label: 'Talypyň bilendiriň göçürmesi', url: data.doc_summons },
{ label: 'Talypyň degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi', url: data.doc_passport_tm },
{ label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi', url: data.doc_foreign_passport },
{ label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurtda galan döwründe bakýan döwleti baradaky bellenen sahypasynyň göçürmesi', url: data.doc_foreign_passport_copy },
{ label: 'Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň dowletiniň girmesiz baradaky bellenen sahypasynyň göçürmesi', url: data.doc_exit_permission },
{ label: 'Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy barada maglumatlary daşary ýurt döwletiniň ýokary okuw mekdebinden haty', url: data.doc_school_foreign_info },
{ label: 'Talypyň daşary ýurt döwletinde okaýandygy baradaky güwänamany daşary ýurt döwletiniň ýokary okuw mekdebinden haty', url: data.doc_school_departure_info },
]
const UPGRAD_DOCS = [
{ label: 'Upgradyý degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi', url: data.upd_doc_passport_tm },
{ label: 'Upgradyý degişli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi', url: data.upd_doc_foreign_passport },
{ label: 'Upgradyý Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurt döwletinde galýandygy baradaky şaýmynyň bellenen sahypasynyň göçürmesi', url: data.upd_doc_visa },
{ label: 'Upgradyýyň we kabul edijiniň resminamalarynyň göçürmesi', url: data.upd_doc_acceptance_letter },
{ label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky maglumatlary', url: data.upd_doc_passport_biometric },
{ label: 'Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky göwnamasy', url: data.upd_doc_passport_old },
]
return (
<div className="max-w-4xl mx-auto space-y-6">
{/* Header */}
<div className="flex items-start justify-between">
<div /> {/* breadcrumb handled by layout */}
<div className="flex items-center gap-2">
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="icon" variant="ghost" className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10">
<Trash2 size={15} />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('intlPayment.deleteTitle', 'Pozmak isleýärsiňizmi?')}</AlertDialogTitle>
<AlertDialogDescription>
{t('intlPayment.deleteDesc', 'Bu amal yzyna dolanyp bolmaz.')} {data.id}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
disabled={isDeleting}
className="bg-destructive hover:bg-destructive/90"
onClick={() => deletePayment(data.id, { onSuccess: () => navigate('/intl-payments/visa-master') })}
>
{t('common.delete', 'Poz')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Button size="icon" variant="ghost" className="h-8 w-8"
onClick={() => navigate(`/intl-payments/visa-master/${id}/edit`)}
>
<Pencil size={15} />
</Button>
</div>
</div>
{/* Status */}
<Section title={t('intlPayment.statusSection', 'Status')}>
<div className="divide-y divide-border">
<FieldRow label={t('intlPayment.client', 'Ulanyjy')}>
<span className="text-primary font-medium">{data.client_label}</span>
</FieldRow>
<FieldRow label="ID">
<span className="font-mono">{data.id}</span>
</FieldRow>
<FieldRow label={t('intlPayment.status', 'Status')}>
<StatusBadge status={data.status} />
</FieldRow>
<FieldRow label={t('intlPayment.tilowanMonth', 'Tölewan (Aý/aý)')}>
{data.created_at}
</FieldRow>
<FieldRow label={t('intlPayment.note', 'Bellik')}>
{data.note}
</FieldRow>
</div>
</Section>
{/* Ýüztumanyň görnüşi */}
<Section title={t('intlPayment.currencySection', 'Ýüztumanyň görnüşi')}>
<div className="divide-y divide-border">
<FieldRow label={t('intlPayment.currencyType', 'Ýüztumanyň görnüşi')}>
{data.currency_type_label}
</FieldRow>
</div>
</Section>
{/* Lokasiýa */}
<Section title={t('intlPayment.locationSection', 'Lokasiýa')}>
<div className="divide-y divide-border">
<FieldRow label={t('intlPayment.province', 'Welaýat')}>{data.province_label}</FieldRow>
<FieldRow label={t('intlPayment.branch', 'Şahamça')}>
<span className="text-primary font-medium">{data.branch_label}</span>
</FieldRow>
</div>
</Section>
{/* Şahsy maglumatlar */}
<Section title={t('intlPayment.personalSection', 'Şahsy maglumatlar')}>
<div className="divide-y divide-border">
<FieldRow label={t('intlPayment.passportFirstName', 'Pasportdaky ady')}>{data.passport_first_name}</FieldRow>
<FieldRow label={t('intlPayment.passportLastName', 'Pasportdaky familiýa')}>{data.passport_last_name}</FieldRow>
<FieldRow label={t('intlPayment.phone', 'Telefon')}>+{data.phone}</FieldRow>
<FieldRow label={t('intlPayment.email', 'E-poçta')}>{data.email}</FieldRow>
<FieldRow label={t('intlPayment.homeAddress', 'Häzirki ýaşyş ýeri')}>{data.home_address}</FieldRow>
</div>
</Section>
{/* Töleg */}
<Section title={t('intlPayment.paymentSection', 'Töleg')}>
<div className="divide-y divide-border mb-4">
<FieldRow label={t('intlPayment.payerFullName', 'Töleg upgradyjynyň maglumatlary')}>
{data.payer_full_name}
</FieldRow>
<FieldRow label={t('intlPayment.payerAccount', 'Töleg upgradyjynyň goşun hasaby')}>
{data.payer_account_number}
</FieldRow>
</div>
{/* Receiver table */}
<div className="border border-border rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-muted/40">
<tr>
<th className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase">
{t('intlPayment.passportSeries', 'Pasport seriýasy')}
</th>
<th className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase">
{t('intlPayment.passportNumber', 'Pasport nomeri')}
</th>
<th className="text-left px-4 py-2.5 text-xs font-semibold text-muted-foreground uppercase">
{t('intlPayment.payerFullName', 'Ady Familiýasy Atasnyň ady')}
</th>
</tr>
</thead>
<tbody>
<tr className="border-t border-border">
<td className="px-4 py-3">{data.passport_series} – {data.passport_number}</td>
<td className="px-4 py-3">{data.passport_number}</td>
<td className="px-4 py-3">{data.payer_full_name}</td>
</tr>
</tbody>
</table>
</div>
</Section>
{/* Kabul ediji talyp boyunca resminamalar */}
<Section title={t('intlPayment.kabulDocsSection', 'Kabul ediji talyp boyunca resminamalar')}>
<div>
{KABUL_DOCS.map((doc, i) => (
<DocFileRow key={i} label={doc.label} url={doc.url} />
))}
</div>
</Section>
{/* Upgradyý boyunca resminamalar */}
<Section title={t('intlPayment.upgradDocsSection', 'Upgradyý boyunca resminamalar')}>
<div>
{UPGRAD_DOCS.map((doc, i) => (
<DocFileRow key={i} label={doc.label} url={doc.url} />
))}
</div>
</Section>
{/* Töleg taryhy */}
<Section title={t('intlPayment.paymentHistory', 'Töleg taryhy')}>
<div className="flex items-center gap-2 mb-4">
<div className="relative flex-1 max-w-xs">
<Search size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
<input
type="text"
value={historySearch}
onChange={(e) => setHistorySearch(e.target.value)}
placeholder={t('intlPayment.search', 'Gözlemek')}
className="h-9 w-full pl-9 pr-3 rounded-md border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
</div>
<div className="flex flex-col items-center justify-center py-12 text-muted-foreground/50">
<div className="w-12 h-12 mb-3 rounded-lg border-2 border-dashed border-muted-foreground/20 flex items-center justify-center">
<svg viewBox="0 0 24 24" className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={1.5}>
<rect x="3" y="3" width="18" height="18" rx="2" />
<line x1="3" y1="9" x2="21" y2="9" />
<line x1="9" y1="9" x2="9" y2="21" />
</svg>
</div>
<p className="text-sm">{t('intlPayment.noHistory', 'Beriilen kriteriýalara Töleg gabat gelmedi')}</p>
</div>
</Section>
</div>
)
}

View File

@@ -0,0 +1,5 @@
import { LoanOrderMobileForm } from "@/features/loanOrderMobiles/components/loanOrderMobileForm";
export default function LoanOrderMobilesCreatePage() {
return <LoanOrderMobileForm mode="create" />;
}

View File

@@ -1,18 +1,18 @@
import { useParams } from 'react-router-dom'
import { Loader2 } from 'lucide-react'
import { LoanOrderMobileForm } from '@/components/loanOrderMobileForm'
import { useLoanOrderMobileById } from '@/features/loanOrderMobiles/hooks/useLoanOrderMobiles'
import { useParams } from "react-router-dom";
import { Loader2 } from "lucide-react";
import { LoanOrderMobileForm } from "@/features/loanOrderMobiles/components/loanOrderMobileForm";
import { useLoanOrderMobileById } from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles";
export default function LoanOrderMobilesEditPage() {
const { id } = useParams<{ id: string }>()
const { data, isLoading, isError } = useLoanOrderMobileById(id ?? '')
const { id } = useParams<{ id: string }>();
const { data, isLoading, isError } = useLoanOrderMobileById(id ?? "");
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<Loader2 className="animate-spin text-muted-foreground" size={32} />
</div>
)
);
}
if (isError || !data) {
@@ -22,14 +22,10 @@ export default function LoanOrderMobilesEditPage() {
Maglumat ýüklenilmedi. Sahypany täzeleläň.
</p>
</div>
)
);
}
return (
<LoanOrderMobileForm
mode="edit"
initialData={data}
loanOrderId={id}
/>
)
<LoanOrderMobileForm mode="edit" initialData={data} loanOrderId={id} />
);
}

View File

@@ -1,5 +0,0 @@
import { LoanOrderMobileForm } from '@/components/loanOrderMobileForm'
export default function LoanOrderMobilesCreatePage() {
return <LoanOrderMobileForm mode="create" />
}