From d8821a0199ecb9168c5f864f39cfcf1a5e4ca548 Mon Sep 17 00:00:00 2001 From: "@jcarymuhammedow" Date: Wed, 13 May 2026 17:29:32 +0500 Subject: [PATCH] added setting card pages --- package-lock.json | 50 ++-- src/app/router/index.tsx | 74 +++++ .../cardReasons/api/cardReasonsApi.ts | 108 ++++++++ .../cardReasons/components/reasonForm.tsx | 231 ++++++++++++++++ .../cardReasons/hooks/useCardReasons.ts | 101 +++++++ src/features/cardTypes/api/cardTypesApi.ts | 107 ++++++++ .../cardTypes/components/cardTypesForm.tsx | 224 ++++++++++++++++ src/features/cardTypes/hooks/useCardTypes.ts | 101 +++++++ src/layouts/DashboardLayout.tsx | 4 +- src/pages/settings/card/cardTypes/index.tsx | 249 +++++++++++++++++ .../settings/card/cardTypesCreate/index.tsx | 40 +++ .../settings/card/cardTypesEdit/index.tsx | 65 +++++ .../settings/card/cardTypesView/index.tsx | 174 ++++++++++++ src/pages/settings/card/reasons/index.tsx | 253 ++++++++++++++++++ .../settings/card/reasonsCreate/index.tsx | 41 +++ src/pages/settings/card/reasonsEdit/index.tsx | 68 +++++ src/pages/settings/card/reasonsView/index.tsx | 180 +++++++++++++ 17 files changed, 2042 insertions(+), 28 deletions(-) create mode 100644 src/features/cardReasons/api/cardReasonsApi.ts create mode 100644 src/features/cardReasons/components/reasonForm.tsx create mode 100644 src/features/cardReasons/hooks/useCardReasons.ts create mode 100644 src/features/cardTypes/api/cardTypesApi.ts create mode 100644 src/features/cardTypes/components/cardTypesForm.tsx create mode 100644 src/features/cardTypes/hooks/useCardTypes.ts create mode 100644 src/pages/settings/card/cardTypes/index.tsx create mode 100644 src/pages/settings/card/cardTypesCreate/index.tsx create mode 100644 src/pages/settings/card/cardTypesEdit/index.tsx create mode 100644 src/pages/settings/card/cardTypesView/index.tsx create mode 100644 src/pages/settings/card/reasons/index.tsx create mode 100644 src/pages/settings/card/reasonsCreate/index.tsx create mode 100644 src/pages/settings/card/reasonsEdit/index.tsx create mode 100644 src/pages/settings/card/reasonsView/index.tsx diff --git a/package-lock.json b/package-lock.json index c2c5893..863fdec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -97,7 +97,6 @@ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -659,6 +658,29 @@ "@noble/ciphers": "^1.0.0" } }, + "node_modules/@emnapi/core": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", + "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.1", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", + "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@emnapi/wasi-threads": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", @@ -812,7 +834,6 @@ "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz", "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==", "license": "MIT", - "peer": true, "dependencies": { "@floating-ui/core": "^1.7.5", "@floating-ui/utils": "^0.2.11" @@ -1169,7 +1190,6 @@ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", "license": "MIT", - "peer": true, "engines": { "node": "^14.21.3 || >=16" }, @@ -3443,7 +3463,6 @@ "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.23.2.tgz", "integrity": "sha512-yjv2N7gaQMbIVfsSZHBMscLoybgetcTraXsSMrELAerl/jfRipg5S1dBXMFvgRy8Kh48+TGoH+5nqshxdOEGoQ==", "license": "MIT", - "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/ueberdosis" @@ -3666,7 +3685,6 @@ "resolved": "https://registry.npmjs.org/@tiptap/extension-list/-/extension-list-3.23.2.tgz", "integrity": "sha512-tRbbjpOPrY4ApIHtn3ctnKIhkkioewMsZa5gJzqVB47LJFNyzLXLo/aID4sJRKTIMi1wd1fA9TiBKPe6KqczPA==", "license": "MIT", - "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/ueberdosis" @@ -3772,7 +3790,6 @@ "resolved": "https://registry.npmjs.org/@tiptap/extensions/-/extensions-3.23.2.tgz", "integrity": "sha512-kRHQ3nSbAfkFdxj9FtDdr4hpREndGgWFA6ZEAwlLeGUxf8QYTpuF9zb2yxdBPBlTc5+JsbPcskNt+u1PazGKYw==", "license": "MIT", - "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/ueberdosis" @@ -3787,7 +3804,6 @@ "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.23.2.tgz", "integrity": "sha512-1kvsBqGNu2ZJ0P/lkxN0pAMqSyUcpkMIzE4xwGUIyAiD0pZV6dr+OCMwGWOTLllSyrn91xI5K7OLk3pYeCPKqA==", "license": "MIT", - "peer": true, "dependencies": { "prosemirror-changeset": "^2.3.0", "prosemirror-commands": "^1.6.2", @@ -3981,7 +3997,6 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz", "integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==", "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~7.16.0" } @@ -3991,7 +4006,6 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", "license": "MIT", - "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -4001,7 +4015,6 @@ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", "license": "MIT", - "peer": true, "peerDependencies": { "@types/react": "^19.2.0" } @@ -4078,7 +4091,6 @@ "integrity": "sha512-HDQH9O/47Dxi1ceDhBXdaldtf/WV9yRYMjbjCuNk3qnaTD564qwv61Y7+gTxwxRKzSrgO5uhtw584igXVuuZkA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.59.1", "@typescript-eslint/types": "8.59.1", @@ -4322,7 +4334,6 @@ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -4604,7 +4615,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", @@ -5464,7 +5474,6 @@ "integrity": "sha512-XbEXaRva5cF0ZQB8w6MluHA0kZZfV2DuCMJ3ozyEOHLwDpZX2Lmm/7Pp0xdJmI0GL1W05VH5VwIFHEm1Vcw2gw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", @@ -5721,7 +5730,6 @@ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", "license": "MIT", - "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", @@ -6396,7 +6404,6 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.16.tgz", "integrity": "sha512-jN0ZewiNAWSe5khM3EyCmBb250+b40wWbwNILNfEvq84VREWwOIkuUsFONk/3i3nqkz7Oe1PcpM2mwQEK2L9Kg==", "license": "MIT", - "peer": true, "engines": { "node": ">=16.9.0" } @@ -6471,7 +6478,6 @@ } ], "license": "MIT", - "peer": true, "peerDependencies": { "typescript": "^5 || ^6" }, @@ -7881,7 +7887,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -8272,7 +8277,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.5.tgz", "integrity": "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -8304,7 +8308,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.5.tgz", "integrity": "sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==", "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -8351,7 +8354,6 @@ "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz", "integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==", "license": "MIT", - "peer": true, "dependencies": { "@types/use-sync-external-store": "^0.0.6", "use-sync-external-store": "^1.4.0" @@ -8546,8 +8548,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/redux-thunk": { "version": "3.1.0", @@ -9319,7 +9320,6 @@ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "devOptional": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -9554,7 +9554,6 @@ "integrity": "sha512-rZuUu9j6J5uotLDs+cAA4O5H4K1SfPliUlQwqa6YEwSrWDZzP4rhm00oJR5snMewjxF5V/K3D4kctsUTsIU9Mw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", @@ -9884,7 +9883,6 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.2.tgz", "integrity": "sha512-IynmDyxsEsb9RKzO3J9+4SxXnl2FTFSzNBaKKaMV6tsSk0rw9gYw9gs+JFCq/qk2LCZ78KDwyj+Z289TijSkUw==", "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index dfd92dd..6439dd7 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -147,6 +147,16 @@ const RequiredDocumentCreatePage = lazy(() => import("@/pages/settings/loan/requ const RequiredDocumentsViewPage = lazy(() => import("@/pages/settings/loan/requiredDocumentsView")); const RequiredDocumentEditPage = lazy(() => import("@/pages/settings/loan/requiredDocumentsEdit")); +const CardReasonsPage = lazy(() => import("@/pages/settings/card/reasons")); +const CardReasonCreatePage = lazy(() => import("@/pages/settings/card/reasonsCreate")); +const CardReasonsViewPage = lazy(() => import("@/pages/settings/card/reasonsView")); +const CardReasonEditPage = lazy(() => import("@/pages/settings/card/reasonsEdit")); + +const CardTypesPage = lazy(() => import("@/pages/settings/card/cardTypes")); +const CardTypeCreatePage = lazy(() => import("@/pages/settings/card/cardTypesCreate")); +const CardTypesViewPage = lazy(() => import("@/pages/settings/card/cardTypesView")); +const CardTypeEditPage = lazy(() => import("@/pages/settings/card/cardTypesEdit")); + function AuthGuard() { const isAuthenticated = useAuthStore((s) => s.isAuthenticated); if (!isAuthenticated) return ; @@ -827,6 +837,70 @@ export const router = createBrowserRouter([ ), }, + { + path: "/settings/card/card-reasons", + element: ( + }> + + + ), + }, + { + path: "/settings/card/card-reasons/create", + element: ( + }> + + + ), + }, + { + path: "/settings/card/card-reasons/:id", + element: ( + }> + + + ), + }, + { + path: "/settings/card/card-reasons/:id/edit", + element: ( + }> + + + ), + }, + { + path: "/settings/card/card-types", + element: ( + }> + + + ), + }, + { + path: "/settings/card/card-types/create", + element: ( + }> + + + ), + }, + { + path: "/settings/card/card-types/:id", + element: ( + }> + + + ), + }, + { + path: "/settings/card/card-types/:id/edit", + element: ( + }> + + + ), + }, ], }, ], diff --git a/src/features/cardReasons/api/cardReasonsApi.ts b/src/features/cardReasons/api/cardReasonsApi.ts new file mode 100644 index 0000000..5fd649c --- /dev/null +++ b/src/features/cardReasons/api/cardReasonsApi.ts @@ -0,0 +1,108 @@ +// ─── Types ──────────────────────────────────────────────────────────────────── + +export interface CardReason { + id: number + name: Record<'tk' | 'ru' | 'en', string> + value: number + description: string | null + isActive: boolean +} + +export interface CardReasonListResponse { + data: CardReason[] + total: number + page: number + perPage: number +} + +export interface CreateCardReasonPayload { + name: Record<'tk' | 'ru' | 'en', string> + value: number + description: string | null + isActive: boolean +} + +export interface UpdateCardReasonPayload extends CreateCardReasonPayload { + id: number +} + +// ─── Mock Data ──────────────────────────────────────────────────────────────── + +const MOCK_CARD_STATES: CardReason[] = [ + { id: 1, name: { tk: 'Täze', ru: 'Новый', en: 'New' }, value: 32, description: null, isActive: true }, + { id: 2, name: { tk: 'Döwülen/Zaýalanan', ru: 'Сломанный/Поврежденный', en: 'Broken/Damaged' }, value: 32, description: null, isActive: true }, + { id: 3, name: { tk: 'Ulanylyş möhleti geçen', ru: 'Срок истёк', en: 'Expired' }, value: 32, description: null, isActive: true }, + { id: 4, name: { tk: 'Maşgalasy üýtgeýär', ru: 'Смена фамилии', en: 'Name change' }, value: 32, description: null, isActive: true }, + { id: 5, name: { tk: 'Ýiten', ru: 'Потерян', en: 'Lost' }, value: 37.75, description: null, isActive: true }, + { id: 6, name: { tk: 'Pin bukja (bloklanan)', ru: 'Пин конверт (заблокирован)', en: 'Pin envelope (blocked)' }, value: 3.02, description: null, isActive: false }, + { id: 7, name: { tk: 'Rekwizit', ru: 'Реквизит', en: 'Requisite' }, value: 2.30, description: null, isActive: false }, +] + +let mockStore = [...MOCK_CARD_STATES] +let nextId = 8 + +// Simulated async delay +const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms)) + +// ─── API Functions ──────────────────────────────────────────────────────────── + +export async function fetchCardReasons(params: { + page?: number + perPage?: number + search?: string + isActive?: string +}): Promise { + await delay() + const { page = 1, perPage = 25, search = '', isActive } = params + + let filtered = mockStore.filter((item) => { + const matchSearch = + !search || + Object.values(item.name).some((n) => + n.toLowerCase().includes(search.toLowerCase()) + ) + const matchActive = + isActive === '' || isActive === undefined + ? true + : isActive === 'true' + ? item.isActive + : !item.isActive + return matchSearch && matchActive + }) + + filtered = [...filtered].sort((a, b) => b.id - a.id) + + const total = filtered.length + const start = (page - 1) * perPage + const data = filtered.slice(start, start + perPage) + + return { data, total, page, perPage } +} + +export async function fetchCardReasonById(id: number): Promise { + await delay() + const item = mockStore.find((c) => c.id === id) + if (!item) throw new Error('Not found') + return { ...item } +} + +export async function createCardReason(payload: CreateCardReasonPayload): Promise { + await delay(400) + const newItem: CardReason = { id: nextId++, ...payload } + mockStore = [newItem, ...mockStore] + return newItem +} + +export async function updateCardReason(payload: UpdateCardReasonPayload): Promise { + await delay(400) + const idx = mockStore.findIndex((c) => c.id === payload.id) + if (idx === -1) throw new Error('Not found') + const updated = { ...mockStore[idx], ...payload } + mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c)) + return updated +} + +export async function deleteCardReason(id: number): Promise { + await delay(300) + mockStore = mockStore.filter((c) => c.id !== id) +} \ No newline at end of file diff --git a/src/features/cardReasons/components/reasonForm.tsx b/src/features/cardReasons/components/reasonForm.tsx new file mode 100644 index 0000000..8ddbc7b --- /dev/null +++ b/src/features/cardReasons/components/reasonForm.tsx @@ -0,0 +1,231 @@ +import { useState, useEffect } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Button } from '@/components/ui/button' +import { Checkbox } from '@/components/ui/checkbox' +import { FormInput } from '@/components/formInput' +import type { CardReason, CreateCardReasonPayload } from '../api/cardReasonsApi' +import { useCreateCardReason, useUpdateCardReason } from '../hooks/useCardReasons' + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface FormErrors { + nameTk?: string + nameRu?: string + nameEn?: string + value?: string +} + +interface FormState { + nameTk: string + nameRu: string + nameEn: string + value: string + description: string + isActive: boolean +} + +interface CardReasonFormProps { + mode: 'create' | 'edit' + initialData?: CardReason + CardReasonId?: number +} + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +function buildInitialState(data?: CardReason): FormState { + if (!data) { + return { nameTk: '', nameRu: '', nameEn: '', value: '', description: '', isActive: true } + } + return { + nameTk: data.name.tk, + nameRu: data.name.ru, + nameEn: data.name.en, + value: String(data.value), + description: data.description ?? '', + isActive: data.isActive, + } +} + +function validate(form: FormState, t: (k: string, fb: string) => string): FormErrors { + const errors: FormErrors = {} + if (!form.nameTk.trim()) + errors.nameTk = t('validation.required', 'Hökmany meýdan') + if (!form.nameRu.trim()) + errors.nameRu = t('validation.required', 'Hökmany meýdan') + if (!form.nameEn.trim()) + errors.nameEn = t('validation.required', 'Hökmany meýdan') + if (!form.value.trim() || isNaN(Number(form.value)) || Number(form.value) < 0) + errors.value = t('validation.invalidNumber', 'Dogry san giriziň') + return errors +} + +// ─── Lang Tab ───────────────────────────────────────────────────────────────── + +type LangKey = 'tk' | 'ru' | 'en' + +const LANG_TABS: { key: LangKey; label: string }[] = [ + { key: 'tk', label: 'Türkmen' }, + { key: 'ru', label: 'Русский' }, + { key: 'en', label: 'English' }, +] + +// ─── CardReasonForm ───────────────────────────────────────────────────────────── + +export function CardReasonForm({ mode, initialData, CardReasonId }: CardReasonFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const createMutation = useCreateCardReason() + const updateMutation = useUpdateCardReason() + + const isPending = createMutation.isPending || updateMutation.isPending + + const [activeLang, setActiveLang] = useState('tk') + const [form, setForm] = useState(() => buildInitialState(initialData)) + const [errors, setErrors] = useState({}) + + // Sync form when initialData arrives (edit mode data fetch) + useEffect(() => { + if (initialData) setForm(buildInitialState(initialData)) + }, [initialData]) + + const set = (key: keyof FormState) => (value: string | boolean) => + setForm((prev) => ({ ...prev, [key]: value })) + + const handleSubmit = () => { + const errs = validate(form, t) + if (Object.keys(errs).length > 0) { + setErrors(errs) + return + } + setErrors({}) + + const payload: CreateCardReasonPayload = { + name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn }, + value: Number(form.value), + description: form.description.trim() || null, + isActive: form.isActive, + } + + if (mode === 'create') { + createMutation.mutate(payload, { + onSuccess: () => navigate('/resources/card-states'), + }) + } else if (CardReasonId !== undefined) { + updateMutation.mutate( + { id: CardReasonId, ...payload }, + { onSuccess: () => navigate('/resources/card-states') } + ) + } + } + + const nameFieldKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as + | 'nameTk' + | 'nameRu' + | 'nameEn' + const nameErrorKey = nameFieldKey as keyof FormErrors + + return ( +
+ {/* Language tabs */} +
+ {LANG_TABS.map((tab) => ( + + ))} +
+ + {/* Form rows */} +
+ {/* Name row */} +
+ + {t('CardReasons.fields.name', 'Ady')} + * + + +
+ + {/* Value row */} +
+ + {t('CardReasons.fields.value', 'Baha')} + * + + +
+ + {/* Description row */} +
+ + {t('CardReasons.fields.description', 'Bellikler')} + + +
+ + {/* isActive row */} +
+ + {t('CardReasons.fields.isActive', 'Işjeň')} + + set('isActive')(!!checked)} + /> +
+
+ + {/* Actions */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/cardReasons/hooks/useCardReasons.ts b/src/features/cardReasons/hooks/useCardReasons.ts new file mode 100644 index 0000000..93d4163 --- /dev/null +++ b/src/features/cardReasons/hooks/useCardReasons.ts @@ -0,0 +1,101 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { + fetchCardReasons, + fetchCardReasonById, + createCardReason, + updateCardReason, + deleteCardReason, + type CreateCardReasonPayload, + type UpdateCardReasonPayload, +} from '../api/cardReasonsApi' + +// ─── Query Keys ─────────────────────────────────────────────────────────────── + +export const cardReasonKeys = { + all: ['cardReasons'] as const, + lists: () => [...cardReasonKeys.all, 'list'] as const, + list: (params: Record) => + [...cardReasonKeys.lists(), params] as const, + detail: (id: number) => [...cardReasonKeys.all, 'detail', id] as const, +} + +// ─── useCardReasons ──────────────────────────────────────────────────────────── + +export function useCardReasons(params: { + page?: number + perPage?: number + search?: string + isActive?: string +}) { + return useQuery({ + queryKey: cardReasonKeys.list(params), + queryFn: () => fetchCardReasons(params), + }) +} + +// ─── useCardReasonById ───────────────────────────────────────────────────────── + +export function useCardReasonById(id: number) { + return useQuery({ + queryKey: cardReasonKeys.detail(id), + queryFn: () => fetchCardReasonById(id), + enabled: !!id, + }) +} + +// ─── useCreateCardReason ─────────────────────────────────────────────────────── + +export function useCreateCardReason() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: CreateCardReasonPayload) => createCardReason(payload), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() }) + toast.success(t('CardReasons.toast.createSuccess', 'Kart ýagdaýy döredildi')) + }, + onError: () => { + toast.error(t('CardReasons.toast.createError', 'Döretmek başartmady')) + }, + }) +} + +// ─── useUpdateCardReason ─────────────────────────────────────────────────────── + +export function useUpdateCardReason() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: UpdateCardReasonPayload) => updateCardReason(payload), + onSuccess: (data) => { + queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() }) + queryClient.invalidateQueries({ queryKey: cardReasonKeys.detail(data.id) }) + toast.success(t('CardReasons.toast.updateSuccess', 'Kart ýagdaýy täzelendi')) + }, + onError: () => { + toast.error(t('CardReasons.toast.updateError', 'Täzelemek başartmady')) + }, + }) +} + +// ─── useDeleteCardReason ─────────────────────────────────────────────────────── + +export function useDeleteCardReason() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (id: number) => deleteCardReason(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() }) + toast.success(t('CardReasons.toast.deleteSuccess', 'Kart ýagdaýy öçürildi')) + }, + onError: () => { + toast.error(t('CardReasons.toast.deleteError', 'Öçürmek başartmady')) + }, + }) +} \ No newline at end of file diff --git a/src/features/cardTypes/api/cardTypesApi.ts b/src/features/cardTypes/api/cardTypesApi.ts new file mode 100644 index 0000000..ba1e405 --- /dev/null +++ b/src/features/cardTypes/api/cardTypesApi.ts @@ -0,0 +1,107 @@ +// ─── Types ──────────────────────────────────────────────────────────────────── + +export interface CardType { + id: number + name: Record<'tk' | 'ru' | 'en', string> + value: number + description: string | null + isActive: boolean +} + +export interface CardTypeListResponse { + data: CardType[] + total: number + page: number + perPage: number +} + +export interface CreateCardTypePayload { + name: Record<'tk' | 'ru' | 'en', string> + value: number + description: string | null + isActive: boolean +} + +export interface UpdateCardTypePayload extends CreateCardTypePayload { + id: number +} + +// ─── Mock Store ─────────────────────────────────────────────────────────────── + +const MOCK_CARD_TYPES: CardType[] = [ + { id: 1, name: { tk: 'Altyn Asyr', ru: 'Алтын Асыр', en: 'Altyn Asyr' }, value: 32, description: null, isActive: true }, + { id: 2, name: { tk: 'Maşgala', ru: 'Семья', en: 'Family' }, value: 32, description: null, isActive: true }, + { id: 3, name: { tk: 'Goýum', ru: 'Депозит', en: 'Deposit' }, value: 32, description: null, isActive: true }, + { id: 4, name: { tk: 'Pensiýa', ru: 'Пенсия', en: 'Pension' }, value: 32, description: null, isActive: true }, + { id: 5, name: { tk: 'Telekeçi', ru: 'Предприниматель', en: 'Entrepreneur' }, value: 32, description: null, isActive: true }, + { id: 6, name: { tk: 'Karz', ru: 'Кредит', en: 'Credit' }, value: 32, description: null, isActive: false }, + { id: 7, name: { tk: 'Owerdraft', ru: 'Овердрафт', en: 'Overdraft' }, value: 32, description: null, isActive: true }, +] + +let mockStore = [...MOCK_CARD_TYPES] +let nextId = 8 + +const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms)) + +// ─── API Functions ──────────────────────────────────────────────────────────── + +export async function fetchCardTypes(params: { + page?: number + perPage?: number + search?: string + isActive?: string +}): Promise { + await delay() + const { page = 1, perPage = 25, search = '', isActive } = params + + let filtered = mockStore.filter((item) => { + const matchSearch = + !search || + Object.values(item.name).some((n) => + n.toLowerCase().includes(search.toLowerCase()) + ) + const matchActive = + isActive === '' || isActive === undefined + ? true + : isActive === 'true' + ? item.isActive + : !item.isActive + return matchSearch && matchActive + }) + + filtered = [...filtered].sort((a, b) => b.id - a.id) + + const total = filtered.length + const start = (page - 1) * perPage + const data = filtered.slice(start, start + perPage) + + return { data, total, page, perPage } +} + +export async function fetchCardTypeById(id: number): Promise { + await delay() + const item = mockStore.find((c) => c.id === id) + if (!item) throw new Error('Not found') + return { ...item } +} + +export async function createCardType(payload: CreateCardTypePayload): Promise { + await delay(400) + const newItem: CardType = { id: nextId++, ...payload } + mockStore = [newItem, ...mockStore] + return newItem +} + +export async function updateCardType(payload: UpdateCardTypePayload): Promise { + await delay(400) + const idx = mockStore.findIndex((c) => c.id === payload.id) + if (idx === -1) throw new Error('Not found') + const updated = { ...mockStore[idx], ...payload } + mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c)) + return updated +} + +export async function deleteCardType(id: number): Promise { + await delay(300) + mockStore = mockStore.filter((c) => c.id !== id) +} \ No newline at end of file diff --git a/src/features/cardTypes/components/cardTypesForm.tsx b/src/features/cardTypes/components/cardTypesForm.tsx new file mode 100644 index 0000000..a8b4cf5 --- /dev/null +++ b/src/features/cardTypes/components/cardTypesForm.tsx @@ -0,0 +1,224 @@ +import { useState, useEffect } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Button } from '@/components/ui/button' +import { Checkbox } from '@/components/ui/checkbox' +import { FormInput } from '@/components/formInput' +import type { CardType, CreateCardTypePayload } from '../api/cardTypesApi' +import { useCreateCardType, useUpdateCardType } from '../hooks/useCardTypes' + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface FormErrors { + nameTk?: string + nameRu?: string + nameEn?: string + value?: string +} + +interface FormState { + nameTk: string + nameRu: string + nameEn: string + value: string + description: string + isActive: boolean +} + +export interface CardTypeFormProps { + mode: 'create' | 'edit' + initialData?: CardType + cardTypeId?: number +} + +type LangKey = 'tk' | 'ru' | 'en' + +const LANG_TABS: { key: LangKey; label: string }[] = [ + { key: 'tk', label: 'Türkmen' }, + { key: 'ru', label: 'Русский' }, + { key: 'en', label: 'English' }, +] + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +function buildInitialState(data?: CardType): FormState { + if (!data) { + return { nameTk: '', nameRu: '', nameEn: '', value: '', description: '', isActive: true } + } + return { + nameTk: data.name.tk, + nameRu: data.name.ru, + nameEn: data.name.en, + value: String(data.value), + description: data.description ?? '', + isActive: data.isActive, + } +} + +function validate(form: FormState, t: (k: string, fb: string) => string): FormErrors { + const errors: FormErrors = {} + if (!form.nameTk.trim()) errors.nameTk = t('validation.required', 'Hökmany meýdan') + if (!form.nameRu.trim()) errors.nameRu = t('validation.required', 'Hökmany meýdan') + if (!form.nameEn.trim()) errors.nameEn = t('validation.required', 'Hökmany meýdan') + if (!form.value.trim() || isNaN(Number(form.value)) || Number(form.value) < 0) + errors.value = t('validation.invalidNumber', 'Dogry san giriziň') + return errors +} + +// ─── CardTypeForm ───────────────────────────────────────────────────────────── + +export function CardTypeForm({ mode, initialData, cardTypeId }: CardTypeFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const createMutation = useCreateCardType() + const updateMutation = useUpdateCardType() + + const isPending = createMutation.isPending || updateMutation.isPending + + const [activeLang, setActiveLang] = useState('tk') + const [form, setForm] = useState(() => buildInitialState(initialData)) + const [errors, setErrors] = useState({}) + + useEffect(() => { + if (initialData) setForm(buildInitialState(initialData)) + }, [initialData]) + + const set = (key: keyof FormState) => (value: string | boolean) => + setForm((prev) => ({ ...prev, [key]: value })) + + const handleSubmit = () => { + const errs = validate(form, t) + if (Object.keys(errs).length > 0) { + setErrors(errs) + return + } + setErrors({}) + + const payload: CreateCardTypePayload = { + name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn }, + value: Number(form.value), + description: form.description.trim() || null, + isActive: form.isActive, + } + + if (mode === 'create') { + createMutation.mutate(payload, { + onSuccess: () => navigate('/settings/card/card-types'), + }) + } else if (cardTypeId !== undefined) { + updateMutation.mutate( + { id: cardTypeId, ...payload }, + { onSuccess: () => navigate('/settings/card/card-types') } + ) + } + } + + const nameFieldKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as + | 'nameTk' + | 'nameRu' + | 'nameEn' + const nameErrorKey = nameFieldKey as keyof FormErrors + + return ( +
+ {/* Language tabs */} +
+ {LANG_TABS.map((tab) => ( + + ))} +
+ + {/* Form rows */} +
+ {/* Name */} +
+ + {t('cardTypes.fields.name', 'Ady')} + * + + +
+ + {/* Value */} +
+ + {t('cardTypes.fields.value', 'Baha')} + + +
+ + {/* Description */} +
+ + {t('cardTypes.fields.description', 'Bellikler')} + + +
+ + {/* isActive */} +
+ + {t('cardTypes.fields.isActive', 'Işjeň')} + + set('isActive')(!!checked)} + /> +
+
+ + {/* Actions */} +
+ + +
+
+ ) +} diff --git a/src/features/cardTypes/hooks/useCardTypes.ts b/src/features/cardTypes/hooks/useCardTypes.ts new file mode 100644 index 0000000..db6f101 --- /dev/null +++ b/src/features/cardTypes/hooks/useCardTypes.ts @@ -0,0 +1,101 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { + fetchCardTypes, + fetchCardTypeById, + createCardType, + updateCardType, + deleteCardType, + type CreateCardTypePayload, + type UpdateCardTypePayload, +} from '../api/cardTypesApi' + +// ─── Query Keys ─────────────────────────────────────────────────────────────── + +export const cardTypeKeys = { + all: ['cardTypes'] as const, + lists: () => [...cardTypeKeys.all, 'list'] as const, + list: (params: Record) => + [...cardTypeKeys.lists(), params] as const, + detail: (id: number) => [...cardTypeKeys.all, 'detail', id] as const, +} + +// ─── useCardTypes ───────────────────────────────────────────────────────────── + +export function useCardTypes(params: { + page?: number + perPage?: number + search?: string + isActive?: string +}) { + return useQuery({ + queryKey: cardTypeKeys.list(params), + queryFn: () => fetchCardTypes(params), + }) +} + +// ─── useCardTypeById ────────────────────────────────────────────────────────── + +export function useCardTypeById(id: number) { + return useQuery({ + queryKey: cardTypeKeys.detail(id), + queryFn: () => fetchCardTypeById(id), + enabled: !!id, + }) +} + +// ─── useCreateCardType ──────────────────────────────────────────────────────── + +export function useCreateCardType() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: CreateCardTypePayload) => createCardType(payload), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() }) + toast.success(t('cardTypes.toast.createSuccess', 'Kart görnüşi döredildi')) + }, + onError: () => { + toast.error(t('cardTypes.toast.createError', 'Döretmek başartmady')) + }, + }) +} + +// ─── useUpdateCardType ──────────────────────────────────────────────────────── + +export function useUpdateCardType() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: UpdateCardTypePayload) => updateCardType(payload), + onSuccess: (data) => { + queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() }) + queryClient.invalidateQueries({ queryKey: cardTypeKeys.detail(data.id) }) + toast.success(t('cardTypes.toast.updateSuccess', 'Kart görnüşi täzelendi')) + }, + onError: () => { + toast.error(t('cardTypes.toast.updateError', 'Täzelemek başartmady')) + }, + }) +} + +// ─── useDeleteCardType ──────────────────────────────────────────────────────── + +export function useDeleteCardType() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (id: number) => deleteCardType(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() }) + toast.success(t('cardTypes.toast.deleteSuccess', 'Kart görnüşi öçürildi')) + }, + onError: () => { + toast.error(t('cardTypes.toast.deleteError', 'Öçürmek başartmady')) + }, + }) +} \ No newline at end of file diff --git a/src/layouts/DashboardLayout.tsx b/src/layouts/DashboardLayout.tsx index ee7b238..56bd642 100644 --- a/src/layouts/DashboardLayout.tsx +++ b/src/layouts/DashboardLayout.tsx @@ -394,11 +394,11 @@ function AppSidebar() { "Card Issuance Reasons", "Kartyň çykarylmagynyň sebäpleri", ), - url: "/settings/card/reasons", + url: "/settings/card/card-reasons", }, { title: t("Card types", "Kart görnüşleri"), - url: "/settings/card/types", + url: "/settings/card/card-types", }, ], }, diff --git a/src/pages/settings/card/cardTypes/index.tsx b/src/pages/settings/card/cardTypes/index.tsx new file mode 100644 index 0000000..3f2603e --- /dev/null +++ b/src/pages/settings/card/cardTypes/index.tsx @@ -0,0 +1,249 @@ +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import type { ColumnDef, VisibilityState } from '@tanstack/react-table' +import { Eye, Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { DataTable } from '@/components/dataTable' +import { DataTableToolbar } from '@/components/dataTableToolbar' +import type { FilterField, ActiveFilter } from '@/components/dataTableToolbar' +import { useCardTypes, useDeleteCardType } from '@/features/cardTypes/hooks/useCardTypes' +import type { CardType } from '@/features/cardTypes/api/cardTypesApi' + +export function CardTypesListPage() { + const { t, i18n } = useTranslation() + const navigate = useNavigate() + + const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en' + + const [page, setPage] = useState(1) + const [perPage, setPerPage] = useState(25) + const [search, setSearch] = useState('') + const [activeFilters, setActiveFilters] = useState([ + { fieldId: 'isActive', value: '' }, + ]) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([ + 'id', 'name', 'value', 'description', 'isActive', 'actions', + ]) + const [deleteId, setDeleteId] = useState(null) + + const deleteMutation = useDeleteCardType() + const isActiveFilter = activeFilters.find((f) => f.fieldId === 'isActive')?.value ?? '' + + const { data, isLoading } = useCardTypes({ page, perPage, search, isActive: isActiveFilter }) + + const filterFields: FilterField[] = [ + { + id: 'isActive', + label: t('cardTypes.fields.isActive', 'Işjeň'), + options: [ + { value: 'true', label: t('common.active', 'Işjeň') }, + { value: 'false', label: t('common.inactive', 'Işjeň däl') }, + ], + }, + ] + + const handleFilterChange = (fieldId: string, value: string) => { + setActiveFilters((prev) => + prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)) + ) + setPage(1) + } + + const handleFilterReset = () => { + setActiveFilters([{ fieldId: 'isActive', value: '' }]) + setPage(1) + } + + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + {row.original.id} + ), + size: 70, + }, + { + accessorKey: 'name', + id: 'name', + header: t('cardTypes.fields.name', 'ADY').toUpperCase(), + cell: ({ row }) => ( + {row.original.name[lang]} + ), + }, + { + accessorKey: 'value', + header: t('cardTypes.fields.value', 'BAHA').toUpperCase(), + cell: ({ row }) => ( + {row.original.value} + ), + size: 120, + }, + { + accessorKey: 'description', + header: t('cardTypes.fields.description', 'BELLIKLER').toUpperCase(), + cell: ({ row }) => ( + + {row.original.description ?? '—'} + + ), + }, + { + accessorKey: 'isActive', + id: 'isActive', + header: t('cardTypes.fields.isActive', 'IŞJEŇ').toUpperCase(), + cell: ({ row }) => + row.original.isActive ? ( + + ) : ( + + ), + size: 100, + }, + { + id: 'actions', + header: '', + cell: ({ row }) => ( +
+ + + +
+ ), + enableSorting: false, + enableHiding: false, + size: 120, + }, + ] + + const columnMeta = columns + .filter( + (c) => + c.id !== 'actions' && + (c as { accessorKey?: string }).accessorKey !== undefined + ) + .map((c) => ({ + id: (c.id ?? (c as { accessorKey?: string }).accessorKey) as string, + label: + typeof c.header === 'string' + ? c.header + : (c.id ?? (c as { accessorKey?: string }).accessorKey ?? ''), + })) + + const totalPages = data ? Math.ceil(data.total / perPage) : 1 + + return ( +
+ {/* Header */} +
+
+ +

+ {t('cardTypes.title', 'Kart görnüşleri')} +

+
+
+ + {/* Toolbar */} + { setSearch(v); setPage(1) }} + searchPlaceholder={t('common.search', 'Gözlemek')} + columns={columnMeta} + columnVisibility={columnVisibility} + onColumnVisibilityChange={setColumnVisibility} + columnOrder={columnOrder} + onColumnOrderChange={setColumnOrder} + filterFields={filterFields} + activeFilters={activeFilters} + onFilterChange={handleFilterChange} + onFilterReset={handleFilterReset} + perPage={perPage} + onPerPageChange={(v) => { setPerPage(v); setPage(1) }} + actionLabel={t('cardTypes.actions.create', 'Kart görnüşi döretdiň')} + onAction={() => navigate('/settings/card/card-types/create')} + /> + + {/* Table */} + String(row.id)} + currentPage={page} + totalPages={totalPages} + totalCount={data?.total} + onPageChange={setPage} + /> + + {/* Delete dialog */} + setDeleteId(null)}> + + + {t('common.confirmDelete', 'Öçürmegi tassyklaň')} + + {t('cardTypes.deleteConfirm', 'Bu kart görnüşini öçürmek isleýärsiňizmi?')} + + + + {t('common.cancel', 'Ýatyr')} + { + if (deleteId !== null) { + deleteMutation.mutate(deleteId, { onSuccess: () => setDeleteId(null) }) + } + }} + > + {deleteMutation.isPending + ? t('common.deleting', 'Öçürilýär...') + : t('common.delete', 'Öçürmek')} + + + + +
+ ) +} + +export default CardTypesListPage diff --git a/src/pages/settings/card/cardTypesCreate/index.tsx b/src/pages/settings/card/cardTypesCreate/index.tsx new file mode 100644 index 0000000..017a893 --- /dev/null +++ b/src/pages/settings/card/cardTypesCreate/index.tsx @@ -0,0 +1,40 @@ +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { CardTypeForm } from '@/features/cardTypes/components/cardTypesForm' + +export default function CardTypeCreatePage() { + const navigate = useNavigate() + const { t } = useTranslation() + + return ( +
+
+ + +

+ {t('cardTypes.create.title', 'Kart görnüşi döretmek')} +

+
+ + +
+ ) +} diff --git a/src/pages/settings/card/cardTypesEdit/index.tsx b/src/pages/settings/card/cardTypesEdit/index.tsx new file mode 100644 index 0000000..d630f06 --- /dev/null +++ b/src/pages/settings/card/cardTypesEdit/index.tsx @@ -0,0 +1,65 @@ +import { useNavigate, useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { CardTypeForm } from '@/features/cardTypes/components/cardTypesForm' +import { useCardTypeById } from '@/features/cardTypes/hooks/useCardTypes' + +export default function CardTypeEditPage() { + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const { t } = useTranslation() + + const numericId = Number(id) + const { data, isLoading, isError } = useCardTypeById(numericId) + + return ( +
+
+ + +

+ {isLoading + ? '...' + : `${t('cardTypes.edit.title', 'Kart görnüşini üýtgetmek')}: ${data?.name.tk ?? ''}`} +

+
+ + {isLoading ? ( +
+ {Array.from({ length: 4 }).map((_, i) => ( +
+
+
+
+ ))} +
+ ) : isError || !data ? ( +
+ {t('common.error', 'Ýalňyşlyk ýüze çykdy')} +
+ ) : ( + + )} +
+ ) +} diff --git a/src/pages/settings/card/cardTypesView/index.tsx b/src/pages/settings/card/cardTypesView/index.tsx new file mode 100644 index 0000000..4fd2593 --- /dev/null +++ b/src/pages/settings/card/cardTypesView/index.tsx @@ -0,0 +1,174 @@ +import { useState } from 'react' +import { useNavigate, useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Section, InfoRow } from '@/components/viewPageComponents' +import { useCardTypeById, useDeleteCardType } from '@/features/cardTypes/hooks/useCardTypes' + +export function CardTypeViewPage() { + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const { t, i18n } = useTranslation() + + const numericId = Number(id) + const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en' + + const { data, isLoading } = useCardTypeById(numericId) + const deleteMutation = useDeleteCardType() + const [deleteOpen, setDeleteOpen] = useState(false) + + return ( +
+ {/* Breadcrumb + actions */} +
+
+ +

+ {isLoading + ? '...' + : `${t('cardTypes.view.title', 'Kart görnüşi giňişleýin')}: ${data?.name[lang] ?? ''}`} +

+
+ +
+ + +
+
+ + {isLoading ? ( +
+ {Array.from({ length: 4 }).map((_, i) => ( +
+
+
+
+ ))} +
+ ) : data ? ( +
+ + + {/* Multilang name with tabs */} +
+ + {t('cardTypes.fields.name', 'Ady')} + +
+
+ {(['tk', 'ru', 'en'] as const).map((l) => ( + + {l === 'tk' ? 'Türkmen' : l === 'ru' ? 'Русский' : 'English'} + + ))} +
+ {data.name[lang]} +
+
+ + + + +
+ + {t('cardTypes.fields.isActive', 'Işjeň')} + + {data.isActive ? ( + + ) : ( + + )} +
+
+ ) : ( +

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

+ )} + + {/* Delete dialog */} + + + + {t('common.confirmDelete', 'Öçürmegi tassyklaň')} + + {t('cardTypes.deleteConfirm', 'Bu kart görnüşini öçürmek isleýärsiňizmi?')} + + + + {t('common.cancel', 'Ýatyr')} + + deleteMutation.mutate(numericId, { + onSuccess: () => navigate('/resources/card-types'), + }) + } + > + {deleteMutation.isPending + ? t('common.deleting', 'Öçürilýär...') + : t('common.delete', 'Öçürmek')} + + + + +
+ ) +} + +export default CardTypeViewPage diff --git a/src/pages/settings/card/reasons/index.tsx b/src/pages/settings/card/reasons/index.tsx new file mode 100644 index 0000000..4a0e5bc --- /dev/null +++ b/src/pages/settings/card/reasons/index.tsx @@ -0,0 +1,253 @@ +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import type { ColumnDef, VisibilityState } from '@tanstack/react-table' +import { Eye, Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { DataTable } from '@/components/dataTable' +import { DataTableToolbar } from '@/components/dataTableToolbar' +import type { FilterField, ActiveFilter } from '@/components/dataTableToolbar' +import { useCardReasons, useDeleteCardReason } from '@/features/cardReasons/hooks/useCardReasons' +import type { CardReason } from '@/features/cardReasons/api/cardReasonsApi' + +// ─── CardReasonsListPage ─────────────────────────────────────────────────────── + +export function CardReasonsListPage() { + const { t, i18n } = useTranslation() + const navigate = useNavigate() + + const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en' + + // ── Table state ───────────────────────────────────────────────────────────── + const [page, setPage] = useState(1) + const [perPage, setPerPage] = useState(25) + const [search, setSearch] = useState('') + const [activeFilters, setActiveFilters] = useState([ + { fieldId: 'isActive', value: '' }, + ]) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([ + 'id', 'name', 'value', 'description', 'isActive', 'actions', + ]) + + // ── Delete dialog ──────────────────────────────────────────────────────────── + const [deleteId, setDeleteId] = useState(null) + const deleteMutation = useDeleteCardReason() + + const isActiveFilter = activeFilters.find((f) => f.fieldId === 'isActive')?.value ?? '' + + const { data, isLoading } = useCardReasons({ + page, + perPage, + search, + isActive: isActiveFilter, + }) + + const filterFields: FilterField[] = [ + { + id: 'isActive', + label: t('CardReasons.fields.isActive', 'Işjeň'), + options: [ + { value: 'true', label: t('common.active', 'Işjeň') }, + { value: 'false', label: t('common.inactive', 'Işjeň däl') }, + ], + }, + ] + + const handleFilterChange = (fieldId: string, value: string) => { + setActiveFilters((prev) => + prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)) + ) + setPage(1) + } + + const handleFilterReset = () => { + setActiveFilters([{ fieldId: 'isActive', value: '' }]) + setPage(1) + } + + // ── Columns ────────────────────────────────────────────────────────────────── + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + + {row.original.id} + + ), + size: 70, + }, + { + accessorKey: 'name', + id: 'name', + header: t('CardReasons.fields.name', 'ADY').toUpperCase(), + cell: ({ row }) => ( + {row.original.name[lang]} + ), + }, + { + accessorKey: 'value', + header: t('CardReasons.fields.value', 'BAHA').toUpperCase(), + cell: ({ row }) => ( + {row.original.value} + ), + size: 120, + }, + { + accessorKey: 'description', + header: t('CardReasons.fields.description', 'BELLIKLER').toUpperCase(), + cell: ({ row }) => ( + + {row.original.description ?? '—'} + + ), + }, + { + accessorKey: 'isActive', + id: 'isActive', + header: t('CardReasons.fields.isActive', 'IŞJEŇ').toUpperCase(), + cell: ({ row }) => + row.original.isActive ? ( + + ) : ( + + ), + size: 100, + }, + { + id: 'actions', + header: '', + cell: ({ row }) => ( +
+ + + +
+ ), + enableSorting: false, + enableHiding: false, + size: 120, + }, + ] + + const columnMeta = columns + .filter((c) => c.id !== 'actions' && (c as { accessorKey?: string }).accessorKey !== undefined) + .map((c) => ({ + id: (c.id ?? (c as { accessorKey?: string }).accessorKey) as string, + label: + typeof c.header === 'string' + ? c.header + : (c.id ?? (c as { accessorKey?: string }).accessorKey ?? ''), + })) + + const totalPages = data ? Math.ceil(data.total / perPage) : 1 + + return ( +
+ {/* Header */} +
+
+

+ {t('CardReasons.title', 'Kartyň çykarylmagynyň sebäpleri')} +

+
+
+ + {/* Toolbar */} + { setSearch(v); setPage(1) }} + searchPlaceholder={t('common.search', 'Gözlemek')} + columns={columnMeta} + columnVisibility={columnVisibility} + onColumnVisibilityChange={setColumnVisibility} + columnOrder={columnOrder} + onColumnOrderChange={setColumnOrder} + filterFields={filterFields} + activeFilters={activeFilters} + onFilterChange={handleFilterChange} + onFilterReset={handleFilterReset} + perPage={perPage} + onPerPageChange={(v) => { setPerPage(v); setPage(1) }} + actionLabel={t('CardReasons.actions.create', 'Kartyň çykarylmagynyň sebäbini döretdiň')} + onAction={() => navigate('/settings/card/card-reasons/create')} + /> + + {/* Table */} + String(row.id)} + currentPage={page} + totalPages={totalPages} + totalCount={data?.total} + onPageChange={setPage} + /> + + {/* Delete dialog */} + setDeleteId(null)}> + + + + {t('common.confirmDelete', 'Öçürmegi tassyklaň')} + + + {t('CardReasons.deleteConfirm', 'Bu kartyň çykarylmagynyň sebäbini öçürmek isleýärsiňizmi?')} + + + + {t('common.cancel', 'Ýatyr')} + { + if (deleteId !== null) { + deleteMutation.mutate(deleteId, { onSuccess: () => setDeleteId(null) }) + } + }} + > + {deleteMutation.isPending + ? t('common.deleting', 'Öçürilýär...') + : t('common.delete', 'Öçürmek')} + + + + +
+ ) +} + +export default CardReasonsListPage diff --git a/src/pages/settings/card/reasonsCreate/index.tsx b/src/pages/settings/card/reasonsCreate/index.tsx new file mode 100644 index 0000000..fff4537 --- /dev/null +++ b/src/pages/settings/card/reasonsCreate/index.tsx @@ -0,0 +1,41 @@ +import { useNavigate, } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { CardReasonForm } from '@/features/cardReasons/components/reasonForm' + +export function CardReasonCreatePage() { + const navigate = useNavigate() + const { t } = useTranslation() + + return ( +
+
+ +

+ {t('CardReasons.create.title', 'Kartyň çykarylmagynyň sebäbi dörediň')} +

+
+ + +
+ ) +} + +export default CardReasonCreatePage diff --git a/src/pages/settings/card/reasonsEdit/index.tsx b/src/pages/settings/card/reasonsEdit/index.tsx new file mode 100644 index 0000000..87241b6 --- /dev/null +++ b/src/pages/settings/card/reasonsEdit/index.tsx @@ -0,0 +1,68 @@ +import { useNavigate, useParams } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { CardReasonForm } from "@/features/cardReasons/components/reasonForm"; +import { useCardReasonById } from "@/features/cardReasons/hooks/useCardReasons"; + +// ─── CardReasonEditPage ──────────────────────────────────────────────────────── + +export function CardReasonEditPage() { + const { id } = useParams<{ id: string }>(); + const navigate = useNavigate(); + const { t } = useTranslation(); + + const numericId = Number(id); + const { data, isLoading } = useCardReasonById(numericId); + + return ( +
+
+ +

