diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index d1dc568..9834686 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -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 ; @@ -179,6 +252,199 @@ export const router = createBrowserRouter([ ), }, + { + // Sidebar: /order-new-card + path: "/order-new-card", + element: ( + }> + + + ), + }, + { + path: "/order-new-card/create", + element: ( + }> + + + ), + }, + { + path: "/order-new-card/:id", + element: ( + }> + + + ), + }, + { + path: "/order-new-card/:id/edit", + element: ( + }> + + + ), + }, + { + path: "/card-transactions", + element: ( + }> + + + ), + }, + { + path: "/card-transactions/create", + element: ( + }> + + + ), + }, + { + path: "/card-transactions/:id", + element: ( + }> + + + ), + }, + { + path: "/card-transactions/:id/edit", + element: ( + }> + + + ), + }, + { + path: "/card-requisites", + element: ( + }> + + + ), + }, + { + path: "/card-requisites/create", + element: ( + }> + + + ), + }, + { + path: "/card-requisites/:id", + element: ( + }> + + + ), + }, + { + path: "/card-requisites/:id/edit", + element: ( + }> + + + ), + }, + { + path: "/card-balances", + element: ( + }> + + + ), + }, + { + path: "/card-balances/create", + element: ( + }> + + + ), + }, + { + path: "/card-balances/:id", + element: ( + }> + + + ), + }, + { + path: "/card-balances/:id/edit", + element: ( + }> + + + ), + }, + { + path: "/card-pins", + element: ( + }> + + + ), + }, + { + path: "/card-pins/create", + element: ( + }> + + + ), + }, + { + path: "/card-pins/:id", + element: ( + }> + + + ), + }, + { + path: "/card-pins/:id/edit", + element: ( + }> + + + ), + }, + { // Sidebar: /visa-master-payments + path: "/visa-master", + element: ( + }> + + + ), + }, + { + path: "/visa-master-payments/create", + element: ( + }> + + + ), + }, + { + path: "/visa-master-payments/:id", + element: ( + }> + + + ), + }, + { + path: "/visa-master-payments/:id/edit", + element: ( + }> + + + ), + }, ], }, ], diff --git a/src/components/ui/alert-dialog.tsx b/src/components/ui/alert-dialog.tsx new file mode 100644 index 0000000..b8171d5 --- /dev/null +++ b/src/components/ui/alert-dialog.tsx @@ -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) { + return +} + +function AlertDialogTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AlertDialogPortal({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AlertDialogOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AlertDialogContent({ + className, + size = "default", + ...props +}: React.ComponentProps & { + size?: "default" | "sm" +}) { + return ( + + + + + ) +} + +function AlertDialogHeader({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AlertDialogFooter({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AlertDialogMedia({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AlertDialogTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AlertDialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AlertDialogAction({ + className, + variant = "default", + size = "default", + ...props +}: React.ComponentProps & + Pick, "variant" | "size">) { + return ( + + ) +} + +function AlertDialogCancel({ + className, + variant = "outline", + size = "default", + ...props +}: React.ComponentProps & + Pick, "variant" | "size">) { + return ( + + ) +} + +export { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogMedia, + AlertDialogOverlay, + AlertDialogPortal, + AlertDialogTitle, + AlertDialogTrigger, +} diff --git a/src/features/cardBalance/api/cardBalanceApi.ts b/src/features/cardBalance/api/cardBalanceApi.ts new file mode 100644 index 0000000..8c022fe --- /dev/null +++ b/src/features/cardBalance/api/cardBalanceApi.ts @@ -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 => { + // 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 => { + // 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 => { + const { data } = await apiClient.post('/card-balances', payload) + return data + }, + + update: async (id: number, payload: UpdateCardBalancePayload): Promise => { + const { data } = await apiClient.put(`/card-balances/${id}`, payload) + return data + }, + + delete: async (id: number): Promise => { + await apiClient.delete(`/card-balances/${id}`) + }, + + download: async (id: number): Promise => { + const { data } = await apiClient.get(`/card-balances/${id}/download`, { + responseType: 'blob', + }) + return data + }, +} \ No newline at end of file diff --git a/src/features/cardBalance/components/cardBalanceForm.tsx b/src/features/cardBalance/components/cardBalanceForm.tsx new file mode 100644 index 0000000..bd9f6a8 --- /dev/null +++ b/src/features/cardBalance/components/cardBalanceForm.tsx @@ -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(EMPTY_FORM) + const [errors, setErrors] = useState({}) + + 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 ( +
+
+ {/* Row 1 */} + + + + {/* Row 2 — card number full width + 2 selects */} + + +
+ + +
+
+ + {/* Actions */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/cardBalance/hooks/useCardBalance.ts b/src/features/cardBalance/hooks/useCardBalance.ts new file mode 100644 index 0000000..6581659 --- /dev/null +++ b/src/features/cardBalance/hooks/useCardBalance.ts @@ -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')) + }, + }) +} \ No newline at end of file diff --git a/src/features/cardPins/api/cardPinApi.ts b/src/features/cardPins/api/cardPinApi.ts new file mode 100644 index 0000000..f96d2bb --- /dev/null +++ b/src/features/cardPins/api/cardPinApi.ts @@ -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 => { + // 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 => { + 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 => { + 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 => { + 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 => + 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 +} \ No newline at end of file diff --git a/src/features/cardPins/components/cardPinForm.tsx b/src/features/cardPins/components/cardPinForm.tsx new file mode 100644 index 0000000..8c5fd5d --- /dev/null +++ b/src/features/cardPins/components/cardPinForm.tsx @@ -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> + +// ─── 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(defaultState) + const [errors, setErrors] = useState({}) + + // 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 = (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 ( +
+

{title}

+ + {/* ── Status & Note ────────────────────────────────────────────────── */} +
+ set('status', v)} + options={STATUS_OPTIONS} + error={errors.status} + required + /> + set('note', v)} + placeholder={t('cardPin.notePlaceholder', 'Bellik')} + /> +
+ + {/* ── Kart ─────────────────────────────────────────────────────────── */} +
+

+ {t('cardPin.cardSection', 'Kart')} +

+
+ set('card_type', v)} + options={CARD_TYPE_OPTIONS} + error={errors.card_type} + required + /> + set('card_number', v)} + placeholder={t('cardPin.cardNumberPlaceholder', 'Kart belgisi')} + error={errors.card_number} + required + /> +
+
+ + {/* ── Lokasiýa ─────────────────────────────────────────────────────── */} +
+

+ {t('cardPin.locationSection', 'Lokasiýa')} +

+
+ { set('province', v); set('branch', '') }} + options={PROVINCE_OPTIONS} + error={errors.province} + required + /> + set('branch', v)} + options={[]} // Populated dynamically based on province from API + placeholder={t('cardPin.branchPlaceholder', 'Saýlamak üçin basyň')} + error={errors.branch} + required + /> +
+
+ + {/* ── Şahsy maglumatlar ─────────────────────────────────────────────── */} +
+

+ {t('cardPin.personalSection', 'Şahsy maglumatlar')} +

+
+ set('first_name', v)} + placeholder={t('cardPin.firstName', 'Ady')} + error={errors.first_name} + required + /> + set('last_name', v)} + placeholder={t('cardPin.lastName', 'Familiýasy')} + error={errors.last_name} + required + /> + set('father_name', v)} + placeholder={t('cardPin.fatherName', 'Atasynyň ady')} + /> +
+
+ set('birth_date', v)} + error={errors.birth_date} + required + /> + set('phone', v)} + error={errors.phone} + required + /> +
+
+ + {/* ── Pasport ───────────────────────────────────────────────────────── */} +
+

+ {t('cardPin.passportSection', 'Pasport')} +

