From f415acd649cc1ce84351cf4728846eaaf4e3272f Mon Sep 17 00:00:00 2001 From: Jelaletdin12 Date: Tue, 12 May 2026 12:41:13 +0500 Subject: [PATCH] added some new pages --- PROJECT_STANDARDS.md | 2 +- src/app/router/index.tsx | 158 +++++++++++++ src/assets/hero.png | Bin 13057 -> 0 bytes src/assets/react.svg | 1 - src/assets/vite.svg | 1 - src/components/formInput.tsx | 1 + .../currencyRates/api/currencyRatesApi.ts | 141 ++++++++++++ .../components/currencyRatesForm.tsx | 203 +++++++++++++++++ .../currencyRates/hooks/useCurrencyRates.ts | 100 +++++++++ .../api/onlinePaymentsHistoryApi.ts | 151 +++++++++++++ .../components/PaymentStatusBadge.tsx | 33 +++ .../hooks/useOnlinePaymentsHistory.ts | 60 +++++ .../permissions/api/permissionsApi.ts | 134 +++++++++++ .../components/permissionsForm.tsx | 202 +++++++++++++++++ .../permissions/hooks/usePermissions.ts | 92 ++++++++ src/features/roles/api/rolesApi.ts | 118 ++++++++++ src/features/roles/components/roleForm.tsx | 203 +++++++++++++++++ src/features/roles/hooks/useRoles.ts | 86 ++++++++ .../api/visaMasterSberSettingsApi.ts | 126 +++++++++++ .../components/visaMasterSberSettingsForm.tsx | 190 ++++++++++++++++ .../hooks/useVisaMasterSettings.ts | 99 +++++++++ src/layouts/DashboardLayout.tsx | 6 +- src/pages/currencies/currencyRates/index.tsx | 208 ++++++++++++++++++ .../currencies/currencyRatesCreate/index.tsx | 23 ++ .../currencies/currencyRatesEdit/index.tsx | 57 +++++ .../currencies/currencyRatesView/index.tsx | 137 ++++++++++++ .../visaMasterSberSettings/index.tsx | 204 +++++++++++++++++ .../visaMasterSberSettingsCreate/index.tsx | 24 ++ .../visaMasterSberSettingsEdit/index.tsx | 57 +++++ src/pages/onlinePaymentsHistory/index.tsx | 208 ++++++++++++++++++ .../onlinePaymenHistoryView.tsx | 130 +++++++++++ src/pages/settings/users/createRole/index.tsx | 15 ++ src/pages/settings/users/editRole/index.tsx | 46 ++++ .../settings/users/permissions/index.tsx | 194 ++++++++++++++++ .../users/permissionsCreate/index.tsx | 15 ++ .../settings/users/permissionsEdit/index.tsx | 46 ++++ .../settings/users/permissionsView/index.tsx | 181 +++++++++++++++ src/pages/settings/users/roles/index.tsx | 194 ++++++++++++++++ src/pages/settings/users/rolesView/index.tsx | 181 +++++++++++++++ src/pages/users/allUsersCreate/index.tsx | 25 +-- 40 files changed, 4022 insertions(+), 30 deletions(-) delete mode 100644 src/assets/hero.png delete mode 100644 src/assets/react.svg delete mode 100644 src/assets/vite.svg create mode 100644 src/features/currencyRates/api/currencyRatesApi.ts create mode 100644 src/features/currencyRates/components/currencyRatesForm.tsx create mode 100644 src/features/currencyRates/hooks/useCurrencyRates.ts create mode 100644 src/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts create mode 100644 src/features/onlinePaymentHistory/components/PaymentStatusBadge.tsx create mode 100644 src/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts create mode 100644 src/features/permissions/api/permissionsApi.ts create mode 100644 src/features/permissions/components/permissionsForm.tsx create mode 100644 src/features/permissions/hooks/usePermissions.ts create mode 100644 src/features/roles/api/rolesApi.ts create mode 100644 src/features/roles/components/roleForm.tsx create mode 100644 src/features/roles/hooks/useRoles.ts create mode 100644 src/features/visaMasterSberSettings/api/visaMasterSberSettingsApi.ts create mode 100644 src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx create mode 100644 src/features/visaMasterSberSettings/hooks/useVisaMasterSettings.ts create mode 100644 src/pages/currencies/currencyRates/index.tsx create mode 100644 src/pages/currencies/currencyRatesCreate/index.tsx create mode 100644 src/pages/currencies/currencyRatesEdit/index.tsx create mode 100644 src/pages/currencies/currencyRatesView/index.tsx create mode 100644 src/pages/currencies/visaMasterSberSettings/index.tsx create mode 100644 src/pages/currencies/visaMasterSberSettingsCreate/index.tsx create mode 100644 src/pages/currencies/visaMasterSberSettingsEdit/index.tsx create mode 100644 src/pages/onlinePaymentsHistory/index.tsx create mode 100644 src/pages/onlinePaymentsHistory/onlinePaymenHistoryView.tsx create mode 100644 src/pages/settings/users/createRole/index.tsx create mode 100644 src/pages/settings/users/editRole/index.tsx create mode 100644 src/pages/settings/users/permissions/index.tsx create mode 100644 src/pages/settings/users/permissionsCreate/index.tsx create mode 100644 src/pages/settings/users/permissionsEdit/index.tsx create mode 100644 src/pages/settings/users/permissionsView/index.tsx create mode 100644 src/pages/settings/users/roles/index.tsx create mode 100644 src/pages/settings/users/rolesView/index.tsx diff --git a/PROJECT_STANDARDS.md b/PROJECT_STANDARDS.md index 6dae3ed..3b77b57 100644 --- a/PROJECT_STANDARDS.md +++ b/PROJECT_STANDARDS.md @@ -81,7 +81,7 @@ src/ - Create ve Edit sayfaları (`pages/`) sadece bu component'i çağıran birer **wrapper** olmalıdır. - Edit sayfası `useParams()` ile URL'den `id` alır, ilgili hook ile veriyi fetch eder ve `initialData` prop'u olarak form'a geçer. - Validation, form state, submit logic — hepsi shared component içinde tek yerde yönetilir. - - Create ve Edit form lar multiple form ise yani bir cok adimdan olusuyorsa o zaman `src/components/stepBarV2.tsx` componentini kullan. Çünkü orada Progressive Disclosure var. Ama eger sadece bir form ise o zaman `src/components/form.tsx` componentini kullan. + - Create ve Edit form lar multiple form ise yani bir cok adimdan olusuyorsa o zaman `src/components/stepBarV2.tsx` componentini kullan. Çünkü orada Progressive Disclosure var. Ama eger sadece bir form ise o zaman `src/components/formInput.tsx` componentini kullan. - Örnek yapı: ``` features/[feature]/ diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index f6e05f9..11a5298 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -115,6 +115,28 @@ const ClientCreatePage = lazy(() => import("@/pages/users/clientsCreate")); const ClientViewPage = lazy(() => import("@/pages/users/clientsView")); const ClientEditPage = lazy(() => import("@/pages/users/clientsEdit")); +const CurrencyRatesPage = lazy(() => import("@/pages/currencies/currencyRates")); +const CurrencyRateCreatePage = lazy(() => import("@/pages/currencies/currencyRatesCreate")); +const CurrencyRateViewPage = lazy(() => import("@/pages/currencies/currencyRatesView")); +const CurrencyRateEditPage = lazy(() => import("@/pages/currencies/currencyRatesEdit")); + +const VisaMasterSberSettingsPage = lazy(() => import("@/pages/currencies/visaMasterSberSettings")); +const VisaMasterSberSettingCreatePage = lazy(() => import("@/pages/currencies/visaMasterSberSettingsCreate")); +const VisaMasterSberSettingEditPage = lazy(() => import("@/pages/currencies/visaMasterSberSettingsEdit")); + +const OnlinePaymentsHistoryPage = lazy(() => import("@/pages/onlinePaymentsHistory")); +const OnlinePaymentsHistoryViewPage = lazy(() => import("@/pages/onlinePaymentsHistory/onlinePaymenHistoryView")); + +const RolesPage = lazy(() => import("@/pages/settings/users/roles")); +const RoleCreatePage = lazy(() => import("@/pages/settings/users/createRole")); +const RoleViewPage = lazy(() => import("@/pages/settings/users/rolesView")); +const RoleEditPage = lazy(() => import("@/pages/settings/users/editRole")); + +const PermissionsPage = lazy(() => import("@/pages/settings/users/permissions")); +const PermissionCreatePage = lazy(() => import("@/pages/settings/users/permissionsCreate")); +const PermissionsViewPage = lazy(() => import("@/pages/settings/users/permissionsView")); +const PermissionEditPage = lazy(() => import("@/pages/settings/users/permissionsEdit")); + function AuthGuard() { const isAuthenticated = useAuthStore((s) => s.isAuthenticated); if (!isAuthenticated) return ; @@ -595,6 +617,142 @@ export const router = createBrowserRouter([ ), }, + { // Sidebar: /currencies-rates + path: "/currency-rates", + element: ( + }> + + + ), + }, + { + path: "/currency-rates/create", + element: ( + }> + + + ), + }, + { + path: "/currency-rates/:id", + element: ( + }> + + + ), + }, + { + path: "/currency-rates/:id/edit", + element: ( + }> + + + ), + }, + { // Sidebar: /visa-master-sber-settings + path: "/visa-master-sber-settings", + element: ( + }> + + + ), + }, + { + path: "/visa-master-sber-settings/create", + element: ( + }> + + + ), + }, + { + path: "/visa-master-sber-settings/:id/edit", + element: ( + }> + + + ), + }, + { + path: "/online-payments-history", + element: ( + }> + + + ), + }, + { + path: "/online-payments-history/:id", + element: ( + }> + + + ), + }, + { + path: "/settings/users/roles", + element: ( + }> + + + ), + }, + { + path: "/settings/users/roles/create", + element: ( + }> + + + ), + }, + { + path: "/settings/users/roles/:id", + element: ( + }> + + + ), + }, + { + path: "/settings/users/roles/:id/edit", + element: ( + }> + + + ), + }, + { + path: "/settings/users/permissions", + element: ( + }> + + + ), + }, + { + path: "/settings/users/permissions/create", + element: ( + }> + + + ), + }, + { + path: "/settings/users/permissions/:id", + element: ( + }> + + + ), + }, + { + path: "/settings/users/permissions/:id/edit", + element: ( + }> + + + ), + }, ], }, ], diff --git a/src/assets/hero.png b/src/assets/hero.png deleted file mode 100644 index 02251f4b956c55af2d76fd0788124d7eee2b45eb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13057 zcmV+cGycqpP)V|)f$;Qooc7=_G zlYe)HToTQIc!$)^+J1M1y0*T%w!p~7%ux`!eRhO?c80XDxKQ*R^lUUMnA>6NT^?feoZ8xxvP32D&s-9ow zqjcM}eesrC)NeDmsf)*P7wJ|K!&xP%Zy4iI8lF)Tv2!reW)tCzg_1=PmOwd1SQfxa z8;58t!=z~Ba7CYlNWVG>he8aRPY|+-JmozNhn!#9i#77Aa_Edt$ijyCWL#=~I>~2X zZNrQ8I0=D+NWD4pq=7~(i zhfThMNw|G>g^y9pGzxX7ZSApl@tIxFcs{p#MX{Ax&XZT+cR#U+OWc@S)pkIuI}dzu zH?^Q=<(y&Vq-oxSLfc0Zmq81bjZWf}RnssBaD6}2g-XJHLcN_|*IOu>m|x$nbm(?E zyNy!Zp=RroS;?Vg*kmoJYBi!n5{_^@rA!)=t#a^;N$8GL!*DsQb}`yvEuX!G@||An znOfUZAevPrkV_qjl|<~3QRZzG&h@C9Y5z zqpNH4xqbF_InIPh)kX}Vn^5kyed|mOuq+2>M;v~KO37a#yrEn3XDqtOl=rc6_KZ!; zreo)DFVB4|>1Zd(bvMI%8uM;3!)YMYu&cG?(PE!B~y@3yKBMt|R zAf=I16tFwPsl)!jDqvY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^f-hZ`d{aVa+xW1EO4wDV4 zB?JgD7*?qkvc|$nIykTvNl2x0j3Q!MXoLL^)~}d7jcYf(H8D~c+?$pKL(px>Z3`eb z04RzS6_AgFT6Pn#iZAg$Sl_j8#;6ShF%&(Fag#E2asU@@LaN;=b=Wf7sgPKhfzhBM zC@eFL8^MrnA*9&Khe*Ab@CC9*uyJGXyi(;y2>lQLJZt;ShtJi?3Yf_t`F+$hY!+Q2Ndsx=U+bjTiAy7djLji>7k%k`$9&--f<*BNA3Hy&ZrHH|4 zG5H&9cB?O#zI1_OOf0Ce%mDfQxdtp3vU%(iY6yji3iISS61XLv#z|!zI_sZqza@B+ zyu9st5-h+`H7QUKx9}3w@oU@EO}&cEzG?fu!!bLO->%zkcg;i9^j`S~=WKMnDi1f= P00000NkvXXu0mjft=yBf diff --git a/src/assets/react.svg b/src/assets/react.svg deleted file mode 100644 index 6c87de9..0000000 --- a/src/assets/react.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/assets/vite.svg b/src/assets/vite.svg deleted file mode 100644 index 5101b67..0000000 --- a/src/assets/vite.svg +++ /dev/null @@ -1 +0,0 @@ -Vite diff --git a/src/components/formInput.tsx b/src/components/formInput.tsx index 9b6d16b..a8b9b0f 100644 --- a/src/components/formInput.tsx +++ b/src/components/formInput.tsx @@ -655,6 +655,7 @@ function FileInput({ ) + } // ─── FormInput (router) ─────────────────────────────────────────────────────── diff --git a/src/features/currencyRates/api/currencyRatesApi.ts b/src/features/currencyRates/api/currencyRatesApi.ts new file mode 100644 index 0000000..9dbf5f1 --- /dev/null +++ b/src/features/currencyRates/api/currencyRatesApi.ts @@ -0,0 +1,141 @@ +// features/currencyRates/api/currencyRatesApi.ts + +export type CurrencyCode = 'USD' | 'RUB' | 'TMT' | 'EUR' | 'GBP' | 'CNY' | 'TRY' + +export interface CurrencyRate { + id: number + currencyFrom: CurrencyCode + currencyTo: CurrencyCode + value: number + createdAt: string + updatedAt: string +} + +export interface CurrencyRateListParams { + page?: number + perPage?: number + search?: string +} + +export interface CurrencyRateListResponse { + data: CurrencyRate[] + total: number + page: number + perPage: number + totalPages: number +} + +export interface CreateCurrencyRatePayload { + currencyFrom: CurrencyCode + currencyTo: CurrencyCode + value: number +} + +export type UpdateCurrencyRatePayload = CreateCurrencyRatePayload + +// ─── Mock Data ──────────────────────────────────────────────────────────────── + +const MOCK_RATES: CurrencyRate[] = [ + { id: 6, currencyFrom: 'USD', currencyTo: 'USD', value: 250, createdAt: '2026-04-01T10:00:00Z', updatedAt: '2026-05-01T10:00:00Z' }, + { id: 5, currencyFrom: 'RUB', currencyTo: 'TMT', value: 0.047504, createdAt: '2026-03-15T08:30:00Z', updatedAt: '2026-05-10T08:30:00Z' }, + { id: 4, currencyFrom: 'USD', currencyTo: 'RUB', value: 74.0455, createdAt: '2026-02-20T14:00:00Z', updatedAt: '2026-05-08T14:00:00Z' }, + { id: 2, currencyFrom: 'USD', currencyTo: 'TMT', value: 3.5175, createdAt: '2026-01-10T09:00:00Z', updatedAt: '2026-05-05T09:00:00Z' }, + { id: 1, currencyFrom: 'EUR', currencyTo: 'TMT', value: 3.8120, createdAt: '2026-01-05T09:00:00Z', updatedAt: '2026-05-03T09:00:00Z' }, + { id: 3, currencyFrom: 'EUR', currencyTo: 'RUB', value: 80.2300, createdAt: '2026-01-12T11:00:00Z', updatedAt: '2026-04-28T11:00:00Z' }, + { id: 7, currencyFrom: 'GBP', currencyTo: 'TMT', value: 4.4500, createdAt: '2026-04-10T13:00:00Z', updatedAt: '2026-05-11T13:00:00Z' }, + { id: 8, currencyFrom: 'CNY', currencyTo: 'TMT', value: 0.4850, createdAt: '2026-04-15T10:00:00Z', updatedAt: '2026-05-09T10:00:00Z' }, +] + +let mockStore: CurrencyRate[] = [...MOCK_RATES] +let nextId = 9 + +const delay = (ms = 400) => new Promise((res) => setTimeout(res, ms)) + +// ─── API Functions ──────────────────────────────────────────────────────────── + +export async function fetchCurrencyRates( + params: CurrencyRateListParams = {} +): Promise { + await delay() + const { page = 1, perPage = 25, search = '' } = params + + let filtered = [...mockStore] + + if (search.trim()) { + const q = search.toLowerCase() + filtered = filtered.filter( + (r) => + r.currencyFrom.toLowerCase().includes(q) || + r.currencyTo.toLowerCase().includes(q) || + String(r.value).includes(q) || + String(r.id).includes(q) + ) + } + + // Sort by id desc + filtered.sort((a, b) => b.id - a.id) + + const total = filtered.length + const totalPages = Math.ceil(total / perPage) + const start = (page - 1) * perPage + const data = filtered.slice(start, start + perPage) + + return { data, total, page, perPage, totalPages } +} + +export async function fetchCurrencyRateById(id: number): Promise { + await delay() + const rate = mockStore.find((r) => r.id === id) + if (!rate) throw new Error(`Currency rate with id ${id} not found`) + return { ...rate } +} + +export async function createCurrencyRate( + payload: CreateCurrencyRatePayload +): Promise { + await delay() + const now = new Date().toISOString() + const newRate: CurrencyRate = { + id: nextId++, + ...payload, + createdAt: now, + updatedAt: now, + } + mockStore = [newRate, ...mockStore] + return newRate +} + +export async function updateCurrencyRate( + id: number, + payload: UpdateCurrencyRatePayload +): Promise { + await delay() + const idx = mockStore.findIndex((r) => r.id === id) + if (idx === -1) throw new Error(`Currency rate with id ${id} not found`) + const updated: CurrencyRate = { + ...mockStore[idx], + ...payload, + updatedAt: new Date().toISOString(), + } + mockStore = mockStore.map((r) => (r.id === id ? updated : r)) + return updated +} + +export async function deleteCurrencyRate(id: number): Promise { + await delay() + const exists = mockStore.some((r) => r.id === id) + if (!exists) throw new Error(`Currency rate with id ${id} not found`) + mockStore = mockStore.filter((r) => r.id !== id) +} + +// ─── Constants ──────────────────────────────────────────────────────────────── + +export const CURRENCY_OPTIONS: { value: CurrencyCode; label: string }[] = [ + { value: 'USD', label: 'USD — US Dollar' }, + { value: 'RUB', label: 'RUB — Russian Ruble' }, + { value: 'TMT', label: 'TMT — Turkmen Manat' }, + { value: 'EUR', label: 'EUR — Euro' }, + { value: 'GBP', label: 'GBP — British Pound' }, + { value: 'CNY', label: 'CNY — Chinese Yuan' }, + { value: 'TRY', label: 'TRY — Turkish Lira' }, +] \ No newline at end of file diff --git a/src/features/currencyRates/components/currencyRatesForm.tsx b/src/features/currencyRates/components/currencyRatesForm.tsx new file mode 100644 index 0000000..da99018 --- /dev/null +++ b/src/features/currencyRates/components/currencyRatesForm.tsx @@ -0,0 +1,203 @@ +// features/currencyRates/components/CurrencyRateForm.tsx + +import { useEffect, useState } 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 { CURRENCY_OPTIONS, type CurrencyCode, type CurrencyRate } from '../api/currencyRatesApi' +import { useCreateCurrencyRate, useUpdateCurrencyRate } from '../hooks/useCurrencyRates' + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface FormState { + currencyFrom: string + currencyTo: string + value: string +} + +interface FormErrors { + currencyFrom?: string + currencyTo?: string + value?: string +} + +export interface CurrencyRateFormProps { + mode: 'create' | 'edit' + initialData?: CurrencyRate + rateId?: number +} + +// ─── Validation ─────────────────────────────────────────────────────────────── + +function validate(form: FormState, t: (key: string, fallback: string) => string): FormErrors { + const errors: FormErrors = {} + + if (!form.currencyFrom) { + errors.currencyFrom = t('currencyRates.errors.currencyFromRequired', 'Walýuta saýlaň') + } + if (!form.currencyTo) { + errors.currencyTo = t('currencyRates.errors.currencyToRequired', 'Walýuta saýlaň') + } + if (!form.value.trim()) { + errors.value = t('currencyRates.errors.valueRequired', 'Bahany giriziň') + } else if (isNaN(Number(form.value)) || Number(form.value) <= 0) { + errors.value = t('currencyRates.errors.valueInvalid', 'Baha 0-dan uly bolmaly') + } + + return errors +} + +// ─── CurrencyRateForm ───────────────────────────────────────────────────────── + +export function CurrencyRateForm({ mode, initialData, rateId }: CurrencyRateFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const [form, setForm] = useState({ + currencyFrom: initialData?.currencyFrom ?? '', + currencyTo: initialData?.currencyTo ?? '', + value: initialData?.value != null ? String(initialData.value) : '', + }) + const [errors, setErrors] = useState({}) + + const createMutation = useCreateCurrencyRate() + const updateMutation = useUpdateCurrencyRate(rateId ?? 0) + + const isPending = createMutation.isPending || updateMutation.isPending + + // Sync form when initialData loads (edit mode) + useEffect(() => { + if (mode === 'edit' && initialData) { + setForm({ + currencyFrom: initialData.currencyFrom, + currencyTo: initialData.currencyTo, + value: String(initialData.value), + }) + } + }, [mode, initialData]) + + const setField = (field: keyof FormState) => (val: string) => { + setForm((prev) => ({ ...prev, [field]: val })) + // Clear error on change + 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 + } + + const payload = { + currencyFrom: form.currencyFrom as CurrencyCode, + currencyTo: form.currencyTo as CurrencyCode, + value: Number(form.value), + } + + if (mode === 'create') { + await createMutation.mutateAsync(payload) + navigate('/resources/currency-rates') + } else { + await updateMutation.mutateAsync(payload) + navigate(`/resources/currency-rates/${rateId}`) + } + } + + const handleCancel = () => { + if (mode === 'create') { + navigate('/resources/currency-rates') + } else { + navigate(`/resources/currency-rates/${rateId}`) + } + } + + return ( +
+ {/* Currency From */} +
+ +
+ +

