Compare commits
45
Commits
0ca218505d
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
015cea9323 | ||
|
|
ae68d705b3 | ||
|
|
7a8c877ca3 | ||
|
|
5fd800d506 | ||
|
|
c3cf23a192 | ||
|
|
524733ad9f | ||
|
|
11903e23bf | ||
|
|
879ed77121 | ||
|
|
cbfb467651 | ||
|
|
6e626482f6 | ||
|
|
cbd17608c1 | ||
|
|
1ebc133d1c | ||
|
|
1c0cbf1023 | ||
|
|
9930a16f5c | ||
|
|
4c4d037a1e | ||
|
|
8dc61d7786 | ||
|
|
9e2a2606c9 | ||
|
|
6ccda86eff | ||
|
|
cc3c718861 | ||
|
|
61a0995ea4 | ||
|
|
18e7c03e76 | ||
|
|
03779995ba | ||
|
|
2effb45d01 | ||
|
|
edf503e329 | ||
|
|
34e8fef9b6 | ||
|
|
d326361a03 | ||
|
|
5ed4c9a8ec | ||
|
|
25c104ad8c | ||
|
|
7445e09d5f | ||
|
|
cc5b5fca24 | ||
|
|
9ad86634dd | ||
|
|
5884ec831c | ||
|
|
d8e903f24c | ||
|
|
7dfac2bd59 | ||
|
|
1a7dd954e2 | ||
|
|
62b6489abf | ||
|
|
f293806d96 | ||
|
|
f00d2abcac | ||
|
|
d230b12d6a | ||
|
|
98bb2f780e | ||
|
|
73142c1fcf | ||
|
|
7bb37f9b43 | ||
|
|
0e75c85fe1 | ||
|
|
5073166931 | ||
|
|
6da59f42d9 |
No files matched your search
@@ -1,2 +1,13 @@
|
|||||||
|
VITE_API_BASE_URL=https://test.webulgam.com/online-backend/api/admin
|
||||||
VITE_API_URL=/api
|
VITE_API_URL=/api
|
||||||
VITE_ENABLE_MOCKS=true
|
VITE_ENABLE_MOCKS=false
|
||||||
|
server_user = 'ubuntu'
|
||||||
|
server_ip = '216.250.10.141'
|
||||||
|
server_password = 'TazePassword'
|
||||||
|
|
||||||
|
|
||||||
|
# Public path the app is served under (router basename follows it)
|
||||||
|
VITE_BASE_PATH=/online/
|
||||||
|
# Dev server: backend origin for the /api proxy, and allowed hosts (comma-separated)
|
||||||
|
VITE_PROXY_TARGET=https://test.webulgam.com/online-backend
|
||||||
|
VITE_ALLOWED_HOSTS=test.webulgam.com
|
||||||
+2
-1
@@ -1,5 +1,5 @@
|
|||||||
# Logs
|
# Logs
|
||||||
logs
|
/logs
|
||||||
*.log
|
*.log
|
||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
yarn-debug.log*
|
yarn-debug.log*
|
||||||
@@ -15,6 +15,7 @@ dist-ssr
|
|||||||
# Editor directories and files
|
# Editor directories and files
|
||||||
.vscode/*
|
.vscode/*
|
||||||
!.vscode/extensions.json
|
!.vscode/extensions.json
|
||||||
|
!.env.example
|
||||||
.idea
|
.idea
|
||||||
.DS_Store
|
.DS_Store
|
||||||
*.suo
|
*.suo
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// ╔════════════════════════════════════════════════════════════════════╗
|
||||||
|
// ║ ║
|
||||||
|
// ║ ## ## ######## ## ## ######### ### #### ║
|
||||||
|
// ║ ## ## ## ## ### ### ## ## ## ## ## ║
|
||||||
|
// ║ ## ## ## ## #### #### ## ## ## ## ## ║
|
||||||
|
// ║ ##### ## ## ## ### ## ######### ## ## ## ║
|
||||||
|
// ║ ## ## ## ## ## ## ## ## ######### ## ║
|
||||||
|
// ║ ## ## ## ## ## ## ## ## ## ## ## ║
|
||||||
|
// ║ ## ## ######## ## ## ######### ## ## #### ║
|
||||||
|
// ║ ║
|
||||||
|
// ║ Generated by Kombai - the AI design engineer ║
|
||||||
|
// ║ Install Kombai extension on your IDE to view this canvas, ║
|
||||||
|
// ║ with the design file(s). ║
|
||||||
|
// ║ https://kombai.com/install/ ║
|
||||||
|
// ║ ║
|
||||||
|
// ╚════════════════════════════════════════════════════════════════════╝
|
||||||
|
{
|
||||||
|
"created": "2026-10-23T16:02:57.188Z",
|
||||||
|
"modified": "2026-10-23T16:07:45.211Z",
|
||||||
|
"canvas": {
|
||||||
|
"viewport": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"zoom": 1
|
||||||
|
},
|
||||||
|
"selected": []
|
||||||
|
},
|
||||||
|
"nodes": {
|
||||||
|
"var_f7c0491a62d9": {
|
||||||
|
"type": "variant",
|
||||||
|
"label": "A · Ters Yüzey — tonal paneller, koyu teal çapa şeridi",
|
||||||
|
"parentId": null,
|
||||||
|
"themeId": null,
|
||||||
|
"rect": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"w": 1280,
|
||||||
|
"h": 0
|
||||||
|
},
|
||||||
|
"html": "<style>\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n @import url('https://cdn.jsdelivr.net/npm/lucide-static@1.48.0/font/lucide.css');\n</style>\n<div class=\"min-h-screen bg-[#f9fbfb] text-[#12211f] antialiased\" data-kid=\"1\" data-name=\"page background container\" style=\"font-family:'Inter',sans-serif\">\n<div class=\"mx-auto w-full max-w-[1200px] px-8 py-8\" data-kid=\"1-1\" data-name=\"main content layout container\">\n<!-- Header -->\n<div class=\"flex items-end justify-between gap-6\" data-kid=\"1-1-1\" data-name=\"page header row\">\n<div data-kid=\"1-1-1-1\" data-name=\"page title group\">\n<h1 class=\"text-[26px] font-semibold leading-none tracking-[-0.02em]\" data-kid=\"1-1-1-1-1\" data-name=\"page headline\">Baş sahypa</h1>\n<p class=\"mt-2 text-[13px] text-[#5c6f6d]\" data-kid=\"1-1-1-1-2\" data-name=\"page subtitle description\">Ähli amallaryň gysgaça görünüşi</p>\n</div>\n<div class=\"flex items-center gap-2\" data-kid=\"1-1-1-2\" data-name=\"header action buttons container\">\n<button class=\"flex h-9 items-center gap-2 rounded-[6px] border border-[#e2e9e9] bg-[#f2f6f6] px-3 text-[13px] text-[#12211f]\" data-kid=\"1-1-1-2-1\" data-name=\"year filter dropdown button\">\n<span class=\"tabular-nums\" data-kid=\"1-1-1-2-1-1\" data-name=\"selected year value\">2026</span>\n<span class=\"text-[11px] text-[#7b8d8b]\" data-kid=\"1-1-1-2-1-2\" data-name=\"year unit label\">ýyl</span>\n<i class=\"icon-chevron-down text-[13px] text-[#7b8d8b]\" data-kid=\"1-1-1-2-1-3\" data-name=\"dropdown chevron down icon\"></i>\n</button>\n<button class=\"flex h-9 w-9 items-center justify-center rounded-[6px] border border-[#e2e9e9] text-[#3d514f]\" data-kid=\"1-1-1-2-2\" data-name=\"refresh data button\">\n<i class=\"icon-refresh-cw text-[15px]\" data-kid=\"1-1-1-2-2-1\" data-name=\"refresh reload icon\"></i>\n</button>\n</div>\n</div>\n<!-- KPI register: one tonal panel, hairline column rules -->\n<div class=\"mt-7 overflow-hidden rounded-[10px] border border-[#e2e9e9] bg-[#f2f6f6]\" data-kid=\"1-1-2\" data-name=\"KPI metric panel\">\n<div class=\"grid grid-cols-4 divide-x divide-[#e2e9e9]\" data-kid=\"1-1-2-1\" data-name=\"KPI metric grid\">\n<div class=\"px-6 py-5\" data-kid=\"1-1-2-1-1\" data-name=\"KPI card: loan orders\">\n<div class=\"flex items-start justify-between\" data-kid=\"1-1-2-1-1-1\" data-name=\"KPI label and icon row\">\n<p class=\"text-[12px] font-medium text-[#5c6f6d]\" data-kid=\"1-1-2-1-1-1-1\" data-name=\"KPI metric label\">Karz sargytlary</p>\n<i class=\"icon-file-text text-[15px] text-[#8a9c9a]\" data-kid=\"1-1-2-1-1-1-2\" data-name=\"document file icon\"></i>\n</div>\n<p class=\"mt-3 text-[30px] font-semibold leading-none tracking-[-0.02em] tabular-nums\" data-kid=\"1-1-2-1-1-2\" data-name=\"KPI metric value\">12,480</p>\n<p class=\"mt-2.5 flex items-center gap-1 text-[11.5px] font-medium text-[#0e8577]\" data-kid=\"1-1-2-1-1-3\" data-name=\"KPI trend indicator row\">\n<i class=\"icon-arrow-up-right text-[12px]\" data-kid=\"1-1-2-1-1-3-1\" data-name=\"upward trend arrow icon\"></i>8,4%\n <span class=\"font-normal text-[#7b8d8b]\" data-kid=\"1-1-2-1-1-3-2\" data-name=\"trend comparison caption\">geçen aýa garanyňda</span>\n</p>\n</div>\n<div class=\"px-6 py-5\" data-kid=\"1-1-2-1-2\" data-name=\"KPI card: active cards\">\n<div class=\"flex items-start justify-between\" data-kid=\"1-1-2-1-2-1\" data-name=\"KPI label and icon row\">\n<p class=\"text-[12px] font-medium text-[#5c6f6d]\" data-kid=\"1-1-2-1-2-1-1\" data-name=\"KPI metric label\">Işjeň kartlar</p>\n<i class=\"icon-credit-card text-[15px] text-[#8a9c9a]\" data-kid=\"1-1-2-1-2-1-2\" data-name=\"credit card icon\"></i>\n</div>\n<p class=\"mt-3 text-[30px] font-semibold leading-none tracking-[-0.02em] tabular-nums\" data-kid=\"1-1-2-1-2-2\" data-name=\"KPI metric value\">8,205</p>\n<p class=\"mt-2.5 flex items-center gap-1 text-[11.5px] font-medium text-[#0e8577]\" data-kid=\"1-1-2-1-2-3\" data-name=\"KPI trend indicator row\">\n<i class=\"icon-arrow-up-right text-[12px]\" data-kid=\"1-1-2-1-2-3-1\" data-name=\"upward trend arrow icon\"></i>3,1%\n <span class=\"font-normal text-[#7b8d8b]\" data-kid=\"1-1-2-1-2-3-2\" data-name=\"trend comparison caption\">geçen aýa garanyňda</span>\n</p>\n</div>\n<div class=\"px-6 py-5\" data-kid=\"1-1-2-1-3\" data-name=\"KPI card: active customers\">\n<div class=\"flex items-start justify-between\" data-kid=\"1-1-2-1-3-1\" data-name=\"KPI label and icon row\">\n<p class=\"text-[12px] font-medium text-[#5c6f6d]\" data-kid=\"1-1-2-1-3-1-1\" data-name=\"KPI metric label\">Işjeň müşderiler</p>\n<i class=\"icon-users text-[15px] text-[#8a9c9a]\" data-kid=\"1-1-2-1-3-1-2\" data-name=\"users group icon\"></i>\n</div>\n<p class=\"mt-3 text-[30px] font-semibold leading-none tracking-[-0.02em] tabular-nums\" data-kid=\"1-1-2-1-3-2\" data-name=\"KPI metric value\">34,912</p>\n<p class=\"mt-2.5 flLine truncated
|
||||||
|
"comments": [],
|
||||||
|
"created": "2026-10-23T16:02:57.731819+00:00",
|
||||||
|
"modified": "2026-10-23T16:05:23.536557+00:00",
|
||||||
|
"id": "var_f7c0491a62d9",
|
||||||
|
"contentHeight": 1634
|
||||||
|
},
|
||||||
|
"var_ee5e76ea0954": {
|
||||||
|
"type": "variant",
|
||||||
|
"label": "B · Tek Defter — kart yok, sıcak kağıt, hairline kurallar",
|
||||||
|
"parentId": null,
|
||||||
|
"themeId": null,
|
||||||
|
"rect": {
|
||||||
|
"x": 2760,
|
||||||
|
"y": 0,
|
||||||
|
"w": 1280,
|
||||||
|
"h": 0
|
||||||
|
},
|
||||||
|
"html": "<style>\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n @import url('https://cdn.jsdelivr.net/npm/lucide-static@1.48.0/font/lucide.css');\n</style>\n<div class=\"min-h-screen bg-[#f4efe7] text-[#33302c] antialiased\" data-kid=\"1\" data-name=\"page background container\" style=\"font-family:'Inter',sans-serif\">\n<div class=\"mx-auto w-full max-w-[1160px] px-10 py-9\" data-kid=\"1-1\" data-name=\"main content wrapper\">\n<!-- Header -->\n<div class=\"flex items-end justify-between gap-6 pb-6\" data-kid=\"1-1-1\" data-name=\"page header row\">\n<div data-kid=\"1-1-1-1\" data-name=\"header title group\">\n<h1 class=\"text-[27px] font-semibold leading-none tracking-[-0.02em]\" data-kid=\"1-1-1-1-1\" data-name=\"dashboard page title\">Baş sahypa</h1>\n<p class=\"mt-2 text-[13px] text-[#7d7568]\" data-kid=\"1-1-1-1-2\" data-name=\"page subtitle description\">Ähli amallaryň gysgaça görünüşi</p>\n</div>\n<div class=\"flex items-center gap-2\" data-kid=\"1-1-1-2\" data-name=\"header action controls\">\n<button class=\"flex h-9 items-center gap-2 rounded-full border border-[#ded5c6] bg-[#fbf8f2] px-4 text-[13px]\" data-kid=\"1-1-1-2-1\" data-name=\"year selector button\">\n<span class=\"tabular-nums\" data-kid=\"1-1-1-2-1-1\" data-name=\"selected year value\">2026</span>\n<span class=\"text-[11px] text-[#93917f]\" data-kid=\"1-1-1-2-1-2\" data-name=\"year unit label\">ýyl</span>\n<i class=\"icon-chevron-down text-[13px] text-[#93917f]\" data-kid=\"1-1-1-2-1-3\" data-name=\"dropdown chevron icon\"></i>\n</button>\n<button class=\"flex h-9 w-9 items-center justify-center rounded-full border border-[#ded5c6] bg-[#fbf8f2] text-[#6b6455]\" data-kid=\"1-1-1-2-2\" data-name=\"refresh data button\">\n<i class=\"icon-refresh-cw text-[14px]\" data-kid=\"1-1-1-2-2-1\" data-name=\"refresh reload icon\"></i>\n</button>\n</div>\n</div>\n<div class=\"border-t border-[#ded5c6]\" data-kid=\"1-1-2\" data-name=\"header divider line\"></div>\n<!-- KPI register on the sheet -->\n<div class=\"grid grid-cols-4 divide-x divide-[#ded5c6]\" data-kid=\"1-1-3\" data-name=\"KPI metrics grid\">\n<div class=\"py-6 pr-6\" data-kid=\"1-1-3-1\" data-name=\"loan orders KPI card\">\n<div class=\"flex items-center justify-between\" data-kid=\"1-1-3-1-1\" data-name=\"KPI card header row\">\n<p class=\"text-[12px] text-[#7d7568]\" data-kid=\"1-1-3-1-1-1\" data-name=\"KPI label text\">Karz sargytlary</p>\n<span class=\"flex h-7 w-7 items-center justify-center rounded-full bg-[#eae1d1] text-[#6f6657]\" data-kid=\"1-1-3-1-1-2\" data-name=\"KPI icon badge\">\n<i class=\"icon-file-text text-[13px]\" data-kid=\"1-1-3-1-1-2-1\" data-name=\"file document icon\"></i>\n</span>\n</div>\n<p class=\"mt-3 text-[31px] font-semibold leading-none tracking-[-0.025em] tabular-nums\" data-kid=\"1-1-3-1-2\" data-name=\"KPI main value\">12,480</p>\n<p class=\"mt-2.5 text-[11.5px]\" data-kid=\"1-1-3-1-3\" data-name=\"KPI trend row\"><span class=\"inline-flex items-center gap-1 font-medium text-[#2f6f63]\" data-kid=\"1-1-3-1-3-1\" data-name=\"trend percentage value\"><i class=\"icon-arrow-up-right text-[12px]\" data-kid=\"1-1-3-1-3-1-1\" data-name=\"upward trend arrow icon\"></i>8,4%</span><span class=\"text-[#8b8377]\" data-kid=\"1-1-3-1-3-2\" data-name=\"trend comparison caption\"> geçen aýa garanyňda</span></p>\n</div>\n<div class=\"px-6 py-6\" data-kid=\"1-1-3-2\" data-name=\"active cards KPI card\">\n<div class=\"flex items-center justify-between\" data-kid=\"1-1-3-2-1\" data-name=\"KPI card header row\">\n<p class=\"text-[12px] text-[#7d7568]\" data-kid=\"1-1-3-2-1-1\" data-name=\"KPI label text\">Işjeň kartlar</p>\n<span class=\"flex h-7 w-7 items-center justify-center rounded-full bg-[#eae1d1] text-[#6f6657]\" data-kid=\"1-1-3-2-1-2\" data-name=\"KPI icon badge\">\n<i class=\"icon-credit-card text-[13px]\" data-kid=\"1-1-3-2-1-2-1\" data-name=\"credit card icon\"></i>\n</span>\n</div>\n<p class=\"mt-3 text-[31px] font-semibold leading-none tracking-[-0.025em] tabular-nums\" data-kid=\"1-1-3-2-2\" data-name=\"KPI main value\">8,205</p>\n<p class=\"mt-2.5 text-[11.5px]\" data-kid=\"1-1-3-2-3\" data-name=\"KPI trend row\"><span class=\"inline-flex items-center gap-1 font-medium text-[#2f6f63]\" data-kid=\"1-1-3-2-3-1\" data-name=\"trend percentage value\"><i class=\"icon-arrow-up-right text-[12px]\" data-kid=\"1-1-3-2-3-1-1\" data-name=\"upward trend arrow icon\"></i>3,1%</span><span class=\"text-[#8b8377]\" data-kid=\"1-1-3-2-3-2\" data-name=\"trend comparison caption\"> geçen aýa garanyňda</span></p>\n</div>\n<div class=\"px-6 py-6\" data-kid=\"1-1-3-3\" data-name=\"active customers KPI card\">\n<div class=\"flex items-center justify-between\" data-kid=\"1-1-3-3-1\" data-name=\"KPI card header row\">\n<p class=\"text-[12px] text-[#7d7568]\" data-kid=\"1-1-3-3-1-1\" data-name=\"KPI label text\">Işjeň müşderiler</p>\n<span class=\"flex h-7 w-7 items-center justify-center rounded-fulLine truncated
|
||||||
|
"comments": [],
|
||||||
|
"created": "2026-10-23T16:03:49.232549+00:00",
|
||||||
|
"modified": "2026-10-23T16:05:22.010377+00:00",
|
||||||
|
"id": "var_ee5e76ea0954",
|
||||||
|
"contentHeight": 1631
|
||||||
|
},
|
||||||
|
"var_5556852de882": {
|
||||||
|
"type": "variant",
|
||||||
|
"label": "C · Seramik Izgara — mat fayanslar, teal rampa, tick göstergeler",
|
||||||
|
"parentId": null,
|
||||||
|
"themeId": null,
|
||||||
|
"rect": {
|
||||||
|
"x": 4140,
|
||||||
|
"y": 0,
|
||||||
|
"w": 1280,
|
||||||
|
"h": 0
|
||||||
|
},
|
||||||
|
"html": "<style>\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n @import url('https://cdn.jsdelivr.net/npm/lucide-static@1.48.0/font/lucide.css');\n</style>\n<div class=\"min-h-screen bg-[#f7f8f8] text-[#1b2a38] antialiased\" data-kid=\"1\" data-name=\"dashboard page root\" style=\"font-family:'Inter',sans-serif\">\n<div class=\"mx-auto w-full max-w-[1200px] px-8 py-7\" data-kid=\"1-1\" data-name=\"page content container\">\n<!-- Header -->\n<div class=\"flex items-center justify-between gap-6\" data-kid=\"1-1-1\" data-name=\"page header with title and controls\">\n<div data-kid=\"1-1-1-1\" data-name=\"page title block\">\n<h1 class=\"text-[25px] font-semibold leading-none tracking-[-0.025em]\" data-kid=\"1-1-1-1-1\" data-name=\"page title heading\">Baş sahypa</h1>\n<p class=\"mt-1.5 text-[12.5px] text-[#66757e]\" data-kid=\"1-1-1-1-2\" data-name=\"page title subtitle text\">Ähli amallaryň gysgaça görünüşi</p>\n</div>\n<div class=\"flex items-center gap-2\" data-kid=\"1-1-1-2\" data-name=\"header action controls row\">\n<button class=\"flex h-8 items-center gap-2 rounded-[3px] border border-[#d9e3e0] bg-white px-3 text-[12.5px]\" data-kid=\"1-1-1-2-1\" data-name=\"year selector button\">\n<span class=\"tabular-nums\" data-kid=\"1-1-1-2-1-1\" data-name=\"selected year value text\">2026</span>\n<span class=\"text-[10.5px] text-[#8493a0]\" data-kid=\"1-1-1-2-1-2\" data-name=\"year unit label\">ýyl</span>\n<i class=\"icon-chevron-down text-[12px] text-[#8493a0]\" data-kid=\"1-1-1-2-1-3\" data-name=\"chevron down dropdown icon\"></i>\n</button>\n<button class=\"flex h-8 w-8 items-center justify-center rounded-[3px] border border-[#d9e3e0] bg-white text-[#4a5a66]\" data-kid=\"1-1-1-2-2\" data-name=\"refresh data button\">\n<i class=\"icon-refresh-cw text-[13px]\" data-kid=\"1-1-1-2-2-1\" data-name=\"refresh icon\"></i>\n</button>\n</div>\n</div>\n<!-- KPI tiles -->\n<div class=\"mt-6 grid grid-cols-4 gap-3\" data-kid=\"1-1-2\" data-name=\"KPI metrics grid\">\n<div class=\"rounded-[4px] border border-[#d9e3e0] bg-white px-5 pb-5 pt-4 shadow-[0_1px_2px_rgba(20,40,50,0.05)]\" data-kid=\"1-1-2-1\" data-name=\"loan orders KPI tile\">\n<div class=\"flex items-center justify-between\" data-kid=\"1-1-2-1-1\" data-name=\"KPI tile header row\">\n<p class=\"text-[11.5px] font-medium text-[#66757e]\" data-kid=\"1-1-2-1-1-1\" data-name=\"KPI card label\">Karz sargytlary</p>\n<i class=\"icon-file-text text-[14px] text-[#9aa9b4]\" data-kid=\"1-1-2-1-1-2\" data-name=\"document file icon\"></i>\n</div>\n<p class=\"mt-4 text-[34px] font-semibold leading-none tracking-[-0.03em] tabular-nums\" data-kid=\"1-1-2-1-2\" data-name=\"KPI primary value\">12,480</p>\n<div class=\"mt-3 flex items-center gap-1.5\" data-kid=\"1-1-2-1-3\" data-name=\"KPI change summary row\">\n<span class=\"inline-flex items-center gap-0.5 rounded-[2px] bg-[#e8f2ef] px-1 py-0.5 text-[10.5px] font-semibold text-[#1f7a6d]\" data-kid=\"1-1-2-1-3-1\" data-name=\"positive percent change badge\">\n<i class=\"icon-arrow-up-right text-[11px]\" data-kid=\"1-1-2-1-3-1-1\" data-name=\"up arrow icon\"></i>8,4%\n </span>\n<span class=\"text-[10.5px] text-[#8493a0]\" data-kid=\"1-1-2-1-3-2\" data-name=\"period comparison caption\">geçen aýa garanyňda</span>\n</div>\n</div>\n<div class=\"rounded-[4px] border border-[#d9e3e0] bg-white px-5 pb-5 pt-4 shadow-[0_1px_2px_rgba(20,40,50,0.05)]\" data-kid=\"1-1-2-2\" data-name=\"active cards KPI tile\">\n<div class=\"flex items-center justify-between\" data-kid=\"1-1-2-2-1\" data-name=\"KPI tile header row\">\n<p class=\"text-[11.5px] font-medium text-[#66757e]\" data-kid=\"1-1-2-2-1-1\" data-name=\"KPI card label\">Işjeň kartlar</p>\n<i class=\"icon-credit-card text-[14px] text-[#9aa9b4]\" data-kid=\"1-1-2-2-1-2\" data-name=\"credit card icon\"></i>\n</div>\n<p class=\"mt-4 text-[34px] font-semibold leading-none tracking-[-0.03em] tabular-nums\" data-kid=\"1-1-2-2-2\" data-name=\"KPI primary value\">8,205</p>\n<div class=\"mt-3 flex items-center gap-1.5\" data-kid=\"1-1-2-2-3\" data-name=\"KPI change summary row\">\n<span class=\"inline-flex items-center gap-0.5 rounded-[2px] bg-[#e8f2ef] px-1 py-0.5 text-[10.5px] font-semibold text-[#1f7a6d]\" data-kid=\"1-1-2-2-3-1\" data-name=\"positive percent change badge\">\n<i class=\"icon-arrow-up-right text-[11px]\" data-kid=\"1-1-2-2-3-1-1\" data-name=\"up arrow icon\"></i>3,1%\n </span>\n<span class=\"text-[10.5px] text-[#8493a0]\" data-kid=\"1-1-2-2-3-2\" data-name=\"period comparison caption\">geçen aýa garanyňda</span>\n</div>\n</div>\n<div class=\"rounded-[4px] border border-[#d9e3e0] bg-white px-5 pb-5 pt-4 shadow-[0_1px_2px_rgba(20,40,50,0.05)]\" data-kid=\"1-1-2-3\" data-name=\"active customers KPI tile\">\n<div class=\"flex items-center justify-between\" data-kid=\"1-1-2-3-1\" data-name=\"KPI tile header row\">\n<p class=\"text-[11.5px] font-medium text-[#66757e]\" data-kid=\"1-1-2-3-1Line truncated
|
||||||
|
"comments": [],
|
||||||
|
"created": "2026-10-23T16:03:56.287587+00:00",
|
||||||
|
"modified": "2026-10-23T16:05:22.482086+00:00",
|
||||||
|
"id": "var_5556852de882",
|
||||||
|
"contentHeight": 1529
|
||||||
|
},
|
||||||
|
"var_0e76cbc03617": {
|
||||||
|
"type": "variant",
|
||||||
|
"label": "A · Final — kayıt panelleri, teslim edilebilir sürüm",
|
||||||
|
"parentId": "var_f7c0491a62d9",
|
||||||
|
"themeId": null,
|
||||||
|
"rect": {
|
||||||
|
"x": 1380,
|
||||||
|
"y": 0,
|
||||||
|
"w": 1280,
|
||||||
|
"h": 0
|
||||||
|
},
|
||||||
|
"html": "<style>\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n @import url('https://cdn.jsdelivr.net/npm/lucide-static@1.48.0/font/lucide.css');\n</style>\n<div class=\"min-h-screen bg-[#f8fbfa] text-[#0f211f] antialiased\" data-kid=\"1\" data-name=\"page background container\" style=\"font-family:'Inter',sans-serif\">\n<div class=\"mx-auto w-full max-w-[1200px] px-8 py-8\" data-kid=\"1-1\" data-name=\"page content wrapper\">\n<!-- ── Page header ───────────────────────────────────────────── -->\n<div class=\"flex items-end justify-between gap-6\" data-kid=\"1-1-1\" data-name=\"page header bar\">\n<div data-kid=\"1-1-1-1\" data-name=\"header title block\">\n<h1 class=\"text-[26px] font-semibold leading-none tracking-[-0.022em]\" data-kid=\"1-1-1-1-1\" data-name=\"page title heading\">Baş sahypa</h1>\n<p class=\"mt-2 text-[13px] text-[#57706d]\" data-kid=\"1-1-1-1-2\" data-name=\"page subtitle text\">Ähli amallaryň gysgaça görünüşi</p>\n</div>\n<div class=\"flex items-center rounded-[7px] border border-[#dfe8e6] bg-[#eff5f4] p-0.5\" data-kid=\"1-1-1-2\" data-name=\"date and refresh control group\">\n<button class=\"flex h-8 items-center gap-2 rounded-[5px] px-2.5 text-[13px] text-[#0f211f]\" data-kid=\"1-1-1-2-1\" data-name=\"year selector button\">\n<span class=\"tabular-nums\" data-kid=\"1-1-1-2-1-1\" data-name=\"selected year text\">2026</span>\n<span class=\"text-[11px] text-[#7d938f]\" data-kid=\"1-1-1-2-1-2\" data-name=\"year unit label\">ýyl</span>\n<i class=\"icon-chevron-down text-[12px] text-[#7d938f]\" data-kid=\"1-1-1-2-1-3\" data-name=\"chevron down dropdown indicator icon\"></i>\n</button>\n<span class=\"h-4 w-px bg-[#d7e2df]\" data-kid=\"1-1-1-2-2\" data-name=\"vertical divider between controls\"></span>\n<button class=\"flex h-8 w-8 items-center justify-center rounded-[5px] text-[#3f5753]\" data-kid=\"1-1-1-2-3\" data-name=\"data refresh button\">\n<i class=\"icon-refresh-cw text-[14px]\" data-kid=\"1-1-1-2-3-1\" data-name=\"refresh circular arrow icon\"></i>\n</button>\n</div>\n</div>\n<!-- ── KPI register ──────────────────────────────────────────── -->\n<div class=\"mt-7 overflow-hidden rounded-[11px] border border-[#dfe8e6] bg-[#eff5f4]\" data-kid=\"1-1-2\" data-name=\"KPI statistics panel\">\n<div class=\"grid grid-cols-4 divide-x divide-[#dfe8e6]\" data-kid=\"1-1-2-1\" data-name=\"KPI grid row\">\n<div class=\"px-6 py-5\" data-kid=\"1-1-2-1-1\" data-name=\"loan orders KPI card\">\n<div class=\"flex items-start justify-between\" data-kid=\"1-1-2-1-1-1\" data-name=\"KPI label and icon row\">\n<p class=\"text-[12px] font-medium text-[#57706d]\" data-kid=\"1-1-2-1-1-1-1\" data-name=\"loan orders metric label\">Karz sargytlary</p>\n<i class=\"icon-file-text text-[15px] text-[#8ba19d]\" data-kid=\"1-1-2-1-1-1-2\" data-name=\"document file icon\"></i>\n</div>\n<p class=\"mt-3 text-[30px] font-semibold leading-none tracking-[-0.025em] tabular-nums\" data-kid=\"1-1-2-1-1-2\" data-name=\"loan orders value number\">12,480</p>\n<p class=\"mt-2.5 flex items-center gap-1 text-[11.5px] font-medium text-[#0c7a6b]\" data-kid=\"1-1-2-1-1-3\" data-name=\"loan orders change indicator\">\n<i class=\"icon-arrow-up-right text-[12px]\" data-kid=\"1-1-2-1-1-3-1\" data-name=\"up-right trend icon\"></i>8,4%\n <span class=\"font-normal text-[#7d938f]\" data-kid=\"1-1-2-1-1-3-2\" data-name=\"change percentage context label\">geçen aýa garanyňda</span>\n</p>\n</div>\n<div class=\"px-6 py-5\" data-kid=\"1-1-2-1-2\" data-name=\"active cards KPI card\">\n<div class=\"flex items-start justify-between\" data-kid=\"1-1-2-1-2-1\" data-name=\"KPI label and icon row\">\n<p class=\"text-[12px] font-medium text-[#57706d]\" data-kid=\"1-1-2-1-2-1-1\" data-name=\"active cards metric label\">Işjeň kartlar</p>\n<i class=\"icon-credit-card text-[15px] text-[#8ba19d]\" data-kid=\"1-1-2-1-2-1-2\" data-name=\"credit card icon\"></i>\n</div>\n<p class=\"mt-3 text-[30px] font-semibold leading-none tracking-[-0.025em] tabular-nums\" data-kid=\"1-1-2-1-2-2\" data-name=\"active cards value number\">8,205</p>\n<p class=\"mt-2.5 flex items-center gap-1 text-[11.5px] font-medium text-[#0c7a6b]\" data-kid=\"1-1-2-1-2-3\" data-name=\"active cards change indicator\">\n<i class=\"icon-arrow-up-right text-[12px]\" data-kid=\"1-1-2-1-2-3-1\" data-name=\"up-right trend icon\"></i>3,1%\n <span class=\"font-normal text-[#7d938f]\" data-kid=\"1-1-2-1-2-3-2\" data-name=\"change percentage context label\">geçen aýa garanyňda</span>\n</p>\n</div>\n<div class=\"px-6 py-5\" data-kid=\"1-1-2-1-3\" data-name=\"active customers KPI card\">\n<div class=\"flex items-start justify-between\" data-kid=\"1-1-2-1-3-1\" data-name=\"KPI label and icon row\">\n<p class=\"text-[12px] fonLine truncated
|
||||||
|
"comments": [],
|
||||||
|
"created": "2026-10-23T16:06:08.609821+00:00",
|
||||||
|
"modified": "2026-10-23T16:07:28.743128+00:00",
|
||||||
|
"id": "var_0e76cbc03617",
|
||||||
|
"contentHeight": 1650
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"comments": [],
|
||||||
|
"nextCommentNumber": 1
|
||||||
|
}
|
||||||
@@ -56,6 +56,7 @@ src/
|
|||||||
├── app/ # Global provider'lar, store'lar ve router konfigürasyonları
|
├── app/ # Global provider'lar, store'lar ve router konfigürasyonları
|
||||||
├── assets/ # Görseller, fontlar vb. statik dosyalar
|
├── assets/ # Görseller, fontlar vb. statik dosyalar
|
||||||
├── components/ # Global ve UI bileşenleri (shadcn vb. ortak bileşenler)
|
├── components/ # Global ve UI bileşenleri (shadcn vb. ortak bileşenler)
|
||||||
|
├── constants/ # Paylaşılan sabitler ve lookup verileri (passportSeries, statusOptions vb.)
|
||||||
├── features/ # Özellik bazlı modüller (auth, dashboard, users vb.)
|
├── features/ # Özellik bazlı modüller (auth, dashboard, users vb.)
|
||||||
│ └── [feature]/
|
│ └── [feature]/
|
||||||
│ ├── api/ # Feature'a özel axios istek fonksiyonları
|
│ ├── api/ # Feature'a özel axios istek fonksiyonları
|
||||||
@@ -70,6 +71,14 @@ src/
|
|||||||
└── pages/ # Router tarafından çağrılan ana sayfalar
|
└── pages/ # Router tarafından çağrılan ana sayfalar
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 5. Authorization (RBAC) Contract
|
||||||
|
|
||||||
|
- Permissions use one code per module (`users`, `roles`, `branches`, `provinces`, `activity-logs`, `backups`, `currencies`, `payment-settings`, `cards`, `loans`, and `dashboard`); a granted code allows both reading and writing that module.
|
||||||
|
- `GET /profile` supplies `role.scope` (`own`, `branch`, or `all`), `role.isSuper`, and `permissions: [{ code, name }]`. Do not depend on `guardName` or a `modules` field.
|
||||||
|
- `GET /permissions` is a read-only `{ code, name }[]` catalog. Permission create, update, delete, tree, and detail endpoints are not supported.
|
||||||
|
- Role creation sends `{ code, name, scope, permissions: string[] }`; role updates send `{ name, scope, permissions: string[] }`. Role codes are immutable. A role with `isSystem: true` cannot be deleted or have its scope changed.
|
||||||
|
- User role assignment uses `PUT /users/:id/role` with `{ roleId }`. Create/update user payloads may include both `role` (code) and `roleId`; the backend prioritizes `roleId`.
|
||||||
|
|
||||||
## AI / Agent İçin Katı Talimatlar (System Instructions)
|
## AI / Agent İçin Katı Talimatlar (System Instructions)
|
||||||
|
|
||||||
1. Yeni bir bileşen veya özellik ekleneceğinde her zaman önce `src/features/` altına eklenip eklenmeyeceğini değerlendir.
|
1. Yeni bir bileşen veya özellik ekleneceğinde her zaman önce `src/features/` altına eklenip eklenmeyeceğini değerlendir.
|
||||||
@@ -127,3 +136,7 @@ src/
|
|||||||
- Her shared endpoint fonksiyonu için `src/features/shared/hooks/useShared[Resource].ts` adında bir React Query hook'u oluşturulur.
|
- Her shared endpoint fonksiyonu için `src/features/shared/hooks/useShared[Resource].ts` adında bir React Query hook'u oluşturulur.
|
||||||
- Shared hook'larda `staleTime` mutlaka belirtilmelidir (dropdown/lookup verileri için minimum 5 dakika önerilir).
|
- Shared hook'larda `staleTime` mutlaka belirtilmelidir (dropdown/lookup verileri için minimum 5 dakika önerilir).
|
||||||
- Aynı `queryKey` ile çağrılan hook TanStack Query tarafından otomatik olarak dedup edilir; aynı hook'u birden fazla component'te çağırmak ekstra network isteği oluşturmaz.
|
- Aynı `queryKey` ile çağrılan hook TanStack Query tarafından otomatik olarak dedup edilir; aynı hook'u birden fazla component'te çağırmak ekstra network isteği oluşturmaz.
|
||||||
|
13. **Paylaşımlı Sabitler ve Lookup Verileri (Shared Constants):**
|
||||||
|
- Birden fazla feature veya sayfada kullanılan statik veriler (pasport seri numaraları, durum/status seçenekleri, sabit listeler vb.) `src/constants/` dizininde tanımlanmalıdır.
|
||||||
|
- `src/constants/index.ts` üzerinden dışa aktarılarak `@/constants` yoluyla projenin her yerinde yeniden kullanılmalıdır.
|
||||||
|
- Form select seçenekleri için `SelectOption[]` formatında sabitler (`PASSPORT_SERIES_OPTIONS`, `STATUS_OPTIONS`) veya i18n uyumlu yardımcı fonksiyonlar (`getStatusOptions` vb.) sunulmalıdır.
|
||||||
@@ -25,6 +25,7 @@ A full-featured internal banking administration panel built with **React 19 + Vi
|
|||||||
7. [Feature Modules](#feature-modules)
|
7. [Feature Modules](#feature-modules)
|
||||||
8. [Shared Components](#shared-components)
|
8. [Shared Components](#shared-components)
|
||||||
9. [Route Map](#route-map)
|
9. [Route Map](#route-map)
|
||||||
|
- [RBAC API contract](#rbac-api-contract)
|
||||||
10. [Development Standards](#development-standards)
|
10. [Development Standards](#development-standards)
|
||||||
11. [Known Issues & Gaps](#known-issues--gaps)
|
11. [Known Issues & Gaps](#known-issues--gaps)
|
||||||
|
|
||||||
@@ -48,7 +49,6 @@ A full-featured internal banking administration panel built with **React 19 + Vi
|
|||||||
| Notifications | Sonner | ^2.0 |
|
| Notifications | Sonner | ^2.0 |
|
||||||
| i18n | i18next + react-i18next | ^26 / ^17 |
|
| i18n | i18next + react-i18next | ^26 / ^17 |
|
||||||
| Charts | Recharts | ^3.8 |
|
| Charts | Recharts | ^3.8 |
|
||||||
| Rich Text | Tiptap | ^3.23 |
|
|
||||||
| Icons | Lucide React | ^1.14 |
|
| Icons | Lucide React | ^1.14 |
|
||||||
| Fonts | Geist + Inter (variable) | ^5.2 |
|
| Fonts | Geist + Inter (variable) | ^5.2 |
|
||||||
|
|
||||||
@@ -146,6 +146,11 @@ src/
|
|||||||
│ ├── tableButton.tsx # Small icon button used inside table rows
|
│ ├── tableButton.tsx # Small icon button used inside table rows
|
||||||
│ └── tableSearch.tsx # Standalone search input for tables
|
│ └── tableSearch.tsx # Standalone search input for tables
|
||||||
│
|
│
|
||||||
|
├── constants/ # Global shared constants & options
|
||||||
|
│ ├── index.ts # Main entry point for re-exporting constants
|
||||||
|
│ ├── passportSeries.ts # Shared passport series options (I-AŞ, I-MR, etc.)
|
||||||
|
│ └── statusOptions.ts # Shared status options & i18n helpers (pending, approved, etc.)
|
||||||
|
│
|
||||||
├── features/ # Feature-Sliced Design — one folder per domain
|
├── features/ # Feature-Sliced Design — one folder per domain
|
||||||
│ ├── shared/ # APIs and hooks used by 2+ features
|
│ ├── shared/ # APIs and hooks used by 2+ features
|
||||||
│ │ ├── api/ # sharedApi.ts — shared endpoints + TypeScript types
|
│ │ ├── api/ # sharedApi.ts — shared endpoints + TypeScript types
|
||||||
@@ -439,7 +444,7 @@ Toolbar placed above `DataTable`. Provides: search input, dynamic filter dropdow
|
|||||||
|
|
||||||
### `FormInput` (`src/components/formInput.tsx`)
|
### `FormInput` (`src/components/formInput.tsx`)
|
||||||
|
|
||||||
Comprehensive single-step form builder. Renders `text`, `select`, `date`, `textarea`, `rich-text` (Tiptap), and `file-upload` fields from a config array. Always paired with RHF + Zod.
|
Comprehensive single-step form builder. Renders `text`, `select`, `date`, `textarea`, and `file-upload` fields from a config array. Always paired with RHF + Zod.
|
||||||
|
|
||||||
### `StepBarV2` (`src/components/stepBarV2.tsx`)
|
### `StepBarV2` (`src/components/stepBarV2.tsx`)
|
||||||
|
|
||||||
@@ -553,9 +558,6 @@ All authenticated routes are nested under `DashboardLayout`. The full list:
|
|||||||
/settings/users/roles/:id/edit
|
/settings/users/roles/:id/edit
|
||||||
|
|
||||||
/settings/users/permissions
|
/settings/users/permissions
|
||||||
/settings/users/permissions/create
|
|
||||||
/settings/users/permissions/:id
|
|
||||||
/settings/users/permissions/:id/edit
|
|
||||||
|
|
||||||
/settings/loan/loan-types
|
/settings/loan/loan-types
|
||||||
/settings/loan/loan-types/create
|
/settings/loan/loan-types/create
|
||||||
@@ -590,6 +592,14 @@ All authenticated routes are nested under `DashboardLayout`. The full list:
|
|||||||
* → NotFoundPage
|
* → NotFoundPage
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### RBAC API contract
|
||||||
|
|
||||||
|
- `/profile` returns `role: { id, code, name, scope, isSuper }`, permissions as `{ code, name }[]`, and no `guardName` or `modules`.
|
||||||
|
- Permission codes are module-level (`users`, `roles`, `branches`, `provinces`, `activity-logs`, `backups`, `currencies`, `payment-settings`, `cards`, `loans`, `dashboard`); a code grants both read and write access. The permissions screen is a read-only catalog from `GET /permissions`.
|
||||||
|
- Roles contain `scope`, `isSuper`, `isSystem`, permission codes, and user count. Creation sends `{ code, name, scope, permissions }`; updates send `{ name, scope, permissions }`.
|
||||||
|
- System roles cannot be deleted or have their scope changed. Role codes are immutable after creation.
|
||||||
|
- User create/update sends the role code and `roleId` when available; role reassignment uses `PUT /users/:id/role` with `{ roleId }`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Development Standards
|
## Development Standards
|
||||||
@@ -621,6 +631,7 @@ All authenticated routes are nested under `DashboardLayout`. The full list:
|
|||||||
| Disable buttons during mutation | `disabled={mutation.isPending}` on submit buttons. |
|
| Disable buttons during mutation | `disabled={mutation.isPending}` on submit buttons. |
|
||||||
| `PageErrorBoundary` on every route | Already set via `errorElement` in the router. |
|
| `PageErrorBoundary` on every route | Already set via `errorElement` in the router. |
|
||||||
| No duplicate API calls | If an endpoint is used by 2+ features, it belongs in `src/features/shared/` — never copy-paste API functions across feature folders. |
|
| No duplicate API calls | If an endpoint is used by 2+ features, it belongs in `src/features/shared/` — never copy-paste API functions across feature folders. |
|
||||||
|
| Use shared constants | Common lookup options (passport series, status options) must be stored in `src/constants/` and exported via `@/constants`. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -634,7 +645,6 @@ These items exist in the sidebar nav or codebase but are **not yet implemented**
|
|||||||
| **`/settings/language/resources`** | ❌ No route or page | Same as above |
|
| **`/settings/language/resources`** | ❌ No route or page | Same as above |
|
||||||
| **`/logs`** | ❌ No route or page | Sidebar entry exists |
|
| **`/logs`** | ❌ No route or page | Sidebar entry exists |
|
||||||
| **`client.ts` uses `any`** | ⚠️ | `failedQueue: any[]` violates the no-`any` rule — should be typed |
|
| **`client.ts` uses `any`** | ⚠️ | `failedQueue: any[]` violates the no-`any` rule — should be typed |
|
||||||
| **`authStore` role type** | ⚠️ | `role: 'admin' \| 'manager' \| 'viewer'` — actual role enforcement (RBAC) not wired to UI |
|
|
||||||
| **`DashboardLayout` sidebar strings** | ⚠️ | Nav item titles use `t("English", "Fallback")` instead of proper i18n keys — inconsistent with the project standard |
|
| **`DashboardLayout` sidebar strings** | ⚠️ | Nav item titles use `t("English", "Fallback")` instead of proper i18n keys — inconsistent with the project standard |
|
||||||
| **`AuthLayout`** | ❌ Missing | No dedicated layout for the login page; it renders without a wrapper layout |
|
| **`AuthLayout`** | ❌ Missing | No dedicated layout for the login page; it renders without a wrapper layout |
|
||||||
| **Mock data** | ⚠️ | All API functions currently return **mock in-memory data**. When connecting a real backend, replace the functions in `[feature]Api.ts` with real `apiClient.get/post/put/delete()` calls. |
|
| **Mock data** | ⚠️ | All API functions currently return **mock in-memory data**. When connecting a real backend, replace the functions in `[feature]Api.ts` with real `apiClient.get/post/put/delete()` calls. |
|
||||||
|
|||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
VITE_API_BASE_URL=https://test.webulgam.com/online-backend/api/admin
|
||||||
|
VITE_API_URL=/api
|
||||||
|
VITE_ENABLE_MOCKS=false
|
||||||
|
|
||||||
|
|
||||||
|
# Public path the app is served under (router basename follows it)
|
||||||
|
VITE_BASE_PATH=/online/
|
||||||
|
# Dev server: backend origin for the /api proxy, and allowed hosts (comma-separated)
|
||||||
|
VITE_PROXY_TARGET=https://test.webulgam.com/online-backend
|
||||||
|
VITE_ALLOWED_HOSTS=test.webulgam.com
|
||||||
+1
-1
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="./src/assets/icon.svg" />
|
<link rel="icon" type="image/svg+xml" href="./src/assets/icon.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>tbbank-admin</title>
|
<title>TÜRKMENBAŞY PTB — Admin</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
Generated
+16
-607
@@ -14,12 +14,10 @@
|
|||||||
"@tailwindcss/container-queries": "^0.1.1",
|
"@tailwindcss/container-queries": "^0.1.1",
|
||||||
"@tanstack/react-query": "^5.100.8",
|
"@tanstack/react-query": "^5.100.8",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"@tiptap/extension-link": "^3.23.2",
|
|
||||||
"@tiptap/react": "^3.23.2",
|
|
||||||
"@tiptap/starter-kit": "^3.23.2",
|
|
||||||
"axios": "^1.15.2",
|
"axios": "^1.15.2",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"cn": "^0.3.2",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
"i18next": "^26.0.8",
|
"i18next": "^26.0.8",
|
||||||
"lucide-react": "^1.14.0",
|
"lucide-react": "^1.14.0",
|
||||||
@@ -37,7 +35,6 @@
|
|||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.5.0",
|
"tailwind-merge": "^3.5.0",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"vaul": "^1.1.2",
|
|
||||||
"zod": "^4.4.3",
|
"zod": "^4.4.3",
|
||||||
"zustand": "^5.0.12"
|
"zustand": "^5.0.12"
|
||||||
},
|
},
|
||||||
@@ -3515,434 +3512,6 @@
|
|||||||
"url": "https://github.com/sponsors/tannerlinsley"
|
"url": "https://github.com/sponsors/tannerlinsley"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@tiptap/core": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-yjv2N7gaQMbIVfsSZHBMscLoybgetcTraXsSMrELAerl/jfRipg5S1dBXMFvgRy8Kh48+TGoH+5nqshxdOEGoQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/pm": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-blockquote": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-blockquote/-/extension-blockquote-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-BBN22/nUErRzUr1HI/Q4iPFBNavWoNC5Fx0KXp9oDOCCrCvj55rtGwLn2dB3r4vLfhjYvhEZ38wN+r7Y9RhORA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-bold": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-bold/-/extension-bold-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-onPFP260enNkjMGhR7sDSqaF80A4sgvMZ/VZLxp7zGa6DAfcuN4PyUQhZN61KmYgbUdr+qrAAMx+tPuid22F4g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-bubble-menu": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-S0LZg6EMdkr5CiYAGmOwzuNPd2T18ZR5pWrgHHHZjt0IFqU01tBJa3zLzC1Vd7noPCec64ygW9S8+p8CHBgOIA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@floating-ui/dom": "^1.0.0"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2",
|
|
||||||
"@tiptap/pm": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-bullet-list": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-bullet-list/-/extension-bullet-list-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-jhvu1qa8F53r//6DrLdA2OkTbRgY73NkQL51Ruozzi+JrfVIo3IfaTNRq01BXO5qcvNH7P/aDBF5cByvuiUMzQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/extension-list": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-code": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-code/-/extension-code-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-5yHYavvBEkxgWL6DCPYNHujxBXF7c812MFNoU62ljNJjIYDc2Mu8ftOie/ajNJbMLqwSVzCuGfG9swEuEKxY5g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-code-block": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-code-block/-/extension-code-block-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-oWwjsLi+m7zHTqM0kYnnogjS3vFENCaLk3ue/1XE9ccpZlmmPzmK70hodB/UPylFJmgr3g726rhxViYv9LRS7A==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2",
|
|
||||||
"@tiptap/pm": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-document": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-Ff/MAaWPzFtb7nhPG6ETdu7/OqkD6cAmJfViBAiRqh9PPULH98fGDaMBm3TGa1s3XB7hGO7c/xVKxEdjYij5rg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-dropcursor": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-T7pVfIF5uDj043CDJlurNoMAmXPy36EjBz/YQVYrVMSSUbvUlOaL3xxoDODRmir29jVrmCROjaKwVExqooQTqQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/extensions": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-floating-menu": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-floating-menu/-/extension-floating-menu-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-1rfxx5X52h44jSS9R1fUx8sOaRpNq8CM0IR3EdjpthVvaRZ9XD1tKX4h5EcwGFqNiwtWXxNne2mV7ZJuH2UYsQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@floating-ui/dom": "^1.0.0",
|
|
||||||
"@tiptap/core": "3.23.2",
|
|
||||||
"@tiptap/pm": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-gapcursor": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-gapcursor/-/extension-gapcursor-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-I3LKYVwyxRaiVaJxss98QWOXzZZrHmsJD3RgAZ0Uoguu3pL29Krn2tXfwp4FAd9NG79wdQHj20c+XuqJLNkAbw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/extensions": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-hard-break": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-hard-break/-/extension-hard-break-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-3p00oC2caRAVtkOweJ9IjTgjhzm34R9tNyMCykzMRygC8CdO08Jv2JKvUaOeMVVmWZI+O9wkGUpaA2Drg6pY4g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-heading": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-heading/-/extension-heading-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-ldQh38ZWTIedSY6XsOkn1ULtk+mD/mezLogrvcVv8neez0qM/S25vyMZKqP7i2/x4i4ds1JYIJLw9y3HX/B69Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-horizontal-rule": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-LbLACqe/OiTdYIq3zbsY7Ue7WOP+mYTGufNDfs8rSGcUbWI2GwUwoGRrTPBbLIesnuCdH6FyMB60Tg/HzjKaYw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2",
|
|
||||||
"@tiptap/pm": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-italic": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-pauWOkom8riyZoIGn8I8uFE//uRgE6kL46Pd6PdSd5Wt6w/ao/le9Ju2Ln947NGjz/6whaDiFnBrkSbZEAhpmw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-link": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-h0D3Lwom0hGDsbpZ6tW0+DRKgBP0qSl4rO/iBfGk3Krb2CoyEn1yII3pSTd1PwAld7bHt/buURi6DWudQsIhgg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"linkifyjs": "^4.3.2"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2",
|
|
||||||
"@tiptap/pm": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-list": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-list/-/extension-list-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-tRbbjpOPrY4ApIHtn3ctnKIhkkioewMsZa5gJzqVB47LJFNyzLXLo/aID4sJRKTIMi1wd1fA9TiBKPe6KqczPA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2",
|
|
||||||
"@tiptap/pm": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-list-item": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-list-item/-/extension-list-item-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-I9Yed0mmBE6AAhc4Cc5UhZLZUMCft9XdPkdBM/wjcjpLwdMhdzelVQXEhNDyPfRkA1TTGs5VHlc6twjCPCTgLg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/extension-list": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-list-keymap": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-list-keymap/-/extension-list-keymap-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-aE4PzCy+OWXXFc8UsrrYjcfEbyXCh8f7LuGgFPl8jf0JjgIK0FHmzWDg3912zWb5Ww66AF2j0KJzTB9NFOMWlw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/extension-list": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-ordered-list": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-ordered-list/-/extension-ordered-list-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-ZhMejT4jXfOEECqI60AVBzULl8AVN8BXk/9vjVnJHxBtcQxW+tIu5GHVZ4DPaCfTX7mH+hsceFMhQ2BvV7qvbg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/extension-list": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-paragraph": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-paragraph/-/extension-paragraph-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-UzHx5zOi9fjhC9TAqHeD7BV5eJIA3t65pa2Mq8b54V9nrIg1yAlgiafU0WDWoom11TF+IWxz5JBsjlW0/P/VeQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-strike": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-strike/-/extension-strike-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-m1BN3EXwYagzVdReGoI7McvuZFyolFwuXLgzU6c+RN7E+u+K68EY+2U3pJI5ee8UgPYGW4eBs/3BT/5k+0so3Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-text": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-Ny4FC+BivfwACTuJO3QPe+BXtVFfzWQVBcfhlFlA7xTaeBktFeBavH2cEyXR8Qbez3Wio/Hn+bibT4d44EBLyg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extension-underline": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-underline/-/extension-underline-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-HdPX1nZarOF8UkDccu6gBy6brZd4vDFCa5Mz1liw3B3D6UBiC+8vzE1YGHtggO+KEBBQYf4GgjT3qqIgOcsTEQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/extensions": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/extensions/-/extensions-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-kRHQ3nSbAfkFdxj9FtDdr4hpREndGgWFA6ZEAwlLeGUxf8QYTpuF9zb2yxdBPBlTc5+JsbPcskNt+u1PazGKYw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2",
|
|
||||||
"@tiptap/pm": "3.23.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/pm": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-1kvsBqGNu2ZJ0P/lkxN0pAMqSyUcpkMIzE4xwGUIyAiD0pZV6dr+OCMwGWOTLllSyrn91xI5K7OLk3pYeCPKqA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-changeset": "^2.3.0",
|
|
||||||
"prosemirror-commands": "^1.6.2",
|
|
||||||
"prosemirror-dropcursor": "^1.8.1",
|
|
||||||
"prosemirror-gapcursor": "^1.3.2",
|
|
||||||
"prosemirror-history": "^1.4.1",
|
|
||||||
"prosemirror-keymap": "^1.2.2",
|
|
||||||
"prosemirror-model": "^1.24.1",
|
|
||||||
"prosemirror-schema-list": "^1.5.0",
|
|
||||||
"prosemirror-state": "^1.4.3",
|
|
||||||
"prosemirror-tables": "^1.6.4",
|
|
||||||
"prosemirror-transform": "^1.10.2",
|
|
||||||
"prosemirror-view": "^1.38.1"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/react": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/react/-/react-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-qfl70xRDQbwov8y5QvK+EiYk6JyoyzUimNtOmLSfeun2NjQwv67hW1iQ+c3geDbcwfUY5+h3XYMy1Lm+Bt46NQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@types/use-sync-external-store": "^0.0.6",
|
|
||||||
"fast-equals": "^5.3.3",
|
|
||||||
"use-sync-external-store": "^1.4.0"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
},
|
|
||||||
"optionalDependencies": {
|
|
||||||
"@tiptap/extension-bubble-menu": "^3.23.2",
|
|
||||||
"@tiptap/extension-floating-menu": "^3.23.2"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@tiptap/core": "3.23.2",
|
|
||||||
"@tiptap/pm": "3.23.2",
|
|
||||||
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
|
||||||
"@types/react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
|
||||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
|
||||||
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tiptap/starter-kit": {
|
|
||||||
"version": "3.23.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@tiptap/starter-kit/-/starter-kit-3.23.2.tgz",
|
|
||||||
"integrity": "sha512-t0o//bLmlUW/3j9ke1wIrrKkvfVYcBiC/cowCUNwN/YQx9Bc3S++yInkR6hat4qI4+O49+NRknVeaF/Sp247QA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@tiptap/core": "^3.23.2",
|
|
||||||
"@tiptap/extension-blockquote": "^3.23.2",
|
|
||||||
"@tiptap/extension-bold": "^3.23.2",
|
|
||||||
"@tiptap/extension-bullet-list": "^3.23.2",
|
|
||||||
"@tiptap/extension-code": "^3.23.2",
|
|
||||||
"@tiptap/extension-code-block": "^3.23.2",
|
|
||||||
"@tiptap/extension-document": "^3.23.2",
|
|
||||||
"@tiptap/extension-dropcursor": "^3.23.2",
|
|
||||||
"@tiptap/extension-gapcursor": "^3.23.2",
|
|
||||||
"@tiptap/extension-hard-break": "^3.23.2",
|
|
||||||
"@tiptap/extension-heading": "^3.23.2",
|
|
||||||
"@tiptap/extension-horizontal-rule": "^3.23.2",
|
|
||||||
"@tiptap/extension-italic": "^3.23.2",
|
|
||||||
"@tiptap/extension-link": "^3.23.2",
|
|
||||||
"@tiptap/extension-list": "^3.23.2",
|
|
||||||
"@tiptap/extension-list-item": "^3.23.2",
|
|
||||||
"@tiptap/extension-list-keymap": "^3.23.2",
|
|
||||||
"@tiptap/extension-ordered-list": "^3.23.2",
|
|
||||||
"@tiptap/extension-paragraph": "^3.23.2",
|
|
||||||
"@tiptap/extension-strike": "^3.23.2",
|
|
||||||
"@tiptap/extension-text": "^3.23.2",
|
|
||||||
"@tiptap/extension-underline": "^3.23.2",
|
|
||||||
"@tiptap/extensions": "^3.23.2",
|
|
||||||
"@tiptap/pm": "^3.23.2"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/ueberdosis"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@ts-morph/common": {
|
"node_modules/@ts-morph/common": {
|
||||||
"version": "0.27.0",
|
"version": "0.27.0",
|
||||||
"resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.27.0.tgz",
|
"resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.27.0.tgz",
|
||||||
@@ -4062,6 +3631,7 @@
|
|||||||
"version": "19.2.14",
|
"version": "19.2.14",
|
||||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
|
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
|
||||||
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
|
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
|
||||||
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"csstype": "^3.2.2"
|
"csstype": "^3.2.2"
|
||||||
@@ -4071,6 +3641,7 @@
|
|||||||
"version": "19.2.3",
|
"version": "19.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
|
||||||
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
|
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
|
||||||
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@types/react": "^19.2.0"
|
"@types/react": "^19.2.0"
|
||||||
@@ -4968,6 +4539,18 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/cn": {
|
||||||
|
"version": "0.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/cn/-/cn-0.3.2.tgz",
|
||||||
|
"integrity": "sha512-RKzY5Edavc8B2Ka6tjJecKFC4nm0p7lADY72xzICmiJSf4TkaxWXt0fHsib2P2G4FkFyXfSDi9oDtIBuCZvY2g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"cn": "bin/cn.mjs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/code-block-writer": {
|
"node_modules/code-block-writer": {
|
||||||
"version": "13.0.3",
|
"version": "13.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz",
|
||||||
@@ -5139,6 +4722,7 @@
|
|||||||
"version": "3.2.3",
|
"version": "3.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||||
|
"devOptional": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/d3-array": {
|
"node_modules/d3-array": {
|
||||||
@@ -5961,15 +5545,6 @@
|
|||||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/fast-equals": {
|
|
||||||
"version": "5.4.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.0.tgz",
|
|
||||||
"integrity": "sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=6.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/fast-glob": {
|
"node_modules/fast-glob": {
|
||||||
"version": "3.3.3",
|
"version": "3.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
||||||
@@ -7367,12 +6942,6 @@
|
|||||||
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
|
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/linkifyjs": {
|
|
||||||
"version": "4.3.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.2.tgz",
|
|
||||||
"integrity": "sha512-NT1CJtq3hHIreOianA8aSXn6Cw0JzYOuDQbOrSPe7gqFnCpKP++MQe3ODgO3oh2GJFORkAAdqredOa60z63GbA==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/lint-staged": {
|
"node_modules/lint-staged": {
|
||||||
"version": "16.4.0",
|
"version": "16.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-16.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-16.4.0.tgz",
|
||||||
@@ -8057,12 +7626,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/orderedmap": {
|
|
||||||
"version": "2.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz",
|
|
||||||
"integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/outvariant": {
|
"node_modules/outvariant": {
|
||||||
"version": "1.4.3",
|
"version": "1.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz",
|
"resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz",
|
||||||
@@ -8333,135 +7896,6 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/prosemirror-changeset": {
|
|
||||||
"version": "2.4.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-changeset/-/prosemirror-changeset-2.4.1.tgz",
|
|
||||||
"integrity": "sha512-96WBLhOaYhJ+kPhLg3uW359Tz6I/MfcrQfL4EGv4SrcqKEMC1gmoGrXHecPE8eOwTVCJ4IwgfzM8fFad25wNfw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-transform": "^1.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-commands": {
|
|
||||||
"version": "1.7.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.1.tgz",
|
|
||||||
"integrity": "sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-model": "^1.0.0",
|
|
||||||
"prosemirror-state": "^1.0.0",
|
|
||||||
"prosemirror-transform": "^1.10.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-dropcursor": {
|
|
||||||
"version": "1.8.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.2.tgz",
|
|
||||||
"integrity": "sha512-CCk6Gyx9+Tt2sbYk5NK0nB1ukHi2ryaRgadV/LvyNuO3ena1payM2z6Cg0vO1ebK8cxbzo41ku2DE5Axj1Zuiw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-state": "^1.0.0",
|
|
||||||
"prosemirror-transform": "^1.1.0",
|
|
||||||
"prosemirror-view": "^1.1.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-gapcursor": {
|
|
||||||
"version": "1.4.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.4.1.tgz",
|
|
||||||
"integrity": "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-keymap": "^1.0.0",
|
|
||||||
"prosemirror-model": "^1.0.0",
|
|
||||||
"prosemirror-state": "^1.0.0",
|
|
||||||
"prosemirror-view": "^1.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-history": {
|
|
||||||
"version": "1.5.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.5.0.tgz",
|
|
||||||
"integrity": "sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-state": "^1.2.2",
|
|
||||||
"prosemirror-transform": "^1.0.0",
|
|
||||||
"prosemirror-view": "^1.31.0",
|
|
||||||
"rope-sequence": "^1.3.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-keymap": {
|
|
||||||
"version": "1.2.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz",
|
|
||||||
"integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-state": "^1.0.0",
|
|
||||||
"w3c-keyname": "^2.2.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-model": {
|
|
||||||
"version": "1.25.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.4.tgz",
|
|
||||||
"integrity": "sha512-PIM7E43PBxKce8OQeezAs9j4TP+5yDpZVbuurd1h5phUxEKIu+G2a+EUZzIC5nS1mJktDJWzbqS23n1tsAf5QA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"orderedmap": "^2.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-schema-list": {
|
|
||||||
"version": "1.5.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz",
|
|
||||||
"integrity": "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-model": "^1.0.0",
|
|
||||||
"prosemirror-state": "^1.0.0",
|
|
||||||
"prosemirror-transform": "^1.7.3"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-state": {
|
|
||||||
"version": "1.4.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz",
|
|
||||||
"integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-model": "^1.0.0",
|
|
||||||
"prosemirror-transform": "^1.0.0",
|
|
||||||
"prosemirror-view": "^1.27.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-tables": {
|
|
||||||
"version": "1.8.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-tables/-/prosemirror-tables-1.8.5.tgz",
|
|
||||||
"integrity": "sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-keymap": "^1.2.3",
|
|
||||||
"prosemirror-model": "^1.25.4",
|
|
||||||
"prosemirror-state": "^1.4.4",
|
|
||||||
"prosemirror-transform": "^1.10.5",
|
|
||||||
"prosemirror-view": "^1.41.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-transform": {
|
|
||||||
"version": "1.12.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.0.tgz",
|
|
||||||
"integrity": "sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-model": "^1.21.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/prosemirror-view": {
|
|
||||||
"version": "1.41.8",
|
|
||||||
"resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.41.8.tgz",
|
|
||||||
"integrity": "sha512-TnKDdohEatgyZNGCDWIdccOHXhYloJwbwU+phw/a23KBvJIR9lWQWW7WHHK3vBdOLDNuF7TaX98GObUZOWkOnA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"prosemirror-model": "^1.20.0",
|
|
||||||
"prosemirror-state": "^1.0.0",
|
|
||||||
"prosemirror-transform": "^1.1.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/proxy-addr": {
|
"node_modules/proxy-addr": {
|
||||||
"version": "2.0.7",
|
"version": "2.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
||||||
@@ -9049,12 +8483,6 @@
|
|||||||
"node_modules/root": {
|
"node_modules/root": {
|
||||||
"resolved": "git+ssh://git@github.com/tanstack/react-query.git#9800c8f1a3f7907956410c23426a26d981e7d694"
|
"resolved": "git+ssh://git@github.com/tanstack/react-query.git#9800c8f1a3f7907956410c23426a26d981e7d694"
|
||||||
},
|
},
|
||||||
"node_modules/rope-sequence": {
|
|
||||||
"version": "1.3.4",
|
|
||||||
"resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz",
|
|
||||||
"integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/router": {
|
"node_modules/router": {
|
||||||
"version": "2.2.0",
|
"version": "2.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
|
||||||
@@ -9959,19 +9387,6 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vaul": {
|
|
||||||
"version": "1.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",
|
|
||||||
"integrity": "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@radix-ui/react-dialog": "^1.1.1"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",
|
|
||||||
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/victory-vendor": {
|
"node_modules/victory-vendor": {
|
||||||
"version": "37.3.6",
|
"version": "37.3.6",
|
||||||
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
|
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
|
||||||
@@ -10081,12 +9496,6 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/w3c-keyname": {
|
|
||||||
"version": "2.2.8",
|
|
||||||
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
|
|
||||||
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/web-streams-polyfill": {
|
"node_modules/web-streams-polyfill": {
|
||||||
"version": "3.3.3",
|
"version": "3.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
|
||||||
|
|||||||
+8
-11
@@ -18,12 +18,10 @@
|
|||||||
"@tailwindcss/container-queries": "^0.1.1",
|
"@tailwindcss/container-queries": "^0.1.1",
|
||||||
"@tanstack/react-query": "^5.100.8",
|
"@tanstack/react-query": "^5.100.8",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"@tiptap/extension-link": "^3.23.2",
|
|
||||||
"@tiptap/react": "^3.23.2",
|
|
||||||
"@tiptap/starter-kit": "^3.23.2",
|
|
||||||
"axios": "^1.15.2",
|
"axios": "^1.15.2",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"cn": "^0.3.2",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
"i18next": "^26.0.8",
|
"i18next": "^26.0.8",
|
||||||
"lucide-react": "^1.14.0",
|
"lucide-react": "^1.14.0",
|
||||||
@@ -41,7 +39,6 @@
|
|||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.5.0",
|
"tailwind-merge": "^3.5.0",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"vaul": "^1.1.2",
|
|
||||||
"zod": "^4.4.3",
|
"zod": "^4.4.3",
|
||||||
"zustand": "^5.0.12"
|
"zustand": "^5.0.12"
|
||||||
},
|
},
|
||||||
@@ -54,18 +51,18 @@
|
|||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.2.3",
|
||||||
"@vitejs/plugin-react": "^6.0.1",
|
"@vitejs/plugin-react": "^6.0.1",
|
||||||
"autoprefixer": "^10.5.0",
|
"autoprefixer": "^10.5.0",
|
||||||
|
"eslint": "^10.2.1",
|
||||||
|
"eslint-config-prettier": "^10.1.8",
|
||||||
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
|
"eslint-plugin-react-refresh": "^0.5.2",
|
||||||
|
"globals": "^17.5.0",
|
||||||
"husky": "^9.1.7",
|
"husky": "^9.1.7",
|
||||||
"lint-staged": "^16.4.0",
|
"lint-staged": "^16.4.0",
|
||||||
"postcss": "^8.5.13",
|
"postcss": "^8.5.13",
|
||||||
"prettier": "^3.8.3",
|
"prettier": "^3.8.3",
|
||||||
"tailwindcss": "^4.2.4",
|
"tailwindcss": "^4.2.4",
|
||||||
"typescript": "~6.0.2",
|
"typescript": "~6.0.2",
|
||||||
"vite": "^8.0.10",
|
"typescript-eslint": "^8.58.2",
|
||||||
"eslint": "^10.2.1",
|
"vite": "^8.0.10"
|
||||||
"eslint-config-prettier": "^10.1.8",
|
|
||||||
"eslint-plugin-react-hooks": "^7.1.1",
|
|
||||||
"eslint-plugin-react-refresh": "^0.5.2",
|
|
||||||
"globals": "^17.5.0",
|
|
||||||
"typescript-eslint": "^8.58.2"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,32 +1,32 @@
|
|||||||
import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from '@tanstack/react-query'
|
import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from "@tanstack/react-query";
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from "react";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import i18next from 'i18next'
|
import i18next from "i18next";
|
||||||
import { isAxiosError } from 'axios'
|
import { isAxiosError } from "axios";
|
||||||
|
|
||||||
function getErrorMessage(error: Error): string | undefined {
|
function getErrorMessage(error: Error): string | undefined {
|
||||||
if (isAxiosError(error)) return error.response?.data?.message
|
if (isAxiosError(error)) return error.response?.data?.message;
|
||||||
return error.message
|
return error.message;
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
export const queryClient = new QueryClient({
|
||||||
queryCache: new QueryCache({
|
queryCache: new QueryCache({
|
||||||
onError: (error, query) => {
|
onError: (error, query) => {
|
||||||
if (query.meta?.silent !== true) {
|
if (query.meta?.silent !== true) {
|
||||||
const serverMessage = getErrorMessage(error)
|
const serverMessage = getErrorMessage(error);
|
||||||
toast.error(serverMessage || i18next.t('errors.fetchFailed'), {
|
toast.error(serverMessage || i18next.t("errors.fetchFailed", "Maglumatlary ýükläp bolmady"), {
|
||||||
id: 'global-query-error',
|
id: "global-query-error",
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
mutationCache: new MutationCache({
|
mutationCache: new MutationCache({
|
||||||
onError: (error, _variables, _context, mutation) => {
|
onError: (error, _variables, _context, mutation) => {
|
||||||
if (mutation.meta?.silent !== true) {
|
if (mutation.meta?.silent !== true) {
|
||||||
const serverMessage = getErrorMessage(error)
|
const serverMessage = getErrorMessage(error);
|
||||||
toast.error(serverMessage || i18next.t('errors.actionFailed'), {
|
toast.error(serverMessage || i18next.t("errors.actionFailed", "Amaly ýerine ýetirip bolmady"), {
|
||||||
id: 'global-mutation-error',
|
id: "global-mutation-error",
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -35,8 +35,8 @@ const queryClient = new QueryClient({
|
|||||||
staleTime: 1000 * 60 * 5,
|
staleTime: 1000 * 60 * 5,
|
||||||
gcTime: 1000 * 60 * 10,
|
gcTime: 1000 * 60 * 10,
|
||||||
retry: (failureCount, error) => {
|
retry: (failureCount, error) => {
|
||||||
if (isAxiosError(error) && [401, 403, 404].includes(error.response?.status ?? 0)) return false
|
if (isAxiosError(error) && [401, 403, 404].includes(error.response?.status ?? 0)) return false;
|
||||||
return failureCount < 1
|
return failureCount < 1;
|
||||||
},
|
},
|
||||||
refetchOnWindowFocus: false,
|
refetchOnWindowFocus: false,
|
||||||
},
|
},
|
||||||
@@ -44,16 +44,12 @@ const queryClient = new QueryClient({
|
|||||||
retry: 0,
|
retry: 0,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
|
|
||||||
interface QueryProviderProps {
|
interface QueryProviderProps {
|
||||||
children: ReactNode
|
children: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function QueryProvider({ children }: QueryProviderProps) {
|
export function QueryProvider({ children }: QueryProviderProps) {
|
||||||
return (
|
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
|
||||||
<QueryClientProvider client={queryClient}>
|
}
|
||||||
{children}
|
|
||||||
</QueryClientProvider>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
+562
-499
File diff suppressed because it is too large.
Load diff
+80
-19
@@ -1,20 +1,59 @@
|
|||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
import { persist } from "zustand/middleware";
|
import { persist } from "zustand/middleware";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import type { ApiSuccessResponse } from "@/lib/api/client";
|
||||||
|
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||||
|
import { getDefaultHomePath } from "@/lib/auth/permissions";
|
||||||
|
import { queryClient } from "@/app/providers/QueryProvider";
|
||||||
|
|
||||||
|
export interface AuthUserRole {
|
||||||
|
id: number;
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
/** Scope determines data access level: own | branch | all */
|
||||||
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthUserBranch {
|
||||||
|
id: number;
|
||||||
|
uniqueCode: string;
|
||||||
|
name: LocalizedText;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Permission entry from GET /profile — now just { code, name } */
|
||||||
|
export interface AuthUserPermission {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AuthUser {
|
export interface AuthUser {
|
||||||
id: string;
|
id?: string | number;
|
||||||
name: string;
|
name: string;
|
||||||
email: string;
|
email?: string;
|
||||||
role: "admin" | "manager" | "viewer";
|
firstName?: string;
|
||||||
|
lastName?: string;
|
||||||
|
phone?: string;
|
||||||
|
role?: AuthUserRole;
|
||||||
avatar?: string;
|
avatar?: string;
|
||||||
|
branches?: AuthUserBranch[];
|
||||||
|
permissions?: AuthUserPermission[];
|
||||||
|
createdAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns the role-appropriate landing page for the current user. */
|
||||||
|
export function getHomePath(): string {
|
||||||
|
const user = useAuthStore.getState().user;
|
||||||
|
return getDefaultHomePath(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AuthState {
|
interface AuthState {
|
||||||
token: string | null;
|
token: string | null;
|
||||||
|
refreshTokenValue: string | null;
|
||||||
user: AuthUser | null;
|
user: AuthUser | null;
|
||||||
isAuthenticated: boolean;
|
isAuthenticated: boolean;
|
||||||
setAuth: (token: string, user: AuthUser) => void;
|
setAuth: (token: string, refreshTokenValue: string | null, user: AuthUser | null) => void;
|
||||||
|
setUser: (user: AuthUser) => void;
|
||||||
clearAuth: () => void;
|
clearAuth: () => void;
|
||||||
logout: () => void;
|
logout: () => void;
|
||||||
refreshToken: () => Promise<string>;
|
refreshToken: () => Promise<string>;
|
||||||
@@ -24,32 +63,54 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
persist(
|
persist(
|
||||||
(set, get) => ({
|
(set, get) => ({
|
||||||
token: null,
|
token: null,
|
||||||
|
refreshTokenValue: null,
|
||||||
user: null,
|
user: null,
|
||||||
isAuthenticated: false,
|
isAuthenticated: false,
|
||||||
|
|
||||||
setAuth: (token, user) => set({ token, user, isAuthenticated: true }),
|
setAuth: (token, refreshTokenValue, user) =>
|
||||||
|
set({
|
||||||
|
token,
|
||||||
|
refreshTokenValue: refreshTokenValue || get().refreshTokenValue,
|
||||||
|
user,
|
||||||
|
isAuthenticated: true,
|
||||||
|
}),
|
||||||
|
|
||||||
clearAuth: () => set({ token: null, user: null, isAuthenticated: false }),
|
setUser: (user) => set({ user }),
|
||||||
|
|
||||||
|
clearAuth: () => {
|
||||||
|
set({ token: null, refreshTokenValue: null, user: null, isAuthenticated: false });
|
||||||
|
queryClient.clear();
|
||||||
|
},
|
||||||
|
|
||||||
logout: () => {
|
logout: () => {
|
||||||
get().clearAuth();
|
get().clearAuth();
|
||||||
},
|
},
|
||||||
|
|
||||||
refreshToken: async () => {
|
refreshToken: async () => {
|
||||||
try {
|
const currentRefreshToken = get().refreshTokenValue;
|
||||||
const response = await axios.post<{ token: string }>(
|
if (!currentRefreshToken) {
|
||||||
`${import.meta.env.VITE_API_BASE_URL}/auth/refresh`,
|
get().clearAuth();
|
||||||
{},
|
throw new Error("No refresh token available");
|
||||||
{
|
}
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${get().token}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const newToken = response.data.token;
|
try {
|
||||||
set((state) => ({ ...state, token: newToken }));
|
const baseURL = import.meta.env.VITE_API_BASE_URL || "/api/admin";
|
||||||
return newToken;
|
const response = await axios.post<
|
||||||
|
ApiSuccessResponse<{
|
||||||
|
accessToken: string;
|
||||||
|
refreshToken: string;
|
||||||
|
}>
|
||||||
|
>(`${baseURL}/token`, { refreshToken: currentRefreshToken });
|
||||||
|
|
||||||
|
const { accessToken, refreshToken: newRefreshToken } = response.data.data;
|
||||||
|
|
||||||
|
if (!accessToken) {
|
||||||
|
throw new Error("Token refresh response missing accessToken");
|
||||||
|
}
|
||||||
|
|
||||||
|
set({ token: accessToken, refreshTokenValue: newRefreshToken });
|
||||||
|
|
||||||
|
return accessToken;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
get().clearAuth();
|
get().clearAuth();
|
||||||
throw error;
|
throw error;
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import { useRef, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { Upload, X, Loader2 } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { postFile, buildFileUrl } from "@/features/shared/api/sharedApi";
|
||||||
|
|
||||||
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface AvatarUploadProps {
|
||||||
|
label?: string;
|
||||||
|
value?: string;
|
||||||
|
onChange?: (url: string) => void;
|
||||||
|
error?: string;
|
||||||
|
required?: boolean;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── FieldLabel ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function FieldLabel({ label, required }: { label?: string; required?: boolean }) {
|
||||||
|
if (!label) return null;
|
||||||
|
return (
|
||||||
|
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 select-none">
|
||||||
|
{label}
|
||||||
|
{required && <span className="text-destructive ml-0.5">*</span>}
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── ErrorMsg ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function ErrorMsg({ error }: { error?: string }) {
|
||||||
|
if (!error) return null;
|
||||||
|
return (
|
||||||
|
<p className="mt-1.5 text-xs text-destructive font-medium flex items-center gap-1.5">
|
||||||
|
<span className="inline-block w-1 h-1 rounded-full bg-destructive shrink-0" />
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── AvatarUpload ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function AvatarUpload({ label, value, onChange, error, required, disabled }: AvatarUploadProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [dragOver, setDragOver] = useState(false);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [uploadError, setUploadError] = useState("");
|
||||||
|
|
||||||
|
const handleFile = async (file: File | null) => {
|
||||||
|
if (!file || disabled) return;
|
||||||
|
|
||||||
|
if (!file.type.startsWith("image/")) {
|
||||||
|
setUploadError(t("users.fields.avatarInvalid", "Diňe surat faýllary kabul edilýär"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setUploading(true);
|
||||||
|
setUploadError("");
|
||||||
|
try {
|
||||||
|
const filename = await postFile(file);
|
||||||
|
onChange?.(buildFileUrl(filename));
|
||||||
|
} catch {
|
||||||
|
setUploadError(t("users.fields.avatarUploadError", "Surat ýüklenip bilinmedi"));
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
if (inputRef.current) inputRef.current.value = "";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDrop = (e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(false);
|
||||||
|
handleFile(e.dataTransfer.files[0] ?? null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const effectiveError = error || uploadError;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<FieldLabel label={label} required={required} />
|
||||||
|
|
||||||
|
<div className="flex flex-col items-center gap-4">
|
||||||
|
{/* Preview — rounded, on top */}
|
||||||
|
<div className="w-26 h-26 rounded-full border border-border bg-muted/40 overflow-hidden shrink-0 flex items-center justify-center shadow-sm">
|
||||||
|
{value ? (
|
||||||
|
<img src={value} alt="avatar" className="w-full h-full object-cover" />
|
||||||
|
) : (
|
||||||
|
<Upload size={26} className="text-muted-foreground/60" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Upload zone — full width, below */}
|
||||||
|
<div className="w-full flex flex-col gap-2 min-w-0">
|
||||||
|
<div
|
||||||
|
role="button"
|
||||||
|
tabIndex={disabled ? -1 : 0}
|
||||||
|
onClick={() => !disabled && !uploading && inputRef.current?.click()}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && !disabled && !uploading && inputRef.current?.click()}
|
||||||
|
onDragOver={(e) => {
|
||||||
|
if (disabled) return;
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(true);
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setDragOver(false)}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center justify-center gap-2",
|
||||||
|
"min-h-20 rounded-md border-2 border-dashed cursor-pointer select-none px-4",
|
||||||
|
"transition-all duration-200 text-sm",
|
||||||
|
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||||
|
dragOver && "border-primary bg-primary/5 scale-[1.01]",
|
||||||
|
effectiveError ? "border-destructive/60" : "border-border",
|
||||||
|
!dragOver && !effectiveError && "hover:border-primary/50 hover:bg-muted/20",
|
||||||
|
(disabled || uploading) && "opacity-60 cursor-not-allowed pointer-events-none",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<>
|
||||||
|
<Loader2 size={16} className="animate-spin text-primary" />
|
||||||
|
<span className="text-muted-foreground">{t("users.fields.avatarUploading", "Ýüklenýär...")}</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Upload size={16} className="text-primary" />
|
||||||
|
<span className="text-foreground">{t("users.fields.avatarUpload", "Surat saýlaň")}</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{value && !disabled && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onChange?.("")}
|
||||||
|
className="flex items-center gap-1.5 text-xs text-destructive hover:text-destructive/80 transition-colors w-fit mx-auto"
|
||||||
|
>
|
||||||
|
<X size={12} />
|
||||||
|
{t("users.fields.avatarRemove", "Aýyr")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/*"
|
||||||
|
disabled={disabled || uploading}
|
||||||
|
onChange={(e) => handleFile(e.target.files?.[0] ?? null)}
|
||||||
|
className="hidden"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ErrorMsg error={effectiveError} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+192
-190
@@ -1,4 +1,5 @@
|
|||||||
import { useRef, useState } from 'react'
|
import { useRef, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
flexRender,
|
flexRender,
|
||||||
getCoreRowModel,
|
getCoreRowModel,
|
||||||
@@ -8,16 +9,9 @@ import {
|
|||||||
type RowSelectionState,
|
type RowSelectionState,
|
||||||
type SortingState,
|
type SortingState,
|
||||||
getSortedRowModel,
|
getSortedRowModel,
|
||||||
} from '@tanstack/react-table'
|
} from "@tanstack/react-table";
|
||||||
import {
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||||
Table,
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
TableBody,
|
|
||||||
TableCell,
|
|
||||||
TableHead,
|
|
||||||
TableHeader,
|
|
||||||
TableRow,
|
|
||||||
} from '@/components/ui/table'
|
|
||||||
import { Checkbox } from '@/components/ui/checkbox'
|
|
||||||
import {
|
import {
|
||||||
Pagination,
|
Pagination,
|
||||||
PaginationContent,
|
PaginationContent,
|
||||||
@@ -26,45 +20,42 @@ import {
|
|||||||
PaginationLink,
|
PaginationLink,
|
||||||
PaginationNext,
|
PaginationNext,
|
||||||
PaginationPrevious,
|
PaginationPrevious,
|
||||||
} from '@/components/ui/pagination'
|
} from "@/components/ui/pagination";
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from "@/lib/utils";
|
||||||
import { useOutsideClick } from '@/lib/hooks/useOutsideClick'
|
import { useOutsideClick } from "@/lib/hooks/useOutsideClick";
|
||||||
import { ChevronDown } from 'lucide-react'
|
import { ChevronDown, ArrowUp, ArrowDown, ArrowUpDown } from "lucide-react";
|
||||||
|
|
||||||
export type { ColumnDef }
|
export type { ColumnDef, SortingState };
|
||||||
|
|
||||||
// ─── Pagination ───────────────────────────────────────────────────────────────
|
// ─── Pagination ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
interface DataTablePaginationProps {
|
interface DataTablePaginationProps {
|
||||||
currentPage: number
|
currentPage: number;
|
||||||
totalPages: number
|
totalPages: number;
|
||||||
onPageChange: (page: number) => void
|
onPageChange: (page: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function DataTablePagination({
|
function DataTablePagination({ currentPage, totalPages, onPageChange }: DataTablePaginationProps) {
|
||||||
currentPage,
|
const { t } = useTranslation();
|
||||||
totalPages,
|
if (totalPages <= 1) return null;
|
||||||
onPageChange,
|
|
||||||
}: DataTablePaginationProps) {
|
|
||||||
if (totalPages <= 1) return null
|
|
||||||
|
|
||||||
const getPages = (): (number | 'ellipsis')[] => {
|
const getPages = (): (number | "ellipsis")[] => {
|
||||||
if (totalPages <= 7) return Array.from({ length: totalPages }, (_, i) => i + 1)
|
if (totalPages <= 7) return Array.from({ length: totalPages }, (_, i) => i + 1);
|
||||||
|
|
||||||
const pages: (number | 'ellipsis')[] = [1]
|
const pages: (number | "ellipsis")[] = [1];
|
||||||
|
|
||||||
if (currentPage > 3) pages.push('ellipsis')
|
if (currentPage > 3) pages.push("ellipsis");
|
||||||
|
|
||||||
const start = Math.max(2, currentPage - 1)
|
const start = Math.max(2, currentPage - 1);
|
||||||
const end = Math.min(totalPages - 1, currentPage + 1)
|
const end = Math.min(totalPages - 1, currentPage + 1);
|
||||||
|
|
||||||
for (let i = start; i <= end; i++) pages.push(i)
|
for (let i = start; i <= end; i++) pages.push(i);
|
||||||
|
|
||||||
if (currentPage < totalPages - 2) pages.push('ellipsis')
|
if (currentPage < totalPages - 2) pages.push("ellipsis");
|
||||||
|
|
||||||
pages.push(totalPages)
|
pages.push(totalPages);
|
||||||
return pages
|
return pages;
|
||||||
}
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Pagination className="justify-center mt-3">
|
<Pagination className="justify-center mt-3">
|
||||||
@@ -72,16 +63,17 @@ function DataTablePagination({
|
|||||||
<PaginationItem>
|
<PaginationItem>
|
||||||
<PaginationPrevious
|
<PaginationPrevious
|
||||||
href="#"
|
href="#"
|
||||||
|
text={t("pagination.previous", t("Previous", "Öňki"))}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
if (currentPage > 1) onPageChange(currentPage - 1)
|
if (currentPage > 1) onPageChange(currentPage - 1);
|
||||||
}}
|
}}
|
||||||
className={cn(currentPage === 1 && 'pointer-events-none opacity-40')}
|
className={cn(currentPage === 1 && "pointer-events-none opacity-40")}
|
||||||
/>
|
/>
|
||||||
</PaginationItem>
|
</PaginationItem>
|
||||||
|
|
||||||
{getPages().map((page, i) =>
|
{getPages().map((page, i) =>
|
||||||
page === 'ellipsis' ? (
|
page === "ellipsis" ? (
|
||||||
<PaginationItem key={`ellipsis-${i}`}>
|
<PaginationItem key={`ellipsis-${i}`}>
|
||||||
<PaginationEllipsis />
|
<PaginationEllipsis />
|
||||||
</PaginationItem>
|
</PaginationItem>
|
||||||
@@ -91,43 +83,44 @@ function DataTablePagination({
|
|||||||
href="#"
|
href="#"
|
||||||
isActive={page === currentPage}
|
isActive={page === currentPage}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
onPageChange(page)
|
onPageChange(page);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{page}
|
{page}
|
||||||
</PaginationLink>
|
</PaginationLink>
|
||||||
</PaginationItem>
|
</PaginationItem>
|
||||||
)
|
),
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<PaginationItem>
|
<PaginationItem>
|
||||||
<PaginationNext
|
<PaginationNext
|
||||||
href="#"
|
href="#"
|
||||||
|
text={t("pagination.next", t("Next", "Indiki"))}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
if (currentPage < totalPages) onPageChange(currentPage + 1)
|
if (currentPage < totalPages) onPageChange(currentPage + 1);
|
||||||
}}
|
}}
|
||||||
className={cn(currentPage === totalPages && 'pointer-events-none opacity-40')}
|
className={cn(currentPage === totalPages && "pointer-events-none opacity-40")}
|
||||||
/>
|
/>
|
||||||
</PaginationItem>
|
</PaginationItem>
|
||||||
</PaginationContent>
|
</PaginationContent>
|
||||||
</Pagination>
|
</Pagination>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Select All Dropdown ──────────────────────────────────────────────────────
|
// ─── Select All Dropdown ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
interface SelectAllDropdownProps {
|
interface SelectAllDropdownProps {
|
||||||
isAllPageSelected: boolean
|
isAllPageSelected: boolean;
|
||||||
isSomePageSelected: boolean
|
isSomePageSelected: boolean;
|
||||||
isAllTotalSelected: boolean
|
isAllTotalSelected: boolean;
|
||||||
totalCount: number
|
totalCount: number;
|
||||||
pageCount: number
|
pageCount: number;
|
||||||
onTogglePage: (checked: boolean) => void
|
onTogglePage: (checked: boolean) => void;
|
||||||
onSelectThisPage: () => void
|
onSelectThisPage: () => void;
|
||||||
onSelectAll: () => void
|
onSelectAll: () => void;
|
||||||
onClearAll: () => void
|
onClearAll: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SelectAllDropdown({
|
function SelectAllDropdown({
|
||||||
@@ -141,15 +134,11 @@ function SelectAllDropdown({
|
|||||||
onSelectAll,
|
onSelectAll,
|
||||||
onClearAll,
|
onClearAll,
|
||||||
}: SelectAllDropdownProps) {
|
}: SelectAllDropdownProps) {
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false);
|
||||||
const ref = useRef<HTMLDivElement>(null)
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
useOutsideClick(ref, () => setOpen(false))
|
useOutsideClick(ref, () => setOpen(false));
|
||||||
|
|
||||||
const checkboxChecked = isAllTotalSelected || isAllPageSelected
|
const checkboxChecked = isAllTotalSelected || isAllPageSelected ? true : isSomePageSelected ? "indeterminate" : false;
|
||||||
? true
|
|
||||||
: isSomePageSelected
|
|
||||||
? 'indeterminate'
|
|
||||||
: false
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className="flex items-center gap-1">
|
<div ref={ref} className="flex items-center gap-1">
|
||||||
@@ -163,9 +152,9 @@ function SelectAllDropdown({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
e.stopPropagation()
|
e.stopPropagation();
|
||||||
setOpen((v) => !v)
|
setOpen((v) => !v);
|
||||||
}}
|
}}
|
||||||
className="relative z-10 flex items-center justify-center w-5 h-5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors rounded"
|
className="relative z-10 flex items-center justify-center w-5 h-5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors rounded"
|
||||||
aria-label="Selection options"
|
aria-label="Selection options"
|
||||||
@@ -178,10 +167,10 @@ function SelectAllDropdown({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
e.stopPropagation()
|
e.stopPropagation();
|
||||||
onSelectThisPage()
|
onSelectThisPage();
|
||||||
setOpen(false)
|
setOpen(false);
|
||||||
}}
|
}}
|
||||||
className="w-full text-left px-3 py-2 text-sm hover:bg-muted/50 transition-colors"
|
className="w-full text-left px-3 py-2 text-sm hover:bg-muted/50 transition-colors"
|
||||||
>
|
>
|
||||||
@@ -191,10 +180,10 @@ function SelectAllDropdown({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
e.stopPropagation()
|
e.stopPropagation();
|
||||||
onSelectAll()
|
onSelectAll();
|
||||||
setOpen(false)
|
setOpen(false);
|
||||||
}}
|
}}
|
||||||
className="w-full text-left px-3 py-2 text-sm hover:bg-muted/50 transition-colors"
|
className="w-full text-left px-3 py-2 text-sm hover:bg-muted/50 transition-colors"
|
||||||
>
|
>
|
||||||
@@ -207,10 +196,10 @@ function SelectAllDropdown({
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
e.stopPropagation()
|
e.stopPropagation();
|
||||||
onClearAll()
|
onClearAll();
|
||||||
setOpen(false)
|
setOpen(false);
|
||||||
}}
|
}}
|
||||||
className="w-full text-left px-3 py-2 text-sm text-destructive hover:bg-destructive/10 transition-colors"
|
className="w-full text-left px-3 py-2 text-sm text-destructive hover:bg-destructive/10 transition-colors"
|
||||||
>
|
>
|
||||||
@@ -221,31 +210,37 @@ function SelectAllDropdown({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── DataTable ────────────────────────────────────────────────────────────────
|
// ─── DataTable ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
interface DataTableProps<TData> {
|
interface DataTableProps<TData> {
|
||||||
columns: ColumnDef<TData>[]
|
columns: ColumnDef<TData>[];
|
||||||
data: TData[]
|
data: TData[];
|
||||||
isLoading?: boolean
|
isLoading?: boolean;
|
||||||
columnVisibility?: VisibilityState
|
columnVisibility?: VisibilityState;
|
||||||
onColumnVisibilityChange?: (visibility: VisibilityState) => void
|
onColumnVisibilityChange?: (visibility: VisibilityState) => void;
|
||||||
columnOrder?: string[]
|
columnOrder?: string[];
|
||||||
onColumnOrderChange?: (order: string[]) => void
|
onColumnOrderChange?: (order: string[]) => void;
|
||||||
enableRowSelection?: boolean
|
enableRowSelection?: boolean;
|
||||||
onRowSelectionChange?: (rows: TData[]) => void
|
onRowSelectionChange?: (rows: TData[]) => void;
|
||||||
getRowId?: (row: TData) => string
|
getRowId?: (row: TData) => string;
|
||||||
|
|
||||||
|
// Sorting — manual / server-side
|
||||||
|
sorting?: SortingState;
|
||||||
|
onSortingChange?: (updater: SortingState | ((prev: SortingState) => SortingState)) => void;
|
||||||
|
manualSorting?: boolean;
|
||||||
|
|
||||||
// Pagination — server-side
|
// Pagination — server-side
|
||||||
currentPage?: number
|
currentPage?: number;
|
||||||
totalPages?: number
|
totalPages?: number;
|
||||||
totalCount?: number
|
totalCount?: number;
|
||||||
onPageChange?: (page: number) => void
|
onPageChange?: (page: number) => void;
|
||||||
|
|
||||||
// Optional content rendered above the table (e.g. month selector)
|
// Optional content rendered above the table (e.g. month selector)
|
||||||
headerContent?: React.ReactNode
|
headerContent?: React.ReactNode;
|
||||||
|
toolbar?: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DataTable<TData>({
|
export function DataTable<TData>({
|
||||||
@@ -259,22 +254,29 @@ export function DataTable<TData>({
|
|||||||
enableRowSelection = false,
|
enableRowSelection = false,
|
||||||
onRowSelectionChange,
|
onRowSelectionChange,
|
||||||
getRowId,
|
getRowId,
|
||||||
|
sorting,
|
||||||
|
onSortingChange,
|
||||||
|
manualSorting,
|
||||||
currentPage = 1,
|
currentPage = 1,
|
||||||
totalPages = 1,
|
totalPages = 1,
|
||||||
totalCount,
|
totalCount,
|
||||||
onPageChange,
|
onPageChange,
|
||||||
headerContent,
|
headerContent,
|
||||||
|
toolbar,
|
||||||
}: DataTableProps<TData>) {
|
}: DataTableProps<TData>) {
|
||||||
const [sorting, setSorting] = useState<SortingState>([])
|
const [internalSorting, setInternalSorting] = useState<SortingState>([]);
|
||||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
const effectiveSorting = sorting !== undefined ? sorting : internalSorting;
|
||||||
// Tracks whether ALL records (across pages) are logically selected
|
const effectiveOnSortingChange = onSortingChange !== undefined ? onSortingChange : setInternalSorting;
|
||||||
const [allTotalSelected, setAllTotalSelected] = useState(false)
|
|
||||||
|
|
||||||
const resolvedTotalCount = totalCount ?? data.length
|
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
|
||||||
|
// Tracks whether ALL records (across pages) are logically selected
|
||||||
|
const [allTotalSelected, setAllTotalSelected] = useState(false);
|
||||||
|
|
||||||
|
const resolvedTotalCount = totalCount ?? data.length;
|
||||||
|
|
||||||
// ── Build selection column ──────────────────────────────────────────────────
|
// ── Build selection column ──────────────────────────────────────────────────
|
||||||
const selectionColumn: ColumnDef<TData> = {
|
const selectionColumn: ColumnDef<TData> = {
|
||||||
id: 'select',
|
id: "select",
|
||||||
header: ({ table }) => (
|
header: ({ table }) => (
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<SelectAllDropdown
|
<SelectAllDropdown
|
||||||
@@ -285,123 +287,115 @@ export function DataTable<TData>({
|
|||||||
pageCount={data.length}
|
pageCount={data.length}
|
||||||
onTogglePage={(checked) => {
|
onTogglePage={(checked) => {
|
||||||
if (!checked) {
|
if (!checked) {
|
||||||
if (allTotalSelected) setAllTotalSelected(false)
|
if (allTotalSelected) setAllTotalSelected(false);
|
||||||
table.toggleAllPageRowsSelected(false)
|
table.toggleAllPageRowsSelected(false);
|
||||||
table.setRowSelection({})
|
table.setRowSelection({});
|
||||||
} else {
|
} else {
|
||||||
table.toggleAllPageRowsSelected(true)
|
table.toggleAllPageRowsSelected(true);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
onSelectThisPage={() => {
|
onSelectThisPage={() => {
|
||||||
table.toggleAllPageRowsSelected(true)
|
table.toggleAllPageRowsSelected(true);
|
||||||
setAllTotalSelected(false)
|
setAllTotalSelected(false);
|
||||||
}}
|
}}
|
||||||
onSelectAll={() => {
|
onSelectAll={() => {
|
||||||
table.toggleAllPageRowsSelected(true)
|
table.toggleAllPageRowsSelected(true);
|
||||||
setAllTotalSelected(true)
|
setAllTotalSelected(true);
|
||||||
}}
|
}}
|
||||||
onClearAll={() => {
|
onClearAll={() => {
|
||||||
table.toggleAllPageRowsSelected(false)
|
table.toggleAllPageRowsSelected(false);
|
||||||
table.setRowSelection({})
|
table.setRowSelection({});
|
||||||
setAllTotalSelected(false)
|
setAllTotalSelected(false);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
cell: ({ row, table }) => {
|
cell: ({ row, table }) => {
|
||||||
const isSelected = allTotalSelected || row.getIsSelected()
|
const isSelected = allTotalSelected || row.getIsSelected();
|
||||||
return (
|
return (
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={isSelected}
|
checked={isSelected}
|
||||||
onCheckedChange={(value) => {
|
onCheckedChange={(value) => {
|
||||||
if (allTotalSelected && !value) {
|
if (allTotalSelected && !value) {
|
||||||
const newSelection: RowSelectionState = {}
|
const newSelection: RowSelectionState = {};
|
||||||
table.getRowModel().rows.forEach((r) => {
|
table.getRowModel().rows.forEach((r) => {
|
||||||
if (r.id !== row.id) {
|
if (r.id !== row.id) {
|
||||||
newSelection[r.id] = true
|
newSelection[r.id] = true;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
table.setRowSelection(newSelection)
|
table.setRowSelection(newSelection);
|
||||||
setAllTotalSelected(false)
|
setAllTotalSelected(false);
|
||||||
} else {
|
} else {
|
||||||
row.toggleSelected(!!value)
|
row.toggleSelected(!!value);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
aria-label="Select row"
|
aria-label="Select row"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
},
|
},
|
||||||
enableSorting: false,
|
enableSorting: false,
|
||||||
enableHiding: false,
|
enableHiding: false,
|
||||||
size: 48,
|
size: 48,
|
||||||
}
|
};
|
||||||
|
|
||||||
const allColumns: ColumnDef<TData>[] = enableRowSelection
|
const allColumns: ColumnDef<TData>[] = enableRowSelection ? [selectionColumn, ...columns] : columns;
|
||||||
? [selectionColumn, ...columns]
|
|
||||||
: columns
|
|
||||||
|
|
||||||
const effectiveColumnOrder: string[] = enableRowSelection
|
const effectiveColumnOrder: string[] = enableRowSelection
|
||||||
? columnOrder && columnOrder.length > 0
|
? columnOrder && columnOrder.length > 0
|
||||||
? columnOrder[0] === 'select'
|
? columnOrder[0] === "select"
|
||||||
? columnOrder
|
? columnOrder
|
||||||
: ['select', ...columnOrder.filter((id) => id !== 'select')]
|
: ["select", ...columnOrder.filter((id) => id !== "select")]
|
||||||
: []
|
: []
|
||||||
: (columnOrder ?? [])
|
: (columnOrder ?? []);
|
||||||
|
|
||||||
const table = useReactTable({
|
const table = useReactTable({
|
||||||
data,
|
data,
|
||||||
columns: allColumns,
|
columns: allColumns,
|
||||||
state: {
|
state: {
|
||||||
sorting,
|
sorting: effectiveSorting,
|
||||||
rowSelection,
|
rowSelection,
|
||||||
columnVisibility: columnVisibility ?? {},
|
columnVisibility: columnVisibility ?? {},
|
||||||
columnOrder: effectiveColumnOrder,
|
columnOrder: effectiveColumnOrder,
|
||||||
},
|
},
|
||||||
|
manualSorting,
|
||||||
getRowId,
|
getRowId,
|
||||||
enableRowSelection,
|
enableRowSelection,
|
||||||
onRowSelectionChange: (updater) => {
|
onRowSelectionChange: (updater) => {
|
||||||
const newSelection =
|
const newSelection = typeof updater === "function" ? updater(rowSelection) : updater;
|
||||||
typeof updater === 'function' ? updater(rowSelection) : updater
|
setRowSelection(newSelection);
|
||||||
setRowSelection(newSelection)
|
|
||||||
// If deselecting anything, clear allTotalSelected
|
// If deselecting anything, clear allTotalSelected
|
||||||
if (Object.keys(newSelection).length < data.length) {
|
if (Object.keys(newSelection).length < data.length) {
|
||||||
setAllTotalSelected(false)
|
setAllTotalSelected(false);
|
||||||
}
|
}
|
||||||
if (onRowSelectionChange) {
|
if (onRowSelectionChange) {
|
||||||
const selectedRows = data.filter((_, index) =>
|
const selectedRows = data.filter((_, index) => newSelection[getRowId ? getRowId(data[index]) : String(index)]);
|
||||||
newSelection[getRowId ? getRowId(data[index]) : String(index)]
|
onRowSelectionChange(selectedRows);
|
||||||
)
|
|
||||||
onRowSelectionChange(selectedRows)
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onSortingChange: setSorting,
|
onSortingChange: effectiveOnSortingChange,
|
||||||
onColumnVisibilityChange: (updater) => {
|
onColumnVisibilityChange: (updater) => {
|
||||||
if (!onColumnVisibilityChange) return
|
if (!onColumnVisibilityChange) return;
|
||||||
const next =
|
const next = typeof updater === "function" ? updater(columnVisibility ?? {}) : updater;
|
||||||
typeof updater === 'function' ? updater(columnVisibility ?? {}) : updater
|
onColumnVisibilityChange(next);
|
||||||
onColumnVisibilityChange(next)
|
|
||||||
},
|
},
|
||||||
onColumnOrderChange: (updater) => {
|
onColumnOrderChange: (updater) => {
|
||||||
if (!onColumnOrderChange) return
|
if (!onColumnOrderChange) return;
|
||||||
const next =
|
const next = typeof updater === "function" ? updater(columnOrder ?? []) : updater;
|
||||||
typeof updater === 'function' ? updater(columnOrder ?? []) : updater
|
onColumnOrderChange(next);
|
||||||
onColumnOrderChange(next)
|
|
||||||
},
|
},
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
getSortedRowModel: getSortedRowModel(),
|
getSortedRowModel: manualSorting ? undefined : getSortedRowModel(),
|
||||||
})
|
});
|
||||||
|
|
||||||
// ── Selection banner ────────────────────────────────────────────────────────
|
// ── Selection banner ────────────────────────────────────────────────────────
|
||||||
const selectedCount = Object.keys(rowSelection).length
|
const selectedCount = Object.keys(rowSelection).length;
|
||||||
const showBanner = enableRowSelection && (selectedCount > 0 || allTotalSelected)
|
const showBanner = enableRowSelection && (selectedCount > 0 || allTotalSelected);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-0">
|
<div className="space-y-0 bg-sidebar">
|
||||||
{/* Header content (e.g. month selector) */}
|
{/* Header content (e.g. month selector) */}
|
||||||
{headerContent && (
|
{headerContent && <div className="mb-3">{headerContent}</div>}
|
||||||
<div className="mb-3">{headerContent}</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Selection banner */}
|
{/* Selection banner */}
|
||||||
{showBanner && (
|
{showBanner && (
|
||||||
@@ -409,13 +403,13 @@ export function DataTable<TData>({
|
|||||||
<span className="text-primary font-medium">
|
<span className="text-primary font-medium">
|
||||||
{allTotalSelected
|
{allTotalSelected
|
||||||
? `All ${resolvedTotalCount} records selected`
|
? `All ${resolvedTotalCount} records selected`
|
||||||
: `${selectedCount} row${selectedCount !== 1 ? 's' : ''} selected`}
|
: `${selectedCount} row${selectedCount !== 1 ? "s" : ""} selected`}
|
||||||
</span>
|
</span>
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
table.toggleAllPageRowsSelected(false)
|
table.toggleAllPageRowsSelected(false);
|
||||||
table.setRowSelection({})
|
table.setRowSelection({});
|
||||||
setAllTotalSelected(false)
|
setAllTotalSelected(false);
|
||||||
}}
|
}}
|
||||||
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
|
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||||
>
|
>
|
||||||
@@ -425,33 +419,44 @@ export function DataTable<TData>({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Table */}
|
{/* Table */}
|
||||||
<div
|
<div className={cn("border border-border overflow-hidden", showBanner ? "rounded-b-lg rounded-t-none" : "rounded-md")}>
|
||||||
className={cn(
|
{toolbar && <div className="flex items-end justify-end gap-3 px-3 py-2.5 border-b border-border bg-muted/20">{toolbar}</div>}
|
||||||
'border border-border overflow-hidden',
|
|
||||||
showBanner ? 'rounded-b-lg rounded-t-none' : 'rounded-md'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
{table.getHeaderGroups().map((headerGroup) => (
|
{table.getHeaderGroups().map((headerGroup) => (
|
||||||
<TableRow key={headerGroup.id} className="bg-muted/40 hover:bg-muted/40">
|
<TableRow key={headerGroup.id} className="bg-muted/40 hover:bg-muted/40">
|
||||||
{headerGroup.headers.map((header) => (
|
{headerGroup.headers.map((header) => {
|
||||||
<TableHead
|
const canSort = header.column.getCanSort();
|
||||||
key={header.id}
|
const sortDir = header.column.getIsSorted();
|
||||||
style={{
|
return (
|
||||||
width: header.getSize() !== 150 ? header.getSize() : undefined,
|
<TableHead
|
||||||
}}
|
key={header.id}
|
||||||
className={cn(
|
style={{
|
||||||
'text-xs font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap',
|
width: header.getSize() !== 150 ? header.getSize() : undefined,
|
||||||
header.column.getCanSort() && 'cursor-pointer select-none'
|
}}
|
||||||
)}
|
className={cn(
|
||||||
onClick={header.column.getToggleSortingHandler()}
|
"text-xs font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap",
|
||||||
>
|
canSort && "cursor-pointer select-none hover:text-foreground",
|
||||||
{header.isPlaceholder
|
)}
|
||||||
? null
|
onClick={header.column.getToggleSortingHandler()}
|
||||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
>
|
||||||
</TableHead>
|
<div className="flex items-center gap-1.5">
|
||||||
))}
|
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||||
|
{canSort && (
|
||||||
|
<span className="inline-flex shrink-0">
|
||||||
|
{sortDir === "asc" ? (
|
||||||
|
<ArrowUp className="size-3 text-primary" />
|
||||||
|
) : sortDir === "desc" ? (
|
||||||
|
<ArrowDown className="size-3 text-primary" />
|
||||||
|
) : (
|
||||||
|
<ArrowUpDown className="size-3 text-muted-foreground/30" />
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TableHead>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
@@ -468,10 +473,7 @@ export function DataTable<TData>({
|
|||||||
))
|
))
|
||||||
) : table.getRowModel().rows.length === 0 ? (
|
) : table.getRowModel().rows.length === 0 ? (
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableCell
|
<TableCell colSpan={allColumns.length} className="text-center py-16 text-muted-foreground">
|
||||||
colSpan={allColumns.length}
|
|
||||||
className="text-center py-16 text-muted-foreground"
|
|
||||||
>
|
|
||||||
No data found
|
No data found
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
@@ -479,7 +481,7 @@ export function DataTable<TData>({
|
|||||||
table.getRowModel().rows.map((row) => (
|
table.getRowModel().rows.map((row) => (
|
||||||
<TableRow
|
<TableRow
|
||||||
key={row.id}
|
key={row.id}
|
||||||
data-state={row.getIsSelected() ? 'selected' : undefined}
|
data-state={row.getIsSelected() ? "selected" : undefined}
|
||||||
className="hover:bg-muted/30 transition-colors border-border"
|
className="hover:bg-muted/30 transition-colors border-border"
|
||||||
>
|
>
|
||||||
{row.getVisibleCells().map((cell) => (
|
{row.getVisibleCells().map((cell) => (
|
||||||
@@ -502,13 +504,13 @@ export function DataTable<TData>({
|
|||||||
onPageChange={(page) => {
|
onPageChange={(page) => {
|
||||||
// Clear selection on page change (server-side pattern)
|
// Clear selection on page change (server-side pattern)
|
||||||
if (!allTotalSelected) {
|
if (!allTotalSelected) {
|
||||||
table.toggleAllPageRowsSelected(false)
|
table.toggleAllPageRowsSelected(false);
|
||||||
setRowSelection({})
|
setRowSelection({});
|
||||||
}
|
}
|
||||||
onPageChange(page)
|
onPageChange(page);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
@@ -8,6 +8,7 @@ import { TableSearchInput } from "@/components/tableSearch";
|
|||||||
import { CreateButton } from "@/components/createButton";
|
import { CreateButton } from "@/components/createButton";
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
|
import { InfiniteSelect } from "@/components/infiniteSelect";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -19,7 +20,18 @@ export interface ColumnMeta {
|
|||||||
export interface FilterField {
|
export interface FilterField {
|
||||||
id: string;
|
id: string;
|
||||||
label: string;
|
label: string;
|
||||||
options: { value: string; label: string }[];
|
type?: "select" | "text" | "infinite-select";
|
||||||
|
options?: { value: string; label: string }[];
|
||||||
|
|
||||||
|
// Infinite Select props
|
||||||
|
loading?: boolean;
|
||||||
|
isLoadingMore?: boolean;
|
||||||
|
hasNextPage?: boolean;
|
||||||
|
onLoadMore?: () => void;
|
||||||
|
searchValue?: string;
|
||||||
|
onSearchChange?: (value: string) => void;
|
||||||
|
searchPlaceholder?: string;
|
||||||
|
disabled?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ActiveFilter {
|
export interface ActiveFilter {
|
||||||
@@ -53,6 +65,8 @@ interface DataTableToolbarProps {
|
|||||||
hideSearch?: boolean;
|
hideSearch?: boolean;
|
||||||
hideAction?: boolean;
|
hideAction?: boolean;
|
||||||
|
|
||||||
|
onFilterOpenChange?: (open: boolean) => void;
|
||||||
|
|
||||||
extraActions?: React.ReactNode;
|
extraActions?: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,7 +179,7 @@ function ToggleColumnsDropdown({
|
|||||||
id={`col-toggle-${col.id}`}
|
id={`col-toggle-${col.id}`}
|
||||||
checked={isVisible(col.id)}
|
checked={isVisible(col.id)}
|
||||||
onChange={() => toggle(col.id)}
|
onChange={() => toggle(col.id)}
|
||||||
className="w-4 h-4 rounded cursor-pointer accent-[#005f78] dark:accent-primary"
|
className="w-4 h-4 rounded cursor-pointer accent-[#18b69b] dark:accent-primary"
|
||||||
/>
|
/>
|
||||||
<label htmlFor={`col-toggle-${col.id}`} className="text-sm text-foreground cursor-pointer flex-1 truncate select-none">
|
<label htmlFor={`col-toggle-${col.id}`} className="text-sm text-foreground cursor-pointer flex-1 truncate select-none">
|
||||||
{col.label}
|
{col.label}
|
||||||
@@ -188,6 +202,7 @@ interface FilterDropdownProps {
|
|||||||
perPageOptions?: number[];
|
perPageOptions?: number[];
|
||||||
perPage?: number;
|
perPage?: number;
|
||||||
onPerPageChange?: (value: number) => void;
|
onPerPageChange?: (value: number) => void;
|
||||||
|
onFilterOpenChange?: (open: boolean) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function FilterDropdown({
|
function FilterDropdown({
|
||||||
@@ -198,17 +213,23 @@ function FilterDropdown({
|
|||||||
perPageOptions = [10, 25, 50, 100],
|
perPageOptions = [10, 25, 50, 100],
|
||||||
perPage = 25,
|
perPage = 25,
|
||||||
onPerPageChange,
|
onPerPageChange,
|
||||||
|
onFilterOpenChange,
|
||||||
}: FilterDropdownProps) {
|
}: FilterDropdownProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
const handleOpenChange = (nextOpen: boolean) => {
|
||||||
|
setOpen(nextOpen);
|
||||||
|
onFilterOpenChange?.(nextOpen);
|
||||||
|
};
|
||||||
|
|
||||||
const activeCount = activeFilters.filter((f) => f.value !== "").length;
|
const activeCount = activeFilters.filter((f) => f.value !== "").length;
|
||||||
const hasActive = activeCount > 0;
|
const hasActive = activeCount > 0;
|
||||||
|
|
||||||
const getActiveValue = (fieldId: string) => activeFilters.find((f) => f.fieldId === fieldId)?.value ?? "";
|
const getActiveValue = (fieldId: string) => activeFilters.find((f) => f.fieldId === fieldId)?.value ?? "";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<Popover open={open} onOpenChange={handleOpenChange}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<button
|
<button
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -229,14 +250,14 @@ function FilterDropdown({
|
|||||||
</button>
|
</button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
|
|
||||||
<PopoverContent align="end" sideOffset={4} className="w-64 p-0">
|
<PopoverContent align="end" sideOffset={4} className="w-64 p-0 max-h-(--radix-popover-content-available-height) flex flex-col">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex items-center justify-between px-3 py-2 border-b border-border">
|
<div className="flex items-center justify-between px-3 py-2 border-b border-border">
|
||||||
<p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">{t("table.filters", "Filters")}</p>
|
<p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">{t("table.filters", "Filters")}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Fields */}
|
{/* Fields */}
|
||||||
<div className="px-3 py-3 space-y-3">
|
<div className="px-3 py-3 space-y-3 overflow-y-auto">
|
||||||
{filterFields.map((field) => {
|
{filterFields.map((field) => {
|
||||||
const current = getActiveValue(field.id);
|
const current = getActiveValue(field.id);
|
||||||
const isFieldActive = current !== "";
|
const isFieldActive = current !== "";
|
||||||
@@ -246,37 +267,82 @@ function FilterDropdown({
|
|||||||
<label className="block text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">{field.label}</label>
|
<label className="block text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">{field.label}</label>
|
||||||
|
|
||||||
<div className="flex items-center gap-1">
|
<div className="flex items-center gap-1">
|
||||||
<Select value={current || "__all__"} onValueChange={(val) => onFilterChange(field.id, val === "__all__" ? "" : val)}>
|
{field.type === "text" ? (
|
||||||
<SelectTrigger
|
<>
|
||||||
className={cn(
|
<input
|
||||||
"h-8 flex-1 text-sm gap-1.5 transition-colors",
|
type="text"
|
||||||
isFieldActive ? "border-primary text-primary [&>svg:last-child]:text-primary" : "text-muted-foreground",
|
value={current}
|
||||||
|
onChange={(e) => onFilterChange(field.id, e.target.value)}
|
||||||
|
placeholder="—"
|
||||||
|
className={cn(
|
||||||
|
"h-8 flex-1 rounded-md border border-input bg-background px-2.5 text-sm text-foreground",
|
||||||
|
"placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-ring",
|
||||||
|
"transition-colors",
|
||||||
|
isFieldActive && "border-primary",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{isFieldActive && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onFilterChange(field.id, "")}
|
||||||
|
className="h-6 w-6 rounded flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors shrink-0"
|
||||||
|
>
|
||||||
|
<X size={11} />
|
||||||
|
</button>
|
||||||
)}
|
)}
|
||||||
>
|
</>
|
||||||
<span className="flex-1 text-left truncate">
|
) : field.type === "infinite-select" ? (
|
||||||
{isFieldActive ? field.options.find((o) => o.value === current)?.label : "—"}
|
<div className="flex-1 min-w-0">
|
||||||
</span>
|
<InfiniteSelect
|
||||||
</SelectTrigger>
|
value={current}
|
||||||
<SelectContent position="popper" sideOffset={4} className="p-1">
|
onChange={(val) => onFilterChange(field.id, val)}
|
||||||
<SelectItem value="__all__">
|
options={field.options}
|
||||||
<span className="text-muted-foreground">— Ählisi</span>
|
placeholder="—"
|
||||||
</SelectItem>
|
searchPlaceholder={field.searchPlaceholder || t("common.search", "Gözle...")}
|
||||||
{field.options.map((opt) => (
|
disabled={field.disabled}
|
||||||
<SelectItem key={opt.value} value={opt.value}>
|
loading={field.loading}
|
||||||
{opt.label}
|
isLoadingMore={field.isLoadingMore}
|
||||||
</SelectItem>
|
hasNextPage={field.hasNextPage}
|
||||||
))}
|
onLoadMore={field.onLoadMore}
|
||||||
</SelectContent>
|
searchValue={field.searchValue}
|
||||||
</Select>
|
onSearchChange={field.onSearchChange}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Select value={current || "__all__"} onValueChange={(val) => onFilterChange(field.id, val === "__all__" ? "" : val)}>
|
||||||
|
<SelectTrigger
|
||||||
|
className={cn(
|
||||||
|
"h-8 flex-1 text-sm gap-1.5 transition-colors",
|
||||||
|
isFieldActive ? "border-primary text-primary [&>svg:last-child]:text-primary" : "text-muted-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className="flex-1 text-left truncate">
|
||||||
|
{isFieldActive ? (field.options ?? []).find((o) => o.value === current)?.label : "—"}
|
||||||
|
</span>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent position="popper" sideOffset={4} className="p-1">
|
||||||
|
<SelectItem value="__all__">
|
||||||
|
<span className="text-muted-foreground">— Ählisi</span>
|
||||||
|
</SelectItem>
|
||||||
|
{(field.options ?? []).map((opt) => (
|
||||||
|
<SelectItem key={opt.value} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
|
||||||
{isFieldActive && (
|
{isFieldActive && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => onFilterChange(field.id, "")}
|
onClick={() => onFilterChange(field.id, "")}
|
||||||
className="h-6 w-6 rounded flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors shrink-0"
|
className="h-6 w-6 rounded flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors shrink-0"
|
||||||
>
|
>
|
||||||
<X size={11} />
|
<X size={11} />
|
||||||
</button>
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -345,10 +411,11 @@ export function DataTableToolbar({
|
|||||||
onAction,
|
onAction,
|
||||||
hideSearch = false,
|
hideSearch = false,
|
||||||
hideAction = false,
|
hideAction = false,
|
||||||
|
onFilterOpenChange,
|
||||||
extraActions,
|
extraActions,
|
||||||
}: DataTableToolbarProps) {
|
}: DataTableToolbarProps) {
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex items-center gap-3 mb-3", hideSearch ? "justify-end" : "justify-between")}>
|
<div className={cn("flex items-center gap-3 ", hideSearch ? "justify-end" : "justify-between")}>
|
||||||
{!hideSearch && <TableSearchInput value={searchValue} onChange={onSearchChange} placeholder={searchPlaceholder} />}
|
{!hideSearch && <TableSearchInput value={searchValue} onChange={onSearchChange} placeholder={searchPlaceholder} />}
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -369,6 +436,7 @@ export function DataTableToolbar({
|
|||||||
perPageOptions={perPageOptions}
|
perPageOptions={perPageOptions}
|
||||||
perPage={perPage}
|
perPage={perPage}
|
||||||
onPerPageChange={onPerPageChange}
|
onPerPageChange={onPerPageChange}
|
||||||
|
onFilterOpenChange={onFilterOpenChange}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import { useRef, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { Upload, X, Loader2, FileText, ExternalLink } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { postFile, buildFileUrl } from "@/features/shared/api/sharedApi";
|
||||||
|
|
||||||
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
interface DocumentUploadProps {
|
||||||
|
label?: string;
|
||||||
|
value?: string;
|
||||||
|
onChange?: (url: string) => void;
|
||||||
|
error?: string;
|
||||||
|
required?: boolean;
|
||||||
|
disabled?: boolean;
|
||||||
|
accept?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── FieldLabel ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function FieldLabel({ label, required }: { label?: string; required?: boolean }) {
|
||||||
|
if (!label) return null;
|
||||||
|
return (
|
||||||
|
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 select-none">
|
||||||
|
{label}
|
||||||
|
{required && <span className="text-destructive ml-0.5">*</span>}
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── ErrorMsg ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function ErrorMsg({ error }: { error?: string }) {
|
||||||
|
if (!error) return null;
|
||||||
|
return (
|
||||||
|
<p className="mt-1.5 text-xs text-destructive font-medium flex items-center gap-1.5">
|
||||||
|
<span className="inline-block w-1 h-1 rounded-full bg-destructive shrink-0" />
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Helper: Extract Filename ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function getDisplayFilename(urlOrName: string): string {
|
||||||
|
if (!urlOrName) return "";
|
||||||
|
try {
|
||||||
|
const parts = urlOrName.split("/");
|
||||||
|
return decodeURIComponent(parts[parts.length - 1]);
|
||||||
|
} catch {
|
||||||
|
return urlOrName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const IMAGE_EXT_REGEX = /\.(png|jpe?g|gif|webp|bmp|svg|avif|heic|heif)$/i;
|
||||||
|
|
||||||
|
function isImageFileName(urlOrName: string): boolean {
|
||||||
|
const clean = urlOrName.split("?")[0].split("#")[0];
|
||||||
|
return IMAGE_EXT_REGEX.test(clean);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── DocumentUpload ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function DocumentUpload({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
error,
|
||||||
|
required,
|
||||||
|
disabled,
|
||||||
|
accept = ".pdf,.doc,.docx,image/*",
|
||||||
|
placeholder,
|
||||||
|
}: DocumentUploadProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [dragOver, setDragOver] = useState(false);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [uploadError, setUploadError] = useState("");
|
||||||
|
|
||||||
|
const defaultPlaceholder = placeholder ?? t("common.fileUploadPlaceholder", "Faýl saýlaň ýa-da süýräp getiriň (PDF, DOCX, Surat)");
|
||||||
|
|
||||||
|
const handleFile = async (file: File | null) => {
|
||||||
|
if (!file || disabled) return;
|
||||||
|
|
||||||
|
setUploading(true);
|
||||||
|
setUploadError("");
|
||||||
|
try {
|
||||||
|
const filename = await postFile(file);
|
||||||
|
const fileUrl = buildFileUrl(filename);
|
||||||
|
onChange?.(fileUrl);
|
||||||
|
} catch {
|
||||||
|
setUploadError(t("common.fileUploadError", "Faýl ýüklenip bilinmedi"));
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
if (inputRef.current) inputRef.current.value = "";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDrop = (e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(false);
|
||||||
|
handleFile(e.dataTransfer.files[0] ?? null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const effectiveError = error || uploadError;
|
||||||
|
const fileName = value ? getDisplayFilename(value) : "";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<FieldLabel label={label} required={required} />
|
||||||
|
|
||||||
|
{value ? (
|
||||||
|
<div className="p-3 rounded-md border border-border bg-muted/30 space-y-2">
|
||||||
|
{isImageFileName(value) ? (
|
||||||
|
<a
|
||||||
|
href={value.startsWith("http") ? value : buildFileUrl(value)}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="block overflow-hidden rounded-md border border-border bg-background"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={value.startsWith("http") ? value : buildFileUrl(value)}
|
||||||
|
alt={fileName}
|
||||||
|
loading="lazy"
|
||||||
|
className="w-full h-36 object-cover"
|
||||||
|
/>
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center gap-2.5 min-w-0">
|
||||||
|
<div className="w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center shrink-0">
|
||||||
|
<FileText size={16} className="text-primary" />
|
||||||
|
</div>
|
||||||
|
<p className="text-sm font-medium text-foreground truncate">{fileName}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<a
|
||||||
|
href={value.startsWith("http") ? value : buildFileUrl(value)}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="text-xs text-primary hover:underline inline-flex items-center gap-1 shrink-0"
|
||||||
|
>
|
||||||
|
<ExternalLink size={11} />
|
||||||
|
{t("common.viewFile", "Faýla seret")}
|
||||||
|
</a>
|
||||||
|
|
||||||
|
{!disabled && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onChange?.("")}
|
||||||
|
className="p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors shrink-0"
|
||||||
|
title={t("common.remove", "Aýyr")}
|
||||||
|
>
|
||||||
|
<X size={16} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
role="button"
|
||||||
|
tabIndex={disabled ? -1 : 0}
|
||||||
|
onClick={() => !disabled && !uploading && inputRef.current?.click()}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && !disabled && !uploading && inputRef.current?.click()}
|
||||||
|
onDragOver={(e) => {
|
||||||
|
if (disabled) return;
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(true);
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setDragOver(false)}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col items-center justify-center gap-2 px-4 py-5",
|
||||||
|
"rounded-md border-2 border-dashed cursor-pointer select-none text-center",
|
||||||
|
"transition-all duration-200 text-sm",
|
||||||
|
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||||
|
dragOver && "border-primary bg-primary/5 scale-[1.01]",
|
||||||
|
effectiveError ? "border-destructive/60" : "border-border",
|
||||||
|
!dragOver && !effectiveError && "hover:border-primary/50 hover:bg-muted/20",
|
||||||
|
(disabled || uploading) && "opacity-60 cursor-not-allowed pointer-events-none",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<div className="flex items-center gap-2 py-1">
|
||||||
|
<Loader2 size={18} className="animate-spin text-primary" />
|
||||||
|
<span className="text-sm text-muted-foreground">{t("common.uploading", "Ýüklenýär...")}</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="w-9 h-9 rounded-full bg-primary/10 flex items-center justify-center">
|
||||||
|
<Upload size={18} className="text-primary" />
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground max-w-xs">{defaultPlaceholder}</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
type="file"
|
||||||
|
accept={accept}
|
||||||
|
disabled={disabled || uploading}
|
||||||
|
onChange={(e) => handleFile(e.target.files?.[0] ?? null)}
|
||||||
|
className="hidden"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ErrorMsg error={effectiveError} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,49 +1,58 @@
|
|||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from "react";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from "lucide-react";
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from "@/components/ui/button";
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
interface FormActionsProps {
|
interface FormActionsProps {
|
||||||
isPending?: boolean
|
isPending?: boolean;
|
||||||
onSubmit?: () => void
|
submitDisabled?: boolean;
|
||||||
onCancel?: () => void
|
onSubmit?: () => void;
|
||||||
submitLabel?: ReactNode
|
onCancel?: () => void;
|
||||||
cancelLabel?: ReactNode
|
submitLabel?: ReactNode;
|
||||||
loadingLabel?: ReactNode
|
cancelLabel?: ReactNode;
|
||||||
cancelVariant?: 'outline' | 'ghost'
|
loadingLabel?: ReactNode;
|
||||||
className?: string
|
cancelVariant?: "outline" | "ghost";
|
||||||
onNext?: () => void
|
className?: string;
|
||||||
onPrev?: () => void
|
onNext?: () => void;
|
||||||
nextLabel?: ReactNode
|
onPrev?: () => void;
|
||||||
prevLabel?: ReactNode
|
nextLabel?: ReactNode;
|
||||||
showSubmit?: boolean
|
prevLabel?: ReactNode;
|
||||||
|
showSubmit?: boolean;
|
||||||
|
/**
|
||||||
|
* When true and not on the last step, render an extra "Save" button so an
|
||||||
|
* edit can be persisted without navigating through every step. Suppressed
|
||||||
|
* on the last step to avoid a duplicate submit button.
|
||||||
|
*/
|
||||||
|
saveOnEveryStep?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function FormActions({
|
export function FormActions({
|
||||||
isPending = false,
|
isPending = false,
|
||||||
|
submitDisabled = false,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onCancel,
|
onCancel,
|
||||||
submitLabel,
|
submitLabel,
|
||||||
cancelLabel,
|
cancelLabel,
|
||||||
loadingLabel,
|
loadingLabel,
|
||||||
cancelVariant = 'outline',
|
cancelVariant = "outline",
|
||||||
className,
|
className,
|
||||||
onNext,
|
onNext,
|
||||||
onPrev,
|
onPrev,
|
||||||
nextLabel,
|
nextLabel,
|
||||||
prevLabel,
|
prevLabel,
|
||||||
showSubmit = true,
|
showSubmit = true,
|
||||||
|
saveOnEveryStep = false,
|
||||||
}: FormActionsProps) {
|
}: FormActionsProps) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
const cancelText = cancelLabel ?? t('common.cancel', 'Ýatyr')
|
const cancelText = cancelLabel ?? t("common.cancel", "Ýatyr");
|
||||||
const loadingText = loadingLabel ?? t('common.saving', 'Saklanýar...')
|
const loadingText = loadingLabel ?? t("common.saving", "Saklanýar...");
|
||||||
const prevText = prevLabel ?? t('common.prev', 'Yza')
|
const prevText = prevLabel ?? t("common.prev", "Yza");
|
||||||
const nextText = nextLabel ?? t('common.next', 'Indiki')
|
const nextText = nextLabel ?? t("common.next", "Indiki");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn('flex items-center justify-end gap-3', className)}>
|
<div className={cn("flex items-center justify-end gap-3", className)}>
|
||||||
{onCancel && (
|
{onCancel && (
|
||||||
<Button type="button" variant={cancelVariant} onClick={onCancel} disabled={isPending}>
|
<Button type="button" variant={cancelVariant} onClick={onCancel} disabled={isPending}>
|
||||||
{cancelText}
|
{cancelText}
|
||||||
@@ -59,8 +68,20 @@ export function FormActions({
|
|||||||
{nextText}
|
{nextText}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
{saveOnEveryStep && onSubmit && !showSubmit && (
|
||||||
|
<Button type="button" onClick={onSubmit} disabled={isPending || submitDisabled}>
|
||||||
|
{isPending ? (
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Loader2 size={14} className="animate-spin" />
|
||||||
|
{loadingText}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
submitLabel
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
{showSubmit && onSubmit && (
|
{showSubmit && onSubmit && (
|
||||||
<Button type="button" onClick={onSubmit} disabled={isPending}>
|
<Button type="button" onClick={onSubmit} disabled={isPending || submitDisabled}>
|
||||||
{isPending ? (
|
{isPending ? (
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<Loader2 size={14} className="animate-spin" />
|
<Loader2 size={14} className="animate-spin" />
|
||||||
@@ -72,5 +93,5 @@ export function FormActions({
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
+318
-41
@@ -1,8 +1,8 @@
|
|||||||
import { useState, useRef, useEffect } from "react";
|
import { useState, useRef, useEffect, useMemo } from "react";
|
||||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
|
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
|
||||||
import { Check, ChevronsUpDown, Search, X, Eye, EyeOff, Upload, Hash } from "lucide-react";
|
import { Check, ChevronsUpDown, Search, X, Eye, EyeOff, Upload, Hash, CreditCard } from "lucide-react";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn, cleanPhoneNumber } from "@/lib/utils";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -29,7 +29,11 @@ export type FormInputType =
|
|||||||
| "select"
|
| "select"
|
||||||
| "searchable-select"
|
| "searchable-select"
|
||||||
| "file"
|
| "file"
|
||||||
| "textarea";
|
| "textarea"
|
||||||
|
| "card-number"
|
||||||
|
| "card-name"
|
||||||
|
| "passport-id"
|
||||||
|
| "digits";
|
||||||
|
|
||||||
export interface SelectOption {
|
export interface SelectOption {
|
||||||
value: string;
|
value: string;
|
||||||
@@ -54,6 +58,7 @@ export interface FormInputProps {
|
|||||||
rows?: number;
|
rows?: number;
|
||||||
name?: string;
|
name?: string;
|
||||||
readOnly?: boolean;
|
readOnly?: boolean;
|
||||||
|
maxLength?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── FieldLabel ───────────────────────────────────────────────────────────────
|
// ─── FieldLabel ───────────────────────────────────────────────────────────────
|
||||||
@@ -86,6 +91,73 @@ const withError = (error?: string) => (error ? "border-destructive focus-visible
|
|||||||
|
|
||||||
// ─── TextInput ────────────────────────────────────────────────────────────────
|
// ─── TextInput ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// ─── formatNumber helpers ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** "1000000.50" → "1 000 000.50" (integer part only gets spaces) */
|
||||||
|
function formatNumberDisplay(raw: string): string {
|
||||||
|
if (!raw) return "";
|
||||||
|
const [intPart, decPart] = raw.split(".");
|
||||||
|
const formatted = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
|
||||||
|
return decPart !== undefined ? `${formatted}.${decPart}` : formatted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "1 000 000.50" → "1000000.50" */
|
||||||
|
function stripNumberFormat(display: string): string {
|
||||||
|
return display.replace(/ /g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── NumberInput ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function NumberInput({ value = "", onChange, placeholder, error, disabled, required, label, className, name, readOnly }: FormInputProps) {
|
||||||
|
// Display state — formatted for the user to see
|
||||||
|
const [display, setDisplay] = useState(() => formatNumberDisplay(value));
|
||||||
|
|
||||||
|
// Sync display when value changes externally (e.g. form reset)
|
||||||
|
useEffect(() => {
|
||||||
|
const current = stripNumberFormat(display);
|
||||||
|
if (current !== value) {
|
||||||
|
setDisplay(formatNumberDisplay(value));
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const raw = e.target.value;
|
||||||
|
// Allow only digits, dots, and spaces (we manage spaces ourselves)
|
||||||
|
const stripped = raw.replace(/ /g, "");
|
||||||
|
if (stripped !== "" && !/^\d*\.?\d*$/.test(stripped)) return;
|
||||||
|
if (stripped !== "" && Number(stripped) < 0) return;
|
||||||
|
|
||||||
|
setDisplay(formatNumberDisplay(stripped));
|
||||||
|
onChange?.(stripped);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={className}>
|
||||||
|
<FieldLabel label={label} required={required} />
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
name={name}
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
value={display}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
readOnly={readOnly}
|
||||||
|
className={cn("pr-10", withError(error))}
|
||||||
|
/>
|
||||||
|
<Hash size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ErrorMsg error={error} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── TextInput ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function TextInput({
|
function TextInput({
|
||||||
type = "text",
|
type = "text",
|
||||||
value = "",
|
value = "",
|
||||||
@@ -104,7 +176,6 @@ function TextInput({
|
|||||||
|
|
||||||
const isPassword = type === "password";
|
const isPassword = type === "password";
|
||||||
const isTextarea = type === "textarea";
|
const isTextarea = type === "textarea";
|
||||||
const isNumber = type === "number";
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={className}>
|
<div className={className}>
|
||||||
@@ -125,21 +196,13 @@ function TextInput({
|
|||||||
) : (
|
) : (
|
||||||
<Input
|
<Input
|
||||||
name={name}
|
name={name}
|
||||||
type={isPassword ? (showPass ? "text" : "password") : isNumber ? "number" : type === "email" ? "email" : "text"}
|
type={isPassword ? (showPass ? "text" : "password") : type === "email" ? "email" : "text"}
|
||||||
min={isNumber ? 0 : undefined}
|
|
||||||
value={value}
|
value={value}
|
||||||
onChange={(e) => {
|
onChange={(e) => onChange?.(e.target.value)}
|
||||||
if (isNumber) {
|
|
||||||
const num = e.target.value;
|
|
||||||
if (num === "" || Number(num) >= 0) onChange?.(num);
|
|
||||||
} else {
|
|
||||||
onChange?.(e.target.value);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
className={cn(isPassword && "pr-10", isNumber && "pr-10", withError(error))}
|
className={cn(isPassword && "pr-10", withError(error))}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -153,8 +216,6 @@ function TextInput({
|
|||||||
{showPass ? <EyeOff size={15} /> : <Eye size={15} />}
|
{showPass ? <EyeOff size={15} /> : <Eye size={15} />}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isNumber && <Hash size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ErrorMsg error={error} />
|
<ErrorMsg error={error} />
|
||||||
@@ -175,6 +236,8 @@ function PhoneInput({
|
|||||||
className,
|
className,
|
||||||
phonePrefix = "+993",
|
phonePrefix = "+993",
|
||||||
}: FormInputProps) {
|
}: FormInputProps) {
|
||||||
|
const cleanedDigits = cleanPhoneNumber(value);
|
||||||
|
|
||||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const digits = e.target.value.replace(/\D/g, "").slice(0, 8);
|
const digits = e.target.value.replace(/\D/g, "").slice(0, 8);
|
||||||
|
|
||||||
@@ -185,13 +248,15 @@ function PhoneInput({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const formattedDisplayValue = cleanedDigits.length <= 2 ? cleanedDigits : `${cleanedDigits.slice(0, 2)} ${cleanedDigits.slice(2)}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={className}>
|
<div className={className}>
|
||||||
<FieldLabel label={label} required={required} />
|
<FieldLabel label={label} required={required} />
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-8 w-full rounded-md border bg-background overflow-hidden",
|
"flex h-8 w-full rounded-md border border-input bg-transparent dark:bg-input/30 overflow-hidden",
|
||||||
"ring-offset-background transition-colors duration-150",
|
"ring-offset-background transition-colors duration-150",
|
||||||
"focus-within:outline-none focus-within:ring-1 focus-within:ring-ring focus-within:ring-offset-0",
|
"focus-within:outline-none focus-within:ring-1 focus-within:ring-ring focus-within:ring-offset-0",
|
||||||
error ? "border-destructive focus-within:ring-destructive/30" : "border-input",
|
error ? "border-destructive focus-within:ring-destructive/30" : "border-input",
|
||||||
@@ -203,11 +268,11 @@ function PhoneInput({
|
|||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
type="tel"
|
type="tel"
|
||||||
value={value}
|
value={formattedDisplayValue}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
className="flex-1 h-full px-3 bg-transparent text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none disabled:cursor-not-allowed"
|
className="flex-1 h-full px-3 bg-transparent text-sm text-foreground placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -216,13 +281,196 @@ function PhoneInput({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── formatCardNumber helper ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function formatCardNumber(value?: string | null): string {
|
||||||
|
if (!value) return "";
|
||||||
|
const digits = value.replace(/\D/g, "").slice(0, 16);
|
||||||
|
return digits.replace(/(\d{4})(?=\d)/g, "$1 ");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── CardNumberInput ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function CardNumberInput({
|
||||||
|
value = "",
|
||||||
|
onChange,
|
||||||
|
placeholder = "9999 9999 9999 9999",
|
||||||
|
error,
|
||||||
|
disabled,
|
||||||
|
required,
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
name,
|
||||||
|
readOnly,
|
||||||
|
}: FormInputProps) {
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const formatted = formatCardNumber(e.target.value);
|
||||||
|
onChange?.(formatted);
|
||||||
|
};
|
||||||
|
|
||||||
|
const display = formatCardNumber(value);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={className}>
|
||||||
|
<FieldLabel label={label} required={required} />
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
name={name}
|
||||||
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
|
value={display}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
readOnly={readOnly}
|
||||||
|
maxLength={19}
|
||||||
|
className={cn("pr-10 font-mono tracking-wider", withError(error))}
|
||||||
|
/>
|
||||||
|
<CreditCard size={15} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
|
||||||
|
</div>
|
||||||
|
<ErrorMsg error={error} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── CardNameInput ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function CardNameInput({
|
||||||
|
value = "",
|
||||||
|
onChange,
|
||||||
|
placeholder,
|
||||||
|
error,
|
||||||
|
disabled,
|
||||||
|
required,
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
name,
|
||||||
|
readOnly,
|
||||||
|
}: FormInputProps) {
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
// Only characters (letters in any alphabet) and spaces
|
||||||
|
const sanitized = e.target.value.replace(/[^\p{L}\s]/gu, "");
|
||||||
|
onChange?.(sanitized);
|
||||||
|
};
|
||||||
|
|
||||||
|
const display = (value || "").replace(/[^\p{L}\s]/gu, "");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={className}>
|
||||||
|
<FieldLabel label={label} required={required} />
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
name={name}
|
||||||
|
type="text"
|
||||||
|
value={display}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
readOnly={readOnly}
|
||||||
|
className={cn(withError(error))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<ErrorMsg error={error} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── PassportIdInput ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function PassportIdInput({
|
||||||
|
value = "",
|
||||||
|
onChange,
|
||||||
|
placeholder = "999999",
|
||||||
|
error,
|
||||||
|
disabled,
|
||||||
|
required,
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
name,
|
||||||
|
readOnly,
|
||||||
|
}: FormInputProps) {
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const digits = e.target.value.replace(/\D/g, "").slice(0, 6);
|
||||||
|
onChange?.(digits);
|
||||||
|
};
|
||||||
|
|
||||||
|
const display = (value || "").replace(/\D/g, "").slice(0, 6);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={className}>
|
||||||
|
<FieldLabel label={label} required={required} />
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
name={name}
|
||||||
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
|
value={display}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
readOnly={readOnly}
|
||||||
|
maxLength={6}
|
||||||
|
className={cn("font-mono tracking-wider", withError(error))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<ErrorMsg error={error} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── DigitsInput ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function DigitsInput({
|
||||||
|
value = "",
|
||||||
|
onChange,
|
||||||
|
placeholder,
|
||||||
|
error,
|
||||||
|
disabled,
|
||||||
|
required,
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
name,
|
||||||
|
readOnly,
|
||||||
|
maxLength,
|
||||||
|
}: FormInputProps) {
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const raw = e.target.value.replace(/\D/g, "");
|
||||||
|
const digits = maxLength ? raw.slice(0, maxLength) : raw;
|
||||||
|
onChange?.(digits);
|
||||||
|
};
|
||||||
|
|
||||||
|
const rawDisplay = (value || "").replace(/\D/g, "");
|
||||||
|
const display = maxLength ? rawDisplay.slice(0, maxLength) : rawDisplay;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={className}>
|
||||||
|
<FieldLabel label={label} required={required} />
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
name={name}
|
||||||
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
|
value={display}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
readOnly={readOnly}
|
||||||
|
maxLength={maxLength}
|
||||||
|
className={cn(withError(error))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<ErrorMsg error={error} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ─── DateInput (shadcn Popover + Calendar) ───────────────────────────────────
|
// ─── DateInput (shadcn Popover + Calendar) ───────────────────────────────────
|
||||||
|
|
||||||
function DateInput({ value = "", onChange, error, disabled, required, label, className, placeholder = "Sene saýlaň" }: FormInputProps) {
|
function DateInput({ value = "", onChange, error, disabled, required, label, className, placeholder = "Sene saýlaň" }: FormInputProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
// value is stored as 'yyyy-MM-dd' string
|
const rawDate = value ? value.trim().slice(0, 10) : "";
|
||||||
const parsed = value ? parse(value, "yyyy-MM-dd", new Date()) : undefined;
|
const parsed = rawDate ? parse(rawDate, "yyyy-MM-dd", new Date()) : undefined;
|
||||||
const selected = parsed && isValid(parsed) ? parsed : undefined;
|
const selected = parsed && isValid(parsed) ? parsed : undefined;
|
||||||
|
|
||||||
const handleSelect = (day: Date | undefined) => {
|
const handleSelect = (day: Date | undefined) => {
|
||||||
@@ -240,12 +488,12 @@ function DateInput({ value = "", onChange, error, disabled, required, label, cla
|
|||||||
type="button"
|
type="button"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-8 w-full items-center justify-between rounded-md border bg-background px-3 py-2",
|
"flex h-8 w-full items-center justify-between rounded-md border border-input bg-transparent dark:bg-input/30 px-3 py-2",
|
||||||
"text-sm ring-offset-background transition-colors duration-150",
|
"text-sm ring-offset-background transition-colors duration-150",
|
||||||
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
|
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
|
||||||
"disabled:cursor-not-allowed disabled:opacity-50",
|
"disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
error ? "border-destructive" : "border-input",
|
error ? "border-destructive" : "border-input",
|
||||||
!selected && "text-muted-foreground/60",
|
!selected && "text-muted-foreground",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<span>{selected ? format(selected, "dd.MM.yyyy") : placeholder}</span>
|
<span>{selected ? format(selected, "dd.MM.yyyy") : placeholder}</span>
|
||||||
@@ -272,6 +520,8 @@ function DateInput({ value = "", onChange, error, disabled, required, label, cla
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ─── SelectInput ──────────────────────────────────────────────────────────────
|
// ─── SelectInput ──────────────────────────────────────────────────────────────
|
||||||
|
// Panel is absolutely positioned (top-full) so it floats over content below
|
||||||
|
// instead of pushing it down — same pattern as SearchableSelect.
|
||||||
|
|
||||||
function SelectInput({
|
function SelectInput({
|
||||||
value = "",
|
value = "",
|
||||||
@@ -286,7 +536,16 @@ function SelectInput({
|
|||||||
}: FormInputProps) {
|
}: FormInputProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
const selected = options.find((o) => o.value === value);
|
const uniqueOptions = useMemo(() => {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
return options.filter((opt) => {
|
||||||
|
if (seen.has(opt.value)) return false;
|
||||||
|
seen.add(opt.value);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}, [options]);
|
||||||
|
|
||||||
|
const selected = uniqueOptions.find((o) => o.value === value);
|
||||||
|
|
||||||
const handleSelect = (val: string) => {
|
const handleSelect = (val: string) => {
|
||||||
onChange?.(val);
|
onChange?.(val);
|
||||||
@@ -308,7 +567,7 @@ function SelectInput({
|
|||||||
type="button"
|
type="button"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-8 w-full items-center justify-between rounded-md border bg-background px-3 py-2",
|
"flex h-8 w-full items-center justify-between rounded-md border border-input bg-transparent dark:bg-input/30 px-3 py-2",
|
||||||
"text-sm ring-offset-background transition-colors duration-150",
|
"text-sm ring-offset-background transition-colors duration-150",
|
||||||
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
|
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
|
||||||
"disabled:cursor-not-allowed disabled:opacity-50",
|
"disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
@@ -316,7 +575,7 @@ function SelectInput({
|
|||||||
open && !error && "ring-2 ring-ring ring-offset-0 border-transparent",
|
open && !error && "ring-2 ring-ring ring-offset-0 border-transparent",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<span className={cn("truncate text-left", !selected && "text-muted-foreground/60")}>
|
<span className={cn("truncate text-left", !selected && "text-muted-foreground")}>
|
||||||
{selected ? selected.label : placeholder}
|
{selected ? selected.label : placeholder}
|
||||||
</span>
|
</span>
|
||||||
<ChevronsUpDown
|
<ChevronsUpDown
|
||||||
@@ -326,9 +585,11 @@ function SelectInput({
|
|||||||
</button>
|
</button>
|
||||||
</CollapsibleTrigger>
|
</CollapsibleTrigger>
|
||||||
|
|
||||||
<CollapsibleContent className="mt-1 rounded-md border border-border bg-card shadow-lg overflow-hidden">
|
<CollapsibleContent
|
||||||
<div className="max-h-52 overflow-y-auto py-1">
|
className={cn("absolute z-50 top-full left-0 right-0 mt-1", "rounded-md border border-border bg-card shadow-lg overflow-hidden")}
|
||||||
{options.map((opt) => {
|
>
|
||||||
|
<div className="max-h-52 overflow-y-auto scrollbar-thin py-1">
|
||||||
|
{uniqueOptions.map((opt) => {
|
||||||
const isSelected = opt.value === value;
|
const isSelected = opt.value === value;
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
@@ -359,9 +620,9 @@ function SelectInput({
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ─── SearchableSelect ─────────────────────────────────────────────────────────
|
// ─── SearchableSelect ─────────────────────────────────────────────────────────
|
||||||
// Uses Radix Collapsible — no portal, no z-index issues, natural document flow.
|
// Panel is absolutely positioned (top-full) so it floats over content below
|
||||||
// onMouseDown (not onClick) on options prevents the trigger's onBlur from
|
// instead of pushing it down. onMouseDown (not onClick) on options prevents
|
||||||
// firing before the selection is registered.
|
// the trigger's onBlur from firing before the selection is registered.
|
||||||
|
|
||||||
function SearchableSelect({
|
function SearchableSelect({
|
||||||
value = "",
|
value = "",
|
||||||
@@ -378,8 +639,17 @@ function SearchableSelect({
|
|||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const searchRef = useRef<HTMLInputElement>(null);
|
const searchRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const selected = options.find((o) => o.value === value);
|
const uniqueOptions = useMemo(() => {
|
||||||
const filtered = query.trim() ? options.filter((o) => o.label.toLowerCase().includes(query.toLowerCase())) : options;
|
const seen = new Set<string>();
|
||||||
|
return options.filter((opt) => {
|
||||||
|
if (seen.has(opt.value)) return false;
|
||||||
|
seen.add(opt.value);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}, [options]);
|
||||||
|
|
||||||
|
const selected = uniqueOptions.find((o) => o.value === value);
|
||||||
|
const filtered = query.trim() ? uniqueOptions.filter((o) => o.label.toLowerCase().includes(query.toLowerCase())) : uniqueOptions;
|
||||||
|
|
||||||
const openDropdown = () => {
|
const openDropdown = () => {
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
@@ -425,7 +695,7 @@ function SearchableSelect({
|
|||||||
type="button"
|
type="button"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-8 w-full items-center justify-between rounded-md border bg-background px-3 py-2",
|
"flex h-8 w-full items-center justify-between rounded-md border border-input bg-transparent dark:bg-input/30 px-3 py-2",
|
||||||
"text-sm ring-offset-background transition-colors duration-150",
|
"text-sm ring-offset-background transition-colors duration-150",
|
||||||
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
|
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
|
||||||
"disabled:cursor-not-allowed disabled:opacity-50",
|
"disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
@@ -433,7 +703,7 @@ function SearchableSelect({
|
|||||||
open && !error && "ring-2 ring-ring ring-offset-0 border-transparent",
|
open && !error && "ring-2 ring-ring ring-offset-0 border-transparent",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<span className={cn("truncate text-left", !selected && "text-muted-foreground/60")}>
|
<span className={cn("truncate text-left", !selected && "text-muted-foreground")}>
|
||||||
{selected ? selected.label : placeholder}
|
{selected ? selected.label : placeholder}
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
@@ -456,8 +726,10 @@ function SearchableSelect({
|
|||||||
</button>
|
</button>
|
||||||
</CollapsibleTrigger>
|
</CollapsibleTrigger>
|
||||||
|
|
||||||
{/* Panel */}
|
{/* Panel — absolute so it floats instead of pushing layout down */}
|
||||||
<CollapsibleContent className="mt-1 rounded-md border border-border bg-card shadow-lg overflow-hidden">
|
<CollapsibleContent
|
||||||
|
className={cn("absolute z-50 top-full left-0 right-0 mt-1", "rounded-md border border-border bg-card shadow-lg overflow-hidden")}
|
||||||
|
>
|
||||||
{/* Search */}
|
{/* Search */}
|
||||||
<div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/20">
|
<div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/20">
|
||||||
<Search size={13} className="text-muted-foreground shrink-0" />
|
<Search size={13} className="text-muted-foreground shrink-0" />
|
||||||
@@ -482,7 +754,7 @@ function SearchableSelect({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Options */}
|
{/* Options */}
|
||||||
<div className="max-h-52 overflow-y-auto py-1">
|
<div className="max-h-52 overflow-y-auto scrollbar-thin py-1">
|
||||||
{filtered.length === 0 ? (
|
{filtered.length === 0 ? (
|
||||||
<p className="px-3 py-4 text-sm text-muted-foreground text-center">Netije tapylmady</p>
|
<p className="px-3 py-4 text-sm text-muted-foreground text-center">Netije tapylmady</p>
|
||||||
) : (
|
) : (
|
||||||
@@ -655,7 +927,12 @@ function FileInput({
|
|||||||
export function FormInput(props: FormInputProps) {
|
export function FormInput(props: FormInputProps) {
|
||||||
const { type = "text" } = props;
|
const { type = "text" } = props;
|
||||||
|
|
||||||
|
if (type === "number") return <NumberInput {...props} />;
|
||||||
if (type === "phone") return <PhoneInput {...props} />;
|
if (type === "phone") return <PhoneInput {...props} />;
|
||||||
|
if (type === "card-number") return <CardNumberInput {...props} />;
|
||||||
|
if (type === "card-name") return <CardNameInput {...props} />;
|
||||||
|
if (type === "passport-id") return <PassportIdInput {...props} />;
|
||||||
|
if (type === "digits") return <DigitsInput {...props} />;
|
||||||
if (type === "date") return <DateInput {...props} />;
|
if (type === "date") return <DateInput {...props} />;
|
||||||
if (type === "select") return <SelectInput {...props} />;
|
if (type === "select") return <SelectInput {...props} />;
|
||||||
if (type === "searchable-select") return <SearchableSelect {...props} />;
|
if (type === "searchable-select") return <SearchableSelect {...props} />;
|
||||||
|
|||||||
@@ -0,0 +1,268 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import * as PopoverPrimitive from "@radix-ui/react-popover";
|
||||||
|
import { Check, ChevronsUpDown, Search, X, Loader2 } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface InfiniteSelectOption {
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InfiniteSelectProps {
|
||||||
|
value?: string;
|
||||||
|
onChange?: (value: string) => void;
|
||||||
|
options?: InfiniteSelectOption[];
|
||||||
|
placeholder?: string;
|
||||||
|
searchPlaceholder?: string;
|
||||||
|
label?: string;
|
||||||
|
required?: boolean;
|
||||||
|
error?: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
loading?: boolean;
|
||||||
|
isLoadingMore?: boolean;
|
||||||
|
hasNextPage?: boolean;
|
||||||
|
onLoadMore?: () => void;
|
||||||
|
searchValue?: string;
|
||||||
|
onSearchChange?: (value: string) => void;
|
||||||
|
onOpenChange?: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Searchable select with infinite scroll.
|
||||||
|
*
|
||||||
|
* The consumer owns the data fetching (e.g. TanStack Query `useInfiniteQuery`):
|
||||||
|
* it passes the flattened options, and `hasNextPage`/`onLoadMore` drive loading
|
||||||
|
* additional pages when the list bottom is reached.
|
||||||
|
*/
|
||||||
|
export function InfiniteSelect({
|
||||||
|
value = "",
|
||||||
|
onChange,
|
||||||
|
options = [],
|
||||||
|
placeholder = "Saýlamak üçin basyň",
|
||||||
|
searchPlaceholder = "Gözle...",
|
||||||
|
label,
|
||||||
|
required,
|
||||||
|
error,
|
||||||
|
disabled,
|
||||||
|
loading = false,
|
||||||
|
isLoadingMore = false,
|
||||||
|
hasNextPage = false,
|
||||||
|
onLoadMore,
|
||||||
|
searchValue,
|
||||||
|
onSearchChange,
|
||||||
|
onOpenChange,
|
||||||
|
}: InfiniteSelectProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [portalContainer, setPortalContainer] = useState<HTMLElement | undefined>(undefined);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (containerRef.current) {
|
||||||
|
const dialog = containerRef.current.closest<HTMLElement>(
|
||||||
|
'[role="dialog"], [role="alertdialog"], [data-slot="alert-dialog-content"], [data-slot="dialog-content"]',
|
||||||
|
);
|
||||||
|
if (dialog) {
|
||||||
|
setPortalContainer(dialog);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = scrollContainerRef.current;
|
||||||
|
if (!el || !open) return;
|
||||||
|
const handleWheel = (e: WheelEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
};
|
||||||
|
el.addEventListener("wheel", handleWheel, { passive: true });
|
||||||
|
return () => el.removeEventListener("wheel", handleWheel);
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
const selected = options.find((o) => o.value === value);
|
||||||
|
|
||||||
|
const handleSelect = (val: string) => {
|
||||||
|
onChange?.(val);
|
||||||
|
setOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClear = (e: React.MouseEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
onChange?.("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadingRef = useRef(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isLoadingMore) {
|
||||||
|
loadingRef.current = false;
|
||||||
|
}
|
||||||
|
}, [isLoadingMore]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || !sentinelRef.current || !hasNextPage || isLoadingMore) return;
|
||||||
|
const el = sentinelRef.current;
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
if (entries[0]?.isIntersecting && hasNextPage && !isLoadingMore && !loadingRef.current) {
|
||||||
|
loadingRef.current = true;
|
||||||
|
onLoadMore?.();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ rootMargin: "120px" },
|
||||||
|
);
|
||||||
|
observer.observe(el);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [open, hasNextPage, isLoadingMore, onLoadMore]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={containerRef} className="relative">
|
||||||
|
{label && (
|
||||||
|
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 select-none">
|
||||||
|
{label}
|
||||||
|
{required && <span className="text-destructive ml-0.5">*</span>}
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<PopoverPrimitive.Root
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (!disabled) {
|
||||||
|
setOpen(next);
|
||||||
|
onOpenChange?.(next);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<PopoverPrimitive.Trigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={disabled}
|
||||||
|
className={cn(
|
||||||
|
"flex h-8 w-full items-center justify-between rounded-md border border-input bg-transparent dark:bg-input/30 px-3 py-2",
|
||||||
|
"text-sm ring-offset-background transition-colors duration-150",
|
||||||
|
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
|
||||||
|
"disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
|
error ? "border-destructive" : "border-input",
|
||||||
|
open && !error && "ring-2 ring-ring ring-offset-0 border-transparent",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className={cn("truncate text-left", !selected && "text-muted-foreground")}>
|
||||||
|
{selected ? selected.label : placeholder}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1 shrink-0 ml-2">
|
||||||
|
{selected && !disabled && (
|
||||||
|
<span
|
||||||
|
role="button"
|
||||||
|
tabIndex={-1}
|
||||||
|
onMouseDown={handleClear}
|
||||||
|
className="p-0.5 rounded text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
<X size={12} />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<ChevronsUpDown
|
||||||
|
size={14}
|
||||||
|
className={cn("text-muted-foreground transition-transform duration-200 shrink-0", open && "text-foreground")}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</PopoverPrimitive.Trigger>
|
||||||
|
|
||||||
|
<PopoverPrimitive.Portal container={portalContainer}>
|
||||||
|
<PopoverPrimitive.Content
|
||||||
|
align="start"
|
||||||
|
side="bottom"
|
||||||
|
sideOffset={4}
|
||||||
|
collisionPadding={16}
|
||||||
|
avoidCollisions
|
||||||
|
style={{ width: "var(--radix-popover-trigger-width)" }}
|
||||||
|
className="z-50 rounded-md border border-border bg-card shadow-lg overflow-hidden max-h-[var(--radix-popover-content-available-height)] flex flex-col"
|
||||||
|
onWheel={(e) => e.stopPropagation()}
|
||||||
|
onTouchMove={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{onSearchChange && (
|
||||||
|
<div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/20 shrink-0">
|
||||||
|
<Search size={13} className="text-muted-foreground shrink-0" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={searchValue ?? ""}
|
||||||
|
onChange={(e) => onSearchChange(e.target.value)}
|
||||||
|
placeholder={searchPlaceholder}
|
||||||
|
className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none"
|
||||||
|
/>
|
||||||
|
{searchValue && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
tabIndex={-1}
|
||||||
|
onMouseDown={() => onSearchChange?.("")}
|
||||||
|
className="text-muted-foreground hover:text-foreground transition-colors"
|
||||||
|
>
|
||||||
|
<X size={12} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div
|
||||||
|
ref={scrollContainerRef}
|
||||||
|
onWheel={(e) => e.stopPropagation()}
|
||||||
|
onTouchMove={(e) => e.stopPropagation()}
|
||||||
|
className="max-h-60 overflow-y-auto overscroll-contain scrollbar-thin py-1"
|
||||||
|
>
|
||||||
|
{loading && options.length === 0 ? (
|
||||||
|
<p className="px-3 py-4 text-sm text-muted-foreground text-center flex items-center justify-center gap-2">
|
||||||
|
<Loader2 size={14} className="animate-spin" /> Loading...
|
||||||
|
</p>
|
||||||
|
) : options.length === 0 ? (
|
||||||
|
<p className="px-3 py-4 text-sm text-muted-foreground text-center">Netije tapylmady</p>
|
||||||
|
) : (
|
||||||
|
options.map((opt) => {
|
||||||
|
const isSelected = opt.value === value;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={opt.value}
|
||||||
|
type="button"
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
handleSelect(opt.value);
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center justify-between w-full text-left px-3 py-2 text-sm transition-colors",
|
||||||
|
"hover:bg-accent hover:text-accent-foreground",
|
||||||
|
isSelected && "text-primary font-medium bg-primary/10",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span>{opt.label}</span>
|
||||||
|
{isSelected && <Check size={13} className="text-primary shrink-0" />}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasNextPage && (
|
||||||
|
<div ref={sentinelRef} className="px-3 py-2 text-xs text-muted-foreground text-center">
|
||||||
|
{isLoadingMore && (
|
||||||
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
<Loader2 size={12} className="animate-spin" /> Loading...
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</PopoverPrimitive.Content>
|
||||||
|
</PopoverPrimitive.Portal>
|
||||||
|
</PopoverPrimitive.Root>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p className="mt-1.5 text-xs text-destructive font-medium flex items-center gap-1.5">
|
||||||
|
<span className="inline-block w-1 h-1 rounded-full bg-destructive shrink-0" />
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -123,8 +123,8 @@ export function StepBarCards({ steps, onGoTo }: StepBarCardsProps) {
|
|||||||
className={cn(
|
className={cn(
|
||||||
"relative flex items-center justify-center rounded-full w-11 h-11 shrink-0 transition-all duration-300",
|
"relative flex items-center justify-center rounded-full w-11 h-11 shrink-0 transition-all duration-300",
|
||||||
isActive &&
|
isActive &&
|
||||||
"bg-[#005f78] text-white ring-4 ring-[#005f78]/15 dark:bg-primary dark:text-primary-foreground dark:ring-primary/15",
|
"bg-[#18b69b] text-white ring-4 ring-[#18b69b]/15 dark:bg-primary dark:text-primary-foreground dark:ring-primary/15",
|
||||||
isDone && "bg-[#005f78]/10 text-[#005f78] dark:bg-muted dark:text-foreground",
|
isDone && "bg-[#18b69b]/10 text-[#18b69b] dark:bg-muted dark:text-foreground",
|
||||||
isError && "bg-destructive/10 text-destructive ring-2 ring-destructive/30",
|
isError && "bg-destructive/10 text-destructive ring-2 ring-destructive/30",
|
||||||
isIdle && "bg-muted text-muted-foreground",
|
isIdle && "bg-muted text-muted-foreground",
|
||||||
reachable && !isActive && "group-hover:scale-105",
|
reachable && !isActive && "group-hover:scale-105",
|
||||||
@@ -144,8 +144,8 @@ export function StepBarCards({ steps, onGoTo }: StepBarCardsProps) {
|
|||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"text-sm font-semibold tracking-tight",
|
"text-sm font-semibold tracking-tight",
|
||||||
isActive && "text-[#005f78] dark:text-foreground",
|
isActive && "text-[#18b69b] dark:text-foreground",
|
||||||
isDone && "text-[#005f78] dark:text-foreground",
|
isDone && "text-[#18b69b] dark:text-foreground",
|
||||||
!isActive && !isDone && !isError && "text-foreground/90",
|
!isActive && !isDone && !isError && "text-foreground/90",
|
||||||
isError && "text-destructive",
|
isError && "text-destructive",
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
const alertVariants = cva(
|
||||||
|
"group/alert relative grid w-full gap-0.5 rounded-2xl border px-4 py-3 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2.5 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-card text-card-foreground",
|
||||||
|
destructive: "bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
function Alert({ className, variant, ...props }: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||||
|
return <div data-slot="alert" role="alert" className={cn(alertVariants({ variant }), className)} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-title"
|
||||||
|
className={cn(
|
||||||
|
"font-medium group-has-[>svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-description"
|
||||||
|
className={cn(
|
||||||
|
"text-sm text-balance text-muted-foreground md:text-pretty [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return <div data-slot="alert-action" className={cn("absolute top-2.5 right-3", className)} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Alert, AlertTitle, AlertDescription, AlertAction };
|
||||||
+14
-25
@@ -1,49 +1,38 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { Slot } from "radix-ui"
|
import { Slot } from "radix-ui";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
const badgeVariants = cva(
|
const badgeVariants = cva(
|
||||||
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-3xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-md border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||||
secondary:
|
secondary: "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||||
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
|
||||||
destructive:
|
destructive:
|
||||||
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
|
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
|
||||||
outline:
|
outline: "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||||
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
ghost: "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
||||||
ghost:
|
|
||||||
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: "default",
|
variant: "default",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
function Badge({
|
function Badge({
|
||||||
className,
|
className,
|
||||||
variant = "default",
|
variant = "default",
|
||||||
asChild = false,
|
asChild = false,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"span"> &
|
}: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
const Comp = asChild ? Slot.Root : "span";
|
||||||
const Comp = asChild ? Slot.Root : "span"
|
|
||||||
|
|
||||||
return (
|
return <Comp data-slot="badge" data-variant={variant} className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||||
<Comp
|
|
||||||
data-slot="badge"
|
|
||||||
data-variant={variant}
|
|
||||||
className={cn(badgeVariants({ variant }), className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Badge, badgeVariants }
|
export { Badge, badgeVariants };
|
||||||
@@ -1,36 +1,33 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
import { Slot } from "radix-ui"
|
import { Slot } from "radix-ui";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
const buttonVariants = cva(
|
const buttonVariants = cva(
|
||||||
"group/button inline-flex cursor-pointer shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
"group/button inline-flex cursor-pointer shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-[#005f78] dark:bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
default: "bg-[#18b69b] hover:bg-[#149e87] active:bg-[#118a76] dark:bg-primary dark:hover:bg-primary/80 text-primary-foreground",
|
||||||
outline:
|
outline:
|
||||||
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||||
secondary:
|
secondary:
|
||||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
||||||
ghost:
|
ghost: "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
|
||||||
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
|
|
||||||
destructive:
|
destructive:
|
||||||
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
|
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
default:
|
default: "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||||
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
|
||||||
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
|
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||||
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
||||||
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||||
icon: "size-8",
|
icon: "size-8",
|
||||||
"icon-xs":
|
"icon-xs":
|
||||||
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3",
|
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||||
"icon-sm":
|
"icon-sm": "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-md",
|
||||||
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-md",
|
|
||||||
"icon-lg": "size-9",
|
"icon-lg": "size-9",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -38,8 +35,8 @@ const buttonVariants = cva(
|
|||||||
variant: "default",
|
variant: "default",
|
||||||
size: "default",
|
size: "default",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
function Button({
|
function Button({
|
||||||
className,
|
className,
|
||||||
@@ -49,9 +46,9 @@ function Button({
|
|||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"button"> &
|
}: React.ComponentProps<"button"> &
|
||||||
VariantProps<typeof buttonVariants> & {
|
VariantProps<typeof buttonVariants> & {
|
||||||
asChild?: boolean
|
asChild?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const Comp = asChild ? Slot.Root : "button"
|
const Comp = asChild ? Slot.Root : "button";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Comp
|
<Comp
|
||||||
@@ -61,7 +58,7 @@ function Button({
|
|||||||
className={cn(buttonVariants({ variant, size, className }))}
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Button, buttonVariants }
|
export { Button, buttonVariants };
|
||||||
+43
-104
@@ -1,14 +1,9 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import {
|
import { DayPicker, getDefaultClassNames, type DayButton, type Locale } from "react-day-picker";
|
||||||
DayPicker,
|
|
||||||
getDefaultClassNames,
|
|
||||||
type DayButton,
|
|
||||||
type Locale,
|
|
||||||
} from "react-day-picker"
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
import { Button, buttonVariants } from "@/components/ui/button"
|
import { Button, buttonVariants } from "@/components/ui/button";
|
||||||
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"
|
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react";
|
||||||
|
|
||||||
function Calendar({
|
function Calendar({
|
||||||
className,
|
className,
|
||||||
@@ -21,9 +16,9 @@ function Calendar({
|
|||||||
components,
|
components,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DayPicker> & {
|
}: React.ComponentProps<typeof DayPicker> & {
|
||||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
buttonVariant?: React.ComponentProps<typeof Button>["variant"];
|
||||||
}) {
|
}) {
|
||||||
const defaultClassNames = getDefaultClassNames()
|
const defaultClassNames = getDefaultClassNames();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DayPicker
|
<DayPicker
|
||||||
@@ -32,150 +27,99 @@ function Calendar({
|
|||||||
"group/calendar bg-background p-2 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
|
"group/calendar bg-background p-2 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
|
||||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
captionLayout={captionLayout}
|
captionLayout={captionLayout}
|
||||||
locale={locale}
|
locale={locale}
|
||||||
formatters={{
|
formatters={{
|
||||||
formatMonthDropdown: (date) =>
|
formatMonthDropdown: (date) => date.toLocaleString(locale?.code, { month: "short" }),
|
||||||
date.toLocaleString(locale?.code, { month: "short" }),
|
|
||||||
...formatters,
|
...formatters,
|
||||||
}}
|
}}
|
||||||
classNames={{
|
classNames={{
|
||||||
root: cn("w-fit", defaultClassNames.root),
|
root: cn("w-fit", defaultClassNames.root),
|
||||||
months: cn(
|
months: cn("relative flex flex-col gap-4 md:flex-row", defaultClassNames.months),
|
||||||
"relative flex flex-col gap-4 md:flex-row",
|
|
||||||
defaultClassNames.months
|
|
||||||
),
|
|
||||||
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||||
nav: cn(
|
nav: cn("absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", defaultClassNames.nav),
|
||||||
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
|
||||||
defaultClassNames.nav
|
|
||||||
),
|
|
||||||
button_previous: cn(
|
button_previous: cn(
|
||||||
buttonVariants({ variant: buttonVariant }),
|
buttonVariants({ variant: buttonVariant }),
|
||||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||||
defaultClassNames.button_previous
|
defaultClassNames.button_previous,
|
||||||
),
|
),
|
||||||
button_next: cn(
|
button_next: cn(
|
||||||
buttonVariants({ variant: buttonVariant }),
|
buttonVariants({ variant: buttonVariant }),
|
||||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||||
defaultClassNames.button_next
|
defaultClassNames.button_next,
|
||||||
),
|
|
||||||
month_caption: cn(
|
|
||||||
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
|
|
||||||
defaultClassNames.month_caption
|
|
||||||
),
|
|
||||||
dropdowns: cn(
|
|
||||||
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
|
|
||||||
defaultClassNames.dropdowns
|
|
||||||
),
|
|
||||||
dropdown_root: cn(
|
|
||||||
"relative rounded-(--cell-radius)",
|
|
||||||
defaultClassNames.dropdown_root
|
|
||||||
),
|
|
||||||
dropdown: cn(
|
|
||||||
"absolute inset-0 bg-popover opacity-0",
|
|
||||||
defaultClassNames.dropdown
|
|
||||||
),
|
),
|
||||||
|
month_caption: cn("flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)", defaultClassNames.month_caption),
|
||||||
|
dropdowns: cn("flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium", defaultClassNames.dropdowns),
|
||||||
|
dropdown_root: cn("relative rounded-(--cell-radius)", defaultClassNames.dropdown_root),
|
||||||
|
dropdown: cn("absolute inset-0 bg-popover opacity-0 scrollbar-thin", defaultClassNames.dropdown),
|
||||||
caption_label: cn(
|
caption_label: cn(
|
||||||
"font-medium select-none",
|
"font-medium select-none",
|
||||||
captionLayout === "label"
|
captionLayout === "label"
|
||||||
? "text-sm"
|
? "text-sm"
|
||||||
: "flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
|
: "flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
|
||||||
defaultClassNames.caption_label
|
defaultClassNames.caption_label,
|
||||||
),
|
),
|
||||||
table: "w-full border-collapse",
|
table: "w-full border-collapse",
|
||||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||||
weekday: cn(
|
weekday: cn(
|
||||||
"flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none",
|
"flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none",
|
||||||
defaultClassNames.weekday
|
defaultClassNames.weekday,
|
||||||
),
|
),
|
||||||
week: cn("mt-2 flex w-full", defaultClassNames.week),
|
week: cn("mt-2 flex w-full", defaultClassNames.week),
|
||||||
week_number_header: cn(
|
week_number_header: cn("w-(--cell-size) select-none", defaultClassNames.week_number_header),
|
||||||
"w-(--cell-size) select-none",
|
week_number: cn("text-[0.8rem] text-muted-foreground select-none", defaultClassNames.week_number),
|
||||||
defaultClassNames.week_number_header
|
|
||||||
),
|
|
||||||
week_number: cn(
|
|
||||||
"text-[0.8rem] text-muted-foreground select-none",
|
|
||||||
defaultClassNames.week_number
|
|
||||||
),
|
|
||||||
day: cn(
|
day: cn(
|
||||||
"group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",
|
"group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)",
|
||||||
props.showWeekNumber
|
props.showWeekNumber
|
||||||
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"
|
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"
|
||||||
: "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",
|
: "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",
|
||||||
defaultClassNames.day
|
defaultClassNames.day,
|
||||||
),
|
),
|
||||||
range_start: cn(
|
range_start: cn(
|
||||||
"relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",
|
"relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",
|
||||||
defaultClassNames.range_start
|
defaultClassNames.range_start,
|
||||||
),
|
),
|
||||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||||
range_end: cn(
|
range_end: cn(
|
||||||
"relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",
|
"relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",
|
||||||
defaultClassNames.range_end
|
defaultClassNames.range_end,
|
||||||
),
|
|
||||||
today: cn(
|
|
||||||
"rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none",
|
|
||||||
defaultClassNames.today
|
|
||||||
),
|
|
||||||
outside: cn(
|
|
||||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
|
||||||
defaultClassNames.outside
|
|
||||||
),
|
|
||||||
disabled: cn(
|
|
||||||
"text-muted-foreground opacity-50",
|
|
||||||
defaultClassNames.disabled
|
|
||||||
),
|
),
|
||||||
|
today: cn("rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none", defaultClassNames.today),
|
||||||
|
outside: cn("text-muted-foreground aria-selected:text-muted-foreground", defaultClassNames.outside),
|
||||||
|
disabled: cn("text-muted-foreground opacity-50", defaultClassNames.disabled),
|
||||||
hidden: cn("invisible", defaultClassNames.hidden),
|
hidden: cn("invisible", defaultClassNames.hidden),
|
||||||
...classNames,
|
...classNames,
|
||||||
}}
|
}}
|
||||||
components={{
|
components={{
|
||||||
Root: ({ className, rootRef, ...props }) => {
|
Root: ({ className, rootRef, ...props }) => {
|
||||||
return (
|
return <div data-slot="calendar" ref={rootRef} className={cn(className)} {...props} />;
|
||||||
<div
|
|
||||||
data-slot="calendar"
|
|
||||||
ref={rootRef}
|
|
||||||
className={cn(className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
Chevron: ({ className, orientation, ...props }) => {
|
Chevron: ({ className, orientation, ...props }) => {
|
||||||
if (orientation === "left") {
|
if (orientation === "left") {
|
||||||
return (
|
return <ChevronLeftIcon className={cn("size-4", className)} {...props} />;
|
||||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (orientation === "right") {
|
if (orientation === "right") {
|
||||||
return (
|
return <ChevronRightIcon className={cn("size-4", className)} {...props} />;
|
||||||
<ChevronRightIcon className={cn("size-4", className)} {...props} />
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return <ChevronDownIcon className={cn("size-4", className)} {...props} />;
|
||||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
DayButton: ({ ...props }) => (
|
DayButton: ({ ...props }) => <CalendarDayButton locale={locale} {...props} />,
|
||||||
<CalendarDayButton locale={locale} {...props} />
|
|
||||||
),
|
|
||||||
WeekNumber: ({ children, ...props }) => {
|
WeekNumber: ({ children, ...props }) => {
|
||||||
return (
|
return (
|
||||||
<td {...props}>
|
<td {...props}>
|
||||||
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
<div className="flex size-(--cell-size) items-center justify-center text-center">{children}</div>
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</td>
|
</td>
|
||||||
)
|
);
|
||||||
},
|
},
|
||||||
...components,
|
...components,
|
||||||
}}
|
}}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CalendarDayButton({
|
function CalendarDayButton({
|
||||||
@@ -185,12 +129,12 @@ function CalendarDayButton({
|
|||||||
locale,
|
locale,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
|
}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
|
||||||
const defaultClassNames = getDefaultClassNames()
|
const defaultClassNames = getDefaultClassNames();
|
||||||
|
|
||||||
const ref = React.useRef<HTMLButtonElement>(null)
|
const ref = React.useRef<HTMLButtonElement>(null);
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (modifiers.focused) ref.current?.focus()
|
if (modifiers.focused) ref.current?.focus();
|
||||||
}, [modifiers.focused])
|
}, [modifiers.focused]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Button
|
<Button
|
||||||
@@ -198,23 +142,18 @@ function CalendarDayButton({
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
data-day={day.date.toLocaleDateString(locale?.code)}
|
data-day={day.date.toLocaleDateString(locale?.code)}
|
||||||
data-selected-single={
|
data-selected-single={modifiers.selected && !modifiers.range_start && !modifiers.range_end && !modifiers.range_middle}
|
||||||
modifiers.selected &&
|
|
||||||
!modifiers.range_start &&
|
|
||||||
!modifiers.range_end &&
|
|
||||||
!modifiers.range_middle
|
|
||||||
}
|
|
||||||
data-range-start={modifiers.range_start}
|
data-range-start={modifiers.range_start}
|
||||||
data-range-end={modifiers.range_end}
|
data-range-end={modifiers.range_end}
|
||||||
data-range-middle={modifiers.range_middle}
|
data-range-middle={modifiers.range_middle}
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",
|
"relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",
|
||||||
defaultClassNames.day,
|
defaultClassNames.day,
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Calendar, CalendarDayButton }
|
export { Calendar, CalendarDayButton };
|
||||||
@@ -1,19 +1,16 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import { Checkbox as CheckboxPrimitive } from "radix-ui"
|
import { Checkbox as CheckboxPrimitive } from "radix-ui";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
import { CheckIcon } from "lucide-react"
|
import { CheckIcon } from "lucide-react";
|
||||||
|
|
||||||
function Checkbox({
|
function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
|
||||||
return (
|
return (
|
||||||
<CheckboxPrimitive.Root
|
<CheckboxPrimitive.Root
|
||||||
data-slot="checkbox"
|
data-slot="checkbox"
|
||||||
className={cn(
|
className={cn(
|
||||||
"peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-[#005f78] data-checked:bg-[#005f78] data-checked:text-white dark:data-checked:border-primary dark:data-checked:bg-primary dark:data-checked:text-primary-foreground",
|
"peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-[#18b69b] data-checked:bg-[#18b69b] data-checked:text-white dark:data-checked:border-primary dark:data-checked:bg-primary dark:data-checked:text-primary-foreground",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
@@ -24,7 +21,7 @@ function Checkbox({
|
|||||||
<CheckIcon />
|
<CheckIcon />
|
||||||
</CheckboxPrimitive.Indicator>
|
</CheckboxPrimitive.Indicator>
|
||||||
</CheckboxPrimitive.Root>
|
</CheckboxPrimitive.Root>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Checkbox }
|
export { Checkbox };
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { Dialog as DialogPrimitive } from "radix-ui";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { XIcon } from "lucide-react";
|
||||||
|
|
||||||
|
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||||
|
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||||
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||||
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||||
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Overlay
|
||||||
|
data-slot="dialog-overlay"
|
||||||
|
className={cn(
|
||||||
|
"fixed inset-0 isolate z-50 bg-black/30 duration-100 supports-backdrop-filter:backdrop-blur-sm data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
showCloseButton = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||||
|
showCloseButton?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DialogPortal>
|
||||||
|
<DialogOverlay />
|
||||||
|
<DialogPrimitive.Content
|
||||||
|
data-slot="dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-md bg-popover p-6 text-sm text-popover-foreground shadow-xl ring-1 ring-foreground/5 duration-100 outline-none sm:max-w-md dark:ring-foreground/10 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close data-slot="dialog-close" asChild>
|
||||||
|
<Button variant="ghost" className="absolute top-4 right-4 bg-secondary" size="icon-sm">
|
||||||
|
<XIcon />
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</Button>
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</DialogPrimitive.Content>
|
||||||
|
</DialogPortal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return <div data-slot="dialog-header" className={cn("flex flex-col gap-1.5", className)} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogFooter({
|
||||||
|
className,
|
||||||
|
showCloseButton = false,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
showCloseButton?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div data-slot="dialog-footer" className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)} {...props}>
|
||||||
|
{children}
|
||||||
|
{showCloseButton && (
|
||||||
|
<DialogPrimitive.Close asChild>
|
||||||
|
<Button variant="outline">Close</Button>
|
||||||
|
</DialogPrimitive.Close>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Title
|
||||||
|
data-slot="dialog-title"
|
||||||
|
className={cn("font-heading text-base leading-none font-medium", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<DialogPrimitive.Description
|
||||||
|
data-slot="dialog-description"
|
||||||
|
className={cn("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogOverlay,
|
||||||
|
DialogPortal,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
};
|
||||||
+17
-73
@@ -1,66 +1,35 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div data-slot="table-container" className="relative w-full overflow-x-auto scrollbar-thin">
|
||||||
data-slot="table-container"
|
<table data-slot="table" className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
||||||
className="relative w-full overflow-x-auto"
|
|
||||||
>
|
|
||||||
<table
|
|
||||||
data-slot="table"
|
|
||||||
className={cn("w-full caption-bottom text-sm", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||||
return (
|
return <thead data-slot="table-header" className={cn("[&_tr]:border-b", className)} {...props} />;
|
||||||
<thead
|
|
||||||
data-slot="table-header"
|
|
||||||
className={cn("[&_tr]:border-b", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||||
return (
|
return <tbody data-slot="table-body" className={cn("[&_tr:last-child]:border-0", className)} {...props} />;
|
||||||
<tbody
|
|
||||||
data-slot="table-body"
|
|
||||||
className={cn("[&_tr:last-child]:border-0", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||||
return (
|
return <tfoot data-slot="table-footer" className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)} {...props} />;
|
||||||
<tfoot
|
|
||||||
data-slot="table-footer"
|
|
||||||
className={cn(
|
|
||||||
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||||
return (
|
return (
|
||||||
<tr
|
<tr
|
||||||
data-slot="table-row"
|
data-slot="table-row"
|
||||||
className={cn(
|
className={cn("border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted", className)}
|
||||||
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||||
@@ -69,46 +38,21 @@ function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
|||||||
data-slot="table-head"
|
data-slot="table-head"
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
|
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||||
return (
|
return (
|
||||||
<td
|
<td data-slot="table-cell" className={cn("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0", className)} {...props} />
|
||||||
data-slot="table-cell"
|
);
|
||||||
className={cn(
|
|
||||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableCaption({
|
function TableCaption({ className, ...props }: React.ComponentProps<"caption">) {
|
||||||
className,
|
return <caption data-slot="table-caption" className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />;
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"caption">) {
|
|
||||||
return (
|
|
||||||
<caption
|
|
||||||
data-slot="table-caption"
|
|
||||||
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
|
||||||
Table,
|
|
||||||
TableHeader,
|
|
||||||
TableBody,
|
|
||||||
TableFooter,
|
|
||||||
TableHead,
|
|
||||||
TableRow,
|
|
||||||
TableCell,
|
|
||||||
TableCaption,
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,18 @@
|
|||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { Download, Eye, ChevronDown, Inbox } from "lucide-react";
|
import { Download, Eye, ChevronDown, Inbox, Pencil, Trash2 } from "lucide-react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
|
|
||||||
@@ -91,14 +102,15 @@ export function InfoRow({ label, value, children, isLink, href }: InfoRowProps)
|
|||||||
|
|
||||||
export interface MultiLangRowProps {
|
export interface MultiLangRowProps {
|
||||||
label: string;
|
label: string;
|
||||||
value?: { tk?: string; ru?: string; en?: string } | null;
|
value?: { tm?: string; tk?: string; ru?: string; en?: string } | string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function MultiLangRow({ label, value }: MultiLangRowProps) {
|
export function MultiLangRow({ label, value }: MultiLangRowProps) {
|
||||||
if (!value) return <InfoRow label={label} value="—" />;
|
if (!value) return <InfoRow label={label} value="—" />;
|
||||||
|
if (typeof value === "string") return <InfoRow label={label} value={value} />;
|
||||||
|
|
||||||
const langs = [
|
const langs = [
|
||||||
{ code: "TK", val: value.tk },
|
{ code: "TK", val: value.tm ?? value.tk },
|
||||||
{ code: "RU", val: value.ru },
|
{ code: "RU", val: value.ru },
|
||||||
{ code: "EN", val: value.en },
|
{ code: "EN", val: value.en },
|
||||||
];
|
];
|
||||||
@@ -175,11 +187,10 @@ export function PassportImage({ label, src, url }: PassportImageProps) {
|
|||||||
const imageSrc = src ?? url ?? null;
|
const imageSrc = src ?? url ?? null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start py-3 px-4 border-b border-border last:border-0 gap-1 sm:gap-0">
|
<div className="flex flex-col items-start py-3 px-4 border-b border-border last:border-0 gap-1 sm:gap-0">
|
||||||
<span className="text-xs sm:text-sm text-muted-foreground">{label}</span>
|
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
{imageSrc ? (
|
{imageSrc ? (
|
||||||
<img src={imageSrc} alt={label} className="w-28 h-20 object-cover rounded-md border border-border" />
|
<img src={imageSrc} alt={label} className="w-full h-46 object-contain rounded-md border border-border" />
|
||||||
) : (
|
) : (
|
||||||
<div className="w-28 h-20 bg-muted rounded-md border border-border flex items-center justify-center">
|
<div className="w-28 h-20 bg-muted rounded-md border border-border flex items-center justify-center">
|
||||||
<span className="text-xs text-muted-foreground">—</span>
|
<span className="text-xs text-muted-foreground">—</span>
|
||||||
@@ -218,7 +229,7 @@ export interface AuditRowProps {
|
|||||||
export function StatusBadge({ status }: { status: string }) {
|
export function StatusBadge({ status }: { status: string }) {
|
||||||
const normalized = status.toLowerCase();
|
const normalized = status.toLowerCase();
|
||||||
const variant =
|
const variant =
|
||||||
normalized === "success" || normalized === "completed"
|
normalized === "success" || normalized === "completed" || normalized === "finished"
|
||||||
? "default"
|
? "default"
|
||||||
: normalized === "failed" || normalized === "error"
|
: normalized === "failed" || normalized === "error"
|
||||||
? "destructive"
|
? "destructive"
|
||||||
@@ -321,6 +332,87 @@ export function EmptyState({ label }: EmptyStateProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── ViewActions ──────────────────────────────────────────────────────────────
|
||||||
|
// Standard edit (→ `/edit` route) + delete (with confirmation AlertDialog)
|
||||||
|
// action buttons rendered in a view page header. Delete validation and the
|
||||||
|
// destructive mutation itself live in the caller's `onDelete`; this component
|
||||||
|
// only handles the dialog flow (open → confirm → close).
|
||||||
|
|
||||||
|
export interface ViewActionsProps {
|
||||||
|
editTo?: string;
|
||||||
|
onDelete?: () => void | Promise<void>;
|
||||||
|
deleteTitle?: string;
|
||||||
|
deleteDescription?: string;
|
||||||
|
deleting?: boolean;
|
||||||
|
deleteConfirmLabel?: string;
|
||||||
|
editDisabled?: boolean;
|
||||||
|
deleteDisabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ViewActions({
|
||||||
|
editTo,
|
||||||
|
onDelete,
|
||||||
|
deleteTitle,
|
||||||
|
deleteDescription,
|
||||||
|
deleting,
|
||||||
|
deleteConfirmLabel,
|
||||||
|
editDisabled,
|
||||||
|
deleteDisabled,
|
||||||
|
}: ViewActionsProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||||
|
|
||||||
|
const handleConfirm = async () => {
|
||||||
|
await onDelete?.();
|
||||||
|
setDeleteOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{editTo && (
|
||||||
|
<Button variant="outline" size="sm" asChild disabled={editDisabled}>
|
||||||
|
<Link to={editTo}>
|
||||||
|
<Pencil size={14} />
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{onDelete && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={deleteDisabled}
|
||||||
|
className="text-destructive border-destructive/30 hover:bg-destructive/10"
|
||||||
|
onClick={() => setDeleteOpen(true)}
|
||||||
|
>
|
||||||
|
<Trash2 size={14} />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>{deleteTitle ?? t("Are you sure?", "Eminsiňizmi?")}</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{deleteDescription ?? t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz.")}
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>{t("Cancel", "Ýatyr")}</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={handleConfirm}
|
||||||
|
disabled={deleting}
|
||||||
|
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||||
|
>
|
||||||
|
{deleting ? t("Deleting...", "Öçürilýär...") : (deleteConfirmLabel ?? t("Delete", "Öçür"))}
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ─── AuditLog ─────────────────────────────────────────────────────────────────
|
// ─── AuditLog ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function AuditLog({ logs, currentPage, totalPages, totalCount, onPageChange, isLoading, onView }: AuditLogProps) {
|
export function AuditLog({ logs, currentPage, totalPages, totalCount, onPageChange, isLoading, onView }: AuditLogProps) {
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import type { TFunction } from "i18next";
|
||||||
|
import type { SelectOption } from "@/components/formInput";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared helpers for enum-like backend values (status, paid flag, education,
|
||||||
|
* marriage, order type …). The enum itself lives in `constants/`, the
|
||||||
|
* localized text lives in `lib/i18n/locales/{en,ru,tk}.json`.
|
||||||
|
*/
|
||||||
|
export type TranslateFn = TFunction | ((key: string, fallback?: string) => string);
|
||||||
|
|
||||||
|
export interface EnumConfig<T extends string> {
|
||||||
|
/** Allowed values as sent by the backend. */
|
||||||
|
values: readonly T[];
|
||||||
|
/** English fallback labels, used when the locale key is missing. */
|
||||||
|
labels: Record<T, string>;
|
||||||
|
/** i18n key prefix, e.g. "onlinePayments.gatewayStatus". */
|
||||||
|
prefix: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Language-neutral fallback for a backend value we have no translation for:
|
||||||
|
* "gateway_reference" → "gateway reference". Never invents a word, so an
|
||||||
|
* unmapped enum can not leak English into the Turkish/Russian UI.
|
||||||
|
*/
|
||||||
|
export function rawEnumKey(key: string): string {
|
||||||
|
return String(key ?? "")
|
||||||
|
.replace(/[_-]+/g, " ")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isEnumValue<T extends string>(values: readonly T[], key: string): key is T {
|
||||||
|
return values.includes(
|
||||||
|
String(key ?? "")
|
||||||
|
.trim()
|
||||||
|
.toLowerCase() as T,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Normalizes a backend key so "MARRIED" and "married" resolve to the same enum value. */
|
||||||
|
function normalize<T extends string>(values: readonly T[], key: string): T | undefined {
|
||||||
|
const needle = String(key ?? "")
|
||||||
|
.trim()
|
||||||
|
.toLowerCase();
|
||||||
|
return values.find((value) => value.toLowerCase() === needle);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Select options for an enum, localized when `t` is given. */
|
||||||
|
export function buildEnumOptions<T extends string>(config: EnumConfig<T>, t?: TranslateFn): SelectOption[] {
|
||||||
|
return config.values.map((value) => ({
|
||||||
|
value,
|
||||||
|
label: t ? t(`${config.prefix}.${value}`, config.labels[value]) : config.labels[value],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Localized label for one enum value; unknown keys fall back to the raw backend value. */
|
||||||
|
export function getEnumLabel<T extends string>(config: EnumConfig<T>, key: string, t?: TranslateFn): string {
|
||||||
|
const value = normalize(config.values, key);
|
||||||
|
if (!value) return rawEnumKey(key);
|
||||||
|
return t ? t(`${config.prefix}.${value}`, config.labels[value]) : config.labels[value];
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import type { SelectOption } from "@/components/formInput";
|
||||||
|
import { buildEnumOptions, getEnumLabel, type EnumConfig, type TranslateFn } from "@/constants/enumLabels";
|
||||||
|
|
||||||
|
// ─── Education level ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const EDUCATION_VALUES = [
|
||||||
|
"high",
|
||||||
|
"higher",
|
||||||
|
"unfinished_high",
|
||||||
|
"masters",
|
||||||
|
"phd",
|
||||||
|
"middle",
|
||||||
|
"secondary",
|
||||||
|
"school",
|
||||||
|
"school_dropout",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type EducationValue = (typeof EDUCATION_VALUES)[number];
|
||||||
|
|
||||||
|
export const EDUCATION_LABELS: Record<EducationValue, string> = {
|
||||||
|
high: "Higher secondary",
|
||||||
|
higher: "Higher education",
|
||||||
|
unfinished_high: "Incomplete higher secondary",
|
||||||
|
masters: "Master's degree",
|
||||||
|
phd: "Doctor of science",
|
||||||
|
middle: "Secondary school",
|
||||||
|
secondary: "Secondary education",
|
||||||
|
school: "Secondary education",
|
||||||
|
school_dropout: "Incomplete secondary education",
|
||||||
|
};
|
||||||
|
|
||||||
|
const EDUCATION_ENUM: EnumConfig<EducationValue> = {
|
||||||
|
values: EDUCATION_VALUES,
|
||||||
|
labels: EDUCATION_LABELS,
|
||||||
|
prefix: "options.education",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── Marital status ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const MARRIAGE_VALUES = ["MARRIED", "SINGLE", "DIVORCED", "WIDOW", "LEGAL"] as const;
|
||||||
|
|
||||||
|
export type MarriageValue = (typeof MARRIAGE_VALUES)[number];
|
||||||
|
|
||||||
|
export const MARRIAGE_LABELS: Record<MarriageValue, string> = {
|
||||||
|
MARRIED: "Married",
|
||||||
|
SINGLE: "Single",
|
||||||
|
DIVORCED: "Divorced",
|
||||||
|
WIDOW: "Widowed",
|
||||||
|
LEGAL: "Not married / legally single",
|
||||||
|
};
|
||||||
|
|
||||||
|
const MARRIAGE_ENUM: EnumConfig<MarriageValue> = {
|
||||||
|
values: MARRIAGE_VALUES,
|
||||||
|
labels: MARRIAGE_LABELS,
|
||||||
|
prefix: "options.marriage",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getEducationOptions(t?: TranslateFn): SelectOption[] {
|
||||||
|
return buildEnumOptions(EDUCATION_ENUM, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getEducationLabel(value: string, t?: TranslateFn): string {
|
||||||
|
return getEnumLabel(EDUCATION_ENUM, value, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMarriageOptions(t?: TranslateFn): SelectOption[] {
|
||||||
|
return buildEnumOptions(MARRIAGE_ENUM, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMarriageLabel(value: string, t?: TranslateFn): string {
|
||||||
|
return getEnumLabel(MARRIAGE_ENUM, value, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Month options for date pickers, "01" … "12". */
|
||||||
|
export const MONTH_OPTIONS: SelectOption[] = Array.from({ length: 12 }, (_, i) => {
|
||||||
|
const val = String(i + 1).padStart(2, "0");
|
||||||
|
return { value: val, label: val };
|
||||||
|
});
|
||||||
|
|
||||||
|
export const YEAR_OPTIONS: SelectOption[] = Array.from({ length: 15 }, (_, i) => {
|
||||||
|
const year = String(new Date().getFullYear() + i);
|
||||||
|
return { value: year, label: year };
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Longer expiry range used by card balance / requisites / transaction forms. */
|
||||||
|
export const CARD_YEAR_OPTIONS: SelectOption[] = Array.from({ length: 20 }, (_, i) => {
|
||||||
|
const year = String(new Date().getFullYear() + i);
|
||||||
|
return { value: year, label: year };
|
||||||
|
});
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
export * from "./enumLabels";
|
||||||
|
export * from "./formOptions";
|
||||||
|
export * from "./orderTypes";
|
||||||
|
export * from "./passportSeries";
|
||||||
|
export * from "./paymentStatus";
|
||||||
|
export * from "./regionCodes";
|
||||||
|
export * from "./statusOptions";
|
||||||
|
export * from "./statusCells";
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { buildEnumOptions, getEnumLabel, type EnumConfig, type TranslateFn } from "@/constants/enumLabels";
|
||||||
|
|
||||||
|
/** Order kinds returned by the analytics endpoints (`orderType` field). */
|
||||||
|
export const ORDER_TYPE_VALUES = ["loan", "loan_paid_off_letter", "card", "card_pin", "card_rekwizit", "visa_master"] as const;
|
||||||
|
|
||||||
|
export type OrderTypeValue = (typeof ORDER_TYPE_VALUES)[number];
|
||||||
|
|
||||||
|
export const ORDER_TYPE_LABELS: Record<OrderTypeValue, string> = {
|
||||||
|
loan: "Loan orders",
|
||||||
|
loan_paid_off_letter: "Loan paid-off letter",
|
||||||
|
card: "New card",
|
||||||
|
card_pin: "Card PIN",
|
||||||
|
card_rekwizit: "Card requisites",
|
||||||
|
visa_master: "Visa / Master",
|
||||||
|
};
|
||||||
|
|
||||||
|
const ORDER_TYPE_ENUM: EnumConfig<OrderTypeValue> = {
|
||||||
|
values: ORDER_TYPE_VALUES,
|
||||||
|
labels: ORDER_TYPE_LABELS,
|
||||||
|
prefix: "analytics.orderType",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function getOrderTypeLabel(type: string, t?: TranslateFn, prefix?: string): string {
|
||||||
|
return getEnumLabel(prefix ? { ...ORDER_TYPE_ENUM, prefix } : ORDER_TYPE_ENUM, type, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getOrderTypeOptions(t?: TranslateFn) {
|
||||||
|
return buildEnumOptions(ORDER_TYPE_ENUM, t);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import type { SelectOption } from "@/components/formInput";
|
||||||
|
|
||||||
|
export const PASSPORT_SERIES = ["I-AŞ", "I-MR", "II-MR", "I-AH", "II-AH", "I-LB", "II-LB", "I-BN", "II-BN", "I-DZ", "II-DZ"] as const;
|
||||||
|
|
||||||
|
export type PassportSerie = (typeof PASSPORT_SERIES)[number];
|
||||||
|
|
||||||
|
export const PASSPORT_SERIES_OPTIONS: SelectOption[] = PASSPORT_SERIES.map((serie) => ({
|
||||||
|
label: serie,
|
||||||
|
value: serie,
|
||||||
|
}));
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import type { ComponentType } from "react";
|
||||||
|
import { AlertCircle, CheckCircle2, Clock, XCircle } from "lucide-react";
|
||||||
|
import type { SelectOption } from "@/components/formInput";
|
||||||
|
import type { StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||||
|
import { buildEnumOptions, getEnumLabel, isEnumValue, type EnumConfig, type TranslateFn } from "@/constants/enumLabels";
|
||||||
|
|
||||||
|
// ─── Gateway status ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const GATEWAY_STATUS_VALUES = ["pending", "paid", "unpaid", "failed", "success", "completed"] as const;
|
||||||
|
|
||||||
|
export type GatewayStatusValue = (typeof GATEWAY_STATUS_VALUES)[number];
|
||||||
|
|
||||||
|
export const GATEWAY_STATUS_LABELS: Record<GatewayStatusValue, string> = {
|
||||||
|
pending: "Pending",
|
||||||
|
paid: "Paid",
|
||||||
|
unpaid: "Unpaid",
|
||||||
|
failed: "Failed",
|
||||||
|
success: "Success",
|
||||||
|
completed: "Completed",
|
||||||
|
};
|
||||||
|
|
||||||
|
const GATEWAY_STATUS_ENUM: EnumConfig<GatewayStatusValue> = {
|
||||||
|
values: GATEWAY_STATUS_VALUES,
|
||||||
|
labels: GATEWAY_STATUS_LABELS,
|
||||||
|
prefix: "onlinePayments.gatewayStatus",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const GATEWAY_STATUS_BADGE_VARIANTS: Record<GatewayStatusValue, StatusBadgeVariant> = {
|
||||||
|
pending: "warning",
|
||||||
|
paid: "success",
|
||||||
|
unpaid: "default",
|
||||||
|
failed: "error",
|
||||||
|
success: "success",
|
||||||
|
completed: "info",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const GATEWAY_STATUS_ICONS: Record<GatewayStatusValue, ComponentType> = {
|
||||||
|
pending: AlertCircle,
|
||||||
|
paid: CheckCircle2,
|
||||||
|
unpaid: Clock,
|
||||||
|
failed: XCircle,
|
||||||
|
success: CheckCircle2,
|
||||||
|
completed: CheckCircle2,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── Paid flag ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const PAID_VALUES = ["paid", "unpaid"] as const;
|
||||||
|
|
||||||
|
export type PaidValue = (typeof PAID_VALUES)[number];
|
||||||
|
|
||||||
|
export const PAID_LABELS: Record<PaidValue, string> = {
|
||||||
|
paid: "Paid",
|
||||||
|
unpaid: "Unpaid",
|
||||||
|
};
|
||||||
|
|
||||||
|
const PAID_ENUM: EnumConfig<PaidValue> = {
|
||||||
|
values: PAID_VALUES,
|
||||||
|
labels: PAID_LABELS,
|
||||||
|
prefix: "onlinePayments.paid",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PAID_BADGE_VARIANTS: Record<PaidValue, StatusBadgeVariant> = {
|
||||||
|
paid: "success",
|
||||||
|
unpaid: "error",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PAID_ICONS: Record<PaidValue, ComponentType> = {
|
||||||
|
paid: CheckCircle2,
|
||||||
|
unpaid: XCircle,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function withPrefix<T extends string>(config: EnumConfig<T>, prefix?: string): EnumConfig<T> {
|
||||||
|
return prefix ? { ...config, prefix } : config;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isGatewayStatusValue(status: string): status is GatewayStatusValue {
|
||||||
|
return isEnumValue(GATEWAY_STATUS_VALUES, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getGatewayStatusLabel(status: string, t?: TranslateFn, prefix?: string): string {
|
||||||
|
return getEnumLabel(withPrefix(GATEWAY_STATUS_ENUM, prefix), status, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getGatewayStatusOptions(t?: TranslateFn, prefix?: string): SelectOption[] {
|
||||||
|
return buildEnumOptions(withPrefix(GATEWAY_STATUS_ENUM, prefix), t);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PAYMENT_HISTORY_STATUS_VALUES = ["failed", "pending", "success", "completed"] as const;
|
||||||
|
|
||||||
|
export function getPaymentHistoryStatusOptions(t?: TranslateFn, prefix?: string): SelectOption[] {
|
||||||
|
return buildEnumOptions(
|
||||||
|
withPrefix(
|
||||||
|
{
|
||||||
|
values: PAYMENT_HISTORY_STATUS_VALUES,
|
||||||
|
labels: GATEWAY_STATUS_LABELS,
|
||||||
|
prefix: "onlinePayments.gatewayStatus",
|
||||||
|
},
|
||||||
|
prefix,
|
||||||
|
),
|
||||||
|
t,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toPaidValue(paid: boolean): PaidValue {
|
||||||
|
return paid ? "paid" : "unpaid";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPaidLabel(paid: boolean, t?: TranslateFn, prefix?: string): string {
|
||||||
|
return getEnumLabel(withPrefix(PAID_ENUM, prefix), toPaidValue(paid), t);
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import type { TFunction } from "i18next";
|
||||||
|
import type { SelectOption } from "@/components/formInput";
|
||||||
|
|
||||||
|
export const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR", "BL"] as const;
|
||||||
|
|
||||||
|
export type RegionCode = (typeof REGION_CODES)[number];
|
||||||
|
|
||||||
|
/** Distinct region set used by loan paid-off letters. */
|
||||||
|
export const LOAN_PAID_OFF_REGION_CODES = ["AG", "AH", "BA", "DA", "LE", "MA"] as const;
|
||||||
|
|
||||||
|
export type LoanPaidOffRegionCode = (typeof LOAN_PAID_OFF_REGION_CODES)[number];
|
||||||
|
|
||||||
|
export const REGION_LABELS: Record<string, string> = {
|
||||||
|
AG: "Aşgabat",
|
||||||
|
AH: "Ahal",
|
||||||
|
BN: "Balkan",
|
||||||
|
BL: "Balkan",
|
||||||
|
DZ: "Daşoguz",
|
||||||
|
LB: "Lebap",
|
||||||
|
MR: "Mary",
|
||||||
|
};
|
||||||
|
|
||||||
|
type TranslateFn = TFunction | ((key: string, fallback?: string) => string);
|
||||||
|
|
||||||
|
export function getRegionOptions(
|
||||||
|
t: TranslateFn,
|
||||||
|
prefix = "loanOrders",
|
||||||
|
codes: readonly string[] = REGION_CODES,
|
||||||
|
labels?: Record<string, string>,
|
||||||
|
): SelectOption[] {
|
||||||
|
return codes.map((code) => ({
|
||||||
|
value: code,
|
||||||
|
label: t(`${prefix}.regions.${code}`, labels?.[code] ?? code),
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { CheckCircle2, XCircle } from "lucide-react";
|
||||||
|
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||||
|
import { STATUS_ICONS, STATUS_BADGE_VARIANTS, isStatusValue, getStatusLabel } from "@/constants/statusOptions";
|
||||||
|
import {
|
||||||
|
GATEWAY_STATUS_BADGE_VARIANTS,
|
||||||
|
GATEWAY_STATUS_ICONS,
|
||||||
|
getGatewayStatusLabel,
|
||||||
|
isGatewayStatusValue,
|
||||||
|
} from "@/constants/paymentStatus";
|
||||||
|
|
||||||
|
interface StatusCellProps {
|
||||||
|
status: string;
|
||||||
|
prefix?: string;
|
||||||
|
fallbackLabels?: Record<string, string>;
|
||||||
|
fallbackVariants?: Record<string, StatusBadgeVariant>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StatusCell({ status, prefix = "status", fallbackLabels, fallbackVariants }: StatusCellProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
if (isStatusValue(status)) {
|
||||||
|
return <StatusBadge label={getStatusLabel(status, t, prefix)} variant={STATUS_BADGE_VARIANTS[status]} icon={STATUS_ICONS[status]} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const label = (fallbackLabels && fallbackLabels[status]) ?? status;
|
||||||
|
const variant = (fallbackVariants && fallbackVariants[status]) ?? "default";
|
||||||
|
return <StatusBadge label={label} variant={variant} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ActiveStatusCellProps {
|
||||||
|
active?: boolean;
|
||||||
|
status?: boolean;
|
||||||
|
labelActive?: string;
|
||||||
|
labelInactive?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ActiveStatusCell({ active, status, labelActive, labelInactive }: ActiveStatusCellProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const isActive = Boolean(active ?? status);
|
||||||
|
return (
|
||||||
|
<StatusBadge
|
||||||
|
label={isActive ? (labelActive ?? t("common.active", "Işjeň")) : (labelInactive ?? t("common.inactive", "Işjeň däl"))}
|
||||||
|
variant={isActive ? "success" : "default"}
|
||||||
|
icon={isActive ? CheckCircle2 : XCircle}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GatewayStatusCellProps {
|
||||||
|
status?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GatewayStatusCell({ status }: GatewayStatusCellProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const normalizedStatus = status || "unknown";
|
||||||
|
|
||||||
|
if (isGatewayStatusValue(normalizedStatus)) {
|
||||||
|
return (
|
||||||
|
<StatusBadge
|
||||||
|
label={getGatewayStatusLabel(normalizedStatus, t)}
|
||||||
|
variant={GATEWAY_STATUS_BADGE_VARIANTS[normalizedStatus]}
|
||||||
|
icon={GATEWAY_STATUS_ICONS[normalizedStatus]}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return <StatusBadge label={normalizedStatus} variant="default" />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import type { TFunction } from "i18next";
|
||||||
|
import type { ComponentType } from "react";
|
||||||
|
import { Clock, CheckCircle2, XCircle, CheckCheck } from "lucide-react";
|
||||||
|
import type { SelectOption } from "@/components/formInput";
|
||||||
|
import type { StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||||
|
|
||||||
|
export const STATUS_ICONS: Record<StatusValue, ComponentType> = {
|
||||||
|
pending: Clock,
|
||||||
|
approved: CheckCircle2,
|
||||||
|
rejected: XCircle,
|
||||||
|
completed: CheckCheck,
|
||||||
|
// satisfied: CheckCircle2,
|
||||||
|
// processing: Clock,
|
||||||
|
// cancelled: XCircle,
|
||||||
|
// registered: CheckCircle2,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DEFAULT_STATUS_VALUES = ["pending", "approved", "rejected", "completed"] as const;
|
||||||
|
|
||||||
|
export const STATUS_VALUES = [
|
||||||
|
"pending",
|
||||||
|
"approved",
|
||||||
|
"rejected",
|
||||||
|
"completed",
|
||||||
|
// "satisfied",
|
||||||
|
// "processing",
|
||||||
|
// "cancelled",
|
||||||
|
// "registered",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type StatusValue = (typeof STATUS_VALUES)[number];
|
||||||
|
|
||||||
|
export const STATUS_OPTIONS: SelectOption[] = [
|
||||||
|
{ value: "pending", label: "Pending" },
|
||||||
|
{ value: "approved", label: "Approved" },
|
||||||
|
{ value: "rejected", label: "Rejected" },
|
||||||
|
{ value: "completed", label: "Completed" },
|
||||||
|
];
|
||||||
|
|
||||||
|
type TranslateFn = TFunction | ((key: string, fallback?: string) => string);
|
||||||
|
|
||||||
|
export function getStatusOptions(
|
||||||
|
t?: TranslateFn,
|
||||||
|
prefix = "status",
|
||||||
|
values: readonly StatusValue[] = DEFAULT_STATUS_VALUES,
|
||||||
|
): SelectOption[] {
|
||||||
|
if (!t) {
|
||||||
|
return values.map((val) => ({
|
||||||
|
value: val,
|
||||||
|
label: STATUS_LABEL_FALLBACKS[val] ?? val,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
return values.map((val) => ({
|
||||||
|
value: val,
|
||||||
|
label: t(`${prefix}.${val}`, STATUS_LABEL_FALLBACKS[val] ?? val),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export const STATUS_BADGE_VARIANTS: Record<StatusValue, StatusBadgeVariant> = {
|
||||||
|
pending: "warning",
|
||||||
|
approved: "success",
|
||||||
|
rejected: "error",
|
||||||
|
completed: "info",
|
||||||
|
// satisfied: "success",
|
||||||
|
// processing: "info",
|
||||||
|
// cancelled: "error",
|
||||||
|
// registered: "default",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const STATUS_LABEL_FALLBACKS: Record<string, string> = {
|
||||||
|
pending: "Pending",
|
||||||
|
approved: "Approved",
|
||||||
|
rejected: "Rejected",
|
||||||
|
completed: "Completed",
|
||||||
|
satisfied: "Satisfied",
|
||||||
|
processing: "Processing",
|
||||||
|
cancelled: "Cancelled",
|
||||||
|
registered: "Registered",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isStatusValue(value: string): value is StatusValue {
|
||||||
|
return STATUS_VALUES.includes(value as StatusValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getStatusLabel(status: string, t?: TranslateFn, prefix = "status"): string {
|
||||||
|
const fallback = STATUS_LABEL_FALLBACKS[status] ?? status;
|
||||||
|
return t ? t(`${prefix}.${status}`, fallback) : fallback;
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface ActivityLogUser {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
role: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActivityLog {
|
||||||
|
id: number;
|
||||||
|
userId: number;
|
||||||
|
user: ActivityLogUser;
|
||||||
|
method: string;
|
||||||
|
path: string;
|
||||||
|
module: string;
|
||||||
|
action: string;
|
||||||
|
statusCode: number;
|
||||||
|
requestBody: Record<string, unknown> | null;
|
||||||
|
ip: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActivityLogsResponse {
|
||||||
|
count: number;
|
||||||
|
logs: ActivityLog[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActivityLogsParams {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
user_id?: number;
|
||||||
|
module?: string;
|
||||||
|
action?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const activityLogsApi = {
|
||||||
|
getActivityLogs: async (params: ActivityLogsParams = {}, signal?: AbortSignal): Promise<ActivityLogsResponse> => {
|
||||||
|
const { page, limit, user_id, module, action } = params;
|
||||||
|
const { data } = await apiClient.get<ActivityLogsResponse>("/activity-logs", {
|
||||||
|
params: { page, limit, user_id, module, action },
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
getActivityLogById: async (id: number): Promise<ActivityLog> => {
|
||||||
|
const { data } = await apiClient.get<ActivityLog>(`/activity-logs/${id}`);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { activityLogsApi, type ActivityLogsParams } from "../api/activityLogsApi";
|
||||||
|
|
||||||
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const activityLogKeys = {
|
||||||
|
all: ["activityLogs"] as const,
|
||||||
|
lists: () => [...activityLogKeys.all, "list"] as const,
|
||||||
|
list: (params: ActivityLogsParams) => [...activityLogKeys.lists(), params] as const,
|
||||||
|
details: () => [...activityLogKeys.all, "detail"] as const,
|
||||||
|
detail: (id: number) => [...activityLogKeys.details(), id] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── useActivityLogs ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useActivityLogs(params: ActivityLogsParams = {}) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: activityLogKeys.list(params),
|
||||||
|
queryFn: ({ signal }) => activityLogsApi.getActivityLogs(params, signal),
|
||||||
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── useActivityLog ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useActivityLog(id: number) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: activityLogKeys.detail(id),
|
||||||
|
queryFn: () => activityLogsApi.getActivityLogById(id),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,198 +1,122 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface User {
|
export interface SocialMedia {
|
||||||
id: number
|
facebook: string;
|
||||||
username: string
|
instagram: string;
|
||||||
name: string
|
telegram: string;
|
||||||
phone: string
|
|
||||||
email: string | null
|
|
||||||
isActive: boolean
|
|
||||||
phoneVerified: boolean
|
|
||||||
createdAt: string
|
|
||||||
updatedAt: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserListItem {
|
export interface User {
|
||||||
id: number
|
id: number;
|
||||||
username: string
|
email: string;
|
||||||
name: string
|
name: string;
|
||||||
phone: string
|
firstName: string;
|
||||||
email: string | null
|
lastName: string;
|
||||||
isActive: boolean
|
username: string;
|
||||||
|
phone: string;
|
||||||
|
avatar: string;
|
||||||
|
socialMedia: SocialMedia;
|
||||||
|
lightMode: number;
|
||||||
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
|
active: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UsersListResponse {
|
export interface UsersListResponse {
|
||||||
data: UserListItem[]
|
count: number;
|
||||||
total: number
|
users: User[];
|
||||||
page: number
|
|
||||||
perPage: number
|
|
||||||
totalPages: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UsersListParams {
|
export interface UsersListParams {
|
||||||
page?: number
|
page?: number;
|
||||||
perPage?: number
|
limit?: number;
|
||||||
search?: string
|
search?: string;
|
||||||
isActive?: string
|
isActive?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateUserPayload {
|
export interface CreateUserPayload {
|
||||||
username: string
|
active: boolean;
|
||||||
name: string
|
avatar: string;
|
||||||
phone: string
|
email: string;
|
||||||
email?: string
|
firstName: string;
|
||||||
password: string
|
lastName: string;
|
||||||
phoneVerified: boolean
|
lightMode: number;
|
||||||
isActive: boolean
|
name: string;
|
||||||
|
password: string;
|
||||||
|
phone: string;
|
||||||
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
|
socialMedia: SocialMedia;
|
||||||
|
username: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateUserPayload {
|
export interface UpdateUserPayload {
|
||||||
username?: string
|
active?: boolean;
|
||||||
name?: string
|
avatar?: string;
|
||||||
phone?: string
|
email?: string;
|
||||||
email?: string
|
firstName?: string;
|
||||||
phoneVerified?: boolean
|
lastName?: string;
|
||||||
isActive?: boolean
|
lightMode?: number;
|
||||||
|
name?: string;
|
||||||
|
phone?: string;
|
||||||
|
/** Role code. If both role and roleId are provided, roleId takes precedence. */
|
||||||
|
role?: string;
|
||||||
|
/** Role ID. Takes precedence over `role` code when both are present. */
|
||||||
|
roleId?: number;
|
||||||
|
socialMedia?: SocialMedia;
|
||||||
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
/** Payload for PUT /users/:id/role */
|
||||||
|
export interface UpdateUserRolePayload {
|
||||||
const MOCK_USERS: User[] = Array.from({ length: 50 }, (_, i) => {
|
roleId: number;
|
||||||
const id = 5970 - i
|
}
|
||||||
const names = [
|
|
||||||
'Orazowa Nurtuwak Täşliyewna',
|
|
||||||
'Hallyýewa Aýna Gurbanmyradowna',
|
|
||||||
'Sopýýewa Maral Agamyradowna',
|
|
||||||
'Babamurat Baýnazarow Şanazarowič',
|
|
||||||
'Narmet Narmet',
|
|
||||||
'Sheker Durdyyewa',
|
|
||||||
'kamalowyusup',
|
|
||||||
'Mahmudowberdimet',
|
|
||||||
'allanazarowasayyara',
|
|
||||||
'dadayewjepbar',
|
|
||||||
]
|
|
||||||
const usernames = [
|
|
||||||
'Nurtuwak_1970', 'Ayna_1989', 'Maral_1974', 'Babamurat_0002', 'Narmet',
|
|
||||||
'8319_ShekerDurdyyewa', 'kamalowyusup', 'Mahmudowberdimet',
|
|
||||||
'allanazarowasayyara', 'dadayewjepbar',
|
|
||||||
]
|
|
||||||
const idx = i % names.length
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
username: i < usernames.length ? usernames[idx] : `user_${id}`,
|
|
||||||
name: names[idx],
|
|
||||||
phone: `+(993)-6${Math.floor(Math.random() * 9 + 1)}-${String(Math.floor(Math.random() * 90 + 10))}-${String(Math.floor(Math.random() * 90 + 10))}-${String(Math.floor(Math.random() * 90 + 10))}`,
|
|
||||||
email: i % 4 === 0 ? `user${id}@tbbank.gov.tm` : null,
|
|
||||||
isActive: Math.random() > 0.1,
|
|
||||||
phoneVerified: Math.random() > 0.3,
|
|
||||||
createdAt: new Date(Date.now() - Math.random() * 1e10).toISOString(),
|
|
||||||
updatedAt: new Date(Date.now() - Math.random() * 1e9).toISOString(),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// ─── Mock delay helper ────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms))
|
|
||||||
|
|
||||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const usersApi = {
|
export const usersApi = {
|
||||||
/**
|
/** GET /users — backend filters by `username` */
|
||||||
* GET /users
|
getUsers: async (params: UsersListParams = {}, signal?: AbortSignal): Promise<UsersListResponse> => {
|
||||||
*/
|
const { page, limit, search, isActive } = params;
|
||||||
getUsers: async (params: UsersListParams = {}): Promise<UsersListResponse> => {
|
const queryParams: Record<string, string | number | undefined> = { page, limit, isActive };
|
||||||
await delay()
|
if (search) queryParams.username = search;
|
||||||
// Uncomment for real API:
|
const { data } = await apiClient.get<UsersListResponse>("/users", {
|
||||||
// const res = await apiClient.get<UsersListResponse>('/users', { params })
|
params: queryParams,
|
||||||
// return res.data
|
signal,
|
||||||
|
});
|
||||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
return data;
|
||||||
|
|
||||||
let filtered = [...MOCK_USERS]
|
|
||||||
|
|
||||||
if (search.trim()) {
|
|
||||||
const q = search.toLowerCase()
|
|
||||||
filtered = filtered.filter(
|
|
||||||
(u) =>
|
|
||||||
u.username.toLowerCase().includes(q) ||
|
|
||||||
u.name.toLowerCase().includes(q) ||
|
|
||||||
u.phone.includes(q),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isActive !== undefined && isActive !== '') {
|
|
||||||
const active = isActive === 'true'
|
|
||||||
filtered = filtered.filter((u) => u.isActive === active)
|
|
||||||
}
|
|
||||||
|
|
||||||
const total = filtered.length
|
|
||||||
const totalPages = Math.ceil(total / perPage)
|
|
||||||
const start = (page - 1) * perPage
|
|
||||||
const data = filtered.slice(start, start + perPage).map(({ id, username, name, phone, email, isActive }) => ({
|
|
||||||
id, username, name, phone, email, isActive,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return { data, total, page, perPage, totalPages }
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/** GET /users/:id */
|
||||||
* GET /users/:id
|
|
||||||
*/
|
|
||||||
getUserById: async (id: number): Promise<User> => {
|
getUserById: async (id: number): Promise<User> => {
|
||||||
await delay()
|
const { data } = await apiClient.get<User>(`/users/${id}`);
|
||||||
// const res = await apiClient.get<User>(`/users/${id}`)
|
return data;
|
||||||
// return res.data
|
|
||||||
|
|
||||||
const user = MOCK_USERS.find((u) => u.id === id)
|
|
||||||
if (!user) throw new Error(`User ${id} not found`)
|
|
||||||
return user
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/** POST /users */
|
||||||
* POST /users
|
|
||||||
*/
|
|
||||||
createUser: async (payload: CreateUserPayload): Promise<User> => {
|
createUser: async (payload: CreateUserPayload): Promise<User> => {
|
||||||
await delay(800)
|
const { data } = await apiClient.post<User>("/users", payload);
|
||||||
// const res = await apiClient.post<User>('/users', payload)
|
return data;
|
||||||
// return res.data
|
|
||||||
|
|
||||||
const newUser: User = {
|
|
||||||
id: Math.max(...MOCK_USERS.map((u) => u.id)) + 1,
|
|
||||||
username: payload.username,
|
|
||||||
name: payload.name,
|
|
||||||
phone: payload.phone,
|
|
||||||
email: payload.email ?? null,
|
|
||||||
isActive: payload.isActive,
|
|
||||||
phoneVerified: payload.phoneVerified,
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
updatedAt: new Date().toISOString(),
|
|
||||||
}
|
|
||||||
MOCK_USERS.unshift(newUser)
|
|
||||||
return newUser
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/** PUT /users/:id */
|
||||||
* PUT /users/:id
|
|
||||||
*/
|
|
||||||
updateUser: async (id: number, payload: UpdateUserPayload): Promise<User> => {
|
updateUser: async (id: number, payload: UpdateUserPayload): Promise<User> => {
|
||||||
await delay(800)
|
const { data } = await apiClient.put<User>(`/users/${id}`, payload);
|
||||||
// const res = await apiClient.put<User>(`/users/${id}`, payload)
|
return data;
|
||||||
// return res.data
|
|
||||||
|
|
||||||
const idx = MOCK_USERS.findIndex((u) => u.id === id)
|
|
||||||
if (idx === -1) throw new Error(`User ${id} not found`)
|
|
||||||
MOCK_USERS[idx] = { ...MOCK_USERS[idx], ...payload, updatedAt: new Date().toISOString() }
|
|
||||||
return MOCK_USERS[idx]
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/** DELETE /users/:id */
|
||||||
* DELETE /users/:id
|
|
||||||
*/
|
|
||||||
deleteUser: async (id: number): Promise<void> => {
|
deleteUser: async (id: number): Promise<void> => {
|
||||||
await delay(600)
|
await apiClient.delete(`/users/${id}`);
|
||||||
// await apiClient.delete(`/users/${id}`)
|
|
||||||
|
|
||||||
const idx = MOCK_USERS.findIndex((u) => u.id === id)
|
|
||||||
if (idx !== -1) MOCK_USERS.splice(idx, 1)
|
|
||||||
},
|
},
|
||||||
}
|
|
||||||
|
/** PUT /users/:id/role — dedicated endpoint to change a user's role */
|
||||||
|
updateUserRole: async (id: number, payload: UpdateUserRolePayload): Promise<User> => {
|
||||||
|
const { data } = await apiClient.put<User>(`/users/${id}/role`, payload);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -1,16 +1,19 @@
|
|||||||
import { useMemo, useEffect, useCallback } from "react";
|
import { useMemo, useEffect, useCallback, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { FormInput } from "@/components/formInput";
|
import { FormInput } from "@/components/formInput";
|
||||||
|
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { FormActions } from "@/components/formActions";
|
import { FormActions } from "@/components/formActions";
|
||||||
|
import { AvatarUpload } from "@/components/avatarUpload";
|
||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import { useCreateUser, useUpdateUser } from "../hooks/useAllUsers";
|
import { useCreateUser, useUpdateUser } from "../hooks/useAllUsers";
|
||||||
|
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||||
import type { User } from "../api/allUsersApi";
|
import type { User } from "../api/allUsersApi";
|
||||||
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/allUser.schema";
|
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload, buildUpdatePayload } from "../schemas/allUser.schema";
|
||||||
import type { AllUserFormData } from "../schemas/allUser.schema";
|
import type { AllUserFormData } from "../schemas/allUser.schema";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
@@ -50,6 +53,35 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
|||||||
|
|
||||||
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language]);
|
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language]);
|
||||||
|
|
||||||
|
// ── Role infinite-scroll select ──
|
||||||
|
const [roleSearch, setRoleSearch] = useState("");
|
||||||
|
const roleQuery = useInfiniteRoles(roleSearch);
|
||||||
|
|
||||||
|
const roleSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||||
|
const opts: InfiniteSelectOption[] = (roleQuery.data?.pages ?? [])
|
||||||
|
.flatMap((p) => p?.roles ?? [])
|
||||||
|
.map((r) => ({ value: r.code, label: r.name }));
|
||||||
|
|
||||||
|
// Ensure the currently-selected role is present (edit mode), even if it
|
||||||
|
// lives beyond the pages loaded so far.
|
||||||
|
if (initialData) {
|
||||||
|
const current = initialData.role;
|
||||||
|
if (current && !opts.some((o) => o.value === current)) {
|
||||||
|
opts.unshift({ value: current, label: current });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
options: opts,
|
||||||
|
loading: roleQuery.isLoading,
|
||||||
|
isLoadingMore: roleQuery.isFetchingNextPage,
|
||||||
|
hasNextPage: !!roleQuery.hasNextPage,
|
||||||
|
onLoadMore: () => roleQuery.fetchNextPage(),
|
||||||
|
searchValue: roleSearch,
|
||||||
|
onSearchChange: setRoleSearch,
|
||||||
|
};
|
||||||
|
}, [roleQuery, roleSearch, initialData]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -65,11 +97,19 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
|||||||
...DEFAULT_FORM_VALUES,
|
...DEFAULT_FORM_VALUES,
|
||||||
username: initialData.username,
|
username: initialData.username,
|
||||||
name: initialData.name,
|
name: initialData.name,
|
||||||
phone: initialData.phone.replace(/^\+993[-\s]?/, ""),
|
firstName: initialData.firstName ?? "",
|
||||||
|
lastName: initialData.lastName ?? "",
|
||||||
|
phone: initialData.phone.replace(/\D/g, "").slice(-8),
|
||||||
email: initialData.email ?? "",
|
email: initialData.email ?? "",
|
||||||
|
avatar: initialData.avatar ?? "",
|
||||||
|
role: initialData.role ?? "",
|
||||||
|
roleId: initialData.roleId ? String(initialData.roleId) : "",
|
||||||
|
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||||
|
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||||
|
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||||
|
lightMode: !!initialData.lightMode,
|
||||||
password: "",
|
password: "",
|
||||||
phoneVerified: initialData.phoneVerified,
|
active: !!initialData.active,
|
||||||
isActive: initialData.isActive,
|
|
||||||
}
|
}
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
});
|
});
|
||||||
@@ -99,17 +139,11 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
|||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
const payload = buildPayload(data);
|
const payload = buildPayload(data);
|
||||||
await createUser.mutateAsync(payload);
|
await createUser.mutateAsync(payload);
|
||||||
navigate("/users");
|
navigate("/all-users");
|
||||||
} else {
|
} else {
|
||||||
await updateUser.mutateAsync({
|
const payload = buildUpdatePayload(data);
|
||||||
username: data.username.trim(),
|
await updateUser.mutateAsync(payload);
|
||||||
name: data.name.trim(),
|
navigate(`/all-users/${initialData!.id}`);
|
||||||
phone: data.phone.trim(),
|
|
||||||
email: data.email.trim() || undefined,
|
|
||||||
phoneVerified: data.phoneVerified,
|
|
||||||
isActive: data.isActive,
|
|
||||||
});
|
|
||||||
navigate(`/users/${initialData!.id}`);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -118,103 +152,150 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
|||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === "create" ? t("users.createTitle", "Ulanyjy dörediň") : t("users.editTitle", "Ulanyjy üýtgetmek")}
|
{mode === "create" ? t("users.createTitle", "Ulanyjy dörediň") : t("users.editTitle", "Ulanyjy üýtgetmek")}
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
{/* ── Identity ── */}
|
||||||
<FormInput
|
<BentoCard title={t("users.sections.identity", "Şahsy maglumat")}>
|
||||||
type="text"
|
<div className="grid grid-cols-2 gap-3">
|
||||||
label={t("users.fields.username", "Ulanyjy ady")}
|
|
||||||
value={form.username}
|
|
||||||
onChange={(v) => setField("username", v)}
|
|
||||||
placeholder={t("users.fields.username", "Ulanyjy ady")}
|
|
||||||
error={errors.username}
|
|
||||||
disabled={isPending}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.usernameHint", "Unikal login ady")}</p>
|
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
|
||||||
type="text"
|
|
||||||
label={t("users.fields.name", "Ady")}
|
|
||||||
value={form.name}
|
|
||||||
onChange={(v) => setField("name", v)}
|
|
||||||
placeholder={t("users.fields.name", "Ady")}
|
|
||||||
error={errors.name}
|
|
||||||
disabled={isPending}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.nameHint", "Doly ady we familiýasy")}</p>
|
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
|
||||||
type="phone"
|
|
||||||
label={t("users.fields.phone", "Telefon")}
|
|
||||||
value={form.phone}
|
|
||||||
onChange={(v) => setField("phone", v)}
|
|
||||||
placeholder="62-38-49-56"
|
|
||||||
error={errors.phone}
|
|
||||||
disabled={isPending}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.phoneHint", "+993 bilen başlanýar")}</p>
|
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
|
||||||
type="email"
|
|
||||||
label={t("users.fields.email", "E-poçta")}
|
|
||||||
value={form.email}
|
|
||||||
onChange={(v) => setField("email", v)}
|
|
||||||
placeholder={t("users.fields.email", "E-poçta")}
|
|
||||||
error={errors.email}
|
|
||||||
disabled={isPending}
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.emailHint", "Islege görä")}</p>
|
|
||||||
</BentoCard>
|
|
||||||
{mode === "create" && (
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="password"
|
type="text"
|
||||||
label={t("users.fields.password", "Açar sözi")}
|
label={t("users.fields.username", "Ulanyjy ady")}
|
||||||
value={form.password}
|
value={form.username}
|
||||||
onChange={(v) => setField("password", v)}
|
onChange={(v) => setField("username", v)}
|
||||||
placeholder={t("users.fields.password", "Açar sözi")}
|
placeholder={t("users.fields.username", "Ulanyjy ady")}
|
||||||
error={errors.password}
|
error={errors.username}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.passwordHint", "Iň az 6 harp")}</p>
|
<FormInput
|
||||||
</BentoCard>
|
type="text"
|
||||||
)}
|
label={t("users.fields.name", "Ady")}
|
||||||
<BentoCard>
|
value={form.name}
|
||||||
<div className="space-y-1">
|
onChange={(v) => setField("name", v)}
|
||||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.phoneVerified", "Telefon tassyklanan")}</p>
|
placeholder={t("users.fields.name", "Ady")}
|
||||||
<p className="text-xs text-muted-foreground">{t("users.fields.phoneVerifiedHint", "SMS arkaly tassyklandy")}</p>
|
error={errors.name}
|
||||||
</div>
|
disabled={isPending}
|
||||||
<div className="flex items-center gap-2">
|
required
|
||||||
<Checkbox
|
/>
|
||||||
id="phoneVerified"
|
<FormInput
|
||||||
checked={form.phoneVerified}
|
type="text"
|
||||||
onCheckedChange={(v) => setField("phoneVerified", !!v)}
|
label={t("users.fields.firstName", "Ady (at)")}
|
||||||
|
value={form.firstName}
|
||||||
|
onChange={(v) => setField("firstName", v)}
|
||||||
|
placeholder={t("users.fields.firstName", "Ady (at)")}
|
||||||
|
error={errors.firstName}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
/>
|
/>
|
||||||
<Label htmlFor="phoneVerified" className="text-sm text-muted-foreground cursor-pointer">
|
<FormInput
|
||||||
{form.phoneVerified ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
type="text"
|
||||||
</Label>
|
label={t("users.fields.lastName", "Familiýasy")}
|
||||||
|
value={form.lastName}
|
||||||
|
onChange={(v) => setField("lastName", v)}
|
||||||
|
placeholder={t("users.fields.lastName", "Familiýasy")}
|
||||||
|
error={errors.lastName}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<FormInput
|
||||||
|
type="phone"
|
||||||
|
label={t("users.fields.phone", "Telefon")}
|
||||||
|
value={form.phone}
|
||||||
|
onChange={(v) => setField("phone", v)}
|
||||||
|
placeholder="62-38-49-56"
|
||||||
|
error={errors.phone}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="email"
|
||||||
|
label={t("users.fields.email", "E-poçta")}
|
||||||
|
value={form.email}
|
||||||
|
onChange={(v) => setField("email", v)}
|
||||||
|
placeholder={t("users.fields.email", "E-poçta")}
|
||||||
|
error={errors.email}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
<InfiniteSelect
|
||||||
|
label={t("users.fields.role", "Roly")}
|
||||||
|
value={form.role}
|
||||||
|
onChange={(v) => {
|
||||||
|
setField("role", v);
|
||||||
|
const selectedRole = (roleQuery.data?.pages ?? []).flatMap((page) => page?.roles ?? []).find((role) => role.code === v);
|
||||||
|
setField("roleId", selectedRole ? String(selectedRole.id) : "");
|
||||||
|
}}
|
||||||
|
placeholder={t("users.fields.role", "Roly")}
|
||||||
|
error={errors.role}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
{...roleSelect}
|
||||||
|
/>
|
||||||
|
{mode === "create" && (
|
||||||
|
<FormInput
|
||||||
|
type="password"
|
||||||
|
label={t("users.fields.password", "Açar sözi")}
|
||||||
|
value={form.password}
|
||||||
|
onChange={(v) => setField("password", v)}
|
||||||
|
placeholder={t("users.fields.password", "Açar sözi")}
|
||||||
|
error={errors.password}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-2 pt-1">
|
||||||
|
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
|
||||||
|
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
|
||||||
|
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
|
{/* ── Avatar ── */}
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<div className="space-y-1">
|
<AvatarUpload
|
||||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.isActive", "Işjeň")}</p>
|
label={t("users.fields.avatar", "Awatar")}
|
||||||
<p className="text-xs text-muted-foreground">{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}</p>
|
value={form.avatar}
|
||||||
</div>
|
onChange={(v) => setField("avatar", v)}
|
||||||
<div className="flex items-center gap-2">
|
error={errors.avatar}
|
||||||
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(v) => setField("isActive", !!v)} disabled={isPending} />
|
disabled={isPending}
|
||||||
<Label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer">
|
/>
|
||||||
{form.isActive ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
</BentoCard>
|
||||||
</Label>
|
|
||||||
|
{/* ── Social media ── */}
|
||||||
|
<BentoCard title={t("users.fields.socialMedia", "Sosial media")} span="full">
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("users.fields.facebook", "Facebook")}
|
||||||
|
value={form.socialFacebook}
|
||||||
|
onChange={(v) => setField("socialFacebook", v)}
|
||||||
|
placeholder="facebook.com/..."
|
||||||
|
error={errors.socialFacebook}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("users.fields.instagram", "Instagram")}
|
||||||
|
value={form.socialInstagram}
|
||||||
|
onChange={(v) => setField("socialInstagram", v)}
|
||||||
|
placeholder="instagram.com/..."
|
||||||
|
error={errors.socialInstagram}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("users.fields.telegram", "Telegram")}
|
||||||
|
value={form.socialTelegram}
|
||||||
|
onChange={(v) => setField("socialTelegram", v)}
|
||||||
|
placeholder="t.me/..."
|
||||||
|
error={errors.socialTelegram}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
<FormActions
|
<FormActions
|
||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
|
|||||||
@@ -1,27 +1,47 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
usersApi,
|
import { usersApi, type CreateUserPayload, type UpdateUserPayload, type UsersListParams } from "../api/allUsersApi";
|
||||||
type CreateUserPayload,
|
|
||||||
type UpdateUserPayload,
|
|
||||||
type UsersListParams,
|
|
||||||
} from '../api/allUsersApi'
|
|
||||||
|
|
||||||
export const userKeys = {
|
export const userKeys = {
|
||||||
all: ['users'] as const,
|
all: ["users"] as const,
|
||||||
lists: () => [...userKeys.all, 'list'] as const,
|
lists: () => [...userKeys.all, "list"] as const,
|
||||||
list: (params: UsersListParams) => [...userKeys.lists(), params] as const,
|
list: (params: UsersListParams) => [...userKeys.lists(), params] as const,
|
||||||
details: () => [...userKeys.all, 'detail'] as const,
|
details: () => [...userKeys.all, "detail"] as const,
|
||||||
detail: (id: number) => [...userKeys.details(), id] as const,
|
detail: (id: number) => [...userKeys.details(), id] as const,
|
||||||
}
|
infinite: (search: string) => [...userKeys.all, "infinite", search] as const,
|
||||||
|
};
|
||||||
|
|
||||||
export function useUsers(params: UsersListParams = {}) {
|
export function useUsers(params: UsersListParams = {}) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
|
const normalized = normalizeSearch(debouncedSearch);
|
||||||
|
const queryParams: UsersListParams = { ...params, search: normalized || undefined };
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: userKeys.list(params),
|
queryKey: userKeys.list(queryParams),
|
||||||
queryFn: () => usersApi.getUsers(params),
|
queryFn: ({ signal }) => usersApi.getUsers(queryParams, signal),
|
||||||
placeholderData: (prev) => prev,
|
placeholderData: (prev) => prev,
|
||||||
})
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const USER_PAGE_SIZE = 25;
|
||||||
|
|
||||||
|
export function useInfiniteUsers(search = "", enabled = true) {
|
||||||
|
const debouncedSearch = useDebouncedValue(search);
|
||||||
|
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||||
|
|
||||||
|
return useInfiniteQuery({
|
||||||
|
queryKey: userKeys.infinite(effectiveSearch),
|
||||||
|
initialPageParam: 1,
|
||||||
|
queryFn: ({ pageParam, signal }) => usersApi.getUsers({ page: pageParam, limit: USER_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||||
|
getNextPageParam: (lastPage, allPages) => {
|
||||||
|
const loaded = allPages.reduce((sum, p) => sum + (p?.users?.length ?? 0), 0);
|
||||||
|
const count = lastPage?.count ?? 0;
|
||||||
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
|
},
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUser(id: number) {
|
export function useUser(id: number) {
|
||||||
@@ -29,45 +49,45 @@ export function useUser(id: number) {
|
|||||||
queryKey: userKeys.detail(id),
|
queryKey: userKeys.detail(id),
|
||||||
queryFn: () => usersApi.getUserById(id),
|
queryFn: () => usersApi.getUserById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCreateUser() {
|
export function useCreateUser() {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateUserPayload) => usersApi.createUser(payload),
|
mutationFn: (payload: CreateUserPayload) => usersApi.createUser(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||||
toast.success(t('users.toast.createSuccess', 'Ulanyjy üstünlikli döredildi'))
|
toast.success(t("users.toast.createSuccess", "Ulanyjy üstünlikli döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUpdateUser(id: number) {
|
export function useUpdateUser(id: number) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateUserPayload) => usersApi.updateUser(id, payload),
|
mutationFn: (payload: UpdateUserPayload) => usersApi.updateUser(id, payload),
|
||||||
onSuccess: (updatedUser) => {
|
onSuccess: (updatedUser) => {
|
||||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||||
queryClient.setQueryData(userKeys.detail(id), updatedUser)
|
queryClient.setQueryData(userKeys.detail(id), updatedUser);
|
||||||
toast.success(t('users.toast.updateSuccess', 'Ulanyjy üstünlikli täzelendi'))
|
toast.success(t("users.toast.updateSuccess", "Ulanyjy üstünlikli täzelendi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDeleteUser() {
|
export function useDeleteUser() {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => usersApi.deleteUser(id),
|
mutationFn: (id: number) => usersApi.deleteUser(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||||
toast.success(t('users.toast.deleteSuccess', 'Ulanyjy üstünlikli öçürildi'))
|
toast.success(t("users.toast.deleteSuccess", "Ulanyjy üstünlikli öçürildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,20 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { CreateUserPayload } from "../api/allUsersApi";
|
import type { CreateUserPayload, UpdateUserPayload } from "../api/allUsersApi";
|
||||||
|
|
||||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||||
|
|
||||||
|
const urlSchema = (t: (key: string, fallback?: string) => string) =>
|
||||||
|
z
|
||||||
|
.string()
|
||||||
|
.refine((v) => !v || /^(https?:\/\/|www\.|[\w.-]+\.[a-z]{2,})/i.test(v), t("validation.invalidUrl", "validation.invalidUrl"))
|
||||||
|
.default("");
|
||||||
|
|
||||||
export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
||||||
const baseSchema = z.object({
|
const baseSchema = z.object({
|
||||||
username: z.string().min(1, t("validation.required", "validation.required")).min(3, t("validation.minLength", "validation.minLength")),
|
username: z.string().min(1, t("validation.required", "validation.required")).min(3, t("validation.minLength", "validation.minLength")),
|
||||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
firstName: z.string().default(""),
|
||||||
|
lastName: z.string().default(""),
|
||||||
phone: z
|
phone: z
|
||||||
.string()
|
.string()
|
||||||
.min(1, t("validation.required", "validation.required"))
|
.min(1, t("validation.required", "validation.required"))
|
||||||
@@ -29,9 +37,15 @@ export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fall
|
|||||||
.string()
|
.string()
|
||||||
.refine((v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), t("validation.invalidEmail", "validation.invalidEmail"))
|
.refine((v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), t("validation.invalidEmail", "validation.invalidEmail"))
|
||||||
.default(""),
|
.default(""),
|
||||||
|
avatar: urlSchema(t),
|
||||||
|
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
roleId: z.string(),
|
||||||
|
socialFacebook: urlSchema(t),
|
||||||
|
socialInstagram: urlSchema(t),
|
||||||
|
socialTelegram: urlSchema(t),
|
||||||
|
lightMode: z.boolean(),
|
||||||
password: z.string(),
|
password: z.string(),
|
||||||
phoneVerified: z.boolean(),
|
active: z.boolean(),
|
||||||
isActive: z.boolean(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return mode === "create"
|
return mode === "create"
|
||||||
@@ -49,21 +63,60 @@ export type AllUserFormData = z.infer<ReturnType<typeof allUserFormSchema>>;
|
|||||||
export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
||||||
username: "",
|
username: "",
|
||||||
name: "",
|
name: "",
|
||||||
|
firstName: "",
|
||||||
|
lastName: "",
|
||||||
phone: "",
|
phone: "",
|
||||||
email: "",
|
email: "",
|
||||||
|
avatar: "",
|
||||||
|
role: "",
|
||||||
|
roleId: "",
|
||||||
|
socialFacebook: "",
|
||||||
|
socialInstagram: "",
|
||||||
|
socialTelegram: "",
|
||||||
|
lightMode: false,
|
||||||
password: "",
|
password: "",
|
||||||
phoneVerified: false,
|
active: true,
|
||||||
isActive: true,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export function buildPayload(data: AllUserFormData): CreateUserPayload {
|
export function buildPayload(data: AllUserFormData): CreateUserPayload {
|
||||||
return {
|
return {
|
||||||
username: data.username.trim(),
|
username: data.username.trim(),
|
||||||
name: data.name.trim(),
|
name: data.name.trim(),
|
||||||
phone: data.phone.trim(),
|
firstName: data.firstName.trim(),
|
||||||
email: data.email.trim() || undefined,
|
lastName: data.lastName.trim(),
|
||||||
|
phone: data.phone.replace(/\s+/g, ""),
|
||||||
|
email: data.email.trim(),
|
||||||
|
avatar: data.avatar.trim(),
|
||||||
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
|
socialMedia: {
|
||||||
|
facebook: data.socialFacebook.trim(),
|
||||||
|
instagram: data.socialInstagram.trim(),
|
||||||
|
telegram: data.socialTelegram.trim(),
|
||||||
|
},
|
||||||
|
lightMode: data.lightMode ? 1 : 0,
|
||||||
password: data.password,
|
password: data.password,
|
||||||
phoneVerified: data.phoneVerified,
|
active: data.active,
|
||||||
isActive: data.isActive,
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildUpdatePayload(data: AllUserFormData): UpdateUserPayload {
|
||||||
|
return {
|
||||||
|
username: data.username.trim(),
|
||||||
|
name: data.name.trim(),
|
||||||
|
firstName: data.firstName.trim(),
|
||||||
|
lastName: data.lastName.trim(),
|
||||||
|
phone: data.phone.replace(/\s+/g, ""),
|
||||||
|
email: data.email.trim(),
|
||||||
|
avatar: data.avatar.trim(),
|
||||||
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
|
socialMedia: {
|
||||||
|
facebook: data.socialFacebook.trim(),
|
||||||
|
instagram: data.socialInstagram.trim(),
|
||||||
|
telegram: data.socialTelegram.trim(),
|
||||||
|
},
|
||||||
|
lightMode: data.lightMode ? 1 : 0,
|
||||||
|
active: data.active,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,63 +1,86 @@
|
|||||||
import type { AuthUser } from '@/app/store/authStore'
|
import apiClient from "@/lib/api/client";
|
||||||
|
import type { AuthUser } from "@/app/store/authStore";
|
||||||
|
|
||||||
|
export interface RegisterRequest {
|
||||||
|
name: string;
|
||||||
|
password: string;
|
||||||
|
passwordConfirm: string;
|
||||||
|
phone: string;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegisterVerifyRequest {
|
||||||
|
code: string;
|
||||||
|
phone: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface LoginRequest {
|
export interface LoginRequest {
|
||||||
email: string
|
name?: string;
|
||||||
password: string
|
phone?: string;
|
||||||
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LoginResponse {
|
export interface LoginData {
|
||||||
token: string
|
accessToken: string;
|
||||||
user: AuthUser
|
refreshToken: string;
|
||||||
|
user?: AuthUser;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mock credentials
|
export interface UpdateProfileRequest {
|
||||||
const MOCK_USERS: Array<{ email: string; password: string; user: AuthUser; token: string }> = [
|
name: string;
|
||||||
{
|
firstName?: string;
|
||||||
email: 'jelaletdin',
|
lastName?: string;
|
||||||
password: '123',
|
phone?: string;
|
||||||
token: 'mock-jwt-token-admin-xyz123',
|
avatar?: string;
|
||||||
user: {
|
|
||||||
id: '1',
|
|
||||||
name: 'Admin User',
|
|
||||||
email: 'admin@tbbank.tm',
|
|
||||||
role: 'admin',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
email: 'manager@tbbank.tm',
|
|
||||||
password: 'Manager123!',
|
|
||||||
token: 'mock-jwt-token-manager-abc456',
|
|
||||||
user: {
|
|
||||||
id: '2',
|
|
||||||
name: 'Branch Manager',
|
|
||||||
email: 'manager@tbbank.tm',
|
|
||||||
role: 'manager',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
function delay(ms: number) {
|
|
||||||
return new Promise<void>((resolve) => setTimeout(resolve, ms))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loginApi(credentials: LoginRequest): Promise<LoginResponse> {
|
export async function loginApi(credentials: LoginRequest): Promise<LoginData> {
|
||||||
// Simulate network latency
|
const response = await apiClient.post<LoginData>("/login", credentials);
|
||||||
await delay(900)
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
const match = MOCK_USERS.find(
|
export async function refreshTokenApi(refreshToken: string): Promise<{ accessToken: string; refreshToken: string }> {
|
||||||
(u) => u.email === credentials.email && u.password === credentials.password,
|
const response = await apiClient.post<{ accessToken: string; refreshToken: string }>("/token", { refreshToken });
|
||||||
)
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
if (!match) {
|
export async function getProfileApi(): Promise<AuthUser> {
|
||||||
throw new Error('INVALID_CREDENTIALS')
|
const response = await apiClient.get<AuthUser>("/profile");
|
||||||
}
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
export async function updateProfileApi(data: UpdateProfileRequest): Promise<AuthUser> {
|
||||||
token: match.token,
|
const response = await apiClient.put<AuthUser>("/profile", data);
|
||||||
user: match.user,
|
return response.data;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function logoutApi(): Promise<void> {
|
export async function logoutApi(): Promise<void> {
|
||||||
await delay(300)
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function registerApi(data: RegisterRequest): Promise<void> {
|
||||||
|
await apiClient.post("/register", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function registerVerifyApi(data: RegisterVerifyRequest): Promise<void> {
|
||||||
|
await apiClient.post("/register/verify", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForgotPasswordRequest {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForgotPasswordVerifyRequest {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
password: string;
|
||||||
|
passwordConfirm: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function forgotPasswordApi(data: ForgotPasswordRequest): Promise<void> {
|
||||||
|
await apiClient.post("/forgot-password", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function forgotPasswordVerifyApi(data: ForgotPasswordVerifyRequest): Promise<void> {
|
||||||
|
await apiClient.post("/forgot-password/verify", data);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { forgotPasswordApi, forgotPasswordVerifyApi, type ForgotPasswordRequest, type ForgotPasswordVerifyRequest } from "../api/authApi";
|
||||||
|
|
||||||
|
export function useForgotPassword() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: ForgotPasswordRequest) => forgotPasswordApi(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useForgotPasswordVerify() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: ForgotPasswordVerifyRequest) => forgotPasswordVerifyApi(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,30 +1,69 @@
|
|||||||
import { useMutation } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from "react-router-dom";
|
||||||
import { toast } from 'sonner'
|
import { useTranslation } from "react-i18next";
|
||||||
import i18next from 'i18next'
|
import { toast } from "sonner";
|
||||||
import { useAuthStore } from '@/app/store/authStore'
|
import { useAuthStore, getHomePath } from "@/app/store/authStore";
|
||||||
import { loginApi, type LoginRequest } from '../api/authApi'
|
import { extractErrorMessage } from "@/lib/api/client";
|
||||||
|
import { loginApi, getProfileApi, updateProfileApi, type LoginRequest, type UpdateProfileRequest } from "../api/authApi";
|
||||||
|
|
||||||
export function useLogin() {
|
export function useLogin() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate();
|
||||||
const setAuth = useAuthStore((s) => s.setAuth)
|
const setAuth = useAuthStore((s) => s.setAuth);
|
||||||
|
const setUser = useAuthStore((s) => s.setUser);
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (credentials: LoginRequest) => loginApi(credentials),
|
mutationFn: (credentials: LoginRequest) => loginApi(credentials),
|
||||||
onSuccess: ({ token, user }) => {
|
onSuccess: async (data) => {
|
||||||
setAuth(token, user)
|
setAuth(data.accessToken, data.refreshToken, data.user ?? null);
|
||||||
toast.success(i18next.t('Success login', 'Login successful'))
|
|
||||||
navigate('/dashboard', { replace: true })
|
const profile = await getProfileApi();
|
||||||
|
setUser(profile);
|
||||||
|
|
||||||
|
navigate(getHomePath(), { replace: true });
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useProfile() {
|
||||||
|
const setUser = useAuthStore((s) => s.setUser);
|
||||||
|
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
|
||||||
|
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["auth", "profile"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const profile = await getProfileApi();
|
||||||
|
setUser(profile);
|
||||||
|
return profile;
|
||||||
|
},
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateProfile() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const setUser = useAuthStore((s) => s.setUser);
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: UpdateProfileRequest) => updateProfileApi(data),
|
||||||
|
onSuccess: (updatedProfile) => {
|
||||||
|
setUser(updatedProfile);
|
||||||
|
queryClient.setQueryData(["auth", "profile"], updatedProfile);
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["auth", "profile"] });
|
||||||
|
toast.success(t("profile.updateSuccess", "Profil üstünlikli täzelendi!"));
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
toast.error(extractErrorMessage(err, t("profile.updateError", "Profil täzelenende ýalňyşlyk ýüze çykdy")));
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useLogout() {
|
export function useLogout() {
|
||||||
const clearAuth = useAuthStore((s) => s.clearAuth)
|
const clearAuth = useAuthStore((s) => s.clearAuth);
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate();
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
clearAuth()
|
clearAuth();
|
||||||
navigate('/login', { replace: true })
|
navigate("/login", { replace: true });
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { registerApi, registerVerifyApi, type RegisterRequest, type RegisterVerifyRequest } from "../api/authApi";
|
||||||
|
|
||||||
|
export function useRegister() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: RegisterRequest) => registerApi(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRegisterVerify() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: RegisterVerifyRequest) => registerVerifyApi(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,78 +1,95 @@
|
|||||||
import apiClient from '@/lib/api/client'
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
export type BackupStatus = 'completed' | 'failed' | 'in_progress'
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export type BackupStatus = "pending" | "in_progress" | "completed" | "failed";
|
||||||
|
|
||||||
|
export interface BackupUser {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
username: string;
|
||||||
|
phone: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Raw backend entity (GET responses mirror this shape). */
|
||||||
export interface Backup {
|
export interface Backup {
|
||||||
id: number
|
id: number;
|
||||||
fileName: string
|
fileName: string;
|
||||||
fileSize: string
|
sizeBytes: number;
|
||||||
status: BackupStatus
|
size: string;
|
||||||
createdAt: string
|
status: BackupStatus;
|
||||||
createdBy: string
|
createdBy: BackupUser;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** LIST RESPONSE: GET /backups */
|
||||||
export interface BackupListResponse {
|
export interface BackupListResponse {
|
||||||
data: Backup[]
|
count: number;
|
||||||
total: number
|
backups: Backup[];
|
||||||
page: number
|
|
||||||
per_page: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** LIST PARAMS */
|
||||||
export interface BackupListParams {
|
export interface BackupListParams {
|
||||||
page?: number
|
page?: number;
|
||||||
per_page?: number
|
limit?: number;
|
||||||
search?: string
|
search?: string;
|
||||||
|
status?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MOCK_BACKUPS: Backup[] = [
|
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||||
{ id: 1, fileName: 'backup_2026_05_22_01.sql', fileSize: '256 MB', status: 'completed', createdAt: '2026-05-22 03:00', createdBy: 'Admin' },
|
|
||||||
{ id: 2, fileName: 'backup_2026_05_21_01.sql', fileSize: '251 MB', status: 'completed', createdAt: '2026-05-21 03:00', createdBy: 'Admin' },
|
|
||||||
{ id: 3, fileName: 'backup_2026_05_20_01.sql', fileSize: '248 MB', status: 'completed', createdAt: '2026-05-20 03:00', createdBy: 'Admin' },
|
|
||||||
{ id: 4, fileName: 'backup_2026_05_19_01.sql', fileSize: '245 MB', status: 'failed', createdAt: '2026-05-19 03:05', createdBy: 'Admin' },
|
|
||||||
{ id: 5, fileName: 'backup_2026_05_18_01.sql', fileSize: '242 MB', status: 'completed', createdAt: '2026-05-18 03:00', createdBy: 'System' },
|
|
||||||
]
|
|
||||||
|
|
||||||
export const backupsApi = {
|
export const backupsApi = {
|
||||||
getAll: async (params?: BackupListParams): Promise<BackupListResponse> => {
|
getList: async (params: BackupListParams = {}, signal?: AbortSignal): Promise<BackupListResponse> => {
|
||||||
const { data } = await apiClient.get('/backups', { params }).catch(() => ({ data: null }))
|
const { page, limit, search, status } = params;
|
||||||
if (data) return data
|
const { data } = await apiClient.get<BackupListResponse>("/backups", {
|
||||||
|
params: {
|
||||||
const { search = '', page = 1, per_page = 25 } = params ?? {}
|
page,
|
||||||
let filtered = [...MOCK_BACKUPS]
|
limit,
|
||||||
if (search) {
|
search: search || undefined,
|
||||||
const s = search.toLowerCase()
|
status: status || undefined,
|
||||||
filtered = filtered.filter((b) => b.fileName.toLowerCase().includes(s))
|
},
|
||||||
}
|
signal,
|
||||||
const total = filtered.length
|
});
|
||||||
const start = (page - 1) * per_page
|
return data;
|
||||||
return { data: filtered.slice(start, start + per_page), total, page, per_page }
|
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getById: async (id: number): Promise<Backup> => {
|
||||||
|
const { data } = await apiClient.get<Backup>(`/backups/${id}`);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
/** POST /backups — no payload, backend creates the backup. */
|
||||||
create: async (): Promise<Backup> => {
|
create: async (): Promise<Backup> => {
|
||||||
const { data } = await apiClient.post('/backups').catch(() => ({ data: null }))
|
const { data } = await apiClient.post<Backup>("/backups");
|
||||||
if (data) return data
|
return data;
|
||||||
|
|
||||||
const newBackup: Backup = {
|
|
||||||
id: Math.floor(Math.random() * 10000),
|
|
||||||
fileName: `backup_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}_01.sql`,
|
|
||||||
fileSize: '0 MB',
|
|
||||||
status: 'in_progress',
|
|
||||||
createdAt: new Date().toLocaleString('tr-TR'),
|
|
||||||
createdBy: 'Admin',
|
|
||||||
}
|
|
||||||
MOCK_BACKUPS.unshift(newBackup)
|
|
||||||
return newBackup
|
|
||||||
},
|
},
|
||||||
|
|
||||||
download: async (id: number): Promise<Blob> => {
|
download: async (id: number): Promise<{ blob: Blob; fileName?: string }> => {
|
||||||
const { data } = await apiClient.get(`/backups/${id}/download`, { responseType: 'blob' }).catch(() => ({ data: null }))
|
const response = await apiClient.get<Blob>(`/backups/${id}/download`, {
|
||||||
if (data) return data
|
responseType: "blob",
|
||||||
return new Blob(['mock backup content'], { type: 'application/sql' })
|
});
|
||||||
|
|
||||||
|
let fileName: string | undefined;
|
||||||
|
const disposition =
|
||||||
|
(response.headers?.["content-disposition"] as string | undefined) ||
|
||||||
|
(response.headers?.["Content-Disposition"] as string | undefined);
|
||||||
|
|
||||||
|
if (disposition) {
|
||||||
|
const match = disposition.match(/filename\*?=(?:UTF-8'')?["']?([^"';]+)["']?/i);
|
||||||
|
if (match && match[1]) {
|
||||||
|
fileName = decodeURIComponent(match[1].trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
blob: response.data,
|
||||||
|
fileName,
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
delete: async (id: number): Promise<void> => {
|
delete: async (id: number): Promise<void> => {
|
||||||
await apiClient.delete(`/backups/${id}`).catch(() => {})
|
await apiClient.delete(`/backups/${id}`);
|
||||||
const index = MOCK_BACKUPS.findIndex((b) => b.id === id)
|
|
||||||
if (index !== -1) MOCK_BACKUPS.splice(index, 1)
|
|
||||||
},
|
},
|
||||||
}
|
};
|
||||||
@@ -1,58 +1,91 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import { backupsApi, type BackupListParams } from '../api/backupsApi'
|
import { backupsApi, type BackupListParams } from "../api/backupsApi";
|
||||||
|
|
||||||
const QUERY_KEY = 'backups'
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useBackups(params?: BackupListParams) {
|
export const backupKeys = {
|
||||||
|
all: ["backups"] as const,
|
||||||
|
lists: () => [...backupKeys.all, "list"] as const,
|
||||||
|
list: (params: BackupListParams) => [...backupKeys.lists(), params] as const,
|
||||||
|
details: () => [...backupKeys.all, "detail"] as const,
|
||||||
|
detail: (id: number) => [...backupKeys.details(), id] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useBackups(params: BackupListParams = {}) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [QUERY_KEY, params],
|
queryKey: backupKeys.list(params),
|
||||||
queryFn: () => backupsApi.getAll(params),
|
queryFn: ({ signal }) => backupsApi.getList(params, signal),
|
||||||
})
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useBackup(id: number) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: backupKeys.detail(id),
|
||||||
|
queryFn: () => backupsApi.getById(id),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateBackup() {
|
export function useCreateBackup() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: () => backupsApi.create(),
|
mutationFn: () => backupsApi.create(),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: backupKeys.lists() });
|
||||||
toast.success(t('backups.toast.created', 'Backup üstünlikli döredildi!'))
|
toast.success(t("backups.toast.created", "Backup üstünlikli döredildi!"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDownloadBackup() {
|
export function useDownloadBackup() {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (id: number) => {
|
mutationFn: async (param: number | { id: number; fileName?: string }) => {
|
||||||
const blob = await backupsApi.download(id)
|
const id = typeof param === "number" ? param : param.id;
|
||||||
const url = URL.createObjectURL(blob)
|
const fallbackName = typeof param === "object" ? param.fileName : undefined;
|
||||||
const a = document.createElement('a')
|
|
||||||
a.href = url
|
const { blob, fileName } = await backupsApi.download(id);
|
||||||
a.download = `backup-${id}.sql`
|
const url = URL.createObjectURL(blob);
|
||||||
a.click()
|
const a = document.createElement("a");
|
||||||
URL.revokeObjectURL(url)
|
a.href = url;
|
||||||
|
a.download = fileName || fallbackName || `backup-${id}.sql`;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
toast.success(t('backups.toast.downloaded', 'Backup üstünlikli ýüklenildi'))
|
toast.success(t("backups.toast.downloaded", "Backup üstünlikli ýüklenildi"));
|
||||||
},
|
},
|
||||||
})
|
onError: () => {
|
||||||
|
toast.error(t("common.error", "Ýalňyşlyk ýüze çykdy"));
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteBackup() {
|
export function useDeleteBackup() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => backupsApi.delete(id),
|
mutationFn: (id: number) => backupsApi.delete(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: backupKeys.lists() });
|
||||||
toast.success(t('backups.toast.deleted', 'Backup üstünlikli pozuldy!'))
|
toast.success(t("backups.toast.deleted", "Backup üstünlikli pozuldy!"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
@@ -1,172 +1,144 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
|
// ─── Localized text (backend keys: tm | ru | en) ──────────────────────────────
|
||||||
|
|
||||||
|
export interface LocalizedText {
|
||||||
|
tm?: string;
|
||||||
|
ru?: string;
|
||||||
|
en?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LocalizedField = string | LocalizedText;
|
||||||
|
|
||||||
|
export function resolveLocalizedName(val: LocalizedField | null | undefined, lang = "tm"): string {
|
||||||
|
if (!val) return "";
|
||||||
|
if (typeof val === "string") return val;
|
||||||
|
const key = (lang === "tk" ? "tm" : lang) as keyof LocalizedText;
|
||||||
|
return val[key] ?? val.tm ?? val.en ?? val.ru ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Province (for the provinceId select) ─────────────────────────────────────
|
||||||
|
|
||||||
|
export interface Province {
|
||||||
|
id: number;
|
||||||
|
name: LocalizedField;
|
||||||
|
region: LocalizedField;
|
||||||
|
active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Branch ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface Branch {
|
export interface Branch {
|
||||||
id: number
|
id: number;
|
||||||
name: Record<'tk' | 'ru' | 'en', string>
|
uniqueCode: string;
|
||||||
code: string
|
name: LocalizedField;
|
||||||
districtId: number
|
address: LocalizedField;
|
||||||
districtName: Record<'tk' | 'ru' | 'en', string>
|
region: string;
|
||||||
address: Record<'tk' | 'ru' | 'en', string>
|
provinceId: number;
|
||||||
phone: string
|
provinceName: LocalizedField;
|
||||||
email: string
|
phoneNumbers: string;
|
||||||
workingHours: string
|
billingUsername: string;
|
||||||
description: string | null
|
billingPassword: string;
|
||||||
isActive: boolean
|
billingSberUsername: string;
|
||||||
|
billingSberPassword: string;
|
||||||
|
billingVisaMasterUsername: string;
|
||||||
|
billingVisaMasterPassword: string;
|
||||||
|
billingSwiftUsername: string;
|
||||||
|
billingSwiftPassword: string;
|
||||||
|
active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BranchListParams {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
search?: string;
|
||||||
|
provinceId?: string;
|
||||||
|
provinceName?: string;
|
||||||
|
uniqueCode?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BranchListResponse {
|
export interface BranchListResponse {
|
||||||
data: Branch[]
|
count: number;
|
||||||
total: number
|
branches: Branch[];
|
||||||
page: number
|
|
||||||
perPage: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── API Payloads ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface CreateBranchPayload {
|
export interface CreateBranchPayload {
|
||||||
name: Record<'tk' | 'ru' | 'en', string>
|
active: boolean;
|
||||||
code: string
|
address: LocalizedText;
|
||||||
districtId: number
|
billingPassword: string;
|
||||||
address: Record<'tk' | 'ru' | 'en', string>
|
billingSberPassword: string;
|
||||||
phone: string
|
billingSberUsername: string;
|
||||||
email: string
|
billingSwiftPassword: string;
|
||||||
workingHours: string
|
billingSwiftUsername: string;
|
||||||
description: string | null
|
billingUsername: string;
|
||||||
isActive: boolean
|
billingVisaMasterPassword: string;
|
||||||
|
billingVisaMasterUsername: string;
|
||||||
|
name: LocalizedText;
|
||||||
|
phoneNumbers: string;
|
||||||
|
provinceId: number;
|
||||||
|
region: string;
|
||||||
|
uniqueCode: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateBranchPayload extends CreateBranchPayload {
|
export interface UpdateBranchPayload extends CreateBranchPayload {
|
||||||
id: number
|
id: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DISTRICTS = [
|
// ─── Branch CRUD ──────────────────────────────────────────────────────────────
|
||||||
{ id: 1, name: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' } },
|
|
||||||
{ id: 2, name: { tk: 'Änew', ru: 'Анев', en: 'Anew' } },
|
|
||||||
{ id: 3, name: { tk: 'Baýramaly', ru: 'Байрамалы', en: 'Bayramaly' } },
|
|
||||||
{ id: 4, name: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' } },
|
|
||||||
{ id: 5, name: { tk: 'Mary', ru: 'Мары', en: 'Mary' } },
|
|
||||||
{ id: 6, name: { tk: 'Türkmenabat', ru: 'Туркменабат', en: 'Turkmenabat' } },
|
|
||||||
{ id: 7, name: { tk: 'Balkanabat', ru: 'Балканабат', en: 'Balkanabat' } },
|
|
||||||
]
|
|
||||||
|
|
||||||
export function getDistrictOptions() {
|
export async function fetchBranches(params: BranchListParams = {}, signal?: AbortSignal): Promise<BranchListResponse> {
|
||||||
return DISTRICTS
|
const { page, limit, search, provinceId, provinceName, uniqueCode } = params;
|
||||||
}
|
const { data } = await apiClient.get<BranchListResponse>("/branches", {
|
||||||
|
params: {
|
||||||
function findDistrict(id: number) {
|
page,
|
||||||
return DISTRICTS.find((d) => d.id === id) ?? DISTRICTS[0]
|
limit,
|
||||||
}
|
branch_name: search || undefined,
|
||||||
|
province_id: provinceId || undefined,
|
||||||
const MOCK_BRANCHES: Branch[] = [
|
province_name: provinceName || undefined,
|
||||||
{
|
unique_code: uniqueCode || undefined,
|
||||||
id: 1,
|
},
|
||||||
name: { tk: 'Merkezi şahamça', ru: 'Главное отделение', en: 'Main branch' },
|
signal,
|
||||||
code: 'BR-001',
|
});
|
||||||
districtId: 1,
|
return data;
|
||||||
districtName: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' },
|
|
||||||
address: { tk: 'Bitarap Türkmenistan şaýoly, 100', ru: 'Проспект Битарap Туркменистан, 100', en: 'Bitarap Turkmenistan avenue, 100' },
|
|
||||||
phone: '+993 12 45-67-89',
|
|
||||||
email: 'main@tbbank.gov.tm',
|
|
||||||
workingHours: '09:00 - 18:00',
|
|
||||||
description: null,
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
name: { tk: 'Mary şahamçasy', ru: 'Марыйское отделение', en: 'Mary branch' },
|
|
||||||
code: 'BR-002',
|
|
||||||
districtId: 5,
|
|
||||||
districtName: { tk: 'Mary', ru: 'Мары', en: 'Mary' },
|
|
||||||
address: { tk: 'Gurbansoltan eje köçesi, 25', ru: 'Улица Гурбансолтан эдже, 25', en: 'Gurbansoltan eje street, 25' },
|
|
||||||
phone: '+993 55 12-34-56',
|
|
||||||
email: 'mary@tbbank.gov.tm',
|
|
||||||
workingHours: '09:00 - 17:00',
|
|
||||||
description: null,
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 3,
|
|
||||||
name: { tk: 'Daşoguz şahamçasy', ru: 'Дашогузское отделение', en: 'Dashoguz branch' },
|
|
||||||
code: 'BR-003',
|
|
||||||
districtId: 4,
|
|
||||||
districtName: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' },
|
|
||||||
address: { tk: 'Garaşsyzlyk köçesi, 10', ru: 'Улица Гарашсызлык, 10', en: 'Garashsyzlyk street, 10' },
|
|
||||||
phone: '+993 32 98-76-54',
|
|
||||||
email: 'dashoguz@tbbank.gov.tm',
|
|
||||||
workingHours: '08:30 - 17:30',
|
|
||||||
description: 'Şenbe güni 09:00 - 13:00',
|
|
||||||
isActive: false,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
let mockStore = [...MOCK_BRANCHES]
|
|
||||||
let nextId = 4
|
|
||||||
|
|
||||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
|
||||||
|
|
||||||
export async function fetchBranches(params: {
|
|
||||||
page?: number
|
|
||||||
perPage?: number
|
|
||||||
search?: string
|
|
||||||
isActive?: string
|
|
||||||
districtId?: string
|
|
||||||
}): Promise<BranchListResponse> {
|
|
||||||
await delay()
|
|
||||||
const { page = 1, perPage = 25, search = '', isActive, districtId } = params
|
|
||||||
|
|
||||||
let filtered = mockStore.filter((item) => {
|
|
||||||
const matchSearch =
|
|
||||||
!search ||
|
|
||||||
Object.values(item.name).some((n) =>
|
|
||||||
n.toLowerCase().includes(search.toLowerCase())
|
|
||||||
) ||
|
|
||||||
item.code.toLowerCase().includes(search.toLowerCase())
|
|
||||||
const matchActive =
|
|
||||||
isActive === '' || isActive === undefined
|
|
||||||
? true
|
|
||||||
: isActive === 'true'
|
|
||||||
? item.isActive
|
|
||||||
: !item.isActive
|
|
||||||
const matchDistrict =
|
|
||||||
!districtId || String(item.districtId) === districtId
|
|
||||||
return matchSearch && matchActive && matchDistrict
|
|
||||||
})
|
|
||||||
|
|
||||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
|
||||||
|
|
||||||
const total = filtered.length
|
|
||||||
const start = (page - 1) * perPage
|
|
||||||
const data = filtered.slice(start, start + perPage)
|
|
||||||
|
|
||||||
return { data, total, page, perPage }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchBranchById(id: number): Promise<Branch> {
|
export async function fetchBranchById(id: number): Promise<Branch> {
|
||||||
await delay()
|
const { data } = await apiClient.get<Branch>(`/branches/${id}`);
|
||||||
const item = mockStore.find((c) => c.id === id)
|
return data;
|
||||||
if (!item) throw new Error('Not found')
|
|
||||||
return { ...item }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createBranch(payload: CreateBranchPayload): Promise<Branch> {
|
export async function createBranch(payload: CreateBranchPayload): Promise<Branch> {
|
||||||
await delay(400)
|
const { data } = await apiClient.post<Branch>("/branches", payload);
|
||||||
const district = findDistrict(payload.districtId)
|
return data;
|
||||||
const newItem: Branch = {
|
|
||||||
id: nextId++,
|
|
||||||
...payload,
|
|
||||||
districtName: district.name,
|
|
||||||
}
|
|
||||||
mockStore = [newItem, ...mockStore]
|
|
||||||
return newItem
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateBranch(payload: UpdateBranchPayload): Promise<Branch> {
|
export async function updateBranch(payload: UpdateBranchPayload): Promise<Branch> {
|
||||||
await delay(400)
|
const { id, ...rest } = payload;
|
||||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
const { data } = await apiClient.put<Branch>(`/branches/${id}`, rest);
|
||||||
if (idx === -1) throw new Error('Not found')
|
return data;
|
||||||
const district = findDistrict(payload.districtId)
|
|
||||||
const updated = { ...mockStore[idx], ...payload, districtName: district.name }
|
|
||||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
|
||||||
return updated
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteBranch(id: number): Promise<void> {
|
export async function deleteBranch(id: number): Promise<void> {
|
||||||
await delay(300)
|
await apiClient.delete(`/branches/${id}`);
|
||||||
mockStore = mockStore.filter((c) => c.id !== id)
|
}
|
||||||
|
|
||||||
|
// ─── Province options (for the provinceId select) ─────────────────────────────
|
||||||
|
|
||||||
|
export interface ProvinceListResponse {
|
||||||
|
count: number;
|
||||||
|
provinces: Province[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchProvinces(
|
||||||
|
params: { page?: number; limit?: number; search?: string } = {},
|
||||||
|
signal?: AbortSignal,
|
||||||
|
): Promise<ProvinceListResponse> {
|
||||||
|
const { page, limit, search } = params;
|
||||||
|
const { data } = await apiClient.get<ProvinceListResponse>("/provinces", {
|
||||||
|
params: { page, limit, name: search || undefined },
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
}
|
}
|
||||||
@@ -1,368 +1,474 @@
|
|||||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
import { useState, useCallback, useMemo, useEffect } from "react";
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { Building2, MapPin, Clock } from 'lucide-react'
|
import { Building2, MapPin, CreditCard } from "lucide-react";
|
||||||
import type { LucideIcon } from 'lucide-react'
|
import type { LucideIcon } from "lucide-react";
|
||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput } from "@/components/formInput";
|
||||||
import { FormActions } from '@/components/formActions'
|
import { FormActions } from "@/components/formActions";
|
||||||
import { MultiLangInput } from '@/components/multiLangInput'
|
import { MultiLangInput } from "@/components/multiLangInput";
|
||||||
import { Checkbox } from '@/components/ui/checkbox'
|
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import { useCreateBranch, useUpdateBranch } from '@/features/branches/hooks/useBranches'
|
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||||
import type { Branch } from '@/features/branches/api/branchesApi'
|
import { useCreateBranch, useUpdateBranch, useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
|
||||||
import { getDistrictOptions } from '@/features/branches/api/branchesApi'
|
import { resolveLocalizedName, type Branch } from "@/features/branches/api/branchesApi";
|
||||||
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/branches/schemas/branch.schema'
|
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/branches/schemas/branch.schema";
|
||||||
import type { BranchFormData } from '@/features/branches/schemas/branch.schema'
|
import type { BranchFormData } from "@/features/branches/schemas/branch.schema";
|
||||||
|
|
||||||
type FlatErrors = Partial<Record<keyof BranchFormData, string>>
|
type FlatErrors = Partial<Record<keyof BranchFormData, string>>;
|
||||||
|
|
||||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||||
const result: FlatErrors = {}
|
const result: FlatErrors = {};
|
||||||
for (const key of Object.keys(errors)) {
|
for (const key of Object.keys(errors)) {
|
||||||
const msg = errors[key]?.message
|
const msg = errors[key]?.message;
|
||||||
if (msg) result[key as keyof BranchFormData] = msg
|
if (msg) result[key as keyof BranchFormData] = msg;
|
||||||
}
|
}
|
||||||
return result
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface StepDef {
|
interface StepDef {
|
||||||
id: string
|
id: string;
|
||||||
titleKey: string
|
titleKey: string;
|
||||||
titleFallback: string
|
titleFallback: string;
|
||||||
shortLabel: string
|
shortLabelKey: string;
|
||||||
icon: LucideIcon
|
shortLabel: string;
|
||||||
subtitle: string
|
icon: LucideIcon;
|
||||||
validate: (form: BranchFormData, mode: 'create' | 'edit', t: (key: string, fallback?: string) => string) => FlatErrors
|
subtitleKey: string;
|
||||||
|
subtitleFallback: string;
|
||||||
|
validate: (form: BranchFormData, mode: "create" | "edit", t: (key: string, fallback?: string) => string) => FlatErrors;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STEPS: StepDef[] = [
|
const STEPS: StepDef[] = [
|
||||||
{
|
{
|
||||||
id: 'basic',
|
id: "basic",
|
||||||
titleKey: 'branches.steps.basic',
|
titleKey: "branches.steps.basic",
|
||||||
titleFallback: 'Esasy maglumatlar',
|
titleFallback: "Esasy maglumatlar",
|
||||||
shortLabel: 'Esasy',
|
shortLabelKey: "branches.steps.basic.shortLabel",
|
||||||
|
shortLabel: "Esasy",
|
||||||
icon: Building2,
|
icon: Building2,
|
||||||
subtitle: 'Ady, kody, etrapy',
|
subtitleKey: "branches.steps.basic.subtitle",
|
||||||
|
subtitleFallback: "Ady, unikal belgisi, welaýaty",
|
||||||
validate: (form, mode, t) => validateStep(0, form, mode, t),
|
validate: (form, mode, t) => validateStep(0, form, mode, t),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'address',
|
id: "address",
|
||||||
titleKey: 'branches.steps.address',
|
titleKey: "branches.steps.address",
|
||||||
titleFallback: 'Salgy we habarlaşmak',
|
titleFallback: "Salgy we habarlaşmak",
|
||||||
shortLabel: 'Salgy',
|
shortLabelKey: "branches.steps.address.shortLabel",
|
||||||
|
shortLabel: "Salgy",
|
||||||
icon: MapPin,
|
icon: MapPin,
|
||||||
subtitle: 'Salgy, telefon, e-poçta',
|
subtitleKey: "branches.steps.address.subtitle",
|
||||||
|
subtitleFallback: "Salgy, telefonlar",
|
||||||
validate: (form, mode, t) => validateStep(1, form, mode, t),
|
validate: (form, mode, t) => validateStep(1, form, mode, t),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'hours',
|
id: "billing",
|
||||||
titleKey: 'branches.steps.hours',
|
titleKey: "branches.steps.billing",
|
||||||
titleFallback: 'Iş wagty',
|
titleFallback: "Billing maglumatlary",
|
||||||
shortLabel: 'Wagt',
|
shortLabelKey: "branches.steps.billing.shortLabel",
|
||||||
icon: Clock,
|
shortLabel: "Billing",
|
||||||
subtitle: 'Iş wagty we bellikler',
|
icon: CreditCard,
|
||||||
|
subtitleKey: "branches.steps.billing.subtitle",
|
||||||
|
subtitleFallback: "Ulanyjy ady we parollar",
|
||||||
validate: (form, mode, t) => validateStep(2, form, mode, t),
|
validate: (form, mode, t) => validateStep(2, form, mode, t),
|
||||||
},
|
},
|
||||||
]
|
];
|
||||||
|
|
||||||
const STEP_FIELDS: Record<number, (keyof BranchFormData)[]> = {
|
const STEP_FIELDS: Record<number, (keyof BranchFormData)[]> = {
|
||||||
0: ['nameTk', 'nameRu', 'nameEn', 'code', 'districtId', 'isActive'],
|
0: ["nameTk", "nameRu", "nameEn", "uniqueCode", "provinceId", "region", "isActive"],
|
||||||
1: ['addressTk', 'addressRu', 'addressEn', 'phone', 'email'],
|
1: ["addressTk", "addressRu", "addressEn", "phoneNumbers"],
|
||||||
2: ['workingHours', 'description'],
|
2: [
|
||||||
}
|
"billingUsername",
|
||||||
|
"billingPassword",
|
||||||
|
"billingSberUsername",
|
||||||
|
"billingSberPassword",
|
||||||
|
"billingVisaMasterUsername",
|
||||||
|
"billingVisaMasterPassword",
|
||||||
|
"billingSwiftUsername",
|
||||||
|
"billingSwiftPassword",
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
interface StepContentProps {
|
interface StepContentProps {
|
||||||
form: BranchFormData
|
form: BranchFormData;
|
||||||
errors: FlatErrors
|
errors: FlatErrors;
|
||||||
set: <K extends keyof BranchFormData>(k: K, v: BranchFormData[K]) => void
|
set: <K extends keyof BranchFormData>(k: K, v: BranchFormData[K]) => void;
|
||||||
t: (key: string, fallback?: string) => string
|
t: (key: string, fallback?: string) => string;
|
||||||
lang: 'tk' | 'ru' | 'en'
|
lang: "tm" | "ru" | "en";
|
||||||
|
provinceSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder">;
|
||||||
}
|
}
|
||||||
|
|
||||||
function StepBasic({ form, errors, set, t, lang }: StepContentProps) {
|
function StepBasic({ form, errors, set, t, provinceSelect }: StepContentProps) {
|
||||||
const nameFields = {
|
const nameFields = {
|
||||||
tk: { value: form.nameTk, onChange: (v: string) => set('nameTk', v), error: errors.nameTk },
|
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk", v), error: errors.nameTk },
|
||||||
ru: { value: form.nameRu, onChange: (v: string) => set('nameRu', v), error: errors.nameRu },
|
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu", v), error: errors.nameRu },
|
||||||
en: { value: form.nameEn, onChange: (v: string) => set('nameEn', v), error: errors.nameEn },
|
en: { value: form.nameEn, onChange: (v: string) => set("nameEn", v), error: errors.nameEn },
|
||||||
}
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
<MultiLangInput fields={nameFields} placeholder={t('branches.fields.name', 'Şahamçanyň ady')} />
|
<MultiLangInput fields={nameFields} placeholder={t("branches.fields.name", "Şahamçanyň ady")} />
|
||||||
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t('branches.fields.code', 'Kod')}
|
label={t("branches.fields.uniqueCode", "Unikal belgisi")}
|
||||||
required
|
required
|
||||||
value={form.code}
|
value={form.uniqueCode}
|
||||||
onChange={(v) => set('code', v)}
|
onChange={(v) => set("uniqueCode", v)}
|
||||||
placeholder="BR-XXX"
|
placeholder={t("branches.fields.uniqueCodePlaceholder", "ORG-XXX-XXXX")}
|
||||||
error={errors.code}
|
error={errors.uniqueCode}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("branches.fields.region", "Welaýat")}
|
||||||
|
required
|
||||||
|
value={form.region}
|
||||||
|
onChange={(v) => set("region", v)}
|
||||||
|
placeholder={t("branches.fields.regionPlaceholder", "Aşgabat şäheri")}
|
||||||
|
error={errors.region}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||||
<FormInput
|
<InfiniteSelect
|
||||||
type="searchable-select"
|
label={t("branches.fields.district", "Etrap")}
|
||||||
label={t('branches.fields.district', 'Etrap')}
|
|
||||||
required
|
required
|
||||||
value={form.districtId}
|
placeholder={t("branches.fields.districtPlaceholder", "Etrap saýlaň")}
|
||||||
onChange={(v) => set('districtId', v)}
|
{...provinceSelect}
|
||||||
options={getDistrictOptions().map((d) => ({ value: String(d.id), label: d.name[lang] }))}
|
error={provinceSelect.error ?? errors.provinceId}
|
||||||
placeholder={t('branches.fields.district', 'Etrap saýlaň')}
|
value={form.provinceId}
|
||||||
error={errors.districtId}
|
onChange={(v) => set("provinceId", v)}
|
||||||
/>
|
/>
|
||||||
<div className="flex items-end pb-2">
|
<div className="flex items-end pb-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Checkbox
|
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(checked) => set("isActive", !!checked)} />
|
||||||
id="isActive"
|
|
||||||
checked={form.isActive}
|
|
||||||
onCheckedChange={(checked) => set('isActive', !!checked)}
|
|
||||||
/>
|
|
||||||
<label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer select-none">
|
<label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer select-none">
|
||||||
{t('branches.fields.isActive', 'Işjeň')}
|
{t("branches.fields.isActive", "Işjeň")}
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function StepAddress({ form, errors, set, t }: StepContentProps) {
|
function StepAddress({ form, errors, set, t }: StepContentProps) {
|
||||||
const addressFields = {
|
const addressFields = {
|
||||||
tk: { value: form.addressTk, onChange: (v: string) => set('addressTk', v), error: errors.addressTk },
|
tk: { value: form.addressTk, onChange: (v: string) => set("addressTk", v), error: errors.addressTk },
|
||||||
ru: { value: form.addressRu, onChange: (v: string) => set('addressRu', v), error: errors.addressRu },
|
ru: { value: form.addressRu, onChange: (v: string) => set("addressRu", v), error: errors.addressRu },
|
||||||
en: { value: form.addressEn, onChange: (v: string) => set('addressEn', v), error: errors.addressEn },
|
en: { value: form.addressEn, onChange: (v: string) => set("addressEn", v), error: errors.addressEn },
|
||||||
}
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
<MultiLangInput fields={addressFields} placeholder={t('branches.fields.address', 'Salgy')} />
|
<MultiLangInput fields={addressFields} placeholder={t("branches.fields.address", "Salgy")} />
|
||||||
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||||
<FormInput
|
<FormInput
|
||||||
type="phone"
|
type="text"
|
||||||
label={t('branches.fields.phone', 'Telefon')}
|
label={t("branches.fields.phoneNumbers", "Telefonlar")}
|
||||||
required
|
required
|
||||||
value={form.phone}
|
value={form.phoneNumbers}
|
||||||
onChange={(v) => set('phone', v)}
|
onChange={(v) => set("phoneNumbers", v)}
|
||||||
placeholder="12 45-67-89"
|
placeholder={t("branches.fields.phoneNumbersPlaceholder", "+99312998877, +99365123456")}
|
||||||
error={errors.phone}
|
error={errors.phoneNumbers}
|
||||||
/>
|
|
||||||
<FormInput
|
|
||||||
type="email"
|
|
||||||
label={t('branches.fields.email', 'E-poçta')}
|
|
||||||
required
|
|
||||||
value={form.email}
|
|
||||||
onChange={(v) => set('email', v)}
|
|
||||||
placeholder="email@tbbank.gov.tm"
|
|
||||||
error={errors.email}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function StepHours({ form, errors, set, t }: StepContentProps) {
|
function StepBilling({ form, errors, set, t }: StepContentProps) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6">
|
<div className="flex flex-col gap-6">
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t('branches.fields.workingHours', 'Iş wagty')}
|
label={t("branches.fields.billingIbr", "Billing ulanyjy ady")}
|
||||||
required
|
required
|
||||||
value={form.workingHours}
|
value={form.billingUsername}
|
||||||
onChange={(v) => set('workingHours', v)}
|
onChange={(v) => set("billingUsername", v)}
|
||||||
placeholder="09:00 - 18:00"
|
placeholder="billing_user"
|
||||||
error={errors.workingHours}
|
error={errors.billingUsername}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="password"
|
||||||
|
label={t("branches.fields.billingPassword", "Billing paroly")}
|
||||||
|
required
|
||||||
|
value={form.billingPassword}
|
||||||
|
onChange={(v) => set("billingPassword", v)}
|
||||||
|
placeholder="••••••••"
|
||||||
|
error={errors.billingPassword}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("branches.fields.billingSber", "Billing ulanyjy ady (SBER)")}
|
||||||
|
required
|
||||||
|
value={form.billingSberUsername}
|
||||||
|
onChange={(v) => set("billingSberUsername", v)}
|
||||||
|
placeholder="sber_merchant"
|
||||||
|
error={errors.billingSberUsername}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="password"
|
||||||
|
label={t("branches.fields.billingSberPassword", "Parol (SBER)")}
|
||||||
|
required
|
||||||
|
value={form.billingSberPassword}
|
||||||
|
onChange={(v) => set("billingSberPassword", v)}
|
||||||
|
placeholder="••••••••"
|
||||||
|
error={errors.billingSberPassword}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("branches.fields.billingVisa", "Billing ulanyjy ady (VISA)")}
|
||||||
|
required
|
||||||
|
value={form.billingVisaMasterUsername}
|
||||||
|
onChange={(v) => set("billingVisaMasterUsername", v)}
|
||||||
|
placeholder="visamaster_merchant"
|
||||||
|
error={errors.billingVisaMasterUsername}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="password"
|
||||||
|
label={t("branches.fields.billingVisaPassword", "Parol (VISA)")}
|
||||||
|
required
|
||||||
|
value={form.billingVisaMasterPassword}
|
||||||
|
onChange={(v) => set("billingVisaMasterPassword", v)}
|
||||||
|
placeholder="••••••••"
|
||||||
|
error={errors.billingVisaMasterPassword}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("branches.fields.billingSwift", "Billing ulanyjy ady (SWIFT)")}
|
||||||
|
required
|
||||||
|
value={form.billingSwiftUsername}
|
||||||
|
onChange={(v) => set("billingSwiftUsername", v)}
|
||||||
|
placeholder="SWIFT_TM_BANK"
|
||||||
|
error={errors.billingSwiftUsername}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="password"
|
||||||
|
label={t("branches.fields.billingSwiftPassword", "Parol (SWIFT)")}
|
||||||
|
required
|
||||||
|
value={form.billingSwiftPassword}
|
||||||
|
onChange={(v) => set("billingSwiftPassword", v)}
|
||||||
|
placeholder="••••••••"
|
||||||
|
error={errors.billingSwiftPassword}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<FormInput
|
|
||||||
type="textarea"
|
|
||||||
label={t('branches.fields.description', 'Bellikler')}
|
|
||||||
value={form.description}
|
|
||||||
onChange={(v) => set('description', v)}
|
|
||||||
placeholder="Goşmaça maglumatlar..."
|
|
||||||
rows={3}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BranchFormProps {
|
export interface BranchFormProps {
|
||||||
mode: 'create' | 'edit'
|
mode: "create" | "edit";
|
||||||
initialData?: Branch
|
initialData?: Branch;
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapInitial(data: Branch): Partial<BranchFormData> {
|
function mapInitial(data: Branch): Partial<BranchFormData> {
|
||||||
return {
|
return {
|
||||||
nameTk: data.name.tk,
|
nameTk: resolveLocalizedName(data.name, "tm"),
|
||||||
nameRu: data.name.ru,
|
nameRu: resolveLocalizedName(data.name, "ru"),
|
||||||
nameEn: data.name.en,
|
nameEn: resolveLocalizedName(data.name, "en"),
|
||||||
code: data.code,
|
uniqueCode: data.uniqueCode,
|
||||||
districtId: String(data.districtId),
|
provinceId: String(data.provinceId),
|
||||||
addressTk: data.address.tk,
|
region: data.region,
|
||||||
addressRu: data.address.ru,
|
addressTk: resolveLocalizedName(data.address, "tm"),
|
||||||
addressEn: data.address.en,
|
addressRu: resolveLocalizedName(data.address, "ru"),
|
||||||
phone: data.phone,
|
addressEn: resolveLocalizedName(data.address, "en"),
|
||||||
email: data.email,
|
phoneNumbers: data.phoneNumbers,
|
||||||
workingHours: data.workingHours,
|
billingUsername: data.billingUsername,
|
||||||
description: data.description ?? '',
|
billingPassword: data.billingPassword,
|
||||||
isActive: data.isActive,
|
billingSberUsername: data.billingSberUsername,
|
||||||
}
|
billingSberPassword: data.billingSberPassword,
|
||||||
|
billingVisaMasterUsername: data.billingVisaMasterUsername,
|
||||||
|
billingVisaMasterPassword: data.billingVisaMasterPassword,
|
||||||
|
billingSwiftUsername: data.billingSwiftUsername,
|
||||||
|
billingSwiftPassword: data.billingSwiftPassword,
|
||||||
|
isActive: data.active,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function BranchForm({ mode, initialData }: BranchFormProps) {
|
export function BranchForm({ mode, initialData }: BranchFormProps) {
|
||||||
const { t: _t, i18n } = useTranslation()
|
const { t: _t, i18n } = useTranslation();
|
||||||
const t: (key: string, fallback?: string) => string = useCallback(
|
const t: (key: string, fallback?: string) => string = useCallback((key, fallback) => _t(key, fallback ?? key) as string, [_t]);
|
||||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
const lang = ((i18n.language?.slice(0, 2) === "tk" ? "tm" : i18n.language?.slice(0, 2)) ?? "tm") as "tm" | "ru" | "en";
|
||||||
[_t],
|
const navigate = useNavigate();
|
||||||
)
|
|
||||||
const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en'
|
|
||||||
const navigate = useNavigate()
|
|
||||||
|
|
||||||
const createMutation = useCreateBranch()
|
const createMutation = useCreateBranch();
|
||||||
const updateMutation = useUpdateBranch()
|
const updateMutation = useUpdateBranch();
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language])
|
const [provinceSearch, setProvinceSearch] = useState("");
|
||||||
|
const provinceQuery = useInfiniteProvinces(provinceSearch);
|
||||||
|
|
||||||
|
const provinceSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||||
|
const opts: InfiniteSelectOption[] = (provinceQuery.data?.pages ?? [])
|
||||||
|
.flatMap((p) => p?.provinces ?? [])
|
||||||
|
.map((p) => ({ value: String(p.id), label: resolveLocalizedName(p.name, lang) }));
|
||||||
|
|
||||||
|
// Ensure the currently-selected province is present (edit mode), even if it
|
||||||
|
// lives beyond the pages loaded so far.
|
||||||
|
if (initialData) {
|
||||||
|
const current = String(initialData.provinceId);
|
||||||
|
if (!opts.some((o) => o.value === current)) {
|
||||||
|
opts.unshift({ value: current, label: resolveLocalizedName(initialData.provinceName, lang) || current });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
options: opts,
|
||||||
|
loading: provinceQuery.isLoading,
|
||||||
|
isLoadingMore: provinceQuery.isFetchingNextPage,
|
||||||
|
hasNextPage: !!provinceQuery.hasNextPage,
|
||||||
|
onLoadMore: () => provinceQuery.fetchNextPage(),
|
||||||
|
searchValue: provinceSearch,
|
||||||
|
onSearchChange: setProvinceSearch,
|
||||||
|
};
|
||||||
|
}, [provinceQuery, provinceSearch, lang, initialData]);
|
||||||
|
|
||||||
|
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
watch,
|
||||||
|
setValue,
|
||||||
|
getValues,
|
||||||
|
formState: { errors: rhfErrors },
|
||||||
|
clearErrors,
|
||||||
|
trigger,
|
||||||
} = useForm<BranchFormData>({
|
} = useForm<BranchFormData>({
|
||||||
resolver: zodResolver(schema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||||
})
|
});
|
||||||
|
|
||||||
const form = watch()
|
const form = watch();
|
||||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||||
|
|
||||||
const [currentStep, setCurrentStep] = useState(0)
|
const [currentStep, setCurrentStep] = useState(0);
|
||||||
const [visited, setVisited] = useState<Set<number>>(
|
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
const [isValidated, setIsValidated] = useState(false);
|
||||||
)
|
|
||||||
const [isValidated, setIsValidated] = useState(false)
|
|
||||||
|
|
||||||
const stepsWithErrors = useMemo(() => {
|
const stepsWithErrors = useMemo(() => {
|
||||||
const out = new Set<number>()
|
const out = new Set<number>();
|
||||||
visited.forEach((i) => {
|
visited.forEach((i) => {
|
||||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i)
|
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i);
|
||||||
})
|
});
|
||||||
return out
|
return out;
|
||||||
}, [form, mode, visited, t])
|
}, [form, mode, visited, t]);
|
||||||
|
|
||||||
const set = useCallback(<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
const set = useCallback(
|
||||||
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value)
|
<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
||||||
clearErrors(key)
|
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value);
|
||||||
}, [setValue, clearErrors])
|
clearErrors(key);
|
||||||
|
},
|
||||||
|
[setValue, clearErrors],
|
||||||
|
);
|
||||||
|
|
||||||
const stepProps = useMemo(() => ({ form, errors, set, t, lang }), [form, errors, set, t, lang])
|
const stepProps = useMemo(() => ({ form, errors, set, t, lang, provinceSelect }), [form, errors, set, t, lang, provinceSelect]);
|
||||||
|
|
||||||
const markVisited = (i: number) =>
|
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||||
setVisited((prev) => new Set([...prev, i]))
|
|
||||||
|
|
||||||
// ── Re-validate on language change ──
|
// ── Re-validate on language change ──
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isValidated) return
|
if (!isValidated) return;
|
||||||
|
|
||||||
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || [])
|
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || []);
|
||||||
if (visitedFields.length > 0) {
|
if (visitedFields.length > 0) {
|
||||||
trigger(visitedFields)
|
trigger(visitedFields);
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [i18n.language, isValidated])
|
}, [i18n.language, isValidated]);
|
||||||
|
|
||||||
const handleNext = async () => {
|
const handleNext = async () => {
|
||||||
setIsValidated(true)
|
setIsValidated(true);
|
||||||
markVisited(currentStep)
|
markVisited(currentStep);
|
||||||
|
|
||||||
const fields = STEP_FIELDS[currentStep] || []
|
const fields = STEP_FIELDS[currentStep] || [];
|
||||||
const isValid = await trigger(fields)
|
const isValid = await trigger(fields);
|
||||||
|
|
||||||
if (!isValid) {
|
if (!isValid) {
|
||||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
if (currentStep < STEPS.length - 1) {
|
if (currentStep < STEPS.length - 1) {
|
||||||
setCurrentStep(currentStep + 1)
|
setCurrentStep(currentStep + 1);
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleBack = () => {
|
const handleBack = () => {
|
||||||
if (currentStep > 0) {
|
if (currentStep > 0) {
|
||||||
markVisited(currentStep)
|
markVisited(currentStep);
|
||||||
setCurrentStep(currentStep - 1)
|
setCurrentStep(currentStep - 1);
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleGoTo = (i: number) => {
|
const handleGoTo = (i: number) => {
|
||||||
markVisited(currentStep)
|
markVisited(currentStep);
|
||||||
setCurrentStep(i)
|
setCurrentStep(i);
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
}
|
};
|
||||||
|
|
||||||
const doSubmit = async () => {
|
const doSubmit = async () => {
|
||||||
setIsValidated(true)
|
setIsValidated(true);
|
||||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||||
|
|
||||||
const isValid = await trigger()
|
const isValid = await trigger();
|
||||||
if (!isValid) {
|
if (!isValid) {
|
||||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||||
for (let i = 0; i < STEPS.length; i++) {
|
for (let i = 0; i < STEPS.length; i++) {
|
||||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) {
|
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) {
|
||||||
setCurrentStep(i); break
|
setCurrentStep(i);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload = buildPayload(getValues())
|
const payload = buildPayload(getValues());
|
||||||
|
|
||||||
if (mode === 'create') {
|
if (mode === "create") {
|
||||||
createMutation.mutate(payload, { onSuccess: () => navigate('/settings/location/branches') })
|
createMutation.mutate(payload, { onSuccess: () => navigate("/settings/location/branches") });
|
||||||
} else if (initialData) {
|
} else if (initialData) {
|
||||||
updateMutation.mutate(
|
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/location/branches") });
|
||||||
{ id: initialData.id, ...payload },
|
|
||||||
{ onSuccess: () => navigate('/settings/location/branches') },
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||||
const isActive = i === currentStep
|
const isActive = i === currentStep;
|
||||||
const hasErrors = stepsWithErrors.has(i)
|
const hasErrors = stepsWithErrors.has(i);
|
||||||
const isDone = visited.has(i) && !hasErrors
|
const isDone = visited.has(i) && !hasErrors;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: s.id,
|
id: s.id,
|
||||||
title: t(s.titleKey) || s.titleFallback,
|
title: t(s.titleKey, s.titleFallback),
|
||||||
subtitle: s.subtitle,
|
subtitle: t(s.subtitleKey, s.subtitleFallback),
|
||||||
icon: s.icon,
|
icon: s.icon,
|
||||||
status: isActive ? 'active'
|
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||||
: hasErrors ? 'error'
|
};
|
||||||
: isDone ? 'done'
|
});
|
||||||
: 'idle',
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const isLastStep = currentStep === STEPS.length - 1
|
const isLastStep = currentStep === STEPS.length - 1;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === 'create' ? t('branches.createTitle', 'Şahamça döretmek') : t('branches.editTitle', 'Şahamçany üýtgetmek')}
|
{mode === "create" ? t("branches.createTitle", "Şahamça döretmek") : t("branches.editTitle", "Şahamçany üýtgetmek")}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">{t("branches.form.subtitle", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}</p>
|
||||||
{t('branches.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
|
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
|
||||||
@@ -372,15 +478,13 @@ export function BranchForm({ mode, initialData }: BranchFormProps) {
|
|||||||
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[11px] font-semibold tabular-nums">
|
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[11px] font-semibold tabular-nums">
|
||||||
{currentStep + 1} / {STEPS.length}
|
{currentStep + 1} / {STEPS.length}
|
||||||
</span>
|
</span>
|
||||||
<h2 className="text-sm font-semibold text-foreground">
|
<h2 className="text-sm font-semibold text-foreground">{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}</h2>
|
||||||
{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}
|
|
||||||
</h2>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="p-5">
|
<div className="p-5">
|
||||||
{currentStep === 0 && <StepBasic {...stepProps} />}
|
{currentStep === 0 && <StepBasic {...stepProps} />}
|
||||||
{currentStep === 1 && <StepAddress {...stepProps} />}
|
{currentStep === 1 && <StepAddress {...stepProps} />}
|
||||||
{currentStep === 2 && <StepHours {...stepProps} />}
|
{currentStep === 2 && <StepBilling {...stepProps} />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<FormActions
|
<FormActions
|
||||||
@@ -389,13 +493,12 @@ export function BranchForm({ mode, initialData }: BranchFormProps) {
|
|||||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||||
onNext={!isLastStep ? handleNext : undefined}
|
onNext={!isLastStep ? handleNext : undefined}
|
||||||
showSubmit={isLastStep}
|
showSubmit={isLastStep}
|
||||||
onSubmit={isLastStep ? doSubmit : undefined}
|
saveOnEveryStep={mode === "edit"}
|
||||||
submitLabel={mode === 'create'
|
onSubmit={doSubmit}
|
||||||
? t('branches.actions.create', 'Şahamça döret')
|
submitLabel={mode === "create" ? t("branches.actions.create", "Şahamça döret") : t("branches.actions.update", "Täzelemek")}
|
||||||
: t('branches.actions.update', 'Täzelemek')}
|
|
||||||
className="px-5 py-3.5 border-t border-border bg-muted/30"
|
className="px-5 py-3.5 border-t border-border bg-muted/30"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
@@ -1,35 +1,105 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
import {
|
import {
|
||||||
fetchBranches,
|
fetchBranches,
|
||||||
fetchBranchById,
|
fetchBranchById,
|
||||||
|
fetchProvinces,
|
||||||
createBranch,
|
createBranch,
|
||||||
updateBranch,
|
updateBranch,
|
||||||
deleteBranch,
|
deleteBranch,
|
||||||
|
type BranchListParams,
|
||||||
type CreateBranchPayload,
|
type CreateBranchPayload,
|
||||||
type UpdateBranchPayload,
|
type UpdateBranchPayload,
|
||||||
} from '../api/branchesApi'
|
type Province,
|
||||||
|
} from "../api/branchesApi";
|
||||||
|
|
||||||
export const branchKeys = {
|
export const branchKeys = {
|
||||||
all: ['branches'] as const,
|
all: ["branches"] as const,
|
||||||
lists: () => [...branchKeys.all, 'list'] as const,
|
lists: () => [...branchKeys.all, "list"] as const,
|
||||||
list: (params: Record<string, unknown>) =>
|
list: (params: BranchListParams) => [...branchKeys.lists(), params] as const,
|
||||||
[...branchKeys.lists(), params] as const,
|
detail: (id: number) => [...branchKeys.all, "detail", id] as const,
|
||||||
detail: (id: number) => [...branchKeys.all, 'detail', id] as const,
|
provinces: ["provinces"] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useBranches(params: BranchListParams) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
|
const normalized = normalizeSearch(debouncedSearch);
|
||||||
|
const queryParams: BranchListParams = { ...params, search: normalized || undefined };
|
||||||
|
|
||||||
|
return useQuery({
|
||||||
|
queryKey: branchKeys.list(queryParams),
|
||||||
|
queryFn: ({ signal }) => fetchBranches(queryParams, signal),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useBranches(params: {
|
const BRANCH_PAGE_SIZE = 25;
|
||||||
page?: number
|
|
||||||
perPage?: number
|
/**
|
||||||
search?: string
|
* Paginated branches for infinite-scroll selects.
|
||||||
isActive?: string
|
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||||
districtId?: string
|
*/
|
||||||
}) {
|
export function useInfiniteBranches(search = "", enabled = true) {
|
||||||
|
const debouncedSearch = useDebouncedValue(search);
|
||||||
|
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||||
|
|
||||||
|
return useInfiniteQuery({
|
||||||
|
queryKey: [...branchKeys.lists(), "infinite", effectiveSearch],
|
||||||
|
initialPageParam: 1,
|
||||||
|
queryFn: ({ pageParam, signal }) => fetchBranches({ page: pageParam, limit: BRANCH_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||||
|
getNextPageParam: (lastPage, allPages) => {
|
||||||
|
const loaded = allPages.reduce((sum, p) => sum + (p?.branches?.length ?? 0), 0);
|
||||||
|
const count = lastPage?.count ?? 0;
|
||||||
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
|
},
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const PROVINCE_PAGE_SIZE = 25;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paginated provinces for infinite-scroll selects.
|
||||||
|
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||||
|
*/
|
||||||
|
export function useInfiniteProvinces(search = "", enabled = true) {
|
||||||
|
const debouncedSearch = useDebouncedValue(search);
|
||||||
|
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||||
|
|
||||||
|
return useInfiniteQuery({
|
||||||
|
queryKey: [...branchKeys.provinces, "infinite", effectiveSearch],
|
||||||
|
initialPageParam: 1,
|
||||||
|
queryFn: ({ pageParam, signal }) => fetchProvinces({ page: pageParam, limit: PROVINCE_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||||
|
getNextPageParam: (lastPage, allPages) => {
|
||||||
|
const loaded = allPages.reduce((sum, p) => sum + (p?.provinces?.length ?? 0), 0);
|
||||||
|
const count = lastPage?.count ?? 0;
|
||||||
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
|
},
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads every province page and flattens them.
|
||||||
|
* Intended for static option lists (e.g. table filter dropdowns) where the
|
||||||
|
* dataset is small and an infinite-scroll select is overkill.
|
||||||
|
*/
|
||||||
|
export function useProvinceOptions() {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: branchKeys.list(params),
|
queryKey: [...branchKeys.provinces, "all"] as const,
|
||||||
queryFn: () => fetchBranches(params),
|
queryFn: async (): Promise<Province[]> => {
|
||||||
})
|
const all: Province[] = [];
|
||||||
|
let page = 1;
|
||||||
|
for (;;) {
|
||||||
|
const res = await fetchProvinces({ page, limit: PROVINCE_PAGE_SIZE });
|
||||||
|
all.push(...res.provinces);
|
||||||
|
if (all.length >= res.count || res.provinces.length === 0) break;
|
||||||
|
page += 1;
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useBranchById(id: number) {
|
export function useBranchById(id: number) {
|
||||||
@@ -37,45 +107,45 @@ export function useBranchById(id: number) {
|
|||||||
queryKey: branchKeys.detail(id),
|
queryKey: branchKeys.detail(id),
|
||||||
queryFn: () => fetchBranchById(id),
|
queryFn: () => fetchBranchById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCreateBranch() {
|
export function useCreateBranch() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateBranchPayload) => createBranch(payload),
|
mutationFn: (payload: CreateBranchPayload) => createBranch(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||||
toast.success(t('branches.toast.createSuccess', 'Şahamça döredildi'))
|
toast.success(t("branches.toast.createSuccess", "Şahamça döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUpdateBranch() {
|
export function useUpdateBranch() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateBranchPayload) => updateBranch(payload),
|
mutationFn: (payload: UpdateBranchPayload) => updateBranch(payload),
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: branchKeys.detail(data.id) })
|
queryClient.invalidateQueries({ queryKey: branchKeys.detail(data.id) });
|
||||||
toast.success(t('branches.toast.updateSuccess', 'Şahamça täzelendi'))
|
toast.success(t("branches.toast.updateSuccess", "Şahamça täzelendi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDeleteBranch() {
|
export function useDeleteBranch() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => deleteBranch(id),
|
mutationFn: (id: number) => deleteBranch(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||||
toast.success(t('branches.toast.deleteSuccess', 'Şahamça öçürildi'))
|
toast.success(t("branches.toast.deleteSuccess", "Şahamça öçürildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
@@ -1,39 +1,26 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { CreateBranchPayload } from "@/features/branches/api/branchesApi";
|
import type { CreateBranchPayload } from "@/features/branches/api/branchesApi";
|
||||||
|
|
||||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
|
||||||
|
|
||||||
export function createBranchFormSchema(t: (key: string, fallback?: string) => string) {
|
export function createBranchFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
return z.object({
|
return z.object({
|
||||||
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
code: z.string().min(1, t("validation.required", "validation.required")),
|
uniqueCode: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
districtId: z.string().min(1, t("validation.required", "validation.required")),
|
provinceId: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
region: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
addressTk: z.string().min(1, t("validation.required", "validation.required")),
|
addressTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
addressRu: z.string().min(1, t("validation.required", "validation.required")),
|
addressRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
addressEn: z.string().min(1, t("validation.required", "validation.required")),
|
addressEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
phone: z
|
phoneNumbers: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
.string()
|
billingUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
.min(1, t("validation.required", "validation.required"))
|
billingPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
.refine(
|
billingSberUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
(val) => {
|
billingSberPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
const digits = val.replace(/\D/g, "");
|
billingVisaMasterUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
return digits.length === 8;
|
billingVisaMasterPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
},
|
billingSwiftUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
{ message: t("validation.invalidPhone", "validation.invalidPhone") },
|
billingSwiftPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
)
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
const digits = val.replace(/\D/g, "");
|
|
||||||
const prefix = digits.slice(0, 2);
|
|
||||||
return VALID_PHONE_PREFIXES.includes(prefix);
|
|
||||||
},
|
|
||||||
{ message: t("validation.invalidPhonePrefix", "validation.invalidPhonePrefix") },
|
|
||||||
),
|
|
||||||
email: z.string().min(1, t("validation.required", "validation.required")),
|
|
||||||
workingHours: z.string().min(1, t("validation.required", "validation.required")),
|
|
||||||
description: z.string().optional(),
|
|
||||||
isActive: z.boolean(),
|
isActive: z.boolean(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -45,9 +32,18 @@ type StepSchemas = Record<number, z.ZodType<Partial<BranchFormData>>>;
|
|||||||
function createStepSchemas(t: (key: string, fallback?: string) => string): StepSchemas {
|
function createStepSchemas(t: (key: string, fallback?: string) => string): StepSchemas {
|
||||||
const schema = createBranchFormSchema(t);
|
const schema = createBranchFormSchema(t);
|
||||||
return {
|
return {
|
||||||
0: schema.pick({ nameTk: true, nameRu: true, nameEn: true, code: true, districtId: true }),
|
0: schema.pick({ nameTk: true, nameRu: true, nameEn: true, uniqueCode: true, provinceId: true, region: true }),
|
||||||
1: schema.pick({ addressTk: true, addressRu: true, addressEn: true, phone: true, email: true }),
|
1: schema.pick({ addressTk: true, addressRu: true, addressEn: true, phoneNumbers: true }),
|
||||||
2: schema.pick({ workingHours: true }),
|
2: schema.pick({
|
||||||
|
billingUsername: true,
|
||||||
|
billingPassword: true,
|
||||||
|
billingSberUsername: true,
|
||||||
|
billingSberPassword: true,
|
||||||
|
billingVisaMasterUsername: true,
|
||||||
|
billingVisaMasterPassword: true,
|
||||||
|
billingSwiftUsername: true,
|
||||||
|
billingSwiftPassword: true,
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,28 +71,40 @@ export const DEFAULT_FORM_VALUES: BranchFormData = {
|
|||||||
nameTk: "",
|
nameTk: "",
|
||||||
nameRu: "",
|
nameRu: "",
|
||||||
nameEn: "",
|
nameEn: "",
|
||||||
code: "",
|
uniqueCode: "",
|
||||||
districtId: "",
|
provinceId: "",
|
||||||
|
region: "",
|
||||||
addressTk: "",
|
addressTk: "",
|
||||||
addressRu: "",
|
addressRu: "",
|
||||||
addressEn: "",
|
addressEn: "",
|
||||||
phone: "",
|
phoneNumbers: "",
|
||||||
email: "",
|
billingUsername: "",
|
||||||
workingHours: "",
|
billingPassword: "",
|
||||||
description: "",
|
billingSberUsername: "",
|
||||||
|
billingSberPassword: "",
|
||||||
|
billingVisaMasterUsername: "",
|
||||||
|
billingVisaMasterPassword: "",
|
||||||
|
billingSwiftUsername: "",
|
||||||
|
billingSwiftPassword: "",
|
||||||
isActive: true,
|
isActive: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function buildPayload(data: BranchFormData): CreateBranchPayload {
|
export function buildPayload(data: BranchFormData): CreateBranchPayload {
|
||||||
return {
|
return {
|
||||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
name: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||||
code: data.code,
|
uniqueCode: data.uniqueCode.trim(),
|
||||||
districtId: Number(data.districtId),
|
provinceId: Number(data.provinceId),
|
||||||
address: { tk: data.addressTk, ru: data.addressRu, en: data.addressEn },
|
region: data.region.trim(),
|
||||||
phone: data.phone,
|
address: { tm: data.addressTk.trim(), ru: data.addressRu.trim(), en: data.addressEn.trim() },
|
||||||
email: data.email,
|
phoneNumbers: data.phoneNumbers.trim(),
|
||||||
workingHours: data.workingHours,
|
billingUsername: data.billingUsername.trim(),
|
||||||
description: (data.description ?? "").trim() || null,
|
billingPassword: data.billingPassword,
|
||||||
isActive: data.isActive,
|
billingSberUsername: data.billingSberUsername.trim(),
|
||||||
|
billingSberPassword: data.billingSberPassword,
|
||||||
|
billingVisaMasterUsername: data.billingVisaMasterUsername.trim(),
|
||||||
|
billingVisaMasterPassword: data.billingVisaMasterPassword,
|
||||||
|
billingSwiftUsername: data.billingSwiftUsername.trim(),
|
||||||
|
billingSwiftPassword: data.billingSwiftPassword,
|
||||||
|
active: data.isActive,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,104 +1,96 @@
|
|||||||
import apiClient from '@/lib/api/client'
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export type CardBalanceStatus = "pending" | "approved" | "rejected";
|
||||||
|
|
||||||
|
export interface CardBalanceUser {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
username: string;
|
||||||
|
phone: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Raw backend entity (GET responses mirror this shape). */
|
||||||
export interface CardBalance {
|
export interface CardBalance {
|
||||||
id: number
|
id: number;
|
||||||
passport_series: string
|
passportNumber: string;
|
||||||
passport_number: string
|
cardLast4: string;
|
||||||
card_number: string
|
expiryMonth: number;
|
||||||
card_expiry_month: string
|
expiryYear: number;
|
||||||
card_expiry_year: string
|
expiryAt: string;
|
||||||
|
balanceAmount: number;
|
||||||
|
balanceCurrency: string;
|
||||||
|
status: string;
|
||||||
|
checkedAt: string;
|
||||||
|
createdBy: CardBalanceUser;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** LIST RESPONSE: GET /card-balances */
|
||||||
export interface CardBalanceListResponse {
|
export interface CardBalanceListResponse {
|
||||||
data: CardBalance[]
|
count: number;
|
||||||
total: number
|
cardBalances: CardBalance[];
|
||||||
page: number
|
|
||||||
per_page: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateCardBalancePayload {
|
/** LIST PARAMS */
|
||||||
passport_series: string
|
|
||||||
passport_number: string
|
|
||||||
card_number: string
|
|
||||||
card_expiry_month: string
|
|
||||||
card_expiry_year: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type UpdateCardBalancePayload = CreateCardBalancePayload
|
|
||||||
|
|
||||||
export interface CardBalanceListParams {
|
export interface CardBalanceListParams {
|
||||||
page?: number
|
page?: number;
|
||||||
per_page?: number
|
limit?: number;
|
||||||
search?: string
|
status?: string;
|
||||||
|
passport_number?: string;
|
||||||
|
created_by?: number | string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── API ─────────────────────────────────────────────────────────────────────
|
/** CREATE / UPDATE PAYLOAD (camelCase, JSON) */
|
||||||
|
export interface CardBalancePayload {
|
||||||
|
balanceAmount: number;
|
||||||
|
balanceCurrency: string;
|
||||||
|
cardNumber: string;
|
||||||
|
checkedAt: string;
|
||||||
|
createdBy: number;
|
||||||
|
expiryMonth: number;
|
||||||
|
expiryYear: number;
|
||||||
|
passportNumber: string;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
const MOCK_CARD_BALANCES: CardBalance[] = [
|
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
passport_series: 'AA',
|
|
||||||
passport_number: '1112223',
|
|
||||||
card_number: '8600123412341234',
|
|
||||||
card_expiry_month: '10',
|
|
||||||
card_expiry_year: '2028',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
passport_series: 'I-MR',
|
|
||||||
passport_number: '9988776',
|
|
||||||
card_number: '9860123456789012',
|
|
||||||
card_expiry_month: '05',
|
|
||||||
card_expiry_year: '2027',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 3,
|
|
||||||
passport_series: 'II-LB',
|
|
||||||
passport_number: '4455667',
|
|
||||||
card_number: '4400556677889900',
|
|
||||||
card_expiry_month: '12',
|
|
||||||
card_expiry_year: '2026',
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
export const cardBalancesApi = {
|
export const cardBalancesApi = {
|
||||||
getAll: async (params?: CardBalanceListParams): Promise<CardBalanceListResponse> => {
|
getList: async (params: CardBalanceListParams = {}, signal?: AbortSignal): Promise<CardBalanceListResponse> => {
|
||||||
// Mock data kullanmak için:
|
const { page, limit, status, passport_number, created_by } = params;
|
||||||
return { data: MOCK_CARD_BALANCES, total: MOCK_CARD_BALANCES.length, page: params?.page || 1, per_page: params?.per_page || 25 }
|
const { data } = await apiClient.get<CardBalanceListResponse>("/card-balances", {
|
||||||
|
params: {
|
||||||
const { data } = await apiClient.get('/card-balances', { params })
|
page,
|
||||||
return data
|
limit,
|
||||||
|
status: status || undefined,
|
||||||
|
passport_number: passport_number || undefined,
|
||||||
|
created_by: created_by || undefined,
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
getById: async (id: number): Promise<CardBalance> => {
|
getById: async (id: number): Promise<CardBalance> => {
|
||||||
// Mock data kullanmak için:
|
const { data } = await apiClient.get<CardBalance>(`/card-balances/${id}`);
|
||||||
const mock = MOCK_CARD_BALANCES.find(b => b.id === id)
|
return data;
|
||||||
if (mock) return mock
|
|
||||||
|
|
||||||
const { data } = await apiClient.get(`/card-balances/${id}`)
|
|
||||||
return data
|
|
||||||
},
|
},
|
||||||
|
|
||||||
create: async (payload: CreateCardBalancePayload): Promise<CardBalance> => {
|
create: async (payload: CardBalancePayload): Promise<CardBalance> => {
|
||||||
const { data } = await apiClient.post('/card-balances', payload)
|
const { data } = await apiClient.post<CardBalance>("/card-balances", payload);
|
||||||
return data
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
update: async (id: number, payload: UpdateCardBalancePayload): Promise<CardBalance> => {
|
update: async (id: number, payload: CardBalancePayload): Promise<CardBalance> => {
|
||||||
const { data } = await apiClient.put(`/card-balances/${id}`, payload)
|
const { data } = await apiClient.put<CardBalance>(`/card-balances/${id}`, payload);
|
||||||
return data
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
delete: async (id: number): Promise<void> => {
|
delete: async (id: number): Promise<void> => {
|
||||||
await apiClient.delete(`/card-balances/${id}`)
|
await apiClient.delete(`/card-balances/${id}`);
|
||||||
},
|
},
|
||||||
|
};
|
||||||
download: async (id: number): Promise<Blob> => {
|
|
||||||
const { data } = await apiClient.get(`/card-balances/${id}/download`, {
|
|
||||||
responseType: 'blob',
|
|
||||||
})
|
|
||||||
return data
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,187 +1,249 @@
|
|||||||
import { useCallback, useMemo } from 'react'
|
import { useState, useCallback, useMemo } from "react";
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from "react-hook-form";
|
||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||||
import { FormActions } from '@/components/formActions'
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||||
import { type CardBalance } from '@/features/cardBalance/api/cardBalanceApi'
|
import { FormActions } from "@/components/formActions";
|
||||||
import { useCreateCardBalance, useUpdateCardBalance } from '@/features/cardBalance/hooks/useCardBalance'
|
import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
||||||
import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '@/features/cardBalance/schemas/cardBalance.schema'
|
import { useCreateCardBalance, useUpdateCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||||
import type { CardBalanceFormData } from '@/features/cardBalance/schemas/cardBalance.schema'
|
import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, mapInitial, buildPayload } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||||
|
import type { CardBalanceFormData } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||||
|
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||||
|
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||||
|
import { MONTH_OPTIONS, CARD_YEAR_OPTIONS } from "@/constants";
|
||||||
|
|
||||||
interface CardBalanceFormProps {
|
interface CardBalanceFormProps {
|
||||||
mode: 'create' | 'edit'
|
mode: "create" | "edit";
|
||||||
initialData?: CardBalance
|
initialData?: CardBalance;
|
||||||
}
|
}
|
||||||
|
|
||||||
type FlatErrors = Partial<Record<keyof CardBalanceFormData, string>>
|
type FlatErrors = Partial<Record<keyof CardBalanceFormData, string>>;
|
||||||
|
|
||||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||||
const result: FlatErrors = {}
|
const result: FlatErrors = {};
|
||||||
for (const key of Object.keys(errors)) {
|
for (const key of Object.keys(errors)) {
|
||||||
const msg = errors[key]?.message
|
const msg = errors[key]?.message;
|
||||||
if (msg) result[key as keyof CardBalanceFormData] = msg
|
if (msg) result[key as keyof CardBalanceFormData] = msg;
|
||||||
}
|
}
|
||||||
return result
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const PASSPORT_SERIES_OPTIONS = [
|
const STATUS_OPTIONS: SelectOption[] = [
|
||||||
{ value: 'I-MR', label: 'I-MR' },
|
{ value: "pending", label: "Garaşylýar" },
|
||||||
{ value: 'II-MR', label: 'II-MR' },
|
{ value: "approved", label: "Tassyklanan" },
|
||||||
{ value: 'I-LB', label: 'I-LB' },
|
{ value: "rejected", label: "Ret edilen" },
|
||||||
{ value: 'II-LB', label: 'II-LB' },
|
];
|
||||||
{ value: 'III-LB', label: 'III-LB' },
|
|
||||||
{ value: 'I-BN', label: 'I-BN' },
|
|
||||||
{ value: 'II-BN', label: 'II-BN' },
|
|
||||||
{ value: 'I-AH', label: 'I-AH' },
|
|
||||||
{ value: 'I-AS', label: 'I-AS' },
|
|
||||||
{ value: 'I-DZ', label: 'I-DZ' },
|
|
||||||
{ value: 'II-DZ', label: 'II-DZ' },
|
|
||||||
{ value: 'A', label: 'A' },
|
|
||||||
{ value: 'B', label: 'B' },
|
|
||||||
]
|
|
||||||
|
|
||||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
|
const CURRENCY_OPTIONS: SelectOption[] = [
|
||||||
const val = String(i + 1).padStart(2, '0')
|
{ value: "TMT", label: "TMT" },
|
||||||
return { value: val, label: val }
|
{ value: "USD", label: "USD" },
|
||||||
})
|
{ value: "RUB", label: "RUB" },
|
||||||
|
{ value: "EUR", label: "EUR" },
|
||||||
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
];
|
||||||
const year = String(new Date().getFullYear() + i)
|
|
||||||
return { value: year, label: year }
|
|
||||||
})
|
|
||||||
|
|
||||||
// ─── Component ────────────────────────────────────────────────────────────────
|
// ─── Component ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const createMutation = useCreateCardBalance()
|
const createMutation = useCreateCardBalance();
|
||||||
const updateMutation = useUpdateCardBalance(initialData?.id ?? 0)
|
const updateMutation = useUpdateCardBalance(initialData?.id ?? 0);
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
|
const [userSearch, setUserSearch] = useState("");
|
||||||
|
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||||
|
const userQuery = useInfiniteUsers(userSearch, !userLocked);
|
||||||
|
|
||||||
|
const userOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||||
|
const opts: InfiniteSelectOption[] = (userQuery.data?.pages ?? [])
|
||||||
|
.flatMap((p) => p?.users ?? [])
|
||||||
|
.map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) }))
|
||||||
|
.filter((o) => !userLocked || o.value === selfUserId);
|
||||||
|
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||||
|
opts.unshift({ value: selfUserId, label: userName });
|
||||||
|
}
|
||||||
|
if (initialData?.createdBy?.id && !opts.some((o) => o.value === String(initialData.createdBy.id))) {
|
||||||
|
opts.unshift({
|
||||||
|
value: String(initialData.createdBy.id),
|
||||||
|
label: initialData.createdBy.name || String(initialData.createdBy.id),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return opts;
|
||||||
|
}, [userQuery, initialData, userLocked, selfUserId, userName]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
watch,
|
||||||
|
setValue,
|
||||||
|
getValues,
|
||||||
|
formState: { errors: rhfErrors },
|
||||||
|
clearErrors,
|
||||||
|
setError,
|
||||||
} = useForm<CardBalanceFormData>({
|
} = useForm<CardBalanceFormData>({
|
||||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES,
|
defaultValues: initialData
|
||||||
})
|
? { ...mapInitial(initialData), ...(userLocked ? { createdBy: selfUserId } : {}) }
|
||||||
|
: { ...DEFAULT_FORM_VALUES, createdBy: selfUserId },
|
||||||
|
});
|
||||||
|
|
||||||
const form = watch()
|
const form = watch();
|
||||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||||
|
|
||||||
const setField = useCallback((field: keyof CardBalanceFormData) => (value: string) => {
|
const set = useCallback(
|
||||||
(setValue as (name: keyof CardBalanceFormData, val: string) => void)(field, value)
|
<K extends keyof CardBalanceFormData>(key: K, value: CardBalanceFormData[K]) => {
|
||||||
clearErrors(field)
|
(setValue as (name: K, val: CardBalanceFormData[K]) => void)(key, value);
|
||||||
}, [setValue, clearErrors])
|
clearErrors(key);
|
||||||
|
},
|
||||||
|
[setValue, clearErrors],
|
||||||
|
);
|
||||||
|
|
||||||
const errMsg = (msg: string | undefined) =>
|
const setString = (key: keyof CardBalanceFormData) => (value: string) => set(key, value as CardBalanceFormData[typeof key]);
|
||||||
!msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg
|
|
||||||
|
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const result = cardBalanceFormSchema.safeParse(getValues())
|
const result = cardBalanceFormSchema.safeParse(getValues());
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
for (const issue of result.error.issues) {
|
for (const issue of result.error.issues) {
|
||||||
const key = issue.path[0] as keyof CardBalanceFormData
|
const key = issue.path[0] as keyof CardBalanceFormData;
|
||||||
setError(key, { message: issue.message })
|
setError(key, { message: issue.message });
|
||||||
}
|
}
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
const payload = buildPayload(result.data)
|
const payload = buildPayload(result.data);
|
||||||
if (mode === 'create') {
|
if (mode === "create") {
|
||||||
await createMutation.mutateAsync(payload)
|
await createMutation.mutateAsync(payload);
|
||||||
navigate('/card-balances')
|
navigate("/card-balances");
|
||||||
} else {
|
} else {
|
||||||
await updateMutation.mutateAsync(payload)
|
await updateMutation.mutateAsync(payload);
|
||||||
navigate(`/card-balances/${initialData!.id}`)
|
navigate(`/card-balances/${initialData!.id}`);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleCancel = () => {
|
const handleCancel = () => {
|
||||||
if (mode === 'create') navigate('/card-balances')
|
if (mode === "create") navigate("/card-balances");
|
||||||
else navigate(`/card-balances/${initialData!.id}`)
|
else navigate(`/card-balances/${initialData!.id}`);
|
||||||
}
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === 'create'
|
{mode === "create"
|
||||||
? t('cardBalance.createTitle', 'Kart galyndysy dörediň')
|
? t("cardBalance.createTitle", "Kart galyndysy dörediň")
|
||||||
: t('cardBalance.editTitle', 'Kart galyndysy üýtgetmek')}
|
: t("cardBalance.editTitle", "Kart galyndysy üýtgetmek")}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="rounded-lg border border-border bg-card p-6">
|
<div className="rounded-lg border border-border bg-card p-6">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
{/* Row 1 */}
|
|
||||||
<FormInput
|
|
||||||
type="searchable-select"
|
|
||||||
label={t('Passport series', 'Pasport seriýasy')}
|
|
||||||
value={form.passport_series}
|
|
||||||
onChange={setField('passport_series')}
|
|
||||||
options={PASSPORT_SERIES_OPTIONS}
|
|
||||||
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
|
|
||||||
error={errMsg(errors.passport_series)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
<FormInput
|
|
||||||
type="text"
|
|
||||||
label={t('Passport number', 'Pasport belgisi')}
|
|
||||||
value={form.passport_number}
|
|
||||||
onChange={setField('passport_number')}
|
|
||||||
placeholder={t('Passport number', 'Pasport belgisi')}
|
|
||||||
error={errMsg(errors.passport_number)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Row 2 — card number full width + 2 selects */}
|
|
||||||
<FormInput
|
|
||||||
type="text"
|
|
||||||
label={t('Card number', 'Kart belgisi')}
|
|
||||||
value={form.card_number}
|
|
||||||
onChange={setField('card_number')}
|
|
||||||
placeholder={t('Card number', 'Kart belgisi')}
|
|
||||||
error={errMsg(errors.card_number)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
label={t('Card expiry month', 'Kart Möhleti (aý)')}
|
label={t("Status", "Status")}
|
||||||
value={form.card_expiry_month}
|
value={form.status}
|
||||||
onChange={setField('card_expiry_month')}
|
onChange={setString("status")}
|
||||||
options={MONTH_OPTIONS}
|
options={STATUS_OPTIONS}
|
||||||
placeholder={t('Select', 'Saýlamak üçin basyň')}
|
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||||
error={errMsg(errors.card_expiry_month)}
|
error={errMsg(errors.status)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="text"
|
||||||
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
|
label={t("Passport number", "Pasport belgisi")}
|
||||||
value={form.card_expiry_year}
|
value={form.passportNumber}
|
||||||
onChange={setField('card_expiry_year')}
|
onChange={setString("passportNumber")}
|
||||||
options={YEAR_OPTIONS}
|
placeholder="999999"
|
||||||
placeholder={t('Select', 'Saýlamak üçin basyň')}
|
error={errMsg(errors.passportNumber)}
|
||||||
error={errMsg(errors.card_expiry_year)}
|
required
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormInput
|
||||||
|
type="card-number"
|
||||||
|
label={t("Card number", "Kart belgisi")}
|
||||||
|
value={form.cardNumber}
|
||||||
|
onChange={setString("cardNumber")}
|
||||||
|
placeholder="9800 0000 0000 0000"
|
||||||
|
error={errMsg(errors.cardNumber)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<FormInput
|
||||||
|
type="select"
|
||||||
|
label={t("Card expiry month", "Kart Möhleti (aý)")}
|
||||||
|
value={form.expiryMonth}
|
||||||
|
onChange={setString("expiryMonth")}
|
||||||
|
options={MONTH_OPTIONS}
|
||||||
|
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||||
|
error={errMsg(errors.expiryMonth)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="select"
|
||||||
|
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
||||||
|
value={form.expiryYear}
|
||||||
|
onChange={setString("expiryYear")}
|
||||||
|
options={CARD_YEAR_OPTIONS}
|
||||||
|
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||||
|
error={errMsg(errors.expiryYear)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<FormInput
|
||||||
|
type="number"
|
||||||
|
label={t("Balance amount", "Galyndy möçberi")}
|
||||||
|
value={form.balanceAmount}
|
||||||
|
onChange={setString("balanceAmount")}
|
||||||
|
placeholder="0.00"
|
||||||
|
error={errMsg(errors.balanceAmount)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="searchable-select"
|
||||||
|
label={t("Balance currency", "Galyndy walýutasy")}
|
||||||
|
value={form.balanceCurrency}
|
||||||
|
onChange={setString("balanceCurrency")}
|
||||||
|
options={CURRENCY_OPTIONS}
|
||||||
|
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||||
|
error={errMsg(errors.balanceCurrency)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormInput
|
||||||
|
type="date"
|
||||||
|
label={t("Checked at", "Barlan senesi")}
|
||||||
|
value={form.checkedAt}
|
||||||
|
onChange={setString("checkedAt")}
|
||||||
|
error={errMsg(errors.checkedAt)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<InfiniteSelect
|
||||||
|
label={t("Created by", "Döreden")}
|
||||||
|
value={form.createdBy}
|
||||||
|
onChange={(v) => set("createdBy", v)}
|
||||||
|
options={userOptions}
|
||||||
|
placeholder={t("Select user", "Ulanyjyny saýlaň")}
|
||||||
|
disabled={userLocked}
|
||||||
|
loading={userQuery.isLoading}
|
||||||
|
isLoadingMore={userQuery.isFetchingNextPage}
|
||||||
|
hasNextPage={!!userQuery.hasNextPage}
|
||||||
|
onLoadMore={() => userQuery.fetchNextPage()}
|
||||||
|
searchValue={userSearch}
|
||||||
|
onSearchChange={setUserSearch}
|
||||||
|
error={errMsg(errors.createdBy)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<FormActions
|
<FormActions
|
||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
onCancel={handleCancel}
|
onCancel={handleCancel}
|
||||||
cancelVariant="ghost"
|
cancelLabel={t("Cancel", "Ýatyr")}
|
||||||
cancelLabel={t('Cancel', 'Ýatyr')}
|
loadingLabel={t("Saving...", "Saklanýar...")}
|
||||||
loadingLabel={t('Saving...', 'Saklanýar...')}
|
submitLabel={mode === "create" ? t("Create card balance", "Kart galyndysy dörediň") : t("Save changes", "Üýtgetmeleri sakla")}
|
||||||
submitLabel={mode === 'create'
|
className="mt-6"
|
||||||
? t('Create card balance', 'Kart galyndysy dörediň')
|
/>
|
||||||
: t('Save changes', 'Üýtgetmeleri sakla')}
|
</div>
|
||||||
className="mt-6"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
);
|
||||||
)
|
}
|
||||||
}
|
|
||||||
@@ -1,84 +1,80 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import { cardBalancesApi, type CardBalanceListParams, type CardBalancePayload } from "../api/cardBalanceApi";
|
||||||
cardBalancesApi,
|
|
||||||
type CardBalanceListParams,
|
|
||||||
type CreateCardBalancePayload,
|
|
||||||
type UpdateCardBalancePayload,
|
|
||||||
} from '../api/cardBalanceApi'
|
|
||||||
|
|
||||||
const QUERY_KEY = 'card-balances'
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardBalances(params?: CardBalanceListParams) {
|
export const cardBalanceKeys = {
|
||||||
|
all: ["cardBalances"] as const,
|
||||||
|
lists: () => [...cardBalanceKeys.all, "list"] as const,
|
||||||
|
list: (params: CardBalanceListParams) => [...cardBalanceKeys.lists(), params] as const,
|
||||||
|
details: () => [...cardBalanceKeys.all, "detail"] as const,
|
||||||
|
detail: (id: number) => [...cardBalanceKeys.details(), id] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useCardBalances(params: CardBalanceListParams = {}) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [QUERY_KEY, params],
|
queryKey: cardBalanceKeys.list(params),
|
||||||
queryFn: () => cardBalancesApi.getAll(params),
|
queryFn: ({ signal }) => cardBalancesApi.getList(params, signal),
|
||||||
})
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardBalance(id: number) {
|
export function useCardBalance(id: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [QUERY_KEY, id],
|
queryKey: cardBalanceKeys.detail(id),
|
||||||
queryFn: () => cardBalancesApi.getById(id),
|
queryFn: () => cardBalancesApi.getById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateCardBalance() {
|
export function useCreateCardBalance() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateCardBalancePayload) => cardBalancesApi.create(payload),
|
mutationFn: (payload: CardBalancePayload) => cardBalancesApi.create(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
|
||||||
toast.success(t('Card balance created successfully', 'Kart galyndysy üstünlikli döredildi'))
|
toast.success(t("cardBalance.createSuccess", "Kart galyndysy üstünlikli döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateCardBalance(id: number) {
|
export function useUpdateCardBalance(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateCardBalancePayload) => cardBalancesApi.update(id, payload),
|
mutationFn: (payload: CardBalancePayload) => cardBalancesApi.update(id, payload),
|
||||||
onSuccess: () => {
|
onSuccess: (updated) => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
|
||||||
toast.success(t('Card balance updated successfully', 'Kart galyndysy üstünlikli üýtgedildi'))
|
queryClient.setQueryData(cardBalanceKeys.detail(id), updated);
|
||||||
|
toast.success(t("cardBalance.updateSuccess", "Kart galyndysy üstünlikli üýtgedildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteCardBalance() {
|
export function useDeleteCardBalance() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => cardBalancesApi.delete(id),
|
mutationFn: (id: number) => cardBalancesApi.delete(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: cardBalanceKeys.lists() });
|
||||||
toast.success(t('Card balance deleted successfully', 'Kart galyndysy üstünlikli öçürildi'))
|
toast.success(t("cardBalance.deleteSuccess", "Kart galyndysy üstünlikli öçürildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDownloadCardBalance() {
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async (id: number) => {
|
|
||||||
const blob = await cardBalancesApi.download(id)
|
|
||||||
const url = URL.createObjectURL(blob)
|
|
||||||
const a = document.createElement('a')
|
|
||||||
a.href = url
|
|
||||||
a.download = `card-balance-${id}.pdf`
|
|
||||||
a.click()
|
|
||||||
URL.revokeObjectURL(url)
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,30 +1,56 @@
|
|||||||
import { z } from 'zod'
|
import { z } from "zod";
|
||||||
import type { CreateCardBalancePayload } from '../api/cardBalanceApi'
|
import type { CardBalance, CardBalancePayload } from "../api/cardBalanceApi";
|
||||||
|
|
||||||
export const cardBalanceFormSchema = z.object({
|
export const cardBalanceFormSchema = z.object({
|
||||||
passport_series: z.string().min(1, 'validation.required'),
|
status: z.string().min(1, "validation.required"),
|
||||||
passport_number: z.string().min(1, 'validation.required'),
|
passportNumber: z.string().min(1, "validation.required"),
|
||||||
card_number: z.string().min(1, 'validation.required'),
|
cardNumber: z.string().min(1, "validation.required"),
|
||||||
card_expiry_month: z.string().min(1, 'validation.required'),
|
expiryMonth: z.string().min(1, "validation.required"),
|
||||||
card_expiry_year: z.string().min(1, 'validation.required'),
|
expiryYear: z.string().min(1, "validation.required"),
|
||||||
})
|
balanceAmount: z.string().min(1, "validation.required"),
|
||||||
|
balanceCurrency: z.string().min(1, "validation.required"),
|
||||||
|
checkedAt: z.string().min(1, "validation.required"),
|
||||||
|
createdBy: z.string().min(1, "validation.required"),
|
||||||
|
});
|
||||||
|
|
||||||
export type CardBalanceFormData = z.infer<typeof cardBalanceFormSchema>
|
export type CardBalanceFormData = z.infer<typeof cardBalanceFormSchema>;
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CardBalanceFormData = {
|
export const DEFAULT_FORM_VALUES: CardBalanceFormData = {
|
||||||
passport_series: '',
|
status: "",
|
||||||
passport_number: '',
|
passportNumber: "",
|
||||||
card_number: '',
|
cardNumber: "",
|
||||||
card_expiry_month: '',
|
expiryMonth: "",
|
||||||
card_expiry_year: '',
|
expiryYear: "",
|
||||||
|
balanceAmount: "",
|
||||||
|
balanceCurrency: "",
|
||||||
|
checkedAt: "",
|
||||||
|
createdBy: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function mapInitial(data: CardBalance): CardBalanceFormData {
|
||||||
|
return {
|
||||||
|
status: data.status ?? "",
|
||||||
|
passportNumber: data.passportNumber ?? "",
|
||||||
|
cardNumber: "",
|
||||||
|
expiryMonth: data.expiryMonth != null ? String(data.expiryMonth) : "",
|
||||||
|
expiryYear: data.expiryYear != null ? String(data.expiryYear) : "",
|
||||||
|
balanceAmount: data.balanceAmount != null ? String(data.balanceAmount) : "",
|
||||||
|
balanceCurrency: data.balanceCurrency ?? "",
|
||||||
|
checkedAt: data.checkedAt ? data.checkedAt.slice(0, 10) : "",
|
||||||
|
createdBy: data.createdBy?.id != null ? String(data.createdBy.id) : "",
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildPayload(data: CardBalanceFormData): CreateCardBalancePayload {
|
export function buildPayload(data: CardBalanceFormData): CardBalancePayload {
|
||||||
return {
|
return {
|
||||||
passport_series: data.passport_series,
|
status: data.status,
|
||||||
passport_number: data.passport_number,
|
passportNumber: data.passportNumber,
|
||||||
card_number: data.card_number,
|
cardNumber: data.cardNumber,
|
||||||
card_expiry_month: data.card_expiry_month,
|
expiryMonth: Number(data.expiryMonth),
|
||||||
card_expiry_year: data.card_expiry_year,
|
expiryYear: Number(data.expiryYear),
|
||||||
}
|
balanceAmount: Number(data.balanceAmount),
|
||||||
|
balanceCurrency: data.balanceCurrency,
|
||||||
|
checkedAt: new Date(data.checkedAt).toISOString(),
|
||||||
|
createdBy: Number(data.createdBy),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -1,214 +1,116 @@
|
|||||||
import apiClient from "@/lib/api/client";
|
import apiClient from "@/lib/api/client";
|
||||||
|
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export type CardPinStatus = "pending" | "approved" | "rejected";
|
export interface CardPinOrder {
|
||||||
|
id: number;
|
||||||
export interface CardPinItem {
|
uniqueId: string;
|
||||||
id: string;
|
user: { id: number; name: string; username: string; phone: string; email: string } | null;
|
||||||
card_type: string;
|
cardType: { id: number; name: LocalizedText | string } | null;
|
||||||
card_type_label: string;
|
cardNumber: string;
|
||||||
card_number: string;
|
region: string;
|
||||||
created_at: string;
|
branch: { id: number; name: LocalizedText | string } | null;
|
||||||
province: string;
|
customerName: string;
|
||||||
province_label: string;
|
customerSurname: string;
|
||||||
branch: string;
|
customerPatronicName: string | null;
|
||||||
branch_label: string;
|
bornAt: string | null;
|
||||||
first_name: string;
|
|
||||||
last_name: string;
|
|
||||||
father_name: string;
|
|
||||||
birth_date: string;
|
|
||||||
phone: string;
|
phone: string;
|
||||||
status: CardPinStatus;
|
passportSerie: string;
|
||||||
note: string | null;
|
passportId: string;
|
||||||
passport_series: string;
|
passportOne: string | null;
|
||||||
passport_number: string;
|
passportTwo: string | null;
|
||||||
passport_file_1: string | null;
|
passportThree: string | null;
|
||||||
passport_file_2: string | null;
|
passportFour: string | null;
|
||||||
passport_file_3: string | null;
|
status: string;
|
||||||
passport_file_4: string | null;
|
notes: string | null;
|
||||||
created_by: string;
|
createdAt: string;
|
||||||
created_by_label: string;
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CardPinListResponse {
|
||||||
|
count: number;
|
||||||
|
cardPinOrders: CardPinOrder[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CardPinListParams {
|
export interface CardPinListParams {
|
||||||
page?: number;
|
page?: number;
|
||||||
per_page?: number;
|
limit?: number;
|
||||||
search?: string;
|
search?: string;
|
||||||
status?: CardPinStatus | "";
|
// ─── Filter params ──────────────────────────────────────────────────────────
|
||||||
province?: string;
|
status?: string;
|
||||||
|
branch_id?: string;
|
||||||
|
user_id?: string;
|
||||||
|
card_type_id?: string;
|
||||||
|
region?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CardPinListResponse {
|
export interface CreateCardPinPayload {
|
||||||
data: CardPinItem[];
|
bornAt: string;
|
||||||
meta: {
|
branchId: number;
|
||||||
current_page: number;
|
cardNumber: string;
|
||||||
last_page: number;
|
cardTypeId: number;
|
||||||
per_page: number;
|
customerName: string;
|
||||||
total: number;
|
customerPatronicName: string;
|
||||||
};
|
customerSurname: string;
|
||||||
}
|
notes: string;
|
||||||
|
passportFour: string;
|
||||||
export interface CardPinCreatePayload {
|
passportId: string;
|
||||||
status: CardPinStatus;
|
passportOne: string;
|
||||||
note: string;
|
passportSerie: string;
|
||||||
card_type: string;
|
passportThree: string;
|
||||||
card_number: string;
|
passportTwo: string;
|
||||||
province: string;
|
|
||||||
branch: string;
|
|
||||||
first_name: string;
|
|
||||||
last_name: string;
|
|
||||||
father_name: string;
|
|
||||||
birth_date: string;
|
|
||||||
phone: string;
|
phone: string;
|
||||||
passport_series: string;
|
region: string;
|
||||||
passport_number: string;
|
status: string;
|
||||||
passport_file_1: File | null;
|
uniqueId: string;
|
||||||
passport_file_2: File | null;
|
userId: number;
|
||||||
passport_file_3: File | null;
|
|
||||||
passport_file_4: File | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CardPinUpdatePayload = CardPinCreatePayload;
|
export type UpdateCardPinPayload = CreateCardPinPayload;
|
||||||
|
|
||||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const MOCK_CARD_PINS: CardPinItem[] = [
|
|
||||||
{
|
|
||||||
id: "1",
|
|
||||||
card_type: "altyn_asyr",
|
|
||||||
card_type_label: "Altyn Asyr",
|
|
||||||
card_number: "8600123456789012",
|
|
||||||
created_at: "2024-05-07 10:00",
|
|
||||||
province: "ashgabat",
|
|
||||||
province_label: "Aşgabat",
|
|
||||||
branch: "1",
|
|
||||||
branch_label: "Merkezi şahamça",
|
|
||||||
first_name: "Aman",
|
|
||||||
last_name: "Amanow",
|
|
||||||
father_name: "Amanowiç",
|
|
||||||
birth_date: "1990-01-01",
|
|
||||||
phone: "99365123456",
|
|
||||||
status: "pending",
|
|
||||||
note: "Test bellik",
|
|
||||||
passport_series: "I-MR",
|
|
||||||
passport_number: "123456",
|
|
||||||
passport_file_1: null,
|
|
||||||
passport_file_2: null,
|
|
||||||
passport_file_3: null,
|
|
||||||
passport_file_4: null,
|
|
||||||
created_by: "1",
|
|
||||||
created_by_label: "Admin",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "2",
|
|
||||||
card_type: "visa",
|
|
||||||
card_type_label: "Visa",
|
|
||||||
card_number: "4400123456789012",
|
|
||||||
created_at: "2024-05-07 11:30",
|
|
||||||
province: "mary",
|
|
||||||
province_label: "Mary",
|
|
||||||
branch: "2",
|
|
||||||
branch_label: "Mary şahamçasy",
|
|
||||||
first_name: "Berdi",
|
|
||||||
last_name: "Berdiyew",
|
|
||||||
father_name: "Berdiyewiç",
|
|
||||||
birth_date: "1995-05-05",
|
|
||||||
phone: "99361112233",
|
|
||||||
status: "approved",
|
|
||||||
note: null,
|
|
||||||
passport_series: "I-LB",
|
|
||||||
passport_number: "654321",
|
|
||||||
passport_file_1: null,
|
|
||||||
passport_file_2: null,
|
|
||||||
passport_file_3: null,
|
|
||||||
passport_file_4: null,
|
|
||||||
created_by: "1",
|
|
||||||
created_by_label: "Admin",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export const cardPinApi = {
|
export const cardPinApi = {
|
||||||
list: async (params: CardPinListParams): Promise<CardPinListResponse> => {
|
/** GET /card-pin-orders */
|
||||||
// Mock data return
|
list: async (params: CardPinListParams = {}, signal?: AbortSignal): Promise<CardPinListResponse> => {
|
||||||
return {
|
const { page, limit, search, status, branch_id, user_id, card_type_id, region } = params;
|
||||||
data: MOCK_CARD_PINS,
|
const { data } = await apiClient.get<CardPinListResponse>("/card-pin-orders", {
|
||||||
meta: {
|
params: {
|
||||||
current_page: params.page || 1,
|
page,
|
||||||
last_page: 1,
|
limit,
|
||||||
per_page: params.per_page || 25,
|
search: search || undefined,
|
||||||
total: MOCK_CARD_PINS.length,
|
status: status || undefined,
|
||||||
|
branch_id: branch_id || undefined,
|
||||||
|
user_id: user_id || undefined,
|
||||||
|
card_type_id: card_type_id || undefined,
|
||||||
|
region: region || undefined,
|
||||||
},
|
},
|
||||||
};
|
signal,
|
||||||
|
});
|
||||||
const { data } = await apiClient.get("/card-pins", { params });
|
|
||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
getById: async (id: string): Promise<CardPinItem> => {
|
/** GET /card-pin-orders/:id */
|
||||||
const mock = MOCK_CARD_PINS.find((p) => p.id === id);
|
getById: async (id: number): Promise<CardPinOrder> => {
|
||||||
if (mock) return mock;
|
const { data } = await apiClient.get<CardPinOrder>(`/card-pin-orders/${id}`);
|
||||||
|
|
||||||
const { data } = await apiClient.get(`/card-pins/${id}`);
|
|
||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
create: (payload: CardPinCreatePayload): Promise<CardPinItem> => {
|
/** POST /card-pin-orders */
|
||||||
const form = buildFormData(payload);
|
create: async (payload: CreateCardPinPayload): Promise<CardPinOrder> => {
|
||||||
return apiClient
|
const { data } = await apiClient.post<CardPinOrder>("/card-pin-orders", payload);
|
||||||
.post("/card-pins", form, {
|
return data;
|
||||||
headers: { "Content-Type": "multipart/form-data" },
|
|
||||||
})
|
|
||||||
.then((r) => r.data);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
update: (id: string, payload: CardPinUpdatePayload): Promise<CardPinItem> => {
|
/** PUT /card-pin-orders/:id */
|
||||||
const form = buildFormData(payload);
|
update: async (id: number, payload: UpdateCardPinPayload): Promise<CardPinOrder> => {
|
||||||
form.append("_method", "PUT");
|
const { data } = await apiClient.put<CardPinOrder>(`/card-pin-orders/${id}`, payload);
|
||||||
return apiClient
|
return data;
|
||||||
.post(`/card-pins/${id}`, form, {
|
|
||||||
headers: { "Content-Type": "multipart/form-data" },
|
|
||||||
})
|
|
||||||
.then((r) => r.data);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
delete: (id: string): Promise<void> => apiClient.delete(`/card-pins/${id}`).then((r) => r.data),
|
/** DELETE /card-pin-orders/:id */
|
||||||
|
delete: async (id: number): Promise<void> => {
|
||||||
|
await apiClient.delete(`/card-pin-orders/${id}`);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function buildFormData(payload: CardPinCreatePayload): FormData {
|
|
||||||
const form = new FormData();
|
|
||||||
|
|
||||||
const textFields: (keyof CardPinCreatePayload)[] = [
|
|
||||||
"status",
|
|
||||||
"note",
|
|
||||||
"card_type",
|
|
||||||
"card_number",
|
|
||||||
"province",
|
|
||||||
"branch",
|
|
||||||
"first_name",
|
|
||||||
"last_name",
|
|
||||||
"father_name",
|
|
||||||
"birth_date",
|
|
||||||
"phone",
|
|
||||||
"passport_series",
|
|
||||||
"passport_number",
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const key of textFields) {
|
|
||||||
const val = payload[key];
|
|
||||||
if (val !== null && val !== undefined) {
|
|
||||||
form.append(key, String(val));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const fileFields: (keyof CardPinCreatePayload)[] = ["passport_file_1", "passport_file_2", "passport_file_3", "passport_file_4"];
|
|
||||||
|
|
||||||
for (const key of fileFields) {
|
|
||||||
const file = payload[key];
|
|
||||||
if (file instanceof File) form.append(key, file);
|
|
||||||
}
|
|
||||||
|
|
||||||
return form;
|
|
||||||
}
|
|
||||||
@@ -1,124 +1,114 @@
|
|||||||
import { useState, useCallback, useMemo } from 'react'
|
import { useState, useCallback, useMemo } from "react";
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import type { TFunction } from 'i18next'
|
import type { TFunction } from "i18next";
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from "react-hook-form";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { CreditCard, User, FileText } from 'lucide-react'
|
import { CreditCard, User, FileText } from "lucide-react";
|
||||||
import type { LucideIcon } from 'lucide-react'
|
import type { LucideIcon } from "lucide-react";
|
||||||
|
|
||||||
import { FormInput } from '@/components/formInput'
|
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||||
import { FormActions } from '@/components/formActions'
|
import { FormActions } from "@/components/formActions";
|
||||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||||
import { BentoGrid, BentoCard } from '@/components/bento'
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import type { CardPinItem, CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi'
|
import type { CardPinOrder, CreateCardPinPayload } from "@/features/cardPins/api/cardPinApi";
|
||||||
import { useCreateCardPin, useUpdateCardPin } from '@/features/cardPins/hooks/useCardPins'
|
import { useCreateCardPin, useUpdateCardPin } from "@/features/cardPins/hooks/useCardPins";
|
||||||
import { validateStep, DEFAULT_FORM_VALUES } from '@/features/cardPins/schemas/cardPin.schema'
|
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/cardPins/schemas/cardPin.schema";
|
||||||
import type { CardPinFormData } from '@/features/cardPins/schemas/cardPin.schema'
|
import type { CardPinFormData } from "@/features/cardPins/schemas/cardPin.schema";
|
||||||
|
import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||||
|
import { resolveCardTypeTitle } from "@/features/cardTypes/api/cardTypesApi";
|
||||||
|
import { useBranches } from "@/features/branches/hooks/useBranches";
|
||||||
|
import { resolveLocalizedName } from "@/features/branches/api/branchesApi";
|
||||||
|
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
||||||
|
import { resolveDistrictName } from "@/features/districts/api/districtsApi";
|
||||||
|
import { PASSPORT_SERIES_OPTIONS, getStatusOptions } from "@/constants";
|
||||||
|
import { DocumentUpload } from "@/components/documentUpload";
|
||||||
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||||
|
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||||
|
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||||
|
import { formatFromApiPhone } from "@/lib/utils";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
interface CardPinFormProps {
|
interface CardPinFormProps {
|
||||||
mode: 'create' | 'edit'
|
mode: "create" | "edit";
|
||||||
initialData?: CardPinItem
|
initialData?: CardPinOrder;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const CARD_TYPE_OPTIONS = [
|
|
||||||
{ value: 'altyn_asyr', label: 'Altyn Asyr' },
|
|
||||||
{ value: 'visa', label: 'Visa' },
|
|
||||||
{ value: 'mastercard', label: 'MasterCard' },
|
|
||||||
]
|
|
||||||
|
|
||||||
const PASSPORT_SERIES_OPTIONS = [
|
|
||||||
{ value: 'I', label: 'I' },
|
|
||||||
{ value: 'II', label: 'II' },
|
|
||||||
{ value: 'I-MR', label: 'I-MR' },
|
|
||||||
{ value: 'II-MR', label: 'II-MR' },
|
|
||||||
]
|
|
||||||
|
|
||||||
const PROVINCE_OPTIONS = [
|
|
||||||
{ value: 'ashgabat', label: 'Aşgabat' },
|
|
||||||
{ value: 'mary', label: 'Mary' },
|
|
||||||
{ value: 'dasoguz', label: 'Daşoguz' },
|
|
||||||
{ value: 'lebap', label: 'Lebap' },
|
|
||||||
{ value: 'balkan', label: 'Balkan' },
|
|
||||||
{ value: 'ahal', label: 'Ahal' },
|
|
||||||
]
|
|
||||||
|
|
||||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
type FlatErrors = Partial<Record<keyof CardPinFormData, string>>
|
type FlatErrors = Partial<Record<keyof CardPinFormData, string>>;
|
||||||
|
|
||||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||||
const result: FlatErrors = {}
|
const result: FlatErrors = {};
|
||||||
for (const key of Object.keys(errors)) {
|
for (const key of Object.keys(errors)) {
|
||||||
const msg = errors[key]?.message
|
const msg = errors[key]?.message;
|
||||||
if (msg) result[key as keyof CardPinFormData] = msg
|
if (msg) result[key as keyof CardPinFormData] = msg;
|
||||||
}
|
}
|
||||||
return result
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
interface StepDef {
|
interface StepDef {
|
||||||
id: string
|
id: string;
|
||||||
titleKey: string
|
titleKey: string;
|
||||||
titleFallback: string
|
titleFallback: string;
|
||||||
subtitleKey: string
|
subtitleKey: string;
|
||||||
subtitleFallback: string
|
subtitleFallback: string;
|
||||||
icon: LucideIcon
|
icon: LucideIcon;
|
||||||
validate: (form: CardPinFormData, mode: 'create' | 'edit') => FlatErrors
|
validate: (form: CardPinFormData) => FlatErrors;
|
||||||
}
|
}
|
||||||
|
|
||||||
const STEPS: StepDef[] = [
|
const STEPS: StepDef[] = [
|
||||||
{
|
{
|
||||||
id: 'card',
|
id: "card",
|
||||||
titleKey: 'cardPin.step.card',
|
titleKey: "cardPin.step.card",
|
||||||
titleFallback: 'Kart',
|
titleFallback: "Kart",
|
||||||
subtitleKey: 'cardPinForm.steps.card.subtitle',
|
subtitleKey: "cardPinForm.steps.card.subtitle",
|
||||||
subtitleFallback: 'Görnüş & lokasiýa',
|
subtitleFallback: "Görnüş & lokasiýa",
|
||||||
icon: CreditCard,
|
icon: CreditCard,
|
||||||
validate: (form, mode) => validateStep(0, form, mode),
|
validate: (form) => validateStep(0, form),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'personal',
|
id: "personal",
|
||||||
titleKey: 'cardPin.step.personal',
|
titleKey: "cardPin.step.personal",
|
||||||
titleFallback: 'Şahsy',
|
titleFallback: "Şahsy",
|
||||||
subtitleKey: 'cardPinForm.steps.personal.subtitle',
|
subtitleKey: "cardPinForm.steps.personal.subtitle",
|
||||||
subtitleFallback: 'Maglumatlar',
|
subtitleFallback: "Maglumatlar",
|
||||||
icon: User,
|
icon: User,
|
||||||
validate: (form, mode) => validateStep(1, form, mode),
|
validate: (form) => validateStep(1, form),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'passport',
|
id: "passport",
|
||||||
titleKey: 'cardPin.step.passport',
|
titleKey: "cardPin.step.passport",
|
||||||
titleFallback: 'Pasport',
|
titleFallback: "Pasport",
|
||||||
subtitleKey: 'cardPinForm.steps.passport.subtitle',
|
subtitleKey: "cardPinForm.steps.passport.subtitle",
|
||||||
subtitleFallback: 'Resminamalar',
|
subtitleFallback: "Resminamalar",
|
||||||
icon: FileText,
|
icon: FileText,
|
||||||
validate: (form, mode) => validateStep(2, form, mode),
|
validate: (form) => validateStep(2, form),
|
||||||
},
|
},
|
||||||
]
|
];
|
||||||
|
|
||||||
// ─── Shared step content props ────────────────────────────────────────────────
|
// ─── Shared step content props ────────────────────────────────────────────────
|
||||||
|
|
||||||
interface StepContentProps {
|
interface StepContentProps {
|
||||||
form: CardPinFormData
|
form: CardPinFormData;
|
||||||
errors: FlatErrors
|
errors: FlatErrors;
|
||||||
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void
|
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void;
|
||||||
t: TFunction
|
t: TFunction;
|
||||||
|
cardTypeOptions: SelectOption[];
|
||||||
|
branchOptions: SelectOption[];
|
||||||
|
districtOptions: SelectOption[];
|
||||||
|
userLocked: boolean;
|
||||||
|
selfUserId: string;
|
||||||
|
userName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function StepCard({ form, errors, set, t }: StepContentProps) {
|
function StepCard({ form, errors, set, t, cardTypeOptions, branchOptions, districtOptions }: StepContentProps) {
|
||||||
const STATUS_OPTIONS = useMemo(() => [
|
const statusOptions = useMemo(() => getStatusOptions(t, "cardPin.status"), [t]);
|
||||||
{ value: 'pending', label: t('cardPin.status.pending', 'Garaşylýar') },
|
|
||||||
{ value: 'approved', label: t('cardPin.status.approved', 'Tassyklandy') },
|
|
||||||
{ value: 'rejected', label: t('cardPin.status.rejected', 'Ret edildi') },
|
|
||||||
], [t])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -126,390 +116,449 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
|
|||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
label={t('loanOrderForm.labels.status') || 'Status'}
|
label={t("cardPin.field.status", "Statusy")}
|
||||||
required
|
required
|
||||||
value={form.status}
|
value={form.status}
|
||||||
onChange={(v) => set('status', v)}
|
onChange={(v) => set("status", v)}
|
||||||
options={STATUS_OPTIONS}
|
options={statusOptions}
|
||||||
error={errors.status}
|
error={errors.status}
|
||||||
placeholder={t('loanOrderForm.placeholders.select') || 'Saýlaň'}
|
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t('Note') || 'Bellik'}
|
label={t("cardPin.field.uniqueId", "Sargyt belgisi")}
|
||||||
value={form.note}
|
required
|
||||||
onChange={(v) => set('note', v)}
|
value={form.uniqueId}
|
||||||
placeholder={t('loanOrderForm.placeholders.note') || 'Bellik...'}
|
onChange={(v) => set("uniqueId", v)}
|
||||||
|
placeholder={t("cardPin.field.uniqueId", "Sargyt belgisi")}
|
||||||
|
error={errors.uniqueId}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard title={t('loanOrderForm.titles.cardInfo') || 'Kart maglumatlary'}>
|
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="searchable-select"
|
type="card-number"
|
||||||
label={t('Loan type') || 'Kart görnüşi'}
|
label={t("cardPin.field.cardNumber", "Kart belgisi")}
|
||||||
required
|
required
|
||||||
value={form.card_type}
|
value={form.cardNumber}
|
||||||
onChange={(v) => set('card_type', v)}
|
onChange={(v) => set("cardNumber", v)}
|
||||||
options={CARD_TYPE_OPTIONS}
|
placeholder="9999 9999 9999 9999"
|
||||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
error={errors.cardNumber}
|
||||||
error={errors.card_type}
|
|
||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="searchable-select"
|
||||||
label={t('Card number') || 'Kart belgisi'}
|
label={t("cardPin.field.cardTypeId", "Kart görnüşi")}
|
||||||
required
|
required
|
||||||
value={form.card_number}
|
value={form.cardTypeId}
|
||||||
onChange={(v) => set('card_number', v)}
|
onChange={(v) => set("cardTypeId", v)}
|
||||||
placeholder={t('Card number') || 'Kart belgisi'}
|
options={cardTypeOptions}
|
||||||
error={errors.card_number}
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||||
|
error={errors.cardTypeId}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title={t('cardPinForm.titles.location') || 'Lokasiýa'}>
|
<BentoCard title={t("cardPinForm.titles.location") || "Lokasiýa"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="searchable-select"
|
type="searchable-select"
|
||||||
label={t('Region') || 'Welaýat'}
|
label={t("cardPin.field.region", "Sebit")}
|
||||||
required
|
required
|
||||||
value={form.province}
|
value={form.region}
|
||||||
onChange={(v) => { set('province', v); set('branch', '') }}
|
onChange={(v) => set("region", v)}
|
||||||
options={PROVINCE_OPTIONS}
|
options={districtOptions}
|
||||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||||
error={errors.province}
|
error={errors.region}
|
||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="searchable-select"
|
type="searchable-select"
|
||||||
label={t('Branch') || 'Şahamça'}
|
label={t("cardPin.field.branchId", "Şahamça")}
|
||||||
required
|
required
|
||||||
value={form.branch}
|
value={form.branchId}
|
||||||
onChange={(v) => set('branch', v)}
|
onChange={(v) => set("branchId", v)}
|
||||||
options={[]}
|
options={branchOptions}
|
||||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||||
disabled={!form.province}
|
error={errors.branchId}
|
||||||
error={errors.branch}
|
/>
|
||||||
|
</BentoCard>
|
||||||
|
</BentoGrid>
|
||||||
|
|
||||||
|
<BentoGrid cols={1}>
|
||||||
|
<BentoCard>
|
||||||
|
<FormInput
|
||||||
|
type="textarea"
|
||||||
|
label={t("cardPin.field.notes", "Bellikler")}
|
||||||
|
value={form.notes}
|
||||||
|
onChange={(v) => set("notes", v)}
|
||||||
|
placeholder={t("cardPin.field.notes", "Bellikler")}
|
||||||
|
error={errors.notes}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
function StepPersonal({
|
||||||
|
form,
|
||||||
|
errors,
|
||||||
|
set,
|
||||||
|
t,
|
||||||
|
initialData,
|
||||||
|
userLocked,
|
||||||
|
selfUserId,
|
||||||
|
userName,
|
||||||
|
}: StepContentProps & { initialData?: CardPinOrder }) {
|
||||||
|
const [clientSearch, setClientSearch] = useState("");
|
||||||
|
const clientsQuery = useInfiniteClients(clientSearch, !userLocked);
|
||||||
|
|
||||||
|
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||||
|
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
||||||
|
.flatMap((p) => p?.users ?? [])
|
||||||
|
.map((u) => ({
|
||||||
|
value: String(u.id),
|
||||||
|
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||||
|
}))
|
||||||
|
.filter((o) => !userLocked || o.value === selfUserId);
|
||||||
|
|
||||||
|
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||||
|
opts.unshift({ value: selfUserId, label: userName });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (initialData?.user?.id && !opts.some((o) => o.value === String(initialData.user!.id))) {
|
||||||
|
opts.unshift({ value: String(initialData.user!.id), label: initialData.user!.name || String(initialData.user!.id) });
|
||||||
|
}
|
||||||
|
return opts;
|
||||||
|
}, [clientsQuery.data, initialData, userLocked, selfUserId, userName]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<BentoGrid cols={3}>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
|
||||||
type="text" label={t('Name') || 'Ady'} required
|
|
||||||
value={form.first_name} onChange={(v) => set('first_name', v)}
|
|
||||||
placeholder={t('Name') || 'Ady'} error={errors.first_name}
|
|
||||||
/>
|
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
|
||||||
type="text" label={t('Surname') || 'Familiýasy'} required
|
|
||||||
value={form.last_name} onChange={(v) => set('last_name', v)}
|
|
||||||
placeholder={t('Surname') || 'Familiýasy'} error={errors.last_name}
|
|
||||||
/>
|
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
|
||||||
type="text" label={t('Patronic name') || 'Atasynyň ady'}
|
|
||||||
value={form.father_name} onChange={(v) => set('father_name', v)}
|
|
||||||
placeholder={t('Patronic name') || 'Atasynyň ady'}
|
|
||||||
/>
|
|
||||||
</BentoCard>
|
|
||||||
</BentoGrid>
|
|
||||||
|
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
<BentoCard title={t("cardPin.titles.name") || "Ady we familiýasy"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="date" label={t('Date of birth') || 'Doglan güni'} required
|
type="text"
|
||||||
value={form.birth_date} onChange={(v) => set('birth_date', v)}
|
label={t("cardPin.field.customerName", "Ady")}
|
||||||
error={errors.birth_date}
|
required
|
||||||
|
value={form.customerName}
|
||||||
|
onChange={(v) => set("customerName", v)}
|
||||||
|
placeholder={t("cardPin.field.customerName", "Ady")}
|
||||||
|
error={errors.customerName}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||||
|
required
|
||||||
|
value={form.customerSurname}
|
||||||
|
onChange={(v) => set("customerSurname", v)}
|
||||||
|
placeholder={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||||
|
error={errors.customerSurname}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||||
|
value={form.customerPatronicName}
|
||||||
|
onChange={(v) => set("customerPatronicName", v)}
|
||||||
|
placeholder={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
|
||||||
|
<BentoCard title={t("cardPin.titles.contactInfo") || "Şahsy we habarlaşmak"}>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="phone" label={t('Phone') || 'Telefon'} required
|
type="date"
|
||||||
value={form.phone} onChange={(v) => set('phone', v)}
|
label={t("cardPin.field.bornAt", "Doglan güni")}
|
||||||
|
value={form.bornAt}
|
||||||
|
onChange={(v) => set("bornAt", v)}
|
||||||
|
error={errors.bornAt}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="phone"
|
||||||
|
label={t("cardPin.field.phone", "Telefon")}
|
||||||
|
required
|
||||||
|
value={form.phone}
|
||||||
|
onChange={(v) => set("phone", v)}
|
||||||
|
placeholder={t("loanOrderForm.placeholders.phone") || "61 097651"}
|
||||||
error={errors.phone}
|
error={errors.phone}
|
||||||
/>
|
/>
|
||||||
|
<InfiniteSelect
|
||||||
|
label={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||||
|
required
|
||||||
|
value={form.userId}
|
||||||
|
onChange={(v) => set("userId", v)}
|
||||||
|
options={clientOptions}
|
||||||
|
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||||
|
error={errors.userId}
|
||||||
|
disabled={userLocked}
|
||||||
|
loading={clientsQuery.isLoading}
|
||||||
|
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||||
|
hasNextPage={!!clientsQuery.hasNextPage}
|
||||||
|
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||||
|
searchValue={clientSearch}
|
||||||
|
onSearchChange={setClientSearch}
|
||||||
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function StepPassport({ form, errors, set, t, mode, initialData }: StepContentProps & {
|
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||||
mode: 'create' | 'edit'
|
|
||||||
initialData?: CardPinItem
|
|
||||||
}) {
|
|
||||||
const existingFiles =
|
|
||||||
mode === 'edit' && initialData
|
|
||||||
? [
|
|
||||||
{ url: initialData.passport_file_1, label: t('Passport (page 1)') || 'Pasport (sahypa 1)' },
|
|
||||||
{ url: initialData.passport_file_2, label: t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)' },
|
|
||||||
{ url: initialData.passport_file_3, label: t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)' },
|
|
||||||
{ url: initialData.passport_file_4, label: t('Passport (page 32)') || 'Pasport (32-nji sahypa)' },
|
|
||||||
].filter((f): f is { url: string; label: string } => !!f.url)
|
|
||||||
: []
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={1}>
|
||||||
<BentoCard>
|
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Pasport maglumatlary"}>
|
||||||
<FormInput
|
<div className="grid grid-cols-2 gap-4">
|
||||||
type="searchable-select"
|
<FormInput
|
||||||
label={t('Passport serie') || 'Pasport seriýasy'}
|
type="select"
|
||||||
required
|
label={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||||
value={form.passport_series}
|
required
|
||||||
onChange={(v) => set('passport_series', v)}
|
value={form.passportSerie}
|
||||||
options={PASSPORT_SERIES_OPTIONS}
|
onChange={(v) => set("passportSerie", v)}
|
||||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
options={PASSPORT_SERIES_OPTIONS}
|
||||||
error={errors.passport_series}
|
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||||
/>
|
error={errors.passportSerie}
|
||||||
</BentoCard>
|
/>
|
||||||
<BentoCard>
|
<FormInput
|
||||||
<FormInput
|
type="passport-id"
|
||||||
type="text"
|
label={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||||
label={t('Passport id') || 'Pasport belgisi'}
|
required
|
||||||
required
|
value={form.passportId}
|
||||||
value={form.passport_number}
|
onChange={(v) => set("passportId", v)}
|
||||||
onChange={(v) => set('passport_number', v)}
|
placeholder="999999"
|
||||||
placeholder={t('Passport id') || 'Pasport belgisi'}
|
error={errors.passportId}
|
||||||
error={errors.passport_number}
|
/>
|
||||||
/>
|
</div>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
{existingFiles.length > 0 && (
|
|
||||||
<BentoGrid cols={4}>
|
|
||||||
{existingFiles.map(({ url, label }) => (
|
|
||||||
<BentoCard key={label} title={label}>
|
|
||||||
<a
|
|
||||||
href={url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="text-xs text-primary underline truncate block"
|
|
||||||
>
|
|
||||||
{t('loanOrderForm.fileLabels.viewFile') || 'Faýly gör'}
|
|
||||||
</a>
|
|
||||||
</BentoCard>
|
|
||||||
))}
|
|
||||||
</BentoGrid>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="file"
|
label={t("cardPin.field.passportOne", "Pasport (sahypa 1)")}
|
||||||
label={mode === 'edit' ? (t('loanOrderForm.fileLabels.replacePage1') || 'Pasport (sahypa 1) (çalyşmak)') : (t('Passport (page 1)') || 'Pasport (sahypa 1)')}
|
value={form.passportOne}
|
||||||
required={mode === 'create'}
|
onChange={(v) => set("passportOne", v)}
|
||||||
accept="image/*,.pdf"
|
error={errors.passportOne}
|
||||||
fileValue={form.passport_file_1}
|
accept="image/*"
|
||||||
onFileChange={(f) => set('passport_file_1', f)}
|
|
||||||
error={errors.passport_file_1}
|
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="file"
|
label={t("cardPin.field.passportTwo", "Pasport (2-3-nji sahypa)")}
|
||||||
label={mode === 'edit' ? (t('loanOrderForm.fileLabels.replacePage23') || 'Pasport (2-3-nji sahypa) (çalyşmak)') : (t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)')}
|
value={form.passportTwo}
|
||||||
required={mode === 'create'}
|
onChange={(v) => set("passportTwo", v)}
|
||||||
accept="image/*,.pdf"
|
error={errors.passportTwo}
|
||||||
fileValue={form.passport_file_2}
|
accept="image/*"
|
||||||
onFileChange={(f) => set('passport_file_2', f)}
|
|
||||||
error={errors.passport_file_2}
|
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="file"
|
label={t("cardPin.field.passportThree", "Pasport (8-9 sahypa)")}
|
||||||
label={t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)'}
|
value={form.passportThree}
|
||||||
required={mode === 'create'}
|
onChange={(v) => set("passportThree", v)}
|
||||||
accept="image/*,.pdf"
|
error={errors.passportThree}
|
||||||
fileValue={form.passport_file_3}
|
accept="image/*"
|
||||||
onFileChange={(f) => set('passport_file_3', f)}
|
|
||||||
error={errors.passport_file_3}
|
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<DocumentUpload
|
||||||
type="file"
|
label={t("cardPin.field.passportFour", "Pasport (32-nji sahypa)")}
|
||||||
label={t('Passport (page 32)') || 'Pasport (32-nji sahypa)'}
|
value={form.passportFour}
|
||||||
required={mode === 'create'}
|
onChange={(v) => set("passportFour", v)}
|
||||||
accept="image/*,.pdf"
|
error={errors.passportFour}
|
||||||
fileValue={form.passport_file_4}
|
accept="image/*"
|
||||||
onFileChange={(f) => set('passport_file_4', f)}
|
|
||||||
error={errors.passport_file_4}
|
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||||
const { t, i18n } = useTranslation()
|
const { t, i18n } = useTranslation();
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate();
|
||||||
const createMutation = useCreateCardPin()
|
|
||||||
const updateMutation = useUpdateCardPin(initialData?.id ?? '')
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending
|
|
||||||
|
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||||
|
|
||||||
|
const createMutation = useCreateCardPin();
|
||||||
|
const updateMutation = useUpdateCardPin(initialData?.id ?? 0);
|
||||||
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
|
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
||||||
|
const { data: branchesData } = useBranches({ page: 1, limit: 25 });
|
||||||
|
const { data: districtsData } = useDistricts({ page: 1, limit: 25 });
|
||||||
|
|
||||||
|
const cardTypeOptions = useMemo(
|
||||||
|
() =>
|
||||||
|
(cardTypesData?.paymentCards ?? []).map((ct) => ({
|
||||||
|
value: String(ct.id),
|
||||||
|
label: resolveCardTypeTitle(ct.title, lang),
|
||||||
|
})),
|
||||||
|
[cardTypesData, lang],
|
||||||
|
);
|
||||||
|
|
||||||
|
const branchOptions = useMemo(
|
||||||
|
() =>
|
||||||
|
(branchesData?.branches ?? []).map((b) => ({
|
||||||
|
value: String(b.id),
|
||||||
|
label: resolveLocalizedName(b.name, lang),
|
||||||
|
})),
|
||||||
|
[branchesData, lang],
|
||||||
|
);
|
||||||
|
|
||||||
|
const districtOptions = useMemo(
|
||||||
|
() =>
|
||||||
|
(districtsData?.provinces ?? []).map((d) => ({
|
||||||
|
value: resolveDistrictName(d.region, "tm") || resolveDistrictName(d.name, "tm"),
|
||||||
|
label: resolveDistrictName(d.name, lang),
|
||||||
|
})),
|
||||||
|
[districtsData, lang],
|
||||||
|
);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
watch,
|
||||||
|
setValue,
|
||||||
|
getValues,
|
||||||
|
formState: { errors: rhfErrors },
|
||||||
|
clearErrors,
|
||||||
|
setError,
|
||||||
} = useForm<CardPinFormData>({
|
} = useForm<CardPinFormData>({
|
||||||
defaultValues: initialData
|
defaultValues: initialData
|
||||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData), ...(userLocked ? { userId: selfUserId } : {}) }
|
||||||
: DEFAULT_FORM_VALUES,
|
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||||
})
|
});
|
||||||
|
|
||||||
const form = watch()
|
const form = watch();
|
||||||
const [currentStep, setCurrentStep] = useState(0)
|
const [currentStep, setCurrentStep] = useState(0);
|
||||||
const [visited, setVisited] = useState<Set<number>>(
|
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set());
|
||||||
)
|
|
||||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set())
|
|
||||||
|
|
||||||
// ── Computed step errors ───────────────────────────────────────────────────
|
// ── Computed step errors ───────────────────────────────────────────────────
|
||||||
|
|
||||||
const stepsWithErrors = useMemo(() => {
|
const stepsWithErrors = useMemo(() => {
|
||||||
const out = new Set<number>()
|
const out = new Set<number>();
|
||||||
visited.forEach((i) => {
|
visited.forEach((i) => {
|
||||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i)
|
if (Object.keys(STEPS[i].validate(form)).length > 0) out.add(i);
|
||||||
})
|
});
|
||||||
return out
|
return out;
|
||||||
}, [form, mode, visited, i18n.language])
|
}, [form, mode, visited, i18n.language]);
|
||||||
|
|
||||||
// ── set helper ─────────────────────────────────────────────────────────────
|
// ── set helper ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const set = useCallback(<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
const set = useCallback(
|
||||||
(setValue as (name: K, val: CardPinFormData[K]) => void)(key, value)
|
<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
||||||
clearErrors(key)
|
(setValue as (name: K, val: CardPinFormData[K]) => void)(key, value);
|
||||||
}, [setValue, clearErrors])
|
clearErrors(key);
|
||||||
|
},
|
||||||
|
[setValue, clearErrors],
|
||||||
|
);
|
||||||
|
|
||||||
const allSubmittedErrors = useMemo(() => {
|
const allSubmittedErrors = useMemo(() => {
|
||||||
const result: FlatErrors = {}
|
const result: FlatErrors = {};
|
||||||
for (const stepIdx of submittedSteps) {
|
for (const stepIdx of submittedSteps) {
|
||||||
Object.assign(result, STEPS[stepIdx].validate(form, mode))
|
Object.assign(result, STEPS[stepIdx].validate(form));
|
||||||
}
|
}
|
||||||
return result
|
return result;
|
||||||
}, [form, mode, submittedSteps, i18n.language])
|
}, [form, mode, submittedSteps, i18n.language]);
|
||||||
const errors = useMemo(() => {
|
const errors = useMemo(() => {
|
||||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>)
|
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||||
return { ...fromRHF, ...allSubmittedErrors }
|
return { ...fromRHF, ...allSubmittedErrors };
|
||||||
}, [rhfErrors, allSubmittedErrors])
|
}, [rhfErrors, allSubmittedErrors]);
|
||||||
|
|
||||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t])
|
const stepProps = useMemo(
|
||||||
|
() => ({ form, errors, set, t, cardTypeOptions, branchOptions, districtOptions, userLocked, selfUserId, userName }),
|
||||||
|
[form, errors, set, t, cardTypeOptions, branchOptions, districtOptions, userLocked, selfUserId, userName],
|
||||||
|
);
|
||||||
|
|
||||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const markVisited = (i: number) =>
|
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||||
setVisited((prev) => new Set([...prev, i]))
|
|
||||||
|
|
||||||
const markSubmitted = (i: number) =>
|
const markSubmitted = (i: number) => setSubmittedSteps((prev) => new Set([...prev, i]));
|
||||||
setSubmittedSteps((prev) => new Set([...prev, i]))
|
|
||||||
|
|
||||||
const handleNext = () => {
|
const handleNext = () => {
|
||||||
markVisited(currentStep)
|
markVisited(currentStep);
|
||||||
markSubmitted(currentStep)
|
markSubmitted(currentStep);
|
||||||
const errs = STEPS[currentStep].validate(form, mode)
|
const errs = STEPS[currentStep].validate(form);
|
||||||
if (Object.keys(errs).length > 0) {
|
if (Object.keys(errs).length > 0) {
|
||||||
Object.entries(errs).forEach(([key, msg]) => {
|
Object.entries(errs).forEach(([key, msg]) => {
|
||||||
setError(key as keyof CardPinFormData, { type: 'manual', message: msg })
|
setError(key as keyof CardPinFormData, { type: "manual", message: msg });
|
||||||
})
|
});
|
||||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
setCurrentStep(currentStep + 1)
|
setCurrentStep(currentStep + 1);
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleBack = () => {
|
const handleBack = () => {
|
||||||
markVisited(currentStep)
|
markVisited(currentStep);
|
||||||
setCurrentStep(currentStep - 1)
|
setCurrentStep(currentStep - 1);
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
}
|
};
|
||||||
|
|
||||||
const handleGoTo = (i: number) => {
|
const handleGoTo = (i: number) => {
|
||||||
markVisited(currentStep)
|
markVisited(currentStep);
|
||||||
setCurrentStep(i)
|
setCurrentStep(i);
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
}
|
};
|
||||||
|
|
||||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const handleSubmit = () => {
|
const handleSubmit = () => {
|
||||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)))
|
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
|
||||||
|
|
||||||
const values = getValues()
|
const values = getValues();
|
||||||
const allErrors: FlatErrors = {}
|
const allErrors: FlatErrors = {};
|
||||||
for (const step of STEPS) Object.assign(allErrors, step.validate(values, mode))
|
for (const step of STEPS) Object.assign(allErrors, step.validate(values));
|
||||||
|
|
||||||
if (Object.keys(allErrors).length > 0) {
|
if (Object.keys(allErrors).length > 0) {
|
||||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||||
setError(key as keyof CardPinFormData, { type: 'manual', message: msg })
|
setError(key as keyof CardPinFormData, { type: "manual", message: msg });
|
||||||
})
|
});
|
||||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||||
for (let i = 0; i < STEPS.length; i++) {
|
for (let i = 0; i < STEPS.length; i++) {
|
||||||
if (Object.keys(STEPS[i].validate(values, mode)).length > 0) {
|
if (Object.keys(STEPS[i].validate(values)).length > 0) {
|
||||||
setCurrentStep(i)
|
setCurrentStep(i);
|
||||||
break
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload: CardPinCreatePayload = {
|
const payload: CreateCardPinPayload = buildPayload(values);
|
||||||
status: values.status as CardPinCreatePayload['status'],
|
|
||||||
note: values.note ?? '',
|
|
||||||
card_type: values.card_type,
|
|
||||||
card_number: values.card_number,
|
|
||||||
province: values.province,
|
|
||||||
branch: values.branch,
|
|
||||||
first_name: values.first_name,
|
|
||||||
last_name: values.last_name,
|
|
||||||
father_name: values.father_name ?? '',
|
|
||||||
birth_date: values.birth_date,
|
|
||||||
phone: values.phone,
|
|
||||||
passport_series: values.passport_series,
|
|
||||||
passport_number: values.passport_number,
|
|
||||||
passport_file_1: values.passport_file_1,
|
|
||||||
passport_file_2: values.passport_file_2,
|
|
||||||
passport_file_3: values.passport_file_3,
|
|
||||||
passport_file_4: values.passport_file_4,
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mode === 'create') {
|
if (mode === "create") {
|
||||||
createMutation.mutate(payload, { onSuccess: (data) => navigate(`/card-pins/${data.id}`) })
|
createMutation.mutate(payload, { onSuccess: (data) => navigate(`/card-pins/${data.id}`) });
|
||||||
} else {
|
} else {
|
||||||
updateMutation.mutate(payload, { onSuccess: () => navigate('/card-pins') })
|
updateMutation.mutate(payload, { onSuccess: () => navigate("/card-pins") });
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
// ── StepBar items ──────────────────────────────────────────────────────────
|
// ── StepBar items ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||||
const isActive = i === currentStep
|
const isActive = i === currentStep;
|
||||||
const hasErrors = stepsWithErrors.has(i)
|
const hasErrors = stepsWithErrors.has(i);
|
||||||
const isDone = visited.has(i) && !hasErrors
|
const isDone = visited.has(i) && !hasErrors;
|
||||||
return {
|
return {
|
||||||
id: s.id,
|
id: s.id,
|
||||||
title: t(s.titleKey) || s.titleFallback,
|
title: t(s.titleKey) || s.titleFallback,
|
||||||
subtitle: t(s.subtitleKey) || s.subtitleFallback,
|
subtitle: t(s.subtitleKey) || s.subtitleFallback,
|
||||||
icon: s.icon,
|
icon: s.icon,
|
||||||
status: isActive ? 'active' : hasErrors ? 'error' : isDone ? 'done' : 'idle',
|
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||||
}
|
};
|
||||||
})
|
});
|
||||||
|
|
||||||
const isLastStep = currentStep === STEPS.length - 1
|
const isLastStep = currentStep === STEPS.length - 1;
|
||||||
|
|
||||||
// ── Render ─────────────────────────────────────────────────────────────────
|
// ── Render ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -518,13 +567,9 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
|||||||
{/* Page header */}
|
{/* Page header */}
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === 'create'
|
{mode === "create" ? t("cardPin.createTitle", "Kart pin bukja dörediň") : t("cardPin.editTitle", "Kart pin bukja redaktirläň")}
|
||||||
? t('cardPin.createTitle', 'Kart pin bukja dörediň')
|
|
||||||
: t('cardPin.editTitle', 'Kart pin bukja redaktirläň')}
|
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-muted-foreground mt-1">
|
<p className="text-sm text-muted-foreground mt-1">{t("common.form.subtitle", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}</p>
|
||||||
{t('common.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Step bar */}
|
{/* Step bar */}
|
||||||
@@ -533,46 +578,49 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Step content */}
|
{/* Step content */}
|
||||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
{currentStep === 1 && <StepPersonal {...stepProps} initialData={initialData} />}
|
||||||
{currentStep === 2 && (
|
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||||
<StepPassport {...stepProps} mode={mode} initialData={initialData} />
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Actions */}
|
{/* Actions */}
|
||||||
<FormActions
|
<FormActions
|
||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onCancel={currentStep === 0 ? () => navigate('/card-pins') : undefined}
|
onCancel={currentStep === 0 ? () => navigate("/card-pins") : undefined}
|
||||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||||
prevLabel={t('common.prev', 'Yza')}
|
prevLabel={t("common.prev", "Yza")}
|
||||||
onNext={!isLastStep ? handleNext : undefined}
|
onNext={!isLastStep ? handleNext : undefined}
|
||||||
nextLabel={t('common.next', 'Indiki')}
|
nextLabel={t("common.next", "Indiki")}
|
||||||
showSubmit={isLastStep}
|
showSubmit={isLastStep}
|
||||||
onSubmit={isLastStep ? handleSubmit : undefined}
|
saveOnEveryStep={mode === "edit"}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
submitLabel={
|
submitLabel={
|
||||||
mode === 'create'
|
mode === "create" ? t("cardPin.createBtn", "Kart pin bukja dörediň") : t("cardPin.editBtn", "Kart pin bukja redaktirläň")
|
||||||
? t('cardPin.createBtn', 'Kart pin bukja dörediň')
|
|
||||||
: t('cardPin.editBtn', 'Kart pin bukja redaktirläň')
|
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapInitial(data: CardPinItem): Partial<CardPinFormData> {
|
function mapInitial(data: CardPinOrder): Partial<CardPinFormData> {
|
||||||
return {
|
return {
|
||||||
status: data.status ?? 'pending',
|
uniqueId: data.uniqueId ?? "",
|
||||||
note: data.note ?? '',
|
status: data.status ?? "",
|
||||||
card_type: data.card_type ?? '',
|
cardNumber: data.cardNumber ?? "",
|
||||||
card_number: data.card_number ?? '',
|
cardTypeId: String(data.cardType?.id ?? ""),
|
||||||
province: data.province ?? '',
|
region: data.region ?? "",
|
||||||
branch: data.branch ?? '',
|
branchId: String(data.branch?.id ?? ""),
|
||||||
first_name: data.first_name ?? '',
|
customerName: data.customerName ?? "",
|
||||||
last_name: data.last_name ?? '',
|
customerSurname: data.customerSurname ?? "",
|
||||||
father_name: data.father_name ?? '',
|
customerPatronicName: data.customerPatronicName ?? "",
|
||||||
birth_date: data.birth_date ?? '',
|
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||||
phone: data.phone ?? '',
|
phone: formatFromApiPhone(data.phone),
|
||||||
passport_series: data.passport_series ?? '',
|
passportSerie: data.passportSerie ?? "",
|
||||||
passport_number: data.passport_number ?? '',
|
passportId: data.passportId ?? "",
|
||||||
}
|
passportOne: data.passportOne ?? "",
|
||||||
|
passportTwo: data.passportTwo ?? "",
|
||||||
|
passportThree: data.passportThree ?? "",
|
||||||
|
passportFour: data.passportFour ?? "",
|
||||||
|
userId: String(data.user?.id ?? ""),
|
||||||
|
notes: data.notes ?? "",
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -1,77 +1,81 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import { cardPinApi, type CardPinListParams, type CardPinCreatePayload, type CardPinUpdatePayload } from '../api/cardPinApi'
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
|
import { cardPinApi, type CardPinListParams, type CreateCardPinPayload, type UpdateCardPinPayload } from "../api/cardPinApi";
|
||||||
|
|
||||||
export const CARD_PIN_KEYS = {
|
export const CARD_PIN_KEYS = {
|
||||||
all: ['card-pins'] as const,
|
all: ["card-pin-orders"] as const,
|
||||||
lists: () => [...CARD_PIN_KEYS.all, 'list'] as const,
|
lists: () => [...CARD_PIN_KEYS.all, "list"] as const,
|
||||||
list: (p: CardPinListParams) => [...CARD_PIN_KEYS.lists(), p] as const,
|
list: (p: CardPinListParams) => [...CARD_PIN_KEYS.lists(), p] as const,
|
||||||
detail: (id: string) => [...CARD_PIN_KEYS.all, 'detail', id] as const,
|
detail: (id: number) => [...CARD_PIN_KEYS.all, "detail", id] as const,
|
||||||
}
|
};
|
||||||
|
|
||||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardPins(params: CardPinListParams) {
|
export function useCardPins(params: CardPinListParams) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
|
const queryParams: CardPinListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: CARD_PIN_KEYS.list(params),
|
queryKey: CARD_PIN_KEYS.list(queryParams),
|
||||||
queryFn: () => cardPinApi.list(params),
|
queryFn: ({ signal }) => cardPinApi.list(queryParams, signal),
|
||||||
placeholderData: (prev) => prev,
|
placeholderData: (prev) => prev,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Detail ───────────────────────────────────────────────────────────────────
|
// ─── Detail ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardPin(id: string) {
|
export function useCardPin(id: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: CARD_PIN_KEYS.detail(id),
|
queryKey: CARD_PIN_KEYS.detail(id),
|
||||||
queryFn: () => cardPinApi.getById(id),
|
queryFn: () => cardPinApi.getById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateCardPin() {
|
export function useCreateCardPin() {
|
||||||
const qc = useQueryClient()
|
const qc = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CardPinCreatePayload) => cardPinApi.create(payload),
|
mutationFn: (payload: CreateCardPinPayload) => cardPinApi.create(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||||
toast.success(t('cardPin.createSuccess', 'Kart pin bukja döredildi'))
|
toast.success(t("cardPin.createSuccess", "Kart pin bukja döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateCardPin(id: string) {
|
export function useUpdateCardPin(id: number) {
|
||||||
const qc = useQueryClient()
|
const qc = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CardPinUpdatePayload) => cardPinApi.update(id, payload),
|
mutationFn: (payload: UpdateCardPinPayload) => cardPinApi.update(id, payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.detail(id) })
|
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.detail(id) });
|
||||||
toast.success(t('cardPin.updateSuccess', 'Kart pin bukja üýtgedildi'))
|
toast.success(t("cardPin.updateSuccess", "Kart pin bukja üýtgedildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteCardPin() {
|
export function useDeleteCardPin() {
|
||||||
const qc = useQueryClient()
|
const qc = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: string) => cardPinApi.delete(id),
|
mutationFn: (id: number) => cardPinApi.delete(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||||
toast.success(t('cardPin.deleteSuccess', 'Kart pin bukja pozuldy'))
|
toast.success(t("cardPin.deleteSuccess", "Kart pin bukja pozuldy"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
@@ -1,89 +1,75 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
|
import type { CreateCardPinPayload } from "../api/cardPinApi";
|
||||||
|
import { formatToApiPhone } from "@/lib/utils";
|
||||||
|
|
||||||
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
|
const optional = () => z.string().default("");
|
||||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
|
||||||
|
|
||||||
export const cardPinFormSchema = z.object({
|
export const cardPinFormSchema = z.object({
|
||||||
|
uniqueId: z.string().min(1, "validation.required"),
|
||||||
status: z.string().min(1, "validation.required"),
|
status: z.string().min(1, "validation.required"),
|
||||||
note: z.string().optional(),
|
customerName: z.string().min(1, "validation.required"),
|
||||||
card_type: z.string().min(1, "validation.required"),
|
customerSurname: z.string().min(1, "validation.required"),
|
||||||
card_number: z.string().min(1, "validation.required"),
|
customerPatronicName: optional(),
|
||||||
province: z.string().min(1, "validation.required"),
|
bornAt: optional(),
|
||||||
branch: z.string().min(1, "validation.required"),
|
region: z.string().min(1, "validation.required"),
|
||||||
first_name: z.string().min(1, "validation.required"),
|
branchId: z.string().min(1, "validation.required"),
|
||||||
last_name: z.string().min(1, "validation.required"),
|
cardTypeId: z.string().min(1, "validation.required"),
|
||||||
father_name: z.string().optional(),
|
cardNumber: z.string().min(1, "validation.required"),
|
||||||
birth_date: z.string().min(1, "validation.required"),
|
phone: z.string().min(1, "validation.required"),
|
||||||
phone: z
|
passportSerie: z.string().min(1, "validation.required"),
|
||||||
.string()
|
passportId: z.string().min(1, "validation.required"),
|
||||||
.min(1, "validation.required")
|
passportOne: optional(),
|
||||||
.refine(
|
passportTwo: optional(),
|
||||||
(val) => {
|
passportThree: optional(),
|
||||||
const digits = val.replace(/\D/g, "");
|
passportFour: optional(),
|
||||||
return digits.length === 8;
|
userId: z.string().min(1, "validation.required"),
|
||||||
},
|
notes: optional(),
|
||||||
{ message: "validation.invalidPhone" },
|
|
||||||
)
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
const digits = val.replace(/\D/g, "");
|
|
||||||
const prefix = digits.slice(0, 2);
|
|
||||||
return VALID_PHONE_PREFIXES.includes(prefix);
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhonePrefix" },
|
|
||||||
),
|
|
||||||
passport_series: z.string().min(1, "validation.required"),
|
|
||||||
passport_number: z.string().min(1, "validation.required"),
|
|
||||||
passport_file_1: z.custom<File | null>().nullable(),
|
|
||||||
passport_file_2: z.custom<File | null>().nullable(),
|
|
||||||
passport_file_3: z.custom<File | null>().nullable(),
|
|
||||||
passport_file_4: z.custom<File | null>().nullable(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export type CardPinFormData = z.infer<typeof cardPinFormSchema>;
|
export type CardPinFormData = z.infer<typeof cardPinFormSchema>;
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CardPinFormData = {
|
export const DEFAULT_FORM_VALUES: CardPinFormData = {
|
||||||
status: "pending",
|
uniqueId: "",
|
||||||
note: "",
|
status: "",
|
||||||
card_type: "",
|
customerName: "",
|
||||||
card_number: "",
|
customerSurname: "",
|
||||||
province: "",
|
customerPatronicName: "",
|
||||||
branch: "",
|
bornAt: "",
|
||||||
first_name: "",
|
region: "",
|
||||||
last_name: "",
|
branchId: "",
|
||||||
father_name: "",
|
cardTypeId: "",
|
||||||
birth_date: "",
|
cardNumber: "",
|
||||||
phone: "",
|
phone: "",
|
||||||
passport_series: "",
|
passportSerie: "",
|
||||||
passport_number: "",
|
passportId: "",
|
||||||
passport_file_1: null,
|
passportOne: "",
|
||||||
passport_file_2: null,
|
passportTwo: "",
|
||||||
passport_file_3: null,
|
passportThree: "",
|
||||||
passport_file_4: null,
|
passportFour: "",
|
||||||
|
userId: "",
|
||||||
|
notes: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
export const stepSchemas: Record<number, z.ZodType<Partial<CardPinFormData>>> = {
|
export const stepSchemas: Record<number, z.ZodType<Partial<CardPinFormData>>> = {
|
||||||
0: cardPinFormSchema.pick({
|
0: cardPinFormSchema.pick({
|
||||||
|
uniqueId: true,
|
||||||
status: true,
|
status: true,
|
||||||
card_type: true,
|
cardNumber: true,
|
||||||
card_number: true,
|
cardTypeId: true,
|
||||||
province: true,
|
region: true,
|
||||||
branch: true,
|
branchId: true,
|
||||||
}),
|
}),
|
||||||
1: cardPinFormSchema.pick({
|
1: cardPinFormSchema.pick({
|
||||||
first_name: true,
|
customerName: true,
|
||||||
last_name: true,
|
customerSurname: true,
|
||||||
birth_date: true,
|
bornAt: true,
|
||||||
phone: true,
|
phone: true,
|
||||||
|
userId: true,
|
||||||
}),
|
}),
|
||||||
2: z.object({
|
2: cardPinFormSchema.pick({
|
||||||
passport_series: z.string().min(1, "validation.required"),
|
passportSerie: true,
|
||||||
passport_number: z.string().min(1, "validation.required"),
|
passportId: true,
|
||||||
passport_file_1: fileRequired,
|
|
||||||
passport_file_2: fileRequired,
|
|
||||||
passport_file_3: fileRequired,
|
|
||||||
passport_file_4: fileRequired,
|
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -91,23 +77,7 @@ function translateMsg(msg: string): string {
|
|||||||
return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function validateStep(
|
export function validateStep(stepIndex: number, form: CardPinFormData): Partial<Record<keyof CardPinFormData, string>> {
|
||||||
stepIndex: number,
|
|
||||||
form: CardPinFormData,
|
|
||||||
mode: "create" | "edit",
|
|
||||||
): Partial<Record<keyof CardPinFormData, string>> {
|
|
||||||
if (stepIndex === 2 && mode === "edit") {
|
|
||||||
const schema = cardPinFormSchema.pick({ passport_series: true, passport_number: true });
|
|
||||||
const result = schema.safeParse(form);
|
|
||||||
if (result.success) return {};
|
|
||||||
const errors: Partial<Record<keyof CardPinFormData, string>> = {};
|
|
||||||
for (const issue of result.error.issues) {
|
|
||||||
const key = issue.path[0] as keyof CardPinFormData;
|
|
||||||
if (!errors[key]) errors[key] = translateMsg(issue.message);
|
|
||||||
}
|
|
||||||
return errors;
|
|
||||||
}
|
|
||||||
|
|
||||||
const schema = stepSchemas[stepIndex];
|
const schema = stepSchemas[stepIndex];
|
||||||
const result = schema.safeParse(form);
|
const result = schema.safeParse(form);
|
||||||
if (result.success) return {};
|
if (result.success) return {};
|
||||||
@@ -119,3 +89,27 @@ export function validateStep(
|
|||||||
}
|
}
|
||||||
return errors;
|
return errors;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function buildPayload(data: CardPinFormData): CreateCardPinPayload {
|
||||||
|
return {
|
||||||
|
uniqueId: data.uniqueId.trim(),
|
||||||
|
status: data.status.trim(),
|
||||||
|
customerName: data.customerName.trim(),
|
||||||
|
customerSurname: data.customerSurname.trim(),
|
||||||
|
customerPatronicName: data.customerPatronicName.trim(),
|
||||||
|
bornAt: data.bornAt.trim(),
|
||||||
|
region: data.region.trim(),
|
||||||
|
branchId: Number(data.branchId),
|
||||||
|
cardTypeId: Number(data.cardTypeId),
|
||||||
|
cardNumber: data.cardNumber.trim(),
|
||||||
|
phone: formatToApiPhone(data.phone),
|
||||||
|
passportSerie: data.passportSerie.trim(),
|
||||||
|
passportId: data.passportId.trim(),
|
||||||
|
passportOne: data.passportOne.trim(),
|
||||||
|
passportTwo: data.passportTwo.trim(),
|
||||||
|
passportThree: data.passportThree.trim(),
|
||||||
|
passportFour: data.passportFour.trim(),
|
||||||
|
userId: Number(data.userId),
|
||||||
|
notes: data.notes.trim(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,108 +1,77 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface LocalizedTitle {
|
||||||
|
tm?: string;
|
||||||
|
ru?: string;
|
||||||
|
en?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LocalizedReasonTitle = string | LocalizedTitle;
|
||||||
|
|
||||||
|
export function resolveCardReasonTitle(val: LocalizedReasonTitle | null | undefined, lang = "tm"): string {
|
||||||
|
if (!val) return "";
|
||||||
|
if (typeof val === "string") return val;
|
||||||
|
const key = (lang === "tk" ? "tm" : lang) as keyof LocalizedTitle;
|
||||||
|
return val[key] ?? val.tm ?? val.en ?? val.ru ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
export interface CardReason {
|
export interface CardReason {
|
||||||
id: number
|
id: number;
|
||||||
name: Record<'tk' | 'ru' | 'en', string>
|
title: LocalizedReasonTitle;
|
||||||
value: number
|
price: string;
|
||||||
description: string | null
|
notes: string;
|
||||||
isActive: boolean
|
active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CardReasonListParams {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
search?: string;
|
||||||
|
isActive?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CardReasonListResponse {
|
export interface CardReasonListResponse {
|
||||||
data: CardReason[]
|
count: number;
|
||||||
total: number
|
reasonCards: CardReason[];
|
||||||
page: number
|
|
||||||
perPage: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateCardReasonPayload {
|
export interface CreateCardReasonPayload {
|
||||||
name: Record<'tk' | 'ru' | 'en', string>
|
active: boolean;
|
||||||
value: number
|
notes: string;
|
||||||
description: string | null
|
price: string;
|
||||||
isActive: boolean
|
title: LocalizedTitle;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateCardReasonPayload extends CreateCardReasonPayload {
|
export type UpdateCardReasonPayload = CreateCardReasonPayload;
|
||||||
id: number
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const MOCK_CARD_STATES: CardReason[] = [
|
|
||||||
{ id: 1, name: { tk: 'Täze', ru: 'Новый', en: 'New' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 2, name: { tk: 'Döwülen/Zaýalanan', ru: 'Сломанный/Поврежденный', en: 'Broken/Damaged' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 3, name: { tk: 'Ulanylyş möhleti geçen', ru: 'Срок истёк', en: 'Expired' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 4, name: { tk: 'Maşgalasy üýtgeýär', ru: 'Смена фамилии', en: 'Name change' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 5, name: { tk: 'Ýiten', ru: 'Потерян', en: 'Lost' }, value: 37.75, description: null, isActive: true },
|
|
||||||
{ id: 6, name: { tk: 'Pin bukja (bloklanan)', ru: 'Пин конверт (заблокирован)', en: 'Pin envelope (blocked)' }, value: 3.02, description: null, isActive: false },
|
|
||||||
{ id: 7, name: { tk: 'Rekwizit', ru: 'Реквизит', en: 'Requisite' }, value: 2.30, description: null, isActive: false },
|
|
||||||
]
|
|
||||||
|
|
||||||
let mockStore = [...MOCK_CARD_STATES]
|
|
||||||
let nextId = 8
|
|
||||||
|
|
||||||
// Simulated async delay
|
|
||||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
|
||||||
|
|
||||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export async function fetchCardReasons(params: {
|
export async function fetchCardReasons(params: CardReasonListParams = {}, signal?: AbortSignal): Promise<CardReasonListResponse> {
|
||||||
page?: number
|
const { page, limit, search, isActive } = params;
|
||||||
perPage?: number
|
const { data } = await apiClient.get<CardReasonListResponse>("/reasons-cards", {
|
||||||
search?: string
|
params: { page, limit, reason_name: search, is_active: isActive },
|
||||||
isActive?: string
|
signal,
|
||||||
}): Promise<CardReasonListResponse> {
|
});
|
||||||
await delay()
|
return data;
|
||||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
|
||||||
|
|
||||||
let filtered = mockStore.filter((item) => {
|
|
||||||
const matchSearch =
|
|
||||||
!search ||
|
|
||||||
Object.values(item.name).some((n) =>
|
|
||||||
n.toLowerCase().includes(search.toLowerCase())
|
|
||||||
)
|
|
||||||
const matchActive =
|
|
||||||
isActive === '' || isActive === undefined
|
|
||||||
? true
|
|
||||||
: isActive === 'true'
|
|
||||||
? item.isActive
|
|
||||||
: !item.isActive
|
|
||||||
return matchSearch && matchActive
|
|
||||||
})
|
|
||||||
|
|
||||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
|
||||||
|
|
||||||
const total = filtered.length
|
|
||||||
const start = (page - 1) * perPage
|
|
||||||
const data = filtered.slice(start, start + perPage)
|
|
||||||
|
|
||||||
return { data, total, page, perPage }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchCardReasonById(id: number): Promise<CardReason> {
|
export async function fetchCardReasonById(id: number): Promise<CardReason> {
|
||||||
await delay()
|
const { data } = await apiClient.get<CardReason>(`/reasons-cards/${id}`);
|
||||||
const item = mockStore.find((c) => c.id === id)
|
return data;
|
||||||
if (!item) throw new Error('Not found')
|
|
||||||
return { ...item }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createCardReason(payload: CreateCardReasonPayload): Promise<CardReason> {
|
export async function createCardReason(payload: CreateCardReasonPayload): Promise<CardReason> {
|
||||||
await delay(400)
|
const { data } = await apiClient.post<CardReason>("/reasons-cards", payload);
|
||||||
const newItem: CardReason = { id: nextId++, ...payload }
|
return data;
|
||||||
mockStore = [newItem, ...mockStore]
|
|
||||||
return newItem
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateCardReason(payload: UpdateCardReasonPayload): Promise<CardReason> {
|
export async function updateCardReason(id: number, payload: UpdateCardReasonPayload): Promise<CardReason> {
|
||||||
await delay(400)
|
const { data } = await apiClient.put<CardReason>(`/reasons-cards/${id}`, payload);
|
||||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
return data;
|
||||||
if (idx === -1) throw new Error('Not found')
|
|
||||||
const updated = { ...mockStore[idx], ...payload }
|
|
||||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
|
||||||
return updated
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteCardReason(id: number): Promise<void> {
|
export async function deleteCardReason(id: number): Promise<void> {
|
||||||
await delay(300)
|
await apiClient.delete(`/reasons-cards/${id}`);
|
||||||
mockStore = mockStore.filter((c) => c.id !== id)
|
}
|
||||||
}
|
|
||||||
@@ -10,10 +10,15 @@ import { MultiLangInput } from "@/components/multiLangInput";
|
|||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import type { CardReason } from "../api/cardReasonsApi";
|
import type { CardReason } from "../api/cardReasonsApi";
|
||||||
import { useCreateCardReason, useUpdateCardReason } from "../hooks/useCardReasons";
|
import { useCreateCardReason, useUpdateCardReason } from "../hooks/useCardReasons";
|
||||||
import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardReason.schema";
|
import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from "../schemas/cardReason.schema";
|
||||||
import type { CardReasonFormData } from "../schemas/cardReason.schema";
|
import type { CardReasonFormData } from "../schemas/cardReason.schema";
|
||||||
|
|
||||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface CardReasonFormProps {
|
||||||
|
mode: "create" | "edit";
|
||||||
|
initialData?: CardReason;
|
||||||
|
}
|
||||||
|
|
||||||
type FlatErrors = Partial<Record<keyof CardReasonFormData, string>>;
|
type FlatErrors = Partial<Record<keyof CardReasonFormData, string>>;
|
||||||
|
|
||||||
@@ -28,22 +33,6 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
|
|
||||||
// ─── CardReasonForm ─────────────────────────────────────────────────────────────
|
// ─── CardReasonForm ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
interface CardReasonFormProps {
|
|
||||||
mode: "create" | "edit";
|
|
||||||
initialData?: CardReason;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mapInitial(data: CardReason): CardReasonFormData {
|
|
||||||
return {
|
|
||||||
nameTk: data.name.tk,
|
|
||||||
nameRu: data.name.ru,
|
|
||||||
nameEn: data.name.en,
|
|
||||||
value: String(data.value),
|
|
||||||
description: data.description ?? "",
|
|
||||||
isActive: data.isActive,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
||||||
const { t: _t, i18n } = useTranslation();
|
const { t: _t, i18n } = useTranslation();
|
||||||
const t: (key: string, fallback?: string) => string = useCallback(
|
const t: (key: string, fallback?: string) => string = useCallback(
|
||||||
@@ -53,7 +42,7 @@ export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const createMutation = useCreateCardReason();
|
const createMutation = useCreateCardReason();
|
||||||
const updateMutation = useUpdateCardReason();
|
const updateMutation = useUpdateCardReason(initialData?.id ?? 0);
|
||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
@@ -62,10 +51,10 @@ export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
|||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
getValues,
|
|
||||||
formState: { errors: rhfErrors },
|
formState: { errors: rhfErrors },
|
||||||
clearErrors,
|
clearErrors,
|
||||||
trigger,
|
trigger,
|
||||||
|
getValues,
|
||||||
} = useForm<CardReasonFormData>({
|
} = useForm<CardReasonFormData>({
|
||||||
resolver: zodResolver(schema),
|
resolver: zodResolver(schema),
|
||||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||||
@@ -74,46 +63,47 @@ export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
|||||||
const form = watch();
|
const form = watch();
|
||||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||||
|
|
||||||
const set = useCallback(
|
|
||||||
<K extends keyof CardReasonFormData>(key: K, value: CardReasonFormData[K]) => {
|
|
||||||
(setValue as (name: K, val: CardReasonFormData[K]) => void)(key, value);
|
|
||||||
clearErrors(key);
|
|
||||||
},
|
|
||||||
[setValue, clearErrors],
|
|
||||||
);
|
|
||||||
|
|
||||||
// ── Re-validate on language change ──
|
// ── Re-validate on language change ──
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [i18n.language]);
|
}, [i18n.language]);
|
||||||
|
|
||||||
|
const set = useCallback(
|
||||||
|
(key: keyof CardReasonFormData) => (value: string | boolean) => {
|
||||||
|
(setValue as (k: keyof CardReasonFormData, v: string | boolean) => void)(key, value);
|
||||||
|
clearErrors(key);
|
||||||
|
},
|
||||||
|
[setValue, clearErrors],
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger();
|
const isValid = await trigger();
|
||||||
if (!isValid) return;
|
if (!isValid) return;
|
||||||
|
|
||||||
const values = getValues();
|
const payload = buildPayload(getValues());
|
||||||
const payload = buildPayload(values);
|
|
||||||
|
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
createMutation.mutate(payload, {
|
const result = await createMutation.mutateAsync(payload);
|
||||||
onSuccess: () => navigate("/resources/card-states"),
|
navigate(`/settings/card/card-reasons/${result.id}`);
|
||||||
});
|
} else {
|
||||||
} else if (initialData) {
|
await updateMutation.mutateAsync(payload);
|
||||||
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/resources/card-states") });
|
navigate(`/settings/card/card-reasons/${initialData!.id}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const nameFields = {
|
const nameFields = {
|
||||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk", v), error: errors.nameTk },
|
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk")(v), error: errors.nameTk },
|
||||||
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu", v), error: errors.nameRu },
|
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu")(v), error: errors.nameRu },
|
||||||
en: { value: form.nameEn, onChange: (v: string) => set("nameEn", v), error: errors.nameEn },
|
en: { value: form.nameEn, onChange: (v: string) => set("nameEn")(v), error: errors.nameEn },
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === "create" ? t("cardReasons.createTitle", "Sebäp dörediň") : t("cardReasons.editTitle", "Sebäp üýtgetmek")}
|
{mode === "create" ? t("cardReasons.createTitle", "Sebäp dörediň") : t("cardReasons.editTitle", "Sebäbi üýtgetmek")}
|
||||||
</h1>
|
</h1>
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard span="full">
|
<BentoCard span="full">
|
||||||
@@ -126,40 +116,35 @@ export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
|||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="number"
|
type="number"
|
||||||
label={t("cardReasons.fields.value", "Baha")}
|
label={t("cardReasons.fields.price", "Baha")}
|
||||||
value={form.value}
|
value={form.price}
|
||||||
onChange={(v) => set("value", v)}
|
onChange={set("price")}
|
||||||
placeholder={t("cardReasons.fields.value", "Baha")}
|
placeholder={t("cardReasons.fields.price", "Baha")}
|
||||||
error={errors.value}
|
error={errors.price}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardReasons.fields.description", "Bellikler")}
|
label={t("cardReasons.fields.notes", "Bellikler")}
|
||||||
value={form.description}
|
value={form.notes}
|
||||||
onChange={(v) => set("description", v)}
|
onChange={set("notes")}
|
||||||
placeholder={t("cardReasons.fields.description", "Bellikler")}
|
placeholder={t("cardReasons.fields.notes", "Bellikler")}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<div className="flex items-center gap-3 pt-1">
|
<div className="flex items-center gap-3 pt-1">
|
||||||
<span className="text-sm font-semibold text-muted-foreground">{t("cardReasons.fields.isActive", "Işjeň")}</span>
|
<span className="text-sm font-semibold text-muted-foreground">{t("cardReasons.fields.isActive", "Işjeň")}</span>
|
||||||
<Checkbox checked={form.isActive} onCheckedChange={(checked) => set("isActive", !!checked)} />
|
<Checkbox checked={form.active} onCheckedChange={(checked) => set("active")(!!checked)} />
|
||||||
</div>
|
</div>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
<FormActions
|
<FormActions
|
||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
onCancel={() => navigate("/resources/card-states")}
|
onCancel={() => navigate("/settings/card/card-reasons")}
|
||||||
cancelVariant="ghost"
|
submitLabel={mode === "create" ? t("cardReasons.actions.create", "Sebäbi döretmek") : t("cardReasons.actions.update", "Täzelemek")}
|
||||||
submitLabel={
|
|
||||||
mode === "create"
|
|
||||||
? t("cardReasons.actions.create", "Kartyň çykarylmagynyň sebäbini döretdiň")
|
|
||||||
: t("cardReasons.actions.update", "Täzelemek")
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,92 +1,94 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
import {
|
import {
|
||||||
fetchCardReasons,
|
fetchCardReasons,
|
||||||
fetchCardReasonById,
|
fetchCardReasonById,
|
||||||
createCardReason,
|
createCardReason,
|
||||||
updateCardReason,
|
updateCardReason,
|
||||||
deleteCardReason,
|
deleteCardReason,
|
||||||
|
type CardReasonListParams,
|
||||||
type CreateCardReasonPayload,
|
type CreateCardReasonPayload,
|
||||||
type UpdateCardReasonPayload,
|
type UpdateCardReasonPayload,
|
||||||
} from '../api/cardReasonsApi'
|
} from "../api/cardReasonsApi";
|
||||||
|
|
||||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const cardReasonKeys = {
|
export const cardReasonKeys = {
|
||||||
all: ['cardReasons'] as const,
|
all: ["cardReasons"] as const,
|
||||||
lists: () => [...cardReasonKeys.all, 'list'] as const,
|
lists: () => [...cardReasonKeys.all, "list"] as const,
|
||||||
list: (params: Record<string, unknown>) =>
|
list: (params: CardReasonListParams) => [...cardReasonKeys.lists(), params] as const,
|
||||||
[...cardReasonKeys.lists(), params] as const,
|
details: () => [...cardReasonKeys.all, "detail"] as const,
|
||||||
detail: (id: number) => [...cardReasonKeys.all, 'detail', id] as const,
|
detail: (id: number) => [...cardReasonKeys.details(), id] as const,
|
||||||
}
|
};
|
||||||
|
|
||||||
// ─── useCardReasons ────────────────────────────────────────────────────────────
|
// ─── useCardReasons ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardReasons(params: {
|
export function useCardReasons(params: CardReasonListParams = {}) {
|
||||||
page?: number
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
perPage?: number
|
const normalized = normalizeSearch(debouncedSearch);
|
||||||
search?: string
|
const queryParams: CardReasonListParams = { ...params, search: normalized || undefined };
|
||||||
isActive?: string
|
|
||||||
}) {
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: cardReasonKeys.list(params),
|
queryKey: cardReasonKeys.list(queryParams),
|
||||||
queryFn: () => fetchCardReasons(params),
|
queryFn: ({ signal }) => fetchCardReasons(queryParams, signal),
|
||||||
})
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useCardReasonById ─────────────────────────────────────────────────────────
|
// ─── useCardReasonById ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardReasonById(id: number) {
|
export function useCardReasonById(id: number | undefined) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: cardReasonKeys.detail(id),
|
queryKey: cardReasonKeys.detail(id!),
|
||||||
queryFn: () => fetchCardReasonById(id),
|
queryFn: () => fetchCardReasonById(id!),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useCreateCardReason ───────────────────────────────────────────────────────
|
// ─── useCreateCardReason ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateCardReason() {
|
export function useCreateCardReason() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateCardReasonPayload) => createCardReason(payload),
|
mutationFn: (payload: CreateCardReasonPayload) => createCardReason(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() });
|
||||||
toast.success(t('CardReasons.toast.createSuccess', 'Kart ýagdaýy döredildi'))
|
toast.success(t("cardReasons.toast.createSuccess", "Sebäp döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useUpdateCardReason ───────────────────────────────────────────────────────
|
// ─── useUpdateCardReason ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateCardReason() {
|
export function useUpdateCardReason(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateCardReasonPayload) => updateCardReason(payload),
|
mutationFn: (payload: UpdateCardReasonPayload) => updateCardReason(id, payload),
|
||||||
onSuccess: (data) => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.detail(data.id) })
|
queryClient.invalidateQueries({ queryKey: cardReasonKeys.detail(id) });
|
||||||
toast.success(t('CardReasons.toast.updateSuccess', 'Kart ýagdaýy täzelendi'))
|
toast.success(t("cardReasons.toast.updateSuccess", "Sebäp täzelendi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useDeleteCardReason ───────────────────────────────────────────────────────
|
// ─── useDeleteCardReason ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteCardReason() {
|
export function useDeleteCardReason() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => deleteCardReason(id),
|
mutationFn: (id: number) => deleteCardReason(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() });
|
||||||
toast.success(t('CardReasons.toast.deleteSuccess', 'Kart ýagdaýy öçürildi'))
|
toast.success(t("cardReasons.toast.deleteSuccess", "Sebäp öçürildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
@@ -1,36 +1,46 @@
|
|||||||
import { z } from 'zod'
|
import { z } from "zod";
|
||||||
import type { CreateCardReasonPayload } from '../api/cardReasonsApi'
|
import { resolveCardReasonTitle, type CardReason, type CreateCardReasonPayload } from "../api/cardReasonsApi";
|
||||||
|
|
||||||
export function createCardReasonFormSchema(t: (key: string, fallback?: string) => string) {
|
export function createCardReasonFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
return z.object({
|
return z.object({
|
||||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
value: z.string().min(1, t('validation.invalidNumber', 'validation.invalidNumber')).refine(
|
price: z
|
||||||
(v) => !isNaN(Number(v)) && Number(v) >= 0,
|
.string()
|
||||||
{ message: t('validation.invalidNumber', 'Dogry san giriziň') },
|
.refine((v) => v.trim() !== "" && !isNaN(Number(v)) && Number(v) >= 0, t("validation.invalidNumber", "Dogry san giriziň")),
|
||||||
),
|
notes: z.string().optional(),
|
||||||
description: z.string().optional(),
|
active: z.boolean(),
|
||||||
isActive: z.boolean(),
|
});
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CardReasonFormData = z.infer<ReturnType<typeof createCardReasonFormSchema>>
|
export type CardReasonFormData = z.infer<ReturnType<typeof createCardReasonFormSchema>>;
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CardReasonFormData = {
|
export const DEFAULT_FORM_VALUES: CardReasonFormData = {
|
||||||
nameTk: '',
|
nameTk: "",
|
||||||
nameRu: '',
|
nameRu: "",
|
||||||
nameEn: '',
|
nameEn: "",
|
||||||
value: '',
|
price: "",
|
||||||
description: '',
|
notes: "",
|
||||||
isActive: true,
|
active: true,
|
||||||
}
|
};
|
||||||
|
|
||||||
export function buildPayload(data: CardReasonFormData): CreateCardReasonPayload {
|
export function buildPayload(data: CardReasonFormData): CreateCardReasonPayload {
|
||||||
return {
|
return {
|
||||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
title: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||||
value: Number(data.value),
|
price: data.price.trim(),
|
||||||
description: data.description?.trim() || null,
|
notes: (data.notes ?? "").trim(),
|
||||||
isActive: data.isActive,
|
active: data.active,
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapInitial(data: CardReason): CardReasonFormData {
|
||||||
|
return {
|
||||||
|
nameTk: resolveCardReasonTitle(data.title, "tm"),
|
||||||
|
nameRu: resolveCardReasonTitle(data.title, "ru"),
|
||||||
|
nameEn: resolveCardReasonTitle(data.title, "en"),
|
||||||
|
price: data.price,
|
||||||
|
notes: data.notes ?? "",
|
||||||
|
active: data.active,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -1,259 +1,147 @@
|
|||||||
import apiClient from '@/lib/api/client'
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export type CardRequisiteStatus = 'pending' | 'approved' | 'rejected'
|
export interface LocalizedText {
|
||||||
|
tm?: string;
|
||||||
|
ru?: string;
|
||||||
|
en?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveLocalizedName(name: LocalizedText | string | null | undefined, lang = "en"): string {
|
||||||
|
if (!name) return "";
|
||||||
|
if (typeof name === "string") return name;
|
||||||
|
const key = (lang === "tk" ? "tm" : lang) as keyof LocalizedText;
|
||||||
|
return name[key] ?? name.tm ?? name.en ?? name.ru ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CardRequisiteStatus = "pending" | "approved" | "rejected";
|
||||||
|
|
||||||
|
export interface CardRequisiteUser {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
username: string;
|
||||||
|
phone: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CardRequisiteCardType {
|
||||||
|
id: number;
|
||||||
|
name: LocalizedText | string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CardRequisiteBranch {
|
||||||
|
id: number;
|
||||||
|
name: LocalizedText | string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Raw backend entity (GET responses mirror this shape). */
|
||||||
export interface CardRequisite {
|
export interface CardRequisite {
|
||||||
id: string
|
id: number;
|
||||||
status: CardRequisiteStatus
|
uniqueId: string;
|
||||||
note: string
|
user: CardRequisiteUser;
|
||||||
created_at: string
|
cardType: CardRequisiteCardType;
|
||||||
|
cardNumber: string;
|
||||||
// Card
|
cardMonth: string;
|
||||||
card_type: string
|
cardYear: string;
|
||||||
card_number: string
|
region: string;
|
||||||
card_expiry_month: string
|
branch: CardRequisiteBranch;
|
||||||
card_expiry_year: string
|
customerName: string;
|
||||||
|
customerSurname: string;
|
||||||
// Location
|
customerPatronicName: string;
|
||||||
province_id: string
|
bornAt: string;
|
||||||
branch_id: string
|
phone: string;
|
||||||
province_name?: string
|
passportSerie: string;
|
||||||
branch_name?: string
|
passportId: string;
|
||||||
|
passportOne: string;
|
||||||
// Personal
|
passportTwo: string;
|
||||||
first_name: string
|
passportThree: string;
|
||||||
last_name: string
|
passportFour: string;
|
||||||
middle_name?: string
|
status: string;
|
||||||
birth_date: string
|
notes: string;
|
||||||
phone: string
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
// Passport
|
|
||||||
passport_series: string
|
|
||||||
passport_number: string
|
|
||||||
passport_page1_url?: string
|
|
||||||
passport_page2_3_url?: string
|
|
||||||
passport_page8_9_url?: string
|
|
||||||
passport_page32_url?: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** LIST RESPONSE: GET /card-rekwizit-orders */
|
||||||
export interface CardRequisiteListResponse {
|
export interface CardRequisiteListResponse {
|
||||||
data: CardRequisite[]
|
count: number;
|
||||||
total: number
|
cardRekwizitOrders: CardRequisite[];
|
||||||
page: number
|
|
||||||
per_page: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateCardRequisitePayload {
|
/** LIST PARAMS */
|
||||||
status: CardRequisiteStatus
|
|
||||||
note?: string
|
|
||||||
card_type: string
|
|
||||||
card_number: string
|
|
||||||
card_expiry_month: string
|
|
||||||
card_expiry_year: string
|
|
||||||
province_id: string
|
|
||||||
branch_id: string
|
|
||||||
first_name: string
|
|
||||||
last_name: string
|
|
||||||
middle_name?: string
|
|
||||||
birth_date: string
|
|
||||||
phone: string
|
|
||||||
passport_series: string
|
|
||||||
passport_number: string
|
|
||||||
passport_page1?: File
|
|
||||||
passport_page2_3?: File
|
|
||||||
passport_page8_9?: File
|
|
||||||
passport_page32?: File
|
|
||||||
}
|
|
||||||
|
|
||||||
export type UpdateCardRequisitePayload = CreateCardRequisitePayload
|
|
||||||
|
|
||||||
export interface CardRequisiteListParams {
|
export interface CardRequisiteListParams {
|
||||||
page?: number
|
page?: number;
|
||||||
per_page?: number
|
limit?: number;
|
||||||
search?: string
|
status?: string;
|
||||||
|
branch_id?: number | string;
|
||||||
|
user_id?: number | string;
|
||||||
|
card_type_id?: number | string;
|
||||||
|
region?: string;
|
||||||
|
search?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
/** CREATE / UPDATE PAYLOAD (camelCase, JSON) */
|
||||||
|
export interface CardRequisitePayload {
|
||||||
function buildFormData(payload: CreateCardRequisitePayload): FormData {
|
bornAt: string;
|
||||||
const fd = new FormData()
|
branchId: number;
|
||||||
|
cardMonth: string;
|
||||||
const textFields: (keyof Omit<
|
cardNumber: string;
|
||||||
CreateCardRequisitePayload,
|
cardTypeId: number;
|
||||||
'passport_page1' | 'passport_page2_3' | 'passport_page8_9' | 'passport_page32'
|
cardYear: string;
|
||||||
>)[] = [
|
customerName: string;
|
||||||
'status', 'note', 'card_type', 'card_number', 'card_expiry_month',
|
customerPatronicName: string;
|
||||||
'card_expiry_year', 'province_id', 'branch_id', 'first_name', 'last_name',
|
customerSurname: string;
|
||||||
'middle_name', 'birth_date', 'phone', 'passport_series', 'passport_number',
|
notes: string;
|
||||||
]
|
passportFour: string;
|
||||||
|
passportId: string;
|
||||||
textFields.forEach((key) => {
|
passportOne: string;
|
||||||
const val = payload[key]
|
passportSerie: string;
|
||||||
if (val !== undefined && val !== null) fd.append(key, val)
|
passportThree: string;
|
||||||
})
|
passportTwo: string;
|
||||||
|
phone: string;
|
||||||
if (payload.passport_page1) fd.append('passport_page1', payload.passport_page1)
|
region: string;
|
||||||
if (payload.passport_page2_3) fd.append('passport_page2_3', payload.passport_page2_3)
|
status: string;
|
||||||
if (payload.passport_page8_9) fd.append('passport_page8_9', payload.passport_page8_9)
|
uniqueId: string;
|
||||||
if (payload.passport_page32) fd.append('passport_page32', payload.passport_page32)
|
userId: number;
|
||||||
|
|
||||||
return fd
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Mock data ─────────────────────────────────────────────────────────────────
|
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const MOCK_CARD_REQUISITES: CardRequisite[] = [
|
|
||||||
{
|
|
||||||
id: '1',
|
|
||||||
status: 'pending',
|
|
||||||
note: '',
|
|
||||||
card_type: 'UZCARD',
|
|
||||||
card_number: '8600123456789012',
|
|
||||||
card_expiry_month: '12',
|
|
||||||
card_expiry_year: '28',
|
|
||||||
province_id: '1',
|
|
||||||
branch_id: '1',
|
|
||||||
province_name: 'Toshkent',
|
|
||||||
branch_name: 'Filial 1',
|
|
||||||
first_name: 'Ali',
|
|
||||||
last_name: 'Valiyev',
|
|
||||||
middle_name: 'Akbarovich',
|
|
||||||
birth_date: '1990-05-15',
|
|
||||||
phone: '+998901234567',
|
|
||||||
passport_series: 'AA',
|
|
||||||
passport_number: '1234567',
|
|
||||||
created_at: '2025-01-15T10:30:00Z',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '2',
|
|
||||||
status: 'approved',
|
|
||||||
note: 'Approved',
|
|
||||||
card_type: 'HUMO',
|
|
||||||
card_number: '9860123456789012',
|
|
||||||
card_expiry_month: '05',
|
|
||||||
card_expiry_year: '27',
|
|
||||||
province_id: '2',
|
|
||||||
branch_id: '3',
|
|
||||||
province_name: 'Samarqand',
|
|
||||||
branch_name: 'Filial 3',
|
|
||||||
first_name: 'Bobur',
|
|
||||||
last_name: 'Karimov',
|
|
||||||
middle_name: 'Rustamovich',
|
|
||||||
birth_date: '1985-08-22',
|
|
||||||
phone: '+998907654321',
|
|
||||||
passport_series: 'AB',
|
|
||||||
passport_number: '7654321',
|
|
||||||
created_at: '2025-02-20T14:00:00Z',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '3',
|
|
||||||
status: 'rejected',
|
|
||||||
note: 'Hujjatlar not\'g\'ri',
|
|
||||||
card_type: 'VISA',
|
|
||||||
card_number: '4400123456789012',
|
|
||||||
card_expiry_month: '08',
|
|
||||||
card_expiry_year: '26',
|
|
||||||
province_id: '3',
|
|
||||||
branch_id: '5',
|
|
||||||
province_name: 'Buxoro',
|
|
||||||
branch_name: 'Filial 5',
|
|
||||||
first_name: 'Dilorom',
|
|
||||||
last_name: 'Rahimova',
|
|
||||||
middle_name: 'Shavkatovna',
|
|
||||||
birth_date: '1995-11-02',
|
|
||||||
phone: '+998903334455',
|
|
||||||
passport_series: 'AC',
|
|
||||||
passport_number: '1122334',
|
|
||||||
created_at: '2025-03-10T09:15:00Z',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '4',
|
|
||||||
status: 'pending',
|
|
||||||
note: '',
|
|
||||||
card_type: 'UZCARD',
|
|
||||||
card_number: '5300123456789012',
|
|
||||||
card_expiry_month: '01',
|
|
||||||
card_expiry_year: '30',
|
|
||||||
province_id: '4',
|
|
||||||
branch_id: '7',
|
|
||||||
province_name: 'Farg\'ona',
|
|
||||||
branch_name: 'Filial 7',
|
|
||||||
first_name: 'Elyor',
|
|
||||||
last_name: 'Toshmatov',
|
|
||||||
middle_name: 'Olimovich',
|
|
||||||
birth_date: '2000-03-18',
|
|
||||||
phone: '+998905556677',
|
|
||||||
passport_series: 'KA',
|
|
||||||
passport_number: '9988776',
|
|
||||||
created_at: '2025-04-05T16:45:00Z',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '5',
|
|
||||||
status: 'approved',
|
|
||||||
note: 'Tasdiqlangan',
|
|
||||||
card_type: 'HUMO',
|
|
||||||
card_number: '6200123456789012',
|
|
||||||
card_expiry_month: '03',
|
|
||||||
card_expiry_year: '29',
|
|
||||||
province_id: '5',
|
|
||||||
branch_id: '9',
|
|
||||||
province_name: 'Namangan',
|
|
||||||
branch_name: 'Filial 9',
|
|
||||||
first_name: 'Gulnora',
|
|
||||||
last_name: 'Abdullayeva',
|
|
||||||
middle_name: 'Anvarovna',
|
|
||||||
birth_date: '1992-07-30',
|
|
||||||
phone: '+998908889900',
|
|
||||||
passport_series: 'KB',
|
|
||||||
passport_number: '5566778',
|
|
||||||
created_at: '2025-05-12T11:30:00Z',
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
// ─── API functions ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export const cardRequisitesApi = {
|
export const cardRequisitesApi = {
|
||||||
getAll: async (params?: CardRequisiteListParams): Promise<CardRequisiteListResponse> => {
|
getList: async (params: CardRequisiteListParams = {}, signal?: AbortSignal): Promise<CardRequisiteListResponse> => {
|
||||||
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
|
const { page, limit, status, branch_id, user_id, card_type_id, region } = params;
|
||||||
return { data: MOCK_CARD_REQUISITES, total: MOCK_CARD_REQUISITES.length, page: params?.page || 1, per_page: params?.per_page || 10 }
|
const { data } = await apiClient.get<CardRequisiteListResponse>("/card-rekwizit-orders", {
|
||||||
|
params: {
|
||||||
const { data } = await apiClient.get('/card-requisites', { params })
|
page,
|
||||||
return data
|
limit,
|
||||||
|
status: status || undefined,
|
||||||
|
branch_id: branch_id || undefined,
|
||||||
|
user_id: user_id || undefined,
|
||||||
|
card_type_id: card_type_id || undefined,
|
||||||
|
region: region || undefined,
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
getById: async (id: string): Promise<CardRequisite> => {
|
getById: async (id: number): Promise<CardRequisite> => {
|
||||||
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
|
const { data } = await apiClient.get<CardRequisite>(`/card-rekwizit-orders/${id}`);
|
||||||
const mock = MOCK_CARD_REQUISITES.find(r => r.id === id)
|
return data;
|
||||||
if (mock) return mock
|
|
||||||
|
|
||||||
const { data } = await apiClient.get(`/card-requisites/${id}`)
|
|
||||||
return data
|
|
||||||
},
|
},
|
||||||
|
|
||||||
create: async (payload: CreateCardRequisitePayload): Promise<CardRequisite> => {
|
create: async (payload: CardRequisitePayload): Promise<CardRequisite> => {
|
||||||
const { data } = await apiClient.post('/card-requisites', buildFormData(payload), {
|
const { data } = await apiClient.post<CardRequisite>("/card-rekwizit-orders", payload);
|
||||||
headers: { 'Content-Type': 'multipart/form-data' },
|
return data;
|
||||||
})
|
|
||||||
return data
|
|
||||||
},
|
},
|
||||||
|
|
||||||
update: async (id: string, payload: UpdateCardRequisitePayload): Promise<CardRequisite> => {
|
update: async (id: number, payload: CardRequisitePayload): Promise<CardRequisite> => {
|
||||||
const { data } = await apiClient.post(`/card-requisites/${id}`, buildFormData(payload), {
|
const { data } = await apiClient.put<CardRequisite>(`/card-rekwizit-orders/${id}`, payload);
|
||||||
headers: { 'Content-Type': 'multipart/form-data' },
|
return data;
|
||||||
})
|
|
||||||
return data
|
|
||||||
},
|
},
|
||||||
|
|
||||||
delete: async (id: string): Promise<void> => {
|
delete: async (id: number): Promise<void> => {
|
||||||
await apiClient.delete(`/card-requisites/${id}`)
|
await apiClient.delete(`/card-rekwizit-orders/${id}`);
|
||||||
},
|
},
|
||||||
|
};
|
||||||
download: async (id: string): Promise<Blob> => {
|
|
||||||
const { data } = await apiClient.get(`/card-requisites/${id}/download`, {
|
|
||||||
responseType: 'blob',
|
|
||||||
})
|
|
||||||
return data
|
|
||||||
},
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,96 +1,80 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import { cardRequisitesApi, type CardRequisiteListParams, type CardRequisitePayload } from "../api/cardRequisitesApi";
|
||||||
cardRequisitesApi,
|
|
||||||
type CardRequisiteListParams,
|
|
||||||
type CreateCardRequisitePayload,
|
|
||||||
type UpdateCardRequisitePayload,
|
|
||||||
} from '../api/cardRequisitesApi'
|
|
||||||
|
|
||||||
const QUERY_KEY = 'card-requisites'
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const cardRequisiteKeys = {
|
||||||
|
all: ["cardRequisites"] as const,
|
||||||
|
lists: () => [...cardRequisiteKeys.all, "list"] as const,
|
||||||
|
list: (params: CardRequisiteListParams) => [...cardRequisiteKeys.lists(), params] as const,
|
||||||
|
details: () => [...cardRequisiteKeys.all, "detail"] as const,
|
||||||
|
detail: (id: number) => [...cardRequisiteKeys.details(), id] as const,
|
||||||
|
};
|
||||||
|
|
||||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardRequisites(params?: CardRequisiteListParams) {
|
export function useCardRequisites(params: CardRequisiteListParams = {}) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [QUERY_KEY, params],
|
queryKey: cardRequisiteKeys.list(params),
|
||||||
queryFn: () => cardRequisitesApi.getAll(params),
|
queryFn: ({ signal }) => cardRequisitesApi.getList(params, signal),
|
||||||
})
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardRequisite(id: string) {
|
export function useCardRequisite(id: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [QUERY_KEY, id],
|
queryKey: cardRequisiteKeys.detail(id),
|
||||||
queryFn: () => cardRequisitesApi.getById(id),
|
queryFn: () => cardRequisitesApi.getById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateCardRequisite() {
|
export function useCreateCardRequisite() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateCardRequisitePayload) => cardRequisitesApi.create(payload),
|
mutationFn: (payload: CardRequisitePayload) => cardRequisitesApi.create(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
|
||||||
toast.success(t('Card requisite created successfully', 'Kart rekwiziti üstünlikli döredildi'))
|
toast.success(t("cardRequisites.createSuccess", "Kart rekwiziti üstünlikli döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateCardRequisite(id: string) {
|
export function useUpdateCardRequisite(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateCardRequisitePayload) => cardRequisitesApi.update(id, payload),
|
mutationFn: (payload: CardRequisitePayload) => cardRequisitesApi.update(id, payload),
|
||||||
onSuccess: () => {
|
onSuccess: (updated) => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
|
||||||
toast.success(t('Card requisite updated successfully', 'Kart rekwiziti üstünlikli üýtgedildi'))
|
queryClient.setQueryData(cardRequisiteKeys.detail(id), updated);
|
||||||
|
toast.success(t("cardRequisites.updateSuccess", "Kart rekwiziti üstünlikli üýtgedildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteCardRequisite() {
|
export function useDeleteCardRequisite() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: string) => cardRequisitesApi.delete(id),
|
mutationFn: (id: number) => cardRequisitesApi.delete(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: cardRequisiteKeys.lists() });
|
||||||
toast.success(t('Card requisite deleted successfully', 'Kart rekwiziti üstünlikli öçürildi'))
|
toast.success(t("cardRequisites.deleteSuccess", "Kart rekwiziti üstünlikli öçürildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Download ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useDownloadCardRequisite() {
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async (id: string) => {
|
|
||||||
const blob = await cardRequisitesApi.download(id)
|
|
||||||
const url = URL.createObjectURL(blob)
|
|
||||||
const a = document.createElement('a')
|
|
||||||
a.href = url
|
|
||||||
a.download = `card-requisite-${id}.pdf`
|
|
||||||
a.click()
|
|
||||||
URL.revokeObjectURL(url)
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
@@ -1,23 +1,24 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import type { CardRequisiteStatus, CreateCardRequisitePayload } from "../api/cardRequisitesApi";
|
import type { CardRequisitePayload } from "../api/cardRequisitesApi";
|
||||||
|
|
||||||
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
|
|
||||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||||
|
|
||||||
export const cardRequisiteFormSchema = z.object({
|
export const cardRequisiteFormSchema = z.object({
|
||||||
status: z.string().min(1, "validation.required"),
|
status: z.string().min(1, "validation.required"),
|
||||||
note: z.string().optional(),
|
notes: z.string().optional(),
|
||||||
card_type: z.string().min(1, "validation.required"),
|
region: z.string().min(1, "validation.required"),
|
||||||
card_number: z.string().min(1, "validation.required"),
|
cardTypeId: z.string().min(1, "validation.required"),
|
||||||
card_expiry_month: z.string().min(1, "validation.required"),
|
branchId: z.string().min(1, "validation.required"),
|
||||||
card_expiry_year: z.string().min(1, "validation.required"),
|
userId: z.string().min(1, "validation.required"),
|
||||||
province_id: z.string().min(1, "validation.required"),
|
uniqueId: z.string().optional(),
|
||||||
branch_id: z.string().min(1, "validation.required"),
|
cardNumber: z.string().optional(),
|
||||||
first_name: z.string().min(1, "validation.required"),
|
cardMonth: z.string().optional(),
|
||||||
last_name: z.string().min(1, "validation.required"),
|
cardYear: z.string().optional(),
|
||||||
middle_name: z.string().optional(),
|
customerName: z.string().min(1, "validation.required"),
|
||||||
birth_date: z.string().min(1, "validation.required"),
|
customerSurname: z.string().min(1, "validation.required"),
|
||||||
|
customerPatronicName: z.string().optional(),
|
||||||
|
bornAt: z.string().min(1, "validation.required"),
|
||||||
phone: z
|
phone: z
|
||||||
.string()
|
.string()
|
||||||
.min(1, "validation.required")
|
.min(1, "validation.required")
|
||||||
@@ -36,12 +37,12 @@ export const cardRequisiteFormSchema = z.object({
|
|||||||
},
|
},
|
||||||
{ message: "validation.invalidPhonePrefix" },
|
{ message: "validation.invalidPhonePrefix" },
|
||||||
),
|
),
|
||||||
passport_series: z.string().min(1, "validation.required"),
|
passportSerie: z.string().min(1, "validation.required"),
|
||||||
passport_number: z.string().min(1, "validation.required"),
|
passportId: z.string().min(1, "validation.required"),
|
||||||
passport_page1: z.custom<File | null>().nullable(),
|
passportOne: z.string().optional(),
|
||||||
passport_page2_3: z.custom<File | null>().nullable(),
|
passportTwo: z.string().optional(),
|
||||||
passport_page8_9: z.custom<File | null>().nullable(),
|
passportThree: z.string().optional(),
|
||||||
passport_page32: z.custom<File | null>().nullable(),
|
passportFour: z.string().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type CardRequisiteFormData = z.infer<typeof cardRequisiteFormSchema>;
|
export type CardRequisiteFormData = z.infer<typeof cardRequisiteFormSchema>;
|
||||||
@@ -49,26 +50,30 @@ export type CardRequisiteFormData = z.infer<typeof cardRequisiteFormSchema>;
|
|||||||
export const stepSchemas: Record<number, z.ZodType<Partial<CardRequisiteFormData>>> = {
|
export const stepSchemas: Record<number, z.ZodType<Partial<CardRequisiteFormData>>> = {
|
||||||
0: cardRequisiteFormSchema.pick({
|
0: cardRequisiteFormSchema.pick({
|
||||||
status: true,
|
status: true,
|
||||||
card_type: true,
|
region: true,
|
||||||
card_number: true,
|
cardTypeId: true,
|
||||||
card_expiry_month: true,
|
branchId: true,
|
||||||
card_expiry_year: true,
|
userId: true,
|
||||||
province_id: true,
|
uniqueId: true,
|
||||||
branch_id: true,
|
cardNumber: true,
|
||||||
|
cardMonth: true,
|
||||||
|
cardYear: true,
|
||||||
|
notes: true,
|
||||||
}),
|
}),
|
||||||
1: cardRequisiteFormSchema.pick({
|
1: cardRequisiteFormSchema.pick({
|
||||||
first_name: true,
|
customerName: true,
|
||||||
last_name: true,
|
customerSurname: true,
|
||||||
birth_date: true,
|
customerPatronicName: true,
|
||||||
|
bornAt: true,
|
||||||
phone: true,
|
phone: true,
|
||||||
}),
|
}),
|
||||||
2: z.object({
|
2: cardRequisiteFormSchema.pick({
|
||||||
passport_series: z.string().min(1, "validation.required"),
|
passportSerie: true,
|
||||||
passport_number: z.string().min(1, "validation.required"),
|
passportId: true,
|
||||||
passport_page1: fileRequired,
|
passportOne: true,
|
||||||
passport_page2_3: fileRequired,
|
passportTwo: true,
|
||||||
passport_page8_9: fileRequired,
|
passportThree: true,
|
||||||
passport_page32: fileRequired,
|
passportFour: true,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -76,26 +81,7 @@ function translateMsg(msg: string): string {
|
|||||||
return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function validateStep(
|
export function validateStep(stepIndex: number, form: CardRequisiteFormData): Partial<Record<keyof CardRequisiteFormData, string>> {
|
||||||
stepIndex: number,
|
|
||||||
form: CardRequisiteFormData,
|
|
||||||
mode: "create" | "edit",
|
|
||||||
): Partial<Record<keyof CardRequisiteFormData, string>> {
|
|
||||||
if (stepIndex === 2 && mode === "edit") {
|
|
||||||
const schema = z.object({
|
|
||||||
passport_series: z.string().min(1, "validation.required"),
|
|
||||||
passport_number: z.string().min(1, "validation.required"),
|
|
||||||
});
|
|
||||||
const result = schema.safeParse(form);
|
|
||||||
if (result.success) return {};
|
|
||||||
const errors: Partial<Record<keyof CardRequisiteFormData, string>> = {};
|
|
||||||
for (const issue of result.error.issues) {
|
|
||||||
const key = issue.path[0] as keyof CardRequisiteFormData;
|
|
||||||
if (!errors[key]) errors[key] = translateMsg(issue.message);
|
|
||||||
}
|
|
||||||
return errors;
|
|
||||||
}
|
|
||||||
|
|
||||||
const schema = stepSchemas[stepIndex];
|
const schema = stepSchemas[stepIndex];
|
||||||
if (!schema) return {};
|
if (!schema) return {};
|
||||||
const result = schema.safeParse(form);
|
const result = schema.safeParse(form);
|
||||||
@@ -110,46 +96,50 @@ export function validateStep(
|
|||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CardRequisiteFormData = {
|
export const DEFAULT_FORM_VALUES: CardRequisiteFormData = {
|
||||||
status: "pending",
|
status: "pending",
|
||||||
note: "",
|
notes: "",
|
||||||
card_type: "",
|
region: "",
|
||||||
card_number: "",
|
cardTypeId: "",
|
||||||
card_expiry_month: "",
|
branchId: "",
|
||||||
card_expiry_year: "",
|
userId: "",
|
||||||
province_id: "",
|
uniqueId: "",
|
||||||
branch_id: "",
|
cardNumber: "",
|
||||||
first_name: "",
|
cardMonth: "",
|
||||||
last_name: "",
|
cardYear: "",
|
||||||
middle_name: "",
|
customerName: "",
|
||||||
birth_date: "",
|
customerSurname: "",
|
||||||
|
customerPatronicName: "",
|
||||||
|
bornAt: "",
|
||||||
phone: "",
|
phone: "",
|
||||||
passport_series: "",
|
passportSerie: "",
|
||||||
passport_number: "",
|
passportId: "",
|
||||||
passport_page1: null,
|
passportOne: "",
|
||||||
passport_page2_3: null,
|
passportTwo: "",
|
||||||
passport_page8_9: null,
|
passportThree: "",
|
||||||
passport_page32: null,
|
passportFour: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
export function buildPayload(data: CardRequisiteFormData): CreateCardRequisitePayload {
|
export function buildPayload(data: CardRequisiteFormData): CardRequisitePayload {
|
||||||
return {
|
return {
|
||||||
status: data.status as CardRequisiteStatus,
|
status: data.status,
|
||||||
note: data.note || undefined,
|
notes: data.notes || "",
|
||||||
card_type: data.card_type,
|
region: data.region,
|
||||||
card_number: data.card_number,
|
cardTypeId: Number(data.cardTypeId),
|
||||||
card_expiry_month: data.card_expiry_month,
|
branchId: Number(data.branchId),
|
||||||
card_expiry_year: data.card_expiry_year,
|
userId: Number(data.userId),
|
||||||
province_id: data.province_id,
|
customerName: data.customerName,
|
||||||
branch_id: data.branch_id,
|
customerSurname: data.customerSurname,
|
||||||
first_name: data.first_name,
|
customerPatronicName: data.customerPatronicName || "",
|
||||||
last_name: data.last_name,
|
bornAt: data.bornAt,
|
||||||
middle_name: data.middle_name || undefined,
|
|
||||||
birth_date: data.birth_date,
|
|
||||||
phone: data.phone,
|
phone: data.phone,
|
||||||
passport_series: data.passport_series,
|
passportSerie: data.passportSerie,
|
||||||
passport_number: data.passport_number,
|
passportId: data.passportId,
|
||||||
...(data.passport_page1 && { passport_page1: data.passport_page1 }),
|
passportOne: data.passportOne || "",
|
||||||
...(data.passport_page2_3 && { passport_page2_3: data.passport_page2_3 }),
|
passportTwo: data.passportTwo || "",
|
||||||
...(data.passport_page8_9 && { passport_page8_9: data.passport_page8_9 }),
|
passportThree: data.passportThree || "",
|
||||||
...(data.passport_page32 && { passport_page32: data.passport_page32 }),
|
passportFour: data.passportFour || "",
|
||||||
|
uniqueId: data.uniqueId || "",
|
||||||
|
cardNumber: data.cardNumber || "",
|
||||||
|
cardMonth: data.cardMonth || "",
|
||||||
|
cardYear: data.cardYear || "",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,120 +1,88 @@
|
|||||||
import apiClient from '@/lib/api/client'
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface CardTransaction {
|
export interface CardTypeInfo {
|
||||||
id: number
|
id: number;
|
||||||
passport_series: string
|
name:
|
||||||
passport_number: string
|
| {
|
||||||
card_number: string
|
en?: string;
|
||||||
card_expiry_month: string
|
ru?: string;
|
||||||
card_expiry_year: string
|
tm?: string;
|
||||||
|
}
|
||||||
|
| string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CardTransactionListResponse {
|
export interface Card {
|
||||||
data: CardTransaction[]
|
id: number;
|
||||||
total: number
|
user: { id: number; name: string; username: string; phone: string; email: string } | null;
|
||||||
page: number
|
number: string;
|
||||||
per_page: number
|
name: string;
|
||||||
|
month: string;
|
||||||
|
year: string;
|
||||||
|
type?: string;
|
||||||
|
cardType?: CardTypeInfo | null;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateCardTransactionPayload {
|
export interface CardListResponse {
|
||||||
passport_series: string
|
count: number;
|
||||||
passport_number: string
|
cards: Card[];
|
||||||
card_number: string
|
|
||||||
card_expiry_month: string
|
|
||||||
card_expiry_year: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type UpdateCardTransactionPayload = CreateCardTransactionPayload
|
export interface CreateCardPayload {
|
||||||
|
month: string;
|
||||||
|
name: string;
|
||||||
|
number: string;
|
||||||
|
type: string;
|
||||||
|
userId: number;
|
||||||
|
year: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CardTransactionListParams {
|
export type UpdateCardPayload = CreateCardPayload;
|
||||||
page?: number
|
|
||||||
per_page?: number
|
export interface CardListParams {
|
||||||
search?: string
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
search?: string;
|
||||||
|
user_id?: number;
|
||||||
|
type?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── API functions ────────────────────────────────────────────────────────────
|
// ─── API functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const MOCK_CARD_TRANSACTIONS: CardTransaction[] = [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
passport_series: 'AA',
|
|
||||||
passport_number: '1234567',
|
|
||||||
card_number: '8600123456789012',
|
|
||||||
card_expiry_month: '12',
|
|
||||||
card_expiry_year: '28',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
passport_series: 'AB',
|
|
||||||
passport_number: '7654321',
|
|
||||||
card_number: '9860123456789012',
|
|
||||||
card_expiry_month: '05',
|
|
||||||
card_expiry_year: '27',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 3,
|
|
||||||
passport_series: 'AC',
|
|
||||||
passport_number: '1122334',
|
|
||||||
card_number: '4400123456789012',
|
|
||||||
card_expiry_month: '08',
|
|
||||||
card_expiry_year: '26',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 4,
|
|
||||||
passport_series: 'KA',
|
|
||||||
passport_number: '9988776',
|
|
||||||
card_number: '5300123456789012',
|
|
||||||
card_expiry_month: '01',
|
|
||||||
card_expiry_year: '30',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 5,
|
|
||||||
passport_series: 'KB',
|
|
||||||
passport_number: '5566778',
|
|
||||||
card_number: '6200123456789012',
|
|
||||||
card_expiry_month: '03',
|
|
||||||
card_expiry_year: '29',
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
export const cardTransactionsApi = {
|
export const cardTransactionsApi = {
|
||||||
getAll: async (params?: CardTransactionListParams): Promise<CardTransactionListResponse> => {
|
/** GET /cards */
|
||||||
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
|
getAll: async (params: CardListParams = {}, signal?: AbortSignal): Promise<CardListResponse> => {
|
||||||
return { data: MOCK_CARD_TRANSACTIONS, total: MOCK_CARD_TRANSACTIONS.length, page: params?.page || 1, per_page: params?.per_page || 10 }
|
const { page, limit, search, user_id, type } = params;
|
||||||
|
const { data } = await apiClient.get<CardListResponse>("/cards", {
|
||||||
const { data } = await apiClient.get('/card-transactions', { params })
|
params: { page, limit, search, user_id, type },
|
||||||
return data
|
signal,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
getById: async (id: number): Promise<CardTransaction> => {
|
/** GET /cards/:id */
|
||||||
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
|
getById: async (id: number): Promise<Card> => {
|
||||||
const mock = MOCK_CARD_TRANSACTIONS.find(t => t.id === id)
|
const { data } = await apiClient.get<Card>(`/cards/${id}`);
|
||||||
if (mock) return mock
|
return data;
|
||||||
|
|
||||||
const { data } = await apiClient.get(`/card-transactions/${id}`)
|
|
||||||
return data
|
|
||||||
},
|
},
|
||||||
|
|
||||||
create: async (payload: CreateCardTransactionPayload): Promise<CardTransaction> => {
|
/** POST /cards */
|
||||||
const { data } = await apiClient.post('/card-transactions', payload)
|
create: async (payload: CreateCardPayload): Promise<Card> => {
|
||||||
return data
|
const { data } = await apiClient.post<Card>("/cards", payload);
|
||||||
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
update: async (id: number, payload: UpdateCardTransactionPayload): Promise<CardTransaction> => {
|
/** PUT /cards/:id */
|
||||||
const { data } = await apiClient.put(`/card-transactions/${id}`, payload)
|
update: async (id: number, payload: UpdateCardPayload): Promise<Card> => {
|
||||||
return data
|
const { data } = await apiClient.put<Card>(`/cards/${id}`, payload);
|
||||||
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/** DELETE /cards/:id */
|
||||||
delete: async (id: number): Promise<void> => {
|
delete: async (id: number): Promise<void> => {
|
||||||
await apiClient.delete(`/card-transactions/${id}`)
|
await apiClient.delete(`/cards/${id}`);
|
||||||
},
|
},
|
||||||
|
};
|
||||||
download: async (id: number): Promise<Blob> => {
|
|
||||||
const { data } = await apiClient.get(`/card-transactions/${id}/download`, {
|
|
||||||
responseType: 'blob',
|
|
||||||
})
|
|
||||||
return data
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,46 +1,34 @@
|
|||||||
import { useMemo } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { FormInput } from "@/components/formInput";
|
import { FormInput } from "@/components/formInput";
|
||||||
import { FormActions } from "@/components/formActions";
|
import { FormActions } from "@/components/formActions";
|
||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import type { CardTransaction } from "../api/cardTransactionsApi";
|
import { InfiniteSelect, type InfiniteSelectOption } from "@/components/infiniteSelect";
|
||||||
|
import type { Card } from "../api/cardTransactionsApi";
|
||||||
import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions";
|
import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions";
|
||||||
|
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||||
|
import { useWebSelfLock } from "@/features/shared/hooks/useWebSelfLock";
|
||||||
|
import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||||
|
import { resolveCardTypeTitle, type LocalizedTitle } from "@/features/cardTypes/api/cardTypesApi";
|
||||||
import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema";
|
import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema";
|
||||||
import type { CardTransactionFormData } from "../schemas/cardTransaction.schema";
|
import type { CardTransactionFormData } from "../schemas/cardTransaction.schema";
|
||||||
|
import { MONTH_OPTIONS, CARD_YEAR_OPTIONS } from "@/constants";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
interface CardTransactionFormProps {
|
interface CardTransactionFormProps {
|
||||||
mode: "create" | "edit";
|
mode: "create" | "edit";
|
||||||
initialData?: CardTransaction;
|
initialData?: Card;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const PASSPORT_SERIES_OPTIONS = [
|
|
||||||
{ value: "I-LB", label: "I-LB" },
|
|
||||||
{ value: "II-LB", label: "II-LB" },
|
|
||||||
{ value: "III-LB", label: "III-LB" },
|
|
||||||
{ value: "A", label: "A" },
|
|
||||||
{ value: "B", label: "B" },
|
|
||||||
];
|
|
||||||
|
|
||||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
|
|
||||||
const val = String(i + 1).padStart(2, "0");
|
|
||||||
return { value: val, label: val };
|
|
||||||
});
|
|
||||||
|
|
||||||
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
|
||||||
const year = String(new Date().getFullYear() + i);
|
|
||||||
return { value: year, label: year };
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── Form errors helper ───────────────────────────────────────────────────────
|
// ─── Form errors helper ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
type FlatErrors = Partial<Record<keyof CardTransactionFormData, string>>;
|
type FlatErrors = Partial<Record<keyof CardTransactionFormData, string>>;
|
||||||
|
|
||||||
|
type CardiacTransactionLoose = Partial<Record<keyof CardTransactionFormData, string>>;
|
||||||
|
|
||||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||||
const result: FlatErrors = {};
|
const result: FlatErrors = {};
|
||||||
for (const key of Object.keys(errors)) {
|
for (const key of Object.keys(errors)) {
|
||||||
@@ -53,9 +41,48 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
|||||||
// ─── Component ────────────────────────────────────────────────────────────────
|
// ─── Component ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) {
|
export function CardTransactionForm({ mode, initialData }: CardTransactionFormProps) {
|
||||||
const { t } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const { locked: userLocked, userId: selfUserId, userName } = useWebSelfLock(true);
|
||||||
|
|
||||||
|
const [clientSearch, setClientSearch] = useState("");
|
||||||
|
const clientsQuery = useInfiniteClients(clientSearch, !userLocked);
|
||||||
|
const { data: cardTypesData } = useCardTypes({ page: 1, limit: 25 });
|
||||||
|
|
||||||
|
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedTitle;
|
||||||
|
|
||||||
|
const clientOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||||
|
const opts: InfiniteSelectOption[] = (clientsQuery.data?.pages ?? [])
|
||||||
|
.flatMap((p) => p?.users ?? [])
|
||||||
|
.map((u) => ({
|
||||||
|
value: String(u.id),
|
||||||
|
label: u.name || `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || String(u.id),
|
||||||
|
}))
|
||||||
|
.filter((o) => !userLocked || o.value === selfUserId);
|
||||||
|
|
||||||
|
if (selfUserId && !opts.some((o) => o.value === selfUserId)) {
|
||||||
|
opts.unshift({ value: selfUserId, label: userName });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (initialData?.user?.id && !opts.some((o) => o.value === String(initialData.user!.id))) {
|
||||||
|
opts.unshift({ value: String(initialData.user!.id), label: initialData.user!.name || String(initialData.user!.id) });
|
||||||
|
}
|
||||||
|
return opts;
|
||||||
|
}, [clientsQuery.data, initialData, userLocked, selfUserId, userName]);
|
||||||
|
|
||||||
|
const cardTypeOptions = useMemo(() => {
|
||||||
|
const opts = (cardTypesData?.paymentCards ?? []).map((ct) => ({
|
||||||
|
value: String(ct.id),
|
||||||
|
label: resolveCardTypeTitle(ct.title, lang),
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (initialData?.type && !opts.some((o) => o.value === initialData.type)) {
|
||||||
|
opts.unshift({ value: initialData.type, label: initialData.type });
|
||||||
|
}
|
||||||
|
return opts;
|
||||||
|
}, [cardTypesData, lang, initialData]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -64,11 +91,46 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
|||||||
clearErrors,
|
clearErrors,
|
||||||
setError,
|
setError,
|
||||||
} = useForm<CardTransactionFormData>({
|
} = useForm<CardTransactionFormData>({
|
||||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES,
|
defaultValues: initialData
|
||||||
|
? {
|
||||||
|
...DEFAULT_FORM_VALUES,
|
||||||
|
number: initialData.number ?? "",
|
||||||
|
name: initialData.name ?? "",
|
||||||
|
type: initialData.type ?? "",
|
||||||
|
month: initialData.month ?? "",
|
||||||
|
year: initialData.year ?? "",
|
||||||
|
userId: userLocked ? selfUserId : String(initialData.user?.id ?? ""),
|
||||||
|
}
|
||||||
|
: { ...DEFAULT_FORM_VALUES, userId: selfUserId },
|
||||||
});
|
});
|
||||||
|
|
||||||
const form = watch();
|
const form = watch();
|
||||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
|
||||||
|
// Live schema errors, only surfaced once the user attempts to submit, so
|
||||||
|
// required-field warnings reliably show under fields (avoids RHF setError
|
||||||
|
// snapshot timing; mirrors the step-based forms' submitted validation).
|
||||||
|
const [submitAttempted, setSubmitAttempted] = useState(false);
|
||||||
|
|
||||||
|
const liveErrors = useMemo<FlatErrors>(() => {
|
||||||
|
if (!submitAttempted) return {};
|
||||||
|
const normalized: CardiacTransactionLoose = { ...DEFAULT_FORM_VALUES, ...form };
|
||||||
|
for (const key of Object.keys(DEFAULT_FORM_VALUES) as (keyof CardTransactionFormData)[]) {
|
||||||
|
if (normalized[key] == null) normalized[key] = "";
|
||||||
|
}
|
||||||
|
const parsed = cardTransactionFormSchema.safeParse(normalized);
|
||||||
|
if (parsed.success) return {};
|
||||||
|
const result: FlatErrors = {};
|
||||||
|
for (const issue of parsed.error.issues) {
|
||||||
|
const key = issue.path[0] as keyof CardTransactionFormData;
|
||||||
|
result[key] = issue.message;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}, [submitAttempted, form]);
|
||||||
|
|
||||||
|
const errors = useMemo(() => {
|
||||||
|
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||||
|
return { ...fromRHF, ...liveErrors };
|
||||||
|
}, [rhfErrors, liveErrors]);
|
||||||
|
|
||||||
const createMutation = useCreateCardTransaction();
|
const createMutation = useCreateCardTransaction();
|
||||||
const updateMutation = useUpdateCardTransaction(initialData?.id ?? 0);
|
const updateMutation = useUpdateCardTransaction(initialData?.id ?? 0);
|
||||||
@@ -83,8 +145,13 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
|||||||
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const result = cardTransactionFormSchema.safeParse(getValues());
|
const raw: CardiacTransactionLoose = { ...DEFAULT_FORM_VALUES, ...getValues() };
|
||||||
|
for (const key of Object.keys(DEFAULT_FORM_VALUES) as (keyof CardTransactionFormData)[]) {
|
||||||
|
if (raw[key] == null) raw[key] = "";
|
||||||
|
}
|
||||||
|
const result = cardTransactionFormSchema.safeParse(raw);
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
|
setSubmitAttempted(true);
|
||||||
for (const issue of result.error.issues) {
|
for (const issue of result.error.issues) {
|
||||||
const key = issue.path[0] as keyof CardTransactionFormData;
|
const key = issue.path[0] as keyof CardTransactionFormData;
|
||||||
setError(key, { message: issue.message });
|
setError(key, { message: issue.message });
|
||||||
@@ -112,68 +179,84 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
|||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === "create"
|
{mode === "create" ? t("cardTransaction.createTitle", "Kart dörediň") : t("cardTransaction.editTitle", "Karty üýtgetmek")}
|
||||||
? t("cardTransaction.createTitle", "Kart herekedi dörediň")
|
|
||||||
: t("cardTransaction.editTitle", "Kart herekedi üýtgetmek")}
|
|
||||||
</h1>
|
</h1>
|
||||||
<BentoGrid cols={1}>
|
<BentoGrid cols={1}>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
{/* Passport Series */}
|
{/* Name */}
|
||||||
<FormInput
|
<FormInput
|
||||||
type="searchable-select"
|
type="card-name"
|
||||||
label={t("Passport series", "Pasport seriýasy")}
|
label={t("Card name", "Kartyň ady")}
|
||||||
value={form.passport_series}
|
value={form.name}
|
||||||
onChange={setField("passport_series")}
|
onChange={setField("name")}
|
||||||
options={PASSPORT_SERIES_OPTIONS}
|
placeholder={t("Card name", "Kartyň ady")}
|
||||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
error={errMsg(errors.name)}
|
||||||
error={errMsg(errors.passport_series)}
|
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Passport Number */}
|
{/* Type */}
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="searchable-select"
|
||||||
label={t("Passport number", "Pasport belgisi")}
|
label={t("Card type", "Kart görnüşi")}
|
||||||
value={form.passport_number}
|
value={form.type}
|
||||||
onChange={setField("passport_number")}
|
onChange={setField("type")}
|
||||||
placeholder={t("Passport number", "Pasport belgisi")}
|
options={cardTypeOptions}
|
||||||
error={errMsg(errors.passport_number)}
|
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||||
|
error={errMsg(errors.type)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Card Number */}
|
{/* Card Number */}
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="card-number"
|
||||||
label={t("Card number", "Kart belgisi")}
|
label={t("Card number", "Kart belgisi")}
|
||||||
value={form.card_number}
|
value={form.number}
|
||||||
onChange={setField("card_number")}
|
onChange={setField("number")}
|
||||||
placeholder={t("Card number", "Kart belgisi")}
|
placeholder="9999 9999 9999 9999"
|
||||||
error={errMsg(errors.card_number)}
|
error={errMsg(errors.number)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* User (Client) */}
|
||||||
|
<InfiniteSelect
|
||||||
|
label={t("User ID", "Ulanyjy ID")}
|
||||||
|
required
|
||||||
|
value={form.userId}
|
||||||
|
onChange={(v) => setField("userId")(v)}
|
||||||
|
options={clientOptions}
|
||||||
|
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||||
|
error={errMsg(errors.userId)}
|
||||||
|
disabled={userLocked}
|
||||||
|
loading={clientsQuery.isLoading}
|
||||||
|
isLoadingMore={clientsQuery.isFetchingNextPage}
|
||||||
|
hasNextPage={!!clientsQuery.hasNextPage}
|
||||||
|
onLoadMore={() => clientsQuery.fetchNextPage()}
|
||||||
|
searchValue={clientSearch}
|
||||||
|
onSearchChange={setClientSearch}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Expiry Month + Year side by side */}
|
{/* Expiry Month + Year side by side */}
|
||||||
<div className="grid grid-cols-2 gap-3">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
label={t("Card expiry month", "Kart Möhleti (aý)")}
|
label={t("Card expiry month", "Kart möhleti (aý)")}
|
||||||
value={form.card_expiry_month}
|
value={form.month}
|
||||||
onChange={setField("card_expiry_month")}
|
onChange={setField("month")}
|
||||||
options={MONTH_OPTIONS}
|
options={MONTH_OPTIONS}
|
||||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||||
error={errMsg(errors.card_expiry_month)}
|
error={errMsg(errors.month)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="select"
|
type="select"
|
||||||
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
label={t("Card expiry year", "Kart möhleti (ýyl)")}
|
||||||
value={form.card_expiry_year}
|
value={form.year}
|
||||||
onChange={setField("card_expiry_year")}
|
onChange={setField("year")}
|
||||||
options={YEAR_OPTIONS}
|
options={CARD_YEAR_OPTIONS}
|
||||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||||
error={errMsg(errors.card_expiry_year)}
|
error={errMsg(errors.year)}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -183,12 +266,9 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
|||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
onCancel={handleCancel}
|
onCancel={handleCancel}
|
||||||
cancelVariant="ghost"
|
|
||||||
cancelLabel={t("Cancel", "Ýatyr")}
|
cancelLabel={t("Cancel", "Ýatyr")}
|
||||||
loadingLabel={t("Saving...", "Saklanýar...")}
|
loadingLabel={t("Saving...", "Saklanýar...")}
|
||||||
submitLabel={
|
submitLabel={mode === "create" ? t("Create card", "Kart dörediň") : t("Save changes", "Üýtgetmeleri sakla")}
|
||||||
mode === "create" ? t("Create card transaction", "Kart herekedi dörediň") : t("Save changes", "Üýtgetmeleri sakla")
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|||||||
@@ -1,98 +1,76 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
cardTransactionsApi,
|
import { cardTransactionsApi, type CardListParams, type CreateCardPayload, type UpdateCardPayload } from "../api/cardTransactionsApi";
|
||||||
type CardTransactionListParams,
|
|
||||||
type CreateCardTransactionPayload,
|
|
||||||
type UpdateCardTransactionPayload,
|
|
||||||
} from '../api/cardTransactionsApi'
|
|
||||||
|
|
||||||
const QUERY_KEY = 'card-transactions'
|
const QUERY_KEY = "cards";
|
||||||
|
|
||||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardTransactions(params?: CardTransactionListParams) {
|
export function useCardTransactions(params?: CardListParams) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params?.search ?? "");
|
||||||
|
const normalized = normalizeSearch(debouncedSearch);
|
||||||
|
const queryParams: CardListParams = { ...(params ?? {}), search: normalized || undefined };
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [QUERY_KEY, params],
|
queryKey: [QUERY_KEY, "list", queryParams],
|
||||||
queryFn: () => cardTransactionsApi.getAll(params),
|
queryFn: ({ signal }) => cardTransactionsApi.getAll(queryParams, signal),
|
||||||
})
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardTransaction(id: number) {
|
export function useCardTransaction(id: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [QUERY_KEY, id],
|
queryKey: [QUERY_KEY, "detail", id],
|
||||||
queryFn: () => cardTransactionsApi.getById(id),
|
queryFn: () => cardTransactionsApi.getById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateCardTransaction() {
|
export function useCreateCardTransaction() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateCardTransactionPayload) =>
|
mutationFn: (payload: CreateCardPayload) => cardTransactionsApi.create(payload),
|
||||||
cardTransactionsApi.create(payload),
|
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
|
||||||
toast.success(t('Card transaction created successfully', 'Kart herekedi üstünlikli döredildi'))
|
toast.success(t("Card transaction created successfully", "Kart üstünlikli döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateCardTransaction(id: number) {
|
export function useUpdateCardTransaction(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateCardTransactionPayload) =>
|
mutationFn: (payload: UpdateCardPayload) => cardTransactionsApi.update(id, payload),
|
||||||
cardTransactionsApi.update(id, payload),
|
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
|
||||||
toast.success(t('Card transaction updated successfully', 'Kart herekedi üstünlikli üýtgedildi'))
|
toast.success(t("Card transaction updated successfully", "Kart üstünlikli üýtgedildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteCardTransaction() {
|
export function useDeleteCardTransaction() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => cardTransactionsApi.delete(id),
|
mutationFn: (id: number) => cardTransactionsApi.delete(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
|
||||||
toast.success(t('Card transaction deleted successfully', 'Kart herekedi üstünlikli öçürildi'))
|
toast.success(t("Card transaction deleted successfully", "Kart üstünlikli öçürildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Download ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useDownloadCardTransaction() {
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async (id: number) => {
|
|
||||||
const blob = await cardTransactionsApi.download(id)
|
|
||||||
const url = URL.createObjectURL(blob)
|
|
||||||
const a = document.createElement('a')
|
|
||||||
a.href = url
|
|
||||||
a.download = `card-transaction-${id}.pdf`
|
|
||||||
a.click()
|
|
||||||
URL.revokeObjectURL(url)
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
@@ -1,30 +1,33 @@
|
|||||||
import { z } from 'zod'
|
import { z } from "zod";
|
||||||
import type { CreateCardTransactionPayload } from '../api/cardTransactionsApi'
|
import type { CreateCardPayload } from "../api/cardTransactionsApi";
|
||||||
|
|
||||||
export const cardTransactionFormSchema = z.object({
|
export const cardTransactionFormSchema = z.object({
|
||||||
passport_series: z.string().min(1, 'validation.required'),
|
number: z.string().min(1, "validation.required"),
|
||||||
passport_number: z.string().min(1, 'validation.required'),
|
name: z.string().min(1, "validation.required"),
|
||||||
card_number: z.string().min(1, 'validation.required'),
|
type: z.string().min(1, "validation.required"),
|
||||||
card_expiry_month: z.string().min(1, 'validation.required'),
|
month: z.string().min(1, "validation.required"),
|
||||||
card_expiry_year: z.string().min(1, 'validation.required'),
|
year: z.string().min(1, "validation.required"),
|
||||||
})
|
userId: z.string().min(1, "validation.required"),
|
||||||
|
});
|
||||||
|
|
||||||
export type CardTransactionFormData = z.infer<typeof cardTransactionFormSchema>
|
export type CardTransactionFormData = z.infer<typeof cardTransactionFormSchema>;
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CardTransactionFormData = {
|
export const DEFAULT_FORM_VALUES: CardTransactionFormData = {
|
||||||
passport_series: '',
|
number: "",
|
||||||
passport_number: '',
|
name: "",
|
||||||
card_number: '',
|
type: "",
|
||||||
card_expiry_month: '',
|
month: "",
|
||||||
card_expiry_year: '',
|
year: "",
|
||||||
}
|
userId: "",
|
||||||
|
};
|
||||||
|
|
||||||
export function buildPayload(data: CardTransactionFormData): CreateCardTransactionPayload {
|
export function buildPayload(data: CardTransactionFormData): CreateCardPayload {
|
||||||
return {
|
return {
|
||||||
passport_series: data.passport_series,
|
number: data.number,
|
||||||
passport_number: data.passport_number,
|
name: data.name,
|
||||||
card_number: data.card_number,
|
type: data.type,
|
||||||
card_expiry_month: data.card_expiry_month,
|
month: data.month,
|
||||||
card_expiry_year: data.card_expiry_year,
|
year: data.year,
|
||||||
}
|
userId: Number(data.userId),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -1,107 +1,87 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface LocalizedTitle {
|
||||||
|
tm?: string;
|
||||||
|
ru?: string;
|
||||||
|
en?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LocalizedCardTypeTitle = string | LocalizedTitle;
|
||||||
|
|
||||||
|
export function resolveCardTypeTitle(val: LocalizedCardTypeTitle | null | undefined, lang = "tm"): string {
|
||||||
|
if (!val) return "";
|
||||||
|
if (typeof val === "string") return val;
|
||||||
|
const key = (lang === "tk" ? "tm" : lang) as keyof LocalizedTitle;
|
||||||
|
return val[key] ?? val.tm ?? val.en ?? val.ru ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
export interface CardType {
|
export interface CardType {
|
||||||
id: number
|
id: number;
|
||||||
name: Record<'tk' | 'ru' | 'en', string>
|
price: string;
|
||||||
value: number
|
title: LocalizedCardTypeTitle;
|
||||||
description: string | null
|
notes: string;
|
||||||
isActive: boolean
|
active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CardTypeListParams {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
search?: string;
|
||||||
|
isActive?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CardTypeListResponse {
|
export interface CardTypeListResponse {
|
||||||
data: CardType[]
|
count: number;
|
||||||
total: number
|
paymentCards: CardType[];
|
||||||
page: number
|
|
||||||
perPage: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateCardTypePayload {
|
export interface CreateCardTypePayload {
|
||||||
name: Record<'tk' | 'ru' | 'en', string>
|
active: boolean;
|
||||||
value: number
|
notes: string;
|
||||||
description: string | null
|
price: string;
|
||||||
isActive: boolean
|
title: LocalizedTitle;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateCardTypePayload extends CreateCardTypePayload {
|
export type UpdateCardTypePayload = CreateCardTypePayload;
|
||||||
id: number
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Mock Store ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const MOCK_CARD_TYPES: CardType[] = [
|
|
||||||
{ id: 1, name: { tk: 'Altyn Asyr', ru: 'Алтын Асыр', en: 'Altyn Asyr' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 2, name: { tk: 'Maşgala', ru: 'Семья', en: 'Family' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 3, name: { tk: 'Goýum', ru: 'Депозит', en: 'Deposit' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 4, name: { tk: 'Pensiýa', ru: 'Пенсия', en: 'Pension' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 5, name: { tk: 'Telekeçi', ru: 'Предприниматель', en: 'Entrepreneur' }, value: 32, description: null, isActive: true },
|
|
||||||
{ id: 6, name: { tk: 'Karz', ru: 'Кредит', en: 'Credit' }, value: 32, description: null, isActive: false },
|
|
||||||
{ id: 7, name: { tk: 'Owerdraft', ru: 'Овердрафт', en: 'Overdraft' }, value: 32, description: null, isActive: true },
|
|
||||||
]
|
|
||||||
|
|
||||||
let mockStore = [...MOCK_CARD_TYPES]
|
|
||||||
let nextId = 8
|
|
||||||
|
|
||||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
|
||||||
|
|
||||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export async function fetchCardTypes(params: {
|
export async function fetchCardTypes(params: CardTypeListParams = {}, signal?: AbortSignal): Promise<CardTypeListResponse> {
|
||||||
page?: number
|
const { page, limit, search, isActive } = params;
|
||||||
perPage?: number
|
const { data } = await apiClient.get<CardTypeListResponse>("/payment-cards", {
|
||||||
search?: string
|
params: {
|
||||||
isActive?: string
|
page,
|
||||||
}): Promise<CardTypeListResponse> {
|
limit,
|
||||||
await delay()
|
card_name: search || undefined,
|
||||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
active: isActive || undefined,
|
||||||
|
},
|
||||||
let filtered = mockStore.filter((item) => {
|
signal,
|
||||||
const matchSearch =
|
});
|
||||||
!search ||
|
return data;
|
||||||
Object.values(item.name).some((n) =>
|
|
||||||
n.toLowerCase().includes(search.toLowerCase())
|
|
||||||
)
|
|
||||||
const matchActive =
|
|
||||||
isActive === '' || isActive === undefined
|
|
||||||
? true
|
|
||||||
: isActive === 'true'
|
|
||||||
? item.isActive
|
|
||||||
: !item.isActive
|
|
||||||
return matchSearch && matchActive
|
|
||||||
})
|
|
||||||
|
|
||||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
|
||||||
|
|
||||||
const total = filtered.length
|
|
||||||
const start = (page - 1) * perPage
|
|
||||||
const data = filtered.slice(start, start + perPage)
|
|
||||||
|
|
||||||
return { data, total, page, perPage }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchCardTypeById(id: number): Promise<CardType> {
|
export async function fetchCardTypeById(id: number): Promise<CardType> {
|
||||||
await delay()
|
const { data } = await apiClient.get<CardType>(`/payment-cards/${id}`);
|
||||||
const item = mockStore.find((c) => c.id === id)
|
return data;
|
||||||
if (!item) throw new Error('Not found')
|
|
||||||
return { ...item }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createCardType(payload: CreateCardTypePayload): Promise<CardType> {
|
export async function createCardType(payload: CreateCardTypePayload): Promise<CardType> {
|
||||||
await delay(400)
|
const { data } = await apiClient.post<CardType>("/payment-cards", payload);
|
||||||
const newItem: CardType = { id: nextId++, ...payload }
|
return data;
|
||||||
mockStore = [newItem, ...mockStore]
|
|
||||||
return newItem
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateCardType(payload: UpdateCardTypePayload): Promise<CardType> {
|
export async function updateCardType(id: number, payload: UpdateCardTypePayload): Promise<CardType> {
|
||||||
await delay(400)
|
const { data } = await apiClient.put<CardType>(`/payment-cards/${id}`, payload);
|
||||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
return data;
|
||||||
if (idx === -1) throw new Error('Not found')
|
|
||||||
const updated = { ...mockStore[idx], ...payload }
|
|
||||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
|
||||||
return updated
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteCardType(id: number): Promise<void> {
|
export async function deleteCardType(id: number): Promise<void> {
|
||||||
await delay(300)
|
await apiClient.delete(`/payment-cards/${id}`);
|
||||||
mockStore = mockStore.filter((c) => c.id !== id)
|
}
|
||||||
}
|
|
||||||
|
export async function updateCardTypeActive(id: number, active: boolean): Promise<CardType> {
|
||||||
|
const { data } = await apiClient.put<CardType>(`/payment-cards/${id}/active`, { active });
|
||||||
|
return data;
|
||||||
|
}
|
||||||
@@ -10,7 +10,7 @@ import { MultiLangInput } from "@/components/multiLangInput";
|
|||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import type { CardType } from "../api/cardTypesApi";
|
import type { CardType } from "../api/cardTypesApi";
|
||||||
import { useCreateCardType, useUpdateCardType } from "../hooks/useCardTypes";
|
import { useCreateCardType, useUpdateCardType } from "../hooks/useCardTypes";
|
||||||
import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardType.schema";
|
import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from "../schemas/cardType.schema";
|
||||||
import type { CardTypeFormData } from "../schemas/cardType.schema";
|
import type { CardTypeFormData } from "../schemas/cardType.schema";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
@@ -20,19 +20,6 @@ export interface CardTypeFormProps {
|
|||||||
initialData?: CardType;
|
initialData?: CardType;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function mapInitial(data: CardType): CardTypeFormData {
|
|
||||||
return {
|
|
||||||
nameTk: data.name.tk,
|
|
||||||
nameRu: data.name.ru,
|
|
||||||
nameEn: data.name.en,
|
|
||||||
value: String(data.value),
|
|
||||||
description: data.description ?? "",
|
|
||||||
isActive: data.isActive,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
type FlatErrors = Partial<Record<keyof CardTypeFormData, string>>;
|
type FlatErrors = Partial<Record<keyof CardTypeFormData, string>>;
|
||||||
|
|
||||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||||
@@ -55,7 +42,7 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const createMutation = useCreateCardType();
|
const createMutation = useCreateCardType();
|
||||||
const updateMutation = useUpdateCardType();
|
const updateMutation = useUpdateCardType(initialData?.id ?? 0);
|
||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
@@ -76,6 +63,12 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
|||||||
const form = watch();
|
const form = watch();
|
||||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||||
|
|
||||||
|
// ── Re-validate on language change ──
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [i18n.language]);
|
||||||
|
|
||||||
const set = useCallback(
|
const set = useCallback(
|
||||||
(key: keyof CardTypeFormData) => (value: string | boolean) => {
|
(key: keyof CardTypeFormData) => (value: string | boolean) => {
|
||||||
(setValue as (k: keyof CardTypeFormData, v: string | boolean) => void)(key, value);
|
(setValue as (k: keyof CardTypeFormData, v: string | boolean) => void)(key, value);
|
||||||
@@ -84,26 +77,22 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
|||||||
[setValue, clearErrors],
|
[setValue, clearErrors],
|
||||||
);
|
);
|
||||||
|
|
||||||
// ── Re-validate on language change ──
|
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||||
useEffect(() => {
|
|
||||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [i18n.language]);
|
|
||||||
|
|
||||||
const handleSubmit = useCallback(async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger();
|
const isValid = await trigger();
|
||||||
if (!isValid) return;
|
if (!isValid) return;
|
||||||
|
|
||||||
const payload = buildPayload(getValues());
|
const payload = buildPayload(getValues());
|
||||||
|
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
createMutation.mutate(payload, {
|
const result = await createMutation.mutateAsync(payload);
|
||||||
onSuccess: () => navigate("/settings/card/card-types"),
|
navigate(`/settings/card/card-types/${result.id}`);
|
||||||
});
|
} else {
|
||||||
} else if (initialData) {
|
await updateMutation.mutateAsync(payload);
|
||||||
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/card/card-types") });
|
navigate(`/settings/card/card-types/${initialData!.id}`);
|
||||||
}
|
}
|
||||||
}, [mode, initialData, createMutation, updateMutation, navigate, trigger, getValues]);
|
};
|
||||||
|
|
||||||
const nameFields = {
|
const nameFields = {
|
||||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk")(v), error: errors.nameTk },
|
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk")(v), error: errors.nameTk },
|
||||||
@@ -127,26 +116,27 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
|||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="number"
|
type="number"
|
||||||
label={t("cardTypes.fields.value", "Baha")}
|
label={t("cardTypes.fields.price", "Baha")}
|
||||||
value={form.value}
|
value={form.price}
|
||||||
onChange={set("value")}
|
onChange={set("price")}
|
||||||
placeholder={t("cardTypes.fields.value", "Baha")}
|
placeholder={t("cardTypes.fields.price", "Baha")}
|
||||||
error={errors.value}
|
error={errors.price}
|
||||||
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("cardTypes.fields.description", "Bellikler")}
|
label={t("cardTypes.fields.notes", "Bellikler")}
|
||||||
value={form.description}
|
value={form.notes}
|
||||||
onChange={set("description")}
|
onChange={set("notes")}
|
||||||
placeholder={t("cardTypes.fields.description", "Bellikler")}
|
placeholder={t("cardTypes.fields.notes", "Bellikler")}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<div className="flex items-center gap-3 pt-1">
|
<div className="flex items-center gap-3 pt-1">
|
||||||
<span className="text-sm font-semibold text-muted-foreground">{t("cardTypes.fields.isActive", "Işjeň")}</span>
|
<span className="text-sm font-semibold text-muted-foreground">{t("cardTypes.fields.isActive", "Işjeň")}</span>
|
||||||
<Checkbox checked={form.isActive} onCheckedChange={(checked) => set("isActive")(!!checked)} />
|
<Checkbox checked={form.active} onCheckedChange={(checked) => set("active")(!!checked)} />
|
||||||
</div>
|
</div>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
@@ -154,7 +144,6 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
|||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
onCancel={() => navigate("/settings/card/card-types")}
|
onCancel={() => navigate("/settings/card/card-types")}
|
||||||
cancelVariant="ghost"
|
|
||||||
submitLabel={
|
submitLabel={
|
||||||
mode === "create" ? t("cardTypes.actions.create", "Kart görnüşi döretdiň") : t("cardTypes.actions.update", "Täzelemek")
|
mode === "create" ? t("cardTypes.actions.create", "Kart görnüşi döretdiň") : t("cardTypes.actions.update", "Täzelemek")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,92 +1,133 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
import {
|
import {
|
||||||
fetchCardTypes,
|
fetchCardTypes,
|
||||||
fetchCardTypeById,
|
fetchCardTypeById,
|
||||||
createCardType,
|
createCardType,
|
||||||
updateCardType,
|
updateCardType,
|
||||||
|
updateCardTypeActive,
|
||||||
deleteCardType,
|
deleteCardType,
|
||||||
|
type CardTypeListParams,
|
||||||
type CreateCardTypePayload,
|
type CreateCardTypePayload,
|
||||||
type UpdateCardTypePayload,
|
type UpdateCardTypePayload,
|
||||||
} from '../api/cardTypesApi'
|
} from "../api/cardTypesApi";
|
||||||
|
|
||||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const cardTypeKeys = {
|
export const cardTypeKeys = {
|
||||||
all: ['cardTypes'] as const,
|
all: ["cardTypes"] as const,
|
||||||
lists: () => [...cardTypeKeys.all, 'list'] as const,
|
lists: () => [...cardTypeKeys.all, "list"] as const,
|
||||||
list: (params: Record<string, unknown>) =>
|
list: (params: CardTypeListParams) => [...cardTypeKeys.lists(), params] as const,
|
||||||
[...cardTypeKeys.lists(), params] as const,
|
details: () => [...cardTypeKeys.all, "detail"] as const,
|
||||||
detail: (id: number) => [...cardTypeKeys.all, 'detail', id] as const,
|
detail: (id: number) => [...cardTypeKeys.details(), id] as const,
|
||||||
}
|
};
|
||||||
|
|
||||||
// ─── useCardTypes ─────────────────────────────────────────────────────────────
|
// ─── useCardTypes ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardTypes(params: {
|
export function useCardTypes(params: CardTypeListParams = {}) {
|
||||||
page?: number
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
perPage?: number
|
const normalized = normalizeSearch(debouncedSearch);
|
||||||
search?: string
|
const queryParams: CardTypeListParams = { ...params, search: normalized || undefined };
|
||||||
isActive?: string
|
|
||||||
}) {
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: cardTypeKeys.list(params),
|
queryKey: cardTypeKeys.list(queryParams),
|
||||||
queryFn: () => fetchCardTypes(params),
|
queryFn: ({ signal }) => fetchCardTypes(queryParams, signal),
|
||||||
})
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const CARD_TYPE_PAGE_SIZE = 25;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paginated card types for infinite-scroll selects.
|
||||||
|
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||||
|
*/
|
||||||
|
export function useInfiniteCardTypes(search = "", enabled = true) {
|
||||||
|
const debouncedSearch = useDebouncedValue(search);
|
||||||
|
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||||
|
|
||||||
|
return useInfiniteQuery({
|
||||||
|
queryKey: [...cardTypeKeys.lists(), "infinite", effectiveSearch],
|
||||||
|
initialPageParam: 1,
|
||||||
|
queryFn: ({ pageParam, signal }) => fetchCardTypes({ page: pageParam, limit: CARD_TYPE_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||||
|
getNextPageParam: (lastPage, allPages) => {
|
||||||
|
const loaded = allPages.reduce((sum, p) => sum + (p?.paymentCards?.length ?? 0), 0);
|
||||||
|
const count = lastPage?.count ?? 0;
|
||||||
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
|
},
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useCardTypeById ──────────────────────────────────────────────────────────
|
// ─── useCardTypeById ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCardTypeById(id: number) {
|
export function useCardTypeById(id: number | undefined) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: cardTypeKeys.detail(id),
|
queryKey: cardTypeKeys.detail(id!),
|
||||||
queryFn: () => fetchCardTypeById(id),
|
queryFn: () => fetchCardTypeById(id!),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useCreateCardType ────────────────────────────────────────────────────────
|
// ─── useCreateCardType ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateCardType() {
|
export function useCreateCardType() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateCardTypePayload) => createCardType(payload),
|
mutationFn: (payload: CreateCardTypePayload) => createCardType(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() });
|
||||||
toast.success(t('cardTypes.toast.createSuccess', 'Kart görnüşi döredildi'))
|
toast.success(t("cardTypes.toast.createSuccess", "Kart görnüşi döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useUpdateCardType ────────────────────────────────────────────────────────
|
// ─── useUpdateCardType ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateCardType() {
|
export function useUpdateCardType(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateCardTypePayload) => updateCardType(payload),
|
mutationFn: (payload: UpdateCardTypePayload) => updateCardType(id, payload),
|
||||||
onSuccess: (data) => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.detail(data.id) })
|
queryClient.invalidateQueries({ queryKey: cardTypeKeys.detail(id) });
|
||||||
toast.success(t('cardTypes.toast.updateSuccess', 'Kart görnüşi täzelendi'))
|
toast.success(t("cardTypes.toast.updateSuccess", "Kart görnüşi täzelendi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── useUpdateCardTypeActive ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useUpdateCardTypeActive() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ id, active }: { id: number; active: boolean }) => updateCardTypeActive(id, active),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() });
|
||||||
|
toast.success(t("cardTypes.toast.statusUpdated", "Kart görnüşi statusy täzelendi!"));
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useDeleteCardType ────────────────────────────────────────────────────────
|
// ─── useDeleteCardType ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteCardType() {
|
export function useDeleteCardType() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => deleteCardType(id),
|
mutationFn: (id: number) => deleteCardType(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() });
|
||||||
toast.success(t('cardTypes.toast.deleteSuccess', 'Kart görnüşi öçürildi'))
|
toast.success(t("cardTypes.toast.deleteSuccess", "Kart görnüşi öçürildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
@@ -1,36 +1,46 @@
|
|||||||
import { z } from 'zod'
|
import { z } from "zod";
|
||||||
import type { CreateCardTypePayload } from '../api/cardTypesApi'
|
import { resolveCardTypeTitle, type CardType, type CreateCardTypePayload } from "../api/cardTypesApi";
|
||||||
|
|
||||||
export function createCardTypeFormSchema(t: (key: string, fallback?: string) => string) {
|
export function createCardTypeFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
return z.object({
|
return z.object({
|
||||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
value: z.string().refine(
|
price: z
|
||||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) >= 0,
|
.string()
|
||||||
t('validation.invalidNumber', 'Dogry san giriziň'),
|
.refine((v) => v.trim() !== "" && !isNaN(Number(v)) && Number(v) >= 0, t("validation.invalidNumber", "Dogry san giriziň")),
|
||||||
),
|
notes: z.string().optional(),
|
||||||
description: z.string().optional(),
|
active: z.boolean(),
|
||||||
isActive: z.boolean(),
|
});
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CardTypeFormData = z.infer<ReturnType<typeof createCardTypeFormSchema>>
|
export type CardTypeFormData = z.infer<ReturnType<typeof createCardTypeFormSchema>>;
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CardTypeFormData = {
|
export const DEFAULT_FORM_VALUES: CardTypeFormData = {
|
||||||
nameTk: '',
|
nameTk: "",
|
||||||
nameRu: '',
|
nameRu: "",
|
||||||
nameEn: '',
|
nameEn: "",
|
||||||
value: '',
|
price: "",
|
||||||
description: '',
|
notes: "",
|
||||||
isActive: true,
|
active: true,
|
||||||
}
|
};
|
||||||
|
|
||||||
export function buildPayload(data: CardTypeFormData): CreateCardTypePayload {
|
export function buildPayload(data: CardTypeFormData): CreateCardTypePayload {
|
||||||
return {
|
return {
|
||||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
title: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||||
value: Number(data.value),
|
price: data.price.trim(),
|
||||||
description: (data.description ?? '').trim() || null,
|
notes: (data.notes ?? "").trim(),
|
||||||
isActive: data.isActive,
|
active: data.active,
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapInitial(data: CardType): CardTypeFormData {
|
||||||
|
return {
|
||||||
|
nameTk: resolveCardTypeTitle(data.title, "tm"),
|
||||||
|
nameRu: resolveCardTypeTitle(data.title, "ru"),
|
||||||
|
nameEn: resolveCardTypeTitle(data.title, "en"),
|
||||||
|
price: data.price,
|
||||||
|
notes: data.notes ?? "",
|
||||||
|
active: data.active,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -1,267 +1,168 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface SocialMedia {
|
||||||
|
facebook: string;
|
||||||
|
instagram: string;
|
||||||
|
telegram: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Client {
|
export interface Client {
|
||||||
id: number
|
id: number;
|
||||||
username: string
|
email: string;
|
||||||
name: string
|
name: string;
|
||||||
phone: string | null
|
firstName: string;
|
||||||
email: string | null
|
lastName: string;
|
||||||
isActive: boolean
|
username: string;
|
||||||
|
phone: string;
|
||||||
|
avatar: string;
|
||||||
|
socialMedia: SocialMedia;
|
||||||
|
lightMode: number;
|
||||||
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
|
active: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientDetail extends Client {
|
export interface ClientDetail extends Client {
|
||||||
roles: ClientRole[]
|
roles: ClientRole[];
|
||||||
permissions: ClientPermission[]
|
permissions: ClientPermission[];
|
||||||
branches: ClientBranch[]
|
branches: ClientBranch[];
|
||||||
loanOrders: ClientLoanOrder[]
|
loanOrders: ClientLoanOrder[];
|
||||||
cardOrders: ClientCardOrder[]
|
cardOrders: ClientCardOrder[];
|
||||||
auditLogs: ClientAuditLog[]
|
auditLogs: ClientAuditLog[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientRole {
|
export interface ClientRole {
|
||||||
id: number
|
id: number;
|
||||||
code: string
|
code: string;
|
||||||
name: string
|
name: string;
|
||||||
guardName: string
|
scope: "own" | "branch" | "all";
|
||||||
|
isSuper: boolean;
|
||||||
|
isSystem: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientPermission {
|
export interface ClientPermission {
|
||||||
id: number
|
code: string;
|
||||||
name: string
|
name: string;
|
||||||
guardName: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientBranch {
|
export interface ClientBranch {
|
||||||
id: number
|
id: number;
|
||||||
name: string
|
name: LocalizedText | string;
|
||||||
region: string
|
region: string;
|
||||||
district: string
|
district: string;
|
||||||
uniqueCode: string
|
uniqueCode: string;
|
||||||
isActive: boolean
|
isActive: boolean;
|
||||||
billingUsernameIbr: string
|
billingUsernameIbr: string;
|
||||||
billingUsernameSber: string
|
billingUsernameSber: string;
|
||||||
billingUsernameVisa: string
|
billingUsernameVisa: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientLoanOrder {
|
export interface ClientLoanOrder {
|
||||||
id: number
|
id: number;
|
||||||
name: string
|
name: string;
|
||||||
amount: number
|
amount: number;
|
||||||
status: string
|
status: string;
|
||||||
createdAt: string
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientCardOrder {
|
export interface ClientCardOrder {
|
||||||
id: number
|
id: number;
|
||||||
name: string
|
name: string;
|
||||||
amount: number
|
amount: number;
|
||||||
status: string
|
status: string;
|
||||||
createdAt: string
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientAuditLog {
|
export interface ClientAuditLog {
|
||||||
id: number
|
id: number;
|
||||||
actionName: string
|
actionName: string;
|
||||||
performedBy: string
|
performedBy: string;
|
||||||
target: string
|
target: string;
|
||||||
status: string
|
status: string;
|
||||||
createdAt: string
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientsListResponse {
|
export interface ClientsListResponse {
|
||||||
data: Client[]
|
count: number;
|
||||||
meta: {
|
users: Client[];
|
||||||
currentPage: number
|
|
||||||
totalPages: number
|
|
||||||
totalCount: number
|
|
||||||
perPage: number
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CreateClientPayload {
|
|
||||||
username: string
|
|
||||||
name: string
|
|
||||||
phone: string
|
|
||||||
email?: string
|
|
||||||
password: string
|
|
||||||
isActive: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UpdateClientPayload {
|
|
||||||
username?: string
|
|
||||||
name?: string
|
|
||||||
phone?: string
|
|
||||||
email?: string
|
|
||||||
password?: string
|
|
||||||
isActive?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientsListParams {
|
export interface ClientsListParams {
|
||||||
page?: number
|
page?: number;
|
||||||
perPage?: number
|
limit?: number;
|
||||||
search?: string
|
search?: string;
|
||||||
isActive?: string
|
isActive?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Mock Data & API ────────────────────────────────────────────────────────────
|
export interface CreateClientPayload {
|
||||||
|
active: boolean;
|
||||||
|
avatar: string;
|
||||||
|
email: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
lightMode: number;
|
||||||
|
name: string;
|
||||||
|
password: string;
|
||||||
|
phone: string;
|
||||||
|
role: string;
|
||||||
|
roleId?: number;
|
||||||
|
socialMedia: SocialMedia;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
export interface UpdateClientPayload {
|
||||||
|
active?: boolean;
|
||||||
|
avatar?: string;
|
||||||
|
email?: string;
|
||||||
|
firstName?: string;
|
||||||
|
lastName?: string;
|
||||||
|
lightMode?: number;
|
||||||
|
name?: string;
|
||||||
|
phone?: string;
|
||||||
|
role?: string;
|
||||||
|
roleId?: number;
|
||||||
|
socialMedia?: SocialMedia;
|
||||||
|
username?: string;
|
||||||
|
}
|
||||||
|
|
||||||
let mockClients: ClientDetail[] = [
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
username: 'client_01',
|
|
||||||
name: 'Merdan Merdanow',
|
|
||||||
phone: '+99361234567',
|
|
||||||
email: 'merdan@example.com',
|
|
||||||
isActive: true,
|
|
||||||
roles: [{ id: 1, code: 'CLIENT_STANDARD', name: 'Standard Client', guardName: 'web' }],
|
|
||||||
permissions: [],
|
|
||||||
branches: [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
name: 'Aşgabat Baş Şahamça',
|
|
||||||
region: 'Aşgabat',
|
|
||||||
district: 'Kopetdag',
|
|
||||||
uniqueCode: '01',
|
|
||||||
isActive: true,
|
|
||||||
billingUsernameIbr: 'ibr_c1',
|
|
||||||
billingUsernameSber: 'sber_c1',
|
|
||||||
billingUsernameVisa: 'visa_c1',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
loanOrders: [
|
|
||||||
{ id: 101, name: 'Sarp ediş karzy', amount: 20000, status: 'Active', createdAt: '2023-11-01T10:00:00Z' }
|
|
||||||
],
|
|
||||||
cardOrders: [
|
|
||||||
{ id: 201, name: 'Visa Gold', amount: 500, status: 'Pending', createdAt: '2023-11-05T14:30:00Z' }
|
|
||||||
],
|
|
||||||
auditLogs: [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
actionName: 'Profile Update',
|
|
||||||
performedBy: 'System',
|
|
||||||
target: 'client_01',
|
|
||||||
status: 'Success',
|
|
||||||
createdAt: '2023-10-27T10:00:00Z',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
username: 'client_02',
|
|
||||||
name: 'Aýnabat Aýmyradowa',
|
|
||||||
phone: '+99365765432',
|
|
||||||
email: 'aynabat@example.com',
|
|
||||||
isActive: false,
|
|
||||||
roles: [{ id: 2, code: 'CLIENT_PREMIUM', name: 'Premium Client', guardName: 'web' }],
|
|
||||||
permissions: [],
|
|
||||||
branches: [],
|
|
||||||
loanOrders: [],
|
|
||||||
cardOrders: [],
|
|
||||||
auditLogs: [],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
export const clientsApi = {
|
export const clientsApi = {
|
||||||
getAll: async (params: ClientsListParams): Promise<ClientsListResponse> => {
|
/** GET /users/clients — backend filters by `username` */
|
||||||
await delay(500)
|
getClients: async (params: ClientsListParams = {}, signal?: AbortSignal): Promise<ClientsListResponse> => {
|
||||||
let filtered = [...mockClients]
|
const { page, limit, search, isActive } = params;
|
||||||
if (params.search) {
|
const { data } = await apiClient.get<ClientsListResponse>("/users/clients", {
|
||||||
const q = params.search.toLowerCase()
|
params: { page, limit, username: search || undefined, isActive: isActive || undefined },
|
||||||
filtered = filtered.filter(
|
signal,
|
||||||
(c) =>
|
});
|
||||||
c.name.toLowerCase().includes(q) ||
|
return data;
|
||||||
c.username.toLowerCase().includes(q) ||
|
|
||||||
(c.phone && c.phone.includes(q))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (params.isActive !== undefined && params.isActive !== '') {
|
|
||||||
const isActive = params.isActive === 'true'
|
|
||||||
filtered = filtered.filter((c) => c.isActive === isActive)
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
data: filtered,
|
|
||||||
meta: {
|
|
||||||
currentPage: params.page || 1,
|
|
||||||
totalPages: Math.ceil(filtered.length / (params.perPage || 25)) || 1,
|
|
||||||
totalCount: filtered.length,
|
|
||||||
perPage: params.perPage || 25,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
|
||||||
getById: async (id: number): Promise<ClientDetail> => {
|
/** GET /users/:id */
|
||||||
await delay(500)
|
getClientById: async (id: number): Promise<ClientDetail> => {
|
||||||
const client = mockClients.find((c) => c.id === Number(id))
|
const { data } = await apiClient.get<ClientDetail>(`/users/${id}`);
|
||||||
if (!client) throw new Error('Not found')
|
return data;
|
||||||
return client
|
|
||||||
},
|
},
|
||||||
|
|
||||||
create: async (payload: CreateClientPayload): Promise<Client> => {
|
/** POST /users — same entity & payload as all users */
|
||||||
await delay(500)
|
createClient: async (payload: CreateClientPayload): Promise<Client> => {
|
||||||
const newClient: ClientDetail = {
|
const { data } = await apiClient.post<Client>("/users", payload);
|
||||||
id: mockClients.length > 0 ? Math.max(...mockClients.map((c) => c.id)) + 1 : 1,
|
return data;
|
||||||
username: payload.username,
|
|
||||||
name: payload.name,
|
|
||||||
phone: payload.phone,
|
|
||||||
email: payload.email || null,
|
|
||||||
isActive: payload.isActive,
|
|
||||||
roles: [],
|
|
||||||
permissions: [],
|
|
||||||
branches: [],
|
|
||||||
loanOrders: [],
|
|
||||||
cardOrders: [],
|
|
||||||
auditLogs: [],
|
|
||||||
}
|
|
||||||
mockClients.unshift(newClient)
|
|
||||||
return newClient
|
|
||||||
},
|
},
|
||||||
|
|
||||||
update: async (id: number, payload: UpdateClientPayload): Promise<Client> => {
|
/** PUT /users/:id */
|
||||||
await delay(500)
|
updateClient: async (id: number, payload: UpdateClientPayload): Promise<Client> => {
|
||||||
const index = mockClients.findIndex((c) => c.id === Number(id))
|
const { data } = await apiClient.put<Client>(`/users/${id}`, payload);
|
||||||
if (index === -1) throw new Error('Not found')
|
return data;
|
||||||
|
|
||||||
mockClients[index] = {
|
|
||||||
...mockClients[index],
|
|
||||||
...payload,
|
|
||||||
username: payload.username ?? mockClients[index].username,
|
|
||||||
name: payload.name ?? mockClients[index].name,
|
|
||||||
phone: payload.phone ?? mockClients[index].phone,
|
|
||||||
email: payload.email !== undefined ? payload.email : mockClients[index].email,
|
|
||||||
isActive: payload.isActive ?? mockClients[index].isActive,
|
|
||||||
}
|
|
||||||
return mockClients[index]
|
|
||||||
},
|
},
|
||||||
|
|
||||||
delete: async (id: number): Promise<void> => {
|
/** DELETE /users/:id */
|
||||||
await delay(500)
|
deleteClient: async (id: number): Promise<void> => {
|
||||||
mockClients = mockClients.filter((c) => c.id !== Number(id))
|
await apiClient.delete(`/users/${id}`);
|
||||||
},
|
},
|
||||||
|
};
|
||||||
assignRole: async (_clientId: number, _roleId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
removeRole: async (_clientId: number, _roleId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
assignPermission: async (_clientId: number, _permissionId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
removePermission: async (_clientId: number, _permissionId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
assignBranch: async (_clientId: number, _branchId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
removeBranch: async (_clientId: number, _branchId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,20 @@
|
|||||||
import { useMemo, useEffect, useCallback } from "react";
|
import { useMemo, useEffect, useCallback, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
|
||||||
import { FormActions } from "@/components/formActions";
|
|
||||||
import { FormInput } from "@/components/formInput";
|
import { FormInput } from "@/components/formInput";
|
||||||
|
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { FormActions } from "@/components/formActions";
|
||||||
|
import { AvatarUpload } from "@/components/avatarUpload";
|
||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import { useCreateClient, useUpdateClient } from "../hooks/useClients";
|
import { useCreateClient, useUpdateClient } from "../hooks/useClients";
|
||||||
import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/client.schema";
|
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||||
import type { ClientFormData } from "../schemas/client.schema";
|
|
||||||
import type { Client } from "../api/clientsApi";
|
import type { Client } from "../api/clientsApi";
|
||||||
|
import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload, buildUpdatePayload } from "../schemas/client.schema";
|
||||||
|
import type { ClientFormData } from "../schemas/client.schema";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -42,13 +46,40 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
);
|
);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const createMutation = useCreateClient();
|
const createClient = useCreateClient();
|
||||||
const updateMutation = useUpdateClient(initialData?.id ?? 0);
|
const updateClient = useUpdateClient(initialData?.id ?? 0);
|
||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
const isPending = createClient.isPending || updateClient.isPending;
|
||||||
|
|
||||||
const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language]);
|
const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language]);
|
||||||
|
|
||||||
|
// ── Role infinite-scroll select ──
|
||||||
|
const [roleSearch, setRoleSearch] = useState("");
|
||||||
|
const roleQuery = useInfiniteRoles(roleSearch);
|
||||||
|
|
||||||
|
const roleSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||||
|
const opts: InfiniteSelectOption[] = (roleQuery.data?.pages ?? [])
|
||||||
|
.flatMap((p) => p?.roles ?? [])
|
||||||
|
.map((r) => ({ value: r.code, label: r.name }));
|
||||||
|
|
||||||
|
if (initialData) {
|
||||||
|
const current = initialData.role;
|
||||||
|
if (current && !opts.some((o) => o.value === current)) {
|
||||||
|
opts.unshift({ value: current, label: current });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
options: opts,
|
||||||
|
loading: roleQuery.isLoading,
|
||||||
|
isLoadingMore: roleQuery.isFetchingNextPage,
|
||||||
|
hasNextPage: !!roleQuery.hasNextPage,
|
||||||
|
onLoadMore: () => roleQuery.fetchNextPage(),
|
||||||
|
searchValue: roleSearch,
|
||||||
|
onSearchChange: setRoleSearch,
|
||||||
|
};
|
||||||
|
}, [roleQuery, roleSearch, initialData]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -64,10 +95,19 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
...DEFAULT_FORM_VALUES,
|
...DEFAULT_FORM_VALUES,
|
||||||
username: initialData.username,
|
username: initialData.username,
|
||||||
name: initialData.name,
|
name: initialData.name,
|
||||||
phone: initialData.phone ?? "",
|
firstName: initialData.firstName ?? "",
|
||||||
|
lastName: initialData.lastName ?? "",
|
||||||
|
phone: initialData.phone.replace(/\D/g, "").slice(-8),
|
||||||
email: initialData.email ?? "",
|
email: initialData.email ?? "",
|
||||||
|
avatar: initialData.avatar ?? "",
|
||||||
|
role: initialData.role ?? "",
|
||||||
|
roleId: initialData.roleId ? String(initialData.roleId) : "",
|
||||||
|
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||||
|
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||||
|
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||||
|
lightMode: !!initialData.lightMode,
|
||||||
password: "",
|
password: "",
|
||||||
isActive: initialData.isActive,
|
active: !!initialData.active,
|
||||||
}
|
}
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
});
|
});
|
||||||
@@ -88,7 +128,6 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [i18n.language]);
|
}, [i18n.language]);
|
||||||
|
|
||||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger();
|
const isValid = await trigger();
|
||||||
if (!isValid) return;
|
if (!isValid) return;
|
||||||
@@ -97,119 +136,170 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
|
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
const payload = buildPayload(data);
|
const payload = buildPayload(data);
|
||||||
createMutation.mutate(payload, {
|
await createClient.mutateAsync(payload);
|
||||||
onSuccess: () => navigate("/clients"),
|
navigate("/clients");
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
updateMutation.mutate(
|
const payload = buildUpdatePayload(data);
|
||||||
{
|
await updateClient.mutateAsync(payload);
|
||||||
username: data.username.trim(),
|
navigate(`/clients/${initialData!.id}`);
|
||||||
name: data.name.trim(),
|
|
||||||
phone: data.phone.trim(),
|
|
||||||
email: data.email.trim() || undefined,
|
|
||||||
isActive: data.isActive,
|
|
||||||
...(data.password.trim() ? { password: data.password } : {}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: () => navigate(`/clients/${initialData!.id}`),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Render ──────────────────────────────────────────────────────────────────
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === "create" ? t("clients.createTitle", "Müşderi dörediň") : t("clients.editTitle", "Müşderi üýtgetmek")}
|
{mode === "create" ? t("clients.createTitle", "Müşderi dörediň") : t("clients.editTitle", "Müşderi üýtgetmek")}
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard>
|
{/* ── Identity ── */}
|
||||||
<FormInput
|
<BentoCard title={t("users.sections.identity", "Şahsy maglumat")}>
|
||||||
type="text"
|
<div className="grid grid-cols-2 gap-3">
|
||||||
label={t("clients.fields.username", "Ulanyjy ady")}
|
<FormInput
|
||||||
value={form.username}
|
type="text"
|
||||||
onChange={(v) => setField("username", v)}
|
label={t("users.fields.username", "Ulanyjy ady")}
|
||||||
placeholder={t("clients.fields.username", "Ulanyjy ady")}
|
value={form.username}
|
||||||
error={errors.username}
|
onChange={(v) => setField("username", v)}
|
||||||
disabled={isPending}
|
placeholder={t("users.fields.username", "Ulanyjy ady")}
|
||||||
required
|
error={errors.username}
|
||||||
/>
|
disabled={isPending}
|
||||||
</BentoCard>
|
required
|
||||||
<BentoCard>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("clients.fields.name", "Ady")}
|
label={t("users.fields.name", "Ady")}
|
||||||
value={form.name}
|
value={form.name}
|
||||||
onChange={(v) => setField("name", v)}
|
onChange={(v) => setField("name", v)}
|
||||||
placeholder={t("clients.fields.name", "Ady")}
|
placeholder={t("users.fields.name", "Ady")}
|
||||||
error={errors.name}
|
error={errors.name}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
<FormInput
|
||||||
<BentoCard>
|
type="text"
|
||||||
<FormInput
|
label={t("users.fields.firstName", "Ady (at)")}
|
||||||
type="phone"
|
value={form.firstName}
|
||||||
label={t("clients.fields.phone", "Telefon")}
|
onChange={(v) => setField("firstName", v)}
|
||||||
value={form.phone}
|
placeholder={t("users.fields.firstName", "Ady (at)")}
|
||||||
onChange={(v) => setField("phone", v)}
|
error={errors.firstName}
|
||||||
error={errors.phone}
|
disabled={isPending}
|
||||||
disabled={isPending}
|
/>
|
||||||
required
|
<FormInput
|
||||||
/>
|
type="text"
|
||||||
</BentoCard>
|
label={t("users.fields.lastName", "Familiýasy")}
|
||||||
<BentoCard>
|
value={form.lastName}
|
||||||
<FormInput
|
onChange={(v) => setField("lastName", v)}
|
||||||
type="email"
|
placeholder={t("users.fields.lastName", "Familiýasy")}
|
||||||
label={t("clients.fields.email", "E-poçta")}
|
error={errors.lastName}
|
||||||
value={form.email}
|
|
||||||
onChange={(v) => setField("email", v)}
|
|
||||||
placeholder={t("clients.fields.email", "E-poçta")}
|
|
||||||
disabled={isPending}
|
|
||||||
/>
|
|
||||||
</BentoCard>
|
|
||||||
</BentoGrid>
|
|
||||||
<BentoGrid cols={1}>
|
|
||||||
<BentoCard>
|
|
||||||
<FormInput
|
|
||||||
type="password"
|
|
||||||
label={t("clients.fields.password", "Açar sözi") + (mode === "create" ? " *" : "")}
|
|
||||||
value={form.password}
|
|
||||||
onChange={(v) => setField("password", v)}
|
|
||||||
placeholder={
|
|
||||||
mode === "edit"
|
|
||||||
? t("clients.fields.passwordEditHint", "Üýtgetmek üçin täze açar söz giriziň")
|
|
||||||
: t("clients.fields.password", "Açar sözi")
|
|
||||||
}
|
|
||||||
error={errors.password}
|
|
||||||
disabled={isPending}
|
|
||||||
/>
|
|
||||||
{mode === "edit" && (
|
|
||||||
<p className="text-xs text-muted-foreground -mt-3">
|
|
||||||
{t("clients.fields.passwordEditNote", "Boş goýsaňyz, açar sözi üýtgemez")}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</BentoCard>
|
|
||||||
<BentoCard>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<span className="text-sm text-muted-foreground">{t("clients.fields.isActive", "Işjeň")}</span>
|
|
||||||
<Checkbox
|
|
||||||
checked={form.isActive}
|
|
||||||
onCheckedChange={(v) => setField("isActive", !!v)}
|
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<FormActions
|
<div className="grid grid-cols-2 gap-3">
|
||||||
isPending={isPending}
|
<FormInput
|
||||||
onSubmit={handleSubmit}
|
type="phone"
|
||||||
onCancel={() => navigate(-1)}
|
label={t("users.fields.phone", "Telefon")}
|
||||||
cancelVariant="ghost"
|
value={form.phone}
|
||||||
submitLabel={mode === "create" ? t("clients.createBtn", "Müşderi döredin") : t("clients.updateBtn", "Üýtgetmeleri sakla")}
|
onChange={(v) => setField("phone", v)}
|
||||||
|
placeholder="62-38-49-56"
|
||||||
|
error={errors.phone}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="email"
|
||||||
|
label={t("users.fields.email", "E-poçta")}
|
||||||
|
value={form.email}
|
||||||
|
onChange={(v) => setField("email", v)}
|
||||||
|
placeholder={t("users.fields.email", "E-poçta")}
|
||||||
|
error={errors.email}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
<InfiniteSelect
|
||||||
|
label={t("users.fields.role", "Roly")}
|
||||||
|
value={form.role}
|
||||||
|
onChange={(v) => {
|
||||||
|
setField("role", v);
|
||||||
|
const selectedRole = (roleQuery.data?.pages ?? []).flatMap((page) => page?.roles ?? []).find((role) => role.code === v);
|
||||||
|
setField("roleId", selectedRole ? String(selectedRole.id) : "");
|
||||||
|
}}
|
||||||
|
placeholder={t("users.fields.role", "Roly")}
|
||||||
|
error={errors.role}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
{...roleSelect}
|
||||||
|
/>
|
||||||
|
{mode === "create" && (
|
||||||
|
<FormInput
|
||||||
|
type="password"
|
||||||
|
label={t("users.fields.password", "Açar sözi")}
|
||||||
|
value={form.password}
|
||||||
|
onChange={(v) => setField("password", v)}
|
||||||
|
placeholder={t("users.fields.password", "Açar sözi")}
|
||||||
|
error={errors.password}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-2 pt-1">
|
||||||
|
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
|
||||||
|
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
|
||||||
|
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</BentoCard>
|
||||||
|
|
||||||
|
{/* ── Avatar ── */}
|
||||||
|
<BentoCard>
|
||||||
|
<AvatarUpload
|
||||||
|
label={t("users.fields.avatar", "Awatar")}
|
||||||
|
value={form.avatar}
|
||||||
|
onChange={(v) => setField("avatar", v)}
|
||||||
|
error={errors.avatar}
|
||||||
|
disabled={isPending}
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
|
{/* ── Social media ── */}
|
||||||
|
<BentoCard title={t("users.fields.socialMedia", "Sosial media")} span="full">
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("users.fields.facebook", "Facebook")}
|
||||||
|
value={form.socialFacebook}
|
||||||
|
onChange={(v) => setField("socialFacebook", v)}
|
||||||
|
placeholder="facebook.com/..."
|
||||||
|
error={errors.socialFacebook}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("users.fields.instagram", "Instagram")}
|
||||||
|
value={form.socialInstagram}
|
||||||
|
onChange={(v) => setField("socialInstagram", v)}
|
||||||
|
placeholder="instagram.com/..."
|
||||||
|
error={errors.socialInstagram}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("users.fields.telegram", "Telegram")}
|
||||||
|
value={form.socialTelegram}
|
||||||
|
onChange={(v) => setField("socialTelegram", v)}
|
||||||
|
placeholder="t.me/..."
|
||||||
|
error={errors.socialTelegram}
|
||||||
|
disabled={isPending}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
|
<FormActions
|
||||||
|
isPending={isPending}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
onCancel={() => navigate(-1)}
|
||||||
|
submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,31 +1,59 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
clientsApi,
|
import { clientsApi, type ClientsListParams, type CreateClientPayload, type UpdateClientPayload } from "../api/clientsApi";
|
||||||
type ClientsListParams,
|
|
||||||
type CreateClientPayload,
|
|
||||||
type UpdateClientPayload,
|
|
||||||
} from '../api/clientsApi'
|
|
||||||
|
|
||||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const clientKeys = {
|
export const clientKeys = {
|
||||||
all: ['clients'] as const,
|
all: ["clients"] as const,
|
||||||
lists: () => [...clientKeys.all, 'list'] as const,
|
lists: () => [...clientKeys.all, "list"] as const,
|
||||||
list: (params: ClientsListParams) => [...clientKeys.lists(), params] as const,
|
list: (params: ClientsListParams) => [...clientKeys.lists(), params] as const,
|
||||||
details: () => [...clientKeys.all, 'detail'] as const,
|
details: () => [...clientKeys.all, "detail"] as const,
|
||||||
detail: (id: number) => [...clientKeys.details(), id] as const,
|
detail: (id: number) => [...clientKeys.details(), id] as const,
|
||||||
}
|
infinite: (search: string) => [...clientKeys.all, "infinite", search] as const,
|
||||||
|
};
|
||||||
|
|
||||||
// ─── useClients ───────────────────────────────────────────────────────────────
|
// ─── useClients ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useClients(params: ClientsListParams) {
|
export function useClients(params: ClientsListParams = {}) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
|
const normalized = normalizeSearch(debouncedSearch);
|
||||||
|
const queryParams: ClientsListParams = { ...params, search: normalized || undefined };
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: clientKeys.list(params),
|
queryKey: clientKeys.list(queryParams),
|
||||||
queryFn: () => clientsApi.getAll(params),
|
queryFn: ({ signal }) => clientsApi.getClients(queryParams, signal),
|
||||||
placeholderData: (prev) => prev,
|
placeholderData: (prev) => prev,
|
||||||
})
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── useInfiniteClients ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const CLIENT_PAGE_SIZE = 25;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Infinite-scroll client list for searchable selects.
|
||||||
|
* Backed by `clientsApi.getClients` (GET /users/clients).
|
||||||
|
*/
|
||||||
|
export function useInfiniteClients(search = "", enabled = true) {
|
||||||
|
const debouncedSearch = useDebouncedValue(search);
|
||||||
|
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||||
|
|
||||||
|
return useInfiniteQuery({
|
||||||
|
queryKey: clientKeys.infinite(effectiveSearch),
|
||||||
|
initialPageParam: 1,
|
||||||
|
queryFn: ({ pageParam, signal }) =>
|
||||||
|
clientsApi.getClients({ page: pageParam, limit: CLIENT_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||||
|
getNextPageParam: (lastPage, allPages) => {
|
||||||
|
const loaded = allPages.reduce((sum, p) => sum + (p?.users?.length ?? 0), 0);
|
||||||
|
const count = lastPage?.count ?? 0;
|
||||||
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
|
},
|
||||||
|
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useClient ────────────────────────────────────────────────────────────────
|
// ─── useClient ────────────────────────────────────────────────────────────────
|
||||||
@@ -33,96 +61,53 @@ export function useClients(params: ClientsListParams) {
|
|||||||
export function useClient(id: number) {
|
export function useClient(id: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: clientKeys.detail(id),
|
queryKey: clientKeys.detail(id),
|
||||||
queryFn: () => clientsApi.getById(id),
|
queryFn: () => clientsApi.getClientById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useCreateClient ──────────────────────────────────────────────────────────
|
// ─── useCreateClient ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateClient() {
|
export function useCreateClient() {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateClientPayload) => clientsApi.create(payload),
|
mutationFn: (payload: CreateClientPayload) => clientsApi.createClient(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: clientKeys.lists() });
|
||||||
toast.success(t('clients.createSuccess', 'Müşderi üstünlikli döredildi'))
|
toast.success(t("clients.createSuccess", "Müşderi üstünlikli döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useUpdateClient ──────────────────────────────────────────────────────────
|
// ─── useUpdateClient ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateClient(id: number) {
|
export function useUpdateClient(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateClientPayload) => clientsApi.update(id, payload),
|
mutationFn: (payload: UpdateClientPayload) => clientsApi.updateClient(id, payload),
|
||||||
onSuccess: () => {
|
onSuccess: (updatedClient) => {
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: clientKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.detail(id) })
|
queryClient.setQueryData(clientKeys.detail(id), updatedClient);
|
||||||
toast.success(t('clients.updateSuccess', 'Müşderi üstünlikli täzelendi'))
|
toast.success(t("clients.updateSuccess", "Müşderi üstünlikli täzelendi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── useDeleteClient ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteClient() {
|
export function useDeleteClient() {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => clientsApi.delete(id),
|
mutationFn: (id: number) => clientsApi.deleteClient(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: clientKeys.lists() });
|
||||||
toast.success(t('clients.deleteSuccess', 'Müşderi üstünlikli pozuldy'))
|
toast.success(t("clients.deleteSuccess", "Müşderi üstünlikli pozuldy"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useAssignClientRole ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useAssignClientRole(clientId: number) {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (roleId: number) => clientsApi.assignRole(clientId, roleId),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
|
|
||||||
toast.success(t('clients.roleAssigned', 'Rol birikdirildi'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── useRemoveClientRole ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useRemoveClientRole(clientId: number) {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (roleId: number) => clientsApi.removeRole(clientId, roleId),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
|
|
||||||
toast.success(t('clients.roleRemoved', 'Rol aýryldy'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── useAssignClientBranch ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useAssignClientBranch(clientId: number) {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (branchId: number) => clientsApi.assignBranch(clientId, branchId),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
|
|
||||||
toast.success(t('clients.branchAssigned', 'Şahamça birikdirildi'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,20 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { CreateClientPayload } from "../api/clientsApi";
|
import type { CreateClientPayload, UpdateClientPayload } from "../api/clientsApi";
|
||||||
|
|
||||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||||
|
|
||||||
|
const urlSchema = (t: (key: string, fallback?: string) => string) =>
|
||||||
|
z
|
||||||
|
.string()
|
||||||
|
.refine((v) => !v || /^(https?:\/\/|www\.|[\w.-]+\.[a-z]{2,})/i.test(v), t("validation.invalidUrl", "validation.invalidUrl"))
|
||||||
|
.default("");
|
||||||
|
|
||||||
export function clientFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
export function clientFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
||||||
const baseSchema = z.object({
|
const baseSchema = z.object({
|
||||||
username: z.string().min(1, t("validation.required", "validation.required")),
|
username: z.string().min(1, t("validation.required", "validation.required")).min(3, t("validation.minLength", "validation.minLength")),
|
||||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
firstName: z.string().default(""),
|
||||||
|
lastName: z.string().default(""),
|
||||||
phone: z
|
phone: z
|
||||||
.string()
|
.string()
|
||||||
.min(1, t("validation.required", "validation.required"))
|
.min(1, t("validation.required", "validation.required"))
|
||||||
@@ -25,14 +33,27 @@ export function clientFormSchema(mode: "create" | "edit", t: (key: string, fallb
|
|||||||
},
|
},
|
||||||
{ message: t("validation.invalidPhonePrefix", "validation.invalidPhonePrefix") },
|
{ message: t("validation.invalidPhonePrefix", "validation.invalidPhonePrefix") },
|
||||||
),
|
),
|
||||||
email: z.string().default(""),
|
email: z
|
||||||
|
.string()
|
||||||
|
.refine((v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), t("validation.invalidEmail", "validation.invalidEmail"))
|
||||||
|
.default(""),
|
||||||
|
avatar: urlSchema(t),
|
||||||
|
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
roleId: z.string(),
|
||||||
|
socialFacebook: urlSchema(t),
|
||||||
|
socialInstagram: urlSchema(t),
|
||||||
|
socialTelegram: urlSchema(t),
|
||||||
|
lightMode: z.boolean(),
|
||||||
password: z.string(),
|
password: z.string(),
|
||||||
isActive: z.boolean(),
|
active: z.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
return mode === "create"
|
return mode === "create"
|
||||||
? baseSchema.extend({
|
? baseSchema.extend({
|
||||||
password: z.string().min(1, t("validation.required", "validation.required")),
|
password: z
|
||||||
|
.string()
|
||||||
|
.min(1, t("validation.required", "validation.required"))
|
||||||
|
.min(6, t("validation.minLength", "validation.minLength")),
|
||||||
})
|
})
|
||||||
: baseSchema;
|
: baseSchema;
|
||||||
}
|
}
|
||||||
@@ -42,19 +63,60 @@ export type ClientFormData = z.infer<ReturnType<typeof clientFormSchema>>;
|
|||||||
export const DEFAULT_FORM_VALUES: ClientFormData = {
|
export const DEFAULT_FORM_VALUES: ClientFormData = {
|
||||||
username: "",
|
username: "",
|
||||||
name: "",
|
name: "",
|
||||||
|
firstName: "",
|
||||||
|
lastName: "",
|
||||||
phone: "",
|
phone: "",
|
||||||
email: "",
|
email: "",
|
||||||
|
avatar: "",
|
||||||
|
role: "",
|
||||||
|
roleId: "",
|
||||||
|
socialFacebook: "",
|
||||||
|
socialInstagram: "",
|
||||||
|
socialTelegram: "",
|
||||||
|
lightMode: false,
|
||||||
password: "",
|
password: "",
|
||||||
isActive: true,
|
active: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function buildPayload(data: ClientFormData): CreateClientPayload {
|
export function buildPayload(data: ClientFormData): CreateClientPayload {
|
||||||
return {
|
return {
|
||||||
username: data.username.trim(),
|
username: data.username.trim(),
|
||||||
name: data.name.trim(),
|
name: data.name.trim(),
|
||||||
phone: data.phone.trim(),
|
firstName: data.firstName.trim(),
|
||||||
email: data.email.trim() || undefined,
|
lastName: data.lastName.trim(),
|
||||||
|
phone: data.phone.replace(/\s+/g, ""),
|
||||||
|
email: data.email.trim(),
|
||||||
|
avatar: data.avatar.trim(),
|
||||||
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
|
socialMedia: {
|
||||||
|
facebook: data.socialFacebook.trim(),
|
||||||
|
instagram: data.socialInstagram.trim(),
|
||||||
|
telegram: data.socialTelegram.trim(),
|
||||||
|
},
|
||||||
|
lightMode: data.lightMode ? 1 : 0,
|
||||||
password: data.password,
|
password: data.password,
|
||||||
isActive: data.isActive,
|
active: data.active,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildUpdatePayload(data: ClientFormData): UpdateClientPayload {
|
||||||
|
return {
|
||||||
|
username: data.username.trim(),
|
||||||
|
name: data.name.trim(),
|
||||||
|
firstName: data.firstName.trim(),
|
||||||
|
lastName: data.lastName.trim(),
|
||||||
|
phone: data.phone.replace(/\s+/g, ""),
|
||||||
|
email: data.email.trim(),
|
||||||
|
avatar: data.avatar.trim(),
|
||||||
|
role: data.role.trim(),
|
||||||
|
...(data.roleId ? { roleId: Number(data.roleId) } : {}),
|
||||||
|
socialMedia: {
|
||||||
|
facebook: data.socialFacebook.trim(),
|
||||||
|
instagram: data.socialInstagram.trim(),
|
||||||
|
telegram: data.socialTelegram.trim(),
|
||||||
|
},
|
||||||
|
lightMode: data.lightMode ? 1 : 0,
|
||||||
|
active: data.active,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,141 +1,97 @@
|
|||||||
// features/currencyRates/api/currencyRatesApi.ts
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
export type CurrencyCode = 'USD' | 'RUB' | 'TMT' | 'EUR' | 'GBP' | 'CNY' | 'TRY'
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface CurrencyRateUser {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
username: string;
|
||||||
|
phone: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Raw backend entity (GET responses mirror this shape). */
|
||||||
export interface CurrencyRate {
|
export interface CurrencyRate {
|
||||||
id: number
|
id: number;
|
||||||
currencyFrom: CurrencyCode
|
currencyFrom: string;
|
||||||
currencyTo: CurrencyCode
|
currencyTo: string;
|
||||||
value: number
|
value: number;
|
||||||
createdAt: string
|
createdBy: CurrencyRateUser;
|
||||||
updatedAt: string
|
updatedBy: CurrencyRateUser;
|
||||||
}
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
export interface CurrencyRateListParams {
|
|
||||||
page?: number
|
|
||||||
perPage?: number
|
|
||||||
search?: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** LIST RESPONSE: GET /currencies */
|
||||||
export interface CurrencyRateListResponse {
|
export interface CurrencyRateListResponse {
|
||||||
data: CurrencyRate[]
|
count: number;
|
||||||
total: number
|
currencies: CurrencyRate[];
|
||||||
page: number
|
|
||||||
perPage: number
|
|
||||||
totalPages: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** LIST PARAMS */
|
||||||
|
export interface CurrencyRateListParams {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
search?: string;
|
||||||
|
currency_from?: string;
|
||||||
|
currency_to?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** CREATE / UPDATE PAYLOAD (camelCase, JSON) */
|
||||||
export interface CreateCurrencyRatePayload {
|
export interface CreateCurrencyRatePayload {
|
||||||
currencyFrom: CurrencyCode
|
currencyFrom: string;
|
||||||
currencyTo: CurrencyCode
|
currencyTo: string;
|
||||||
value: number
|
value: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type UpdateCurrencyRatePayload = CreateCurrencyRatePayload
|
export type UpdateCurrencyRatePayload = CreateCurrencyRatePayload;
|
||||||
|
|
||||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const MOCK_RATES: CurrencyRate[] = [
|
export const currencyRatesApi = {
|
||||||
{ id: 6, currencyFrom: 'USD', currencyTo: 'USD', value: 250, createdAt: '2026-04-01T10:00:00Z', updatedAt: '2026-05-01T10:00:00Z' },
|
getList: async (params: CurrencyRateListParams = {}, signal?: AbortSignal): Promise<CurrencyRateListResponse> => {
|
||||||
{ id: 5, currencyFrom: 'RUB', currencyTo: 'TMT', value: 0.047504, createdAt: '2026-03-15T08:30:00Z', updatedAt: '2026-05-10T08:30:00Z' },
|
const { page, limit, search, currency_from, currency_to } = params;
|
||||||
{ id: 4, currencyFrom: 'USD', currencyTo: 'RUB', value: 74.0455, createdAt: '2026-02-20T14:00:00Z', updatedAt: '2026-05-08T14:00:00Z' },
|
const { data } = await apiClient.get<CurrencyRateListResponse>("/currencies", {
|
||||||
{ id: 2, currencyFrom: 'USD', currencyTo: 'TMT', value: 3.5175, createdAt: '2026-01-10T09:00:00Z', updatedAt: '2026-05-05T09:00:00Z' },
|
params: {
|
||||||
{ id: 1, currencyFrom: 'EUR', currencyTo: 'TMT', value: 3.8120, createdAt: '2026-01-05T09:00:00Z', updatedAt: '2026-05-03T09:00:00Z' },
|
page,
|
||||||
{ id: 3, currencyFrom: 'EUR', currencyTo: 'RUB', value: 80.2300, createdAt: '2026-01-12T11:00:00Z', updatedAt: '2026-04-28T11:00:00Z' },
|
limit,
|
||||||
{ id: 7, currencyFrom: 'GBP', currencyTo: 'TMT', value: 4.4500, createdAt: '2026-04-10T13:00:00Z', updatedAt: '2026-05-11T13:00:00Z' },
|
search: search || undefined,
|
||||||
{ id: 8, currencyFrom: 'CNY', currencyTo: 'TMT', value: 0.4850, createdAt: '2026-04-15T10:00:00Z', updatedAt: '2026-05-09T10:00:00Z' },
|
currency_from: currency_from || undefined,
|
||||||
]
|
currency_to: currency_to || undefined,
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
let mockStore: CurrencyRate[] = [...MOCK_RATES]
|
getById: async (id: number): Promise<CurrencyRate> => {
|
||||||
let nextId = 9
|
const { data } = await apiClient.get<CurrencyRate>(`/currencies/${id}`);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
|
create: async (payload: CreateCurrencyRatePayload): Promise<CurrencyRate> => {
|
||||||
|
const { data } = await apiClient.post<CurrencyRate>("/currencies", payload);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
update: async (id: number, payload: UpdateCurrencyRatePayload): Promise<CurrencyRate> => {
|
||||||
|
const { data } = await apiClient.put<CurrencyRate>(`/currencies/${id}`, payload);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
export async function fetchCurrencyRates(
|
delete: async (id: number): Promise<void> => {
|
||||||
params: CurrencyRateListParams = {}
|
await apiClient.delete(`/currencies/${id}`);
|
||||||
): Promise<CurrencyRateListResponse> {
|
},
|
||||||
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<CurrencyRate> {
|
|
||||||
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<CurrencyRate> {
|
|
||||||
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<CurrencyRate> {
|
|
||||||
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<void> {
|
|
||||||
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 ────────────────────────────────────────────────────────────────
|
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const CURRENCY_OPTIONS: { value: CurrencyCode; label: string }[] = [
|
export const CURRENCY_OPTIONS: { value: string; label: string }[] = [
|
||||||
{ value: 'USD', label: 'USD — US Dollar' },
|
{ value: "USD", label: "USD — US Dollar" },
|
||||||
{ value: 'RUB', label: 'RUB — Russian Ruble' },
|
{ value: "RUB", label: "RUB — Russian Ruble" },
|
||||||
{ value: 'TMT', label: 'TMT — Turkmen Manat' },
|
{ value: "TMT", label: "TMT — Turkmen Manat" },
|
||||||
{ value: 'EUR', label: 'EUR — Euro' },
|
{ value: "EUR", label: "EUR — Euro" },
|
||||||
{ value: 'GBP', label: 'GBP — British Pound' },
|
{ value: "GBP", label: "GBP — British Pound" },
|
||||||
{ value: 'CNY', label: 'CNY — Chinese Yuan' },
|
{ value: "CNY", label: "CNY — Chinese Yuan" },
|
||||||
{ value: 'TRY', label: 'TRY — Turkish Lira' },
|
{ value: "TRY", label: "TRY — Turkish Lira" },
|
||||||
]
|
];
|
||||||
@@ -47,6 +47,16 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
|||||||
|
|
||||||
const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language]);
|
const schema = useMemo(() => createCurrencyRateFormSchema(t), [t, i18n.language]);
|
||||||
|
|
||||||
|
const currencyOptions = useMemo(() => {
|
||||||
|
const opts = [...CURRENCY_OPTIONS];
|
||||||
|
if (initialData) {
|
||||||
|
for (const v of [initialData.currencyFrom, initialData.currencyTo]) {
|
||||||
|
if (v && !opts.some((o) => o.value === v)) opts.push({ value: v, label: v });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return opts;
|
||||||
|
}, [initialData]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -92,18 +102,18 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
|||||||
|
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
await createMutation.mutateAsync(payload);
|
await createMutation.mutateAsync(payload);
|
||||||
navigate("/resources/currency-rates");
|
navigate("/currency-rates");
|
||||||
} else {
|
} else {
|
||||||
await updateMutation.mutateAsync(payload);
|
await updateMutation.mutateAsync(payload);
|
||||||
navigate(`/resources/currency-rates/${initialData!.id}`);
|
navigate(`/currency-rates/${initialData!.id}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCancel = () => {
|
const handleCancel = () => {
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
navigate("/resources/currency-rates");
|
navigate("/currency-rates");
|
||||||
} else {
|
} else {
|
||||||
navigate(`/resources/currency-rates/${initialData!.id}`);
|
navigate(`/currency-rates/${initialData!.id}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -121,7 +131,7 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
|||||||
label={t("currencyRates.fields.currencyFrom", "Currency from")}
|
label={t("currencyRates.fields.currencyFrom", "Currency from")}
|
||||||
value={form.currencyFrom}
|
value={form.currencyFrom}
|
||||||
onChange={setField("currencyFrom")}
|
onChange={setField("currencyFrom")}
|
||||||
options={CURRENCY_OPTIONS}
|
options={currencyOptions}
|
||||||
placeholder={t("common.selectPlaceholder", "Saýlamak üçin basyň")}
|
placeholder={t("common.selectPlaceholder", "Saýlamak üçin basyň")}
|
||||||
error={errors.currencyFrom}
|
error={errors.currencyFrom}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
@@ -135,7 +145,7 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
|||||||
label={t("currencyRates.fields.currencyTo", "Currency to")}
|
label={t("currencyRates.fields.currencyTo", "Currency to")}
|
||||||
value={form.currencyTo}
|
value={form.currencyTo}
|
||||||
onChange={setField("currencyTo")}
|
onChange={setField("currencyTo")}
|
||||||
options={CURRENCY_OPTIONS}
|
options={currencyOptions}
|
||||||
placeholder={t("common.selectPlaceholder", "Saýlamak üçin basyň")}
|
placeholder={t("common.selectPlaceholder", "Saýlamak üçin basyň")}
|
||||||
error={errors.currencyTo}
|
error={errors.currencyTo}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
@@ -162,7 +172,6 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
|||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
onCancel={handleCancel}
|
onCancel={handleCancel}
|
||||||
cancelVariant="ghost"
|
|
||||||
submitLabel={
|
submitLabel={
|
||||||
mode === "create"
|
mode === "create"
|
||||||
? t("currencyRates.actions.create", "Walýuta kursy dörediň")
|
? t("currencyRates.actions.create", "Walýuta kursy dörediň")
|
||||||
|
|||||||
@@ -1,91 +1,90 @@
|
|||||||
// features/currencyRates/hooks/useCurrencyRates.ts
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from 'sonner'
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
import { useTranslation } from 'react-i18next'
|
|
||||||
import {
|
import {
|
||||||
fetchCurrencyRates,
|
currencyRatesApi,
|
||||||
fetchCurrencyRateById,
|
|
||||||
createCurrencyRate,
|
|
||||||
updateCurrencyRate,
|
|
||||||
deleteCurrencyRate,
|
|
||||||
type CurrencyRateListParams,
|
type CurrencyRateListParams,
|
||||||
type CreateCurrencyRatePayload,
|
type CreateCurrencyRatePayload,
|
||||||
type UpdateCurrencyRatePayload,
|
type UpdateCurrencyRatePayload,
|
||||||
} from '../api/currencyRatesApi'
|
} from "../api/currencyRatesApi";
|
||||||
|
|
||||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const currencyRateKeys = {
|
export const currencyRateKeys = {
|
||||||
all: ['currencyRates'] as const,
|
all: ["currencyRates"] as const,
|
||||||
lists: () => [...currencyRateKeys.all, 'list'] as const,
|
lists: () => [...currencyRateKeys.all, "list"] as const,
|
||||||
list: (params: CurrencyRateListParams) =>
|
list: (params: CurrencyRateListParams) => [...currencyRateKeys.lists(), params] as const,
|
||||||
[...currencyRateKeys.lists(), params] as const,
|
details: () => [...currencyRateKeys.all, "detail"] as const,
|
||||||
detail: (id: number) =>
|
detail: (id: number) => [...currencyRateKeys.details(), id] as const,
|
||||||
[...currencyRateKeys.all, 'detail', id] as const,
|
};
|
||||||
}
|
|
||||||
|
|
||||||
// ─── useGetCurrencyRates ──────────────────────────────────────────────────────
|
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useGetCurrencyRates(params: CurrencyRateListParams = {}) {
|
export function useGetCurrencyRates(params: CurrencyRateListParams = {}) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
|
const normalized = normalizeSearch(debouncedSearch);
|
||||||
|
const queryParams: CurrencyRateListParams = { ...params, search: normalized || undefined };
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: currencyRateKeys.list(params),
|
queryKey: currencyRateKeys.list(queryParams),
|
||||||
queryFn: () => fetchCurrencyRates(params),
|
queryFn: ({ signal }) => currencyRatesApi.getList(queryParams, signal),
|
||||||
})
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useGetCurrencyRateById ───────────────────────────────────────────────────
|
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useGetCurrencyRateById(id: number) {
|
export function useGetCurrencyRateById(id: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: currencyRateKeys.detail(id),
|
queryKey: currencyRateKeys.detail(id),
|
||||||
queryFn: () => fetchCurrencyRateById(id),
|
queryFn: () => currencyRatesApi.getById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useCreateCurrencyRate ────────────────────────────────────────────────────
|
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateCurrencyRate() {
|
export function useCreateCurrencyRate() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateCurrencyRatePayload) => createCurrencyRate(payload),
|
mutationFn: (payload: CreateCurrencyRatePayload) => currencyRatesApi.create(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() });
|
||||||
toast.success(t('currencyRates.toast.created', 'Walýuta kursy döredildi'))
|
toast.success(t("currencyRates.toast.created", "Walýuta kursy döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useUpdateCurrencyRate ────────────────────────────────────────────────────
|
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateCurrencyRate(id: number) {
|
export function useUpdateCurrencyRate(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateCurrencyRatePayload) => updateCurrencyRate(id, payload),
|
mutationFn: (payload: UpdateCurrencyRatePayload) => currencyRatesApi.update(id, payload),
|
||||||
onSuccess: () => {
|
onSuccess: (updated) => {
|
||||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.detail(id) })
|
queryClient.setQueryData(currencyRateKeys.detail(id), updated);
|
||||||
toast.success(t('currencyRates.toast.updated', 'Walýuta kursy üýtgedildi'))
|
toast.success(t("currencyRates.toast.updated", "Walýuta kursy üýtgedildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useDeleteCurrencyRate ────────────────────────────────────────────────────
|
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteCurrencyRate() {
|
export function useDeleteCurrencyRate() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => deleteCurrencyRate(id),
|
mutationFn: (id: number) => currencyRatesApi.delete(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: currencyRateKeys.lists() });
|
||||||
toast.success(t('currencyRates.toast.deleted', 'Walýuta kursy pozuldy'))
|
toast.success(t("currencyRates.toast.deleted", "Walýuta kursy pozuldy"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
@@ -1,29 +1,29 @@
|
|||||||
import { z } from 'zod'
|
import { z } from "zod";
|
||||||
import type { CreateCurrencyRatePayload, CurrencyCode } from '../api/currencyRatesApi'
|
import type { CreateCurrencyRatePayload } from "../api/currencyRatesApi";
|
||||||
|
|
||||||
export function createCurrencyRateFormSchema(t: (key: string, fallback?: string) => string) {
|
export function createCurrencyRateFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
return z.object({
|
return z.object({
|
||||||
currencyFrom: z.string().min(1, t('validation.required', 'validation.required')),
|
currencyFrom: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
currencyTo: z.string().min(1, t('validation.required', 'validation.required')),
|
currencyTo: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
value: z
|
value: z
|
||||||
.string()
|
.string()
|
||||||
.min(1, t('validation.required', 'validation.required'))
|
.min(1, t("validation.required", "validation.required"))
|
||||||
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, t('validation.valuePositive', 'validation.valuePositive')),
|
.refine((v) => !isNaN(Number(v)) && Number(v) > 0, t("validation.valuePositive", "validation.valuePositive")),
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CurrencyRateFormData = z.infer<ReturnType<typeof createCurrencyRateFormSchema>>
|
export type CurrencyRateFormData = z.infer<ReturnType<typeof createCurrencyRateFormSchema>>;
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: CurrencyRateFormData = {
|
export const DEFAULT_FORM_VALUES: CurrencyRateFormData = {
|
||||||
currencyFrom: '',
|
currencyFrom: "",
|
||||||
currencyTo: '',
|
currencyTo: "",
|
||||||
value: '',
|
value: "",
|
||||||
}
|
};
|
||||||
|
|
||||||
export function buildPayload(data: CurrencyRateFormData): CreateCurrencyRatePayload {
|
export function buildPayload(data: CurrencyRateFormData): CreateCurrencyRatePayload {
|
||||||
return {
|
return {
|
||||||
currencyFrom: data.currencyFrom as CurrencyCode,
|
currencyFrom: data.currencyFrom,
|
||||||
currencyTo: data.currencyTo as CurrencyCode,
|
currencyTo: data.currencyTo,
|
||||||
value: Number(data.value),
|
value: Number(data.value),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
|
// ─── Shared ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface AnalyticsParams {
|
||||||
|
/** YYYY-MM-DD, inclusive */
|
||||||
|
from: string;
|
||||||
|
/** YYYY-MM-DD, inclusive */
|
||||||
|
to: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CountItem {
|
||||||
|
key: string;
|
||||||
|
count: number;
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Localized name stored as JSON on the backend, e.g. { tm, ru, en }. */
|
||||||
|
export type LocalizedName = Partial<Record<"tm" | "ru" | "en", string>>;
|
||||||
|
|
||||||
|
export type OrderType = "loan" | "loan_paid_off_letter" | "card" | "card_pin" | "card_rekwizit" | "visa_master";
|
||||||
|
|
||||||
|
// ─── /finance ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface PaymentTotals {
|
||||||
|
count: number;
|
||||||
|
amountTmt: number;
|
||||||
|
bankFeeTmt: number;
|
||||||
|
gbusFeeTmt: number;
|
||||||
|
tvebFeeTmt: number;
|
||||||
|
totalTmt: number;
|
||||||
|
avgTotalTmt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinanceMonth {
|
||||||
|
month: string; // YYYY-MM
|
||||||
|
count: number;
|
||||||
|
totalTmt: number;
|
||||||
|
bankFeeTmt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoanRequested {
|
||||||
|
count: number;
|
||||||
|
totalTmt: number;
|
||||||
|
avgTmt: number;
|
||||||
|
unparsed: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinanceData {
|
||||||
|
payments: PaymentTotals;
|
||||||
|
gateway: CountItem[];
|
||||||
|
gatewaySuccessRate: number | null;
|
||||||
|
monthly: FinanceMonth[];
|
||||||
|
loanRequested: LoanRequested;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── /backlog ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface BacklogItem {
|
||||||
|
type: OrderType;
|
||||||
|
open: number;
|
||||||
|
under1Day: number;
|
||||||
|
from1To3Days: number;
|
||||||
|
over3Days: number;
|
||||||
|
oldestOpenAt: string | null;
|
||||||
|
oldestOpenDays: number | null;
|
||||||
|
finished: number;
|
||||||
|
avgProcessHours: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VisaMasterTiming {
|
||||||
|
orders: number;
|
||||||
|
avgMinutes: number | null;
|
||||||
|
p90Minutes: number | null;
|
||||||
|
maxMinutes: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BacklogData {
|
||||||
|
items: BacklogItem[];
|
||||||
|
visaMasterTiming: VisaMasterTiming;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── /branches ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface BranchStat {
|
||||||
|
branchId: number;
|
||||||
|
name: LocalizedName;
|
||||||
|
region: string;
|
||||||
|
orders: Partial<Record<OrderType, number>>;
|
||||||
|
total: number;
|
||||||
|
open: number;
|
||||||
|
approved: number;
|
||||||
|
rejected: number;
|
||||||
|
approvalRate: number | null;
|
||||||
|
avgProcessHours: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BranchesData {
|
||||||
|
branches: BranchStat[];
|
||||||
|
regions: CountItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── /products ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface NamedCount {
|
||||||
|
id: number;
|
||||||
|
name: LocalizedName;
|
||||||
|
count: number;
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProductsData {
|
||||||
|
loanSources: CountItem[];
|
||||||
|
loanTypes: NamedCount[];
|
||||||
|
cardTypes: NamedCount[];
|
||||||
|
cardOrderPay: CountItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── /customers ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface ApprovalCount {
|
||||||
|
key: string;
|
||||||
|
count: number;
|
||||||
|
percent: number;
|
||||||
|
approved: number;
|
||||||
|
rejected: number;
|
||||||
|
/** Not decided yet (new / in review). */
|
||||||
|
open: number;
|
||||||
|
approvalRate: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CustomersData {
|
||||||
|
total: number;
|
||||||
|
approved: number;
|
||||||
|
rejected: number;
|
||||||
|
open: number;
|
||||||
|
approvalRate: number | null;
|
||||||
|
ageGroups: ApprovalCount[];
|
||||||
|
education: ApprovalCount[];
|
||||||
|
marriageStatus: ApprovalCount[];
|
||||||
|
guarantors: ApprovalCount[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── /system ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface RegistrationFunnel {
|
||||||
|
started: number;
|
||||||
|
completed: number;
|
||||||
|
abandoned: number;
|
||||||
|
waitingCode: number;
|
||||||
|
wrongCodeTries: number;
|
||||||
|
conversionPct: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OperatorActivity {
|
||||||
|
userId: number;
|
||||||
|
name: string;
|
||||||
|
actions: number;
|
||||||
|
errors: number;
|
||||||
|
lastSeen: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ModuleError {
|
||||||
|
module: string;
|
||||||
|
requests: number;
|
||||||
|
errors: number;
|
||||||
|
errorRate: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** weekday: Monday=1 .. Sunday=7; hour 0..23 (Asia/Ashgabat). */
|
||||||
|
export interface HeatmapCell {
|
||||||
|
weekday: number;
|
||||||
|
hour: number;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CardBalanceStats {
|
||||||
|
statuses: CountItem[];
|
||||||
|
failureRate: number | null;
|
||||||
|
expiringIn30d: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SystemData {
|
||||||
|
registration: RegistrationFunnel | null;
|
||||||
|
operators: OperatorActivity[];
|
||||||
|
moduleErrors: ModuleError[];
|
||||||
|
peakHours: HeatmapCell[];
|
||||||
|
cardBalances: CardBalanceStats | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const BASE = "/dashboard/analytics";
|
||||||
|
|
||||||
|
async function getAnalytics<T>(path: string, params: AnalyticsParams, signal?: AbortSignal): Promise<T> {
|
||||||
|
const { data } = await apiClient.get<T>(`${BASE}/${path}`, { params, signal });
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getAnalyticsFinance = (params: AnalyticsParams, signal?: AbortSignal) => getAnalytics<FinanceData>("finance", params, signal);
|
||||||
|
|
||||||
|
export const getAnalyticsBacklog = (params: AnalyticsParams, signal?: AbortSignal) => getAnalytics<BacklogData>("backlog", params, signal);
|
||||||
|
|
||||||
|
export const getAnalyticsBranches = (params: AnalyticsParams, signal?: AbortSignal) =>
|
||||||
|
getAnalytics<BranchesData>("branches", params, signal);
|
||||||
|
|
||||||
|
export const getAnalyticsProducts = (params: AnalyticsParams, signal?: AbortSignal) =>
|
||||||
|
getAnalytics<ProductsData>("products", params, signal);
|
||||||
|
|
||||||
|
export const getAnalyticsCustomers = (params: AnalyticsParams, signal?: AbortSignal) =>
|
||||||
|
getAnalytics<CustomersData>("customers", params, signal);
|
||||||
|
|
||||||
|
export const getAnalyticsSystem = (params: AnalyticsParams, signal?: AbortSignal) => getAnalytics<SystemData>("system", params, signal);
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
|
// ─── Types (Backend & UI) ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface StatItem {
|
||||||
|
count: number;
|
||||||
|
changePercent: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardStats {
|
||||||
|
loanOrders: StatItem;
|
||||||
|
activeCards: StatItem;
|
||||||
|
activeCustomers: StatItem;
|
||||||
|
onlinePayments: StatItem;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrendPoint {
|
||||||
|
month: number;
|
||||||
|
loans: number;
|
||||||
|
cards: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardTrend {
|
||||||
|
year: number;
|
||||||
|
points: TrendPoint[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoanStatusItem {
|
||||||
|
status: string;
|
||||||
|
count: number;
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WeeklyOrderItem {
|
||||||
|
date: string;
|
||||||
|
weekday: number;
|
||||||
|
loans: number;
|
||||||
|
cards: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RecentActivityItem {
|
||||||
|
id: number;
|
||||||
|
uniqueId: string;
|
||||||
|
customerName: string;
|
||||||
|
amount: string;
|
||||||
|
status: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardOverviewData {
|
||||||
|
stats: DashboardStats;
|
||||||
|
trend: DashboardTrend;
|
||||||
|
loanStatus: LoanStatusItem[];
|
||||||
|
weeklyOrders: WeeklyOrderItem[];
|
||||||
|
recentActivity: RecentActivityItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardOverviewParams {
|
||||||
|
year?: number | string;
|
||||||
|
recent_limit?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function getDashboardOverview(params: DashboardOverviewParams = {}, signal?: AbortSignal): Promise<DashboardOverviewData> {
|
||||||
|
const currentYear = new Date().getFullYear();
|
||||||
|
const { data } = await apiClient.get<DashboardOverviewData>("/dashboard/overview", {
|
||||||
|
params: {
|
||||||
|
year: params.year ?? currentYear,
|
||||||
|
recent_limit: params.recent_limit ?? 10,
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { useCallback } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import type { TFunction } from "i18next";
|
||||||
|
import { REGION_LABELS } from "@/constants/regionCodes";
|
||||||
|
import { getOrderTypeLabel } from "@/constants/orderTypes";
|
||||||
|
import type { LocalizedName, OrderType } from "@/features/dashboard/api/analyticsApi";
|
||||||
|
|
||||||
|
// ─── Formatting ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function formatNumber(value: number | null | undefined, digits = 0): string {
|
||||||
|
if (value === null || value === undefined || !Number.isFinite(value)) return "—";
|
||||||
|
return value.toLocaleString(undefined, { maximumFractionDigits: digits, minimumFractionDigits: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatTmt(value: number | null | undefined): string {
|
||||||
|
if (value === null || value === undefined) return "—";
|
||||||
|
return `${formatNumber(value, 2)} TMT`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatPercent(value: number | null | undefined): string {
|
||||||
|
if (value === null || value === undefined) return "—";
|
||||||
|
return `${formatNumber(value, 1)}%`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hours → "45 min", "5.5 sag", "2.1 gün" style. */
|
||||||
|
export function formatDuration(hours: number | null | undefined, t: TFunction): string {
|
||||||
|
if (hours === null || hours === undefined || !Number.isFinite(hours)) return "—";
|
||||||
|
const minutes = Math.round(hours * 60);
|
||||||
|
if (minutes < 60) return `${minutes} ${t("analytics.unit.min", "min")}`;
|
||||||
|
if (hours < 48) return `${formatNumber(hours, 1)} ${t("analytics.unit.hours", "sag")}`;
|
||||||
|
return `${formatNumber(hours / 24, 1)} ${t("analytics.unit.days", "gün")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Picks the current UI language from a backend { tm, ru, en } name. */
|
||||||
|
export function useLocalizedName() {
|
||||||
|
const { i18n } = useTranslation();
|
||||||
|
const short = i18n.language?.slice(0, 2);
|
||||||
|
const lang = (short === "tk" ? "tm" : short) as keyof LocalizedName;
|
||||||
|
return useCallback((name: LocalizedName | null | undefined): string => name?.[lang] || name?.tm || name?.ru || name?.en || "—", [lang]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function orderTypeLabel(type: OrderType | string, t: TFunction): string {
|
||||||
|
return getOrderTypeLabel(type, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function regionLabel(code: string, t: TFunction): string {
|
||||||
|
if (code === "unknown") return t("analytics.unknown", "Näbelli");
|
||||||
|
return t(`loanOrders.regions.${code}`, REGION_LABELS[code] ?? code);
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { AlertCircle, Info, RefreshCw } from "lucide-react";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { formatNumber } from "./analyticsFormat";
|
||||||
|
|
||||||
|
// ─── Register panel ───────────────────────────────────────────────────────────
|
||||||
|
// One bordered surface whose regions are divided by hairlines instead of being
|
||||||
|
// separate floating cards. This is the base container for every dashboard block.
|
||||||
|
|
||||||
|
interface RegisterPanelProps {
|
||||||
|
children: ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RegisterPanel({ children, className }: RegisterPanelProps) {
|
||||||
|
return <div className={cn("overflow-hidden rounded-panel border border-border bg-card", className)}>{children}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── One cell of a register (title + optional description + content) ─────────
|
||||||
|
|
||||||
|
interface SectionCardProps {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
isLoading?: boolean;
|
||||||
|
isError?: boolean;
|
||||||
|
onRetry?: () => void;
|
||||||
|
/** Border classes that draw the cell dividers inside the parent register. */
|
||||||
|
className?: string;
|
||||||
|
contentClassName?: string;
|
||||||
|
action?: ReactNode;
|
||||||
|
skeletonHeight?: number;
|
||||||
|
children?: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SectionCard({
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
isLoading,
|
||||||
|
isError,
|
||||||
|
onRetry,
|
||||||
|
className,
|
||||||
|
contentClassName,
|
||||||
|
action,
|
||||||
|
skeletonHeight = 200,
|
||||||
|
children,
|
||||||
|
}: SectionCardProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<div className={cn("px-5 py-4 lg:px-6 lg:py-5", className)}>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-[14px] font-semibold tracking-tight">{title}</p>
|
||||||
|
{description && <p className="mt-1 text-[12.5px] text-muted-foreground">{description}</p>}
|
||||||
|
</div>
|
||||||
|
{action}
|
||||||
|
</div>
|
||||||
|
<div className={cn("mt-5", contentClassName)}>
|
||||||
|
{isLoading ? (
|
||||||
|
<Skeleton className="w-full rounded-md" style={{ height: skeletonHeight }} />
|
||||||
|
) : isError ? (
|
||||||
|
<div className="flex flex-col items-center justify-center gap-3 py-8 text-center" style={{ minHeight: skeletonHeight }}>
|
||||||
|
<div className="flex size-10 items-center justify-center rounded-full bg-destructive/10 text-destructive">
|
||||||
|
<AlertCircle className="size-5" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">{t("dashboard.errorTitle", "Maglumatlary ýükläp bolmady")}</p>
|
||||||
|
{onRetry && (
|
||||||
|
<Button variant="outline" size="sm" className="gap-2" onClick={onRetry}>
|
||||||
|
<RefreshCw className="size-3.5" aria-hidden="true" />
|
||||||
|
{t("common.retry", "Täzeden synanyş")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
children
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EmptyState({ height = 160 }: { height?: number }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center text-[13px] text-muted-foreground" style={{ height }}>
|
||||||
|
{t("dashboard.noData", "Maglumat ýok")}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Horizontal bar list (label · measured rule · value) ────────────────────
|
||||||
|
// The unfilled remainder is a 1px rule in the track tone and the value is a 3px
|
||||||
|
// bar sitting on it, so the chart reads like a measuring line, not a pill.
|
||||||
|
|
||||||
|
export interface BarListRow {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
value: number;
|
||||||
|
/** Text on the right; defaults to the formatted value. */
|
||||||
|
valueText?: ReactNode;
|
||||||
|
/** Secondary text under the label, e.g. approval rate. */
|
||||||
|
sub?: ReactNode;
|
||||||
|
/** Bar width as a share of the whole (0–100). Without it, bars are scaled to the largest row. */
|
||||||
|
share?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BarListProps {
|
||||||
|
rows: BarListRow[];
|
||||||
|
color?: string;
|
||||||
|
/** Collapse rows with value 0 into one muted line instead of listing them. */
|
||||||
|
hideEmpty?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BarList({ rows, color = "var(--chart-1)", hideEmpty }: BarListProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const visible = hideEmpty ? rows.filter((r) => r.value > 0) : rows;
|
||||||
|
const hidden = rows.length - visible.length;
|
||||||
|
const max = Math.max(1, ...rows.map((r) => r.value));
|
||||||
|
if (visible.length === 0) return <EmptyState height={120} />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{visible.map((row) => (
|
||||||
|
<div key={row.key}>
|
||||||
|
<div className="flex items-baseline justify-between gap-3 text-[13.5px]">
|
||||||
|
<span className="min-w-0 truncate text-foreground" title={row.label}>
|
||||||
|
{row.label}
|
||||||
|
</span>
|
||||||
|
<span className="shrink-0 tabular-nums">{row.valueText ?? formatNumber(row.value)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="relative mt-2.5 h-[2px] bg-track">
|
||||||
|
<div
|
||||||
|
className="absolute -top-[1.5px] left-0 h-[5px] rounded-[2px] transition-[width] duration-500"
|
||||||
|
style={{ width: `${row.share ?? (row.value / max) * 100}%`, background: color }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{row.sub && <div className="mt-2 text-[11.5px] text-muted-foreground">{row.sub}</div>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{hidden > 0 && (
|
||||||
|
<p
|
||||||
|
className="flex items-center gap-2 border-t border-border pt-3 text-[11.5px] text-muted-foreground"
|
||||||
|
title={rows
|
||||||
|
.filter((r) => r.value === 0)
|
||||||
|
.map((r) => r.label)
|
||||||
|
.join(", ")}
|
||||||
|
>
|
||||||
|
<Info className="size-3.5 shrink-0" aria-hidden="true" />
|
||||||
|
{t("analytics.emptyRows", "+{{count}} görnüşde sargyt ýok", { count: hidden })}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,439 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import type { TFunction } from "i18next";
|
||||||
|
import { Info } from "lucide-react";
|
||||||
|
import { Cell, Pie, PieChart } from "recharts";
|
||||||
|
import { getEducationLabel, getMarriageLabel } from "@/constants/formOptions";
|
||||||
|
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
|
||||||
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import type { ApprovalCount, CountItem, CustomersData, ProductsData } from "../api/analyticsApi";
|
||||||
|
import { BarList, EmptyState, RegisterPanel, SectionCard, type BarListRow } from "./analyticsShared";
|
||||||
|
import { formatNumber, formatPercent, useLocalizedName } from "./analyticsFormat";
|
||||||
|
|
||||||
|
interface QueryProps<T> {
|
||||||
|
data?: T;
|
||||||
|
isLoading: boolean;
|
||||||
|
isError: boolean;
|
||||||
|
onRetry: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One meaning per colour across the dashboard: teal = loans / approved,
|
||||||
|
// mid teal = cards, light teal = secondary share, sand = waiting, clay = rejected.
|
||||||
|
const LOAN_COLOR = "var(--chart-1)";
|
||||||
|
const CARD_COLOR = "var(--chart-2)";
|
||||||
|
const SHARE_COLOR = "var(--chart-3)";
|
||||||
|
const GOOD_COLOR = "var(--chart-1)";
|
||||||
|
const WAIT_COLOR = "var(--chart-4)";
|
||||||
|
const BAD_COLOR = "var(--chart-5)";
|
||||||
|
|
||||||
|
/** Below this many decided orders an approval rate is shown but flagged as unreliable. */
|
||||||
|
const MIN_DECIDED = 5;
|
||||||
|
|
||||||
|
/** Shared 2×2 cell dividers: vertical rule + row rule, collapsing to stacked rows on mobile. */
|
||||||
|
const CELL_BORDERS = [
|
||||||
|
"border-b border-border md:border-r",
|
||||||
|
"border-b border-border",
|
||||||
|
"border-b border-border md:border-b-0 md:border-r",
|
||||||
|
"border-b-0",
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Donut geometry — the empty remainder is drawn as a static ring behind the chart. */
|
||||||
|
const DONUT_SIZE = 164;
|
||||||
|
const DONUT_INNER = 56;
|
||||||
|
const DONUT_OUTER = 72;
|
||||||
|
|
||||||
|
/** "3 sargyt · 60%" — count first, share muted. */
|
||||||
|
function CountShare({ count, percent }: { count: number; percent: number }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<span className="font-semibold">
|
||||||
|
{formatNumber(count)} {t("analytics.kpi.orders", "sargyt")}
|
||||||
|
</span>
|
||||||
|
<span className="text-muted-foreground"> · {formatNumber(percent, 1)}%</span>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function InfoHint({ children, className }: { children: ReactNode; className?: string }) {
|
||||||
|
return (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<button type="button" className={cn("inline-flex cursor-help", className ?? "text-muted-foreground hover:text-foreground")}>
|
||||||
|
<Info className="size-3.5" aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent className="max-w-xs leading-relaxed">{children}</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Donut with the total in the middle ──────────────────────────────────────
|
||||||
|
|
||||||
|
interface DonutRow {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
color: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TotalDonut({ items, rows: rowDefs }: { items: CountItem[]; rows: DonutRow[] }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const byKey = new Map(items.map((it) => [it.key, it]));
|
||||||
|
// Fixed row order and colors, so "unpaid" is always sand and never swaps with "paid".
|
||||||
|
const known = new Set(rowDefs.map((r) => r.key));
|
||||||
|
const extra = items.filter((it) => !known.has(it.key)).map((it) => ({ key: it.key, label: it.key, color: "var(--muted-foreground)" }));
|
||||||
|
const rows = [...rowDefs, ...extra].map((r) => ({
|
||||||
|
...r,
|
||||||
|
count: byKey.get(r.key)?.count ?? 0,
|
||||||
|
percent: byKey.get(r.key)?.percent ?? 0,
|
||||||
|
}));
|
||||||
|
const total = rows.reduce((s, r) => s + r.count, 0);
|
||||||
|
if (total === 0) return <EmptyState height={140} />;
|
||||||
|
const config = Object.fromEntries(rows.map((r) => [r.label, { label: r.label, color: r.color }]));
|
||||||
|
// Recharts derives its own slice angles; a pre-computed `percent` on the datum
|
||||||
|
// would be read as geometry, so the chart rows carry the count only.
|
||||||
|
const chartRows = rows.map(({ key, label, color, count }) => ({ key, label, color, count }));
|
||||||
|
const ringRadius = (DONUT_INNER + DONUT_OUTER) / 2;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-start gap-6 sm:flex-row sm:items-center">
|
||||||
|
<div className="relative shrink-0" style={{ width: DONUT_SIZE, height: DONUT_SIZE }}>
|
||||||
|
<svg viewBox={`0 0 ${DONUT_SIZE} ${DONUT_SIZE}`} className="absolute inset-0 size-full" aria-hidden="true">
|
||||||
|
<circle
|
||||||
|
cx={DONUT_SIZE / 2}
|
||||||
|
cy={DONUT_SIZE / 2}
|
||||||
|
r={ringRadius}
|
||||||
|
fill="none"
|
||||||
|
stroke="var(--track)"
|
||||||
|
strokeWidth={DONUT_OUTER - DONUT_INNER}
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
<ChartContainer config={config} className="aspect-square h-full w-full">
|
||||||
|
<PieChart>
|
||||||
|
<Pie
|
||||||
|
data={chartRows}
|
||||||
|
dataKey="count"
|
||||||
|
nameKey="label"
|
||||||
|
innerRadius={DONUT_INNER}
|
||||||
|
outerRadius={DONUT_OUTER}
|
||||||
|
strokeWidth={3}
|
||||||
|
stroke="var(--card)"
|
||||||
|
>
|
||||||
|
{chartRows.map((r) => (
|
||||||
|
<Cell key={r.key} fill={r.color} />
|
||||||
|
))}
|
||||||
|
</Pie>
|
||||||
|
<ChartTooltip content={<ChartTooltipContent nameKey="label" hideLabel />} />
|
||||||
|
</PieChart>
|
||||||
|
</ChartContainer>
|
||||||
|
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
|
||||||
|
<span className="text-[26px] font-semibold leading-none tabular-nums tracking-tight">{formatNumber(total)}</span>
|
||||||
|
<span className="mt-1 text-[11px] text-muted-foreground">{t("analytics.kpi.orders", "sargyt")}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1 space-y-4">
|
||||||
|
{rows.map((r) => (
|
||||||
|
<div key={r.key}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="size-2.5 shrink-0 rounded-[3px]" style={{ background: r.color }} aria-hidden="true" />
|
||||||
|
<span className="truncate text-[13.5px]">{r.label}</span>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1.5 pl-5 text-[12.5px] tabular-nums text-muted-foreground">
|
||||||
|
{formatNumber(r.count)} <span className="text-muted-foreground/70">{formatNumber(r.percent, 1)}%</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Products ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function ProductsSection({ data, isLoading, isError, onRetry }: QueryProps<ProductsData>) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const localized = useLocalizedName();
|
||||||
|
const common = { isLoading, isError, onRetry, skeletonHeight: 170 };
|
||||||
|
|
||||||
|
const toRows = (items: ProductsData["loanTypes"]): BarListRow[] =>
|
||||||
|
items.map((it) => ({
|
||||||
|
key: String(it.id),
|
||||||
|
label: localized(it.name),
|
||||||
|
value: it.count,
|
||||||
|
share: it.percent,
|
||||||
|
valueText: <CountShare count={it.count} percent={it.percent} />,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<RegisterPanel>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2">
|
||||||
|
<SectionCard
|
||||||
|
className={CELL_BORDERS[0]}
|
||||||
|
title={t("analytics.products.sources", "Karz: Web we mobil")}
|
||||||
|
description={t("analytics.products.sourcesDesc", "Karz sargytlary nireden iberildi")}
|
||||||
|
{...common}
|
||||||
|
>
|
||||||
|
<TotalDonut
|
||||||
|
items={data?.loanSources ?? []}
|
||||||
|
rows={[
|
||||||
|
{ key: "mobile", label: t("analytics.source.mobile", "Mobil"), color: LOAN_COLOR },
|
||||||
|
{ key: "web", label: t("analytics.source.web", "Web"), color: SHARE_COLOR },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</SectionCard>
|
||||||
|
<SectionCard
|
||||||
|
className={CELL_BORDERS[1]}
|
||||||
|
title={t("analytics.products.cardPaid", "Kart sargytlary: töleg")}
|
||||||
|
description={t("analytics.products.cardPaidDesc", "Kart sargytlarynyň näçesi tölendi")}
|
||||||
|
{...common}
|
||||||
|
>
|
||||||
|
<TotalDonut
|
||||||
|
items={data?.cardOrderPay ?? []}
|
||||||
|
rows={[
|
||||||
|
{ key: "paid", label: t("analytics.paid", "Tölenen"), color: GOOD_COLOR },
|
||||||
|
{ key: "unpaid", label: t("analytics.unpaid", "Tölenmedik"), color: WAIT_COLOR },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</SectionCard>
|
||||||
|
<SectionCard
|
||||||
|
className={CELL_BORDERS[2]}
|
||||||
|
title={t("analytics.products.loanTypes", "Karz görnüşleri")}
|
||||||
|
description={t("analytics.products.loanTypesDesc", "Her görnüşiň ähli karz sargytlaryndaky paýy")}
|
||||||
|
{...common}
|
||||||
|
>
|
||||||
|
<BarList rows={toRows(data?.loanTypes ?? [])} color={LOAN_COLOR} hideEmpty />
|
||||||
|
</SectionCard>
|
||||||
|
<SectionCard
|
||||||
|
className={CELL_BORDERS[3]}
|
||||||
|
title={t("analytics.products.cardTypes", "Kart görnüşleri")}
|
||||||
|
description={t("analytics.products.cardTypesDesc", "Her görnüşiň ähli kart sargytlaryndaky paýy")}
|
||||||
|
{...common}
|
||||||
|
>
|
||||||
|
<BarList rows={toRows(data?.cardTypes ?? [])} color={CARD_COLOR} hideEmpty />
|
||||||
|
</SectionCard>
|
||||||
|
</div>
|
||||||
|
</RegisterPanel>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Customers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Approved / rejected / waiting counts as marked dots, then the approval rate. */
|
||||||
|
function Outcome({ item, t }: { item: ApprovalCount; t: TFunction }) {
|
||||||
|
const decided = item.approved + item.rejected;
|
||||||
|
const parts = [
|
||||||
|
{ n: item.approved, color: GOOD_COLOR, label: t("analytics.outcome.approved", "tassyklandy") },
|
||||||
|
{ n: item.rejected, color: BAD_COLOR, label: t("analytics.outcome.rejected", "ret edildi") },
|
||||||
|
{ n: item.open, color: WAIT_COLOR, label: t("analytics.outcome.open", "garaşýar"), pending: true },
|
||||||
|
].filter((p) => p.n > 0);
|
||||||
|
|
||||||
|
const fewData = decided > 0 && decided < MIN_DECIDED;
|
||||||
|
|
||||||
|
// Two fixed columns: counts on the left, approval rate pinned right — so every row lines up the same way.
|
||||||
|
return (
|
||||||
|
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3">
|
||||||
|
<span className="flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-0.5">
|
||||||
|
{parts.map((p) => (
|
||||||
|
<span key={p.label} className="inline-flex items-center gap-1 whitespace-nowrap">
|
||||||
|
<span
|
||||||
|
className={cn("size-2 shrink-0 rounded-full", p.pending && "border border-dashed bg-transparent")}
|
||||||
|
style={p.pending ? { borderColor: p.color } : { background: p.color }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
{formatNumber(p.n)} {p.label}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
{decided === 0 ? (
|
||||||
|
<span className="whitespace-nowrap">{t("analytics.outcome.noDecision", "Karar entek ýok")}</span>
|
||||||
|
) : (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className="inline-flex cursor-help items-baseline gap-1 whitespace-nowrap tabular-nums">
|
||||||
|
<span
|
||||||
|
className={
|
||||||
|
fewData
|
||||||
|
? "font-medium text-muted-foreground underline decoration-dotted underline-offset-2"
|
||||||
|
: "font-semibold text-foreground"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{formatPercent(item.approvalRate)}
|
||||||
|
</span>
|
||||||
|
<span className="text-muted-foreground/80">
|
||||||
|
{formatNumber(item.approved)}/{formatNumber(decided)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent className="max-w-xs leading-relaxed">
|
||||||
|
{fewData
|
||||||
|
? t("analytics.outcome.fewDataHint", "Az maglumat: diňe {{count}} karar bar, göterim takyk däl", { count: decided })
|
||||||
|
: t("analytics.outcome.rateHint", "Tassyklama derejesi: tassyklanan / karar berlen")}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function approvalRows(items: ApprovalCount[], labelFor: (key: string) => string, t: TFunction): BarListRow[] {
|
||||||
|
return items.map((it) => ({
|
||||||
|
key: it.key,
|
||||||
|
label: labelFor(it.key),
|
||||||
|
value: it.count,
|
||||||
|
share: it.percent,
|
||||||
|
valueText: <CountShare count={it.count} percent={it.percent} />,
|
||||||
|
sub: <Outcome item={it} t={t} />,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Anchor band: the five headline customer metrics on one dark surface ────
|
||||||
|
|
||||||
|
function BandStat({ label, value, color, pending }: { label: string; value: string; color?: string; pending?: boolean }) {
|
||||||
|
return (
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="flex items-center gap-1.5 text-[11.5px] font-medium uppercase tracking-[0.07em] text-surface-strong-muted">
|
||||||
|
{color && (
|
||||||
|
<span
|
||||||
|
className={cn("size-2 shrink-0 rounded-full", pending && "border border-dashed bg-transparent")}
|
||||||
|
style={pending ? { borderColor: color } : { background: color }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<span className="truncate">{label}</span>
|
||||||
|
</p>
|
||||||
|
<p className="mt-2.5 text-[28px] font-semibold leading-none tracking-tight tabular-nums text-surface-strong-foreground">{value}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CustomersSummary({ data, isLoading }: { data?: CustomersData; isLoading: boolean }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
// The endpoint reports totals per dimension but may omit the headline counts.
|
||||||
|
// When they are absent, ages are the one dimension that covers every applicant,
|
||||||
|
// so they are the honest source for the band.
|
||||||
|
const fromGroups = data?.ageGroups?.length
|
||||||
|
? data.ageGroups.reduce(
|
||||||
|
(acc, g) => ({
|
||||||
|
approved: acc.approved + (g.approved ?? 0),
|
||||||
|
rejected: acc.rejected + (g.rejected ?? 0),
|
||||||
|
open: acc.open + (g.open ?? 0),
|
||||||
|
}),
|
||||||
|
{ approved: 0, rejected: 0, open: 0 },
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const approved = data?.approved ?? fromGroups?.approved;
|
||||||
|
const rejected = data?.rejected ?? fromGroups?.rejected;
|
||||||
|
const open = data?.open ?? fromGroups?.open;
|
||||||
|
const decided = (approved ?? 0) + (rejected ?? 0);
|
||||||
|
const approvalRate = data?.approvalRate ?? (decided > 0 ? ((approved ?? 0) / decided) * 100 : null);
|
||||||
|
|
||||||
|
const rateValue = formatPercent(approvalRate);
|
||||||
|
const width = typeof approvalRate === "number" ? `${Math.min(100, Math.max(0, approvalRate))}%` : "0%";
|
||||||
|
const rateHint = t(
|
||||||
|
"analytics.customers.approvalHint",
|
||||||
|
"Tassyklama derejesi = tassyklanan ÷ (tasyklanan + ret edilen). Garaşýan sargytlar hasaba alynmaýar.",
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-panel bg-surface-strong px-5 py-[18px] lg:px-7">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3 lg:grid-cols-5">
|
||||||
|
{Array.from({ length: 5 }, (_, i) => (
|
||||||
|
<div key={i} className="h-10 animate-pulse rounded-md bg-surface-strong-foreground/10" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3 lg:grid-cols-5 lg:items-end">
|
||||||
|
<BandStat label={t("analytics.customers.totalOrders", "Jemi karz sargytlary")} value={formatNumber(data?.total)} />
|
||||||
|
<BandStat label={t("analytics.outcome.approvedTitle", "Tassyklandy")} value={formatNumber(approved)} color="var(--chart-3)" />
|
||||||
|
<BandStat label={t("analytics.outcome.rejectedTitle", "Ret edildi")} value={formatNumber(rejected)} color="var(--chart-5)" />
|
||||||
|
<BandStat label={t("analytics.outcome.openTitle", "Garaşýar")} value={formatNumber(open)} color="var(--chart-4)" pending />
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="flex items-center gap-1.5 text-[11.5px] font-medium uppercase tracking-[0.07em] text-surface-strong-muted">
|
||||||
|
<span className="truncate">{t("analytics.customers.approvalRate", "Tassyklama derejesi")}</span>
|
||||||
|
<InfoHint className="text-surface-strong-muted hover:text-surface-strong-foreground">{rateHint}</InfoHint>
|
||||||
|
</p>
|
||||||
|
<p className="mt-2.5 text-[28px] font-semibold leading-none tracking-tight tabular-nums text-surface-strong-foreground">
|
||||||
|
{rateValue}
|
||||||
|
</p>
|
||||||
|
<span className="mt-3 block h-1 w-full overflow-hidden rounded-full bg-surface-strong-foreground/15">
|
||||||
|
<span className="block h-full rounded-full bg-surface-strong-foreground/70" style={{ width }} />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CustomersSectionProps extends QueryProps<CustomersData> {
|
||||||
|
/** Product breakdown is a sibling query, passed in so both blocks refresh together. */
|
||||||
|
products: QueryProps<ProductsData>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CustomersSection({ data, isLoading, isError, onRetry, products }: CustomersSectionProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
// One error card instead of four identical ones.
|
||||||
|
if (isError) {
|
||||||
|
return (
|
||||||
|
<RegisterPanel>
|
||||||
|
<SectionCard title={t("analytics.customers.title", "Müşderiler")} isError onRetry={onRetry} skeletonHeight={160} />
|
||||||
|
</RegisterPanel>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const unknown = t("analytics.unknown", "Näbelli");
|
||||||
|
const ageLabel = (k: string) =>
|
||||||
|
k === "under25" ? t("analytics.age.under25", "25 ýaşdan kiçi") : k === "unknown" ? unknown : `${k} ${t("analytics.age.years", "ýaş")}`;
|
||||||
|
const educationLabel = (k: string) => (k === "unknown" ? unknown : getEducationLabel(k, t));
|
||||||
|
const marriageLabel = (k: string) => (k === "unknown" ? unknown : getMarriageLabel(k, t));
|
||||||
|
const guarantorLabel = (k: string) =>
|
||||||
|
({
|
||||||
|
none: t("analytics.guarantors.none", "Zamunsyz"),
|
||||||
|
one: t("analytics.guarantors.one", "1 zamun"),
|
||||||
|
two: t("analytics.guarantors.two", "2 zamun"),
|
||||||
|
})[k] ?? k;
|
||||||
|
|
||||||
|
const cards: { title: string; items?: ApprovalCount[]; label: (k: string) => string }[] = [
|
||||||
|
{ title: t("analytics.customers.age", "Ýaş toparlary"), items: data?.ageGroups, label: ageLabel },
|
||||||
|
{ title: t("analytics.customers.education", "Bilimi"), items: data?.education, label: educationLabel },
|
||||||
|
{ title: t("analytics.customers.marriage", "Maşgala ýagdaýy"), items: data?.marriageStatus, label: marriageLabel },
|
||||||
|
{ title: t("analytics.customers.guarantors", "Zamunlar"), items: data?.guarantors, label: guarantorLabel },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3.5">
|
||||||
|
<CustomersSummary data={data} isLoading={isLoading} />
|
||||||
|
|
||||||
|
<ProductsSection {...products} />
|
||||||
|
|
||||||
|
<RegisterPanel>
|
||||||
|
<div className="flex flex-col gap-1 border-b border-border px-5 py-3.5 sm:flex-row sm:items-baseline sm:justify-between lg:px-6">
|
||||||
|
<p className="text-[13px] text-muted-foreground">
|
||||||
|
{t("analytics.customers.desc", "Saýlanan döwürde karz sargydyny berenleriň profili")}
|
||||||
|
</p>
|
||||||
|
<span className="flex items-center gap-1.5 text-[11.5px] text-muted-foreground/80">
|
||||||
|
{t("analytics.customers.approvalRate", "Tassyklama derejesi")}
|
||||||
|
<InfoHint>
|
||||||
|
{t(
|
||||||
|
"analytics.customers.approvalHint",
|
||||||
|
"Tassyklama derejesi = tassyklanan ÷ (tasyklanan + ret edilen). Garaşýan sargytlar hasaba alynmaýar.",
|
||||||
|
)}
|
||||||
|
</InfoHint>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2">
|
||||||
|
{cards.map((c, i) => (
|
||||||
|
<SectionCard key={c.title} className={CELL_BORDERS[i]} title={c.title} isLoading={isLoading} skeletonHeight={180}>
|
||||||
|
<BarList rows={approvalRows(c.items ?? [], c.label, t)} color={LOAN_COLOR} />
|
||||||
|
</SectionCard>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</RegisterPanel>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
getAnalyticsBacklog,
|
||||||
|
getAnalyticsBranches,
|
||||||
|
getAnalyticsCustomers,
|
||||||
|
getAnalyticsFinance,
|
||||||
|
getAnalyticsProducts,
|
||||||
|
getAnalyticsSystem,
|
||||||
|
type AnalyticsParams,
|
||||||
|
} from "../api/analyticsApi";
|
||||||
|
|
||||||
|
export const ANALYTICS_KEY = "dashboard-analytics";
|
||||||
|
|
||||||
|
const STALE_TIME = 60 * 1000;
|
||||||
|
|
||||||
|
function useAnalyticsQuery<T>(
|
||||||
|
name: string,
|
||||||
|
fetcher: (params: AnalyticsParams, signal?: AbortSignal) => Promise<T>,
|
||||||
|
params: AnalyticsParams,
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: [ANALYTICS_KEY, name, params],
|
||||||
|
queryFn: ({ signal }) => fetcher(params, signal),
|
||||||
|
staleTime: STALE_TIME,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useAnalyticsFinance = (params: AnalyticsParams) => useAnalyticsQuery("finance", getAnalyticsFinance, params);
|
||||||
|
export const useAnalyticsBacklog = (params: AnalyticsParams) => useAnalyticsQuery("backlog", getAnalyticsBacklog, params);
|
||||||
|
export const useAnalyticsBranches = (params: AnalyticsParams) => useAnalyticsQuery("branches", getAnalyticsBranches, params);
|
||||||
|
export const useAnalyticsProducts = (params: AnalyticsParams) => useAnalyticsQuery("products", getAnalyticsProducts, params);
|
||||||
|
export const useAnalyticsCustomers = (params: AnalyticsParams) => useAnalyticsQuery("customers", getAnalyticsCustomers, params);
|
||||||
|
export const useAnalyticsSystem = (params: AnalyticsParams) => useAnalyticsQuery("system", getAnalyticsSystem, params);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { getDashboardOverview, type DashboardOverviewParams } from "../api/dashboardApi";
|
||||||
|
|
||||||
|
export const DASHBOARD_OVERVIEW_KEY = "dashboard-overview";
|
||||||
|
|
||||||
|
export function useDashboardOverview(params: DashboardOverviewParams = {}) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: [DASHBOARD_OVERVIEW_KEY, params],
|
||||||
|
queryFn: ({ signal }) => getDashboardOverview(params, signal),
|
||||||
|
staleTime: 60 * 1000,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,99 +1,88 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
|
// ─── Localized text (backend keys: tm | ru | en) ──────────────────────────────
|
||||||
|
|
||||||
|
export interface LocalizedText {
|
||||||
|
tm?: string;
|
||||||
|
ru?: string;
|
||||||
|
en?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LocalizedDistrictField = string | LocalizedText;
|
||||||
|
|
||||||
|
export function resolveDistrictName(val: LocalizedDistrictField | null | undefined, lang = "tm"): string {
|
||||||
|
if (!val) return "";
|
||||||
|
if (typeof val === "string") return val;
|
||||||
|
const key = (lang === "tk" ? "tm" : lang) as keyof LocalizedText;
|
||||||
|
return val[key] ?? val.tm ?? val.en ?? val.ru ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── District (Province) ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface District {
|
export interface District {
|
||||||
id: number
|
id: number;
|
||||||
name: Record<'tk' | 'ru' | 'en', string>
|
name: LocalizedDistrictField;
|
||||||
description: string | null
|
region: LocalizedDistrictField;
|
||||||
isActive: boolean
|
active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DistrictListParams {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
search?: string;
|
||||||
|
active?: string;
|
||||||
|
region?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DistrictListResponse {
|
export interface DistrictListResponse {
|
||||||
data: District[]
|
count: number;
|
||||||
total: number
|
provinces: District[];
|
||||||
page: number
|
|
||||||
perPage: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── API Payloads ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface CreateDistrictPayload {
|
export interface CreateDistrictPayload {
|
||||||
name: Record<'tk' | 'ru' | 'en', string>
|
active: boolean;
|
||||||
description: string | null
|
name: LocalizedText;
|
||||||
isActive: boolean
|
region: LocalizedText;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateDistrictPayload extends CreateDistrictPayload {
|
export interface UpdateDistrictPayload extends CreateDistrictPayload {
|
||||||
id: number
|
id: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MOCK_DISTRICTS: District[] = [
|
// ─── District CRUD ────────────────────────────────────────────────────────────
|
||||||
{ id: 1, name: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' }, description: null, isActive: true },
|
|
||||||
{ id: 2, name: { tk: 'Änew', ru: 'Анев', en: 'Anew' }, description: null, isActive: true },
|
|
||||||
{ id: 3, name: { tk: 'Baýramaly', ru: 'Байрамалы', en: 'Bayramaly' }, description: null, isActive: true },
|
|
||||||
{ id: 4, name: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' }, description: null, isActive: true },
|
|
||||||
{ id: 5, name: { tk: 'Mary', ru: 'Мары', en: 'Mary' }, description: null, isActive: true },
|
|
||||||
{ id: 6, name: { tk: 'Türkmenabat', ru: 'Туркменабат', en: 'Turkmenabat' }, description: null, isActive: false },
|
|
||||||
{ id: 7, name: { tk: 'Balkanabat', ru: 'Балканабат', en: 'Balkanabat' }, description: null, isActive: true },
|
|
||||||
]
|
|
||||||
|
|
||||||
let mockStore = [...MOCK_DISTRICTS]
|
export async function fetchDistricts(params: DistrictListParams = {}): Promise<DistrictListResponse> {
|
||||||
let nextId = 8
|
const { page, limit, search, active, region } = params;
|
||||||
|
const { data } = await apiClient.get<DistrictListResponse>("/provinces", {
|
||||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
params: {
|
||||||
|
page,
|
||||||
export async function fetchDistricts(params: {
|
limit,
|
||||||
page?: number
|
name: search || undefined,
|
||||||
perPage?: number
|
region: region || undefined,
|
||||||
search?: string
|
active: active || undefined,
|
||||||
isActive?: string
|
},
|
||||||
}): Promise<DistrictListResponse> {
|
});
|
||||||
await delay()
|
return data;
|
||||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
|
||||||
|
|
||||||
let filtered = mockStore.filter((item) => {
|
|
||||||
const matchSearch =
|
|
||||||
!search ||
|
|
||||||
Object.values(item.name).some((n) =>
|
|
||||||
n.toLowerCase().includes(search.toLowerCase())
|
|
||||||
)
|
|
||||||
const matchActive =
|
|
||||||
isActive === '' || isActive === undefined
|
|
||||||
? true
|
|
||||||
: isActive === 'true'
|
|
||||||
? item.isActive
|
|
||||||
: !item.isActive
|
|
||||||
return matchSearch && matchActive
|
|
||||||
})
|
|
||||||
|
|
||||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
|
||||||
|
|
||||||
const total = filtered.length
|
|
||||||
const start = (page - 1) * perPage
|
|
||||||
const data = filtered.slice(start, start + perPage)
|
|
||||||
|
|
||||||
return { data, total, page, perPage }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchDistrictById(id: number): Promise<District> {
|
export async function fetchDistrictById(id: number): Promise<District> {
|
||||||
await delay()
|
const { data } = await apiClient.get<District>(`/provinces/${id}`);
|
||||||
const item = mockStore.find((c) => c.id === id)
|
return data;
|
||||||
if (!item) throw new Error('Not found')
|
|
||||||
return { ...item }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createDistrict(payload: CreateDistrictPayload): Promise<District> {
|
export async function createDistrict(payload: CreateDistrictPayload): Promise<District> {
|
||||||
await delay(400)
|
const { data } = await apiClient.post<District>("/provinces", payload);
|
||||||
const newItem: District = { id: nextId++, ...payload }
|
return data;
|
||||||
mockStore = [newItem, ...mockStore]
|
|
||||||
return newItem
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateDistrict(payload: UpdateDistrictPayload): Promise<District> {
|
export async function updateDistrict(payload: UpdateDistrictPayload): Promise<District> {
|
||||||
await delay(400)
|
const { id, ...rest } = payload;
|
||||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
const { data } = await apiClient.put<District>(`/provinces/${id}`, rest);
|
||||||
if (idx === -1) throw new Error('Not found')
|
return data;
|
||||||
const updated = { ...mockStore[idx], ...payload }
|
|
||||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
|
||||||
return updated
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteDistrict(id: number): Promise<void> {
|
export async function deleteDistrict(id: number): Promise<void> {
|
||||||
await delay(300)
|
await apiClient.delete(`/provinces/${id}`);
|
||||||
mockStore = mockStore.filter((c) => c.id !== id)
|
|
||||||
}
|
}
|
||||||
@@ -5,10 +5,9 @@ import { useForm } from "react-hook-form";
|
|||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import { FormActions } from "@/components/formActions";
|
import { FormActions } from "@/components/formActions";
|
||||||
import { FormInput } from "@/components/formInput";
|
|
||||||
import { MultiLangInput } from "@/components/multiLangInput";
|
import { MultiLangInput } from "@/components/multiLangInput";
|
||||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import type { District } from "../api/districtsApi";
|
import { resolveDistrictName, type District } from "../api/districtsApi";
|
||||||
import { useCreateDistrict, useUpdateDistrict } from "../hooks/useDistricts";
|
import { useCreateDistrict, useUpdateDistrict } from "../hooks/useDistricts";
|
||||||
import { createDistrictFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/district.schema";
|
import { createDistrictFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/district.schema";
|
||||||
import type { DistrictFormData } from "../schemas/district.schema";
|
import type { DistrictFormData } from "../schemas/district.schema";
|
||||||
@@ -31,11 +30,13 @@ export interface DistrictFormProps {
|
|||||||
|
|
||||||
function mapInitial(data: District): DistrictFormData {
|
function mapInitial(data: District): DistrictFormData {
|
||||||
return {
|
return {
|
||||||
nameTk: data.name.tk,
|
nameTk: resolveDistrictName(data.name, "tm"),
|
||||||
nameRu: data.name.ru,
|
nameRu: resolveDistrictName(data.name, "ru"),
|
||||||
nameEn: data.name.en,
|
nameEn: resolveDistrictName(data.name, "en"),
|
||||||
description: data.description ?? "",
|
regionTk: resolveDistrictName(data.region, "tm"),
|
||||||
isActive: data.isActive,
|
regionRu: resolveDistrictName(data.region, "ru"),
|
||||||
|
regionEn: resolveDistrictName(data.region, "en"),
|
||||||
|
isActive: data.active,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,6 +106,12 @@ export function DistrictForm({ mode, initialData }: DistrictFormProps) {
|
|||||||
en: { value: form.nameEn, onChange: set("nameEn"), error: errors.nameEn },
|
en: { value: form.nameEn, onChange: set("nameEn"), error: errors.nameEn },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const regionFields = {
|
||||||
|
tk: { value: form.regionTk, onChange: set("regionTk"), error: errors.regionTk },
|
||||||
|
ru: { value: form.regionRu, onChange: set("regionRu"), error: errors.regionRu },
|
||||||
|
en: { value: form.regionEn, onChange: set("regionEn"), error: errors.regionEn },
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
@@ -118,14 +125,12 @@ export function DistrictForm({ mode, initialData }: DistrictFormProps) {
|
|||||||
</p>
|
</p>
|
||||||
<MultiLangInput fields={nameFields} placeholder={t("districts.fields.name", "Ady")} />
|
<MultiLangInput fields={nameFields} placeholder={t("districts.fields.name", "Ady")} />
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard span="full">
|
||||||
<FormInput
|
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||||
type="text"
|
{t("districts.fields.region", "Region")}
|
||||||
label={t("districts.fields.description", "Bellikler")}
|
<span className="text-destructive ml-0.5">*</span>
|
||||||
value={form.description}
|
</p>
|
||||||
onChange={set("description")}
|
<MultiLangInput fields={regionFields} placeholder={t("districts.fields.region", "Region")} />
|
||||||
placeholder={t("districts.fields.description", "Bellikler")}
|
|
||||||
/>
|
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<div className="flex items-center gap-3 pt-1">
|
<div className="flex items-center gap-3 pt-1">
|
||||||
@@ -138,7 +143,6 @@ export function DistrictForm({ mode, initialData }: DistrictFormProps) {
|
|||||||
isPending={isPending}
|
isPending={isPending}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
onCancel={() => navigate("/settings/location/districts")}
|
onCancel={() => navigate("/settings/location/districts")}
|
||||||
cancelVariant="ghost"
|
|
||||||
submitLabel={mode === "create" ? t("districts.actions.create", "Etrap döret") : t("districts.actions.update", "Täzelemek")}
|
submitLabel={mode === "create" ? t("districts.actions.create", "Etrap döret") : t("districts.actions.update", "Täzelemek")}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,34 +1,57 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
import {
|
import {
|
||||||
fetchDistricts,
|
fetchDistricts,
|
||||||
fetchDistrictById,
|
fetchDistrictById,
|
||||||
createDistrict,
|
createDistrict,
|
||||||
updateDistrict,
|
updateDistrict,
|
||||||
deleteDistrict,
|
deleteDistrict,
|
||||||
|
type DistrictListParams,
|
||||||
type CreateDistrictPayload,
|
type CreateDistrictPayload,
|
||||||
type UpdateDistrictPayload,
|
type UpdateDistrictPayload,
|
||||||
} from '../api/districtsApi'
|
} from "../api/districtsApi";
|
||||||
|
|
||||||
export const districtKeys = {
|
export const districtKeys = {
|
||||||
all: ['districts'] as const,
|
all: ["districts"] as const,
|
||||||
lists: () => [...districtKeys.all, 'list'] as const,
|
lists: () => [...districtKeys.all, "list"] as const,
|
||||||
list: (params: Record<string, unknown>) =>
|
list: (params: DistrictListParams) => [...districtKeys.lists(), params] as const,
|
||||||
[...districtKeys.lists(), params] as const,
|
detail: (id: number) => [...districtKeys.all, "detail", id] as const,
|
||||||
detail: (id: number) => [...districtKeys.all, 'detail', id] as const,
|
};
|
||||||
|
|
||||||
|
export function useDistricts(params: DistrictListParams) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
|
const normalized = normalizeSearch(debouncedSearch);
|
||||||
|
const queryParams: DistrictListParams = { ...params, search: normalized || undefined };
|
||||||
|
|
||||||
|
return useQuery({
|
||||||
|
queryKey: districtKeys.list(queryParams),
|
||||||
|
queryFn: () => fetchDistricts(queryParams),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDistricts(params: {
|
const DISTRICT_PAGE_SIZE = 25;
|
||||||
page?: number
|
|
||||||
perPage?: number
|
/**
|
||||||
search?: string
|
* Paginated districts for infinite-scroll selects.
|
||||||
isActive?: string
|
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||||
}) {
|
*/
|
||||||
return useQuery({
|
export function useInfiniteDistricts(search = "", enabled = true) {
|
||||||
queryKey: districtKeys.list(params),
|
const debouncedSearch = useDebouncedValue(search);
|
||||||
queryFn: () => fetchDistricts(params),
|
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||||
})
|
|
||||||
|
return useInfiniteQuery({
|
||||||
|
queryKey: [...districtKeys.lists(), "infinite", effectiveSearch],
|
||||||
|
initialPageParam: 1,
|
||||||
|
queryFn: ({ pageParam }) => fetchDistricts({ page: pageParam, limit: DISTRICT_PAGE_SIZE, search: effectiveSearch }),
|
||||||
|
getNextPageParam: (lastPage, allPages) => {
|
||||||
|
const loaded = allPages.reduce((sum, p) => sum + (p?.provinces?.length ?? 0), 0);
|
||||||
|
const count = lastPage?.count ?? 0;
|
||||||
|
return loaded < count ? allPages.length + 1 : undefined;
|
||||||
|
},
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDistrictById(id: number) {
|
export function useDistrictById(id: number) {
|
||||||
@@ -36,45 +59,45 @@ export function useDistrictById(id: number) {
|
|||||||
queryKey: districtKeys.detail(id),
|
queryKey: districtKeys.detail(id),
|
||||||
queryFn: () => fetchDistrictById(id),
|
queryFn: () => fetchDistrictById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCreateDistrict() {
|
export function useCreateDistrict() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateDistrictPayload) => createDistrict(payload),
|
mutationFn: (payload: CreateDistrictPayload) => createDistrict(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: districtKeys.lists() });
|
||||||
toast.success(t('districts.toast.createSuccess', 'Etrap döredildi'))
|
toast.success(t("districts.toast.createSuccess", "Etrap döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUpdateDistrict() {
|
export function useUpdateDistrict() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateDistrictPayload) => updateDistrict(payload),
|
mutationFn: (payload: UpdateDistrictPayload) => updateDistrict(payload),
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: districtKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: districtKeys.detail(data.id) })
|
queryClient.invalidateQueries({ queryKey: districtKeys.detail(data.id) });
|
||||||
toast.success(t('districts.toast.updateSuccess', 'Etrap täzelendi'))
|
toast.success(t("districts.toast.updateSuccess", "Etrap täzelendi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDeleteDistrict() {
|
export function useDeleteDistrict() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => deleteDistrict(id),
|
mutationFn: (id: number) => deleteDistrict(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: districtKeys.lists() });
|
||||||
toast.success(t('districts.toast.deleteSuccess', 'Etrap öçürildi'))
|
toast.success(t("districts.toast.deleteSuccess", "Etrap öçürildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
@@ -1,30 +1,34 @@
|
|||||||
import { z } from 'zod'
|
import { z } from "zod";
|
||||||
import type { CreateDistrictPayload } from '../api/districtsApi'
|
import type { CreateDistrictPayload } from "../api/districtsApi";
|
||||||
|
|
||||||
export function createDistrictFormSchema(t: (key: string, fallback?: string) => string) {
|
export function createDistrictFormSchema(t: (key: string, fallback?: string) => string) {
|
||||||
return z.object({
|
return z.object({
|
||||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
description: z.string().optional(),
|
regionTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
regionRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
regionEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
isActive: z.boolean(),
|
isActive: z.boolean(),
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export type DistrictFormData = z.infer<ReturnType<typeof createDistrictFormSchema>>
|
export type DistrictFormData = z.infer<ReturnType<typeof createDistrictFormSchema>>;
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: DistrictFormData = {
|
export const DEFAULT_FORM_VALUES: DistrictFormData = {
|
||||||
nameTk: '',
|
nameTk: "",
|
||||||
nameRu: '',
|
nameRu: "",
|
||||||
nameEn: '',
|
nameEn: "",
|
||||||
description: '',
|
regionTk: "",
|
||||||
|
regionRu: "",
|
||||||
|
regionEn: "",
|
||||||
isActive: true,
|
isActive: true,
|
||||||
}
|
};
|
||||||
|
|
||||||
export function buildPayload(data: DistrictFormData): CreateDistrictPayload {
|
export function buildPayload(data: DistrictFormData): CreateDistrictPayload {
|
||||||
return {
|
return {
|
||||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
name: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||||
description: data.description?.trim() || null,
|
region: { tm: data.regionTk.trim(), ru: data.regionRu.trim(), en: data.regionEn.trim() },
|
||||||
isActive: data.isActive,
|
active: data.isActive,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
@@ -1,497 +1,83 @@
|
|||||||
import apiClient from "@/lib/api/client";
|
import apiClient from "@/lib/api/client";
|
||||||
|
import {
|
||||||
|
mapBackendToUI,
|
||||||
|
getLoanOrderById,
|
||||||
|
createLoanOrder,
|
||||||
|
updateLoanOrder,
|
||||||
|
patchLoanOrder,
|
||||||
|
deleteLoanOrder,
|
||||||
|
type LoanOrder,
|
||||||
|
type LoanOrderStatus,
|
||||||
|
type LoanOrderUser,
|
||||||
|
type LoanOrderPayload,
|
||||||
|
type LoanOrdersParams,
|
||||||
|
type LoanOrdersResponse,
|
||||||
|
type BackendLoanOrder,
|
||||||
|
type LoanOrdersListResponse,
|
||||||
|
} from "@/features/loanOrders/api/loanOrdersApi";
|
||||||
|
|
||||||
// ─── Types ─────────────────────────────────────────────────────────────────────
|
// ─── Type Aliases (Seamless backwards compatibility & domain clarity) ────────
|
||||||
|
|
||||||
export type LoanOrderMobileStatus = "GARAŞYLÝAR" | "KANAGATLANDYRYLAN" | "RED_EDILDI" | "IŞLENÝÄR";
|
export type { LoanOrderStatus, LoanOrder, LoanOrderUser, LoanOrderPayload, LoanOrdersParams, LoanOrdersResponse };
|
||||||
|
|
||||||
export interface LoanOrderMobile {
|
export type LoanOrderMobileStatus = LoanOrderStatus;
|
||||||
id: string;
|
export type LoanOrderMobile = LoanOrder;
|
||||||
loanType: string;
|
export type LoanOrderMobileUser = LoanOrderUser;
|
||||||
createdAt: string;
|
export type LoanOrderMobilePayload = LoanOrderPayload;
|
||||||
region: string;
|
export type LoanOrderMobileListParams = LoanOrdersParams;
|
||||||
branch: string;
|
export type LoanOrderMobilesResponse = LoanOrdersResponse;
|
||||||
branchId?: number | string;
|
export type PaginatedResponse<T> = {
|
||||||
loanTypeId?: number | string;
|
|
||||||
workCityId?: number | string;
|
|
||||||
createdById?: number | string;
|
|
||||||
firstName: string;
|
|
||||||
lastName: string;
|
|
||||||
phone: string;
|
|
||||||
status: LoanOrderMobileStatus;
|
|
||||||
createdBy?: string;
|
|
||||||
|
|
||||||
// ── Detail fields ─────────────────────────────────────────────────────────
|
|
||||||
patronicName?: string | null;
|
|
||||||
education?: string | null;
|
|
||||||
marriageStatus?: string | null;
|
|
||||||
dateOfBirth?: string | null;
|
|
||||||
residence?: string | null;
|
|
||||||
currentResidence?: string | null;
|
|
||||||
|
|
||||||
// Passport
|
|
||||||
passportSerie?: string | null;
|
|
||||||
passportNumber?: string | null;
|
|
||||||
passportDateOfIssue?: string | null;
|
|
||||||
passportGivenBy?: string | null;
|
|
||||||
bornPlace?: string | null;
|
|
||||||
passportPage1Url?: string | null;
|
|
||||||
passportPage23Url?: string | null;
|
|
||||||
passportPage89Url?: string | null;
|
|
||||||
passportPage32Url?: string | null;
|
|
||||||
|
|
||||||
// Contact
|
|
||||||
email?: string | null;
|
|
||||||
phoneAdditional?: string | null;
|
|
||||||
homePhone?: string | null;
|
|
||||||
|
|
||||||
// Employment
|
|
||||||
workCompany?: string | null;
|
|
||||||
workHrPhone?: string | null;
|
|
||||||
workRegion?: string | null;
|
|
||||||
workProvince?: string | null;
|
|
||||||
position?: string | null;
|
|
||||||
salary?: number | null;
|
|
||||||
workStartedAt?: string | null;
|
|
||||||
|
|
||||||
// New fields
|
|
||||||
note?: string | null;
|
|
||||||
loanAmount?: number | null;
|
|
||||||
loanHistory?: string | null;
|
|
||||||
|
|
||||||
// Card (Zähmet haky)
|
|
||||||
cardNumber?: string | null;
|
|
||||||
cardName?: string | null;
|
|
||||||
cardExpMonth?: string | null;
|
|
||||||
cardExpYear?: string | null;
|
|
||||||
|
|
||||||
// Guarantor (Zamun)
|
|
||||||
guarantor1Name?: string | null;
|
|
||||||
guarantor1Surname?: string | null;
|
|
||||||
guarantor1Patronic?: string | null;
|
|
||||||
guarantor1PassportSerie?: string | null;
|
|
||||||
guarantor1PassportNumber?: string | null;
|
|
||||||
guarantor1CardNumber?: string | null;
|
|
||||||
guarantor1CardName?: string | null;
|
|
||||||
guarantor1CardExpMonth?: string | null;
|
|
||||||
guarantor1CardExpYear?: string | null;
|
|
||||||
guarantor1Salary?: number | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LoanOrderMobilePayload {
|
|
||||||
status: string;
|
|
||||||
loanType: string;
|
|
||||||
region: string;
|
|
||||||
branch: string;
|
|
||||||
firstName: string;
|
|
||||||
lastName: string;
|
|
||||||
patronicName?: string;
|
|
||||||
education: string;
|
|
||||||
marriageStatus: string;
|
|
||||||
dateOfBirth: string;
|
|
||||||
residence: string;
|
|
||||||
currentResidence?: string;
|
|
||||||
passportSerie: string;
|
|
||||||
passportNumber: string;
|
|
||||||
passportDateOfIssue: string;
|
|
||||||
passportGivenBy: string;
|
|
||||||
bornPlace?: string;
|
|
||||||
email?: string;
|
|
||||||
phone: string;
|
|
||||||
phoneAdditional?: string;
|
|
||||||
homePhone?: string;
|
|
||||||
workCompany: string;
|
|
||||||
workHrPhone?: string;
|
|
||||||
workRegion?: string;
|
|
||||||
workProvince?: string;
|
|
||||||
position: string;
|
|
||||||
salary: number;
|
|
||||||
workStartedAt: string;
|
|
||||||
|
|
||||||
note?: string;
|
|
||||||
loanAmount?: number;
|
|
||||||
loanHistory?: string;
|
|
||||||
|
|
||||||
cardNumber?: string;
|
|
||||||
cardName?: string;
|
|
||||||
cardExpMonth?: string;
|
|
||||||
cardExpYear?: string;
|
|
||||||
|
|
||||||
guarantor1Name?: string;
|
|
||||||
guarantor1Surname?: string;
|
|
||||||
guarantor1Patronic?: string;
|
|
||||||
guarantor1PassportSerie?: string;
|
|
||||||
guarantor1PassportNumber?: string;
|
|
||||||
guarantor1CardNumber?: string;
|
|
||||||
guarantor1CardName?: string;
|
|
||||||
guarantor1CardExpMonth?: string;
|
|
||||||
guarantor1CardExpYear?: string;
|
|
||||||
guarantor1Salary?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LoanOrderMobileListParams {
|
|
||||||
search?: string;
|
|
||||||
region?: string;
|
|
||||||
status?: LoanOrderMobileStatus;
|
|
||||||
branch?: string;
|
|
||||||
archived?: string;
|
|
||||||
page?: number;
|
|
||||||
perPage?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PaginatedResponse<T> {
|
|
||||||
data: T[];
|
data: T[];
|
||||||
total: number;
|
total: number;
|
||||||
|
page?: number;
|
||||||
|
perPage?: number;
|
||||||
|
};
|
||||||
|
export type BackendLoanOrderMobile = BackendLoanOrder;
|
||||||
|
|
||||||
|
// ─── Shared CRUD API Functions (Re-exported from loanOrdersApi) ───────────────
|
||||||
|
|
||||||
|
export const getLoanOrderMobileById = getLoanOrderById;
|
||||||
|
export const updateLoanOrderMobile = updateLoanOrder;
|
||||||
|
export const patchLoanOrderMobile = patchLoanOrder;
|
||||||
|
export const deleteLoanOrderMobile = deleteLoanOrder;
|
||||||
|
|
||||||
|
export async function createLoanOrderMobile(payload: LoanOrderPayload): Promise<LoanOrder> {
|
||||||
|
return createLoanOrder({ ...payload, source: payload.source ?? "mobile" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Mock Data ─────────────────────────────────────────────────────────────────
|
// ─── Mobile-specific List API ──────────────────────────────────────────────────
|
||||||
|
|
||||||
const MOCK_DATA: LoanOrderMobile[] = [
|
export async function fetchLoanOrderMobiles(params: LoanOrdersParams = {}, signal?: AbortSignal): Promise<LoanOrdersResponse> {
|
||||||
{
|
const { page, perPage, limit, search, region, status, branch, branch_id, createdById, userId, user_id } = params;
|
||||||
id: "LOM-0001",
|
const branchId = branch || branch_id;
|
||||||
loanType: "Sarp ediş karzy",
|
const uid = createdById || userId || user_id;
|
||||||
createdAt: "2025-01-15 09:42",
|
|
||||||
region: "Aşgabat",
|
|
||||||
branch: "Merkezi şahamça",
|
|
||||||
branchId: 1,
|
|
||||||
loanTypeId: 1,
|
|
||||||
workCityId: 1,
|
|
||||||
createdById: "U-1001",
|
|
||||||
firstName: "Oraz",
|
|
||||||
lastName: "Annaýew",
|
|
||||||
phone: "+99361123456",
|
|
||||||
status: "GARAŞYLÝAR",
|
|
||||||
note: "Müşderi dokumentleri tassyklamady",
|
|
||||||
loanAmount: 15000,
|
|
||||||
loanHistory: "positive",
|
|
||||||
patronicName: "Myradowiç",
|
|
||||||
education: "high",
|
|
||||||
marriageStatus: "MARRIED",
|
|
||||||
dateOfBirth: "1992-04-18",
|
|
||||||
residence: "Aşgabat, Bitarap Türkmenistan şaýoly, 15",
|
|
||||||
currentResidence: "Aşgabat, Garaşsyzlyk köçesi, 5",
|
|
||||||
passportSerie: "I",
|
|
||||||
passportNumber: "123456",
|
|
||||||
passportDateOfIssue: "2015-03-10",
|
|
||||||
passportGivenBy: "Aşgabat şäheriniň Içeri işler müdirligi",
|
|
||||||
bornPlace: "Aşgabat şäheri",
|
|
||||||
email: "oraz.annayew@email.com",
|
|
||||||
phoneAdditional: "+99365443322",
|
|
||||||
workCompany: "Türkmennebit",
|
|
||||||
workHrPhone: "+99312456789",
|
|
||||||
workRegion: "Aşgabat",
|
|
||||||
workProvince: "Büzmeýin etraby",
|
|
||||||
position: "Inžener",
|
|
||||||
salary: 2500,
|
|
||||||
workStartedAt: "2018-06-01",
|
|
||||||
cardNumber: "4111111111111111",
|
|
||||||
cardName: "ORAZ ANNAÝEW",
|
|
||||||
cardExpMonth: "12",
|
|
||||||
cardExpYear: "2027",
|
|
||||||
guarantor1Name: "Berdi",
|
|
||||||
guarantor1Surname: "Berdiýew",
|
|
||||||
guarantor1Patronic: "Annagulyýewiç",
|
|
||||||
guarantor1PassportSerie: "II",
|
|
||||||
guarantor1PassportNumber: "654321",
|
|
||||||
guarantor1CardNumber: "4222222222222222",
|
|
||||||
guarantor1CardName: "BERDI BERDIÝEW",
|
|
||||||
guarantor1CardExpMonth: "06",
|
|
||||||
guarantor1CardExpYear: "2026",
|
|
||||||
guarantor1Salary: 3000,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "LOM-0002",
|
|
||||||
loanType: "Awtoulag karzy",
|
|
||||||
createdAt: "2025-01-18 11:05",
|
|
||||||
region: "Ahal",
|
|
||||||
branch: "Änew şahamçasy",
|
|
||||||
branchId: 2,
|
|
||||||
loanTypeId: 2,
|
|
||||||
workCityId: 2,
|
|
||||||
createdById: "U-1002",
|
|
||||||
firstName: "Merjen",
|
|
||||||
lastName: "Hudaýewa",
|
|
||||||
phone: "+99362234567",
|
|
||||||
status: "KANAGATLANDYRYLAN",
|
|
||||||
loanAmount: 30000,
|
|
||||||
loanHistory: "new",
|
|
||||||
patronicName: "Myratowna",
|
|
||||||
education: "masters",
|
|
||||||
marriageStatus: "SINGLE",
|
|
||||||
dateOfBirth: "1995-11-20",
|
|
||||||
residence: "Änew şäher, Garaşsyzlyk köçesi, 10",
|
|
||||||
passportSerie: "I",
|
|
||||||
passportNumber: "789012",
|
|
||||||
passportDateOfIssue: "2018-07-22",
|
|
||||||
passportGivenBy: "Ahal welaýatynyň Içeri işler müdirligi",
|
|
||||||
bornPlace: "Änew şäheri",
|
|
||||||
email: "merjen.hudayewa@email.com",
|
|
||||||
workCompany: "Änew etrap hasap bölümi",
|
|
||||||
position: "Hasapçy",
|
|
||||||
salary: 1800,
|
|
||||||
workStartedAt: "2019-03-15",
|
|
||||||
cardNumber: "4333333333333333",
|
|
||||||
cardName: "MERJEN HUDAÝEWA",
|
|
||||||
cardExpMonth: "09",
|
|
||||||
cardExpYear: "2028",
|
|
||||||
guarantor1Name: "Merdan",
|
|
||||||
guarantor1Surname: "Merdanow",
|
|
||||||
guarantor1PassportSerie: "I",
|
|
||||||
guarantor1PassportNumber: "345678",
|
|
||||||
guarantor1CardNumber: "4444444444444444",
|
|
||||||
guarantor1CardName: "MERDAN MERDANOW",
|
|
||||||
guarantor1CardExpMonth: "03",
|
|
||||||
guarantor1CardExpYear: "2025",
|
|
||||||
guarantor1Salary: 2200,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "LOM-0003",
|
|
||||||
loanType: "Ipoteka karzy",
|
|
||||||
createdAt: "2025-01-20 14:30",
|
|
||||||
region: "Balkan",
|
|
||||||
branch: "Balkanabat şahamçasy",
|
|
||||||
branchId: 3,
|
|
||||||
loanTypeId: 3,
|
|
||||||
workCityId: 7,
|
|
||||||
createdById: "U-1003",
|
|
||||||
firstName: "Serdar",
|
|
||||||
lastName: "Durdyýew",
|
|
||||||
phone: "+99363345678",
|
|
||||||
status: "IŞLENÝÄR",
|
|
||||||
loanAmount: 50000,
|
|
||||||
loanHistory: "positive",
|
|
||||||
patronicName: "Annagylyjowiç",
|
|
||||||
education: "high",
|
|
||||||
marriageStatus: "MARRIED",
|
|
||||||
dateOfBirth: "1988-07-12",
|
|
||||||
residence: "Balkanabat, Magtymguly köçesi, 25",
|
|
||||||
passportSerie: "II",
|
|
||||||
passportNumber: "456123",
|
|
||||||
passportDateOfIssue: "2016-05-18",
|
|
||||||
passportGivenBy: "Balkan welaýatynyň Içeri işler müdirligi",
|
|
||||||
email: "serdar.durdyyew@email.com",
|
|
||||||
workCompany: "Balkan nebit",
|
|
||||||
position: "Operator",
|
|
||||||
salary: 3200,
|
|
||||||
workStartedAt: "2015-09-01",
|
|
||||||
cardNumber: "4555555555555555",
|
|
||||||
cardName: "SERDAR DURDYÝEW",
|
|
||||||
cardExpMonth: "04",
|
|
||||||
cardExpYear: "2029",
|
|
||||||
guarantor1Name: "Döwran",
|
|
||||||
guarantor1Surname: "Döwranow",
|
|
||||||
guarantor1PassportSerie: "I",
|
|
||||||
guarantor1PassportNumber: "789456",
|
|
||||||
guarantor1CardNumber: "4666666666666666",
|
|
||||||
guarantor1CardName: "DÖWRAN DÖWRANOW",
|
|
||||||
guarantor1CardExpMonth: "11",
|
|
||||||
guarantor1CardExpYear: "2027",
|
|
||||||
guarantor1Salary: 3500,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "LOM-0004",
|
|
||||||
loanType: "Telekeçilik karzy",
|
|
||||||
createdAt: "2025-01-22 08:15",
|
|
||||||
region: "Lebap",
|
|
||||||
branch: "Türkmenabat şahamçasy",
|
|
||||||
firstName: "Aýna",
|
|
||||||
lastName: "Meredowa",
|
|
||||||
phone: "+99365456789",
|
|
||||||
status: "RED_EDILDI",
|
|
||||||
loanAmount: 25000,
|
|
||||||
patronicName: "Begenjowna",
|
|
||||||
education: "high",
|
|
||||||
marriageStatus: "DIVORCED",
|
|
||||||
dateOfBirth: "1991-02-28",
|
|
||||||
residence: "Türkmenabat, Lebap köçesi, 8",
|
|
||||||
passportSerie: "I",
|
|
||||||
passportNumber: "321654",
|
|
||||||
passportDateOfIssue: "2017-11-05",
|
|
||||||
passportGivenBy: "Lebap welaýatynyň Içeri işler müdirligi",
|
|
||||||
workCompany: "Hususy telekeçi",
|
|
||||||
position: "Telekeçi",
|
|
||||||
salary: 4000,
|
|
||||||
workStartedAt: "2020-01-10",
|
|
||||||
cardNumber: "4777777777777777",
|
|
||||||
cardName: "AÝNA MEREDOWA",
|
|
||||||
cardExpMonth: "07",
|
|
||||||
cardExpYear: "2026",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "LOM-0005",
|
|
||||||
loanType: "Sarp ediş karzy",
|
|
||||||
createdAt: "2025-01-25 16:00",
|
|
||||||
region: "Mary",
|
|
||||||
branch: "Mary-1 şahamçasy",
|
|
||||||
firstName: "Begmyrat",
|
|
||||||
lastName: "Oraz",
|
|
||||||
phone: "+99366567890",
|
|
||||||
status: "GARAŞYLÝAR",
|
|
||||||
loanAmount: 8000,
|
|
||||||
loanHistory: "new",
|
|
||||||
patronicName: "Annageldiwiç",
|
|
||||||
education: "middle",
|
|
||||||
marriageStatus: "SINGLE",
|
|
||||||
dateOfBirth: "2000-08-15",
|
|
||||||
residence: "Mary şäher, Saýat köçesi, 3",
|
|
||||||
passportSerie: "I",
|
|
||||||
passportNumber: "567890",
|
|
||||||
passportDateOfIssue: "2020-01-20",
|
|
||||||
passportGivenBy: "Mary welaýatynyň Içeri işler müdirligi",
|
|
||||||
workCompany: "Mary gurluşyk",
|
|
||||||
position: "Işçi",
|
|
||||||
salary: 1200,
|
|
||||||
workStartedAt: "2022-06-01",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "LOM-0006",
|
|
||||||
loanType: "Bilim karzy",
|
|
||||||
createdAt: "2025-01-28 10:20",
|
|
||||||
region: "Daşoguz",
|
|
||||||
branch: "Daşoguz şahamçasy",
|
|
||||||
firstName: "Gülälek",
|
|
||||||
lastName: "Saparowa",
|
|
||||||
phone: "+99361678901",
|
|
||||||
status: "KANAGATLANDYRYLAN",
|
|
||||||
loanAmount: 12000,
|
|
||||||
patronicName: "Mämmedowna",
|
|
||||||
education: "phd",
|
|
||||||
marriageStatus: "MARRIED",
|
|
||||||
dateOfBirth: "1985-12-03",
|
|
||||||
residence: "Daşoguz, Gurbansoltan eje köçesi, 12",
|
|
||||||
passportSerie: "II",
|
|
||||||
passportNumber: "901234",
|
|
||||||
passportDateOfIssue: "2014-08-30",
|
|
||||||
passportGivenBy: "Daşoguz welaýatynyň Içeri işler müdirligi",
|
|
||||||
email: "gulalek.saparowa@email.com",
|
|
||||||
workCompany: "Daşoguz uniwersiteti",
|
|
||||||
position: "Mugallym",
|
|
||||||
salary: 2000,
|
|
||||||
workStartedAt: "2016-09-01",
|
|
||||||
cardNumber: "4888888888888888",
|
|
||||||
cardName: "GÜLÄLEK SAPAROWA",
|
|
||||||
cardExpMonth: "02",
|
|
||||||
cardExpYear: "2028",
|
|
||||||
guarantor1Name: "Maksat",
|
|
||||||
guarantor1Surname: "Saparow",
|
|
||||||
guarantor1PassportSerie: "I",
|
|
||||||
guarantor1PassportNumber: "112233",
|
|
||||||
guarantor1CardNumber: "4999999999999999",
|
|
||||||
guarantor1CardName: "MAKSAT SAPAROW",
|
|
||||||
guarantor1CardExpMonth: "10",
|
|
||||||
guarantor1CardExpYear: "2027",
|
|
||||||
guarantor1Salary: 2500,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "LOM-0007",
|
|
||||||
loanType: "Awtoulag karzy",
|
|
||||||
createdAt: "2025-02-01 13:45",
|
|
||||||
region: "Aşgabat",
|
|
||||||
branch: "Garaşsyzlyk şahamçasy",
|
|
||||||
firstName: "Myrat",
|
|
||||||
lastName: "Ataýew",
|
|
||||||
phone: "+99362789012",
|
|
||||||
status: "IŞLENÝÄR",
|
|
||||||
loanAmount: 35000,
|
|
||||||
patronicName: "Batyrowiç",
|
|
||||||
education: "high",
|
|
||||||
marriageStatus: "MARRIED",
|
|
||||||
dateOfBirth: "1989-09-22",
|
|
||||||
residence: "Aşgabat, Çandybil köçesi, 45",
|
|
||||||
passportSerie: "I",
|
|
||||||
passportNumber: "334455",
|
|
||||||
passportDateOfIssue: "2015-12-12",
|
|
||||||
passportGivenBy: "Aşgabat şäheriniň Içeri işler müdirligi",
|
|
||||||
workCompany: "Türkmenhowaýollar",
|
|
||||||
position: "Sürüji",
|
|
||||||
salary: 2800,
|
|
||||||
workStartedAt: "2017-04-01",
|
|
||||||
cardNumber: "4111111111112222",
|
|
||||||
cardName: "MYRAT ATAÝEW",
|
|
||||||
cardExpMonth: "08",
|
|
||||||
cardExpYear: "2027",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
let mockStore = [...MOCK_DATA];
|
const { data } = await apiClient.get<LoanOrdersListResponse>("/loan-orders/mobile", {
|
||||||
let nextId = 8;
|
params: {
|
||||||
|
page: page ?? 1,
|
||||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms));
|
limit: perPage ?? limit ?? 25,
|
||||||
|
search: search || undefined,
|
||||||
function applyMockFilters(params: LoanOrderMobileListParams): PaginatedResponse<LoanOrderMobile> {
|
region: region || undefined,
|
||||||
const page = params.page ?? 1;
|
status: status || undefined,
|
||||||
const perPage = params.perPage ?? 25;
|
branch_id: branchId || undefined,
|
||||||
|
user_id: uid || undefined,
|
||||||
let result = [...mockStore];
|
},
|
||||||
|
signal,
|
||||||
if (params.search) {
|
});
|
||||||
const q = params.search.toLowerCase();
|
const orders = (data.loanOrders ?? []).map(mapBackendToUI);
|
||||||
result = result.filter(
|
return {
|
||||||
(r) =>
|
data: orders,
|
||||||
r.firstName.toLowerCase().includes(q) ||
|
total: data.count ?? orders.length,
|
||||||
r.lastName.toLowerCase().includes(q) ||
|
page: page ?? 1,
|
||||||
r.phone.includes(q) ||
|
perPage: perPage ?? limit ?? 25,
|
||||||
r.id.toLowerCase().includes(q),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (params.region) result = result.filter((r) => r.region === params.region);
|
|
||||||
if (params.status) result = result.filter((r) => r.status === params.status);
|
|
||||||
if (params.branch) result = result.filter((r) => r.branch === params.branch);
|
|
||||||
|
|
||||||
const total = result.length;
|
|
||||||
const start = (page - 1) * perPage;
|
|
||||||
|
|
||||||
return { data: result.slice(start, start + perPage), total };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export async function fetchLoanOrderMobiles(params: LoanOrderMobileListParams): Promise<PaginatedResponse<LoanOrderMobile>> {
|
|
||||||
if (true) {
|
|
||||||
await delay(500);
|
|
||||||
return applyMockFilters(params);
|
|
||||||
}
|
|
||||||
const { data } = await apiClient.get<PaginatedResponse<LoanOrderMobile>>("/loan-order-mobiles", { params });
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function deleteLoanOrderMobile(id: string): Promise<void> {
|
|
||||||
await delay(300);
|
|
||||||
mockStore = mockStore.filter((r) => r.id !== id);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getLoanOrderMobileById(id: string): Promise<LoanOrderMobile> {
|
|
||||||
await delay(300);
|
|
||||||
const order = mockStore.find((r) => r.id === id);
|
|
||||||
if (!order) throw new Error("Not found");
|
|
||||||
return { ...order };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createLoanOrderMobile(payload: LoanOrderMobilePayload): Promise<LoanOrderMobile> {
|
|
||||||
await delay(500);
|
|
||||||
const newOrder: LoanOrderMobile = {
|
|
||||||
...payload,
|
|
||||||
id: `LOM-${String(nextId++).padStart(4, "0")}`,
|
|
||||||
createdAt: new Date().toISOString().slice(0, 16).replace("T", " "),
|
|
||||||
status: payload.status as LoanOrderMobileStatus,
|
|
||||||
};
|
};
|
||||||
mockStore = [newOrder, ...mockStore];
|
|
||||||
return newOrder;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateLoanOrderMobile(id: string, payload: Partial<LoanOrderMobilePayload>): Promise<LoanOrderMobile> {
|
// ─── Branch options by region (Fallback) ──────────────────────────────────────
|
||||||
await delay(500);
|
|
||||||
const idx = mockStore.findIndex((r) => r.id === id);
|
|
||||||
if (idx === -1) throw new Error("Not found");
|
|
||||||
const updated = { ...mockStore[idx], ...payload } as LoanOrderMobile;
|
|
||||||
mockStore = mockStore.map((r) => (r.id === id ? updated : r));
|
|
||||||
return updated;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Branch options by region ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export const BRANCHES_BY_REGION_MOBILE: Record<string, { value: string; label: string }[]> = {
|
export const BRANCHES_BY_REGION_MOBILE: Record<string, { value: string; label: string }[]> = {
|
||||||
Aşgabat: [
|
Aşgabat: [
|
||||||
{ value: "Merkezi şahamça", label: "Merkezi şahamça" },
|
{ value: "Merkezi şahamça", label: "Merkezi şahamçaaaaaaaaaaaaaaaaaa" },
|
||||||
{ value: "Garaşsyzlyk şahamçasy", label: "Garaşsyzlyk şahamçasy" },
|
{ value: "Garaşsyzlyk şahamçasy", label: "Garaşsyzlyk şahamçasy" },
|
||||||
{ value: "Bitarap şahamça", label: "Bitarap şahamça" },
|
{ value: "Bitarap şahamça", label: "Bitarap şahamça" },
|
||||||
{ value: "Aşgabat-1 şahamçasy", label: "Aşgabat-1 şahamçasy" },
|
{ value: "Aşgabat-1 şahamçasy", label: "Aşgabat-1 şahamçasy" },
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
fetchLoanOrderMobiles,
|
fetchLoanOrderMobiles,
|
||||||
@@ -8,40 +8,42 @@ import {
|
|||||||
getLoanOrderMobileById,
|
getLoanOrderMobileById,
|
||||||
createLoanOrderMobile,
|
createLoanOrderMobile,
|
||||||
updateLoanOrderMobile,
|
updateLoanOrderMobile,
|
||||||
|
patchLoanOrderMobile,
|
||||||
type LoanOrderMobileListParams,
|
type LoanOrderMobileListParams,
|
||||||
type LoanOrderMobilePayload,
|
type LoanOrderMobilePayload,
|
||||||
} from '../api/loanOrderMobilesApi'
|
} from "../api/loanOrderMobilesApi";
|
||||||
|
|
||||||
// ─── Query keys ────────────────────────────────────────────────────────────────
|
// ─── Query keys ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const loanOrderMobileKeys = {
|
export const loanOrderMobileKeys = {
|
||||||
all: ['loanOrderMobiles'] as const,
|
all: ["loanOrderMobiles"] as const,
|
||||||
lists: () => [...loanOrderMobileKeys.all, 'list'] as const,
|
lists: () => [...loanOrderMobileKeys.all, "list"] as const,
|
||||||
list: (params: LoanOrderMobileListParams) => [...loanOrderMobileKeys.lists(), params] as const,
|
list: (params: LoanOrderMobileListParams) => [...loanOrderMobileKeys.lists(), params] as const,
|
||||||
details: () => [...loanOrderMobileKeys.all, 'detail'] as const,
|
details: () => [...loanOrderMobileKeys.all, "detail"] as const,
|
||||||
detail: (id: string) => [...loanOrderMobileKeys.details(), id] as const,
|
detail: (id: string) => [...loanOrderMobileKeys.details(), id] as const,
|
||||||
}
|
};
|
||||||
|
|
||||||
// ─── Hooks ─────────────────────────────────────────────────────────────────────
|
// ─── Hooks ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useLoanOrderMobiles(params: LoanOrderMobileListParams) {
|
export function useLoanOrderMobiles(params: LoanOrderMobileListParams) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: loanOrderMobileKeys.list(params),
|
queryKey: loanOrderMobileKeys.list(params),
|
||||||
queryFn: () => fetchLoanOrderMobiles(params),
|
queryFn: ({ signal }) => fetchLoanOrderMobiles(params, signal),
|
||||||
})
|
placeholderData: (prev) => prev,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useDeleteLoanOrderMobile() {
|
export function useDeleteLoanOrderMobile() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: string) => deleteLoanOrderMobile(id),
|
mutationFn: (id: string) => deleteLoanOrderMobile(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
|
||||||
toast.success(t('loanOrderMobiles.deleteSuccess', 'Sargyt üstünlikli pozuldy'))
|
toast.success(t("loanOrderMobiles.deleteSuccess", "Sargyt üstünlikli pozuldy"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useLoanOrderMobileById(id: string) {
|
export function useLoanOrderMobileById(id: string) {
|
||||||
@@ -49,33 +51,47 @@ export function useLoanOrderMobileById(id: string) {
|
|||||||
queryKey: loanOrderMobileKeys.detail(id),
|
queryKey: loanOrderMobileKeys.detail(id),
|
||||||
queryFn: () => getLoanOrderMobileById(id),
|
queryFn: () => getLoanOrderMobileById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useCreateLoanOrderMobile() {
|
export function useCreateLoanOrderMobile() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: LoanOrderMobilePayload) => createLoanOrderMobile(payload),
|
mutationFn: (payload: LoanOrderMobilePayload) => createLoanOrderMobile(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
|
||||||
toast.success(t('loanOrderMobiles.createSuccess', 'Sargyt üstünlikli döredildi'))
|
toast.success(t("loanOrderMobiles.createSuccess", "Sargyt üstünlikli döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUpdateLoanOrderMobile() {
|
export function useUpdateLoanOrderMobile() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({ id, payload }: { id: string; payload: Partial<LoanOrderMobilePayload> }) =>
|
mutationFn: ({ id, payload }: { id: string; payload: Partial<LoanOrderMobilePayload> }) => updateLoanOrderMobile(id, payload),
|
||||||
updateLoanOrderMobile(id, payload),
|
|
||||||
onSuccess: (_, variables) => {
|
onSuccess: (_, variables) => {
|
||||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) })
|
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) });
|
||||||
toast.success(t('loanOrderMobiles.updateSuccess', 'Sargyt üstünlikli üýtgedildi'))
|
toast.success(t("loanOrderMobiles.updateSuccess", "Sargyt üstünlikli üýtgedildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function usePatchLoanOrderMobile() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ id, payload }: { id: string; payload: Partial<LoanOrderMobilePayload> | Record<string, unknown> }) =>
|
||||||
|
patchLoanOrderMobile(id, payload),
|
||||||
|
onSuccess: (_, variables) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.lists() });
|
||||||
|
queryClient.invalidateQueries({ queryKey: loanOrderMobileKeys.detail(variables.id) });
|
||||||
|
toast.success(t("loanOrderMobiles.updateSuccess", "Sargyt üstünlikli üýtgedildi"));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,293 +1,3 @@
|
|||||||
import { z } from "zod";
|
export * from "@/features/loanOrders/schemas/loanOrder.schema";
|
||||||
import i18next from "i18next";
|
export type { LoanOrderFormData as LoanOrderMobileFormData } from "@/features/loanOrders/schemas/loanOrder.schema";
|
||||||
|
export { loanOrderFormSchema as loanOrderMobileFormSchema } from "@/features/loanOrders/schemas/loanOrder.schema";
|
||||||
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
|
|
||||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
|
||||||
|
|
||||||
export const loanOrderMobileFormSchema = z.object({
|
|
||||||
status: z.string().min(1, "validation.required"),
|
|
||||||
loanType: z.string().min(1, "validation.required"),
|
|
||||||
region: z.string().min(1, "validation.required"),
|
|
||||||
branch: z.string().min(1, "validation.required"),
|
|
||||||
firstName: z.string().min(1, "validation.required"),
|
|
||||||
lastName: z.string().min(1, "validation.required"),
|
|
||||||
patronicName: z.string().optional(),
|
|
||||||
education: z.string().min(1, "validation.required"),
|
|
||||||
marriageStatus: z.string().min(1, "validation.required"),
|
|
||||||
dateOfBirth: z.string().min(1, "validation.required"),
|
|
||||||
residence: z.string().min(1, "validation.required"),
|
|
||||||
currentResidence: z.string().optional(),
|
|
||||||
passportSerie: z.string().min(1, "validation.required"),
|
|
||||||
passportNumber: z.string().min(1, "validation.required"),
|
|
||||||
passportDateOfIssue: z.string().min(1, "validation.required"),
|
|
||||||
passportGivenBy: z.string().min(1, "validation.required"),
|
|
||||||
bornPlace: z.string().optional(),
|
|
||||||
email: z.string().optional(),
|
|
||||||
phone: z
|
|
||||||
.string()
|
|
||||||
.min(1, "validation.required")
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
const digits = val.replace(/\D/g, "");
|
|
||||||
return digits.length === 8;
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhone" },
|
|
||||||
)
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
const digits = val.replace(/\D/g, "");
|
|
||||||
const prefix = digits.slice(0, 2);
|
|
||||||
return VALID_PHONE_PREFIXES.includes(prefix);
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhonePrefix" },
|
|
||||||
),
|
|
||||||
phoneAdditional: z
|
|
||||||
.string()
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
|
||||||
const digits = val.replace(/\D/g, "");
|
|
||||||
return digits.length === 8;
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhone" },
|
|
||||||
)
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
|
||||||
const digits = val.replace(/\D/g, "");
|
|
||||||
return VALID_PHONE_PREFIXES.includes(digits.slice(0, 2));
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhonePrefix" },
|
|
||||||
)
|
|
||||||
.optional(),
|
|
||||||
homePhone: z
|
|
||||||
.string()
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
|
||||||
return val.replace(/\D/g, "").length === 8;
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhone" },
|
|
||||||
)
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
|
||||||
return VALID_PHONE_PREFIXES.includes(val.replace(/\D/g, "").slice(0, 2));
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhonePrefix" },
|
|
||||||
)
|
|
||||||
.optional(),
|
|
||||||
workCompany: z.string().min(1, "validation.required"),
|
|
||||||
workHrPhone: z
|
|
||||||
.string()
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
|
||||||
return val.replace(/\D/g, "").length === 8;
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhone" },
|
|
||||||
)
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
|
||||||
return VALID_PHONE_PREFIXES.includes(val.replace(/\D/g, "").slice(0, 2));
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhonePrefix" },
|
|
||||||
)
|
|
||||||
.optional(),
|
|
||||||
workRegion: z.string().optional(),
|
|
||||||
workProvince: z.string().optional(),
|
|
||||||
position: z.string().min(1, "validation.required"),
|
|
||||||
salary: z.string().min(1, "validation.required"),
|
|
||||||
workStartedAt: z.string().min(1, "validation.required"),
|
|
||||||
passportPage1: z.custom<File | null>().nullable(),
|
|
||||||
passportPage23: z.custom<File | null>().nullable(),
|
|
||||||
passportPage89: z.custom<File | null>().nullable(),
|
|
||||||
passportPage32: z.custom<File | null>().nullable(),
|
|
||||||
note: z.string().optional(),
|
|
||||||
loanAmount: z.string().min(1, "validation.required"),
|
|
||||||
loanHistory: z.string().optional(),
|
|
||||||
cardNumber: z.string().min(1, "validation.required"),
|
|
||||||
cardName: z.string().min(1, "validation.required"),
|
|
||||||
cardExpMonth: z.string().min(1, "validation.required"),
|
|
||||||
cardExpYear: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1Name: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1Surname: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1Patronic: z.string().optional(),
|
|
||||||
guarantor1PassportSerie: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1PassportNumber: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1CardNumber: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1CardName: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1CardExpMonth: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1CardExpYear: z.string().min(1, "validation.required"),
|
|
||||||
guarantor1Salary: z.string().min(1, "validation.required"),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type LoanOrderMobileFormData = z.infer<typeof loanOrderMobileFormSchema>;
|
|
||||||
|
|
||||||
export const stepSchemas: Record<number, z.ZodType<Partial<LoanOrderMobileFormData>>> = {
|
|
||||||
0: loanOrderMobileFormSchema.pick({ loanType: true, loanAmount: true, region: true, branch: true }),
|
|
||||||
1: loanOrderMobileFormSchema.pick({
|
|
||||||
firstName: true,
|
|
||||||
lastName: true,
|
|
||||||
education: true,
|
|
||||||
marriageStatus: true,
|
|
||||||
dateOfBirth: true,
|
|
||||||
residence: true,
|
|
||||||
passportSerie: true,
|
|
||||||
passportNumber: true,
|
|
||||||
passportDateOfIssue: true,
|
|
||||||
passportGivenBy: true,
|
|
||||||
}),
|
|
||||||
2: loanOrderMobileFormSchema.pick({
|
|
||||||
phone: true,
|
|
||||||
phoneAdditional: true,
|
|
||||||
homePhone: true,
|
|
||||||
workCompany: true,
|
|
||||||
position: true,
|
|
||||||
salary: true,
|
|
||||||
workStartedAt: true,
|
|
||||||
workHrPhone: true,
|
|
||||||
}),
|
|
||||||
3: loanOrderMobileFormSchema.pick({
|
|
||||||
cardNumber: true,
|
|
||||||
cardName: true,
|
|
||||||
cardExpMonth: true,
|
|
||||||
cardExpYear: true,
|
|
||||||
guarantor1Name: true,
|
|
||||||
guarantor1Surname: true,
|
|
||||||
guarantor1PassportSerie: true,
|
|
||||||
guarantor1PassportNumber: true,
|
|
||||||
guarantor1CardNumber: true,
|
|
||||||
guarantor1CardName: true,
|
|
||||||
guarantor1CardExpMonth: true,
|
|
||||||
guarantor1CardExpYear: true,
|
|
||||||
guarantor1Salary: true,
|
|
||||||
}),
|
|
||||||
4: z.object({
|
|
||||||
passportPage1: fileRequired,
|
|
||||||
passportPage23: fileRequired,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
export function validateStep(
|
|
||||||
stepIndex: number,
|
|
||||||
form: LoanOrderMobileFormData,
|
|
||||||
mode: "create" | "edit",
|
|
||||||
): Partial<Record<keyof LoanOrderMobileFormData, string>> {
|
|
||||||
if (stepIndex === 4 && mode === "edit") return {};
|
|
||||||
const schema = stepSchemas[stepIndex];
|
|
||||||
const result = schema.safeParse(form);
|
|
||||||
if (result.success) return {};
|
|
||||||
const errors: Partial<Record<keyof LoanOrderMobileFormData, string>> = {};
|
|
||||||
for (const issue of result.error.issues) {
|
|
||||||
const key = issue.path[0] as keyof LoanOrderMobileFormData;
|
|
||||||
if (!errors[key]) {
|
|
||||||
const msg = issue.message;
|
|
||||||
errors[key] = msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return errors;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DEFAULT_FORM_VALUES: LoanOrderMobileFormData = {
|
|
||||||
status: "GARAŞYLÝAR",
|
|
||||||
loanType: "",
|
|
||||||
region: "Aşgabat",
|
|
||||||
branch: "",
|
|
||||||
firstName: "",
|
|
||||||
lastName: "",
|
|
||||||
patronicName: "",
|
|
||||||
education: "",
|
|
||||||
marriageStatus: "",
|
|
||||||
dateOfBirth: "",
|
|
||||||
residence: "",
|
|
||||||
currentResidence: "",
|
|
||||||
passportSerie: "",
|
|
||||||
passportNumber: "",
|
|
||||||
passportDateOfIssue: "",
|
|
||||||
passportGivenBy: "",
|
|
||||||
bornPlace: "",
|
|
||||||
email: "",
|
|
||||||
phone: "",
|
|
||||||
phoneAdditional: "",
|
|
||||||
homePhone: "",
|
|
||||||
workCompany: "",
|
|
||||||
workHrPhone: "",
|
|
||||||
workRegion: "Aşgabat",
|
|
||||||
workProvince: "",
|
|
||||||
position: "",
|
|
||||||
salary: "",
|
|
||||||
workStartedAt: "",
|
|
||||||
passportPage1: null,
|
|
||||||
passportPage23: null,
|
|
||||||
passportPage89: null,
|
|
||||||
passportPage32: null,
|
|
||||||
note: "",
|
|
||||||
loanAmount: "",
|
|
||||||
loanHistory: "",
|
|
||||||
cardNumber: "",
|
|
||||||
cardName: "",
|
|
||||||
cardExpMonth: "",
|
|
||||||
cardExpYear: "",
|
|
||||||
guarantor1Name: "",
|
|
||||||
guarantor1Surname: "",
|
|
||||||
guarantor1Patronic: "",
|
|
||||||
guarantor1PassportSerie: "",
|
|
||||||
guarantor1PassportNumber: "",
|
|
||||||
guarantor1CardNumber: "",
|
|
||||||
guarantor1CardName: "",
|
|
||||||
guarantor1CardExpMonth: "",
|
|
||||||
guarantor1CardExpYear: "",
|
|
||||||
guarantor1Salary: "",
|
|
||||||
};
|
|
||||||
|
|
||||||
export function buildPayload(data: LoanOrderMobileFormData) {
|
|
||||||
return {
|
|
||||||
status: data.status,
|
|
||||||
loanType: data.loanType,
|
|
||||||
region: data.region,
|
|
||||||
branch: data.branch,
|
|
||||||
firstName: data.firstName,
|
|
||||||
lastName: data.lastName,
|
|
||||||
patronicName: data.patronicName || undefined,
|
|
||||||
education: data.education,
|
|
||||||
marriageStatus: data.marriageStatus,
|
|
||||||
dateOfBirth: data.dateOfBirth,
|
|
||||||
residence: data.residence,
|
|
||||||
currentResidence: data.currentResidence || undefined,
|
|
||||||
passportSerie: data.passportSerie,
|
|
||||||
passportNumber: data.passportNumber,
|
|
||||||
passportDateOfIssue: data.passportDateOfIssue,
|
|
||||||
passportGivenBy: data.passportGivenBy,
|
|
||||||
bornPlace: data.bornPlace || undefined,
|
|
||||||
email: data.email || undefined,
|
|
||||||
phone: data.phone,
|
|
||||||
phoneAdditional: data.phoneAdditional || undefined,
|
|
||||||
homePhone: data.homePhone || undefined,
|
|
||||||
workCompany: data.workCompany,
|
|
||||||
workHrPhone: data.workHrPhone || undefined,
|
|
||||||
workRegion: data.workRegion || undefined,
|
|
||||||
workProvince: data.workProvince || undefined,
|
|
||||||
position: data.position,
|
|
||||||
salary: Number(data.salary),
|
|
||||||
workStartedAt: data.workStartedAt,
|
|
||||||
note: data.note || undefined,
|
|
||||||
loanAmount: Number(data.loanAmount) || undefined,
|
|
||||||
loanHistory: data.loanHistory || undefined,
|
|
||||||
cardNumber: data.cardNumber || undefined,
|
|
||||||
cardName: data.cardName || undefined,
|
|
||||||
cardExpMonth: data.cardExpMonth || undefined,
|
|
||||||
cardExpYear: data.cardExpYear || undefined,
|
|
||||||
guarantor1Name: data.guarantor1Name || undefined,
|
|
||||||
guarantor1Surname: data.guarantor1Surname || undefined,
|
|
||||||
guarantor1Patronic: data.guarantor1Patronic || undefined,
|
|
||||||
guarantor1PassportSerie: data.guarantor1PassportSerie || undefined,
|
|
||||||
guarantor1PassportNumber: data.guarantor1PassportNumber || undefined,
|
|
||||||
guarantor1CardNumber: data.guarantor1CardNumber || undefined,
|
|
||||||
guarantor1CardName: data.guarantor1CardName || undefined,
|
|
||||||
guarantor1CardExpMonth: data.guarantor1CardExpMonth || undefined,
|
|
||||||
guarantor1CardExpYear: data.guarantor1CardExpYear || undefined,
|
|
||||||
guarantor1Salary: Number(data.guarantor1Salary) || undefined,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user