+
+ set('passport_series', v)} + options={PASSPORT_SERIES_OPTIONS} + error={errors.passport_series} + required + /> + set('passport_number', v)} + placeholder={t('cardPin.passportNumber', 'Pasport belgisi')} + error={errors.passport_number} + required + /> +
+
+ set('passport_file_1', f)} + fileValue={form.passport_file_1} + accept="image/*,.pdf" + error={errors.passport_file_1} + required={mode === 'create'} + /> + set('passport_file_2', f)} + fileValue={form.passport_file_2} + accept="image/*,.pdf" + error={errors.passport_file_2} + required={mode === 'create'} + /> + set('passport_file_3', f)} + fileValue={form.passport_file_3} + accept="image/*,.pdf" + error={errors.passport_file_3} + required={mode === 'create'} + /> + set('passport_file_4', f)} + fileValue={form.passport_file_4} + accept="image/*,.pdf" + error={errors.passport_file_4} + required={mode === 'create'} + /> +
+
+ + {/* ── Actions ───────────────────────────────────────────────────────── */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/cardPins/hooks/useCardPins.ts b/src/features/cardPins/hooks/useCardPins.ts new file mode 100644 index 0000000..596907d --- /dev/null +++ b/src/features/cardPins/hooks/useCardPins.ts @@ -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')) + }, + }) +} \ No newline at end of file diff --git a/src/features/cardRequisites/api/cardRequisitesApi.ts b/src/features/cardRequisites/api/cardRequisitesApi.ts new file mode 100644 index 0000000..113fc6d --- /dev/null +++ b/src/features/cardRequisites/api/cardRequisitesApi.ts @@ -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 => { + const { data } = await apiClient.get('/card-requisites', { params }) + return data + }, + + getById: async (id: string): Promise => { + const { data } = await apiClient.get(`/card-requisites/${id}`) + return data + }, + + create: async (payload: CreateCardRequisitePayload): Promise => { + const { data } = await apiClient.post('/card-requisites', buildFormData(payload), { + headers: { 'Content-Type': 'multipart/form-data' }, + }) + return data + }, + + update: async (id: string, payload: UpdateCardRequisitePayload): Promise => { + const { data } = await apiClient.post(`/card-requisites/${id}`, buildFormData(payload), { + headers: { 'Content-Type': 'multipart/form-data' }, + }) + return data + }, + + delete: async (id: string): Promise => { + await apiClient.delete(`/card-requisites/${id}`) + }, + + download: async (id: string): Promise => { + const { data } = await apiClient.get(`/card-requisites/${id}/download`, { + responseType: 'blob', + }) + return data + }, +} diff --git a/src/features/cardRequisites/components/cardRequisiteForm.tsx b/src/features/cardRequisites/components/cardRequisiteForm.tsx new file mode 100644 index 0000000..df7cded --- /dev/null +++ b/src/features/cardRequisites/components/cardRequisiteForm.tsx @@ -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 = { + '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 ( +

{children}

+ ) +} + +// ─── Component ──────────────────────────────────────────────────────────────── + +export function CardRequisiteForm({ + mode, + initialData, + cardRequisiteId, +}: CardRequisiteFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const [form, setForm] = useState(EMPTY_FORM) + const [files, setFiles] = useState(EMPTY_FILES) + const [errors, setErrors] = useState({}) + + 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 ( +
+ {/* ── General ── */} +
+
+ + +
+
+ + {/* ── Kart ── */} + {t('Card', 'Kart')} +
+
+ + + + +
+
+ + {/* ── Lokasiýa ── */} + {t('Location', 'Lokasiýa')} +
+
+ + +
+
+ + {/* ── Şahsy maglumatlar ── */} + {t('Personal information', 'Şahsy maglumatlar')} +
+
+ + + +
+
+ + +
+
+ + {/* ── Pasport ── */} + {t('Passport', 'Pasport')} +
+
+ + +
+ +
+ + + + +
+
+ + {/* ── Actions ── */} +
+ + +
+
+ ) +} diff --git a/src/features/cardRequisites/hooks/useCardRequisites.ts b/src/features/cardRequisites/hooks/useCardRequisites.ts new file mode 100644 index 0000000..724ac13 --- /dev/null +++ b/src/features/cardRequisites/hooks/useCardRequisites.ts @@ -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')) + }, + }) +} diff --git a/src/features/cardTransactions/api/cardTransactionsApi.ts b/src/features/cardTransactions/api/cardTransactionsApi.ts new file mode 100644 index 0000000..15de0a9 --- /dev/null +++ b/src/features/cardTransactions/api/cardTransactionsApi.ts @@ -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 => { + // 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 => { + // 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 => { + const { data } = await apiClient.post('/card-transactions', payload) + return data + }, + + update: async (id: number, payload: UpdateCardTransactionPayload): Promise => { + const { data } = await apiClient.put(`/card-transactions/${id}`, payload) + return data + }, + + delete: async (id: number): Promise => { + await apiClient.delete(`/card-transactions/${id}`) + }, + + download: async (id: number): Promise => { + const { data } = await apiClient.get(`/card-transactions/${id}/download`, { + responseType: 'blob', + }) + return data + }, +} diff --git a/src/features/cardTransactions/components/cardTransactionForm.tsx b/src/features/cardTransactions/components/cardTransactionForm.tsx new file mode 100644 index 0000000..cf49c66 --- /dev/null +++ b/src/features/cardTransactions/components/cardTransactionForm.tsx @@ -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(EMPTY_FORM) + const [errors, setErrors] = useState({}) + + 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 ( +
+
+ {/* Passport Series */} + + + {/* Passport Number */} + + + {/* Card Number */} + + + {/* Expiry Month + Year side by side */} +
+ + + +
+
+ + {/* Actions */} +
+ + +
+
+ ) +} diff --git a/src/features/cardTransactions/hooks/useCardTransactions.ts b/src/features/cardTransactions/hooks/useCardTransactions.ts new file mode 100644 index 0000000..e49bc6a --- /dev/null +++ b/src/features/cardTransactions/hooks/useCardTransactions.ts @@ -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')) + }, + }) +} diff --git a/src/components/loanOrderMobileForm.tsx b/src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx similarity index 100% rename from src/components/loanOrderMobileForm.tsx rename to src/features/loanOrderMobiles/components/loanOrderMobileForm.tsx diff --git a/src/features/orderNewCard/api/orderNewCardApi.ts b/src/features/orderNewCard/api/orderNewCardApi.ts new file mode 100644 index 0000000..f097434 --- /dev/null +++ b/src/features/orderNewCard/api/orderNewCardApi.ts @@ -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 { + 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 {} + +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> { + 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>( + `/card-orders?${params.toString()}`, + ) + return data +} + +export async function fetchCardOrderById(id: string): Promise { + 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(`/card-orders/${id}`) + return data +} + +export async function createCardOrder( + payload: CreateCardOrderPayload, +): Promise { + 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('/card-orders', formData, { + headers: { 'Content-Type': 'multipart/form-data' }, + }) + return data +} + +export async function updateCardOrder( + id: string, + payload: UpdateCardOrderPayload, +): Promise { + if (USE_MOCK) { + await new Promise((r) => setTimeout(r, 1000)) + return { ...MOCK_ORDERS[0], id } + } + const formData = buildFormData(payload) + const { data } = await apiClient.put(`/card-orders/${id}`, formData, { + headers: { 'Content-Type': 'multipart/form-data' }, + }) + return data +} + +export async function deleteCardOrder(id: string): Promise { + if (USE_MOCK) { + await new Promise((r) => setTimeout(r, 500)) + return + } + await apiClient.delete(`/card-orders/${id}`) +} + +// ─── Lookup lists ───────────────────────────────────────────────────────────── + +export async function fetchCardIssuanceReasons(): Promise { + if (USE_MOCK) return MOCK_REASONS + const { data } = await apiClient.get('/settings/card/reasons') + return data +} + +export async function fetchCardTypes(): Promise { + if (USE_MOCK) return MOCK_TYPES + const { data } = await apiClient.get('/settings/card/types') + return data +} + +export async function fetchProvinces(): Promise { + if (USE_MOCK) return MOCK_PROVINCES + const { data } = await apiClient.get('/settings/location/districts') + return data +} + +export async function fetchBranches(provinceId?: number): Promise { + 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(`/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 +} \ No newline at end of file diff --git a/src/features/orderNewCard/components/orderNewCardForm.tsx b/src/features/orderNewCard/components/orderNewCardForm.tsx new file mode 100644 index 0000000..7b13dd9 --- /dev/null +++ b/src/features/orderNewCard/components/orderNewCardForm.tsx @@ -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> + +// ─── 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 ( +
+ {title && ( +

{title}

+ )} +
+ {children} +
+
+ ) +} + +// ─── CardOrderForm ──────────────────────────────────────────────────────────── + +export function CardOrderForm({ + mode, + initialData, + cardOrderId, + onSuccess, + onCancel, +}: CardOrderFormProps) { + const { t } = useTranslation() + const isEdit = mode === 'edit' + + const [form, setForm] = useState(() => getInitialState(initialData)) + const [errors, setErrors] = useState({}) + 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 ( +
+ + {/* ── Status section ── */} + +
+ setForm((f) => ({ ...f, isPaid: e.target.checked }))} + className="w-4 h-4 accent-primary cursor-pointer" + /> + +
+ +
+ + +
+
+ + {/* ── Kart ── */} + +
+ + +
+
+ + {/* ── Lokasiýa ── */} + +
+ { + setForm((f) => ({ ...f, provinceId: v, branchId: '' })) + }} + options={toOptions(provinces)} + error={errors.provinceId} + /> + +
+
+ + {/* ── Şahsy maglumatlar ── */} + +
+ + + +
+ +
+ + +
+ +
+ + + +
+ +
+ + +
+ + +
+ + {/* ── Pasport ── */} + +
+ + + +
+ +
+ + +
+
+ + {/* ── Pasport faýýlar ── */} + +
+ + + + +
+
+ + {/* ── Terms ── */} + {!isEdit && ( +
setForm((f) => ({ ...f, termsAccepted: !f.termsAccepted }))} + > +
+ {form.termsAccepted && ( + + + + )} +
+ + {t('cardOrder.terms', 'Şertnama bilen razylaşýaryn (Okamak üçin bas)')} + +
+ )} + + {/* ── Actions ── */} +
+ {onCancel && ( + + )} + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/orderNewCard/components/orderNewCardTable.tsx b/src/features/orderNewCard/components/orderNewCardTable.tsx new file mode 100644 index 0000000..66f803a --- /dev/null +++ b/src/features/orderNewCard/components/orderNewCardTable.tsx @@ -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 = { + PENDING: '⏳', + APPROVED: '✓', + REJECTED: '✕', + } + return ( + + {icons[status]} + {cfg.label} + + ) +} + +// ─── 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 {value} +} + +// ─── useCardOrderColumns ────────────────────────────────────────────────────── + +export function useCardOrderColumns(): ColumnDef[] { + const { t } = useTranslation() + + return [ + { + accessorKey: 'id', + header: t('cardOrder.col.id', 'ID'), + cell: ({ row }) => ( + + {row.original.id} + + ), + size: 130, + }, + { + accessorKey: 'issuanceReasonName', + header: t('cardOrder.col.reason', 'Sebäp'), + cell: ({ row }) => ( + + {row.original.issuanceReasonName} + + ), + }, + { + accessorKey: 'createdAt', + header: t('cardOrder.col.createdAt', 'Döredilen wagty'), + cell: ({ row }) => ( + + {row.original.createdAt} + + ), + size: 160, + }, + { + accessorKey: 'cardTypeName', + header: t('cardOrder.col.cardType', 'Görnüşi'), + cell: ({ row }) => { + const isAltyn = row.original.cardTypeName === 'Altyn Asyr' + return ( + + ) + }, + }, + { + accessorKey: 'provinceName', + header: t('cardOrder.col.province', 'Welaýat'), + cell: ({ row }) => ( + {row.original.provinceName} + ), + }, + { + 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 ( + + ) + }, + }, + { + id: 'fullName', + header: t('cardOrder.col.name', 'Ady'), + cell: ({ row }) => ( + + {row.original.lastName} {row.original.firstName} + + ), + }, + { + accessorKey: 'status', + header: t('cardOrder.col.status', 'Status'), + cell: ({ row }) => , + size: 130, + }, + + ] +} \ No newline at end of file diff --git a/src/features/orderNewCard/hooks/useOrderNewCard.ts b/src/features/orderNewCard/hooks/useOrderNewCard.ts new file mode 100644 index 0000000..8485bef --- /dev/null +++ b/src/features/orderNewCard/hooks/useOrderNewCard.ts @@ -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, + }) +} \ No newline at end of file diff --git a/src/features/visaMasterPayments/api/visaMasterPaymentsApi.ts b/src/features/visaMasterPayments/api/visaMasterPaymentsApi.ts new file mode 100644 index 0000000..efeccf8 --- /dev/null +++ b/src/features/visaMasterPayments/api/visaMasterPaymentsApi.ts @@ -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 => { + 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 => { + 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 => { + 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 => { + 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 => + 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 +} diff --git a/src/features/visaMasterPayments/components/intlPaymentForm.tsx b/src/features/visaMasterPayments/components/intlPaymentForm.tsx new file mode 100644 index 0000000..18e6af5 --- /dev/null +++ b/src/features/visaMasterPayments/components/intlPaymentForm.tsx @@ -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> + +// ─── 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 ( +
+ {title && ( +

{title}

+ )} + {children} +
+ ) +} + +// ─── Component ──────────────────────────────────────────────────────────────── + +export function IntlPaymentForm({ mode, initialData, onSubmit, isSubmitting }: IntlPaymentFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const [form, setForm] = useState(defaultState) + const [errors, setErrors] = useState({}) + + 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 = (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 ( +
+