+ {t('currencyRates.hints.oneUnit', '1 möçberi')} +

+
+
+ + {/* Currency To */} +
+ + +
+ + {/* Value */} +
+ +
+ +

+ {t('currencyRates.hints.decimalNote', 'Bitin däl sanlary "." bilen ýazmaly')} +

+
+
+ + {/* Footer Actions */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/currencyRates/hooks/useCurrencyRates.ts b/src/features/currencyRates/hooks/useCurrencyRates.ts new file mode 100644 index 0000000..3b6411d --- /dev/null +++ b/src/features/currencyRates/hooks/useCurrencyRates.ts @@ -0,0 +1,100 @@ +// features/currencyRates/hooks/useCurrencyRates.ts + +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { + fetchCurrencyRates, + fetchCurrencyRateById, + createCurrencyRate, + updateCurrencyRate, + deleteCurrencyRate, + type CurrencyRateListParams, + type CreateCurrencyRatePayload, + type UpdateCurrencyRatePayload, +} from '../api/currencyRatesApi' + +// ─── Query Keys ─────────────────────────────────────────────────────────────── + +export const currencyRateKeys = { + all: ['currencyRates'] as const, + lists: () => [...currencyRateKeys.all, 'list'] as const, + list: (params: CurrencyRateListParams) => + [...currencyRateKeys.lists(), params] as const, + detail: (id: number) => + [...currencyRateKeys.all, 'detail', id] as const, +} + +// ─── useGetCurrencyRates ────────────────────────────────────────────────────── + +export function useGetCurrencyRates(params: CurrencyRateListParams = {}) { + return useQuery({ + queryKey: currencyRateKeys.list(params), + queryFn: () => fetchCurrencyRates(params), + }) +} + +// ─── useGetCurrencyRateById ─────────────────────────────────────────────────── + +export function useGetCurrencyRateById(id: number) { + return useQuery({ + queryKey: currencyRateKeys.detail(id), + queryFn: () => fetchCurrencyRateById(id), + enabled: !!id, + }) +} + +// ─── useCreateCurrencyRate ──────────────────────────────────────────────────── + +export function useCreateCurrencyRate() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: CreateCurrencyRatePayload) => createCurrencyRate(payload), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() }) + toast.success(t('currencyRates.toast.created', 'Walýuta kursy döredildi')) + }, + onError: () => { + toast.error(t('currencyRates.toast.createError', 'Döretmek başartmady')) + }, + }) +} + +// ─── useUpdateCurrencyRate ──────────────────────────────────────────────────── + +export function useUpdateCurrencyRate(id: number) { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: UpdateCurrencyRatePayload) => updateCurrencyRate(id, payload), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() }) + queryClient.invalidateQueries({ queryKey: currencyRateKeys.detail(id) }) + toast.success(t('currencyRates.toast.updated', 'Walýuta kursy üýtgedildi')) + }, + onError: () => { + toast.error(t('currencyRates.toast.updateError', 'Üýtgetmek başartmady')) + }, + }) +} + +// ─── useDeleteCurrencyRate ──────────────────────────────────────────────────── + +export function useDeleteCurrencyRate() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (id: number) => deleteCurrencyRate(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() }) + toast.success(t('currencyRates.toast.deleted', 'Walýuta kursy pozuldy')) + }, + onError: () => { + toast.error(t('currencyRates.toast.deleteError', 'Pozmak başartmady')) + }, + }) +} \ No newline at end of file diff --git a/src/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts b/src/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts new file mode 100644 index 0000000..6acafbe --- /dev/null +++ b/src/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi.ts @@ -0,0 +1,151 @@ +// features/onlinePaymentHistory/api/onlinePaymentHistoryApi.ts + +export type PaymentStatus = 'GARAŞYLÝAR' | 'TÖLENEN' | 'YATYRYLAN' + +export interface OnlinePayment { + id: number + orderId: string + amount: number + orderNumber: string + apiClient: string + description: string + formUrl: string + successUrl: string + status: PaymentStatus + callbackStatus: string | null + username: string + onlinePaymantableId: number + onlinePaymantableType: string + createdAt: string + updatedAt: string +} + +export interface OnlinePaymentListParams { + page?: number + perPage?: number + search?: string +} + +export interface OnlinePaymentListResponse { + data: OnlinePayment[] + total: number + page: number + perPage: number + totalPages: number +} + +// ─── Mock Data ──────────────────────────────────────────────────────────────── + +const buildPayment = ( + id: number, + orderId: string, + amount: number, + orderNumber: string, + apiClient: string, + description: string, + status: PaymentStatus, + username: string, + paymantableId: number, + paymantableType: string, + createdAt: string, + callbackStatus: string | null = null +): OnlinePayment => ({ + id, + orderId, + amount, + orderNumber, + apiClient, + description, + formUrl: `https://mpi.gov.tm/payment/merchants/online/payment_ru.html?mdOrder=${orderId}`, + successUrl: 'https://online.tbbank.gov.tm/online-payment-store-visa-master', + status, + callbackStatus, + username, + onlinePaymantableId: paymantableId, + onlinePaymantableType: paymantableType, + createdAt, + updatedAt: createdAt, +}) + +const VM_TYPE = 'App\\Modules\\VisaMasterPaymentOrder\\Models\\VisaMasterPaymentOrder' +const SBER_TYPE = 'App\\Modules\\SberPaymentOrder\\Models\\SberPaymentOrder' +const KART_TYPE = 'App\\Modules\\KartPaymentOrder\\Models\\KartPaymentOrder' + +const MOCK_PAYMENTS: OnlinePayment[] = [ + buildPayment(1667, 'ed99d307-65fd-40ed-98ec-898019000af4', 99438, '110526160855', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040830', 5280, VM_TYPE, '2026-05-11T16:08:00Z'), + buildPayment(1666, 'ab12c456-11aa-22bb-33cc-111111000001', 99438, '110526160800', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5279, VM_TYPE, '2026-05-11T16:06:00Z', 'SUCCESS'), + buildPayment(1665, 'bc23d567-22bb-33cc-44dd-222222000002', 99438, '110526160745', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5278, VM_TYPE, '2026-05-11T16:04:00Z', 'SUCCESS'), + buildPayment(1664, 'cd34e678-33cc-44dd-55ee-333333000003', 99438, '110526160730', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5277, VM_TYPE, '2026-05-11T16:03:00Z', 'SUCCESS'), + buildPayment(1663, 'de45f789-44dd-55ee-66ff-444444000004', 99438, '110526160715', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5276, VM_TYPE, '2026-05-11T16:01:00Z', 'SUCCESS'), + buildPayment(1662, 'ef56a890-55ee-66ff-77aa-555555000005', 99438, '110526155900', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5275, VM_TYPE, '2026-05-11T15:40:00Z', 'SUCCESS'), + buildPayment(1661, 'fa67b901-66ff-77aa-88bb-666666000006', 99438, '110526155830', 'billing_visa_master_username', 'Visa/Master tölegi', 'YATYRYLAN', '10130100040844', 5274, VM_TYPE, '2026-05-11T15:39:00Z'), + buildPayment(1660, 'ab78c012-77aa-88bb-99cc-777777000007', 99438, '110526155800', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5273, VM_TYPE, '2026-05-11T15:38:00Z', 'SUCCESS'), + buildPayment(1659, 'bc89d123-88bb-99cc-00dd-888888000008', 99438, '110526155730', 'billing_visa_master_username', 'Visa/Master tölegi', 'YATYRYLAN', '10130100040844', 5272, VM_TYPE, '2026-05-11T15:35:00Z'), + buildPayment(1658, 'cd90e234-99cc-00dd-11ee-999999000009', 99438, '110526152900', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040830', 5271, VM_TYPE, '2026-05-11T15:29:00Z', 'SUCCESS'), + buildPayment(1657, 'de01f345-00dd-11ee-22ff-000000000010', 99438, '110526103900', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5270, VM_TYPE, '2026-05-11T10:39:00Z'), + buildPayment(1656, 'ef12a456-11ee-22ff-33aa-111111000011', 99438, '110526103800', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5269, VM_TYPE, '2026-05-11T10:39:00Z'), + buildPayment(1655, 'fa23b567-22ff-33aa-44bb-222222000012', 99438, '110526103700', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5268, VM_TYPE, '2026-05-11T10:38:00Z'), + buildPayment(1654, 'ab34c678-33aa-44bb-55cc-333333000013', 99438, '110526103600', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040862', 5267, VM_TYPE, '2026-05-11T10:38:00Z'), + buildPayment(1653, 'bc45d789-44bb-55cc-66dd-444444000014', 99438, '110526085200', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040828', 5266, VM_TYPE, '2026-05-11T08:52:00Z'), + buildPayment(1652, 'cd56e890-55cc-66dd-77ee-555555000015', 99438, '060526142300', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040826', 5265, VM_TYPE, '2026-05-06T14:23:00Z'), + buildPayment(1651, 'de67f901-66dd-77ee-88ff-666666000016', 106345,'280426161300', 'billing_sber_username', 'Sber tölegi', 'GARAŞYLÝAR', '10130100040827', 5264, SBER_TYPE, '2026-04-28T16:13:00Z'), + buildPayment(1650, 'ef78a012-77ee-88ff-99aa-777777000017', 32, '250426130100', 'billing_username', 'Kart tölegi', 'GARAŞYLÝAR', '10130100004083', 5263, KART_TYPE, '2026-04-25T13:01:00Z'), + buildPayment(1649, 'fa89b123-88ff-99aa-00bb-888888000018', 32, '240426101900', 'billing_username', 'Kart tölegi', 'GARAŞYLÝAR', '10130100004083', 5262, KART_TYPE, '2026-04-24T10:19:00Z'), + buildPayment(1648, 'ab90c234-99aa-00bb-11cc-999999000019', 106344,'210426105900', 'billing_sber_username', 'Sber tölegi', 'TÖLENEN', '10130100040827', 5261, SBER_TYPE, '2026-04-21T10:59:00Z', 'SUCCESS'), + buildPayment(1647, 'bc01d345-00bb-11cc-22dd-000000000020', 106243,'200426153100', 'billing_sber_username', 'Sber tölegi', 'GARAŞYLÝAR', '10130100040833', 5260, SBER_TYPE, '2026-04-20T15:31:00Z'), + buildPayment(1646, 'cd12e456-11cc-22dd-33ee-111111000021', 99438, '170426111400', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040832', 5259, VM_TYPE, '2026-04-17T11:14:00Z', 'SUCCESS'), + buildPayment(1645, 'de23f567-22dd-33ee-44ff-222222000022', 99438, '170426103400', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040832', 5258, VM_TYPE, '2026-04-17T10:34:00Z'), + buildPayment(1644, 'ef34a678-33ee-44ff-55aa-333333000023', 99438, '160426175600', 'billing_visa_master_username', 'Visa/Master tölegi', 'GARAŞYLÝAR', '10130100040830', 5257, VM_TYPE, '2026-04-16T17:56:00Z'), + buildPayment(1643, 'fa45b789-44ff-55aa-66bb-444444000024', 99438, '150426155000', 'billing_visa_master_username', 'Visa/Master tölegi', 'TÖLENEN', '10130100040826', 5256, VM_TYPE, '2026-04-15T15:50:00Z', 'SUCCESS'), +] + +// Total mock count is 1664 per screenshot — we serve paginated slices of the 25 above +const TOTAL_MOCK = 1664 + +const delay = (ms = 400) => new Promise((res) => setTimeout(res, ms)) + +// ─── API Functions ──────────────────────────────────────────────────────────── + +export async function fetchOnlinePayments( + params: OnlinePaymentListParams = {} +): Promise { + await delay() + const { page = 1, perPage = 25, search = '' } = params + + let filtered = [...MOCK_PAYMENTS] + + if (search.trim()) { + const q = search.toLowerCase() + filtered = filtered.filter( + (r) => + String(r.amount).includes(q) || + r.apiClient.toLowerCase().includes(q) || + r.description.toLowerCase().includes(q)|| + r.username.toLowerCase().includes(q) || + r.status.toLowerCase().includes(q) || + r.orderId.toLowerCase().includes(q) + ) + } + + const total = search.trim() ? filtered.length : TOTAL_MOCK + const totalPages = Math.ceil(total / perPage) + const start = (page - 1) * perPage + const data = filtered.slice(start, start + perPage) + + return { data, total, page, perPage, totalPages } +} + +export async function fetchOnlinePaymentById(id: number): Promise { + await delay() + const item = MOCK_PAYMENTS.find((r) => r.id === id) + if (!item) throw new Error(`OnlinePayment with id ${id} not found`) + return { ...item } +} + +// Callback trigger — mock only logs; in real impl would POST to backend +export async function triggerPaymentCallback(id: number): Promise { + await delay(600) + const item = MOCK_PAYMENTS.find((r) => r.id === id) + if (!item) throw new Error(`OnlinePayment with id ${id} not found`) + // no-op in mock +} \ No newline at end of file diff --git a/src/features/onlinePaymentHistory/components/PaymentStatusBadge.tsx b/src/features/onlinePaymentHistory/components/PaymentStatusBadge.tsx new file mode 100644 index 0000000..07d2f2b --- /dev/null +++ b/src/features/onlinePaymentHistory/components/PaymentStatusBadge.tsx @@ -0,0 +1,33 @@ +import { + StatusBadge, + type StatusBadgeVariant, +} from '@/components/ui/statusBadge' +import { AlertCircle, CheckCircle2, XCircle } from 'lucide-react' +import type { PaymentStatus } from '@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi' + +const STATUS_CONFIG = { + GARAŞYLÝAR: { + label: 'Garaşylýar', + variant: 'warning' as StatusBadgeVariant, + icon: AlertCircle, + }, + TÖLENEN: { + label: 'Tölenen', + variant: 'success' as StatusBadgeVariant, + icon: CheckCircle2, + }, + YATYRYLAN: { + label: 'Ýatyrylan', + variant: 'error' as StatusBadgeVariant, + icon: XCircle, + }, +} satisfies Record< + PaymentStatus, + { label: string; variant: StatusBadgeVariant; icon: React.ElementType } +> + +export function PaymentStatusBadge({ status }: { status: PaymentStatus }) { + const cfg = STATUS_CONFIG[status] + if (!cfg) return {String(status)} + return +} diff --git a/src/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts b/src/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts new file mode 100644 index 0000000..559d788 --- /dev/null +++ b/src/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory.ts @@ -0,0 +1,60 @@ +// features/onlinePaymentHistory/hooks/useOnlinePaymentHistory.ts + +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { + fetchOnlinePayments, + fetchOnlinePaymentById, + triggerPaymentCallback, + type OnlinePaymentListParams, +} from '../api/onlinePaymentsHistoryApi' + +// ─── Query Keys ─────────────────────────────────────────────────────────────── + +export const onlinePaymentKeys = { + all: ['onlinePayments'] as const, + lists: () => [...onlinePaymentKeys.all, 'list'] as const, + list: (params: OnlinePaymentListParams) => + [...onlinePaymentKeys.lists(), params] as const, + detail: (id: number) => + [...onlinePaymentKeys.all, 'detail', id] as const, +} + +// ─── useGetOnlinePayments ───────────────────────────────────────────────────── + +export function useGetOnlinePayments(params: OnlinePaymentListParams = {}) { + return useQuery({ + queryKey: onlinePaymentKeys.list(params), + queryFn: () => fetchOnlinePayments(params), + }) +} + +// ─── useGetOnlinePaymentById ────────────────────────────────────────────────── + +export function useGetOnlinePaymentById(id: number) { + return useQuery({ + queryKey: onlinePaymentKeys.detail(id), + queryFn: () => fetchOnlinePaymentById(id), + enabled: !!id, + }) +} + +// ─── useTriggerPaymentCallback ──────────────────────────────────────────────── + +export function useTriggerPaymentCallback() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (id: number) => triggerPaymentCallback(id), + onSuccess: (_data, id) => { + queryClient.invalidateQueries({ queryKey: onlinePaymentKeys.detail(id) }) + queryClient.invalidateQueries({ queryKey: onlinePaymentKeys.lists() }) + toast.success(t('onlinePayments.toast.callbackTriggered', 'Callback ugradyldy')) + }, + onError: () => { + toast.error(t('onlinePayments.toast.callbackError', 'Callback ugratmak başartmady')) + }, + }) +} \ No newline at end of file diff --git a/src/features/permissions/api/permissionsApi.ts b/src/features/permissions/api/permissionsApi.ts new file mode 100644 index 0000000..8380bd1 --- /dev/null +++ b/src/features/permissions/api/permissionsApi.ts @@ -0,0 +1,134 @@ +// import {apiClient} from '@/lib/api/client' + +// ─── Types ──────────────────────────────────────────────────────────────────── + +export interface PermissionTranslation { + tk: string + ru: string + en: string +} + +export interface AuditLog { + id: number + action: string + by: string + target: string + status: string + date: string +} + +export interface Permission { + id: number + code: string + name: PermissionTranslation + guard_name: string + audit_logs?: AuditLog[] +} + +export interface PermissionPayload { + code: string + name: PermissionTranslation + guard_name: string +} + +export interface PermissionsListParams { + search?: string + page?: number + per_page?: number +} + +export interface PaginatedResponse { + data: T[] + meta: { + current_page: number + last_page: number + per_page: number + total: number + } +} + +// ─── Mock Data ──────────────────────────────────────────────────────────────── + +const MOCK_PERMISSIONS: Permission[] = [ + { id: 1, code: 'users.view', guard_name: 'web', name: { tk: 'Ulanyjylary görmek', ru: 'Просмотр пользователей', en: 'View users' } }, + { id: 2, code: 'users.create', guard_name: 'web', name: { tk: 'Ulanyjy döretmek', ru: 'Создание пользователя', en: 'Create user' } }, + { id: 3, code: 'users.edit', guard_name: 'web', name: { tk: 'Ulanyjyny üýtgetmek', ru: 'Редактирование пользователя', en: 'Edit user' } }, + { id: 4, code: 'users.delete', guard_name: 'web', name: { tk: 'Ulanyjyny pozmak', ru: 'Удаление пользователя', en: 'Delete user' } }, + { id: 5, code: 'roles.view', guard_name: 'web', name: { tk: 'Rollary görmek', ru: 'Просмотр ролей', en: 'View roles' } }, + { id: 6, code: 'roles.create', guard_name: 'web', name: { tk: 'Rol döretmek', ru: 'Создание роли', en: 'Create role' } }, + { id: 7, code: 'roles.edit', guard_name: 'web', name: { tk: 'Roly üýtgetmek', ru: 'Редактирование роли', en: 'Edit role' } }, + { id: 8, code: 'roles.delete', guard_name: 'web', name: { tk: 'Roly pozmak', ru: 'Удаление роли', en: 'Delete role' } }, + { id: 9, code: 'permissions.view', guard_name: 'web', name: { tk: 'Rugsatlary görmek', ru: 'Просмотр разрешений', en: 'View permissions' } }, + { id: 10, code: 'permissions.edit', guard_name: 'web', name: { tk: 'Rugsady üýtgetmek', ru: 'Редактирование разрешения', en: 'Edit permission' } }, +] + +const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms)) + +// ─── API functions ──────────────────────────────────────────────────────────── + +export const permissionsApi = { + getAll: async (params?: PermissionsListParams): Promise<{ data: PaginatedResponse }> => { + await delay() + const { search = '', page = 1, per_page = 25 } = params ?? {} + + let filtered = [...MOCK_PERMISSIONS] + if (search) { + const s = search.toLowerCase() + filtered = filtered.filter( + (p) => + p.code.toLowerCase().includes(s) || + p.name.tk.toLowerCase().includes(s) || + p.name.ru.toLowerCase().includes(s) || + p.name.en.toLowerCase().includes(s) + ) + } + + const total = filtered.length + const last_page = Math.ceil(total / per_page) + const start = (page - 1) * per_page + const data = filtered.slice(start, start + per_page) + + return { + data: { + data, + meta: { + current_page: page, + last_page, + per_page, + total, + }, + }, + } + }, + + getById: async (id: number): Promise<{ data: Permission }> => { + await delay() + const item = MOCK_PERMISSIONS.find((p) => p.id === id) + if (!item) throw new Error('Not found') + return { data: item } + }, + + create: async (payload: PermissionPayload): Promise<{ data: Permission }> => { + await delay() + const newItem: Permission = { + ...payload, + id: Math.floor(Math.random() * 10000), + } + MOCK_PERMISSIONS.push(newItem) + return { data: newItem } + }, + + update: async (id: number, payload: PermissionPayload): Promise<{ data: Permission }> => { + await delay() + const index = MOCK_PERMISSIONS.findIndex((p) => p.id === id) + if (index === -1) throw new Error('Not found') + MOCK_PERMISSIONS[index] = { ...MOCK_PERMISSIONS[index], ...payload } + return { data: MOCK_PERMISSIONS[index] } + }, + + delete: async (id: number): Promise => { + await delay() + const index = MOCK_PERMISSIONS.findIndex((p) => p.id === id) + if (index !== -1) MOCK_PERMISSIONS.splice(index, 1) + }, +} \ No newline at end of file diff --git a/src/features/permissions/components/permissionsForm.tsx b/src/features/permissions/components/permissionsForm.tsx new file mode 100644 index 0000000..f07a4a5 --- /dev/null +++ b/src/features/permissions/components/permissionsForm.tsx @@ -0,0 +1,202 @@ +import { useState } 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 { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions' +import type { Permission, PermissionPayload } from '../api/permissionsApi' + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface PermissionFormProps { + mode: 'create' | 'edit' + initialData?: Permission + permissionId?: number +} + +interface FormErrors { + code?: string + name_tk?: string + name_ru?: string + name_en?: string + guard_name?: string +} + +type LangKey = 'tk' | 'ru' | 'en' + +const LANG_TABS: { key: LangKey; label: string }[] = [ + { key: 'tk', label: 'Türkmen' }, + { key: 'ru', label: 'Русский' }, + { key: 'en', label: 'English' }, +] + +const GUARD_OPTIONS = [ + { value: 'web', label: 'web' }, + { value: 'api', label: 'api' }, + { value: 'sanctum', label: 'sanctum' }, +] + +// ─── PermissionForm ─────────────────────────────────────────────────────────── + +export function PermissionForm({ mode, initialData, permissionId }: PermissionFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const createPermission = useCreatePermission() + const updatePermission = useUpdatePermission(permissionId ?? 0) + + const isPending = createPermission.isPending || updatePermission.isPending + + const [activeLang, setActiveLang] = useState('tk') + const [errors, setErrors] = useState({}) + + const [form, setForm] = useState({ + code: initialData?.code ?? '', + guard_name: initialData?.guard_name ?? 'web', + name: { + tk: initialData?.name?.tk ?? '', + ru: initialData?.name?.ru ?? '', + en: initialData?.name?.en ?? '', + }, + }) + + // ── Helpers ──────────────────────────────────────────────────────────────── + + const setField = (field: keyof Omit, value: string) => { + setForm((prev) => ({ ...prev, [field]: value })) + setErrors((prev) => ({ ...prev, [field]: undefined })) + } + + const setNameField = (lang: LangKey, value: string) => { + setForm((prev) => ({ ...prev, name: { ...prev.name, [lang]: value } })) + setErrors((prev) => ({ ...prev, [`name_${lang}`]: undefined })) + } + + // ── Validation ───────────────────────────────────────────────────────────── + + const validate = (): boolean => { + const newErrors: FormErrors = {} + + if (!form.code.trim()) + newErrors.code = t('permissions.validation.codeRequired', 'Kod hökman!') + if (!form.name.tk.trim()) + newErrors.name_tk = t('permissions.validation.nameTkRequired', 'Türkmençe ady hökman!') + if (!form.guard_name.trim()) + newErrors.guard_name = t('permissions.validation.guardRequired', 'Guard name hökman!') + + setErrors(newErrors) + return Object.keys(newErrors).length === 0 + } + + // ── Submit ───────────────────────────────────────────────────────────────── + + const handleSubmit = () => { + if (!validate()) return + + if (mode === 'create') { + createPermission.mutate(form, { + onSuccess: () => navigate('/settings/users/permissions'), + }) + } else { + updatePermission.mutate(form, { + onSuccess: () => navigate('/settings/users/permissions'), + }) + } + } + + // ── Render ───────────────────────────────────────────────────────────────── + + return ( +
+ + {/* Code */} +
+ + {t('permissions.fields.code', 'Kod')} + * + + setField('code', v)} + placeholder={t('permissions.fields.code', 'Kod')} + error={errors.code} + disabled={isPending} + /> +
+ + {/* Name (multilingual) */} +
+ + {t('permissions.fields.name', 'Ady')} + * + +
+
+ {LANG_TABS.map((tab) => ( + + ))} +
+ setNameField(activeLang, v)} + placeholder={t('permissions.fields.name', 'Ady')} + error={errors[`name_${activeLang}` as keyof FormErrors]} + disabled={isPending} + /> +
+
+ + {/* Guard name */} +
+ + {t('permissions.fields.guardName', 'Guard name')} + * + + setField('guard_name', v)} + options={GUARD_OPTIONS} + error={errors.guard_name} + disabled={isPending} + /> +
+ + {/* Actions */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/permissions/hooks/usePermissions.ts b/src/features/permissions/hooks/usePermissions.ts new file mode 100644 index 0000000..7db409f --- /dev/null +++ b/src/features/permissions/hooks/usePermissions.ts @@ -0,0 +1,92 @@ +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { + permissionsApi, + type PermissionPayload, + type PermissionsListParams, +} from '../api/permissionsApi' + +// ─── Query keys ─────────────────────────────────────────────────────────────── + +export const permissionKeys = { + all: ['permissions'] as const, + list: (params: PermissionsListParams) => ['permissions', 'list', params] as const, + detail: (id: number) => ['permissions', 'detail', id] as const, +} + +// ─── usePermissions (list) ──────────────────────────────────────────────────── + +export function usePermissions(params: PermissionsListParams) { + return useQuery({ + queryKey: permissionKeys.list(params), + queryFn: () => permissionsApi.getAll(params).then((r) => r.data), + }) +} + +// ─── usePermission (single) ─────────────────────────────────────────────────── + +export function usePermission(id: number) { + return useQuery({ + queryKey: permissionKeys.detail(id), + queryFn: () => permissionsApi.getById(id).then((r) => r.data), + enabled: !!id, + }) +} + +// ─── useCreatePermission ────────────────────────────────────────────────────── + +export function useCreatePermission() { + const { t } = useTranslation() + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (payload: PermissionPayload) => + permissionsApi.create(payload).then((r) => r.data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: permissionKeys.all }) + toast.success(t('permissions.toast.created', 'Rugsat üstünlikli döredildi!')) + }, + onError: () => { + toast.error(t('permissions.toast.createError', 'Rugsat döretmekde ýalňyşlyk ýüze çykdy.')) + }, + }) +} + +// ─── useUpdatePermission ────────────────────────────────────────────────────── + +export function useUpdatePermission(id: number) { + const { t } = useTranslation() + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (payload: PermissionPayload) => + permissionsApi.update(id, payload).then((r) => r.data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: permissionKeys.all }) + queryClient.invalidateQueries({ queryKey: permissionKeys.detail(id) }) + toast.success(t('permissions.toast.updated', 'Rugsat üstünlikli üýtgedildi!')) + }, + onError: () => { + toast.error(t('permissions.toast.updateError', 'Rugsat üýtgetmekde ýalňyşlyk ýüze çykdy.')) + }, + }) +} + +// ─── useDeletePermission ────────────────────────────────────────────────────── + +export function useDeletePermission() { + const { t } = useTranslation() + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => permissionsApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: permissionKeys.all }) + toast.success(t('permissions.toast.deleted', 'Rugsat üstünlikli pozuldy!')) + }, + onError: () => { + toast.error(t('permissions.toast.deleteError', 'Rugsat pozmakda ýalňyşlyk ýüze çykdy.')) + }, + }) +} \ No newline at end of file diff --git a/src/features/roles/api/rolesApi.ts b/src/features/roles/api/rolesApi.ts new file mode 100644 index 0000000..5c3f036 --- /dev/null +++ b/src/features/roles/api/rolesApi.ts @@ -0,0 +1,118 @@ +// import {apiClient} from '@/lib/api/client' + +// ─── Types ──────────────────────────────────────────────────────────────────── + +export interface RoleTranslation { + tk: string + ru: string + en: string +} + +export interface Role { + id: number + code: string + name: RoleTranslation + guard_name: string +} + +export interface RolePayload { + code: string + name: RoleTranslation + guard_name: string +} + +export interface RolesListParams { + search?: string + page?: number + per_page?: number +} + +export interface PaginatedResponse { + data: T[] + meta: { + current_page: number + last_page: number + per_page: number + total: number + } +} + +// ─── Mock Data ──────────────────────────────────────────────────────────────── + +const MOCK_ROLES: Role[] = [ + { id: 1, code: 'admin', guard_name: 'web', name: { tk: 'Administrator', ru: 'Администратор', en: 'Administrator' } }, + { id: 2, code: 'operator', guard_name: 'web', name: { tk: 'Operator', ru: 'Оператор', en: 'Operator' } }, + { id: 3, code: 'manager', guard_name: 'web', name: { tk: 'Menijer', ru: 'Менеджер', en: 'Manager' } }, + { id: 4, code: 'editor', guard_name: 'web', name: { tk: 'Redaktor', ru: 'Редактор', en: 'Editor' } }, +] + +const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms)) + +// ─── API functions ──────────────────────────────────────────────────────────── + +export const rolesApi = { + getAll: async (params?: RolesListParams): Promise<{ data: PaginatedResponse }> => { + await delay() + const { search = '', page = 1, per_page = 25 } = params ?? {} + + let filtered = [...MOCK_ROLES] + if (search) { + const s = search.toLowerCase() + filtered = filtered.filter( + (r) => + r.code.toLowerCase().includes(s) || + r.name.tk.toLowerCase().includes(s) || + r.name.ru.toLowerCase().includes(s) || + r.name.en.toLowerCase().includes(s) + ) + } + + const total = filtered.length + const last_page = Math.ceil(total / per_page) + const start = (page - 1) * per_page + const data = filtered.slice(start, start + per_page) + + return { + data: { + data, + meta: { + current_page: page, + last_page, + per_page, + total, + }, + }, + } + }, + + getById: async (id: number): Promise<{ data: Role }> => { + await delay() + const item = MOCK_ROLES.find((r) => r.id === id) + if (!item) throw new Error('Not found') + return { data: item } + }, + + create: async (payload: RolePayload): Promise<{ data: Role }> => { + await delay() + const newItem: Role = { + ...payload, + id: Math.floor(Math.random() * 10000), + } + MOCK_ROLES.push(newItem) + return { data: newItem } + }, + + update: async (id: number, payload: RolePayload): Promise<{ data: Role }> => { + await delay() + const index = MOCK_ROLES.findIndex((r) => r.id === id) + if (index === -1) throw new Error('Not found') + MOCK_ROLES[index] = { ...MOCK_ROLES[index], ...payload } + return { data: MOCK_ROLES[index] } + }, + + delete: async (id: number): Promise => { + await delay() + const index = MOCK_ROLES.findIndex((r) => r.id === id) + if (index !== -1) MOCK_ROLES.splice(index, 1) + }, +} \ No newline at end of file diff --git a/src/features/roles/components/roleForm.tsx b/src/features/roles/components/roleForm.tsx new file mode 100644 index 0000000..647ccda --- /dev/null +++ b/src/features/roles/components/roleForm.tsx @@ -0,0 +1,203 @@ +import { useState } 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 { useCreateRole, useUpdateRole } from '../hooks/useRoles' +import type { Role, RolePayload } from '../api/rolesApi' + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface RoleFormProps { + mode: 'create' | 'edit' + initialData?: Role + roleId?: number +} + +interface FormErrors { + code?: string + name_tk?: string + name_ru?: string + name_en?: string + guard_name?: string +} + +type LangKey = 'tk' | 'ru' | 'en' + +const LANG_TABS: { key: LangKey; label: string }[] = [ + { key: 'tk', label: 'Türkmen' }, + { key: 'ru', label: 'Русский' }, + { key: 'en', label: 'English' }, +] + +const GUARD_OPTIONS = [ + { value: 'web', label: 'web' }, + { value: 'api', label: 'api' }, + { value: 'sanctum', label: 'sanctum' }, +] + +// ─── RoleForm ───────────────────────────────────────────────────────────────── + +export function RoleForm({ mode, initialData, roleId }: RoleFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const createRole = useCreateRole() + const updateRole = useUpdateRole(roleId ?? 0) + + const isPending = createRole.isPending || updateRole.isPending + + const [activeLang, setActiveLang] = useState('tk') + const [errors, setErrors] = useState({}) + + const [form, setForm] = useState({ + code: initialData?.code ?? '', + guard_name: initialData?.guard_name ?? 'web', + name: { + tk: initialData?.name?.tk ?? '', + ru: initialData?.name?.ru ?? '', + en: initialData?.name?.en ?? '', + }, + }) + + // ── Helpers ──────────────────────────────────────────────────────────────── + + const setField = (field: keyof Omit, value: string) => { + setForm((prev) => ({ ...prev, [field]: value })) + setErrors((prev) => ({ ...prev, [field]: undefined })) + } + + const setNameField = (lang: LangKey, value: string) => { + setForm((prev) => ({ ...prev, name: { ...prev.name, [lang]: value } })) + setErrors((prev) => ({ ...prev, [`name_${lang}`]: undefined })) + } + + // ── Validation ───────────────────────────────────────────────────────────── + + const validate = (): boolean => { + const newErrors: FormErrors = {} + + if (!form.code.trim()) + newErrors.code = t('roles.validation.codeRequired', 'Kod hökman!') + if (!form.name.tk.trim()) + newErrors.name_tk = t('roles.validation.nameTkRequired', 'Türkmençe ady hökman!') + if (!form.guard_name.trim()) + newErrors.guard_name = t('roles.validation.guardRequired', 'Guard name hökman!') + + setErrors(newErrors) + return Object.keys(newErrors).length === 0 + } + + // ── Submit ───────────────────────────────────────────────────────────────── + + const handleSubmit = () => { + if (!validate()) return + + if (mode === 'create') { + createRole.mutate(form, { + onSuccess: () => navigate('/settings/users/roles'), + }) + } else { + updateRole.mutate(form, { + onSuccess: () => navigate('/settings/users/roles'), + }) + } + } + + // ── Render ───────────────────────────────────────────────────────────────── + + return ( +
+ + {/* Code */} +
+ + {t('roles.fields.code', 'Kod')} + * + + setField('code', v)} + placeholder={t('roles.fields.code', 'Kod')} + error={errors.code} + disabled={isPending} + /> +
+ + {/* Name (multilingual) */} +
+ + {t('roles.fields.name', 'Ady')} + * + +
+ {/* Language tabs */} +
+ {LANG_TABS.map((tab) => ( + + ))} +
+ setNameField(activeLang, v)} + placeholder={t('roles.fields.name', 'Ady')} + error={errors[`name_${activeLang}` as keyof FormErrors]} + disabled={isPending} + /> +
+
+ + {/* Guard name */} +
+ + {t('roles.fields.guardName', 'Guard name')} + * + + setField('guard_name', v)} + options={GUARD_OPTIONS} + error={errors.guard_name} + disabled={isPending} + /> +
+ + {/* Actions */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/roles/hooks/useRoles.ts b/src/features/roles/hooks/useRoles.ts new file mode 100644 index 0000000..5f95696 --- /dev/null +++ b/src/features/roles/hooks/useRoles.ts @@ -0,0 +1,86 @@ +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { rolesApi, type RolePayload, type RolesListParams } from '../api/rolesApi' + +// ─── Query keys ─────────────────────────────────────────────────────────────── + +export const roleKeys = { + all: ['roles'] as const, + list: (params: RolesListParams) => ['roles', 'list', params] as const, + detail: (id: number) => ['roles', 'detail', id] as const, +} + +// ─── useRoles (list) ────────────────────────────────────────────────────────── + +export function useRoles(params: RolesListParams) { + return useQuery({ + queryKey: roleKeys.list(params), + queryFn: () => rolesApi.getAll(params).then((r) => r.data), + }) +} + +// ─── useRole (single) ───────────────────────────────────────────────────────── + +export function useRole(id: number) { + return useQuery({ + queryKey: roleKeys.detail(id), + queryFn: () => rolesApi.getById(id).then((r) => r.data), + enabled: !!id, + }) +} + +// ─── useCreateRole ──────────────────────────────────────────────────────────── + +export function useCreateRole() { + const { t } = useTranslation() + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (payload: RolePayload) => rolesApi.create(payload).then((r) => r.data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: roleKeys.all }) + toast.success(t('roles.toast.created', 'Rol üstünlikli döredildi!')) + }, + onError: () => { + toast.error(t('roles.toast.createError', 'Rol döretmekde ýalňyşlyk ýüze çykdy.')) + }, + }) +} + +// ─── useUpdateRole ──────────────────────────────────────────────────────────── + +export function useUpdateRole(id: number) { + const { t } = useTranslation() + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (payload: RolePayload) => rolesApi.update(id, payload).then((r) => r.data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: roleKeys.all }) + queryClient.invalidateQueries({ queryKey: roleKeys.detail(id) }) + toast.success(t('roles.toast.updated', 'Rol üstünlikli üýtgedildi!')) + }, + onError: () => { + toast.error(t('roles.toast.updateError', 'Roly üýtgetmekde ýalňyşlyk ýüze çykdy.')) + }, + }) +} + +// ─── useDeleteRole ──────────────────────────────────────────────────────────── + +export function useDeleteRole() { + const { t } = useTranslation() + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => rolesApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: roleKeys.all }) + toast.success(t('roles.toast.deleted', 'Rol üstünlikli pozuldy!')) + }, + onError: () => { + toast.error(t('roles.toast.deleteError', 'Roly pozmakda ýalňyşlyk ýüze çykdy.')) + }, + }) +} \ No newline at end of file diff --git a/src/features/visaMasterSberSettings/api/visaMasterSberSettingsApi.ts b/src/features/visaMasterSberSettings/api/visaMasterSberSettingsApi.ts new file mode 100644 index 0000000..c01ea0e --- /dev/null +++ b/src/features/visaMasterSberSettings/api/visaMasterSberSettingsApi.ts @@ -0,0 +1,126 @@ +// features/visaMasterSettings/api/visaMasterSettingsApi.ts + +export interface VisaMasterSetting { + id: number + kod: string + ady: string + yazgy: string + createdAt: string + updatedAt: string +} + +export interface VisaMasterSettingListParams { + page?: number + perPage?: number + search?: string +} + +export interface VisaMasterSettingListResponse { + data: VisaMasterSetting[] + total: number + page: number + perPage: number + totalPages: number +} + +export interface VisaMasterSettingPayload { + kod: string + ady: string + yazgy: string +} + +// ─── Mock Store ─────────────────────────────────────────────────────────────── + +let mockStore: VisaMasterSetting[] = [ + { + id: 2, + kod: 'sber_payment_warning', + ady: 'Sber töleg duýduryş', + yazgy: 'Sber töleg duýduryş', + createdAt: '2026-03-10T08:00:00Z', + updatedAt: '2026-05-01T08:00:00Z', + }, + { + id: 1, + kod: 'payment_warning_text', + ady: 'Visa/Master töleg duýduryş', + yazgy: 'Dogry töleg aýyny saýlamagyňyzy haýyş edýäris!!!!', + createdAt: '2026-01-05T09:00:00Z', + updatedAt: '2026-04-20T09:00:00Z', + }, +] + +let nextId = 3 + +const delay = (ms = 400) => new Promise((res) => setTimeout(res, ms)) + +// ─── API Functions ──────────────────────────────────────────────────────────── + +export async function fetchVisaMasterSettings( + params: VisaMasterSettingListParams = {} +): Promise { + await delay() + const { page = 1, perPage = 25, search = '' } = params + + let filtered = [...mockStore] + + if (search.trim()) { + const q = search.toLowerCase() + filtered = filtered.filter( + (r) => + r.kod.toLowerCase().includes(q) || + r.ady.toLowerCase().includes(q) || + r.yazgy.toLowerCase().includes(q) || + String(r.id).includes(q) + ) + } + + filtered.sort((a, b) => b.id - a.id) + + const total = filtered.length + const totalPages = Math.ceil(total / perPage) || 1 + const start = (page - 1) * perPage + const data = filtered.slice(start, start + perPage) + + return { data, total, page, perPage, totalPages } +} + +export async function fetchVisaMasterSettingById(id: number): Promise { + await delay() + const item = mockStore.find((r) => r.id === id) + if (!item) throw new Error(`VisaMasterSetting with id ${id} not found`) + return { ...item } +} + +export async function createVisaMasterSetting( + payload: VisaMasterSettingPayload +): Promise { + await delay() + const now = new Date().toISOString() + const created: VisaMasterSetting = { id: nextId++, ...payload, createdAt: now, updatedAt: now } + mockStore = [created, ...mockStore] + return created +} + +export async function updateVisaMasterSetting( + id: number, + payload: VisaMasterSettingPayload +): Promise { + await delay() + const idx = mockStore.findIndex((r) => r.id === id) + if (idx === -1) throw new Error(`VisaMasterSetting with id ${id} not found`) + const updated: VisaMasterSetting = { + ...mockStore[idx], + ...payload, + updatedAt: new Date().toISOString(), + } + mockStore = mockStore.map((r) => (r.id === id ? updated : r)) + return updated +} + +export async function deleteVisaMasterSetting(id: number): Promise { + await delay() + if (!mockStore.some((r) => r.id === id)) + throw new Error(`VisaMasterSetting with id ${id} not found`) + mockStore = mockStore.filter((r) => r.id !== id) +} \ No newline at end of file diff --git a/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx b/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx new file mode 100644 index 0000000..7bbfb30 --- /dev/null +++ b/src/features/visaMasterSberSettings/components/visaMasterSberSettingsForm.tsx @@ -0,0 +1,190 @@ +// features/visaMasterSettings/components/VisaMasterSettingForm.tsx + +import { useEffect, useState } 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 { type VisaMasterSetting } from '../api/visaMasterSberSettingsApi' +import { + useCreateVisaMasterSetting, + useUpdateVisaMasterSetting, +} from '../hooks/useVisaMasterSettings' + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface FormState { + kod: string + ady: string + yazgy: string +} + +interface FormErrors { + kod?: string + ady?: string + yazgy?: string +} + +export interface VisaMasterSettingFormProps { + mode: 'create' | 'edit' + initialData?: VisaMasterSetting + settingId?: number +} + +// ─── Validation ─────────────────────────────────────────────────────────────── + +function validate( + form: FormState, + t: (key: string, fallback: string) => string +): FormErrors { + const errors: FormErrors = {} + + if (!form.kod.trim()) + errors.kod = t('visaMasterSettings.errors.kodRequired', 'Kod giriziň') + + if (!form.ady.trim()) + errors.ady = t('visaMasterSettings.errors.adyRequired', 'Ady giriziň') + + if (!form.yazgy.trim()) + errors.yazgy = t('visaMasterSettings.errors.yazgyRequired', 'Yazgy giriziň') + + return errors +} + +// ─── VisaMasterSettingForm ──────────────────────────────────────────────────── + +export function VisaMasterSettingForm({ + mode, + initialData, + settingId, +}: VisaMasterSettingFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const [form, setForm] = useState({ + kod: initialData?.kod ?? '', + ady: initialData?.ady ?? '', + yazgy: initialData?.yazgy ?? '', + }) + const [errors, setErrors] = useState({}) + + const createMutation = useCreateVisaMasterSetting() + const updateMutation = useUpdateVisaMasterSetting(settingId ?? 0) + + const isPending = createMutation.isPending || updateMutation.isPending + + // Sync when initialData arrives (edit mode async fetch) + useEffect(() => { + if (mode === 'edit' && initialData) { + setForm({ + kod: initialData.kod, + ady: initialData.ady, + yazgy: initialData.yazgy, + }) + } + }, [mode, initialData]) + + const setField = (field: keyof FormState) => (val: string) => { + setForm((prev) => ({ ...prev, [field]: val })) + 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 + } + + const payload = { kod: form.kod.trim(), ady: form.ady.trim(), yazgy: form.yazgy.trim() } + + if (mode === 'create') { + await createMutation.mutateAsync(payload) + navigate('/resources/visa-master-settings') + } else { + await updateMutation.mutateAsync(payload) + navigate('/resources/visa-master-settings') + } + } + + const handleCancel = () => navigate('/resources/visa-master-settings') + + // ─── Render ─────────────────────────────────────────────────────────────── + + return ( +
+ {/* Kod */} +
+ + +
+ + {/* Ady */} +
+ + +
+ + {/* Yazgy */} +
+ + +
+ + {/* Footer */} +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/src/features/visaMasterSberSettings/hooks/useVisaMasterSettings.ts b/src/features/visaMasterSberSettings/hooks/useVisaMasterSettings.ts new file mode 100644 index 0000000..4e25480 --- /dev/null +++ b/src/features/visaMasterSberSettings/hooks/useVisaMasterSettings.ts @@ -0,0 +1,99 @@ +// features/visaMasterSettings/hooks/useVisaMasterSettings.ts + +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { + fetchVisaMasterSettings, + fetchVisaMasterSettingById, + createVisaMasterSetting, + updateVisaMasterSetting, + deleteVisaMasterSetting, + type VisaMasterSettingListParams, + type VisaMasterSettingPayload, +} from '../api/visaMasterSberSettingsApi' + +// ─── Query Keys ─────────────────────────────────────────────────────────────── + +export const visaMasterSettingKeys = { + all: ['visaMasterSettings'] as const, + lists: () => [...visaMasterSettingKeys.all, 'list'] as const, + list: (params: VisaMasterSettingListParams) => + [...visaMasterSettingKeys.lists(), params] as const, + detail: (id: number) => + [...visaMasterSettingKeys.all, 'detail', id] as const, +} + +// ─── useGetVisaMasterSettings ───────────────────────────────────────────────── + +export function useGetVisaMasterSettings(params: VisaMasterSettingListParams = {}) { + return useQuery({ + queryKey: visaMasterSettingKeys.list(params), + queryFn: () => fetchVisaMasterSettings(params), + }) +} + +// ─── useGetVisaMasterSettingById ────────────────────────────────────────────── + +export function useGetVisaMasterSettingById(id: number) { + return useQuery({ + queryKey: visaMasterSettingKeys.detail(id), + queryFn: () => fetchVisaMasterSettingById(id), + enabled: !!id, + }) +} + +// ─── useCreateVisaMasterSetting ─────────────────────────────────────────────── + +export function useCreateVisaMasterSetting() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: VisaMasterSettingPayload) => createVisaMasterSetting(payload), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() }) + toast.success(t('visaMasterSettings.toast.created', 'Sazlama döredildi')) + }, + onError: () => { + toast.error(t('visaMasterSettings.toast.createError', 'Döretmek başartmady')) + }, + }) +} + +// ─── useUpdateVisaMasterSetting ─────────────────────────────────────────────── + +export function useUpdateVisaMasterSetting(id: number) { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: VisaMasterSettingPayload) => updateVisaMasterSetting(id, payload), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() }) + queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.detail(id) }) + toast.success(t('visaMasterSettings.toast.updated', 'Sazlama üýtgedildi')) + }, + onError: () => { + toast.error(t('visaMasterSettings.toast.updateError', 'Üýtgetmek başartmady')) + }, + }) +} + +// ─── useDeleteVisaMasterSetting ─────────────────────────────────────────────── + +export function useDeleteVisaMasterSetting() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (id: number) => deleteVisaMasterSetting(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() }) + toast.success(t('visaMasterSettings.toast.deleted', 'Sazlama pozuldy')) + }, + onError: () => { + toast.error(t('visaMasterSettings.toast.deleteError', 'Pozmak başartmady')) + }, + }) +} \ No newline at end of file diff --git a/src/layouts/DashboardLayout.tsx b/src/layouts/DashboardLayout.tsx index 221de7b..2d8f627 100644 --- a/src/layouts/DashboardLayout.tsx +++ b/src/layouts/DashboardLayout.tsx @@ -338,20 +338,20 @@ function AppSidebar() { items: [ { title: t("Currency rates", "Walýuta kurslary"), - url: "/currencies/rates", + url: "/currency-rates", }, { title: t( "Visa/Master, Sber Settings", "Visa/Master, Sber sazlamalary", ), - url: "/currencies/settings", + url: "/visa-master-sber-settings", }, ], }, { title: t("Online payment history", "Onlaýn töleg taryhy"), - url: "/online-payments", + url: "/online-payments-history", icon: CreditCard, }, ], diff --git a/src/pages/currencies/currencyRates/index.tsx b/src/pages/currencies/currencyRates/index.tsx new file mode 100644 index 0000000..3e5466e --- /dev/null +++ b/src/pages/currencies/currencyRates/index.tsx @@ -0,0 +1,208 @@ +// pages/CurrencyRatesPage.tsx + +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Eye, Pencil, Trash2 } from 'lucide-react' +import { DataTable, type ColumnDef } from '@/components/dataTable' +import { DataTableToolbar } from '@/components/dataTableToolbar' +import { Button } from '@/components/ui/button' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { useGetCurrencyRates, useDeleteCurrencyRate } from '@/features/currencyRates/hooks/useCurrencyRates' +import type { CurrencyRate } from '@/features/currencyRates/api/currencyRatesApi' + +// ─── Column visibility defaults ─────────────────────────────────────────────── + +const DEFAULT_VISIBILITY = { id: true, currencyFrom: true, currencyTo: true, value: true } +const DEFAULT_ORDER = ['id', 'currencyFrom', 'currencyTo', 'value', 'actions'] + +// ─── CurrencyRatesPage ──────────────────────────────────────────────────────── + +export default function CurrencyRatesPage() { + const { t } = useTranslation() + const navigate = useNavigate() + + const [page, setPage] = useState(1) + const [perPage] = useState(25) + const [search, setSearch] = useState('') + const [columnVisibility, setColumnVisibility] = useState>(DEFAULT_VISIBILITY) + const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER) + const [deleteId, setDeleteId] = useState(null) + + const { data, isLoading } = useGetCurrencyRates({ page, perPage, search }) + const deleteMutation = useDeleteCurrencyRate() + + const handleDeleteConfirm = async () => { + if (deleteId === null) return + await deleteMutation.mutateAsync(deleteId) + setDeleteId(null) + } + + const handleSearchChange = (val: string) => { + setSearch(val) + setPage(1) + } + + // ─── Columns ────────────────────────────────────────────────────────────── + + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + + ), + size: 80, + }, + { + accessorKey: 'currencyFrom', + header: t('currencyRates.columns.currencyFrom', 'CURRENCY FROM'), + cell: ({ row }) => ( + {row.original.currencyFrom} + ), + }, + { + accessorKey: 'currencyTo', + header: t('currencyRates.columns.currencyTo', 'CURRENCY TO'), + cell: ({ row }) => ( + {row.original.currencyTo} + ), + }, + { + accessorKey: 'value', + header: t('currencyRates.columns.value', 'VALUE'), + cell: ({ row }) => ( + {row.original.value} + ), + }, + { + id: 'actions', + header: '', + enableSorting: false, + enableHiding: false, + cell: ({ row }) => ( +
+ + + +
+ ), + size: 120, + }, + ] + + const columnMeta = columns + .filter((c) => 'accessorKey' in c && c.accessorKey) + .map((c) => ({ + id: String(('accessorKey' in c ? c.accessorKey : c.id) ?? ''), + label: typeof c.header === 'string' ? c.header : String(('accessorKey' in c ? c.accessorKey : '') ?? ''), + })) + + // ─── Render ─────────────────────────────────────────────────────────────── + + return ( +
+ + +