+ {isLoading + ? "..." + : `${t("CardReasons.edit.title", "Kartyň çykarylmagynyň sebäbini üýtgetmek")}: ${data?.name.tk ?? ""}`} +

+
+ + {isLoading ? ( +
+ {Array.from({ length: 4 }).map((_, i) => ( +
+
+
+
+ ))} +
+ ) : ( + + )} +
+ ); +} + +export default CardReasonEditPage diff --git a/src/pages/settings/card/reasonsView/index.tsx b/src/pages/settings/card/reasonsView/index.tsx new file mode 100644 index 0000000..09d13de --- /dev/null +++ b/src/pages/settings/card/reasonsView/index.tsx @@ -0,0 +1,180 @@ +import { useNavigate, useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Pencil, Trash2 } from 'lucide-react' +import { useState } from 'react' +import { Button } from '@/components/ui/button' +import { CheckCircle2, XCircle } from 'lucide-react' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Section, InfoRow } from '@/components/viewPageComponents' +import { useCardReasonById, useDeleteCardReason } from '@/features/cardReasons/hooks/useCardReasons' + +// ─── CardReasonViewPage ──────────────────────────────────────────────────────── + +export function CardReasonViewPage() { + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const { t, i18n } = useTranslation() + + const numericId = Number(id) + const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en' + + const { data, isLoading } = useCardReasonById(numericId) + const deleteMutation = useDeleteCardReason() + const [deleteOpen, setDeleteOpen] = useState(false) + + return ( +
+ {/* Breadcrumb + actions */} +
+
+ +