{title}

+ + {/* ── Status ────────────────────────────────────────────────────────── */} +
+ set('client_id', v)} + options={[]} // Fetched from clients API + placeholder="Saýlamak üçin basyň" + error={errors.client_id} + required + /> + set('status', v)} + options={STATUS_OPTIONS} + error={errors.status} + required + /> + set('note', v)} + placeholder="Bellik" + rows={2} + /> +
+ + {/* ── Ýüztumanyň görnüşi ───────────────────────────────────────────── */} +
+ set('currency_type', v)} + options={CURRENCY_OPTIONS} + error={errors.currency_type} + required + /> +
+ + {/* ── Lokasiýa ─────────────────────────────────────────────────────── */} +
+
+ { set('province', v); set('branch', '') }} + options={PROVINCE_OPTIONS} + error={errors.province} + required + /> + set('branch', v)} + options={[]} // Fetched from branches API filtered by province + placeholder="Saýlamak üçin basyň" + error={errors.branch} + required + /> +
+
+ + {/* ── Şahsy maglumatlar ─────────────────────────────────────────────── */} +
+
+ set('passport_last_name', v)} + options={[]} + placeholder="Pasportdaky familýa" + error={errors.passport_last_name} + required + /> + set('passport_first_name', v)} + placeholder="Pasportdaky ady" + error={errors.passport_first_name} + required + /> +
+
+ set('phone', v)} + error={errors.phone} + required + /> + set('email', v)} + placeholder="E-poçta" + /> +
+ set('home_address', v)} + placeholder="Häzirki ýaşyş ýeri" + /> +
+ + {/* ── Töleg upgradyjynyň maglumatlary ──────────────────────────────── */} +
+
+ set('passport_series', v)} + options={PASSPORT_SERIES_OPTIONS} + error={errors.passport_series} + required + /> + set('passport_number', v)} + placeholder="Pasport nomeri" + error={errors.passport_number} + required + /> +
+ set('payer_full_name', v)} + placeholder="Ady Familiýasy Atasnyň ady" + error={errors.payer_full_name} + required + /> + set('payer_account_number', v)} + placeholder="Goşun hasaby" + error={errors.payer_account_number} + required + /> +
+ + {/* ── Töleg kabul edijiniň maglumatlary ────────────────────────────── */} +
+ set('receiver_info', v)} + placeholder="Saňa ger" + rows={3} + error={errors.receiver_info} + required + /> +
+ + {/* ── Kabul ediji talyp boyunca resminamalar ────────────────────────── */} +
+
+ {KABUL_DOCS.map(({ key, label }) => ( + set(key, f)} + fileValue={form[key] as File | null} + accept="image/*,.pdf" + /> + ))} +
+
+ + {/* ── Upgradyý boyunca resminamalar ─────────────────────────────────── */} +
+
+ {UPGRAD_DOCS.map(({ key, label }) => ( + set(key, f)} + fileValue={form[key] as File | null} + accept="image/*,.pdf" + /> + ))} +
+
+ + {/* ── Actions ───────────────────────────────────────────────────────── */} +
+ + +
+
+ ) +} diff --git a/src/features/visaMasterPayments/hooks/useVisaMasterPayments.ts b/src/features/visaMasterPayments/hooks/useVisaMasterPayments.ts new file mode 100644 index 0000000..bb82995 --- /dev/null +++ b/src/features/visaMasterPayments/hooks/useVisaMasterPayments.ts @@ -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')) + }, + }) +} diff --git a/src/layouts/DashboardLayout.tsx b/src/layouts/DashboardLayout.tsx index 6211323..5d433c4 100644 --- a/src/layouts/DashboardLayout.tsx +++ b/src/layouts/DashboardLayout.tsx @@ -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' }, ], }, ], diff --git a/src/pages/cardDepartment/cardBalance/index.tsx b/src/pages/cardDepartment/cardBalance/index.tsx new file mode 100644 index 0000000..eb72f10 --- /dev/null +++ b/src/pages/cardDepartment/cardBalance/index.tsx @@ -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(null) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([]) + + const { data, isLoading } = useCardBalances({ page, per_page: perPage, search }) + const deleteMutation = useDeleteCardBalance() + const downloadMutation = useDownloadCardBalance() + + // ── Columns ─────────────────────────────────────────────────────────────── + + const columns: ColumnDef[] = [ + { + id: 'id', + accessorKey: 'id', + header: t('ID', 'ID'), + cell: ({ row }) => ( + + ), + }, + { + id: 'passport_series', + accessorKey: 'passport_series', + header: t('Passport series', 'PASPORT SERIYASY'), + cell: ({ row }) => {row.original.passport_series}, + }, + { + id: 'passport_number', + accessorKey: 'passport_number', + header: t('Passport number', 'PASPORT BELGISI'), + cell: ({ row }) => {row.original.passport_number}, + }, + { + id: 'card_number', + accessorKey: 'card_number', + header: t('Card number', 'KART BELGISI'), + cell: ({ row }) => {row.original.card_number}, + }, + { + id: 'card_expiry_month', + accessorKey: 'card_expiry_month', + header: t('Expiry month', 'KART MÖHLETI (AÝ)'), + cell: ({ row }) => {row.original.card_expiry_month}, + }, + { + id: 'card_expiry_year', + accessorKey: 'card_expiry_year', + header: t('Expiry year', 'KART MÖHLETI (ÝYL)'), + cell: ({ row }) => {row.original.card_expiry_year}, + }, + { + id: 'actions', + header: '', + enableHiding: false, + cell: ({ row }) => ( +
+ + + + +
+ ), + }, + ] + + 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 ( +
+
+

+ {t('Card balances', 'Kart galyndylary')} +

+
+ + { 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) }} + /> + + String(row.id)} + currentPage={page} + totalPages={totalPages} + totalCount={total} + onPageChange={setPage} + /> + + !open && setDeleteId(null)}> + + + {t('Are you sure?', 'Eminsiňizmi?')} + + {t( + 'This action cannot be undone.', + 'Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.', + )} + + + + {t('Cancel', 'Ýatyr')} + + {deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/cardBalanceCreate/index.tsx b/src/pages/cardDepartment/cardBalanceCreate/index.tsx new file mode 100644 index 0000000..f446da8 --- /dev/null +++ b/src/pages/cardDepartment/cardBalanceCreate/index.tsx @@ -0,0 +1,16 @@ +import { useTranslation } from 'react-i18next' +import { CardBalanceForm } from '@/features/cardBalance/components/cardBalanceForm' + +export default function CardBalanceCreatePage() { + const { t } = useTranslation() + + return ( +
+

+ {t('Create card balance', 'Kart galyndysy dörediň')} +

+ + +
+ ) +} diff --git a/src/pages/cardDepartment/cardBalanceEdit/index.tsx b/src/pages/cardDepartment/cardBalanceEdit/index.tsx new file mode 100644 index 0000000..e0b9e6c --- /dev/null +++ b/src/pages/cardDepartment/cardBalanceEdit/index.tsx @@ -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 ( +
+ + {Array.from({ length: 8 }).map((_, i) => ( + + ))} +
+ ) + } + + if (!data) { + return ( +
+ {t('Not found', 'Tapylmady')} +
+ ) + } + + return ( +
+

+ {t('Edit card balance', 'Kart galyndysyny düzetmek')}:{' '} + {data.id} +

+ + +
+ ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/cardBalanceView/index.tsx b/src/pages/cardDepartment/cardBalanceView/index.tsx new file mode 100644 index 0000000..8132d15 --- /dev/null +++ b/src/pages/cardDepartment/cardBalanceView/index.tsx @@ -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 = { + 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 ( + + + {status} + + ) +} + +// ─── Detail row ─────────────────────────────────────────────────────────────── + +function DetailRow({ label, value }: { label: string; value: string | number }) { + return ( +
+
+ {label} +
+
{value}
+
+ ) +} + +// ─── 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 ( +
+ +
+ ) + } + + if (!data) { + return ( +
+ {t('Not found', 'Tapylmady')} +
+ ) + } + + return ( +
+ {/* Header */} +
+

+ {t('Card balance detail', 'Kart galyndysy giňişleýin')}: +

+
+ + + +
+
+ + {/* Detail card */} +
+ + + + + + +
+ + {/* Ammallar (Operations) collapsible section */} +
+ {/* Section toggle header */} + + + {opsExpanded && ( + <> +
+ + + + {[ + 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) => ( + + ))} + + + + {operations.length === 0 ? ( + + + + ) : ( + operations.map((op) => ( + + + + + + + + + )) + )} + +
+ {h} +
+ {t('No operations found', 'Amal tapylmady')} +
{op.id}{op.action_name}{op.performed_by}{op.target}{op.date}
+
+ + {/* Ops pagination */} +
+ + + {opsTotal === 0 ? '0' : `1–${opsTotal}`} {t('of', 'of')} {opsTotal} + + +
+ + )} +
+ + {/* Delete dialog */} + + + + {t('Are you sure?', 'Eminsiňizmi?')} + + {t( + 'This action cannot be undone.', + 'Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.', + )} + + + + {t('Cancel', 'Ýatyr')} + + {deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/cardPins/index.tsx b/src/pages/cardDepartment/cardPins/index.tsx new file mode 100644 index 0000000..5701715 --- /dev/null +++ b/src/pages/cardDepartment/cardPins/index.tsx @@ -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 = + { + 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 ( + + {cfg.label} + + ); +} + +// ─── 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(""); + + const [columnVisibility, setColumnVisibility] = useState({}); + const [columnOrder, setColumnOrder] = useState([]); + + const [deleteTarget, setDeleteTarget] = useState(null); + + const { data, isLoading } = useCardPins({ + page, + per_page: perPage, + search, + status: statusFilter, + }); + const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin(); + + const columns: ColumnDef[] = [ + { + accessorKey: "id", + header: "ID", + cell: ({ row }) => ( + + {row.original.id} + + ), + }, + { + accessorKey: "card_type_label", + header: t("cardPin.cardType", "Görnüşi"), + cell: ({ row }) => ( + + {row.original.card_type_label} + + ), + }, + { + accessorKey: "created_at", + header: t("cardPin.createdAt", "Döredilen wagty"), + cell: ({ row }) => ( + + {row.original.created_at} + + ), + }, + { + accessorKey: "province_label", + header: t("cardPin.province", "Welaýat"), + }, + { + accessorKey: "branch_label", + header: t("cardPin.branch", "Şahamça"), + cell: ({ row }) => ( + + {row.original.branch_label} + + ), + }, + { + 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 }) => ( + {row.original.phone} + ), + }, + { + accessorKey: "status", + header: t("cardPin.status", "Status"), + cell: ({ row }) => , + }, + { + id: "actions", + enableHiding: false, + cell: ({ row }) => ( +
+ + + +
+ ), + }, + ]; + + 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 ( +
+
+

+ {t("Card pins", "Kart pin bukjalary")} +

+
+ { + 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")} + /> + + + + {/* Delete confirmation */} + !o && setDeleteTarget(null)} + > + + + + {t("cardPin.deleteTitle", "Pozmak isleýärsiňizmi?")} + + + {t("cardPin.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")}{" "} + {deleteTarget?.id} + + + + + {t("common.cancel", "Ýatyr")} + + { + if (deleteTarget) { + deletePin(deleteTarget.id, { + onSuccess: () => setDeleteTarget(null), + }); + } + }} + > + {t("common.delete", "Poz")} + + + + +
+ ); +} diff --git a/src/pages/cardDepartment/cardPinsCreate/index.tsx b/src/pages/cardDepartment/cardPinsCreate/index.tsx new file mode 100644 index 0000000..b2ed046 --- /dev/null +++ b/src/pages/cardDepartment/cardPinsCreate/index.tsx @@ -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 ( + + ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/cardPinsEdit/index.tsx b/src/pages/cardDepartment/cardPinsEdit/index.tsx new file mode 100644 index 0000000..05ab629 --- /dev/null +++ b/src/pages/cardDepartment/cardPinsEdit/index.tsx @@ -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 ( +
+ +
+ ) + } + + if (isError || !data) { + return ( +
+ {t('common.notFound', 'Maglumat tapylmady')} +
+ ) + } + + return ( + + ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/cardPinsView/index.tsx b/src/pages/cardDepartment/cardPinsView/index.tsx new file mode 100644 index 0000000..61ac8cc --- /dev/null +++ b/src/pages/cardDepartment/cardPinsView/index.tsx @@ -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 = { + 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 ( + + + {cfg.label} + + ) +} + +// ─── Field row ──────────────────────────────────────────────────────────────── + +function FieldRow({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
+ {label} + {children} +
+ ) +} + +// ─── Passport image ─────────────────────────────────────────────────────────── + +function PassportImage({ label, url }: { label: string; url: string | null }) { + if (!url) return null + return ( +
+