+ {t('currencyRates.title', 'Walýuta kursy')} +

+ + navigate('/currency-rates/create')} + /> + + String(row.id)} + currentPage={page} + totalPages={data?.totalPages ?? 1} + totalCount={data?.total ?? 0} + onPageChange={setPage} + /> + + {/* Delete Confirmation Dialog */} + { if (!open) setDeleteId(null) }}> + + + + {t('currencyRates.deleteDialog.title', 'Pozmak isleýärsiňizmi?')} + + + {t( + 'currencyRates.deleteDialog.description', + 'Bu amal yzyna gaýtarylyp bilinmez. Walýuta kursy hemişelik pozular.' + )} + + + + {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/currencies/currencyRatesCreate/index.tsx b/src/pages/currencies/currencyRatesCreate/index.tsx new file mode 100644 index 0000000..879d8eb --- /dev/null +++ b/src/pages/currencies/currencyRatesCreate/index.tsx @@ -0,0 +1,23 @@ +// pages/CurrencyRateCreatePage.tsx + +import { useTranslation } from 'react-i18next' +import { CurrencyRateForm } from '@/features/currencyRates/components/currencyRatesForm' + +// ─── CurrencyRateCreatePage ─────────────────────────────────────────────────── + +export default function CurrencyRateCreatePage() { + const { t } = useTranslation() + + return ( +
+ +

+ {t('currencyRates.actions.create', 'Walýuta kursy dörediň')} +

+ +
+ +
+
+ ) +} \ No newline at end of file diff --git a/src/pages/currencies/currencyRatesEdit/index.tsx b/src/pages/currencies/currencyRatesEdit/index.tsx new file mode 100644 index 0000000..6a70100 --- /dev/null +++ b/src/pages/currencies/currencyRatesEdit/index.tsx @@ -0,0 +1,57 @@ +// pages/CurrencyRateEditPage.tsx + +import { useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { CurrencyRateForm } from '@/features/currencyRates/components/currencyRatesForm' +import { useGetCurrencyRateById } from '@/features/currencyRates/hooks/useCurrencyRates' + +// ─── CurrencyRateEditPage ───────────────────────────────────────────────────── + +export default function CurrencyRateEditPage() { + const { id } = useParams<{ id: string }>() + const numericId = Number(id) + const { t } = useTranslation() + + const { data: rate, isLoading } = useGetCurrencyRateById(numericId) + + // ─── Loading skeleton ────────────────────────────────────────────────────── + + if (isLoading) { + return ( +
+
+
+
+ ) + } + + if (!rate) { + return ( +
+

+ {t('currencyRates.notFound', 'Walýuta kursy tapylmady')} +

+
+ ) + } + + // ─── Render ─────────────────────────────────────────────────────────────── + + return ( +
+ + +