+ {isLoading + ? '...' + : `${t('CardReasons.view.title', 'Kartyň çykarylmagynyň sebäbi giňişleýin')}: ${data?.name[lang] ?? ''}`} +

+
+ +
+ + +
+
+ + {isLoading ? ( +
+ {Array.from({ length: 4 }).map((_, i) => ( +
+
+
+
+ ))} +
+ ) : data ? ( +
+ + + {/* Multilang name tabs */} +
+ + {t('CardReasons.fields.name', 'Ady')} + +
+ {/* Lang switcher is displayed in top-right corner of this cell */} +
+ {(['tk', 'ru', 'en'] as const).map((l) => ( + + {l === 'tk' ? 'Türkmen' : l === 'ru' ? 'Русский' : 'English'} + + ))} +
+ {data.name[lang]} +
+
+ + + + + {/* isActive custom row */} +
+ + {t('CardReasons.fields.isActive', 'Işjeň')} + + {data.isActive ? ( + + ) : ( + + )} +
+
+ ) : ( +

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

+ )} + + {/* Delete dialog */} + + + + {t('common.confirmDelete', 'Öçürmegi tassyklaň')} + + {t('CardReasons.deleteConfirm', 'Bu kartyň çykarylmagynyň sebäbini öçürmek isleýärsiňizmi?')} + + + + {t('common.cancel', 'Ýatyr')} + + deleteMutation.mutate(numericId, { + onSuccess: () => navigate('/resources/card-states'), + }) + } + > + {deleteMutation.isPending + ? t('common.deleting', 'Öçürilýär...') + : t('common.delete', 'Öçürmek')} + + + + +
+ ) +} + +export default CardReasonViewPage