{label}

+ +
+ ) +} + +// ─── 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 ( +
+ +
+ ) + } + + if (isError || !data) { + return ( +
+ {t('common.notFound', 'Maglumat tapylmady')} +
+ ) + } + + return ( +
+ {/* Header */} +
+

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

+
+ + + + + + + {t('cardPin.deleteTitle', 'Pozmak isleýärsiňizmi?')} + + {t('cardPin.deleteDesc', 'Bu amal yzyna dolanyp bolmaz.')} {data.id} + + + + + {t('common.cancel', 'Ýatyr')} + + deletePin(data.id, { onSuccess: () => navigate('/card-pins') })} + > + {t('common.delete', 'Poz')} + + + + + + +
+
+ + {/* Main Info */} +
+ + {data.id} + + + {data.created_at} + + + + + + {data.note || '—'} + + + {data.created_by_label} + +
+ + {/* Kart */} +
+

+ {t('cardPin.cardSection', 'Kart')} +

+
+ + {data.card_number} + + — + — +
+
+ + {/* Lokasiýa */} +
+

+ {t('cardPin.locationSection', 'Lokasiýa')} +

+
+ {data.province_label} + + {data.branch_label} + +
+
+ + {/* Şahsy maglumatlar */} +
+

+ {t('cardPin.personalSection', 'Şahsy maglumatlar')} +