+ {t('currencyRates.detail.editTitle', 'Walýuta kursyny üýtgetmek')}: {rate.id} +

+ +
+ +
+
+ ) +} \ No newline at end of file diff --git a/src/pages/currencies/currencyRatesView/index.tsx b/src/pages/currencies/currencyRatesView/index.tsx new file mode 100644 index 0000000..4326f7d --- /dev/null +++ b/src/pages/currencies/currencyRatesView/index.tsx @@ -0,0 +1,137 @@ +// pages/CurrencyRateDetailPage.tsx + +import { useNavigate, useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Pencil, Trash2 } from 'lucide-react' +import { useState } from 'react' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Button } from '@/components/ui/button' +import { Section, InfoRow } from '@/components/viewPageComponents' +import { useGetCurrencyRateById, useDeleteCurrencyRate } from '@/features/currencyRates/hooks/useCurrencyRates' + +// ─── CurrencyRateDetailPage ─────────────────────────────────────────────────── + +export default function CurrencyRateDetailPage() { + const { id } = useParams<{ id: string }>() + const numericId = Number(id) + const { t } = useTranslation() + const navigate = useNavigate() + + const [deleteOpen, setDeleteOpen] = useState(false) + + const { data: rate, isLoading } = useGetCurrencyRateById(numericId) + const deleteMutation = useDeleteCurrencyRate() + + const handleDeleteConfirm = async () => { + await deleteMutation.mutateAsync(numericId) + navigate('/resources/currency-rates') + } + + // ─── Loading skeleton ────────────────────────────────────────────────────── + + if (isLoading) { + return ( +
+
+
+
+ ) + } + + if (!rate) { + return ( +
+

+ {t('currencyRates.notFound', 'Walýuta kursy tapylmady')} +

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

+ {t('currencyRates.detail.title', 'Walýuta kursy giňişleýin')}: {rate.id} +

+
+ + +
+
+ + {/* Detail Card */} +
+ + + + + + +
+ + {/* Delete Dialog */} + + + + + {t('currencyRates.deleteDialog.title', 'Pozmak isleýärsiňizmi?')} + + + {t( + 'currencyRates.deleteDialog.description', + 'Bu amal yzyna gaýtarylyp bilinmez. Walýuta kursy hemişelik pozular.' + )} + + + + {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/currencies/visaMasterSberSettings/index.tsx b/src/pages/currencies/visaMasterSberSettings/index.tsx new file mode 100644 index 0000000..e574986 --- /dev/null +++ b/src/pages/currencies/visaMasterSberSettings/index.tsx @@ -0,0 +1,204 @@ +// pages/VisaMasterSettingsPage.tsx + +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Pencil, Trash2 } from 'lucide-react' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Button } from '@/components/ui/button' +import { DataTable, type ColumnDef } from '@/components/dataTable' +import { DataTableToolbar } from '@/components/dataTableToolbar' +import { + useGetVisaMasterSettings, + useDeleteVisaMasterSetting, +} from '@/features/visaMasterSberSettings/hooks/useVisaMasterSettings' +import type { VisaMasterSetting } from '@/features/visaMasterSberSettings/api/visaMasterSberSettingsApi' + +// ─── Column defaults ────────────────────────────────────────────────────────── + +const DEFAULT_VISIBILITY = { id: true, kod: true, ady: true, yazgy: true } +const DEFAULT_ORDER = ['id', 'kod', 'ady', 'yazgy', 'actions'] + +// ─── VisaMasterSettingsPage ─────────────────────────────────────────────────── + +export default function VisaMasterSettingsPage() { + const { t } = useTranslation() + const navigate = useNavigate() + + const [page, setPage] = useState(1) + const [perPage] = useState(25) + const [search, setSearch] = useState('') + const [columnVisibility, setColumnVisibility] = useState>(DEFAULT_VISIBILITY) + const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER) + const [deleteId, setDeleteId] = useState(null) + + const { data, isLoading } = useGetVisaMasterSettings({ page, perPage, search }) + const deleteMutation = useDeleteVisaMasterSetting() + + const handleDeleteConfirm = async () => { + if (deleteId === null) return + await deleteMutation.mutateAsync(deleteId) + setDeleteId(null) + } + + const handleSearchChange = (val: string) => { + setSearch(val) + setPage(1) + } + + // ─── Columns ────────────────────────────────────────────────────────────── + + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + {row.original.id} + ), + size: 80, + }, + { + accessorKey: 'kod', + header: t('visaMasterSettings.columns.kod', 'KOD'), + cell: ({ row }) => ( + + {row.original.kod} + + ), + }, + { + accessorKey: 'ady', + header: t('visaMasterSettings.columns.ady', 'ADY'), + cell: ({ row }) => ( + {row.original.ady} + ), + }, + { + accessorKey: 'yazgy', + header: t('visaMasterSettings.columns.yazgy', 'YAZGY'), + cell: ({ row }) => ( + {row.original.yazgy} + ), + }, + { + id: 'actions', + header: '', + enableSorting: false, + enableHiding: false, + cell: ({ row }) => ( +
+ + +
+ ), + size: 100, + }, + ] + + const columnMeta = columns + .filter((c) => 'accessorKey' in c && c.accessorKey) + .map((c) => ({ + id: String(('accessorKey' in c ? c.accessorKey : c.id) ?? ''), + label: typeof c.header === 'string' ? c.header : String(('accessorKey' in c ? c.accessorKey : '') ?? ''), + })) + + // ─── Render ─────────────────────────────────────────────────────────────── + + return ( +
+ + +