+
+ + {`${data.last_name} ${data.first_name} ${data.father_name}`} + + {data.birth_date} + +{data.phone} +
+
+ + {/* Pasport */} +
+

+ {t('cardPin.passportSection', 'Pasport')} +

+
+ + {data.passport_series} + + + {data.passport_number} + +
+
+ + + + +
+
+
+ ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/cardRequisites/index.tsx b/src/pages/cardDepartment/cardRequisites/index.tsx new file mode 100644 index 0000000..a755a17 --- /dev/null +++ b/src/pages/cardDepartment/cardRequisites/index.tsx @@ -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 = { + 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 ( + + {cfg.label} + + ) +} + +// ─── 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(null) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([]) + + const { data, isLoading } = useCardRequisites({ page, per_page: perPage, search }) + const deleteMutation = useDeleteCardRequisite() + const downloadMutation = useDownloadCardRequisite() + + // ── Columns ────────────────────────────────────────────────────────────────── + + const columns: ColumnDef[] = [ + { + id: 'id', + accessorKey: 'id', + header: t('ID', 'ID'), + cell: ({ row }) => ( + + ), + }, + { + id: 'card_type', + accessorKey: 'card_type', + header: t('Card type', 'GÖRNÜŞI'), + cell: ({ row }) => ( + {row.original.card_type} + ), + }, + { + id: 'created_at', + accessorKey: 'created_at', + header: t('Created at', 'DÖREDILEN WAGTY'), + cell: ({ row }) => ( + {row.original.created_at} + ), + }, + { + id: 'province_name', + accessorKey: 'province_name', + header: t('Province', 'WELAÝAT'), + cell: ({ row }) => ( + {row.original.province_name ?? '—'} + ), + }, + { + id: 'branch_name', + accessorKey: 'branch_name', + header: t('Branch', 'ŞAHAMÇA'), + cell: ({ row }) => ( + {row.original.branch_name ?? '—'} + ), + }, + { + id: 'first_name', + accessorKey: 'first_name', + header: t('First name', 'ADY'), + cell: ({ row }) => {row.original.first_name}, + }, + { + id: 'last_name', + accessorKey: 'last_name', + header: t('Last name', 'FAMILIÝASY'), + cell: ({ row }) => {row.original.last_name}, + }, + { + id: 'status', + accessorKey: 'status', + header: t('Status', 'STATUS'), + cell: ({ row }) => , + }, + { + id: 'actions', + header: '', + enableHiding: false, + cell: ({ row }) => ( +
+ + + + +
+ ), + }, + ] + + // ── 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 ( +
+ {/* Header */} +
+

+ {t('Card requisites', 'Kart rekwizitler')} +

+
+ + {/* Toolbar */} + { 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 */} + row.id} + currentPage={page} + totalPages={totalPages} + totalCount={total} + onPageChange={setPage} + /> + + {/* Delete dialog */} + !open && setDeleteId(null)}> + + + {t('Are you sure?', 'Eminsiňizmi?')} + + {t( + 'This action cannot be undone.', + 'Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.', + )} + + + + {t('Cancel', 'Ýatyr')} + + {deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')} + + + + +
+ ) +} diff --git a/src/pages/cardDepartment/cardRequisitesCreate/index.tsx b/src/pages/cardDepartment/cardRequisitesCreate/index.tsx new file mode 100644 index 0000000..c1cf079 --- /dev/null +++ b/src/pages/cardDepartment/cardRequisitesCreate/index.tsx @@ -0,0 +1,15 @@ +import { useTranslation } from 'react-i18next' +import { CardRequisiteForm } from '@/features/cardRequisites/components/cardRequisiteForm' + +export default function CardRequisiteCreatePage() { + const { t } = useTranslation() + + return ( +
+

+ {t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň dörediň')} +

+ +
+ ) +} diff --git a/src/pages/cardDepartment/cardRequisitesEdit/index.tsx b/src/pages/cardDepartment/cardRequisitesEdit/index.tsx new file mode 100644 index 0000000..7439cf0 --- /dev/null +++ b/src/pages/cardDepartment/cardRequisitesEdit/index.tsx @@ -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 ( +
+ +
+ ) + } + + if (!data) { + return ( +
+ {t('Not found', 'Tapylmady')} +
+ ) + } + + return ( +
+

+ {t('Edit card requisite', 'Kart rekwizitini üýtget')} +

+ +
+ ) +} diff --git a/src/pages/cardDepartment/cardRequisitesView/index.tsx b/src/pages/cardDepartment/cardRequisitesView/index.tsx new file mode 100644 index 0000000..2001bba --- /dev/null +++ b/src/pages/cardDepartment/cardRequisitesView/index.tsx @@ -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 = { + 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 ( +
+
+ {label} +
+
{children}
+
+ ) +} + +// ─── Section header ─────────────────────────────────────────────────────────── + +function SectionTitle({ children }: { children: React.ReactNode }) { + return ( +

{children}

+ ) +} + +// ─── Passport image row ─────────────────────────────────────────────────────── + +function PassportImageRow({ label, url }: { label: string; url?: string }) { + return ( +
+
+ {label} +
+
+ {url ? ( + <> + {label} + + + {('Download', 'Göçürip al')} + + + ) : ( + — + )} +
+
+ ) +} + +// ─── 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 ( +
+ +
+ ) + } + + if (!data) { + return ( +
+ {t('Not found', 'Tapylmady')} +
+ ) + } + + const statusCfg = STATUS_BADGE[data.status] ?? STATUS_BADGE.pending + + return ( +
+ {/* Header */} +
+

+ {t('Card requisite detail', 'Kart rekwizit giňişleýin')}: {data.id} +

+
+ + + +
+
+ + {/* General info */} +
+ {data.id} + {data.created_at} + + + {statusCfg.label} + + + + {data.note || '—'} + + + {data.first_name && data.last_name ? ( + + {data.last_name}_{data.first_name} ({data.first_name}) + + ) : '—'} + +
+ + {/* Card */} + {t('Card', 'Kart')} +
+ {data.card_number} + {data.card_expiry_month} + {data.card_expiry_year} +
+ + {/* Location */} + {t('Location', 'Lokasiýa')} +
+ {data.province_name ?? '—'} + + {data.branch_name ?? '—'} + +
+ + {/* Personal */} + {t('Personal information', 'Şahsy maglumatlar')} +
+ + {[data.first_name, data.last_name, data.middle_name].filter(Boolean).join(' ')} + + {data.birth_date} + {data.phone} +
+ + {/* Passport */} + {t('Passport', 'Pasport')} +
+ {data.passport_series} + {data.passport_number} + + + + +
+ + {/* Delete dialog */} + + + + {t('Are you sure?', 'Eminsiňizmi?')} + + {t( + 'This action cannot be undone.', + 'Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.', + )} + + + + {t('Cancel', 'Ýatyr')} + + {deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')} + + + + +
+ ) +} diff --git a/src/pages/cardDepartment/cardTransactions/index.tsx b/src/pages/cardDepartment/cardTransactions/index.tsx new file mode 100644 index 0000000..8cd3953 --- /dev/null +++ b/src/pages/cardDepartment/cardTransactions/index.tsx @@ -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(null) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([]) + + const { data, isLoading } = useCardTransactions({ page, per_page: perPage, search }) + const deleteMutation = useDeleteCardTransaction() + const downloadMutation = useDownloadCardTransaction() + + // ── Columns ────────────────────────────────────────────────────────────────── + + const columns: ColumnDef[] = [ + { + id: 'id', + accessorKey: 'id', + header: t('ID', 'ID'), + cell: ({ row }) => ( + + ), + }, + { + id: 'passport_series', + accessorKey: 'passport_series', + header: t('Passport series', 'PASPORT SERIYASY'), + cell: ({ row }) => {row.original.passport_series}, + }, + { + id: 'passport_number', + accessorKey: 'passport_number', + header: t('Passport number', 'PASPORT BELGISI'), + cell: ({ row }) => {row.original.passport_number}, + }, + { + id: 'card_number', + accessorKey: 'card_number', + header: t('Card number', 'KART BELGISI'), + cell: ({ row }) => {row.original.card_number}, + }, + { + id: 'card_expiry_month', + accessorKey: 'card_expiry_month', + header: t('Expiry month', 'KART MÖHLETI (AÝ)'), + cell: ({ row }) => {row.original.card_expiry_month}, + }, + { + id: 'card_expiry_year', + accessorKey: 'card_expiry_year', + header: t('Expiry year', 'KART MÖHLETI (ÝYL)'), + cell: ({ row }) => {row.original.card_expiry_year}, + }, + { + id: 'actions', + header: '', + enableHiding: false, + cell: ({ row }) => ( +
+ + + + +
+ ), + }, + ] + + // ── 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 ( +
+ {/* Header */} +
+

+ {t('Card transactions', 'Kart hereketleri')} +

+
+ + {/* Toolbar */} + { 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 */} + row.id.toString()} + currentPage={page} + totalPages={totalPages} + totalCount={total} + onPageChange={setPage} + /> + + {/* Delete dialog */} + !open && setDeleteId(null)}> + + + {t('Are you sure?', 'Eminsiňizmi?')} + + {t( + 'This action cannot be undone. This will permanently delete the card transaction.', + 'Bu amal yzyna gaýtarylmaz. Kart herekedi hemişelik öçüriler.', + )} + + + + {t('Cancel', 'Ýatyr')} + + {deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')} + + + + +
+ ) +} diff --git a/src/pages/cardDepartment/cardTransactionsCreate/index.tsx b/src/pages/cardDepartment/cardTransactionsCreate/index.tsx new file mode 100644 index 0000000..810f05d --- /dev/null +++ b/src/pages/cardDepartment/cardTransactionsCreate/index.tsx @@ -0,0 +1,15 @@ +import { useTranslation } from 'react-i18next' +import { CardTransactionForm } from '@/features/cardTransactions/components/cardTransactionForm' + +export default function CardTransactionCreatePage() { + const { t } = useTranslation() + + return ( +
+

+ {t('Create card transaction', 'Kart herekedi dörediň')} +

+ +
+ ) +} diff --git a/src/pages/cardDepartment/cardTransactionsEdit/index.tsx b/src/pages/cardDepartment/cardTransactionsEdit/index.tsx new file mode 100644 index 0000000..8fce1cc --- /dev/null +++ b/src/pages/cardDepartment/cardTransactionsEdit/index.tsx @@ -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 ( +
+ +
+ ); + } + + if (!data) { + return ( +
+ {t("Not found", "Tapylmady")} +
+ ); + } + + return ( +
+

+ {t("Edit card transaction", "Kart herekedini üýtget")} +

+ +
+ ); +} diff --git a/src/pages/cardDepartment/cardTransactionsView/index.tsx b/src/pages/cardDepartment/cardTransactionsView/index.tsx new file mode 100644 index 0000000..e74c914 --- /dev/null +++ b/src/pages/cardDepartment/cardTransactionsView/index.tsx @@ -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 ( +
+
+ {label} +
+
{value}
+
+ ) +} + +// ─── 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 ( +
+ +
+ ) + } + + if (!data) { + return ( +
+ {t('Not found', 'Tapylmady')} +
+ ) + } + + return ( +
+ {/* Header */} +
+

+ {t('Card transaction detail', 'Kart herekedi giňişleýin')}: +

+
+ + + +
+
+ + {/* Detail card */} +
+ + + + + + +
+ + {/* Delete dialog */} + + + + {t('Are you sure?', 'Eminsiňizmi?')} + + {t( + 'This action cannot be undone. This will permanently delete the card transaction.', + 'Bu amal yzyna gaýtarylmaz. Kart herekedi hemişelik öçüriler.', + )} + + + + {t('Cancel', 'Ýatyr')} + + {deleteMutation.isPending + ? t('Deleting...', 'Öçürilýär...') + : t('Delete', 'Öçür')} + + + + +
+ ) +} diff --git a/src/pages/cardDepartment/orderNewCard/index.tsx b/src/pages/cardDepartment/orderNewCard/index.tsx new file mode 100644 index 0000000..8b4e483 --- /dev/null +++ b/src/pages/cardDepartment/orderNewCard/index.tsx @@ -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({}) + const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER) + const [activeFilters, setActiveFilters] = useState([ + { 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 }) => ( +
+ + + +
+ ), + 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 ( +
+ {/* Page Header */} +
+

+ {t('cardOrder.title', 'Kart sargytlary')} +

+
+ + {/* Table Card */} +
+ { 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')} + /> + + row.id} + currentPage={page} + totalPages={data?.totalPages ?? 1} + totalCount={data?.totalCount} + onPageChange={setPage} + /> +
+
+ ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/orderNewCardCreate/index.tsx b/src/pages/cardDepartment/orderNewCardCreate/index.tsx new file mode 100644 index 0000000..b66e1c1 --- /dev/null +++ b/src/pages/cardDepartment/orderNewCardCreate/index.tsx @@ -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 ( +
+
+

+ {t('cardOrder.createTitle', 'Kart sargyt dörediň')} +

+
+ + navigate('/order-new-card')} + onCancel={() => navigate('/order-new-card')} + /> +
+ ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/orderNewCardEdit/index.tsx b/src/pages/cardDepartment/orderNewCardEdit/index.tsx new file mode 100644 index 0000000..c9a8e65 --- /dev/null +++ b/src/pages/cardDepartment/orderNewCardEdit/index.tsx @@ -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 ( +
+ + {Array.from({ length: 8 }).map((_, i) => ( + + ))} +
+ ) + } + + if (!order) { + return ( +

+ {t('common.notFound', 'Tapylmady')} +

+ ) + } + + return ( +
+
+

+ {t('cardOrder.editTitle', 'Düzetmek')}:{' '} + {order.id} +

+
+ + navigate(`/order-new-card/${id}`)} + onCancel={() => navigate(`/order-new-card/${id}`)} + /> +
+ ) +} \ No newline at end of file diff --git a/src/pages/cardDepartment/orderNewCardView/index.tsx b/src/pages/cardDepartment/orderNewCardView/index.tsx new file mode 100644 index 0000000..67d2a66 --- /dev/null +++ b/src/pages/cardDepartment/orderNewCardView/index.tsx @@ -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 = { + 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 ( + + {cfg.icon} + {cfg.label} + + ) +} + +// ─── Info row ───────────────────────────────────────────────────────────────── + +function InfoRow({ + label, + children, +}: { + label: string + children: React.ReactNode +}) { + return ( +
+ {label} + {children} +
+ ) +} + +// ─── Section ────────────────────────────────────────────────────────────────── + +function Section({ title, children }: { title: string; children: React.ReactNode }) { + return ( +
+