+ {t('visaMasterSettings.title', 'Visa/Master, Sber sazlamalar')} +

+ + navigate('/visa-master-sber-settings/create')} + /> + + String(row.id)} + currentPage={page} + totalPages={data?.totalPages ?? 1} + totalCount={data?.total ?? 0} + onPageChange={setPage} + /> + + {/* Delete Confirmation */} + { if (!open) setDeleteId(null) }} + > + + + + {t('visaMasterSettings.deleteDialog.title', 'Pozmak isleýärsiňizmi?')} + + + {t( + 'visaMasterSettings.deleteDialog.description', + 'Bu amal yzyna gaýtarylyp bilinmez. Sazlama hemişelik pozular.' + )} + + + + {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/currencies/visaMasterSberSettingsCreate/index.tsx b/src/pages/currencies/visaMasterSberSettingsCreate/index.tsx new file mode 100644 index 0000000..cbc31de --- /dev/null +++ b/src/pages/currencies/visaMasterSberSettingsCreate/index.tsx @@ -0,0 +1,24 @@ +// pages/VisaMasterSettingCreatePage.tsx + +import { useTranslation } from 'react-i18next' +import { VisaMasterSettingForm } from '@/features/visaMasterSberSettings/components/visaMasterSberSettingsForm' + +// ─── VisaMasterSettingCreatePage ────────────────────────────────────────────── + +export default function VisaMasterSettingCreatePage() { + const { t } = useTranslation() + + return ( +
+ + +

+ {t('visaMasterSettings.actions.create', 'Visa/Master, Sber sazlamalar dörediň')} +

+ +
+ +
+
+ ) +} \ No newline at end of file diff --git a/src/pages/currencies/visaMasterSberSettingsEdit/index.tsx b/src/pages/currencies/visaMasterSberSettingsEdit/index.tsx new file mode 100644 index 0000000..fddd3c7 --- /dev/null +++ b/src/pages/currencies/visaMasterSberSettingsEdit/index.tsx @@ -0,0 +1,57 @@ +// pages/VisaMasterSettingEditPage.tsx + +import {useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { VisaMasterSettingForm } from '@/features/visaMasterSberSettings/components/visaMasterSberSettingsForm' +import { useGetVisaMasterSettingById } from '@/features/visaMasterSberSettings/hooks/useVisaMasterSettings' + +// ─── VisaMasterSettingEditPage ──────────────────────────────────────────────── + +export default function VisaMasterSettingEditPage() { + const { id } = useParams<{ id: string }>() + const numericId = Number(id) + const { t } = useTranslation() + + const { data: setting, isLoading } = useGetVisaMasterSettingById(numericId) + + // ─── Loading skeleton ────────────────────────────────────────────────────── + + if (isLoading) { + return ( +
+
+
+
+ ) + } + + if (!setting) { + return ( +
+

+ {t('visaMasterSettings.notFound', 'Sazlama tapylmady')} +

+
+ ) + } + + // ─── Render ─────────────────────────────────────────────────────────────── + + return ( +
+ + +