{title}

+
+ {children} +
+
+ ) +} + +// ─── Passport file card ─────────────────────────────────────────────────────── + +function PassportFileCard({ label, url }: { label: string; url: string | null }) { + const { t } = useTranslation() + + return ( +
+ {label} +
+ {url ? ( + <> +
+ {label} { + ;(e.currentTarget as HTMLImageElement).style.display = 'none' + }} + /> +
+ + + {t('common.download', 'Göçürip al')} + + + ) : ( + — + )} +
+
+ ) +} + +// ─── Loading skeleton ───────────────────────────────────────────────────────── + +function DetailSkeleton() { + return ( +
+ +
+ {Array.from({ length: 5 }).map((_, i) => ( + + ))} +
+
+ ) +} + +// ─── 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 + if (!order) return ( +

+ {t('common.notFound', 'Tapylmady')} +

+ ) + + return ( +
+ + {/* Header */} +
+
+

+ {t('cardOrder.detailTitle', 'Kart sargyt giriş üçin')}:{' '} + {order.id} +

+
+ +
+ + + + +
+
+ + {/* Main info */} +
+ {order.id} + + {order.createdAt} + + + + {order.isPaid ? '✓' : '✕'} + + + + + + + {order.note ?? '—'} + + + {order.createdBy} + +
+ + {/* Kart */} +
+ + {order.issuanceReasonName} + + + {order.cardTypeName} + +
+ + {/* Lokasiýa */} +
+ + {order.provinceName} + + + {order.branchName} + +
+ + {/* Şahsy maglumatlar */} +
+ + {[order.lastName, order.firstName, order.middleName].filter(Boolean).join(' ')} + + + {order.birthDate} + + + {order.phone} + + + {order.phoneExtra ?? '—'} + + + {order.citizenship} + + + {order.registeredAddress} + + + {order.currentAddress} + + + {order.workplace} + +
+ + {/* Pasport faýýlar */} +
+ + + + +
+ + {/* Delete confirm dialog */} + + + + + {t('cardOrder.deleteTitle', 'Pozmak isleýärsiňizmi?')} + + + {t( + 'cardOrder.deleteDescription', + 'Bu kart sargyt hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.', + )} + + + + + {t('common.cancel', 'Ýatyr')} + + + {deleteMutation.isPending + ? t('common.deleting', 'Pozulýar...') + : t('common.delete', 'Pozmak')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/internationalPayments/visaMasterPayments/index.tsx b/src/pages/internationalPayments/visaMasterPayments/index.tsx new file mode 100644 index 0000000..0171f17 --- /dev/null +++ b/src/pages/internationalPayments/visaMasterPayments/index.tsx @@ -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 = { + 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 ( + + {cfg.label} + + ) +} + +// ─── 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 ( +
+ + {t('intlPayment.monthFilter', 'AÝ TÖLEGI')} + +
+ + +
+
+ ) +} + +// ─── 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('') + + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([]) + + const [deleteTarget, setDeleteTarget] = useState(null) + + const { data, isLoading } = useIntlPayments({ page, per_page: perPage, search, status: statusFilter, month }) + const { mutate: deletePayment, isPending: isDeleting } = useDeleteIntlPayment() + + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + {row.original.id} + ), + }, + { + accessorKey: 'currency_type_label', + header: t('intlPayment.currencyType', 'Ýüztumanyň görnüşi'), + cell: ({ row }) => ( + {row.original.currency_type_label} + ), + }, + { + accessorKey: 'created_at', + header: t('intlPayment.createdAt', 'Döredilen wagty'), + cell: ({ row }) => ( + {row.original.created_at} + ), + }, + { + accessorKey: 'province_label', + header: t('intlPayment.province', 'Welaýat'), + }, + { + accessorKey: 'branch_label', + header: t('intlPayment.branch', 'Şahamça'), + cell: ({ row }) => ( + {row.original.branch_label} + ), + }, + { + 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 }) => ( + {row.original.phone} + ), + }, + { + accessorKey: 'status', + header: t('intlPayment.status', 'Status'), + cell: ({ row }) => , + }, + { + id: 'actions', + enableHiding: false, + cell: ({ row }) => ( +
+ + + +
+ ), + }, + ] + + 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 ( +
+
+

+ {t("intlPayment.title", "Halkara tölegler (Visa/Mastercard)")} +

+
+ { setMonth(v); setPage(1) }} /> + + { 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')} + /> + + + + !o && setDeleteTarget(null)}> + + + {t('intlPayment.deleteTitle', 'Pozmak isleýärsiňizmi?')} + + {t('intlPayment.deleteDesc', 'Bu amal yzyna dolanyp bolmaz.')} {deleteTarget?.id} + + + + {t('common.cancel', 'Ýatyr')} + { + if (deleteTarget) { + deletePayment(deleteTarget.id, { onSuccess: () => setDeleteTarget(null) }) + } + }} + > + {t('common.delete', 'Poz')} + + + + +
+ ) +} diff --git a/src/pages/internationalPayments/visaMasterPaymentsCreate/index.tsx b/src/pages/internationalPayments/visaMasterPaymentsCreate/index.tsx new file mode 100644 index 0000000..e218eb4 --- /dev/null +++ b/src/pages/internationalPayments/visaMasterPaymentsCreate/index.tsx @@ -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 ( + + ) +} diff --git a/src/pages/internationalPayments/visaMasterPaymentsEdit/index.tsx b/src/pages/internationalPayments/visaMasterPaymentsEdit/index.tsx new file mode 100644 index 0000000..803a404 --- /dev/null +++ b/src/pages/internationalPayments/visaMasterPaymentsEdit/index.tsx @@ -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 ( +
+ +
+ ) + } + + if (isError || !data) { + return ( +
+ {t('common.notFound', 'Maglumat tapylmady')} +
+ ) + } + + return ( + + ) +} diff --git a/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx b/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx new file mode 100644 index 0000000..7f9fac2 --- /dev/null +++ b/src/pages/internationalPayments/visaMasterPaymentsView/index.tsx @@ -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 = { + 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 ( + + + {cfg.label} + + ) +} + +// ─── FieldRow ───────────────────────────────────────────────────────────────── + +function FieldRow({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
+ {label} + {children ?? '—'} +
+ ) +} + +// ─── Section ────────────────────────────────────────────────────────────────── + +function Section({ title, children }: { title: string; children: React.ReactNode }) { + return ( +
+

{title}

+
{children}
+
+ ) +} + +// ─── DocFile row ───────────────────────────────────────────────────────────── + +function DocFileRow({ label, url }: { label: string; url: string | null }) { + if (!url) return ( +
+ {label} + — +
+ ) + + const filename = url.split('/').pop() ?? 'faýl' + const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(url) + + return ( +
+ {label} +
+ {isImage && ( + + + {filename} + + )} + + + {filename} + +
+
+ ) +} + +// ─── 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 ( +
+ +
+ ) + } + + if (isError || !data) { + return ( +
+ {t('common.notFound', 'Maglumat tapylmady')} +
+ ) + } + + 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 ( +
+ {/* Header */} +
+
{/* breadcrumb handled by layout */} +
+ + + + + + + {t('intlPayment.deleteTitle', 'Pozmak isleýärsiňizmi?')} + + {t('intlPayment.deleteDesc', 'Bu amal yzyna dolanyp bolmaz.')} {data.id} + + + + {t('common.cancel', 'Ýatyr')} + deletePayment(data.id, { onSuccess: () => navigate('/intl-payments/visa-master') })} + > + {t('common.delete', 'Poz')} + + + + + + +
+
+ + {/* Status */} +
+
+ + {data.client_label} + + + {data.id} + + + + + + {data.created_at} + + + {data.note} + +
+
+ + {/* Ýüztumanyň görnüşi */} +
+
+ + {data.currency_type_label} + +
+
+ + {/* Lokasiýa */} +
+
+ {data.province_label} + + {data.branch_label} + +
+
+ + {/* Şahsy maglumatlar */} +
+
+ {data.passport_first_name} + {data.passport_last_name} + +{data.phone} + {data.email} + {data.home_address} +
+
+ + {/* Töleg */} +
+
+ + {data.payer_full_name} + + + {data.payer_account_number} + +
+ {/* Receiver table */} +
+ + + + + + + + + + + + + + + +
+ {t('intlPayment.passportSeries', 'Pasport seriýasy')} + + {t('intlPayment.passportNumber', 'Pasport nomeri')} + + {t('intlPayment.payerFullName', 'Ady Familiýasy Atasnyň ady')} +
{data.passport_series} – {data.passport_number}{data.passport_number}{data.payer_full_name}
+
+
+ + {/* Kabul ediji talyp boyunca resminamalar */} +
+
+ {KABUL_DOCS.map((doc, i) => ( + + ))} +
+
+ + {/* Upgradyý boyunca resminamalar */} +
+
+ {UPGRAD_DOCS.map((doc, i) => ( + + ))} +
+
+ + {/* Töleg taryhy */} +
+
+
+ + 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" + /> +
+
+
+
+ + + + + +
+

{t('intlPayment.noHistory', 'Beriilen kriteriýalara Töleg gabat gelmedi')}

+
+
+
+ ) +} diff --git a/src/pages/loanOrderCreate/index.tsx b/src/pages/loanDepartment/loanOrderCreate/index.tsx similarity index 100% rename from src/pages/loanOrderCreate/index.tsx rename to src/pages/loanDepartment/loanOrderCreate/index.tsx diff --git a/src/pages/loanOrderEdit/index.tsx b/src/pages/loanDepartment/loanOrderEdit/index.tsx similarity index 100% rename from src/pages/loanOrderEdit/index.tsx rename to src/pages/loanDepartment/loanOrderEdit/index.tsx diff --git a/src/pages/loanOrderMobile/index.tsx b/src/pages/loanDepartment/loanOrderMobile/index.tsx similarity index 100% rename from src/pages/loanOrderMobile/index.tsx rename to src/pages/loanDepartment/loanOrderMobile/index.tsx diff --git a/src/pages/loanDepartment/loanOrderMobileCreate/index.tsx b/src/pages/loanDepartment/loanOrderMobileCreate/index.tsx new file mode 100644 index 0000000..26f0480 --- /dev/null +++ b/src/pages/loanDepartment/loanOrderMobileCreate/index.tsx @@ -0,0 +1,5 @@ +import { LoanOrderMobileForm } from "@/features/loanOrderMobiles/components/loanOrderMobileForm"; + +export default function LoanOrderMobilesCreatePage() { + return ; +} diff --git a/src/pages/loanOrderMobileEdit/index.tsx b/src/pages/loanDepartment/loanOrderMobileEdit/index.tsx similarity index 57% rename from src/pages/loanOrderMobileEdit/index.tsx rename to src/pages/loanDepartment/loanOrderMobileEdit/index.tsx index 589b447..490d4a7 100644 --- a/src/pages/loanOrderMobileEdit/index.tsx +++ b/src/pages/loanDepartment/loanOrderMobileEdit/index.tsx @@ -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 (
- ) + ); } if (isError || !data) { @@ -22,14 +22,10 @@ export default function LoanOrderMobilesEditPage() { Maglumat ýüklenilmedi. Sahypany täzeleläň.

- ) + ); } return ( - - ) + + ); } diff --git a/src/pages/loanOrderMobileView/index.tsx b/src/pages/loanDepartment/loanOrderMobileView/index.tsx similarity index 100% rename from src/pages/loanOrderMobileView/index.tsx rename to src/pages/loanDepartment/loanOrderMobileView/index.tsx diff --git a/src/pages/loanOrderView/index.tsx b/src/pages/loanDepartment/loanOrderView/index.tsx similarity index 100% rename from src/pages/loanOrderView/index.tsx rename to src/pages/loanDepartment/loanOrderView/index.tsx diff --git a/src/pages/loanOrders/index.tsx b/src/pages/loanDepartment/loanOrders/index.tsx similarity index 100% rename from src/pages/loanOrders/index.tsx rename to src/pages/loanDepartment/loanOrders/index.tsx diff --git a/src/pages/loanPaidOffLetters/index.tsx b/src/pages/loanDepartment/loanPaidOffLetters/index.tsx similarity index 100% rename from src/pages/loanPaidOffLetters/index.tsx rename to src/pages/loanDepartment/loanPaidOffLetters/index.tsx diff --git a/src/pages/loanRemaining/index.tsx b/src/pages/loanDepartment/loanRemaining/index.tsx similarity index 100% rename from src/pages/loanRemaining/index.tsx rename to src/pages/loanDepartment/loanRemaining/index.tsx diff --git a/src/pages/loanRemainingCreate/index.tsx b/src/pages/loanDepartment/loanRemainingCreate/index.tsx similarity index 100% rename from src/pages/loanRemainingCreate/index.tsx rename to src/pages/loanDepartment/loanRemainingCreate/index.tsx diff --git a/src/pages/loanRemainingEdit/index.tsx b/src/pages/loanDepartment/loanRemainingEdit/index.tsx similarity index 100% rename from src/pages/loanRemainingEdit/index.tsx rename to src/pages/loanDepartment/loanRemainingEdit/index.tsx diff --git a/src/pages/loanRemainingView/index.tsx b/src/pages/loanDepartment/loanRemainingView/index.tsx similarity index 100% rename from src/pages/loanRemainingView/index.tsx rename to src/pages/loanDepartment/loanRemainingView/index.tsx diff --git a/src/pages/loanOrderMobileCreate/index.tsx b/src/pages/loanOrderMobileCreate/index.tsx deleted file mode 100644 index b4c4601..0000000 --- a/src/pages/loanOrderMobileCreate/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { LoanOrderMobileForm } from '@/components/loanOrderMobileForm' - -export default function LoanOrderMobilesCreatePage() { - return -}