+ {t('visaMasterSettings.detail.editTitle', 'Sazlamany üýtgetmek')}: {setting.id} +

+ +
+ +
+
+ ) +} \ No newline at end of file diff --git a/src/pages/onlinePaymentsHistory/index.tsx b/src/pages/onlinePaymentsHistory/index.tsx new file mode 100644 index 0000000..5d5e282 --- /dev/null +++ b/src/pages/onlinePaymentsHistory/index.tsx @@ -0,0 +1,208 @@ +// pages/OnlinePaymentHistoryPage.tsx + +import { useState } from "react"; +import { useNavigate } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { Eye, Rss } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { DataTable, type ColumnDef } from "@/components/dataTable"; +import { DataTableToolbar } from "@/components/dataTableToolbar"; +import type { VisibilityState } from "@tanstack/react-table"; +import { + useGetOnlinePayments, + useTriggerPaymentCallback, +} from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory"; +import type { OnlinePayment } from "@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi"; +import { PaymentStatusBadge } from "../../features/onlinePaymentHistory/components/PaymentStatusBadge"; + +// ─── Defaults ───────────────────────────────────────────────────────────────── + +const DEFAULT_VISIBILITY = { + amount: true, + apiClient: true, + description: true, + status: true, + username: true, + createdAt: true, +}; +const DEFAULT_ORDER = [ + "amount", + "apiClient", + "description", + "status", + "username", + "createdAt", + "actions", +]; + +// ─── OnlinePaymentHistoryPage ───────────────────────────────────────────────── + +export default function OnlinePaymentHistoryPage() { + const { t } = useTranslation(); + const navigate = useNavigate(); + + const [page, setPage] = useState(1); + const [perPage] = useState(25); + const [search, setSearch] = useState(""); + const [columnVisibility, setColumnVisibility] = + useState(DEFAULT_VISIBILITY); + const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER); + + const { data, isLoading } = useGetOnlinePayments({ page, perPage, search }); + const callbackMutation = useTriggerPaymentCallback(); + + const handleSearchChange = (val: string) => { + setSearch(val); + setPage(1); + }; + + // ─── Columns ────────────────────────────────────────────────────────────── + + const columns: ColumnDef[] = [ + { + accessorKey: "amount", + header: t("onlinePayments.columns.amount", "MÖÇBERI"), + cell: ({ row }) => ( + + {row.original.amount} + + ), + size: 100, + }, + { + accessorKey: "apiClient", + header: t("onlinePayments.columns.apiClient", "API CLIENT"), + cell: ({ row }) => ( + + {row.original.apiClient} + + ), + }, + { + accessorKey: "description", + header: t("onlinePayments.columns.description", "DESC"), + cell: ({ row }) => ( + + {row.original.description} + + ), + size: 140, + }, + { + accessorKey: "status", + header: t("onlinePayments.columns.status", "STATUS"), + cell: ({ row }) => , + size: 140, + }, + { + accessorKey: "username", + header: t("onlinePayments.columns.username", "USERNAME"), + cell: ({ row }) => ( + + {row.original.username} + + ), + }, + { + accessorKey: "createdAt", + header: t("onlinePayments.columns.createdAt", "DÖREDILEN WAGTY"), + cell: ({ row }) => ( + + {formatDateTime(row.original.createdAt)} + + ), + size: 140, + }, + { + id: "actions", + header: "", + enableSorting: false, + enableHiding: false, + cell: ({ row }) => ( +
+ {/* Callback trigger */} + + {/* View detail */} + +
+ ), + size: 90, + }, + ]; + + const columnMeta = columns + .filter((c) => "accessorKey" in c && c.accessorKey) + .map((c) => ({ + id: String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""), + label: typeof c.header === "string" ? c.header : "", + })); + + // ─── Render ─────────────────────────────────────────────────────────────── + + return ( +
+

+ {t("onlinePayments.title", "Onlaýn töleg taryhy")} +

+ + + + String(row.id)} + currentPage={page} + totalPages={data?.totalPages ?? 1} + totalCount={data?.total ?? 0} + onPageChange={setPage} + /> +
+ ); +} + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +function formatDateTime(iso: string): string { + const d = new Date(iso); + const hh = String(d.getHours()).padStart(2, "0"); + const mm = String(d.getMinutes()).padStart(2, "0"); + const dd = String(d.getDate()).padStart(2, "0"); + const mo = String(d.getMonth() + 1).padStart(2, "0"); + const yy = d.getFullYear(); + return `${hh}:${mm}, ${dd}.${mo}.${yy}`; +} diff --git a/src/pages/onlinePaymentsHistory/onlinePaymenHistoryView.tsx b/src/pages/onlinePaymentsHistory/onlinePaymenHistoryView.tsx new file mode 100644 index 0000000..78eafe0 --- /dev/null +++ b/src/pages/onlinePaymentsHistory/onlinePaymenHistoryView.tsx @@ -0,0 +1,130 @@ +// pages/OnlinePaymentDetailPage.tsx + +import { useParams } from "react-router-dom"; +import { useTranslation } from "react-i18next"; +import { Section, InfoRow } from "@/components/viewPageComponents"; +import { useGetOnlinePaymentById } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory"; +import { PaymentStatusBadge } from "../../features/onlinePaymentHistory/components/PaymentStatusBadge"; + +// ─── OnlinePaymentDetailPage ────────────────────────────────────────────────── + +export default function OnlinePaymentDetailPage() { + const { id } = useParams<{ id: string }>(); + const numericId = Number(id); + const { t } = useTranslation(); + + const { data: payment, isLoading } = useGetOnlinePaymentById(numericId); + + // ─── Loading skeleton ────────────────────────────────────────────────────── + + if (isLoading) { + return ( +
+
+
+
+ ); + } + + if (!payment) { + return ( +
+

+ {t("onlinePayments.notFound", "Töleg tapylmady")} +

+
+ ); + } + + const title = `${t("onlinePayments.detail.title", "Onlaýn töleg taryhy giňişleýin")}: ${payment.orderId}`; + + // ─── Render ─────────────────────────────────────────────────────────────── + + return ( +
+

+ {title} +

+ + {/* Detail Card */} +
+ + + + + + + + + + + + + + + + + +
+
+ ); +} + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +function formatDateTime(iso: string): string { + const d = new Date(iso); + const hh = String(d.getHours()).padStart(2, "0"); + const mm = String(d.getMinutes()).padStart(2, "0"); + const dd = String(d.getDate()).padStart(2, "0"); + const mo = String(d.getMonth() + 1).padStart(2, "0"); + const yy = d.getFullYear(); + return `${hh}:${mm}, ${dd}.${mo}.${yy}`; +} diff --git a/src/pages/settings/users/createRole/index.tsx b/src/pages/settings/users/createRole/index.tsx new file mode 100644 index 0000000..5670892 --- /dev/null +++ b/src/pages/settings/users/createRole/index.tsx @@ -0,0 +1,15 @@ +import { useTranslation } from 'react-i18next' +import { RoleForm } from '@/features/roles/components/roleForm' + +export default function RoleCreatePage() { + const { t } = useTranslation() + + return ( +
+

+ {t('roles.actions.create', 'Rol dörediň')} +

+ +
+ ) +} \ No newline at end of file diff --git a/src/pages/settings/users/editRole/index.tsx b/src/pages/settings/users/editRole/index.tsx new file mode 100644 index 0000000..0697ddd --- /dev/null +++ b/src/pages/settings/users/editRole/index.tsx @@ -0,0 +1,46 @@ +import { useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { RoleForm } from '@/features/roles/components/roleForm' +import { useRole } from '@/features/roles/hooks/useRoles' +import { Skeleton } from '@/components/ui/skeleton' + +export default function RoleEditPage() { + const { t } = useTranslation() + const { id } = useParams<{ id: string }>() + const roleId = Number(id) + + const { data: role, isLoading, isError } = useRole(roleId) + + if (isLoading) { + return ( +
+ +
+ {Array.from({ length: 3 }).map((_, i) => ( +
+ + +
+ ))} +
+
+ ) + } + + if (isError || !role) { + return ( +

+ {t('common.fetchError', 'Maglumat ýüklenmedi.')} +

+ ) + } + + return ( +
+

+ {t('roles.editTitle', 'Rol üýtget')}: {role.name?.tk} +

+ +
+ ) +} \ No newline at end of file diff --git a/src/pages/settings/users/permissions/index.tsx b/src/pages/settings/users/permissions/index.tsx new file mode 100644 index 0000000..7a1263f --- /dev/null +++ b/src/pages/settings/users/permissions/index.tsx @@ -0,0 +1,194 @@ +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Eye, Pencil, Trash2 } from 'lucide-react' +import type { ColumnDef, VisibilityState } from '@tanstack/react-table' +import { DataTable } from '@/components/dataTable' +import { DataTableToolbar } from '@/components/dataTableToolbar' +import { Button } from '@/components/ui/button' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { usePermissions, useDeletePermission } from '@/features/permissions/hooks/usePermissions' +import type { Permission } from '@/features/permissions/api/permissionsApi' + +// ─── Column meta for toolbar ────────────────────────────────────────────────── + +const COLUMN_META = [ + { id: 'id', label: 'ID' }, + { id: 'code', label: 'Kod' }, + { id: 'name', label: 'Ady' }, + { id: 'guard_name', label: 'Guard name' }, +] + +// ─── PermissionsPage ────────────────────────────────────────────────────────── + +export default function PermissionsPage() { + const { t } = useTranslation() + const navigate = useNavigate() + + // ── State ────────────────────────────────────────────────────────────────── + const [search, setSearch] = useState('') + const [page, setPage] = useState(1) + const [perPage, setPerPage] = useState(25) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([]) + const [deleteId, setDeleteId] = useState(null) + + // ── Data ─────────────────────────────────────────────────────────────────── + const { data, isLoading } = usePermissions({ search, page, per_page: perPage }) + const deletePermission = useDeletePermission() + + // ── Columns ──────────────────────────────────────────────────────────────── + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + size: 70, + cell: ({ row }) => ( + {row.original.id} + ), + }, + { + accessorKey: 'code', + header: t('permissions.fields.code', 'Kod'), + }, + { + accessorKey: 'name', + header: t('permissions.fields.name', 'Ady'), + cell: ({ row }) => {row.original.name?.tk ?? '—'}, + }, + { + accessorKey: 'guard_name', + header: 'Guard name', + }, + { + id: 'actions', + header: '', + size: 120, + enableSorting: false, + enableHiding: false, + cell: ({ row }) => ( +
+ + + +
+ ), + }, + ] + + // ── Handlers ─────────────────────────────────────────────────────────────── + const handleConfirmDelete = () => { + if (deleteId === null) return + deletePermission.mutate(deleteId, { + onSuccess: () => setDeleteId(null), + onError: () => setDeleteId(null), + }) + } + + // ── Render ───────────────────────────────────────────────────────────────── + return ( +
+ {/* Page heading */} +
+

+ {t('permissions.title', 'Rugsatlar')} +

+ +
+ + {/* Toolbar */} + { setSearch(v); setPage(1) }} + searchPlaceholder={t('permissions.searchPlaceholder', 'Gözlemek...')} + columns={COLUMN_META} + columnVisibility={columnVisibility} + onColumnVisibilityChange={setColumnVisibility} + columnOrder={columnOrder} + onColumnOrderChange={setColumnOrder} + perPageOptions={[10, 25, 50, 100]} + perPage={perPage} + onPerPageChange={(v) => { setPerPage(v); setPage(1) }} + /> + + {/* Table */} + String(row.id)} + currentPage={data?.meta?.current_page ?? 1} + totalPages={data?.meta?.last_page ?? 1} + totalCount={data?.meta?.total ?? 0} + onPageChange={setPage} + /> + + {/* Delete confirmation dialog */} + { if (!open) setDeleteId(null) }} + > + + + + {t('permissions.deleteDialog.title', 'Rugsaty pozmak')} + + + {t( + 'permissions.deleteDialog.description', + 'Bu rugsaty pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.', + )} + + + + {t('common.cancel', 'Ýatyr')} + + {deletePermission.isPending + ? t('common.deleting', 'Pozulýar...') + : t('common.delete', 'Poz')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/settings/users/permissionsCreate/index.tsx b/src/pages/settings/users/permissionsCreate/index.tsx new file mode 100644 index 0000000..e7b80e4 --- /dev/null +++ b/src/pages/settings/users/permissionsCreate/index.tsx @@ -0,0 +1,15 @@ +import { useTranslation } from 'react-i18next' +import { PermissionForm } from '@/features/permissions/components/permissionsForm' + +export default function PermissionCreatePage() { + const { t } = useTranslation() + + return ( +
+

+ {t('permissions.actions.create', 'Rugsat dörediň')} +

+ +
+ ) +} \ No newline at end of file diff --git a/src/pages/settings/users/permissionsEdit/index.tsx b/src/pages/settings/users/permissionsEdit/index.tsx new file mode 100644 index 0000000..63d4f7f --- /dev/null +++ b/src/pages/settings/users/permissionsEdit/index.tsx @@ -0,0 +1,46 @@ +import { useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { PermissionForm } from '@/features/permissions/components/permissionsForm' +import { usePermission } from '@/features/permissions/hooks/usePermissions' +import { Skeleton } from '@/components/ui/skeleton' + +export default function PermissionEditPage() { + const { t } = useTranslation() + const { id } = useParams<{ id: string }>() + const permissionId = Number(id) + + const { data: permission, isLoading, isError } = usePermission(permissionId) + + if (isLoading) { + return ( +
+ +
+ {Array.from({ length: 3 }).map((_, i) => ( +
+ + +
+ ))} +
+
+ ) + } + + if (isError || !permission) { + return ( +

+ {t('common.fetchError', 'Maglumat ýüklenmedi.')} +

+ ) + } + + return ( +
+

+ {t('permissions.editTitle', 'Rugsaty üýtget')}: {permission.name?.tk} +

+ +
+ ) +} \ No newline at end of file diff --git a/src/pages/settings/users/permissionsView/index.tsx b/src/pages/settings/users/permissionsView/index.tsx new file mode 100644 index 0000000..d9be990 --- /dev/null +++ b/src/pages/settings/users/permissionsView/index.tsx @@ -0,0 +1,181 @@ +import { useState } from 'react' +import { useParams, useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Pencil, Trash2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Skeleton } from '@/components/ui/skeleton' +import { Section, InfoRow } from '@/components/viewPageComponents' +import { usePermission, useDeletePermission } from '@/features/permissions/hooks/usePermissions' + +// ─── LangTabs ───────────────────────────────────────────────────────────────── + +type LangKey = 'tk' | 'ru' | 'en' + +const LANG_TABS: { key: LangKey; label: string }[] = [ + { key: 'tk', label: 'Türkmen' }, + { key: 'ru', label: 'Русский' }, + { key: 'en', label: 'English' }, +] + +function LangTabs({ + active, + onChange, +}: { + active: LangKey + onChange: (l: LangKey) => void +}) { + return ( +
+ {LANG_TABS.map((tab) => ( + + ))} +
+ ) +} + +// ─── PermissionViewPage ─────────────────────────────────────────────────────── + +export default function PermissionViewPage() { + const { t } = useTranslation() + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const permissionId = Number(id) + + const [activeLang, setActiveLang] = useState('tk') + const [showDelete, setShowDelete] = useState(false) + + const { data: permission, isLoading, isError } = usePermission(permissionId) + const deletePermission = useDeletePermission() + + const handleConfirmDelete = () => { + deletePermission.mutate(permissionId, { + onSuccess: () => navigate('/settings/users/permissions'), + onError: () => setShowDelete(false), + }) + } + + // ── Loading skeleton ─────────────────────────────────────────────────────── + if (isLoading) { + return ( +
+ +
+ {Array.from({ length: 4 }).map((_, i) => ( +
+ + +
+ ))} +
+
+ ) + } + + if (isError || !permission) { + return ( +

+ {t('common.fetchError', 'Maglumat ýüklenmedi.')} +

+ ) + } + + // ── Render ───────────────────────────────────────────────────────────────── + return ( +
+ {/* Page heading + actions */} +
+

+ {t('permissions.viewTitle', 'Rugsat giňişleýin')}: {permission.name?.tk} +

+
+ + +
+
+ + {/* Detail section */} +
+ + + + {/* Name row — with lang switcher */} +
+ + {t('permissions.fields.name', 'Ady')} + +
+ + + {permission.name?.[activeLang] || '—'} + +
+
+ + +
+ + {/* Delete dialog */} + + + + + {t('permissions.deleteDialog.title', 'Rugsaty pozmak')} + + + {t( + 'permissions.deleteDialog.description', + 'Bu rugsaty pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.', + )} + + + + {t('common.cancel', 'Ýatyr')} + + {deletePermission.isPending + ? t('common.deleting', 'Pozulýar...') + : t('common.delete', 'Poz')} + + + + +
+ ) +} diff --git a/src/pages/settings/users/roles/index.tsx b/src/pages/settings/users/roles/index.tsx new file mode 100644 index 0000000..198daa4 --- /dev/null +++ b/src/pages/settings/users/roles/index.tsx @@ -0,0 +1,194 @@ +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Eye, Pencil, Trash2 } from 'lucide-react' +import type { ColumnDef, VisibilityState } from '@tanstack/react-table' +import { DataTable } from '@/components/dataTable' +import { DataTableToolbar } from '@/components/dataTableToolbar' +import { Button } from '@/components/ui/button' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { useRoles, useDeleteRole } from '@/features/roles/hooks/useRoles' +import type { Role } from '@/features/roles/api/rolesApi' + +// ─── Column meta for toolbar ────────────────────────────────────────────────── + +const COLUMN_META = [ + { id: 'id', label: 'ID' }, + { id: 'code', label: 'Kod' }, + { id: 'name', label: 'Ady' }, + { id: 'guard_name', label: 'Guard name' }, +] + +// ─── RolesPage ──────────────────────────────────────────────────────────────── + +export default function RolesPage() { + const { t } = useTranslation() + const navigate = useNavigate() + + // ── State ────────────────────────────────────────────────────────────────── + const [search, setSearch] = useState('') + const [page, setPage] = useState(1) + const [perPage, setPerPage] = useState(25) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([]) + const [deleteId, setDeleteId] = useState(null) + + // ── Data ─────────────────────────────────────────────────────────────────── + const { data, isLoading } = useRoles({ search, page, per_page: perPage }) + const deleteRole = useDeleteRole() + + // ── Columns ──────────────────────────────────────────────────────────────── + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + size: 70, + cell: ({ row }) => ( + {row.original.id} + ), + }, + { + accessorKey: 'code', + header: t('roles.fields.code', 'Kod'), + }, + { + accessorKey: 'name', + header: t('roles.fields.name', 'Ady'), + cell: ({ row }) => {row.original.name?.tk ?? '—'}, + }, + { + accessorKey: 'guard_name', + header: 'Guard name', + }, + { + id: 'actions', + header: '', + size: 120, + enableSorting: false, + enableHiding: false, + cell: ({ row }) => ( +
+ + + +
+ ), + }, + ] + + // ── Handlers ─────────────────────────────────────────────────────────────── + const handleConfirmDelete = () => { + if (deleteId === null) return + deleteRole.mutate(deleteId, { + onSuccess: () => setDeleteId(null), + onError: () => setDeleteId(null), + }) + } + + // ── Render ───────────────────────────────────────────────────────────────── + return ( +
+ {/* Page heading */} +
+

+ {t('roles.title', 'Rollar')} +

+ +
+ + {/* Toolbar */} + { setSearch(v); setPage(1) }} + searchPlaceholder={t('roles.searchPlaceholder', 'Gözlemek...')} + columns={COLUMN_META} + columnVisibility={columnVisibility} + onColumnVisibilityChange={setColumnVisibility} + columnOrder={columnOrder} + onColumnOrderChange={setColumnOrder} + perPageOptions={[10, 25, 50, 100]} + perPage={perPage} + onPerPageChange={(v) => { setPerPage(v); setPage(1) }} + /> + + {/* Table */} + String(row.id)} + currentPage={data?.meta?.current_page ?? 1} + totalPages={data?.meta?.last_page ?? 1} + totalCount={data?.meta?.total ?? 0} + onPageChange={setPage} + /> + + {/* Delete confirmation dialog */} + { if (!open) setDeleteId(null) }} + > + + + + {t('roles.deleteDialog.title', 'Roly pozmak')} + + + {t( + 'roles.deleteDialog.description', + 'Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.', + )} + + + + {t('common.cancel', 'Ýatyr')} + + {deleteRole.isPending + ? t('common.deleting', 'Pozulýar...') + : t('common.delete', 'Poz')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/settings/users/rolesView/index.tsx b/src/pages/settings/users/rolesView/index.tsx new file mode 100644 index 0000000..77b74d9 --- /dev/null +++ b/src/pages/settings/users/rolesView/index.tsx @@ -0,0 +1,181 @@ +import { useState } from 'react' +import { useParams, useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Pencil, Trash2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Skeleton } from '@/components/ui/skeleton' +import { Section, InfoRow } from '@/components/viewPageComponents' +import { useRole, useDeleteRole } from '@/features/roles/hooks/useRoles' + +// ─── LangTabs ───────────────────────────────────────────────────────────────── + +type LangKey = 'tk' | 'ru' | 'en' + +const LANG_TABS: { key: LangKey; label: string }[] = [ + { key: 'tk', label: 'Türkmen' }, + { key: 'ru', label: 'Русский' }, + { key: 'en', label: 'English' }, +] + +function LangTabs({ + active, + onChange, +}: { + active: LangKey + onChange: (l: LangKey) => void +}) { + return ( +
+ {LANG_TABS.map((tab) => ( + + ))} +
+ ) +} + +// ─── RoleViewPage ───────────────────────────────────────────────────────────── + +export default function RoleViewPage() { + const { t } = useTranslation() + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const roleId = Number(id) + + const [activeLang, setActiveLang] = useState('tk') + const [showDelete, setShowDelete] = useState(false) + + const { data: role, isLoading, isError } = useRole(roleId) + const deleteRole = useDeleteRole() + + const handleConfirmDelete = () => { + deleteRole.mutate(roleId, { + onSuccess: () => navigate('/settings/users/roles'), + onError: () => setShowDelete(false), + }) + } + + // ── Loading skeleton ─────────────────────────────────────────────────────── + if (isLoading) { + return ( +
+ +
+ {Array.from({ length: 4 }).map((_, i) => ( +
+ + +
+ ))} +
+
+ ) + } + + if (isError || !role) { + return ( +

+ {t('common.fetchError', 'Maglumat ýüklenmedi.')} +

+ ) + } + + // ── Render ───────────────────────────────────────────────────────────────── + return ( +
+ {/* Page heading + actions */} +
+

+ {t('roles.viewTitle', 'Rol giňişleýin')}: {role.name?.tk} +

+
+ + +
+
+ + {/* Detail section */} +
+ + + + {/* Name row — with lang switcher */} +
+ + {t('roles.fields.name', 'Ady')} + +
+ + + {role.name?.[activeLang] || '—'} + +
+
+ + +
+ + {/* Delete dialog */} + + + + + {t('roles.deleteDialog.title', 'Roly pozmak')} + + + {t( + 'roles.deleteDialog.description', + 'Bu roly pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylmaz.', + )} + + + + {t('common.cancel', 'Ýatyr')} + + {deleteRole.isPending + ? t('common.deleting', 'Pozulýar...') + : t('common.delete', 'Poz')} + + + + +
+ ) +} \ No newline at end of file diff --git a/src/pages/users/allUsersCreate/index.tsx b/src/pages/users/allUsersCreate/index.tsx index 72144a6..785e312 100644 --- a/src/pages/users/allUsersCreate/index.tsx +++ b/src/pages/users/allUsersCreate/index.tsx @@ -1,37 +1,14 @@ import { useTranslation } from 'react-i18next' -import { useNavigate } from 'react-router-dom' -import { ChevronRight } from 'lucide-react' import { UserForm } from '@/features/allUsers/components/allUsersForm' // ─── UserCreatePage ─────────────────────────────────────────────────────────── export default function UserCreatePage() { const { t } = useTranslation() - const navigate = useNavigate() return (
- {/* Breadcrumb */} - - + {/* Title */}

{t('users.actions.create', 'Ulanyjy dörediň')}