fixed some ui

This commit is contained in:
@jcarymuhammedow committed 2026-05-14 18:38:14 +05:00
1 parent d46c951b7d
commit a6981e2775
30 files changed
+3093 -3006

No files matched your search

@@ -145,27 +145,158 @@ export interface PaginatedResponse<T> {
// ─── Mock Data ───────────────────────────────────────────────────────────────── // ─── Mock Data ─────────────────────────────────────────────────────────────────
const USE_MOCK = true // gerçek API hazır olunca false yap
const MOCK_DATA: LoanOrderMobile[] = [ const MOCK_DATA: LoanOrderMobile[] = [
{ id: 'LOM-0001', loanType: 'Sarp etmek karzy', createdAt: '2025-01-15 09:42', region: 'Aşgabat', branch: 'Merkezi', firstName: 'Oraz', lastName: 'Annaýew', phone: '+99361123456', status: 'GARAŞYLÝAR' }, {
{ id: 'LOM-0002', loanType: 'Awtoulag karzy', createdAt: '2025-01-18 11:05', region: 'Ahal', branch: 'Änew', firstName: 'Merjen', lastName: 'Hudaýewa', phone: '+99362234567', status: 'KANAGATLANDYRYLAN' }, id: 'LOM-0001', loanType: 'Sarp ediş karzy', createdAt: '2025-01-15 09:42',
{ id: 'LOM-0003', loanType: 'Ipoteka karzy', createdAt: '2025-01-20 14:30', region: 'Balkan', branch: 'Türkmenbaşy', firstName: 'Serdar', lastName: 'Durdyýew', phone: '+99363345678', status: 'IŞLENÝÄR' }, region: 'Aşgabat', branch: 'Merkezi şahamça',
{ id: 'LOM-0004', loanType: 'Telekeçilik karzy', createdAt: '2025-01-22 08:15', region: 'Lebap', branch: 'Türkmenabat', firstName: 'Aýna', lastName: 'Meredowa', phone: '+99365456789', status: 'RED_EDILDI' }, firstName: 'Oraz', lastName: 'Annaýew', phone: '+99361123456', status: 'GARAŞYLÝAR',
{ id: 'LOM-0005', loanType: 'Sarp etmek karzy', createdAt: '2025-01-25 16:00', region: 'Mary', branch: 'Mary', firstName: 'Begmyrat',lastName: 'Oraz', phone: '+99366567890', status: 'GARAŞYLÝAR' }, note: 'Müşderi dokumentleri tassyklamady',
{ id: 'LOM-0006', loanType: 'Bilim karzy', createdAt: '2025-01-28 10:20', region: 'Daşoguz', branch: 'Daşoguz', firstName: 'Gülälek', lastName: 'Saparowa', phone: '+99361678901', status: 'KANAGATLANDYRYLAN' }, loanAmount: 15000, loanHistory: 'positive',
{ id: 'LOM-0007', loanType: 'Awtoulag karzy', createdAt: '2025-02-01 13:45', region: 'Aşgabat', branch: 'Çoganly', firstName: 'Myrat', lastName: 'Ataýew', phone: '+99362789012', status: 'IŞLENÝÄR' }, patronicName: 'Myradowiç', education: 'high', marriageStatus: 'MARRIED',
{ id: 'LOM-0008', loanType: 'Ipoteka karzy', createdAt: '2025-02-03 09:00', region: 'Ahal', branch: 'Tejen', firstName: 'Ogulnur', lastName: 'Berdiýewa', phone: '+99363890123', status: 'GARAŞYLÝAR' }, dateOfBirth: '1992-04-18',
{ id: 'LOM-0009', loanType: 'Telekeçilik karzy', createdAt: '2025-02-05 15:30', region: 'Balkan', branch: 'Balkanabat', firstName: 'Döwlet', lastName: 'Çaryýew', phone: '+99364901234', status: 'RED_EDILDI' }, residence: 'Aşgabat, Bitarap Türkmenistan şaýoly, 15',
{ id: 'LOM-0010', loanType: 'Sarp etmek karzy', createdAt: '2025-02-08 11:15', region: 'Lebap', branch: 'Farap', firstName: 'Maral', lastName: 'Ýollyýewa', phone: '+99365012345', status: 'KANAGATLANDYRYLAN' }, currentResidence: 'Aşgabat, Garaşsyzlyk köçesi, 5',
{ id: 'LOM-0011', loanType: 'Bilim karzy', createdAt: '2025-02-10 08:45', region: 'Mary', branch: 'Baýramaly', firstName: 'Nurmuhammet', lastName: 'Garaýew', phone: '+99366123456', status: 'GARAŞYLÝAR' }, passportSerie: 'I', passportNumber: '123456',
{ id: 'LOM-0012', loanType: 'Awtoulag karzy', createdAt: '2025-02-12 14:00', region: 'Daşoguz', branch: 'Köneürgenç', firstName: 'Şemşat', lastName: 'Jumaýewa', phone: '+99361234567', status: 'IŞLENÝÄR' }, 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',
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',
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]
let nextId = 8
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
function applyMockFilters( function applyMockFilters(
params: LoanOrderMobileListParams, params: LoanOrderMobileListParams,
): PaginatedResponse<LoanOrderMobile> { ): PaginatedResponse<LoanOrderMobile> {
let result = [...MOCK_DATA] const page = params.page ?? 1
const perPage = params.perPage ?? 25
let result = [...mockStore]
if (params.search) { if (params.search) {
const q = params.search.toLowerCase() const q = params.search.toLowerCase()
@@ -182,8 +313,6 @@ function applyMockFilters(
if (params.branch) result = result.filter((r) => r.branch === params.branch) if (params.branch) result = result.filter((r) => r.branch === params.branch)
const total = result.length const total = result.length
const page = params.page ?? 1
const perPage = params.perPage ?? 25
const start = (page - 1) * perPage const start = (page - 1) * perPage
return { data: result.slice(start, start + perPage), total } return { data: result.slice(start, start + perPage), total }
@@ -194,8 +323,10 @@ function applyMockFilters(
export async function fetchLoanOrderMobiles( export async function fetchLoanOrderMobiles(
params: LoanOrderMobileListParams, params: LoanOrderMobileListParams,
): Promise<PaginatedResponse<LoanOrderMobile>> { ): Promise<PaginatedResponse<LoanOrderMobile>> {
if (USE_MOCK) return applyMockFilters(params) if (true) {
await delay(500)
return applyMockFilters(params)
}
const { data } = await apiClient.get<PaginatedResponse<LoanOrderMobile>>( const { data } = await apiClient.get<PaginatedResponse<LoanOrderMobile>>(
'/loan-order-mobiles', '/loan-order-mobiles',
{ params }, { params },
@@ -204,51 +335,78 @@ export async function fetchLoanOrderMobiles(
} }
export async function deleteLoanOrderMobile(id: string): Promise<void> { export async function deleteLoanOrderMobile(id: string): Promise<void> {
if (USE_MOCK) { await delay(300)
const idx = MOCK_DATA.findIndex((r) => r.id === id) mockStore = mockStore.filter((r) => r.id !== id)
if (idx !== -1) MOCK_DATA.splice(idx, 1)
return
}
await apiClient.delete(`/loan-order-mobiles/${id}`)
} }
export async function getLoanOrderMobileById(id: string): Promise<LoanOrderMobile> { export async function getLoanOrderMobileById(id: string): Promise<LoanOrderMobile> {
if (USE_MOCK) { await delay(300)
const order = MOCK_DATA.find((r) => r.id === id) const order = mockStore.find((r) => r.id === id)
if (!order) throw new Error('Not found') if (!order) throw new Error('Not found')
return order return { ...order }
}
const { data } = await apiClient.get<LoanOrderMobile>(`/loan-order-mobiles/${id}`)
return data
} }
export async function createLoanOrderMobile( export async function createLoanOrderMobile(
payload: LoanOrderMobilePayload payload: LoanOrderMobilePayload
): Promise<LoanOrderMobile> { ): Promise<LoanOrderMobile> {
if (USE_MOCK) { await delay(500)
const newOrder: LoanOrderMobile = { const newOrder: LoanOrderMobile = {
...payload, ...payload,
id: `LOM-${String(MOCK_DATA.length + 1).padStart(4, '0')}`, id: `LOM-${String(nextId++).padStart(4, '0')}`,
createdAt: new Date().toISOString().slice(0, 16).replace('T', ' '), createdAt: new Date().toISOString().slice(0, 16).replace('T', ' '),
status: payload.status as LoanOrderMobileStatus, status: payload.status as LoanOrderMobileStatus,
}
MOCK_DATA.unshift(newOrder)
return newOrder
} }
const { data } = await apiClient.post<LoanOrderMobile>('/loan-order-mobiles', payload) mockStore = [newOrder, ...mockStore]
return data return newOrder
} }
export async function updateLoanOrderMobile( export async function updateLoanOrderMobile(
id: string, id: string,
payload: Partial<LoanOrderMobilePayload> payload: Partial<LoanOrderMobilePayload>
): Promise<LoanOrderMobile> { ): Promise<LoanOrderMobile> {
if (USE_MOCK) { await delay(500)
const idx = MOCK_DATA.findIndex((r) => r.id === id) const idx = mockStore.findIndex((r) => r.id === id)
if (idx === -1) throw new Error('Not found') if (idx === -1) throw new Error('Not found')
MOCK_DATA[idx] = { ...MOCK_DATA[idx], ...payload } as LoanOrderMobile const updated = { ...mockStore[idx], ...payload } as LoanOrderMobile
return MOCK_DATA[idx] mockStore = mockStore.map((r) => (r.id === id ? updated : r))
} return updated
const { data } = await apiClient.put<LoanOrderMobile>(`/loan-order-mobiles/${id}`, payload) }
return data
} // ─── Branch options by region ─────────────────────────────────────────────────
export const BRANCHES_BY_REGION_MOBILE: Record<string, { value: string; label: string }[]> = {
'Aşgabat': [
{ value: 'Merkezi şahamça', label: 'Merkezi şahamça' },
{ value: 'Garaşsyzlyk şahamçasy', label: 'Garaşsyzlyk şahamçasy' },
{ value: 'Bitarap şahamça', label: 'Bitarap şahamça' },
{ value: 'Aşgabat-1 şahamçasy', label: 'Aşgabat-1 şahamçasy' },
],
'Ahal': [
{ value: 'Änew şahamçasy', label: 'Änew şahamçasy' },
{ value: 'Gökdepe şahamçasy', label: 'Gökdepe şahamçasy' },
{ value: 'Tejen şahamçasy', label: 'Tejen şahamçasy' },
],
'Balkan': [
{ value: 'Balkanabat şahamçasy', label: 'Balkanabat şahamçasy' },
{ value: 'Türkmenbaşy şahamçasy', label: 'Türkmenbaşy şahamçasy' },
{ value: 'Bereket şahamçasy', label: 'Bereket şahamçasy' },
],
'Daşoguz': [
{ value: 'Daşoguz şahamçasy', label: 'Daşoguz şahamçasy' },
{ value: 'Akdepe şahamçasy', label: 'Akdepe şahamçasy' },
{ value: 'Boldumsaz şahamçasy', label: 'Boldumsaz şahamçasy' },
],
'Lebap': [
{ value: 'Türkmenabat şahamçasy', label: 'Türkmenabat şahamçasy' },
{ value: 'Seýdi şahamçasy', label: 'Seýdi şahamçasy' },
{ value: 'Kerki şahamçasy', label: 'Kerki şahamçasy' },
],
'Mary': [
{ value: 'Mary-1 şahamçasy', label: 'Mary-1 şahamçasy' },
{ value: 'Mary-2 şahamçasy', label: 'Mary-2 şahamçasy' },
{ value: 'Baýramaly şahamçasy', label: 'Baýramaly şahamçasy' },
],
'Arkadag': [
{ value: 'Arkadag şahamçasy', label: 'Arkadag şahamçasy' },
],
}
File diff suppressed because it is too large. Load diff
+166 -35
View File
@@ -1,5 +1,3 @@
import { apiClient } from '@/lib/api/client'
// ─── Types ──────────────────────────────────────────────────────────────────── // ─── Types ────────────────────────────────────────────────────────────────────
export type LoanOrderStatus = export type LoanOrderStatus =
@@ -9,7 +7,6 @@ export type LoanOrderStatus =
| 'IŞLENÝÄR' | 'IŞLENÝÄR'
export interface LoanOrder { export interface LoanOrder {
// ── List fields ──────────────────────────────────────────────────────────
id: string id: string
loanType: string loanType: string
createdAt: string createdAt: string
@@ -21,7 +18,6 @@ export interface LoanOrder {
status: LoanOrderStatus status: LoanOrderStatus
note?: string | null note?: string | null
// ── Detail fields ─────────────────────────────────────────────────────────
loanAmount?: number | null loanAmount?: number | null
loanHistory?: string | null loanHistory?: string | null
patronicName?: string | null patronicName?: string | null
@@ -31,7 +27,6 @@ export interface LoanOrder {
residence?: string | null residence?: string | null
currentResidence?: string | null currentResidence?: string | null
// Passport
passportSerie?: string | null passportSerie?: string | null
passportNumber?: string | null passportNumber?: string | null
passportDateOfIssue?: string | null passportDateOfIssue?: string | null
@@ -42,12 +37,10 @@ export interface LoanOrder {
passportPage89Url?: string | null passportPage89Url?: string | null
passportPage32Url?: string | null passportPage32Url?: string | null
// Contact
email?: string | null email?: string | null
phoneAdditional?: string | null phoneAdditional?: string | null
homePhone?: string | null homePhone?: string | null
// Employment
workCompany?: string | null workCompany?: string | null
workHrPhone?: string | null workHrPhone?: string | null
workRegion?: string | null workRegion?: string | null
@@ -56,13 +49,11 @@ export interface LoanOrder {
salary?: number | null salary?: number | null
workStartedAt?: string | null workStartedAt?: string | null
// Card (Zähmet haky)
cardNumber?: string | null cardNumber?: string | null
cardName?: string | null cardName?: string | null
cardExpMonth?: string | null cardExpMonth?: string | null
cardExpYear?: string | null cardExpYear?: string | null
// Guarantor (Zamun)
guarantor1Name?: string | null guarantor1Name?: string | null
guarantor1Surname?: string | null guarantor1Surname?: string | null
guarantor1Patronic?: string | null guarantor1Patronic?: string | null
@@ -74,7 +65,6 @@ export interface LoanOrder {
guarantor1CardExpYear?: string | null guarantor1CardExpYear?: string | null
guarantor1Salary?: number | null guarantor1Salary?: number | null
// ── Restored fields from previous version ───────────────────────────────
amount?: number | null amount?: number | null
createdBy?: string | null createdBy?: string | null
fullName?: string | null fullName?: string | null
@@ -172,6 +162,44 @@ const MOCK_DATA: LoanOrder[] = [
lastName: 'Amanow', lastName: 'Amanow',
phone: '+993 65 112233', phone: '+993 65 112233',
status: 'GARAŞYLÝAR', status: 'GARAŞYLÝAR',
note: 'Müşderi dokumentleri tassyklamady',
loanAmount: 50000,
loanHistory: 'positive',
patronicName: 'Myradowiç',
education: 'high',
marriageStatus: 'MARRIED',
dateOfBirth: '1990-05-15',
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: 'aman.amanow@email.com',
phoneAdditional: '+993 65 334455',
homePhone: '+993 12 456789',
workCompany: 'Türkmennebit',
workHrPhone: '+993 12 987654',
workRegion: 'Aşgabat',
workProvince: 'Büzmeýin etraby',
position: 'Inžener',
salary: 2500,
workStartedAt: '2018-06-01',
cardNumber: '4111111111111111',
cardName: 'AMAN AMANOW',
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: 'L-1002', id: 'L-1002',
@@ -183,56 +211,159 @@ const MOCK_DATA: LoanOrder[] = [
lastName: 'Berdiýewa', lastName: 'Berdiýewa',
phone: '+993 61 445566', phone: '+993 61 445566',
status: 'IŞLENÝÄR', status: 'IŞLENÝÄR',
note: null,
loanAmount: 10000,
loanHistory: 'new',
patronicName: 'Myratowna',
education: 'masters',
marriageStatus: 'SINGLE',
dateOfBirth: '1995-11-20',
residence: 'Mary şäher, Gurbansoltan eje köçesi, 10',
currentResidence: 'Mary şäher, Gurbansoltan eje köçesi, 10',
passportSerie: 'I',
passportNumber: '789012',
passportDateOfIssue: '2018-07-22',
passportGivenBy: 'Mary şäheriniň Içeri işler müdirligi',
bornPlace: 'Mary şäheri',
email: 'oguljan.berdiýewa@email.com',
phoneAdditional: null,
homePhone: null,
workCompany: 'Mary ýangyn söndüriş bölümi',
workHrPhone: '+993 55 112233',
workRegion: 'Mary',
workProvince: 'Mary şäher',
position: 'Hasapçy',
salary: 1800,
workStartedAt: '2019-03-15',
cardNumber: '4333333333333333',
cardName: 'OGULJAN BERDIÝEWA',
cardExpMonth: '09',
cardExpYear: '2028',
guarantor1Name: 'Merdan',
guarantor1Surname: 'Merdanow',
guarantor1Patronic: 'Amanowiç',
guarantor1PassportSerie: 'I',
guarantor1PassportNumber: '345678',
guarantor1CardNumber: '4444444444444444',
guarantor1CardName: 'MERDAN MERDANOW',
guarantor1CardExpMonth: '03',
guarantor1CardExpYear: '2025',
guarantor1Salary: 2200,
}, },
] ]
let mockStore = [...MOCK_DATA]
let nextId = 1003
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
// ─── API Functions ──────────────────────────────────────────────────────────── // ─── API Functions ────────────────────────────────────────────────────────────
export async function fetchLoanOrders( export async function fetchLoanOrders(
params: LoanOrdersParams params: LoanOrdersParams
): Promise<LoanOrdersResponse> { ): Promise<LoanOrdersResponse> {
// Mock — real API hazır bolanda aşakdaky commentden çykar await delay(600)
await new Promise((resolve) => setTimeout(resolve, 800))
const page = params.page || 1 const page = params.page || 1
const perPage = params.perPage || 25 const perPage = params.perPage || 25
const filtered = MOCK_DATA.filter(
(item) =>
!params.search ||
item.firstName.toLowerCase().includes(params.search.toLowerCase()) ||
item.id.toLowerCase().includes(params.search.toLowerCase())
)
const start = (page - 1) * perPage
return {
data: filtered.slice(start, start + perPage),
total: filtered.length,
page,
perPage,
}
// const { data } = await apiClient.get<LoanOrdersResponse>('/loan-orders', { params }) let filtered = mockStore.filter((item) => {
// return data const matchSearch =
!params.search ||
`${item.firstName} ${item.lastName}`.toLowerCase().includes(params.search.toLowerCase()) ||
item.id.toLowerCase().includes(params.search.toLowerCase()) ||
item.phone.includes(params.search)
const matchStatus =
!params.status
? true
: item.status === params.status
const matchRegion =
!params.region ? true : item.region === params.region
const matchBranch =
!params.branch ? true : item.branch === params.branch
return matchSearch && matchStatus && matchRegion && matchBranch
})
filtered = [...filtered].sort((a, b) => b.createdAt.localeCompare(a.createdAt))
const total = filtered.length
const start = (page - 1) * perPage
const data = filtered.slice(start, start + perPage)
return { data, total, page, perPage }
} }
export async function getLoanOrderById(id: string): Promise<LoanOrder> { export async function getLoanOrderById(id: string): Promise<LoanOrder> {
const { data } = await apiClient.get<LoanOrder>(`/loan-orders/${id}`) await delay(300)
return data const item = mockStore.find((o) => o.id === id)
if (!item) throw new Error('Not found')
return { ...item }
} }
export async function createLoanOrder( export async function createLoanOrder(
payload: LoanOrderPayload payload: LoanOrderPayload
): Promise<LoanOrder> { ): Promise<LoanOrder> {
const { data } = await apiClient.post<LoanOrder>('/loan-orders', payload) await delay(500)
return data const newItem = {
id: `L-${nextId++}`,
createdAt: new Date().toISOString().slice(0, 16).replace('T', ' '),
...payload,
} as LoanOrder
mockStore = [newItem, ...mockStore]
return newItem
} }
export async function updateLoanOrder( export async function updateLoanOrder(
id: string, id: string,
payload: Partial<LoanOrderPayload> payload: Partial<LoanOrderPayload>
): Promise<LoanOrder> { ): Promise<LoanOrder> {
const { data } = await apiClient.put<LoanOrder>(`/loan-orders/${id}`, payload) await delay(500)
return data const idx = mockStore.findIndex((o) => o.id === id)
if (idx === -1) throw new Error('Not found')
const updated = { ...mockStore[idx], ...payload } as LoanOrder
mockStore = mockStore.map((o) => (o.id === id ? updated : o))
return updated
} }
export async function deleteLoanOrder(id: string): Promise<void> { export async function deleteLoanOrder(id: string): Promise<void> {
await apiClient.delete(`/loan-orders/${id}`) await delay(300)
} mockStore = mockStore.filter((o) => o.id !== id)
}
// ─── Branch options by region ─────────────────────────────────────────────────
export const BRANCHES_BY_REGION: Record<string, { value: string; label: string }[]> = {
'Aşgabat': [
{ value: 'Merkezi şahamça', label: 'Merkezi şahamça' },
{ value: 'Garaşsyzlyk şahamçasy', label: 'Garaşsyzlyk şahamçasy' },
{ value: 'Bitarap şahamça', label: 'Bitarap şahamça' },
{ value: 'Aşgabat-1 şahamçasy', label: 'Aşgabat-1 şahamçasy' },
{ value: 'Aşgabat-2 şahamçasy', label: 'Aşgabat-2 şahamçasy' },
],
'Ahal': [
{ value: 'Änew şahamçasy', label: 'Änew şahamçasy' },
{ value: 'Gökdepe şahamçasy', label: 'Gökdepe şahamçasy' },
{ value: 'Tejen şahamçasy', label: 'Tejen şahamçasy' },
],
'Balkan': [
{ value: 'Balkanabat şahamçasy', label: 'Balkanabat şahamçasy' },
{ value: 'Türkmenbaşy şahamçasy', label: 'Türkmenbaşy şahamçasy' },
{ value: 'Bereket şahamçasy', label: 'Bereket şahamçasy' },
],
'Daşoguz': [
{ value: 'Daşoguz şahamçasy', label: 'Daşoguz şahamçasy' },
{ value: 'Akdepe şahamçasy', label: 'Akdepe şahamçasy' },
{ value: 'Boldumsaz şahamçasy', label: 'Boldumsaz şahamçasy' },
],
'Lebap': [
{ value: 'Türkmenabat şahamçasy', label: 'Türkmenabat şahamçasy' },
{ value: 'Seýdi şahamçasy', label: 'Seýdi şahamçasy' },
{ value: 'Kerki şahamçasy', label: 'Kerki şahamçasy' },
],
'Mary': [
{ value: 'Mary-1 şahamçasy', label: 'Mary-1 şahamçasy' },
{ value: 'Mary-2 şahamçasy', label: 'Mary-2 şahamçasy' },
{ value: 'Baýramaly şahamçasy', label: 'Baýramaly şahamçasy' },
],
'Arkadag': [
{ value: 'Arkadag şahamçasy', label: 'Arkadag şahamçasy' },
],
}
@@ -13,6 +13,7 @@ import { FormActions } from '@/components/formActions'
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2' import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
import { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders' import { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders'
import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi' import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi'
import { BRANCHES_BY_REGION } from '@/features/loanOrders/api/loanOrdersApi'
// ─── Static options ─────────────────────────────────────────────────────────── // ─── Static options ───────────────────────────────────────────────────────────
@@ -387,7 +388,7 @@ interface StepContentProps {
function StepStatus({ form, errors, set }: StepContentProps) { function StepStatus({ form, errors, set }: StepContentProps) {
return ( return (
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Ýagdaý"> <BentoCard>
<FormInput <FormInput
type="select" type="select"
label="Status" label="Status"
@@ -400,7 +401,7 @@ function StepStatus({ form, errors, set }: StepContentProps) {
/> />
</BentoCard> </BentoCard>
<BentoCard title="Bellik"> <BentoCard>
<FormInput <FormInput
type="textarea" type="textarea"
label="Bellik" label="Bellik"
@@ -417,7 +418,7 @@ function StepStatus({ form, errors, set }: StepContentProps) {
function StepLoan({ form, errors, set }: StepContentProps) { function StepLoan({ form, errors, set }: StepContentProps) {
return ( return (
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Karz görnüşi"> <BentoCard>
<FormInput <FormInput
type="searchable-select" type="searchable-select"
label="Karz görnüşi" label="Karz görnüşi"
@@ -430,7 +431,7 @@ function StepLoan({ form, errors, set }: StepContentProps) {
/> />
</BentoCard> </BentoCard>
<BentoCard title="Möçber"> <BentoCard>
<FormInput <FormInput
type="number" type="number"
label="Karz möçberi" label="Karz möçberi"
@@ -446,9 +447,11 @@ function StepLoan({ form, errors, set }: StepContentProps) {
} }
function StepLocation({ form, errors, set }: StepContentProps) { function StepLocation({ form, errors, set }: StepContentProps) {
const branchOptions = BRANCHES_BY_REGION[form.region] ?? []
return ( return (
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Welaýat"> <BentoCard>
<FormInput <FormInput
type="searchable-select" type="searchable-select"
label="Welaýat" label="Welaýat"
@@ -459,19 +462,16 @@ function StepLocation({ form, errors, set }: StepContentProps) {
placeholder="Saýlamak üçin basyň" placeholder="Saýlamak üçin basyň"
error={errors.region} error={errors.region}
/> />
<p className="text-xs text-muted-foreground">
Welaýaty saýlasaňyz şahamçalar güncellenar.
</p>
</BentoCard> </BentoCard>
<BentoCard title="Şahamça"> <BentoCard>
<FormInput <FormInput
type="searchable-select" type="searchable-select"
label="Şahamça" label="Şahamça"
required required
value={form.branch} value={form.branch}
onChange={(v) => set('branch', v)} onChange={(v) => set('branch', v)}
options={[]} options={branchOptions}
placeholder="Saýlamak üçin basyň" placeholder="Saýlamak üçin basyň"
disabled={!form.region} disabled={!form.region}
error={errors.branch} error={errors.branch}
@@ -485,37 +485,37 @@ function StepPersonal({ form, errors, set }: StepContentProps) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<BentoGrid cols={3}> <BentoGrid cols={3}>
<BentoCard title="Ady"> <BentoCard>
<FormInput type="text" label="Ady" required value={form.firstName} onChange={(v) => set('firstName', v)} placeholder="Ady" error={errors.firstName} /> <FormInput type="text" label="Ady" required value={form.firstName} onChange={(v) => set('firstName', v)} placeholder="Ady" error={errors.firstName} />
</BentoCard> </BentoCard>
<BentoCard title="Familiýasy"> <BentoCard>
<FormInput type="text" label="Familiýasy" required value={form.lastName} onChange={(v) => set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} /> <FormInput type="text" label="Familiýasy" required value={form.lastName} onChange={(v) => set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} />
</BentoCard> </BentoCard>
<BentoCard title="Atasynyň ady"> <BentoCard>
<FormInput type="text" label="Atasynyň ady" value={form.patronicName} onChange={(v) => set('patronicName', v)} placeholder="Atasynyň ady" /> <FormInput type="text" label="Atasynyň ady" value={form.patronicName} onChange={(v) => set('patronicName', v)} placeholder="Atasynyň ady" />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
<BentoGrid cols={3}> <BentoGrid cols={3}>
<BentoCard title="Bilimi"> <BentoCard >
<FormInput type="select" label="Bilimi" required value={form.education} onChange={(v) => set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} /> <FormInput type="select" label="Bilimi" required value={form.education} onChange={(v) => set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} />
</BentoCard> </BentoCard>
<BentoCard title="Maşgala ýagdaýy"> <BentoCard >
<FormInput type="select" label="Maşgala ýagdaýy" required value={form.marriageStatus} onChange={(v) => set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} /> <FormInput type="select" label="Maşgala ýagdaýy" required value={form.marriageStatus} onChange={(v) => set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} />
</BentoCard> </BentoCard>
<BentoCard title="Doglan güni"> <BentoCard >
<FormInput type="date" label="Doglan güni" required value={form.dateOfBirth} onChange={(v) => set('dateOfBirth', v)} error={errors.dateOfBirth} /> <FormInput type="date" label="Doglan güni" required value={form.dateOfBirth} onChange={(v) => set('dateOfBirth', v)} error={errors.dateOfBirth} />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Ýazgy edilen salgy"> <BentoCard >
<FormInput type="text" label="Ýazgy edilen salgyňyz" required value={form.residence} onChange={(v) => set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} /> <FormInput type="text" label="Ýazgy edilen salgyňyz" required value={form.residence} onChange={(v) => set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} />
</BentoCard> </BentoCard>
<BentoCard title="Häzirki ýaşaýyş ýeri"> <BentoCard >
<FormInput type="text" label="Häzirki ýaşaýyş ýeri" value={form.currentResidence} onChange={(v) => set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" /> <FormInput type="text" label="Häzirki ýaşaýyş ýeri" value={form.currentResidence} onChange={(v) => set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" />
</BentoCard> </BentoCard>
<BentoCard title="Karz taryhy" span="full"> <BentoCard span="full">
<FormInput type="searchable-select" label="Karz taryhy" value={form.loanHistory} onChange={(v) => set('loanHistory', v)} options={[]} placeholder="Saýlamak üçin basyň" /> <FormInput type="searchable-select" label="Karz taryhy" value={form.loanHistory} onChange={(v) => set('loanHistory', v)} options={[]} placeholder="Saýlamak üçin basyň" />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
@@ -543,22 +543,22 @@ function StepPassport({ form, errors, set }: StepContentProps) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<BentoGrid cols={3}> <BentoGrid cols={3}>
<BentoCard title="Seriýasy"> <BentoCard >
<FormInput type="searchable-select" label="Pasport seriýasy" required value={form.passportSerie} onChange={(v) => set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} /> <FormInput type="searchable-select" label="Pasport seriýasy" required value={form.passportSerie} onChange={(v) => set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} />
</BentoCard> </BentoCard>
<BentoCard title="Belgisi"> <BentoCard >
<FormInput type="text" label="Pasport belgisi" required value={form.passportNumber} onChange={(v) => set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} /> <FormInput type="text" label="Pasport belgisi" required value={form.passportNumber} onChange={(v) => set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} />
</BentoCard> </BentoCard>
<BentoCard title="Berlen senesi"> <BentoCard >
<FormInput type="date" label="Pasport berlen senesi" required value={form.passportDateOfIssue} onChange={(v) => set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} /> <FormInput type="date" label="Pasport berlen senesi" required value={form.passportDateOfIssue} onChange={(v) => set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Kim tarapyndan berildi"> <BentoCard >
<FormInput type="text" label="Kim tarapyndan berildi" required value={form.passportGivenBy} onChange={(v) => set('passportGivenBy', v)} placeholder="Kim tarapyndan berildi" error={errors.passportGivenBy} /> <FormInput type="text" label="Kim tarapyndan berildi" required value={form.passportGivenBy} onChange={(v) => set('passportGivenBy', v)} placeholder="Kim tarapyndan berildi" error={errors.passportGivenBy} />
</BentoCard> </BentoCard>
<BentoCard title="Doglan ýeri"> <BentoCard >
<FormInput type="text" label="Doglan ýeri (pasport)" value={form.bornPlace} onChange={(v) => set('bornPlace', v)} placeholder="Doglan ýeri (pasport)" /> <FormInput type="text" label="Doglan ýeri (pasport)" value={form.bornPlace} onChange={(v) => set('bornPlace', v)} placeholder="Doglan ýeri (pasport)" />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
@@ -586,25 +586,25 @@ function StepJob({ form, errors, set }: StepContentProps) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Kärhana"> <BentoCard >
<FormInput type="text" label="Işleýän edaranyň/kärhananyň ady" required value={form.workCompany} onChange={(v) => set('workCompany', v)} placeholder="Kärhananyň ady" error={errors.workCompany} /> <FormInput type="text" label="Işleýän edaranyň/kärhananyň ady" required value={form.workCompany} onChange={(v) => set('workCompany', v)} placeholder="Kärhananyň ady" error={errors.workCompany} />
<FormInput type="phone" label="Işgärler bölüminiň iş belgisi" value={form.workHrPhone} onChange={(v) => set('workHrPhone', v)} placeholder="61 097 651" /> <FormInput type="phone" label="Işgärler bölüminiň iş belgisi" value={form.workHrPhone} onChange={(v) => set('workHrPhone', v)} placeholder="61 097 651" />
</BentoCard> </BentoCard>
<BentoCard title="Iş ýeri"> <BentoCard >
<FormInput type="searchable-select" label="Işleýän welaýatyňyz" value={form.workRegion} onChange={(v) => set('workRegion', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" /> <FormInput type="searchable-select" label="Işleýän welaýatyňyz" value={form.workRegion} onChange={(v) => set('workRegion', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" />
<FormInput type="searchable-select" label="Işleýän etrabyňyz" value={form.workProvince} onChange={(v) => set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" /> <FormInput type="searchable-select" label="Işleýän etrabyňyz" value={form.workProvince} onChange={(v) => set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
<BentoGrid cols={3}> <BentoGrid cols={3}>
<BentoCard title="Wezipe"> <BentoCard >
<FormInput type="text" label="Wezipe" required value={form.position} onChange={(v) => set('position', v)} placeholder="Wezipe" error={errors.position} /> <FormInput type="text" label="Wezipe" required value={form.position} onChange={(v) => set('position', v)} placeholder="Wezipe" error={errors.position} />
</BentoCard> </BentoCard>
<BentoCard title="Zähmet haky"> <BentoCard>
<FormInput type="number" label="Zähmet haky" required value={form.salary} onChange={(v) => set('salary', v)} placeholder="Zähmet haky" error={errors.salary} /> <FormInput type="number" label="Zähmet haky" required value={form.salary} onChange={(v) => set('salary', v)} placeholder="Zähmet haky" error={errors.salary} />
</BentoCard> </BentoCard>
<BentoCard title="Işe başlan wagty"> <BentoCard>
<FormInput type="date" label="Işe başlan wagtyňyz" required value={form.workStartedAt} onChange={(v) => set('workStartedAt', v)} error={errors.workStartedAt} /> <FormInput type="date" label="Işe başlan wagtyňyz" required value={form.workStartedAt} onChange={(v) => set('workStartedAt', v)} error={errors.workStartedAt} />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
@@ -644,7 +644,7 @@ function StepFiles({
)} )}
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Pasport (sahypa 1)"> <BentoCard >
<FormInput <FormInput
type="file" type="file"
label={mode === 'edit' ? 'Pasport (sahypa 1) (çalyşmak)' : 'Pasport (sahypa 1)'} label={mode === 'edit' ? 'Pasport (sahypa 1) (çalyşmak)' : 'Pasport (sahypa 1)'}
@@ -656,7 +656,7 @@ function StepFiles({
/> />
</BentoCard> </BentoCard>
<BentoCard title="Pasport (2-3-nji sahypa)"> <BentoCard>
<FormInput <FormInput
type="file" type="file"
label={mode === 'edit' ? 'Pasport (2-3-nji sahypa) (çalyşmak)' : 'Pasport (2-3-nji sahypa)'} label={mode === 'edit' ? 'Pasport (2-3-nji sahypa) (çalyşmak)' : 'Pasport (2-3-nji sahypa)'}
@@ -668,7 +668,7 @@ function StepFiles({
/> />
</BentoCard> </BentoCard>
<BentoCard title="Pasport (8-9 sahypa)"> <BentoCard >
<FormInput <FormInput
type="file" type="file"
label="Pasport (8-9 sahypa)" label="Pasport (8-9 sahypa)"
@@ -678,7 +678,7 @@ function StepFiles({
/> />
</BentoCard> </BentoCard>
<BentoCard title="Pasport (32-nji sahypa)"> <BentoCard >
<FormInput <FormInput
type="file" type="file"
label="Pasport (32-nji sahypa)" label="Pasport (32-nji sahypa)"
@@ -696,33 +696,33 @@ function StepGuarantor({ form, errors, set }: StepContentProps) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<BentoGrid cols={3}> <BentoGrid cols={3}>
<BentoCard title="Ady"> <BentoCard>
<FormInput type="text" label="Zamunyň ady" required value={form.guarantor1Name} onChange={(v) => set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} /> <FormInput type="text" label="Zamunyň ady" required value={form.guarantor1Name} onChange={(v) => set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} />
</BentoCard> </BentoCard>
<BentoCard title="Familiýasy"> <BentoCard >
<FormInput type="text" label="Zamunyň familiýasy" required value={form.guarantor1Surname} onChange={(v) => set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} /> <FormInput type="text" label="Zamunyň familiýasy" required value={form.guarantor1Surname} onChange={(v) => set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} />
</BentoCard> </BentoCard>
<BentoCard title="Atasynyň ady"> <BentoCard >
<FormInput type="text" label="Zamunyň atasynyň ady" value={form.guarantor1Patronic} onChange={(v) => set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" /> <FormInput type="text" label="Zamunyň atasynyň ady" value={form.guarantor1Patronic} onChange={(v) => set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Pasport seriýasy"> <BentoCard >
<FormInput type="searchable-select" label="Pasport seriýasy" required value={form.guarantor1PassportSerie} onChange={(v) => set('guarantor1PassportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1PassportSerie} /> <FormInput type="searchable-select" label="Pasport seriýasy" required value={form.guarantor1PassportSerie} onChange={(v) => set('guarantor1PassportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1PassportSerie} />
</BentoCard> </BentoCard>
<BentoCard title="Pasport belgisi"> <BentoCard >
<FormInput type="text" label="Pasport belgisi" required value={form.guarantor1PassportNumber} onChange={(v) => set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} /> <FormInput type="text" label="Pasport belgisi" required value={form.guarantor1PassportNumber} onChange={(v) => set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} />
</BentoCard> </BentoCard>
</BentoGrid> </BentoGrid>
<BentoGrid cols={2}> <BentoGrid cols={2}>
<BentoCard title="Kart maglumatlary"> <BentoCard >
<FormInput type="text" label="Kart belgisi" required value={form.guarantor1CardNumber} onChange={(v) => set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} /> <FormInput type="text" label="Kart belgisi" required value={form.guarantor1CardNumber} onChange={(v) => set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} />
<FormInput type="text" label="Kartdaky ady" required value={form.guarantor1CardName} onChange={(v) => set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} /> <FormInput type="text" label="Kartdaky ady" required value={form.guarantor1CardName} onChange={(v) => set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} />
</BentoCard> </BentoCard>
<BentoCard title="Kart möhleti we zähmet haky"> <BentoCard>
<FormInput type="searchable-select" label="Möhleti (aý)" required value={form.guarantor1CardExpMonth} onChange={(v) => set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} /> <FormInput type="searchable-select" label="Möhleti (aý)" required value={form.guarantor1CardExpMonth} onChange={(v) => set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} />
<FormInput type="searchable-select" label="Möhleti (ýyl)" required value={form.guarantor1CardExpYear} onChange={(v) => set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} /> <FormInput type="searchable-select" label="Möhleti (ýyl)" required value={form.guarantor1CardExpYear} onChange={(v) => set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} />
<FormInput type="number" label="Ortaca zähmet haky" required value={form.guarantor1Salary} onChange={(v) => set('guarantor1Salary', v)} placeholder="Ortaca zähmet haky" error={errors.guarantor1Salary} /> <FormInput type="number" label="Ortaca zähmet haky" required value={form.guarantor1Salary} onChange={(v) => set('guarantor1Salary', v)} placeholder="Ortaca zähmet haky" error={errors.guarantor1Salary} />
@@ -923,16 +923,6 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} /> <StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
</div> </div>
{/* Step label */}
<div className="flex items-center gap-2">
<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}
</span>
<h2 className="text-sm font-semibold text-foreground">
{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}
</h2>
</div>
{/* Step content */} {/* Step content */}
{currentStep === 0 && <StepStatus {...stepProps} />} {currentStep === 0 && <StepStatus {...stepProps} />}
{currentStep === 1 && <StepLoan {...stepProps} />} {currentStep === 1 && <StepLoan {...stepProps} />}
@@ -149,6 +149,7 @@ export default function CardBalancesPage() {
{t('Card balances', 'Kart galyndylary')} {t('Card balances', 'Kart galyndylary')}
</h1> </h1>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -181,6 +182,7 @@ export default function CardBalancesPage() {
totalCount={total} totalCount={total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}> <AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialogContent> <AlertDialogContent>
+93 -72
View File
@@ -11,7 +11,14 @@ import type {
CardPinStatus, CardPinStatus,
} from "@/features/cardPins/api/cardPinApi"; } from "@/features/cardPins/api/cardPinApi";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Eye, Pencil, Trash2, AlertCircle, CheckCircle2, XCircle } from "lucide-react"; import {
Eye,
Pencil,
Trash2,
AlertCircle,
CheckCircle2,
XCircle,
} from "lucide-react";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -25,33 +32,43 @@ import {
// ─── Status Badge ───────────────────────────────────────────────────────────── // ─── Status Badge ─────────────────────────────────────────────────────────────
import { StatusBadge, type StatusBadgeVariant } from '@/components/ui/statusBadge' import {
StatusBadge,
type StatusBadgeVariant,
} from "@/components/ui/statusBadge";
// ─── Status badge ───────────────────────────────────────────────────────────── // ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_CONFIG = { const STATUS_CONFIG = {
pending: { pending: {
label: 'Garaşylýar', label: "Garaşylýar",
variant: 'warning' as StatusBadgeVariant, variant: "warning" as StatusBadgeVariant,
icon: AlertCircle, icon: AlertCircle,
}, },
approved: { approved: {
label: 'Tassyklandy', label: "Tassyklandy",
variant: 'success' as StatusBadgeVariant, variant: "success" as StatusBadgeVariant,
icon: CheckCircle2, icon: CheckCircle2,
}, },
rejected: { rejected: {
label: 'Ýatyryldy', label: "Ýatyryldy",
variant: 'error' as StatusBadgeVariant, variant: "error" as StatusBadgeVariant,
icon: XCircle, icon: XCircle,
}, },
} satisfies Record<CardPinStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }> } satisfies Record<
CardPinStatus,
{ label: string; variant: StatusBadgeVariant; icon: React.ElementType }
>;
function CardPinStatusStatusBadge({ status }: { status: CardPinStatus }) { function CardPinStatusStatusBadge({ status }: { status: CardPinStatus }) {
const cfg = STATUS_CONFIG[status] const cfg = STATUS_CONFIG[status];
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span> if (!cfg)
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} /> return (
<span className="text-xs text-muted-foreground">{String(status)}</span>
);
return (
<StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
);
} }
// ─── Page ───────────────────────────────────────────────────────────────────── // ─── Page ─────────────────────────────────────────────────────────────────────
@@ -137,7 +154,9 @@ export default function CardPinsPage() {
{ {
accessorKey: "status", accessorKey: "status",
header: t("cardPin.status", "Status"), header: t("cardPin.status", "Status"),
cell: ({ row }) => <CardPinStatusStatusBadge status={row.original.status} />, cell: ({ row }) => (
<CardPinStatusStatusBadge status={row.original.status} />
),
}, },
{ {
id: "actions", id: "actions",
@@ -193,62 +212,64 @@ export default function CardPinsPage() {
{t("Card pins", "Kart pin bukjalary")} {t("Card pins", "Kart pin bukjalary")}
</h1> </h1>
</div> </div>
<DataTableToolbar <div className="bg-card border border-border rounded-xl p-4">
searchValue={search} <DataTableToolbar
onSearchChange={(v) => { searchValue={search}
setSearch(v); onSearchChange={(v) => {
setPage(1); setSearch(v);
}} setPage(1);
searchPlaceholder={t("cardPin.search", "Gözlemek")} }}
columns={columnMeta} searchPlaceholder={t("cardPin.search", "Gözlemek")}
columnVisibility={columnVisibility} columns={columnMeta}
onColumnVisibilityChange={setColumnVisibility} columnVisibility={columnVisibility}
columnOrder={columnOrder} onColumnVisibilityChange={setColumnVisibility}
onColumnOrderChange={setColumnOrder} columnOrder={columnOrder}
filterFields={[ onColumnOrderChange={setColumnOrder}
{ filterFields={[
id: "status", {
label: t("cardPin.status", "Status"), id: "status",
options: [ label: t("cardPin.status", "Status"),
{ value: "pending", label: "Garaşylýar" }, options: [
{ value: "approved", label: "Tassyklandy" }, { value: "pending", label: "Garaşylýar" },
{ value: "rejected", label: "Ret edildi" }, { value: "approved", label: "Tassyklandy" },
], { value: "rejected", label: "Ret edildi" },
}, ],
]} },
activeFilters={[{ fieldId: "status", value: statusFilter }]} ]}
onFilterChange={(fieldId, value) => { activeFilters={[{ fieldId: "status", value: statusFilter }]}
if (fieldId === "status") onFilterChange={(fieldId, value) => {
setStatusFilter(value as CardPinStatus | ""); if (fieldId === "status")
setPage(1); setStatusFilter(value as CardPinStatus | "");
}} setPage(1);
onFilterReset={() => { }}
setStatusFilter(""); onFilterReset={() => {
setPage(1); setStatusFilter("");
}} setPage(1);
perPage={perPage} }}
onPerPageChange={(v) => { perPage={perPage}
setPerPage(v); onPerPageChange={(v) => {
setPage(1); setPerPage(v);
}} setPage(1);
actionLabel={t("cardPin.createBtn", "Kart pin bukja dörediň")} }}
onAction={() => navigate("/card-pins/create")} actionLabel={t("cardPin.createBtn", "Kart pin bukja dörediň")}
/> onAction={() => navigate("/card-pins/create")}
/>
<DataTable <DataTable
columns={columns} columns={columns}
data={data?.data ?? []} data={data?.data ?? []}
isLoading={isLoading} isLoading={isLoading}
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility} onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder} columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder} onColumnOrderChange={setColumnOrder}
enableRowSelection enableRowSelection
currentPage={data?.meta?.current_page ?? 1} currentPage={data?.meta?.current_page ?? 1}
totalPages={data?.meta?.last_page ?? 1} totalPages={data?.meta?.last_page ?? 1}
totalCount={data?.meta?.total} totalCount={data?.meta?.total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
{/* Delete confirmation */} {/* Delete confirmation */}
<AlertDialog <AlertDialog
+109 -101
View File
@@ -25,56 +25,77 @@ import {
} from "@/components/ui/statusBadge"; } from "@/components/ui/statusBadge";
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react"; import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
import { InfoRow, PassportImage } from "@/components/viewPageComponents"; import { InfoRow, PassportImage } from "@/components/viewPageComponents";
// ─── Status badge ─────────────────────────────────────────────────────────────
// ─── Status config ────────────────────────────────────────────────────────────
const STATUS_CONFIG = { const STATUS_CONFIG = {
pending: { pending: { label: "Garaşylýar", variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
label: "Garaşylýar", approved: { label: "Tassyklandy", variant: "success" as StatusBadgeVariant, icon: CheckCircle2 },
variant: "warning" as StatusBadgeVariant, rejected: { label: "Ýatyryldy", variant: "error" as StatusBadgeVariant, icon: XCircle },
icon: AlertCircle, } satisfies Record<CardPinStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }>
},
approved: {
label: "Tassyklandy",
variant: "success" as StatusBadgeVariant,
icon: CheckCircle2,
},
rejected: {
label: "Ýatyryldy",
variant: "error" as StatusBadgeVariant,
icon: XCircle,
},
} satisfies Record<
CardPinStatus,
{ label: string; variant: StatusBadgeVariant; icon: React.ElementType }
>;
function CardPinStatusBadge({ status }: { status: CardPinStatus }) { function CardPinStatusBadge({ status }: { status: CardPinStatus }) {
const cfg = STATUS_CONFIG[status]; const cfg = STATUS_CONFIG[status]
if (!cfg) if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
return ( return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
<span className="text-xs text-muted-foreground">{String(status)}</span> }
);
// ─── Bento primitives ─────────────────────────────────────────────────────────
function BentoGrid({ cols = 2, children }: { cols?: 1 | 2 | 3 | 4; children: React.ReactNode }) {
const colClass = {
1: "grid-cols-1",
2: "grid-cols-1 sm:grid-cols-2",
3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",
}[cols]
return <div className={`grid ${colClass} gap-4`}>{children}</div>
}
function BentoCard({
title,
span,
children,
}: {
title?: string
span?: "full" | 2 | 3
children: React.ReactNode
}) {
const spanClass =
span === "full" ? "sm:col-span-full" :
span === 2 ? "sm:col-span-2" :
span === 3 ? "sm:col-span-3" : ""
return ( return (
<StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} /> <div className={`bg-card border border-border rounded-xl overflow-hidden ${spanClass}`}>
); {title && (
<div className="px-4 py-2.5 border-b border-border">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
{title}
</p>
</div>
)}
{children}
</div>
)
} }
// ─── Page ───────────────────────────────────────────────────────────────────── // ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardPinViewPage() { export default function CardPinViewPage() {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>()
const navigate = useNavigate(); const navigate = useNavigate()
const { t } = useTranslation(); const { t } = useTranslation()
const { data, isLoading, isError } = useCardPin(id!); const { data, isLoading, isError } = useCardPin(id!)
const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin(); const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin()
if (isLoading) { if (isLoading) {
return ( return (
<div className="flex items-center justify-center py-24"> <div className="flex items-center justify-center py-24">
<Spinner className="size-8 text-primary" /> <Spinner className="size-8 text-primary" />
</div> </div>
); )
} }
if (isError || !data) { if (isError || !data) {
@@ -82,12 +103,13 @@ export default function CardPinViewPage() {
<div className="flex items-center justify-center py-24 text-muted-foreground"> <div className="flex items-center justify-center py-24 text-muted-foreground">
{t("common.notFound", "Maglumat tapylmady")} {t("common.notFound", "Maglumat tapylmady")}
</div> </div>
); )
} }
return ( return (
<div className="mx-auto space-y-6"> <div className="mx-auto flex flex-col gap-6">
{/* Header */}
{/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-start justify-between"> <div className="flex items-start justify-between">
<h1 className="text-xl font-bold text-foreground"> <h1 className="text-xl font-bold text-foreground">
{t("cardPin.viewTitle", "Kart pin bukja giňişleýin")}: {data.id} {t("cardPin.viewTitle", "Kart pin bukja giňişleýin")}: {data.id}
@@ -120,11 +142,7 @@ export default function CardPinViewPage() {
<AlertDialogAction <AlertDialogAction
disabled={isDeleting} disabled={isDeleting}
className="bg-destructive hover:bg-destructive/90" className="bg-destructive hover:bg-destructive/90"
onClick={() => onClick={() => deletePin(data.id, { onSuccess: () => navigate("/card-pins") })}
deletePin(data.id, {
onSuccess: () => navigate("/card-pins"),
})
}
> >
{t("common.delete", "Poz")} {t("common.delete", "Poz")}
</AlertDialogAction> </AlertDialogAction>
@@ -143,33 +161,27 @@ export default function CardPinViewPage() {
</div> </div>
</div> </div>
{/* Main Info */} {/* ── Row 1: Meta + Kart + Lokasiýa ───────────────────────────────── */}
<section className="bg-card border border-border rounded-lg px-6"> <BentoGrid cols={3}>
<InfoRow label="ID"> <BentoCard title={t("cardPin.metaSection", "Esasy maglumatlar")}>
<span className="font-mono">{data.id}</span> <InfoRow label="ID">
</InfoRow> <span className="font-mono">{data.id}</span>
<InfoRow label={t("cardPin.createdAt", "Döredilen wagty")}> </InfoRow>
{data.created_at} <InfoRow label={t("cardPin.createdAt", "Döredilen wagty")}>
</InfoRow> {data.created_at}
<InfoRow label={t("cardPin.status", "Status")}> </InfoRow>
<CardPinStatusBadge status={data.status} /> <InfoRow label={t("cardPin.status", "Status")}>
</InfoRow> <CardPinStatusBadge status={data.status} />
<InfoRow label={t("cardPin.note", "Bellik")}> </InfoRow>
{data.note || "—"} <InfoRow label={t("cardPin.note", "Bellik")}>
</InfoRow> {data.note || "—"}
<InfoRow label={t("cardPin.createdBy", "Sargyt eden")}> </InfoRow>
<span className="text-primary font-medium"> <InfoRow label={t("cardPin.createdBy", "Sargyt eden")}>
{data.created_by_label} <span className="text-primary font-medium">{data.created_by_label}</span>
</span> </InfoRow>
</InfoRow> </BentoCard>
</section>
{/* Kart */} <BentoCard title={t("cardPin.cardSection", "Kart")}>
<section className="bg-card border border-border rounded-lg px-6 py-4">
<h2 className="text-base font-semibold text-foreground mb-2">
{t("cardPin.cardSection", "Kart")}
</h2>
<div className="divide-y divide-border">
<InfoRow label={t("cardPin.cardNumber", "Kart belgisi")}> <InfoRow label={t("cardPin.cardNumber", "Kart belgisi")}>
<span className="font-mono tracking-wider">{data.card_number}</span> <span className="font-mono tracking-wider">{data.card_number}</span>
</InfoRow> </InfoRow>
@@ -179,74 +191,70 @@ export default function CardPinViewPage() {
<InfoRow label={t("cardPin.cardExpireYear", "Kart Möhleti (ýyl)")}> <InfoRow label={t("cardPin.cardExpireYear", "Kart Möhleti (ýyl)")}>
— —
</InfoRow> </InfoRow>
</div> </BentoCard>
</section>
{/* Lokasiýa */} <BentoCard title={t("cardPin.locationSection", "Lokasiýa")}>
<section className="bg-card border border-border rounded-lg px-6 py-4">
<h2 className="text-base font-semibold text-foreground mb-2">
{t("cardPin.locationSection", "Lokasiýa")}
</h2>
<div className="divide-y divide-border">
<InfoRow label={t("cardPin.province", "Welaýat")}> <InfoRow label={t("cardPin.province", "Welaýat")}>
{data.province_label} {data.province_label}
</InfoRow> </InfoRow>
<InfoRow label={t("cardPin.branch", "Şahamça")}> <InfoRow label={t("cardPin.branch", "Şahamça")}>
<span className="text-primary font-medium"> <span className="text-primary font-medium">{data.branch_label}</span>
{data.branch_label}
</span>
</InfoRow> </InfoRow>
</div> </BentoCard>
</section> </BentoGrid>
{/* Şahsy maglumatlar */} {/* ── Row 2: Şahsy + Pasport maglumatlary ─────────────────────────── */}
<section className="bg-card border border-border rounded-lg px-6 py-4"> <BentoGrid cols={2}>
<h2 className="text-base font-semibold text-foreground mb-2"> <BentoCard title={t("cardPin.personalSection", "Şahsy maglumatlar")}>
{t("cardPin.personalSection", "Şahsy maglumatlar")}
</h2>
<div className="divide-y divide-border">
<InfoRow label={t("cardPin.fullName", "Doly ady")}> <InfoRow label={t("cardPin.fullName", "Doly ady")}>
{`${data.last_name} ${data.first_name} ${data.father_name}`} {`${data.last_name} ${data.first_name} ${data.father_name}`}
</InfoRow> </InfoRow>
<InfoRow label={t("cardPin.birthDate", "Doglan güni")}> <InfoRow label={t("cardPin.birthDate", "Doglan güni")}>
{data.birth_date} {data.birth_date}
</InfoRow> </InfoRow>
<InfoRow label={t("cardPin.phone", "Telefon")}>+{data.phone}</InfoRow> <InfoRow label={t("cardPin.phone", "Telefon")}>
</div> +{data.phone}
</section> </InfoRow>
</BentoCard>
{/* Pasport */} <BentoCard title={t("cardPin.passportSection", "Pasport")}>
<section className="bg-card border border-border rounded-lg px-6 py-4">
<h2 className="text-base font-semibold text-foreground mb-2">
{t("cardPin.passportSection", "Pasport")}
</h2>
<div className="divide-y divide-border mb-4">
<InfoRow label={t("cardPin.passportSeries", "Pasport seriýasy")}> <InfoRow label={t("cardPin.passportSeries", "Pasport seriýasy")}>
{data.passport_series} {data.passport_series}
</InfoRow> </InfoRow>
<InfoRow label={t("cardPin.passportNumber", "Pasport belgisi")}> <InfoRow label={t("cardPin.passportNumber", "Pasport belgisi")}>
{data.passport_number} {data.passport_number}
</InfoRow> </InfoRow>
</div> </BentoCard>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4"> </BentoGrid>
{/* ── Row 3: Passport images ───────────────────────────────────────── */}
<BentoGrid cols={4}>
<BentoCard title={t("cardPin.passportFile1", "Sahypa 1")}>
<PassportImage <PassportImage
label={t("cardPin.passportFile1", "Pasport (sahypa 1)")} label={t("cardPin.passportFile1", "Pasport (sahypa 1)")}
url={data.passport_file_1} url={data.passport_file_1}
/> />
</BentoCard>
<BentoCard title={t("cardPin.passportFile2", "Sahypa 2-3")}>
<PassportImage <PassportImage
label={t("cardPin.passportFile2", "Pasport (2-3-nji sahypa)")} label={t("cardPin.passportFile2", "Pasport (2-3-nji sahypa)")}
url={data.passport_file_2} url={data.passport_file_2}
/> />
</BentoCard>
<BentoCard title={t("cardPin.passportFile3", "Sahypa 8-9")}>
<PassportImage <PassportImage
label={t("cardPin.passportFile3", "Pasport (8-9 sahypa)")} label={t("cardPin.passportFile3", "Pasport (8-9 sahypa)")}
url={data.passport_file_3} url={data.passport_file_3}
/> />
</BentoCard>
<BentoCard title={t("cardPin.passportFile4", "Sahypa 32")}>
<PassportImage <PassportImage
label={t("cardPin.passportFile4", "Pasport (32-nji sahypa)")} label={t("cardPin.passportFile4", "Pasport (32-nji sahypa)")}
url={data.passport_file_4} url={data.passport_file_4}
/> />
</div> </BentoCard>
</section> </BentoGrid>
</div> </div>
); )
} }
+168 -116
View File
@@ -1,8 +1,8 @@
import { useState } from 'react' import { 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 { Download, Eye, Pencil, Trash2 } from 'lucide-react' import { Download, Eye, Pencil, Trash2 } from "lucide-react";
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -12,60 +12,84 @@ import {
AlertDialogFooter, AlertDialogFooter,
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from '@/components/ui/alert-dialog' } from "@/components/ui/alert-dialog";
import { DataTable, type ColumnDef } from '@/components/dataTable' import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar, type ColumnMeta } from '@/components/dataTableToolbar' import {
import type { VisibilityState } from '@tanstack/react-table' DataTableToolbar,
type ColumnMeta,
} from "@/components/dataTableToolbar";
import type { VisibilityState } from "@tanstack/react-table";
import { import {
useCardRequisites, useCardRequisites,
useDeleteCardRequisite, useDeleteCardRequisite,
useDownloadCardRequisite, useDownloadCardRequisite,
} from '@/features/cardRequisites/hooks/useCardRequisites' } from "@/features/cardRequisites/hooks/useCardRequisites";
import type { CardRequisite, CardRequisiteStatus } from '@/features/cardRequisites/api/cardRequisitesApi' import type {
CardRequisite,
CardRequisiteStatus,
} from "@/features/cardRequisites/api/cardRequisitesApi";
// ─── Status badge ───────────────────────────────────────────────────────────── // ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_BADGE: Record<CardRequisiteStatus, { label: string; className: string }> = { const STATUS_BADGE: Record<
pending: { label: 'Garaşylýar', className: 'bg-yellow-500/15 text-yellow-500 border-yellow-500/20' }, CardRequisiteStatus,
approved: { label: 'Tassyklanan', className: 'bg-emerald-500/15 text-emerald-500 border-emerald-500/20' }, { label: string; className: string }
rejected: { label: 'Ret edilen', className: 'bg-red-500/15 text-red-500 border-red-500/20' }, > = {
} pending: {
label: "Garaşylýar",
className: "bg-yellow-500/15 text-yellow-500 border-yellow-500/20",
},
approved: {
label: "Tassyklanan",
className: "bg-emerald-500/15 text-emerald-500 border-emerald-500/20",
},
rejected: {
label: "Ret edilen",
className: "bg-red-500/15 text-red-500 border-red-500/20",
},
};
function StatusBadge({ status }: { status: CardRequisiteStatus }) { function StatusBadge({ status }: { status: CardRequisiteStatus }) {
const cfg = STATUS_BADGE[status] ?? STATUS_BADGE.pending const cfg = STATUS_BADGE[status] ?? STATUS_BADGE.pending;
return ( return (
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${cfg.className}`}> <span
className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${cfg.className}`}
>
{cfg.label} {cfg.label}
</span> </span>
) );
} }
// ─── Page ───────────────────────────────────────────────────────────────────── // ─── Page ─────────────────────────────────────────────────────────────────────
const PER_PAGE = 25 const PER_PAGE = 25;
export default function CardRequisitesPage() { export default function CardRequisitesPage() {
const { t } = useTranslation() const { t } = useTranslation();
const navigate = useNavigate() const navigate = useNavigate();
const [page, setPage] = useState(1) const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE) const [perPage, setPerPage] = useState(PER_PAGE);
const [search, setSearch] = useState('') const [search, setSearch] = useState("");
const [deleteId, setDeleteId] = useState<string | null>(null) const [deleteId, setDeleteId] = useState<string | null>(null);
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({}) const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
const [columnOrder, setColumnOrder] = useState<string[]>([]) const [columnOrder, setColumnOrder] = useState<string[]>([]);
const { data, isLoading } = useCardRequisites({ page, per_page: perPage, search }) const { data, isLoading } = useCardRequisites({
const deleteMutation = useDeleteCardRequisite() page,
const downloadMutation = useDownloadCardRequisite() per_page: perPage,
search,
});
const deleteMutation = useDeleteCardRequisite();
const downloadMutation = useDownloadCardRequisite();
// ── Columns ────────────────────────────────────────────────────────────────── // ── Columns ──────────────────────────────────────────────────────────────────
const columns: ColumnDef<CardRequisite>[] = [ const columns: ColumnDef<CardRequisite>[] = [
{ {
id: 'id', id: "id",
accessorKey: 'id', accessorKey: "id",
header: t('ID', 'ID'), header: t("ID", "ID"),
cell: ({ row }) => ( cell: ({ row }) => (
<button <button
className="text-primary font-medium hover:underline text-left" className="text-primary font-medium hover:underline text-left"
@@ -76,81 +100,94 @@ export default function CardRequisitesPage() {
), ),
}, },
{ {
id: 'card_type', id: "card_type",
accessorKey: 'card_type', accessorKey: "card_type",
header: t('Card type', 'GÖRNÜŞI'), header: t("Card type", "GÖRNÜŞI"),
cell: ({ row }) => ( cell: ({ row }) => (
<span className="text-primary font-medium">{row.original.card_type}</span> <span className="text-primary font-medium">
{row.original.card_type}
</span>
), ),
}, },
{ {
id: 'created_at', id: "created_at",
accessorKey: 'created_at', accessorKey: "created_at",
header: t('Created at', 'DÖREDILEN WAGTY'), header: t("Created at", "DÖREDILEN WAGTY"),
cell: ({ row }) => ( cell: ({ row }) => (
<span className="text-foreground">{row.original.created_at}</span> <span className="text-foreground">{row.original.created_at}</span>
), ),
}, },
{ {
id: 'province_name', id: "province_name",
accessorKey: 'province_name', accessorKey: "province_name",
header: t('Province', 'WELAÝAT'), header: t("Province", "WELAÝAT"),
cell: ({ row }) => ( cell: ({ row }) => (
<span className="text-foreground">{row.original.province_name ?? '—'}</span> <span className="text-foreground">
{row.original.province_name ?? "—"}
</span>
), ),
}, },
{ {
id: 'branch_name', id: "branch_name",
accessorKey: 'branch_name', accessorKey: "branch_name",
header: t('Branch', 'ŞAHAMÇA'), header: t("Branch", "ŞAHAMÇA"),
cell: ({ row }) => ( cell: ({ row }) => (
<span className="text-primary font-medium">{row.original.branch_name ?? '—'}</span> <span className="text-primary font-medium">
{row.original.branch_name ?? "—"}
</span>
), ),
}, },
{ {
id: 'first_name', id: "first_name",
accessorKey: 'first_name', accessorKey: "first_name",
header: t('First name', 'ADY'), header: t("First name", "ADY"),
cell: ({ row }) => <span>{row.original.first_name}</span>, cell: ({ row }) => <span>{row.original.first_name}</span>,
}, },
{ {
id: 'last_name', id: "last_name",
accessorKey: 'last_name', accessorKey: "last_name",
header: t('Last name', 'FAMILIÝASY'), header: t("Last name", "FAMILIÝASY"),
cell: ({ row }) => <span>{row.original.last_name}</span>, cell: ({ row }) => <span>{row.original.last_name}</span>,
}, },
{ {
id: 'status', id: "status",
accessorKey: 'status', accessorKey: "status",
header: t('Status', 'STATUS'), header: t("Status", "STATUS"),
cell: ({ row }) => <StatusBadge status={row.original.status} />, cell: ({ row }) => <StatusBadge status={row.original.status} />,
}, },
{ {
id: 'actions', id: "actions",
header: '', header: "",
enableHiding: false, enableHiding: false,
cell: ({ row }) => ( cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end"> <div className="flex items-center gap-1 justify-end">
<Button <Button
variant="ghost" size="icon" className="h-7 w-7" variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => downloadMutation.mutate(row.original.id)} onClick={() => downloadMutation.mutate(row.original.id)}
> >
<Download size={14} /> <Download size={14} />
</Button> </Button>
<Button <Button
variant="ghost" size="icon" className="h-7 w-7" variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => navigate(`/card-requisites/${row.original.id}`)} onClick={() => navigate(`/card-requisites/${row.original.id}`)}
> >
<Eye size={14} /> <Eye size={14} />
</Button> </Button>
<Button <Button
variant="ghost" size="icon" className="h-7 w-7" variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => navigate(`/card-requisites/${row.original.id}/edit`)} onClick={() => navigate(`/card-requisites/${row.original.id}/edit`)}
> >
<Pencil size={14} /> <Pencil size={14} />
</Button> </Button>
<Button <Button
variant="ghost" size="icon" variant="ghost"
size="icon"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10" className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteId(row.original.id)} onClick={() => setDeleteId(row.original.id)}
> >
@@ -159,94 +196,109 @@ export default function CardRequisitesPage() {
</div> </div>
), ),
}, },
] ];
// ── Column meta for toolbar ─────────────────────────────────────────────────── // ── Column meta for toolbar ───────────────────────────────────────────────────
const columnMeta: ColumnMeta[] = columns const columnMeta: ColumnMeta[] = columns
.filter((c) => c.id !== 'actions') .filter((c) => c.id !== "actions")
.map((c) => ({ .map((c) => ({
id: c.id!, id: c.id!,
label: typeof c.header === 'string' ? c.header : c.id!, label: typeof c.header === "string" ? c.header : c.id!,
})) }));
// ── Pagination ──────────────────────────────────────────────────────────────── // ── Pagination ────────────────────────────────────────────────────────────────
const total = data?.total ?? 0 const total = data?.total ?? 0;
const totalPages = Math.ceil(total / perPage) const totalPages = Math.ceil(total / perPage);
const handleDelete = async () => { const handleDelete = async () => {
if (!deleteId) return if (!deleteId) return;
await deleteMutation.mutateAsync(deleteId) await deleteMutation.mutateAsync(deleteId);
setDeleteId(null) setDeleteId(null);
} };
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{/* Header */} {/* Header */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground"> <h1 className="text-xl font-semibold text-foreground">
{t('Card requisites', 'Kart rekwizitler')} {t("Card requisites", "Kart rekwizitler")}
</h1> </h1>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => {
setSearch(v);
setPage(1);
}}
searchPlaceholder={t("Search", "Gözlemek")}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
actionLabel={t(
"Create card requisite order",
"Kart rekwiziti üçin sargyt dörediň",
)}
onAction={() => navigate("/card-requisites/create")}
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => {
setPerPage(v);
setPage(1);
}}
/>
{/* Toolbar */} {/* Table */}
<DataTableToolbar <DataTable
searchValue={search} columns={columns}
onSearchChange={(v) => { setSearch(v); setPage(1) }} data={data?.data ?? []}
searchPlaceholder={t('Search', 'Gözlemek')} isLoading={isLoading}
columns={columnMeta} columnVisibility={columnVisibility}
columnVisibility={columnVisibility} onColumnVisibilityChange={setColumnVisibility}
onColumnVisibilityChange={setColumnVisibility} columnOrder={columnOrder}
columnOrder={columnOrder} onColumnOrderChange={setColumnOrder}
onColumnOrderChange={setColumnOrder} enableRowSelection
actionLabel={t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň')} getRowId={(row) => row.id}
onAction={() => navigate('/card-requisites/create')} currentPage={page}
perPageOptions={[10, 25, 50, 100]} totalPages={totalPages}
perPage={perPage} totalCount={total}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }} onPageChange={setPage}
/> />
</div>
{/* Table */}
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => row.id}
currentPage={page}
totalPages={totalPages}
totalCount={total}
onPageChange={setPage}
/>
{/* Delete dialog */} {/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}> <AlertDialog
open={deleteId !== null}
onOpenChange={(open) => !open && setDeleteId(null)}
>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle>{t('Are you sure?', 'Eminsiňizmi?')}</AlertDialogTitle> <AlertDialogTitle>
{t("Are you sure?", "Eminsiňizmi?")}
</AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
{t( {t(
'This action cannot be undone.', "This action cannot be undone.",
'Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.', "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.",
)} )}
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t('Cancel', 'Ýatyr')}</AlertDialogCancel> <AlertDialogCancel>{t("Cancel", "Ýatyr")}</AlertDialogCancel>
<AlertDialogAction <AlertDialogAction
onClick={handleDelete} onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90" className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
> >
{deleteMutation.isPending ? t('Deleting...', 'Öçürilýär...') : t('Delete', 'Öçür')} {deleteMutation.isPending
? t("Deleting...", "Öçürilýär...")
: t("Delete", "Öçür")}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
</div> </div>
) );
} }
@@ -157,6 +157,9 @@ export default function CardTransactionsPage() {
</h1> </h1>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -190,6 +193,7 @@ export default function CardTransactionsPage() {
totalCount={total} totalCount={total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
{/* Delete dialog */} {/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}> <AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
@@ -19,112 +19,127 @@ import {
useDeleteCardOrder, useDeleteCardOrder,
} from "@/features/orderNewCard/hooks/useOrderNewCard"; } from "@/features/orderNewCard/hooks/useOrderNewCard";
import type { CardOrderStatus } from "@/features/orderNewCard/api/orderNewCardApi"; import type { CardOrderStatus } from "@/features/orderNewCard/api/orderNewCardApi";
import { import { InfoRow, PassportImage } from "@/components/viewPageComponents";
InfoRow,
Section,
PassportImage,
} from "@/components/viewPageComponents";
// ─── Status badge ───────────────────────────────────────────────────────────── // ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_CFG: Record< const STATUS_CFG: Record<CardOrderStatus, { label: string; className: string; icon: string }> = {
CardOrderStatus, PENDING: { label: "Garaşylýar", icon: "⏳", className: "bg-amber-500/10 text-amber-400 border border-amber-500/20" },
{ label: string; className: string; icon: string } APPROVED: { label: "Tassyklandy", icon: "✓", className: "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20" },
> = { REJECTED: { label: "Ýatyryldy", icon: "✕", className: "bg-red-500/10 text-red-400 border border-red-500/20" },
PENDING: { }
label: "Garaşylýar",
icon: "⏳",
className: "bg-amber-500/10 text-amber-400 border border-amber-500/20",
},
APPROVED: {
label: "Tassyklandy",
icon: "✓",
className:
"bg-emerald-500/10 text-emerald-400 border border-emerald-500/20",
},
REJECTED: {
label: "Ýatyryldy",
icon: "✕",
className: "bg-red-500/10 text-red-400 border border-red-500/20",
},
};
function StatusBadge({ status }: { status: CardOrderStatus }) { function StatusBadge({ status }: { status: CardOrderStatus }) {
const cfg = STATUS_CFG[status]; const cfg = STATUS_CFG[status]
return ( return (
<span <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-bold tracking-wide ${cfg.className}`}>
className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-bold tracking-wide ${cfg.className}`}
>
<span className="text-[10px]">{cfg.icon}</span> <span className="text-[10px]">{cfg.icon}</span>
{cfg.label} {cfg.label}
</span> </span>
); )
} }
// ─── Loading skeleton ───────────────────────────────────────────────────────── // ─── Bento primitives ─────────────────────────────────────────────────────────
function BentoGrid({ cols = 2, children }: { cols?: 1 | 2 | 3 | 4; children: React.ReactNode }) {
const colClass = {
1: "grid-cols-1",
2: "grid-cols-1 sm:grid-cols-2",
3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",
}[cols]
return <div className={`grid ${colClass} gap-4`}>{children}</div>
}
function BentoCard({
title,
span,
children,
}: {
title?: string
span?: "full" | 2 | 3
children: React.ReactNode
}) {
const spanClass =
span === "full" ? "sm:col-span-full" :
span === 2 ? "sm:col-span-2" :
span === 3 ? "sm:col-span-3" : ""
return (
<div className={`bg-card border border-border rounded-xl overflow-hidden ${spanClass}`}>
{title && (
<div className="px-4 py-2.5 border-b border-border">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
{title}
</p>
</div>
)}
{children}
</div>
)
}
// ─── Skeleton ─────────────────────────────────────────────────────────────────
function DetailSkeleton() { function DetailSkeleton() {
return ( return (
<div className="space-y-6"> <div className="flex flex-col gap-4">
<Skeleton className="h-8 w-64" /> <Skeleton className="h-8 w-64" />
<div className="space-y-3"> <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{Array.from({ length: 5 }).map((_, i) => ( {Array.from({ length: 4 }).map((_, i) => (
<Skeleton key={i} className="h-10 w-full" /> <div key={i} className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3">
<Skeleton className="h-3 w-24 mb-1" />
{Array.from({ length: 3 }).map((_, j) => (
<Skeleton key={j} className="h-4 w-full" />
))}
</div>
))} ))}
</div> </div>
</div> </div>
); )
} }
// ─── CardOrderDetailPage ────────────────────────────────────────────────────── // ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardOrderDetailPage() { export default function CardOrderDetailPage() {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>()
const navigate = useNavigate(); const navigate = useNavigate()
const { t } = useTranslation(); const { t } = useTranslation()
const [deleteOpen, setDeleteOpen] = useState(false); const [deleteOpen, setDeleteOpen] = useState(false)
const { data: order, isLoading } = useCardOrderById(id ?? ""); const { data: order, isLoading } = useCardOrderById(id ?? "")
const deleteMutation = useDeleteCardOrder(); const deleteMutation = useDeleteCardOrder()
const handleDelete = async () => { const handleDelete = async () => {
if (!id) return; if (!id) return
await deleteMutation.mutateAsync(id); await deleteMutation.mutateAsync(id)
navigate("/order-new-card"); navigate("/order-new-card")
}; }
if (isLoading) return <DetailSkeleton />; if (isLoading) return <DetailSkeleton />
if (!order) if (!order)
return ( return (
<p className="text-muted-foreground text-sm"> <p className="text-muted-foreground text-sm">
{t("common.notFound", "Tapylmady")} {t("common.notFound", "Tapylmady")}
</p> </p>
); )
return ( return (
<div> <div className="flex flex-col gap-6">
{/* Header */}
<div className="flex items-start justify-between mb-6 gap-4"> {/* ── Page header ──────────────────────────────────────────────────── */}
<div> <div className="flex items-start justify-between gap-4">
<h1 className="text-xl font-semibold text-foreground"> <h1 className="text-xl font-semibold text-foreground">
{t("cardOrder.detailTitle", "Kart sargyt giriş üçin")}:{" "} {t("cardOrder.detailTitle", "Kart sargyt giriş üçin")}:{" "}
<span className="text-primary font-mono">{order.id}</span> <span className="text-primary font-mono">{order.id}</span>
</h1> </h1>
</div>
<div className="flex items-center gap-2 shrink-0"> <div className="flex items-center gap-2 shrink-0">
<Button <Button variant="outline" size="icon" title={t("common.print", "Çap etmek")}>
variant="outline"
size="icon"
title={t("common.print", "Çap etmek")}
>
<Printer size={15} /> <Printer size={15} />
</Button> </Button>
<Button <Button variant="outline" size="icon" title={t("common.export", "Eksport")}>
variant="outline"
size="icon"
title={t("common.export", "Eksport")}
>
<Download size={15} /> <Download size={15} />
</Button> </Button>
<Button <Button
@@ -145,127 +160,110 @@ export default function CardOrderDetailPage() {
</div> </div>
</div> </div>
{/* Main info */} {/* ── Row 1: Meta + Kart + Lokasiýa ───────────────────────────────── */}
<Section title=""> <BentoGrid cols={3}>
<InfoRow label="ID">{order.id}</InfoRow> <BentoCard title={t("cardOrder.section.meta", "Esasy maglumatlar")}>
<InfoRow label={t("cardOrder.field.createdAt", "Döredilen wagty")}> <InfoRow label="ID">{order.id}</InfoRow>
{order.createdAt} <InfoRow label={t("cardOrder.field.createdAt", "Döredilen wagty")}>
</InfoRow> {order.createdAt}
<InfoRow label={t("cardOrder.field.isPaid", "Tölenen")}> </InfoRow>
<span <InfoRow label={t("cardOrder.field.status", "Status")}>
className={`inline-flex items-center justify-center w-5 h-5 rounded-full text-xs font-bold <StatusBadge status={order.status} />
${ </InfoRow>
order.isPaid <InfoRow label={t("cardOrder.field.isPaid", "Tölenen")}>
? "bg-emerald-500/15 text-emerald-400" <span className={`inline-flex items-center justify-center w-5 h-5 rounded-full text-xs font-bold ${order.isPaid ? "bg-emerald-500/15 text-emerald-400" : "bg-red-500/15 text-red-400"}`}>
: "bg-red-500/15 text-red-400" {order.isPaid ? "✓" : "✕"}
}`} </span>
> </InfoRow>
{order.isPaid ? "✓" : "✕"} <InfoRow label={t("cardOrder.field.note", "Bellik")}>
</span> {order.note ?? "—"}
</InfoRow> </InfoRow>
<InfoRow label={t("cardOrder.field.status", "Status")}> <InfoRow label={t("cardOrder.field.createdBy", "Sargyt eden")}>
<StatusBadge status={order.status} /> <span className="text-primary font-medium">{order.createdBy}</span>
</InfoRow> </InfoRow>
<InfoRow label={t("cardOrder.field.note", "Bellik")}> </BentoCard>
{order.note ?? "—"}
</InfoRow>
<InfoRow label={t("cardOrder.field.createdBy", "Sargyt eden")}>
<span className="text-primary font-medium">{order.createdBy}</span>
</InfoRow>
</Section>
{/* Kart */} <BentoCard title={t("cardOrder.section.card", "Kart")}>
<Section title={t("cardOrder.section.card", "Kart")}> <InfoRow label={t("cardOrder.field.issuanceReason", "Kartyň çykarylmagynyň sebäbi")}>
<InfoRow <span className="text-primary font-medium">{order.issuanceReasonName}</span>
label={t( </InfoRow>
"cardOrder.field.issuanceReason", <InfoRow label={t("cardOrder.field.cardType", "Kart görnüşi")}>
"Kartyň çykarylmagynyň sebäbi", <span className="text-cyan-400 font-medium">{order.cardTypeName}</span>
)} </InfoRow>
> </BentoCard>
<span className="text-primary font-medium">
{order.issuanceReasonName}
</span>
</InfoRow>
<InfoRow label={t("cardOrder.field.cardType", "Kart görnüşi")}>
<span className="text-cyan-400 font-medium">
{order.cardTypeName}
</span>
</InfoRow>
</Section>
{/* Lokasiýa */} <BentoCard title={t("cardOrder.section.location", "Lokasiýa")}>
<Section title={t("cardOrder.section.location", "Lokasiýa")}> <InfoRow label={t("cardOrder.field.province", "Welaýat")}>
<InfoRow label={t("cardOrder.field.province", "Welaýat")}> {order.provinceName}
{order.provinceName} </InfoRow>
</InfoRow> <InfoRow label={t("cardOrder.field.branch", "Şahamça")}>
<InfoRow label={t("cardOrder.field.branch", "Şahamça")}> <span className="text-cyan-400 font-medium">{order.branchName}</span>
<span className="text-cyan-400 font-medium">{order.branchName}</span> </InfoRow>
</InfoRow> </BentoCard>
</Section> </BentoGrid>
{/* Şahsy maglumatlar */} {/* ── Row 2: Şahsy maglumatlar (full width — many fields) ─────────── */}
<Section title={t("cardOrder.section.personal", "Şahsy maglumatlar")}> <BentoGrid cols={2}>
<InfoRow label={t("cardOrder.field.fullName", "Doly ady")}> <BentoCard title={t("cardOrder.section.personal", "Şahsy maglumatlar")}>
{[order.lastName, order.firstName, order.middleName] <InfoRow label={t("cardOrder.field.fullName", "Doly ady")}>
.filter(Boolean) {[order.lastName, order.firstName, order.middleName].filter(Boolean).join(" ")}
.join(" ")} </InfoRow>
</InfoRow> <InfoRow label={t("cardOrder.field.birthDate", "Doglan güni")}>
<InfoRow label={t("cardOrder.field.birthDate", "Doglan güni")}> {order.birthDate}
{order.birthDate} </InfoRow>
</InfoRow> <InfoRow label={t("cardOrder.field.citizenship", "Raýatlyk")}>
<InfoRow label={t("cardOrder.field.phone", "Telefon")}> {order.citizenship}
{order.phone} </InfoRow>
</InfoRow> <InfoRow label={t("cardOrder.field.registeredAddress", "Ýazgy edilen salgy")}>
<InfoRow label={t("cardOrder.field.phoneExtra", "Telefon goşmaça")}> {order.registeredAddress}
{order.phoneExtra ?? "—"} </InfoRow>
</InfoRow> <InfoRow label={t("cardOrder.field.currentAddress", "Häzirki ýaşaýyş ýeri")}>
<InfoRow label={t("cardOrder.field.citizenship", "Raýatlyk")}> {order.currentAddress}
{order.citizenship} </InfoRow>
</InfoRow> <InfoRow label={t("cardOrder.field.workplace", "Işleýän ýeri we wezipesi")}>
<InfoRow {order.workplace}
label={t( </InfoRow>
"cardOrder.field.registeredAddress", </BentoCard>
"Ýazgy edilen salgyňyz",
)}
>
{order.registeredAddress}
</InfoRow>
<InfoRow
label={t("cardOrder.field.currentAddress", "Häzirki ýaşaýyş ýeri")}
>
{order.currentAddress}
</InfoRow>
<InfoRow
label={t("cardOrder.field.workplace", "Işleýän ýeriňiz we wezipäňiz")}
>
{order.workplace}
</InfoRow>
</Section>
{/* Pasport faýýlar */} <BentoCard title={t("cardOrder.section.contacts", "Kontakt")}>
<Section title={t("cardOrder.section.passportFiles", "Pasport faýýlar")}> <InfoRow label={t("cardOrder.field.phone", "Telefon")}>
<PassportImage {order.phone}
label={t("cardOrder.field.passportPage1", "Pasport (sahypa 1)")} </InfoRow>
url={order.passportFiles.page1} <InfoRow label={t("cardOrder.field.phoneExtra", "Telefon goşmaça")}>
/> {order.phoneExtra ?? "—"}
<PassportImage </InfoRow>
label={t( </BentoCard>
"cardOrder.field.passportPage23", </BentoGrid>
"Pasport (2-3-nji sahypa)",
)}
url={order.passportFiles.page23}
/>
<PassportImage
label={t("cardOrder.field.passportPage89", "Pasport (8-9 sahypa)")}
url={order.passportFiles.page89}
/>
<PassportImage
label={t("cardOrder.field.passportPage32", "Pasport (32-nji sahypa)")}
url={order.passportFiles.page32}
/>
</Section>
{/* Delete confirm dialog */} {/* ── Row 3: Passport images ───────────────────────────────────────── */}
<BentoGrid cols={4}>
<BentoCard title={t("cardOrder.field.passportPage1", "Sahypa 1")}>
<PassportImage
label={t("cardOrder.field.passportPage1", "Pasport (sahypa 1)")}
url={order.passportFiles.page1}
/>
</BentoCard>
<BentoCard title={t("cardOrder.field.passportPage23", "Sahypa 2-3")}>
<PassportImage
label={t("cardOrder.field.passportPage23", "Pasport (2-3-nji sahypa)")}
url={order.passportFiles.page23}
/>
</BentoCard>
<BentoCard title={t("cardOrder.field.passportPage89", "Sahypa 8-9")}>
<PassportImage
label={t("cardOrder.field.passportPage89", "Pasport (8-9 sahypa)")}
url={order.passportFiles.page89}
/>
</BentoCard>
<BentoCard title={t("cardOrder.field.passportPage32", "Sahypa 32")}>
<PassportImage
label={t("cardOrder.field.passportPage32", "Pasport (32-nji sahypa)")}
url={order.passportFiles.page32}
/>
</BentoCard>
</BentoGrid>
{/* ── Delete confirm dialog ─────────────────────────────────────────── */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}> <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
@@ -273,10 +271,7 @@ export default function CardOrderDetailPage() {
{t("cardOrder.deleteTitle", "Pozmak isleýärsiňizmi?")} {t("cardOrder.deleteTitle", "Pozmak isleýärsiňizmi?")}
</AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
{t( {t("cardOrder.deleteDescription", "Bu kart sargyt hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.")}
"cardOrder.deleteDescription",
"Bu kart sargyt hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.",
)}
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
@@ -292,6 +287,7 @@ export default function CardOrderDetailPage() {
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
</div> </div>
); )
} }
+118 -91
View File
@@ -1,12 +1,12 @@
// pages/CurrencyRatesPage.tsx // pages/CurrencyRatesPage.tsx
import { useState } from 'react' import { 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 { Eye, Pencil, Trash2 } from 'lucide-react' import { Eye, Pencil, Trash2 } from "lucide-react";
import { DataTable, type ColumnDef } from '@/components/dataTable' import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar } from '@/components/dataTableToolbar' import { DataTableToolbar } from "@/components/dataTableToolbar";
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -16,52 +16,63 @@ import {
AlertDialogFooter, AlertDialogFooter,
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from '@/components/ui/alert-dialog' } from "@/components/ui/alert-dialog";
import { useGetCurrencyRates, useDeleteCurrencyRate } from '@/features/currencyRates/hooks/useCurrencyRates' import {
import type { CurrencyRate } from '@/features/currencyRates/api/currencyRatesApi' useGetCurrencyRates,
useDeleteCurrencyRate,
} from "@/features/currencyRates/hooks/useCurrencyRates";
import type { CurrencyRate } from "@/features/currencyRates/api/currencyRatesApi";
// ─── Column visibility defaults ─────────────────────────────────────────────── // ─── Column visibility defaults ───────────────────────────────────────────────
const DEFAULT_VISIBILITY = { id: true, currencyFrom: true, currencyTo: true, value: true } const DEFAULT_VISIBILITY = {
const DEFAULT_ORDER = ['id', 'currencyFrom', 'currencyTo', 'value', 'actions'] id: true,
currencyFrom: true,
currencyTo: true,
value: true,
};
const DEFAULT_ORDER = ["id", "currencyFrom", "currencyTo", "value", "actions"];
// ─── CurrencyRatesPage ──────────────────────────────────────────────────────── // ─── CurrencyRatesPage ────────────────────────────────────────────────────────
export default function CurrencyRatesPage() { export default function CurrencyRatesPage() {
const { t } = useTranslation() const { t } = useTranslation();
const navigate = useNavigate() const navigate = useNavigate();
const [page, setPage] = useState(1) const [page, setPage] = useState(1);
const [perPage] = useState(25) const [perPage] = useState(25);
const [search, setSearch] = useState('') const [search, setSearch] = useState("");
const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>(DEFAULT_VISIBILITY) const [columnVisibility, setColumnVisibility] =
const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER) useState<Record<string, boolean>>(DEFAULT_VISIBILITY);
const [deleteId, setDeleteId] = useState<number | null>(null) const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER);
const [deleteId, setDeleteId] = useState<number | null>(null);
const { data, isLoading } = useGetCurrencyRates({ page, perPage, search }) const { data, isLoading } = useGetCurrencyRates({ page, perPage, search });
const deleteMutation = useDeleteCurrencyRate() const deleteMutation = useDeleteCurrencyRate();
const handleDeleteConfirm = async () => { const handleDeleteConfirm = async () => {
if (deleteId === null) return if (deleteId === null) return;
await deleteMutation.mutateAsync(deleteId) await deleteMutation.mutateAsync(deleteId);
setDeleteId(null) setDeleteId(null);
} };
const handleSearchChange = (val: string) => { const handleSearchChange = (val: string) => {
setSearch(val) setSearch(val);
setPage(1) setPage(1);
} };
// ─── Columns ────────────────────────────────────────────────────────────── // ─── Columns ──────────────────────────────────────────────────────────────
const columns: ColumnDef<CurrencyRate>[] = [ const columns: ColumnDef<CurrencyRate>[] = [
{ {
accessorKey: 'id', accessorKey: "id",
header: 'ID', header: "ID",
cell: ({ row }) => ( cell: ({ row }) => (
<button <button
className="text-primary font-semibold hover:underline" className="text-primary font-semibold hover:underline"
onClick={() => navigate(`/resources/currency-rates/${row.original.id}`)} onClick={() =>
navigate(`/resources/currency-rates/${row.original.id}`)
}
> >
{row.original.id} {row.original.id}
</button> </button>
@@ -69,29 +80,35 @@ export default function CurrencyRatesPage() {
size: 80, size: 80,
}, },
{ {
accessorKey: 'currencyFrom', accessorKey: "currencyFrom",
header: t('currencyRates.columns.currencyFrom', 'CURRENCY FROM'), header: t("currencyRates.columns.currencyFrom", "CURRENCY FROM"),
cell: ({ row }) => ( cell: ({ row }) => (
<span className="font-medium text-foreground">{row.original.currencyFrom}</span> <span className="font-medium text-foreground">
{row.original.currencyFrom}
</span>
), ),
}, },
{ {
accessorKey: 'currencyTo', accessorKey: "currencyTo",
header: t('currencyRates.columns.currencyTo', 'CURRENCY TO'), header: t("currencyRates.columns.currencyTo", "CURRENCY TO"),
cell: ({ row }) => ( cell: ({ row }) => (
<span className="font-medium text-foreground">{row.original.currencyTo}</span> <span className="font-medium text-foreground">
{row.original.currencyTo}
</span>
), ),
}, },
{ {
accessorKey: 'value', accessorKey: "value",
header: t('currencyRates.columns.value', 'VALUE'), header: t("currencyRates.columns.value", "VALUE"),
cell: ({ row }) => ( cell: ({ row }) => (
<span className="text-foreground tabular-nums">{row.original.value}</span> <span className="text-foreground tabular-nums">
{row.original.value}
</span>
), ),
}, },
{ {
id: 'actions', id: "actions",
header: '', header: "",
enableSorting: false, enableSorting: false,
enableHiding: false, enableHiding: false,
cell: ({ row }) => ( cell: ({ row }) => (
@@ -101,7 +118,7 @@ export default function CurrencyRatesPage() {
size="icon" size="icon"
className="h-8 w-8 text-muted-foreground hover:text-foreground" className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/currency-rates/${row.original.id}`)} onClick={() => navigate(`/currency-rates/${row.original.id}`)}
title={t('common.view', 'Görmek')} title={t("common.view", "Görmek")}
> >
<Eye size={15} /> <Eye size={15} />
</Button> </Button>
@@ -110,7 +127,7 @@ export default function CurrencyRatesPage() {
size="icon" size="icon"
className="h-8 w-8 text-muted-foreground hover:text-foreground" className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/currency-rates/${row.original.id}/edit`)} onClick={() => navigate(`/currency-rates/${row.original.id}/edit`)}
title={t('common.edit', 'Üýtgetmek')} title={t("common.edit", "Üýtgetmek")}
> >
<Pencil size={15} /> <Pencil size={15} />
</Button> </Button>
@@ -119,7 +136,7 @@ export default function CurrencyRatesPage() {
size="icon" size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive" className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteId(row.original.id)} onClick={() => setDeleteId(row.original.id)}
title={t('common.delete', 'Pozmak')} title={t("common.delete", "Pozmak")}
> >
<Trash2 size={15} /> <Trash2 size={15} />
</Button> </Button>
@@ -127,82 +144,92 @@ export default function CurrencyRatesPage() {
), ),
size: 120, size: 120,
}, },
] ];
const columnMeta = columns const columnMeta = columns
.filter((c) => 'accessorKey' in c && c.accessorKey) .filter((c) => "accessorKey" in c && c.accessorKey)
.map((c) => ({ .map((c) => ({
id: String(('accessorKey' in c ? c.accessorKey : c.id) ?? ''), id: String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""),
label: typeof c.header === 'string' ? c.header : String(('accessorKey' in c ? c.accessorKey : '') ?? ''), label:
})) typeof c.header === "string"
? c.header
: String(("accessorKey" in c ? c.accessorKey : "") ?? ""),
}));
// ─── Render ─────────────────────────────────────────────────────────────── // ─── Render ───────────────────────────────────────────────────────────────
return ( return (
<div className="p-6"> <div className="p-6">
<h1 className="text-2xl font-semibold text-foreground mb-5"> <h1 className="text-2xl font-semibold text-foreground mb-5">
{t('currencyRates.title', 'Walýuta kursy')} {t("currencyRates.title", "Walýuta kursy")}
</h1> </h1>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
onSearchChange={handleSearchChange}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
actionLabel={t(
"currencyRates.actions.create",
"Walýuta kursy dörediň",
)}
onAction={() => navigate("/currency-rates/create")}
/>
<DataTableToolbar <DataTable
searchValue={search} columns={columns}
onSearchChange={handleSearchChange} data={data?.data ?? []}
searchPlaceholder={t('common.search', 'Gözlemek')} isLoading={isLoading}
columns={columnMeta} columnVisibility={columnVisibility}
columnVisibility={columnVisibility} onColumnVisibilityChange={setColumnVisibility}
onColumnVisibilityChange={setColumnVisibility} columnOrder={columnOrder}
columnOrder={columnOrder} onColumnOrderChange={setColumnOrder}
onColumnOrderChange={setColumnOrder} enableRowSelection
actionLabel={t('currencyRates.actions.create', 'Walýuta kursy dörediň')} getRowId={(row) => String(row.id)}
onAction={() => navigate('/currency-rates/create')} currentPage={page}
/> totalPages={data?.totalPages ?? 1}
totalCount={data?.total ?? 0}
<DataTable onPageChange={setPage}
columns={columns} />
data={data?.data ?? []} </div>
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => String(row.id)}
currentPage={page}
totalPages={data?.totalPages ?? 1}
totalCount={data?.total ?? 0}
onPageChange={setPage}
/>
{/* Delete Confirmation Dialog */} {/* Delete Confirmation Dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => { if (!open) setDeleteId(null) }}> <AlertDialog
open={deleteId !== null}
onOpenChange={(open) => {
if (!open) setDeleteId(null);
}}
>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle> <AlertDialogTitle>
{t('currencyRates.deleteDialog.title', 'Pozmak isleýärsiňizmi?')} {t("currencyRates.deleteDialog.title", "Pozmak isleýärsiňizmi?")}
</AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
{t( {t(
'currencyRates.deleteDialog.description', "currencyRates.deleteDialog.description",
'Bu amal yzyna gaýtarylyp bilinmez. Walýuta kursy hemişelik pozular.' "Bu amal yzyna gaýtarylyp bilinmez. Walýuta kursy hemişelik pozular.",
)} )}
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel> <AlertDialogCancel>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
<AlertDialogAction <AlertDialogAction
onClick={handleDeleteConfirm} onClick={handleDeleteConfirm}
disabled={deleteMutation.isPending} disabled={deleteMutation.isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90" className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
> >
{deleteMutation.isPending {deleteMutation.isPending
? t('common.deleting', 'Pozulýar...') ? t("common.deleting", "Pozulýar...")
: t('common.delete', 'Pozmak')} : t("common.delete", "Pozmak")}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
</div> </div>
) );
} }
@@ -1,9 +1,9 @@
// pages/VisaMasterSettingsPage.tsx // pages/VisaMasterSettingsPage.tsx
import { useState } from 'react' import { 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 { Pencil, Trash2 } from 'lucide-react' import { Pencil, Trash2 } from "lucide-react";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -13,97 +13,82 @@ import {
AlertDialogFooter, AlertDialogFooter,
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from '@/components/ui/alert-dialog' } from "@/components/ui/alert-dialog";
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { DataTable, type ColumnDef } from '@/components/dataTable' import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar } from '@/components/dataTableToolbar' import { DataTableToolbar } from "@/components/dataTableToolbar";
import { import { useGetVisaMasterSettings, useDeleteVisaMasterSetting } from "@/features/visaMasterSberSettings/hooks/useVisaMasterSettings";
useGetVisaMasterSettings, import type { VisaMasterSetting } from "@/features/visaMasterSberSettings/api/visaMasterSberSettingsApi";
useDeleteVisaMasterSetting,
} from '@/features/visaMasterSberSettings/hooks/useVisaMasterSettings'
import type { VisaMasterSetting } from '@/features/visaMasterSberSettings/api/visaMasterSberSettingsApi'
// ─── Column defaults ────────────────────────────────────────────────────────── // ─── Column defaults ──────────────────────────────────────────────────────────
const DEFAULT_VISIBILITY = { id: true, kod: true, ady: true, yazgy: true } const DEFAULT_VISIBILITY = { id: true, kod: true, ady: true, yazgy: true };
const DEFAULT_ORDER = ['id', 'kod', 'ady', 'yazgy', 'actions'] const DEFAULT_ORDER = ["id", "kod", "ady", "yazgy", "actions"];
// ─── VisaMasterSettingsPage ─────────────────────────────────────────────────── // ─── VisaMasterSettingsPage ───────────────────────────────────────────────────
export default function VisaMasterSettingsPage() { export default function VisaMasterSettingsPage() {
const { t } = useTranslation() const { t } = useTranslation();
const navigate = useNavigate() const navigate = useNavigate();
const [page, setPage] = useState(1) const [page, setPage] = useState(1);
const [perPage] = useState(25) const [perPage] = useState(25);
const [search, setSearch] = useState('') const [search, setSearch] = useState("");
const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>(DEFAULT_VISIBILITY) const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>(DEFAULT_VISIBILITY);
const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER) const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER);
const [deleteId, setDeleteId] = useState<number | null>(null) const [deleteId, setDeleteId] = useState<number | null>(null);
const { data, isLoading } = useGetVisaMasterSettings({ page, perPage, search }) const { data, isLoading } = useGetVisaMasterSettings({ page, perPage, search });
const deleteMutation = useDeleteVisaMasterSetting() const deleteMutation = useDeleteVisaMasterSetting();
const handleDeleteConfirm = async () => { const handleDeleteConfirm = async () => {
if (deleteId === null) return if (deleteId === null) return;
await deleteMutation.mutateAsync(deleteId) await deleteMutation.mutateAsync(deleteId);
setDeleteId(null) setDeleteId(null);
} };
const handleSearchChange = (val: string) => { const handleSearchChange = (val: string) => {
setSearch(val) setSearch(val);
setPage(1) setPage(1);
} };
// ─── Columns ────────────────────────────────────────────────────────────── // ─── Columns ──────────────────────────────────────────────────────────────
const columns: ColumnDef<VisaMasterSetting>[] = [ const columns: ColumnDef<VisaMasterSetting>[] = [
{ {
accessorKey: 'id', accessorKey: "id",
header: 'ID', header: "ID",
cell: ({ row }) => ( cell: ({ row }) => <span className="text-primary font-semibold">{row.original.id}</span>,
<span className="text-primary font-semibold">{row.original.id}</span>
),
size: 80, size: 80,
}, },
{ {
accessorKey: 'kod', accessorKey: "kod",
header: t('visaMasterSettings.columns.kod', 'KOD'), header: t("visaMasterSettings.columns.kod", "KOD"),
cell: ({ row }) => ( cell: ({ row }) => <span className="font-medium text-foreground font-mono text-xs">{row.original.kod}</span>,
<span className="font-medium text-foreground font-mono text-xs">
{row.original.kod}
</span>
),
}, },
{ {
accessorKey: 'ady', accessorKey: "ady",
header: t('visaMasterSettings.columns.ady', 'ADY'), header: t("visaMasterSettings.columns.ady", "ADY"),
cell: ({ row }) => ( cell: ({ row }) => <span className="text-foreground">{row.original.ady}</span>,
<span className="text-foreground">{row.original.ady}</span>
),
}, },
{ {
accessorKey: 'yazgy', accessorKey: "yazgy",
header: t('visaMasterSettings.columns.yazgy', 'YAZGY'), header: t("visaMasterSettings.columns.yazgy", "YAZGY"),
cell: ({ row }) => ( cell: ({ row }) => <span className="text-foreground line-clamp-1 max-w-xs">{row.original.yazgy}</span>,
<span className="text-foreground line-clamp-1 max-w-xs">{row.original.yazgy}</span>
),
}, },
{ {
id: 'actions', id: "actions",
header: '', header: "",
enableSorting: false, enableSorting: false,
enableHiding: false, enableHiding: false,
cell: ({ row }) => ( cell: ({ row }) => (
<div className="flex items-center justify-end gap-1"> <div className="flex items-center justify-end gap-1">
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"
className="h-8 w-8 text-muted-foreground hover:text-foreground" className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() => onClick={() => navigate(`/visa-master-sber-settings/${row.original.id}/edit`)}
navigate(`/visa-master-sber-settings/${row.original.id}/edit`) title={t("common.edit", "Üýtgetmek")}
}
title={t('common.edit', 'Üýtgetmek')}
> >
<Pencil size={15} /> <Pencil size={15} />
</Button> </Button>
@@ -112,7 +97,7 @@ export default function VisaMasterSettingsPage() {
size="icon" size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive" className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteId(row.original.id)} onClick={() => setDeleteId(row.original.id)}
title={t('common.delete', 'Pozmak')} title={t("common.delete", "Pozmak")}
> >
<Trash2 size={15} /> <Trash2 size={15} />
</Button> </Button>
@@ -120,85 +105,78 @@ export default function VisaMasterSettingsPage() {
), ),
size: 100, size: 100,
}, },
] ];
const columnMeta = columns const columnMeta = columns
.filter((c) => 'accessorKey' in c && c.accessorKey) .filter((c) => "accessorKey" in c && c.accessorKey)
.map((c) => ({ .map((c) => ({
id: String(('accessorKey' in c ? c.accessorKey : c.id) ?? ''), id: String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""),
label: typeof c.header === 'string' ? c.header : String(('accessorKey' in c ? c.accessorKey : '') ?? ''), label: typeof c.header === "string" ? c.header : String(("accessorKey" in c ? c.accessorKey : "") ?? ""),
})) }));
// ─── Render ─────────────────────────────────────────────────────────────── // ─── Render ───────────────────────────────────────────────────────────────
return ( return (
<div className="p-6"> <div className="p-6">
<h1 className="text-2xl font-semibold text-foreground mb-5">{t("visaMasterSettings.title", "Visa/Master, Sber sazlamalar")}</h1>
<h1 className="text-2xl font-semibold text-foreground mb-5"> <div className="bg-card border border-border rounded-xl p-4">
{t('visaMasterSettings.title', 'Visa/Master, Sber sazlamalar')} <DataTableToolbar
</h1> searchValue={search}
onSearchChange={handleSearchChange}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
actionLabel={t("visaMasterSettings.actions.create", "Visa/Master, Sber sazlamalar dörediň")}
onAction={() => navigate("/visa-master-sber-settings/create")}
/>
<DataTableToolbar <DataTable
searchValue={search} columns={columns}
onSearchChange={handleSearchChange} data={data?.data ?? []}
searchPlaceholder={t('common.search', 'Gözlemek')} isLoading={isLoading}
columns={columnMeta} columnVisibility={columnVisibility}
columnVisibility={columnVisibility} onColumnVisibilityChange={setColumnVisibility}
onColumnVisibilityChange={setColumnVisibility} columnOrder={columnOrder}
columnOrder={columnOrder} onColumnOrderChange={setColumnOrder}
onColumnOrderChange={setColumnOrder} enableRowSelection
actionLabel={t('visaMasterSettings.actions.create', 'Visa/Master, Sber sazlamalar dörediň')} getRowId={(row) => String(row.id)}
onAction={() => navigate('/visa-master-sber-settings/create')} currentPage={page}
/> totalPages={data?.totalPages ?? 1}
totalCount={data?.total ?? 0}
<DataTable onPageChange={setPage}
columns={columns} />
data={data?.data ?? []} </div>
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => String(row.id)}
currentPage={page}
totalPages={data?.totalPages ?? 1}
totalCount={data?.total ?? 0}
onPageChange={setPage}
/>
{/* Delete Confirmation */} {/* Delete Confirmation */}
<AlertDialog <AlertDialog
open={deleteId !== null} open={deleteId !== null}
onOpenChange={(open) => { if (!open) setDeleteId(null) }} onOpenChange={(open) => {
if (!open) setDeleteId(null);
}}
> >
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle> <AlertDialogTitle>{t("visaMasterSettings.deleteDialog.title", "Pozmak isleýärsiňizmi?")}</AlertDialogTitle>
{t('visaMasterSettings.deleteDialog.title', 'Pozmak isleýärsiňizmi?')}
</AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
{t( {t("visaMasterSettings.deleteDialog.description", "Bu amal yzyna gaýtarylyp bilinmez. Sazlama hemişelik pozular.")}
'visaMasterSettings.deleteDialog.description',
'Bu amal yzyna gaýtarylyp bilinmez. Sazlama hemişelik pozular.'
)}
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel> <AlertDialogCancel>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
<AlertDialogAction <AlertDialogAction
onClick={handleDeleteConfirm} onClick={handleDeleteConfirm}
disabled={deleteMutation.isPending} disabled={deleteMutation.isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90" className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
> >
{deleteMutation.isPending {deleteMutation.isPending ? t("common.deleting", "Pozulýar...") : t("common.delete", "Pozmak")}
? t('common.deleting', 'Pozulýar...')
: t('common.delete', 'Pozmak')}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
</div> </div>
) );
} }
@@ -303,7 +303,8 @@ export default function SberPaymentsListPage() {
<h1 className="text-xl font-semibold text-foreground"> <h1 className="text-xl font-semibold text-foreground">
Sber tolegier (talyplar ucin) Sber tolegier (talyplar ucin)
</h1> </h1>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -347,5 +348,6 @@ export default function SberPaymentsListPage() {
onPageChange={setPage} onPageChange={setPage}
/> />
</div> </div>
</div>
) )
} }
@@ -215,6 +215,7 @@ export default function IntlPaymentsPage() {
</h1> </h1>
</div> </div>
<MonthSelector value={month} onChange={(v) => { setMonth(v); setPage(1) }} /> <MonthSelector value={month} onChange={(v) => { setMonth(v); setPage(1) }} />
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -262,6 +263,7 @@ export default function IntlPaymentsPage() {
totalCount={data?.meta?.total} totalCount={data?.meta?.total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
<AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}> <AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>
<AlertDialogContent> <AlertDialogContent>
@@ -1,6 +1,6 @@
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Trash2, Pencil, ChevronRight } from "lucide-react"; import { Trash2, Pencil } from "lucide-react";
import { import {
useLoanOrderMobileById, useLoanOrderMobileById,
useDeleteLoanOrderMobile, useDeleteLoanOrderMobile,
@@ -14,57 +14,69 @@ import {
type StatusBadgeVariant, type StatusBadgeVariant,
} from "@/components/ui/statusBadge"; } from "@/components/ui/statusBadge";
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react"; import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
import { import {
InfoRow, InfoRow,
Section,
PassportImage, PassportImage,
AuditLog,
type AuditRowProps,
} from "@/components/viewPageComponents"; } from "@/components/viewPageComponents";
import { AuditRow, type AuditRowProps } from "@/components/viewPageComponents";
// ─── Status badge ───────────────────────────────────────────────────────────── // ─── Status config ────────────────────────────────────────────────────────────
const STATUS_CONFIG = { const STATUS_CONFIG = {
GARAŞYLÝAR: { GARAŞYLÝAR: { label: "Garaşylýar", variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
label: "Garaşylýar", KANAGATLANDYRYLAN: { label: "Tassyklandy", variant: "success" as StatusBadgeVariant, icon: CheckCircle2 },
variant: "warning" as StatusBadgeVariant, RED_EDILDI: { label: "Ýatyryldy", variant: "error" as StatusBadgeVariant, icon: XCircle },
icon: AlertCircle, IŞLENÝÄR: { label: "Işlenýär", variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
}, } satisfies Record<LoanOrderMobileStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }>
KANAGATLANDYRYLAN: {
label: "Tassyklandy",
variant: "success" as StatusBadgeVariant,
icon: CheckCircle2,
},
RED_EDILDI: {
label: "Ýatyryldy",
variant: "error" as StatusBadgeVariant,
icon: XCircle,
},
IŞLENÝÄR: {
label: "Işlenýär",
variant: "warning" as StatusBadgeVariant,
icon: AlertCircle,
},
} satisfies Record<
LoanOrderMobileStatus,
{ label: string; variant: StatusBadgeVariant; icon: React.ElementType }
>;
function LoanOrderMobileStatusBadge({ function LoanOrderMobileStatusBadge({ status }: { status: LoanOrderMobileStatus }) {
status, const cfg = STATUS_CONFIG[status]
}: { if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
status: LoanOrderMobileStatus; return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
}) {
const cfg = STATUS_CONFIG[status];
if (!cfg)
return (
<span className="text-xs text-muted-foreground">{String(status)}</span>
);
return (
<StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
);
} }
// ─── InfoRow ───────────────────────────────────────────────────────────────── // ─── Bento primitives ─────────────────────────────────────────────────────────
function BentoGrid({ cols = 2, children }: { cols?: 1 | 2 | 3 | 4; children: React.ReactNode }) {
const colClass = {
1: "grid-cols-1",
2: "grid-cols-1 sm:grid-cols-2",
3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",
}[cols]
return <div className={`grid ${colClass} gap-4`}>{children}</div>
}
function BentoCard({
title,
span,
children,
noPadding,
}: {
title?: string
span?: "full" | 2 | 3
children: React.ReactNode
noPadding?: boolean
}) {
const spanClass =
span === "full" ? "sm:col-span-full" :
span === 2 ? "sm:col-span-2" :
span === 3 ? "sm:col-span-3" : ""
return (
<div className={`bg-card border border-border rounded-xl overflow-hidden ${spanClass}`}>
{title && (
<div className="px-4 py-2.5 border-b border-border">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
{title}
</p>
</div>
)}
<div className={noPadding ? "" : undefined}>{children}</div>
</div>
)
}
// ─── Skeleton ───────────────────────────────────────────────────────────────── // ─── Skeleton ─────────────────────────────────────────────────────────────────
@@ -72,77 +84,72 @@ function LoanOrderMobilesViewSkeleton() {
return ( return (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<Skeleton className="h-7 w-64" /> <Skeleton className="h-7 w-64" />
{[...Array(5)].map((_, i) => ( <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div {[...Array(6)].map((_, i) => (
key={i} <div key={i} className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3">
className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3" <Skeleton className="h-3 w-24 mb-1" />
> {[...Array(3)].map((_, j) => (
<Skeleton className="h-4 w-32 mb-1" /> <Skeleton key={j} className="h-4 w-full" />
{[...Array(3)].map((_, j) => ( ))}
<Skeleton key={j} className="h-4 w-full" /> </div>
))} ))}
</div> </div>
))}
</div> </div>
); )
} }
// ─── Page ───────────────────────────────────────────────────────────────────── // ─── Page ─────────────────────────────────────────────────────────────────────
export default function LoanOrderMobilesViewPage() { export default function LoanOrderMobilesViewPage() {
const { t } = useTranslation(); const { t } = useTranslation()
const navigate = useNavigate(); const navigate = useNavigate()
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>()
const deleteMutation = useDeleteLoanOrderMobile(); const deleteMutation = useDeleteLoanOrderMobile()
const { data: order, isLoading } = useLoanOrderMobileById(id!); const { data: order, isLoading } = useLoanOrderMobileById(id!)
const handleDelete = () => { const handleDelete = () => {
if ( if (!window.confirm(t("loanOrderMobiles.deleteConfirm", "Bu sargyt pozulsynmy?"))) return
!window.confirm(
t("loanOrderMobiles.deleteConfirm", "Bu sargyt pozulsynmy?"),
)
)
return;
deleteMutation.mutate(id!, { deleteMutation.mutate(id!, {
onSuccess: () => { onSuccess: () => {
toast.success(t("loanOrderMobiles.deleteSuccess", "Sargyt pozuldy")); toast.success(t("loanOrderMobiles.deleteSuccess", "Sargyt pozuldy"))
navigate("/loan-order-mobiles"); navigate("/loan-order-mobiles")
}, },
onError: () => { onError: () => {
toast.error( toast.error(t("loanOrderMobiles.deleteError", "Pozma wagty ýalňyşlyk ýüze çykdy"))
t("loanOrderMobiles.deleteError", "Pozma wagty ýalňyşlyk ýüze çykdy"),
);
}, },
}); })
}; }
if (isLoading) return <LoanOrderMobilesViewSkeleton />; if (isLoading) return <LoanOrderMobilesViewSkeleton />
if (!order) { if (!order) {
return ( return (
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm"> <div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
{t("common.notFound", "Tapylmady")} {t("common.notFound", "Tapylmady")}
</div> </div>
); )
} }
// Replace with real audit data from API when available
const auditLogs: AuditRowProps[] = [ const auditLogs: AuditRowProps[] = [
{ {
id: "44548", id: "44548",
action: t("audit.actions.view", "Görmek"), action: t("audit.actions.view", "Görmek"),
by: order.createdBy ?? "", by: order.createdBy ?? "",
target: `${t("loanOrderMobiles.title", "Karz sargyt")}: ${order.id}`, target: `${t("loanOrderMobiles.title", "Karz sargyt")}: ${order.id}`,
status: "FINISHED", status: "FINISHED",
date: order.createdAt ?? "", date: order.createdAt ?? "",
}, },
]; ]
const hasCard = !!(order.cardNumber || order.cardName)
const hasGuarantor = !!(order.guarantor1Name || order.guarantor1CardNumber)
return ( return (
<div className="flex flex-col"> <div className="flex flex-col gap-6">
{/* Page Header */}
<div className="flex items-center justify-between mb-5"> {/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground"> <h1 className="text-xl font-semibold text-foreground">
{t("loanOrderMobiles.view.title", "Karz sargyt giriş")}: {order.id} {t("loanOrderMobiles.view.title", "Karz sargyt giriş")}: {order.id}
</h1> </h1>
@@ -165,299 +172,270 @@ export default function LoanOrderMobilesViewPage() {
</div> </div>
</div> </div>
{/* ── Basic Info ─────────────────────────────────────────────────────── */} {/* ── Row 1: Meta + Loan + Location ───────────────────────────────── */}
<div className="bg-card border border-border rounded-xl overflow-hidden mb-6"> <BentoGrid cols={3}>
<InfoRow label="ID" value={order.id} /> <BentoCard title={t("loanOrders.sections.meta", "Esasy maglumatlar")}>
{/* Status row — special render */} <InfoRow label="ID" value={order.id} />
<div className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4 border-b border-border">
<span className="text-sm text-muted-foreground">
{t("loanOrders.columns.status", "Status")}
</span>
<LoanOrderMobileStatusBadge status={order.status} />
</div>
<InfoRow
label={t("loanOrders.columns.createdAt", "Döredilen wagty")}
value={order.createdAt}
/>
<InfoRow
label={t("loanOrders.columns.branch", "Şahamça")}
value={order.branch}
isLink
/>
<InfoRow
label={t("loanOrders.fields.note", "Bellik")}
value={order.note || "-"}
/>
</div>
{/* ── Card ───────────────────────────────────────────────────────────── */}
{(order.cardNumber || order.cardName) && (
<Section title={t("loanOrders.sections.card", "Kart")}>
<div className="p-6 bg-slate-50 dark:bg-slate-900/50 border-b border-border flex items-center justify-center">
<CreditCardVisual
cardNumber={order.cardNumber}
cardName={order.cardName}
expMonth={order.cardExpMonth}
expYear={order.cardExpYear}
variant="primary"
/>
</div>
<InfoRow <InfoRow
label={t("loanOrders.fields.cardNumber", "Kart belgisi")} label={t("loanOrders.columns.status", "Status")}
value={order.cardNumber} >
<LoanOrderMobileStatusBadge status={order.status} />
</InfoRow>
<InfoRow
label={t("loanOrders.columns.createdAt", "Döredilen wagty")}
value={order.createdAt}
/> />
<InfoRow <InfoRow
label={t("loanOrders.fields.cardName", "Kartdaky ady")} label={t("loanOrders.columns.branch", "Şahamça")}
value={order.cardName} value={order.branch}
/> isLink
</Section>
)}
{/* ── Loan ───────────────────────────────────────────────────────────── */}
<Section title={t("loanOrders.sections.loan", "Karz")}>
<InfoRow
label={t("loanOrders.columns.loanType", "Karz görnüşi")}
value={order.loanType}
isLink
/>
<InfoRow
label={t("loanOrders.fields.loanAmount", "Karz möçberi")}
value={order.loanAmount ? String(order.loanAmount) : undefined}
/>
</Section>
{/* ── Location ───────────────────────────────────────────────────────── */}
<Section title={t("loanOrders.sections.location", "Lokasiýa")}>
<InfoRow
label={t("loanOrders.columns.region", "Welaýat")}
value={order.region}
/>
</Section>
{/* ── Personal Info ──────────────────────────────────────────────────── */}
<Section title={t("loanOrders.sections.personal", "Şahsy maglumatlar")}>
<InfoRow
label={t("loanOrders.fields.fullName", "Doly ady")}
value={`${order.firstName} ${order.lastName} ${order.patronicName || ""}`.trim()}
/>
<InfoRow
label={t("loanOrders.fields.education", "Bilimi")}
value={order.education ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.maritalStatus", "Maşgala ýagdaýy")}
value={order.marriageStatus ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.birthDate", "Doglan güni")}
value={order.dateOfBirth ?? undefined}
/>
<InfoRow
label={t(
"loanOrders.fields.registeredAddress",
"Ýazgy edilen salgyňyz",
)}
value={order.residence ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.currentAddress", "Häzirki ýaşaýyş ýeri")}
value={order.currentResidence ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.loanHistory", "Karz taryhy")}
value={order.loanHistory ?? undefined}
isLink
/>
</Section>
{/* ── Contacts ───────────────────────────────────────────────────────── */}
<Section
title={t(
"loanOrders.sections.contacts",
"Habarlaşmak üçin maglumatlar",
)}
>
<InfoRow
label={t("loanOrders.fields.email", "E-poçta")}
value={order.email ?? undefined}
/>
<InfoRow
label={t("loanOrders.columns.phone", "Telefon")}
value={order.phone}
/>
<InfoRow
label={t("loanOrders.fields.phoneAlt", "Telefon goşmaça")}
value={order.phoneAdditional ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.homePhone", "Öý telefony")}
value={order.homePhone ?? undefined}
/>
</Section>
{/* ── Employment ─────────────────────────────────────────────────────── */}
<Section title={t("loanOrders.sections.employment", "Iş")}>
<InfoRow
label={t(
"loanOrders.fields.employer",
"Işleýän edaranyň/kärhananyn ady",
)}
value={order.workCompany ?? undefined}
/>
<InfoRow
label={t(
"loanOrders.fields.deptPhone",
"Işgärler bölüminiň iş belgisi",
)}
value={order.workHrPhone ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.workRegion", "Işleýän welaýatyňyz")}
value={order.workRegion ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.workCity", "Işleýän etrabyňyz")}
value={order.workProvince ?? undefined}
isLink
/>
<InfoRow
label={t("loanOrders.fields.position", "Wezipe")}
value={order.position ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.salary", "Zähmet haky")}
value={order.salary ? String(order.salary) : undefined}
/>
<InfoRow
label={t("loanOrders.fields.employedSince", "Işe başlan wagtyňyz")}
value={order.workStartedAt ?? undefined}
/>
</Section>
{/* ── Passport ───────────────────────────────────────────────────────── */}
<Section title={t("loanOrders.sections.passport", "Pasport")}>
<InfoRow
label={t("loanOrders.fields.passportNumber", "Pasport")}
value={order.passportNumber ?? undefined}
/>
<InfoRow
label={t(
"loanOrders.fields.passportIssuedBy",
"Kim tarapyndan berildi",
)}
value={order.passportGivenBy ?? undefined}
/>
<InfoRow
label={t(
"loanOrders.fields.passportBirthPlace",
"Doglan ýeri (pasport)",
)}
value={order.bornPlace ?? undefined}
/>
<PassportImage
label={t("loanOrders.fields.passportPage1", "Pasport (sahypa 1)")}
src={order.passportPage1Url ?? undefined}
/>
<PassportImage
label={t(
"loanOrders.fields.passportPage23",
"Pasport (2-3-nji sahypa)",
)}
src={order.passportPage23Url ?? undefined}
/>
<PassportImage
label={t("loanOrders.fields.passportPage89", "Pasport (8-9 sahypa)")}
src={order.passportPage89Url ?? undefined}
/>
<PassportImage
label={t(
"loanOrders.fields.passportPage32",
"Pasport (32-nji sahypa)",
)}
src={order.passportPage32Url ?? undefined}
/>
</Section>
{/* ── Guarantor ──────────────────────────────────────────────────────── */}
{(order.guarantor1Name || order.guarantor1CardNumber) && (
<Section title={t("loanOrders.sections.guarantor", "1. Zamun")}>
<InfoRow
label={t("loanOrders.fields.guarantorName", "Zamunyň doly ady")}
value={`${order.guarantor1Name || ""} ${order.guarantor1Surname || ""} ${order.guarantor1Patronic || ""}`.trim()}
/> />
<InfoRow <InfoRow
label={t("loanOrders.fields.guarantorPassport", "Pasport")} label={t("loanOrders.fields.note", "Bellik")}
value={`${order.guarantor1PassportSerie || ""} ${order.guarantor1PassportNumber || ""}`.trim()} value={order.note || undefined}
/>
</BentoCard>
<BentoCard title={t("loanOrders.sections.loan", "Karz")}>
<InfoRow
label={t("loanOrders.columns.loanType", "Karz görnüşi")}
value={order.loanType}
isLink
/> />
<InfoRow <InfoRow
label={t("loanOrders.fields.guarantorSalary", "Ortaca zähmet haky")} label={t("loanOrders.fields.loanAmount", "Karz möçberi")}
value={ value={order.loanAmount ? String(order.loanAmount) : undefined}
order.guarantor1Salary
? String(order.guarantor1Salary)
: undefined
}
/> />
{order.guarantor1CardNumber && ( </BentoCard>
<div className="p-6 bg-slate-50 dark:bg-slate-900/50 border-t border-border flex items-center justify-center">
<BentoCard title={t("loanOrders.sections.location", "Lokasiýa")}>
<InfoRow
label={t("loanOrders.columns.region", "Welaýat")}
value={order.region}
/>
</BentoCard>
</BentoGrid>
{/* ── Row 2: Card visual (conditional) ────────────────────────────── */}
{hasCard && (
<BentoGrid cols={2}>
<BentoCard title={t("loanOrders.sections.card", "Kart")} noPadding>
<div className="p-6 bg-slate-50 dark:bg-slate-900/50 border-b border-border flex items-center justify-center">
<CreditCardVisual <CreditCardVisual
cardNumber={order.guarantor1CardNumber} cardNumber={order.cardNumber}
cardName={order.guarantor1CardName} cardName={order.cardName}
expMonth={order.guarantor1CardExpMonth} expMonth={order.cardExpMonth}
expYear={order.guarantor1CardExpYear} expYear={order.cardExpYear}
variant="secondary" variant="primary"
/> />
</div> </div>
<InfoRow
label={t("loanOrders.fields.cardNumber", "Kart belgisi")}
value={order.cardNumber}
/>
<InfoRow
label={t("loanOrders.fields.cardName", "Kartdaky ady")}
value={order.cardName}
/>
</BentoCard>
{/* Guarantor card — shown side-by-side with main card when both exist */}
{hasGuarantor && (
<BentoCard title={t("loanOrders.sections.guarantor", "1. Zamun")} noPadding>
<InfoRow
label={t("loanOrders.fields.guarantorName", "Zamunyň doly ady")}
value={`${order.guarantor1Name || ""} ${order.guarantor1Surname || ""} ${order.guarantor1Patronic || ""}`.trim()}
/>
<InfoRow
label={t("loanOrders.fields.guarantorPassport", "Pasport")}
value={`${order.guarantor1PassportSerie || ""} ${order.guarantor1PassportNumber || ""}`.trim()}
/>
<InfoRow
label={t("loanOrders.fields.guarantorSalary", "Ortaca zähmet haky")}
value={order.guarantor1Salary ? String(order.guarantor1Salary) : undefined}
/>
{order.guarantor1CardNumber && (
<div className="p-6 bg-slate-50 dark:bg-slate-900/50 border-t border-border flex items-center justify-center">
<CreditCardVisual
cardNumber={order.guarantor1CardNumber}
cardName={order.guarantor1CardName}
expMonth={order.guarantor1CardExpMonth}
expYear={order.guarantor1CardExpYear}
variant="secondary"
/>
</div>
)}
</BentoCard>
)} )}
</Section> </BentoGrid>
)} )}
{/* ── Audit Log ──────────────────────────────────────────────────────── */} {/* ── Row 3: Personal + Contacts ──────────────────────────────────── */}
<div className="mb-6"> <BentoGrid cols={2}>
<details open> <BentoCard title={t("loanOrders.sections.personal", "Şahsy maglumatlar")}>
<summary className="text-base font-semibold text-foreground mb-2 cursor-pointer select-none list-none flex items-center gap-1.5 w-fit"> <InfoRow
{t("loanOrders.sections.audit", "Ammallar")} label={t("loanOrders.fields.fullName", "Doly ady")}
<ChevronRight size={15} className="text-muted-foreground" /> value={`${order.firstName} ${order.lastName} ${order.patronicName || ""}`.trim()}
</summary> />
<div className="bg-card border border-border rounded-xl overflow-hidden mt-2"> <InfoRow
<div className="overflow-x-auto"> label={t("loanOrders.fields.education", "Bilimi")}
<table className="w-full text-sm"> value={order.education ?? undefined}
<thead> />
<tr className="border-b border-border bg-muted/30"> <InfoRow
{[ label={t("loanOrders.fields.maritalStatus", "Maşgala ýagdaýy")}
"ID", value={order.marriageStatus ?? undefined}
t("audit.columns.action", "AMALYŇ ADY"), />
t("audit.columns.by", "KIM TARAPYNDAN"), <InfoRow
t("audit.columns.target", "AMALYŇ NYŞANY (TARIBESI)"), label={t("loanOrders.fields.birthDate", "Doglan güni")}
t("audit.columns.status", "AMALYŇ STATUSY"), value={order.dateOfBirth ?? undefined}
t("audit.columns.date", "SENE"), />
"", <InfoRow
].map((col, i) => ( label={t("loanOrders.fields.registeredAddress", "Ýazgy edilen salgy")}
<th value={order.residence ?? undefined}
key={i} />
className="px-4 py-2.5 text-left text-xs font-medium text-muted-foreground uppercase tracking-wide whitespace-nowrap" <InfoRow
> label={t("loanOrders.fields.currentAddress", "Häzirki ýaşaýyş ýeri")}
{col} value={order.currentResidence ?? undefined}
</th> />
))} <InfoRow
</tr> label={t("loanOrders.fields.loanHistory", "Karz taryhy")}
</thead> value={order.loanHistory ?? undefined}
<tbody> isLink
{auditLogs.map((log) => ( />
<AuditRow key={log.id} {...log} /> </BentoCard>
))}
</tbody> <BentoCard title={t("loanOrders.sections.contacts", "Habarlaşmak")}>
</table> <InfoRow
</div> label={t("loanOrders.fields.email", "E-poçta")}
<div className="flex items-center justify-between px-4 py-2.5 border-t border-border text-xs text-muted-foreground"> value={order.email ?? undefined}
<span>{t("common.prev", "Öňki")}</span> />
<span> <InfoRow
1–{auditLogs.length} / {auditLogs.length} label={t("loanOrders.columns.phone", "Telefon")}
</span> value={order.phone}
<span>{t("common.next", "Soňky")}</span> />
</div> <InfoRow
</div> label={t("loanOrders.fields.phoneAlt", "Telefon goşmaça")}
</details> value={order.phoneAdditional ?? undefined}
</div> />
<InfoRow
label={t("loanOrders.fields.homePhone", "Öý telefony")}
value={order.homePhone ?? undefined}
/>
</BentoCard>
</BentoGrid>
{/* ── Row 4: Employment + Passport info ───────────────────────────── */}
<BentoGrid cols={2}>
<BentoCard title={t("loanOrders.sections.employment", "Iş")}>
<InfoRow
label={t("loanOrders.fields.employer", "Kärhananyň ady")}
value={order.workCompany ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.deptPhone", "Işgärler bölüminiň belgisi")}
value={order.workHrPhone ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.workRegion", "Işleýän welaýaty")}
value={order.workRegion ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.workCity", "Işleýän etraby")}
value={order.workProvince ?? undefined}
isLink
/>
<InfoRow
label={t("loanOrders.fields.position", "Wezipe")}
value={order.position ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.salary", "Zähmet haky")}
value={order.salary ? String(order.salary) : undefined}
/>
<InfoRow
label={t("loanOrders.fields.employedSince", "Işe başlan wagty")}
value={order.workStartedAt ?? undefined}
/>
</BentoCard>
<BentoCard title={t("loanOrders.sections.passport", "Pasport")}>
<InfoRow
label={t("loanOrders.fields.passportNumber", "Pasport")}
value={order.passportNumber ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.passportIssuedBy", "Kim tarapyndan berildi")}
value={order.passportGivenBy ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.passportBirthPlace", "Doglan ýeri (pasport)")}
value={order.bornPlace ?? undefined}
/>
</BentoCard>
</BentoGrid>
{/* ── Row 5: Passport images ───────────────────────────────────────── */}
<BentoGrid cols={4}>
<BentoCard title={t("loanOrders.fields.passportPage1", "Sahypa 1")}>
<PassportImage
label={t("loanOrders.fields.passportPage1", "Pasport (sahypa 1)")}
src={order.passportPage1Url ?? undefined}
/>
</BentoCard>
<BentoCard title={t("loanOrders.fields.passportPage23", "Sahypa 2-3")}>
<PassportImage
label={t("loanOrders.fields.passportPage23", "Pasport (2-3-nji sahypa)")}
src={order.passportPage23Url ?? undefined}
/>
</BentoCard>
<BentoCard title={t("loanOrders.fields.passportPage89", "Sahypa 8-9")}>
<PassportImage
label={t("loanOrders.fields.passportPage89", "Pasport (8-9 sahypa)")}
src={order.passportPage89Url ?? undefined}
/>
</BentoCard>
<BentoCard title={t("loanOrders.fields.passportPage32", "Sahypa 32")}>
<PassportImage
label={t("loanOrders.fields.passportPage32", "Pasport (32-nji sahypa)")}
src={order.passportPage32Url ?? undefined}
/>
</BentoCard>
</BentoGrid>
{/* ── Guarantor (standalone — only when no card to pair with) ─────── */}
{hasGuarantor && !hasCard && (
<BentoGrid cols={2}>
<BentoCard title={t("loanOrders.sections.guarantor", "1. Zamun")}>
<InfoRow
label={t("loanOrders.fields.guarantorName", "Zamunyň doly ady")}
value={`${order.guarantor1Name || ""} ${order.guarantor1Surname || ""} ${order.guarantor1Patronic || ""}`.trim()}
/>
<InfoRow
label={t("loanOrders.fields.guarantorPassport", "Pasport")}
value={`${order.guarantor1PassportSerie || ""} ${order.guarantor1PassportNumber || ""}`.trim()}
/>
<InfoRow
label={t("loanOrders.fields.guarantorSalary", "Ortaca zähmet haky")}
value={order.guarantor1Salary ? String(order.guarantor1Salary) : undefined}
/>
{order.guarantor1CardNumber && (
<div className="p-6 bg-slate-50 dark:bg-slate-900/50 border-t border-border flex items-center justify-center">
<CreditCardVisual
cardNumber={order.guarantor1CardNumber}
cardName={order.guarantor1CardName}
expMonth={order.guarantor1CardExpMonth}
expYear={order.guarantor1CardExpYear}
variant="secondary"
/>
</div>
)}
</BentoCard>
</BentoGrid>
)}
{/* ── Audit log ────────────────────────────────────────────────────── */}
<AuditLog logs={auditLogs} />
</div> </div>
); )
} }
+264 -305
View File
@@ -1,6 +1,6 @@
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Trash2, Pencil, ChevronRight } from "lucide-react"; import { Trash2, Pencil } from "lucide-react";
import { import {
useLoanOrderById, useLoanOrderById,
useDeleteLoanOrder, useDeleteLoanOrder,
@@ -15,50 +15,64 @@ import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
import type { LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi"; import type { LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi";
import { import {
InfoRow, InfoRow,
Section,
PassportImage, PassportImage,
AuditLog,
type AuditRowProps,
} from "@/components/viewPageComponents"; } from "@/components/viewPageComponents";
import { AuditRow, type AuditRowProps } from "@/components/viewPageComponents";
// ─── Status config ────────────────────────────────────────────────────────────
const STATUS_CONFIG = { const STATUS_CONFIG = {
GARAŞYLÝAR: { GARAŞYLÝAR: { label: "Garaşylýar", variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
label: "Garaşylýar", KANAGATLANDYRYLAN: { label: "Tassyklandy", variant: "success" as StatusBadgeVariant, icon: CheckCircle2 },
variant: "warning" as StatusBadgeVariant, RED_EDILDI: { label: "Ýatyryldy", variant: "error" as StatusBadgeVariant, icon: XCircle },
icon: AlertCircle, IŞLENÝÄR: { label: "Işlenýär", variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
}, } satisfies Record<LoanOrderMobileStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }>
KANAGATLANDYRYLAN: {
label: "Tassyklandy",
variant: "success" as StatusBadgeVariant,
icon: CheckCircle2,
},
RED_EDILDI: {
label: "Ýatyryldy",
variant: "error" as StatusBadgeVariant,
icon: XCircle,
},
IŞLENÝÄR: {
label: "Işlenýär",
variant: "warning" as StatusBadgeVariant,
icon: AlertCircle,
},
} satisfies Record<
LoanOrderMobileStatus,
{ label: string; variant: StatusBadgeVariant; icon: React.ElementType }
>;
function LoanOrderMobileStatusBadge({ function LoanOrderMobileStatusBadge({ status }: { status: LoanOrderMobileStatus }) {
status, const cfg = STATUS_CONFIG[status]
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />
}
// ─── Bento primitives ─────────────────────────────────────────────────────────
function BentoGrid({ cols = 2, children }: { cols?: 1 | 2 | 3 | 4; children: React.ReactNode }) {
const colClass = {
1: "grid-cols-1",
2: "grid-cols-1 sm:grid-cols-2",
3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",
}[cols]
return <div className={`grid ${colClass} gap-4`}>{children}</div>
}
function BentoCard({
title,
span,
children,
}: { }: {
status: LoanOrderMobileStatus; title?: string
span?: "full" | 2 | 3
children: React.ReactNode
}) { }) {
const cfg = STATUS_CONFIG[status]; const spanClass =
if (!cfg) span === "full" ? "sm:col-span-full" :
return ( span === 2 ? "sm:col-span-2" :
<span className="text-xs text-muted-foreground">{String(status)}</span> span === 3 ? "sm:col-span-3" : ""
);
return ( return (
<StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} /> <div className={`bg-card border border-border rounded-xl overflow-hidden ${spanClass}`}>
); {title && (
<div className="px-4 py-2.5 border-b border-border">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
{title}
</p>
</div>
)}
{children}
</div>
)
} }
// ─── Skeleton ───────────────────────────────────────────────────────────────── // ─── Skeleton ─────────────────────────────────────────────────────────────────
@@ -67,73 +81,69 @@ function LoanOrderViewSkeleton() {
return ( return (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<Skeleton className="h-7 w-64" /> <Skeleton className="h-7 w-64" />
{[...Array(5)].map((_, i) => ( <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div {[...Array(6)].map((_, i) => (
key={i} <div key={i} className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3">
className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3" <Skeleton className="h-3 w-24 mb-1" />
> {[...Array(3)].map((_, j) => (
<Skeleton className="h-4 w-32 mb-1" /> <Skeleton key={j} className="h-4 w-full" />
{[...Array(3)].map((_, j) => ( ))}
<Skeleton key={j} className="h-4 w-full" /> </div>
))} ))}
</div> </div>
))}
</div> </div>
); )
} }
// ─── Page ───────────────────────────────────────────────────────────────────── // ─── Page ─────────────────────────────────────────────────────────────────────
export default function LoanOrderViewPage() { export default function LoanOrderViewPage() {
const { t } = useTranslation(); const { t } = useTranslation()
const navigate = useNavigate(); const navigate = useNavigate()
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>()
const deleteMutation = useDeleteLoanOrder(); const deleteMutation = useDeleteLoanOrder()
const { data: order, isLoading } = useLoanOrderById(id!); const { data: order, isLoading } = useLoanOrderById(id!)
const handleDelete = () => { const handleDelete = () => {
if (!window.confirm(t("loanOrders.deleteConfirm", "Bu sargyt pozulsynmy?"))) if (!window.confirm(t("loanOrders.deleteConfirm", "Bu sargyt pozulsynmy?"))) return
return;
deleteMutation.mutate(id!, { deleteMutation.mutate(id!, {
onSuccess: () => { onSuccess: () => {
toast.success(t("loanOrders.deleteSuccess", "Sargyt pozuldy")); toast.success(t("loanOrders.deleteSuccess", "Sargyt pozuldy"))
navigate("/loan-orders"); navigate("/loan-orders")
}, },
onError: () => { onError: () => {
toast.error( toast.error(t("loanOrders.deleteError", "Pozma wagty ýalňyşlyk ýüze çykdy"))
t("loanOrders.deleteError", "Pozma wagty ýalňyşlyk ýüze çykdy"),
);
}, },
}); })
}; }
if (isLoading) return <LoanOrderViewSkeleton />; if (isLoading) return <LoanOrderViewSkeleton />
if (!order) { if (!order) {
return ( return (
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm"> <div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
{t("common.notFound", "Tapylmady")} {t("common.notFound", "Tapylmady")}
</div> </div>
); )
} }
// Replace with real audit data from API when available
const auditLogs: AuditRowProps[] = [ const auditLogs: AuditRowProps[] = [
{ {
id: "44548", id: "44548",
action: t("audit.actions.view", "Görmek"), action: t("audit.actions.view", "Görmek"),
by: order.createdBy ?? "", by: order.createdBy ?? "",
target: `${t("loanOrders.title", "Karz sargyt")}: ${order.id}`, target: `${t("loanOrders.title", "Karz sargyt")}: ${order.id}`,
status: "FINISHED", status: "FINISHED",
date: order.createdAt ?? "", date: order.createdAt ?? "",
}, },
]; ]
return ( return (
<div className="flex flex-col"> <div className="flex flex-col gap-6">
{/* Page Header */}
<div className="flex items-center justify-between mb-5"> {/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground"> <h1 className="text-xl font-semibold text-foreground">
{t("loanOrders.view.title", "Karz sargyt giriş")}: {order.id} {t("loanOrders.view.title", "Karz sargyt giriş")}: {order.id}
</h1> </h1>
@@ -156,243 +166,192 @@ export default function LoanOrderViewPage() {
</div> </div>
</div> </div>
{/* ── Basic Info ─────────────────────────────────────────────────────── */} {/* ── Row 1: Meta + Loan + Location ───────────────────────────────── */}
<div className="bg-card border border-border rounded-xl overflow-hidden mb-6"> <BentoGrid cols={3}>
<InfoRow label="ID" value={order.id} /> {/* Meta */}
<InfoRow <BentoCard title={t("loanOrders.sections.meta", "Esasy maglumatlar")}>
label={t("loanOrders.columns.createdAt", "Döredilen wagty")} <InfoRow label="ID" value={order.id} />
value={order.createdAt} <InfoRow
/> label={t("loanOrders.columns.createdAt", "Döredilen wagty")}
{/* Status row — special render */} value={order.createdAt}
<div className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4 border-b border-border"> />
<span className="text-sm text-muted-foreground"> <InfoRow
{t("loanOrders.columns.status", "Status")} label={t("loanOrders.columns.status", "Status")}
</span> >
<LoanOrderMobileStatusBadge status={order.status} /> <LoanOrderMobileStatusBadge status={order.status} />
</div> </InfoRow>
<InfoRow <InfoRow
label={t("loanOrders.fields.amount", "Berlik")} label={t("loanOrders.fields.amount", "Berlik")}
value={order.amount ? String(order.amount) : undefined} value={order.amount ? String(order.amount) : undefined}
/> />
<InfoRow <InfoRow
label={t("loanOrders.fields.createdBy", "Sargyt eden")} label={t("loanOrders.fields.createdBy", "Sargyt eden")}
value={order.createdBy ?? undefined} value={order.createdBy ?? undefined}
isLink isLink
/> />
</div> </BentoCard>
{/* ── Loan ───────────────────────────────────────────────────────────── */} {/* Loan */}
<Section title={t("loanOrders.sections.loan", "Karz")}> <BentoCard title={t("loanOrders.sections.loan", "Karz")}>
<InfoRow <InfoRow
label={t("loanOrders.columns.loanType", "Karz görnüşi")} label={t("loanOrders.columns.loanType", "Karz görnüşi")}
value={order.loanType} value={order.loanType}
isLink isLink
/> />
<InfoRow <InfoRow
label={t("loanOrders.fields.loanAmount", "Karz mukdary")} label={t("loanOrders.fields.loanAmount", "Karz mukdary")}
value={order.loanAmount ? String(order.loanAmount) : undefined} value={order.loanAmount ? String(order.loanAmount) : undefined}
/> />
</Section> </BentoCard>
{/* ── Location ───────────────────────────────────────────────────────── */} {/* Location */}
<Section title={t("loanOrders.sections.location", "Lokasiýa")}> <BentoCard title={t("loanOrders.sections.location", "Lokasiýa")}>
<InfoRow <InfoRow
label={t("loanOrders.columns.region", "Welaýat")} label={t("loanOrders.columns.region", "Welaýat")}
value={order.region} value={order.region}
/> />
<InfoRow <InfoRow
label={t("loanOrders.columns.branch", "Şahamça")} label={t("loanOrders.columns.branch", "Şahamça")}
value={order.branch} value={order.branch}
isLink isLink
/> />
</Section> </BentoCard>
</BentoGrid>
{/* ── Personal Info ──────────────────────────────────────────────────── */} {/* ── Row 2: Personal + Contacts ──────────────────────────────────── */}
<Section title={t("loanOrders.sections.personal", "Şahsy maglumatlar")}> <BentoGrid cols={2}>
<InfoRow {/* Personal */}
label={t("loanOrders.fields.fullName", "Doly ady")} <BentoCard title={t("loanOrders.sections.personal", "Şahsy maglumatlar")}>
value={order.fullName ?? `${order.firstName} ${order.lastName}`} <InfoRow
/> label={t("loanOrders.fields.fullName", "Doly ady")}
<InfoRow value={order.fullName ?? `${order.firstName} ${order.lastName}`}
label={t("loanOrders.fields.education", "Bilimi")} />
value={order.education ?? undefined} <InfoRow
/> label={t("loanOrders.fields.education", "Bilimi")}
<InfoRow value={order.education ?? undefined}
label={t("loanOrders.fields.maritalStatus", "Maşgala ýagdaýy")} />
value={order.maritalStatus ?? undefined} <InfoRow
/> label={t("loanOrders.fields.maritalStatus", "Maşgala ýagdaýy")}
<InfoRow value={order.maritalStatus ?? undefined}
label={t("loanOrders.fields.birthDate", "Doglan güni")} />
value={order.birthDate ?? undefined} <InfoRow
/> label={t("loanOrders.fields.birthDate", "Doglan güni")}
<InfoRow value={order.birthDate ?? undefined}
label={t( />
"loanOrders.fields.registeredAddress", <InfoRow
"Ýazgy edilen salgyňyz", label={t("loanOrders.fields.registeredAddress", "Ýazgy edilen salgy")}
)} value={order.registeredAddress ?? undefined}
value={order.registeredAddress ?? undefined} />
/> <InfoRow
<InfoRow label={t("loanOrders.fields.currentAddress", "Häzirki ýaşaýyş ýeri")}
label={t("loanOrders.fields.currentAddress", "Häzirki ýaşaýyş ýeri")} value={order.currentAddress ?? undefined}
value={order.currentAddress ?? undefined} />
/> </BentoCard>
</Section>
{/* ── Contacts ───────────────────────────────────────────────────────── */} {/* Contacts */}
<Section <BentoCard title={t("loanOrders.sections.contacts", "Habarlaşmak")}>
title={t( <InfoRow
"loanOrders.sections.contacts", label={t("loanOrders.fields.email", "E-poçta")}
"Habarlaşmak üçin maglumatlar", value={order.email ?? undefined}
)} />
> <InfoRow
<InfoRow label={t("loanOrders.columns.phone", "Telefon")}
label={t("loanOrders.fields.email", "E-poçta")} value={order.phone}
value={order.email ?? undefined} />
/> <InfoRow
<InfoRow label={t("loanOrders.fields.phoneAlt", "Telefon goşmaça")}
label={t("loanOrders.columns.phone", "Telefon")} value={order.phoneAlt ?? undefined}
value={order.phone} />
/> <InfoRow
<InfoRow label={t("loanOrders.fields.homePhone", "Öý telefony")}
label={t("loanOrders.fields.phoneAlt", "Telefon goşmaça")} value={order.homePhone ?? undefined}
value={order.phoneAlt ?? undefined} />
/> </BentoCard>
<InfoRow </BentoGrid>
label={t("loanOrders.fields.homePhone", "Öý telefony")}
value={order.homePhone ?? undefined}
/>
</Section>
{/* ── Employment ─────────────────────────────────────────────────────── */} {/* ── Row 3: Employment + Passport info ───────────────────────────── */}
<Section title={t("loanOrders.sections.employment", "Iş")}> <BentoGrid cols={2}>
<InfoRow {/* Employment */}
label={t( <BentoCard title={t("loanOrders.sections.employment", "Iş")}>
"loanOrders.fields.employer", <InfoRow
"Işleýän edaranyň/kärhananyn ady", label={t("loanOrders.fields.employer", "Kärhananyň ady")}
)} value={order.employer ?? undefined}
value={order.employer ?? undefined} />
/> <InfoRow
<InfoRow label={t("loanOrders.fields.deptPhone", "Işgärler bölüminiň belgisi")}
label={t( value={order.deptPhone ?? undefined}
"loanOrders.fields.deptPhone", />
"Işgärler bölüminiň iş belgisi", <InfoRow
)} label={t("loanOrders.fields.workRegion", "Işleýän welaýaty")}
value={order.deptPhone ?? undefined} value={order.workRegion ?? undefined}
/> />
<InfoRow <InfoRow
label={t("loanOrders.fields.workRegion", "Işleýän welaýatyňyz")} label={t("loanOrders.fields.workCity", "Işleýän etraby")}
value={order.workRegion ?? undefined} value={order.workCity ?? undefined}
/> isLink
<InfoRow />
label={t("loanOrders.fields.workCity", "Işleýän etrabyňyz")} <InfoRow
value={order.workCity ?? undefined} label={t("loanOrders.fields.position", "Wezipe")}
isLink value={order.position ?? undefined}
/> />
<InfoRow <InfoRow
label={t("loanOrders.fields.position", "Wezipe")} label={t("loanOrders.fields.salary", "Zähmet haky")}
value={order.position ?? undefined} value={order.salary ? String(order.salary) : undefined}
/> />
<InfoRow <InfoRow
label={t("loanOrders.fields.salary", "Zähmet haky")} label={t("loanOrders.fields.employedSince", "Işe başlan wagty")}
value={order.salary ? String(order.salary) : undefined} value={order.employedSince ?? undefined}
/> />
<InfoRow </BentoCard>
label={t("loanOrders.fields.employedSince", "Işe başlan wagtyňyz")}
value={order.employedSince ?? undefined}
/>
</Section>
{/* ── Passport ───────────────────────────────────────────────────────── */} {/* Passport info */}
<Section title={t("loanOrders.sections.passport", "Pasport")}> <BentoCard title={t("loanOrders.sections.passport", "Pasport")}>
<InfoRow <InfoRow
label={t("loanOrders.fields.passportNumber", "Pasport")} label={t("loanOrders.fields.passportNumber", "Pasport")}
value={order.passportNumber ?? undefined} value={order.passportNumber ?? undefined}
/> />
<InfoRow <InfoRow
label={t( label={t("loanOrders.fields.passportIssuedBy", "Kim tarapyndan berildi")}
"loanOrders.fields.passportIssuedBy", value={order.passportIssuedBy ?? undefined}
"Kim tarapyndan berildi", />
)} <InfoRow
value={order.passportIssuedBy ?? undefined} label={t("loanOrders.fields.passportBirthPlace", "Doglan ýeri (pasport)")}
/> value={order.passportBirthPlace ?? undefined}
<InfoRow />
label={t( </BentoCard>
"loanOrders.fields.passportBirthPlace", </BentoGrid>
"Doglan ýeri (pasport)",
)} {/* ── Row 4: Passport images ───────────────────────────────────────── */}
value={order.passportBirthPlace ?? undefined} <BentoGrid cols={4}>
/> <BentoCard title={t("loanOrders.fields.passportPage1", "Sahypa 1")}>
<PassportImage <PassportImage
label={t("loanOrders.fields.passportPage1", "Pasport (sahypa 1)")} label={t("loanOrders.fields.passportPage1", "Pasport (sahypa 1)")}
src={order.passportPage1Url ?? undefined} src={order.passportPage1Url ?? undefined}
/> />
<PassportImage </BentoCard>
label={t( <BentoCard title={t("loanOrders.fields.passportPage23", "Sahypa 2-3")}>
"loanOrders.fields.passportPage23", <PassportImage
"Pasport (2-3-nji sahypa)", label={t("loanOrders.fields.passportPage23", "Pasport (2-3-nji sahypa)")}
)} src={order.passportPage23Url ?? undefined}
src={order.passportPage23Url ?? undefined} />
/> </BentoCard>
<PassportImage <BentoCard title={t("loanOrders.fields.passportPage89", "Sahypa 8-9")}>
label={t("loanOrders.fields.passportPage89", "Pasport (8-9 sahypa)")} <PassportImage
src={order.passportPage89Url ?? undefined} label={t("loanOrders.fields.passportPage89", "Pasport (8-9 sahypa)")}
/> src={order.passportPage89Url ?? undefined}
<PassportImage />
label={t( </BentoCard>
"loanOrders.fields.passportPage32", <BentoCard title={t("loanOrders.fields.passportPage32", "Sahypa 32")}>
"Pasport (32-nji sahypa)", <PassportImage
)} label={t("loanOrders.fields.passportPage32", "Pasport (32-nji sahypa)")}
src={order.passportPage32Url ?? undefined} src={order.passportPage32Url ?? undefined}
/> />
</Section> </BentoCard>
</BentoGrid>
{/* ── Audit log ────────────────────────────────────────────────────── */}
<AuditLog logs={auditLogs} />
{/* ── Audit Log ──────────────────────────────────────────────────────── */}
<div className="mb-6">
<details open>
<summary className="text-base font-semibold text-foreground mb-2 cursor-pointer select-none list-none flex items-center gap-1.5 w-fit">
{t("loanOrders.sections.audit", "Ammallar")}
<ChevronRight size={15} className="text-muted-foreground" />
</summary>
<div className="bg-card border border-border rounded-xl overflow-hidden mt-2">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border bg-muted/30">
{[
"ID",
t("audit.columns.action", "AMALYŇ ADY"),
t("audit.columns.by", "KIM TARAPYNDAN"),
t("audit.columns.target", "AMALYŇ NYŞANY (TARIBESI)"),
t("audit.columns.status", "AMALYŇ STATUSY"),
t("audit.columns.date", "SENE"),
"",
].map((col, i) => (
<th
key={i}
className="px-4 py-2.5 text-left text-xs font-medium text-muted-foreground uppercase tracking-wide whitespace-nowrap"
>
{col}
</th>
))}
</tr>
</thead>
<tbody>
{auditLogs.map((log) => (
<AuditRow key={log.id} {...log} />
))}
</tbody>
</table>
</div>
<div className="flex items-center justify-between px-4 py-2.5 border-t border-border text-xs text-muted-foreground">
<span>{t("common.prev", "Öňki")}</span>
<span>
1–{auditLogs.length} / {auditLogs.length}
</span>
<span>{t("common.next", "Soňky")}</span>
</div>
</div>
</details>
</div>
</div> </div>
); )
} }
@@ -163,6 +163,8 @@ export default function OnlinePaymentHistoryPage() {
<h1 className="text-2xl font-semibold text-foreground mb-5"> <h1 className="text-2xl font-semibold text-foreground mb-5">
{t("onlinePayments.title", "Onlaýn töleg taryhy")} {t("onlinePayments.title", "Onlaýn töleg taryhy")}
</h1> </h1>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -191,6 +193,7 @@ export default function OnlinePaymentHistoryPage() {
totalCount={data?.total ?? 0} totalCount={data?.total ?? 0}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
</div> </div>
); );
} }
@@ -172,6 +172,7 @@ export function CardTypesListPage() {
</h1> </h1>
</div> </div>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
@@ -209,6 +210,7 @@ export function CardTypesListPage() {
totalCount={data?.total} totalCount={data?.total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
{/* Delete dialog */} {/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}> <AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
@@ -180,6 +180,7 @@ export function CardReasonsListPage() {
</h1> </h1>
</div> </div>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
@@ -217,6 +218,7 @@ export function CardReasonsListPage() {
totalCount={data?.total} totalCount={data?.total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
{/* Delete dialog */} {/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}> <AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
@@ -161,6 +161,7 @@ export default function LoanTypesListPage() {
<h1 className="text-xl font-semibold text-foreground mb-5"> <h1 className="text-xl font-semibold text-foreground mb-5">
{t('loanTypes.title', 'Karz görnüşleri')} {t('loanTypes.title', 'Karz görnüşleri')}
</h1> </h1>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -190,6 +191,7 @@ export default function LoanTypesListPage() {
totalCount={data?.total} totalCount={data?.total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
{/* Delete confirmation dialog */} {/* Delete confirmation dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}> <AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
@@ -102,6 +102,7 @@ export default function RequiredDocumentsListPage() {
<h1 className="text-xl font-semibold text-foreground mb-4"> <h1 className="text-xl font-semibold text-foreground mb-4">
{t('loanDocuments.title', 'Karz gerekli resminamalary')} {t('loanDocuments.title', 'Karz gerekli resminamalary')}
</h1> </h1>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
@@ -134,5 +135,6 @@ export default function RequiredDocumentsListPage() {
onPageChange={setPage} onPageChange={setPage}
/> />
</div> </div>
</div>
) )
} }
@@ -195,6 +195,7 @@ export function BranchesListPage() {
</h1> </h1>
</div> </div>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -230,6 +231,7 @@ export function BranchesListPage() {
totalCount={data?.total} totalCount={data?.total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}> <AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
<AlertDialogContent> <AlertDialogContent>
@@ -163,6 +163,7 @@ export function DistrictsListPage() {
</h1> </h1>
</div> </div>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -198,6 +199,7 @@ export function DistrictsListPage() {
totalCount={data?.total} totalCount={data?.total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}> <AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
<AlertDialogContent> <AlertDialogContent>
@@ -123,10 +123,9 @@ export default function PermissionsPage() {
<h1 className="text-2xl font-bold text-foreground"> <h1 className="text-2xl font-bold text-foreground">
{t('permissions.title', 'Rugsatlar')} {t('permissions.title', 'Rugsatlar')}
</h1> </h1>
<Button onClick={() => navigate('/settings/users/permissions/create')}>
{t('permissions.actions.create', 'Rugsat dörediň')}
</Button>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
@@ -141,6 +140,8 @@ export default function PermissionsPage() {
perPageOptions={[10, 25, 50, 100]} perPageOptions={[10, 25, 50, 100]}
perPage={perPage} perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }} onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('permissions.actions.create', 'Rugsat dörediň')}
onAction={() => navigate('/settings/users/permissions/create')}
/> />
{/* Table */} {/* Table */}
@@ -158,6 +159,7 @@ export default function PermissionsPage() {
totalCount={data?.meta?.total ?? 0} totalCount={data?.meta?.total ?? 0}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
{/* Delete confirmation dialog */} {/* Delete confirmation dialog */}
<AlertDialog <AlertDialog
+5 -4
View File
@@ -123,10 +123,9 @@ export default function RolesPage() {
<h1 className="text-2xl font-bold text-foreground"> <h1 className="text-2xl font-bold text-foreground">
{t('roles.title', 'Rollar')} {t('roles.title', 'Rollar')}
</h1> </h1>
<Button onClick={() => navigate('/settings/users/roles/create')}>
{t('roles.actions.create', 'Rol dörediň')}
</Button>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
@@ -141,6 +140,8 @@ export default function RolesPage() {
perPageOptions={[10, 25, 50, 100]} perPageOptions={[10, 25, 50, 100]}
perPage={perPage} perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }} onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('roles.actions.create', 'Rol dörediň')}
onAction={() => navigate('/settings/users/roles/create')}
/> />
{/* Table */} {/* Table */}
@@ -158,7 +159,7 @@ export default function RolesPage() {
totalCount={data?.meta?.total ?? 0} totalCount={data?.meta?.total ?? 0}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
{/* Delete confirmation dialog */} {/* Delete confirmation dialog */}
<AlertDialog <AlertDialog
open={deleteId !== null} open={deleteId !== null}
+8 -2
View File
@@ -190,8 +190,13 @@ export default function UsersListPage() {
// ── Render ───────────────────────────────────────────────────────────────── // ── Render ─────────────────────────────────────────────────────────────────
return ( return (
<div className="p-6 space-y-4"> <div className="p-6 space-y-4">
<div className="mb-6">
<h1 className="text-2xl font-semibold text-foreground">
{t('clients.title', 'Ahli Müşderiler')}
</h1>
</div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -238,6 +243,7 @@ export default function UsersListPage() {
totalCount={data?.total} totalCount={data?.total}
onPageChange={setPage} onPageChange={setPage}
/> />
</div>
{/* Delete confirm dialog */} {/* Delete confirm dialog */}
<AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}> <AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>
+2
View File
@@ -146,6 +146,7 @@ export default function ClientsPage() {
{t('clients.title', 'Müşderiler')} {t('clients.title', 'Müşderiler')}
</h1> </h1>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar <DataTableToolbar
searchValue={search} searchValue={search}
@@ -194,6 +195,7 @@ export default function ClientsPage() {
onPageChange={setPage} onPageChange={setPage}
enableRowSelection enableRowSelection
/> />
</div>
<AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}> <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
<AlertDialogContent> <AlertDialogContent>
+297 -109
View File
@@ -13,27 +13,158 @@ import {
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from '@/components/ui/alert-dialog' } from '@/components/ui/alert-dialog'
import { Section, InfoRow, AuditLog } from '@/components/viewPageComponents' import { InfoRow, AuditLog } from '@/components/viewPageComponents'
import { DataTable, type ColumnDef } from '@/components/dataTable' import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar' import { DataTableToolbar } from '@/components/dataTableToolbar'
import { useClient, useDeleteClient } from '@/features/clients/hooks/useClients' import { useClient, useDeleteClient } from '@/features/clients/hooks/useClients'
import type { ClientRole, ClientBranch, ClientAuditLog } from '@/features/clients/api/clientsApi' import type { ClientRole, ClientBranch, ClientAuditLog } from '@/features/clients/api/clientsApi'
// ─── Bento primitives ─────────────────────────────────────────────────────────
function BentoGrid({ cols = 2, children }: { cols?: 1 | 2 | 3 | 4; children: React.ReactNode }) {
const colClass = {
1: 'grid-cols-1',
2: 'grid-cols-1 sm:grid-cols-2',
3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3',
4: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4',
}[cols]
return <div className={`grid ${colClass} gap-4`}>{children}</div>
}
function BentoCard({
title,
span,
children,
}: {
title?: string
span?: 'full' | 2 | 3
children: React.ReactNode
}) {
const spanClass =
span === 'full' ? 'sm:col-span-full' :
span === 2 ? 'sm:col-span-2' :
span === 3 ? 'sm:col-span-3' : ''
return (
<div className={`bg-card border border-border rounded-xl overflow-hidden ${spanClass}`}>
{title && (
<div className="px-4 py-2.5 border-b border-border">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
{title}
</p>
</div>
)}
{children}
</div>
)
}
// ─── ActiveIndicator ──────────────────────────────────────────────────────────
function ActiveIndicator({ active }: { active: boolean }) {
return active ? (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
)
}
// ─── CollapsibleSection ───────────────────────────────────────────────────────
interface CollapsibleSectionProps {
title: string
actionLabel: string
onAction: () => void
children: React.ReactNode
}
function CollapsibleSection({ title, actionLabel, onAction, children }: CollapsibleSectionProps) {
const [open, setOpen] = useState(true)
return (
<div>
<div
className="flex items-center gap-2 mb-2 cursor-pointer select-none w-fit"
onClick={() => setOpen((v) => !v)}
>
<h2 className="text-base font-semibold text-foreground">{title}</h2>
<ChevronDown
size={15}
className={`text-muted-foreground transition-transform duration-200 ${open ? '' : '-rotate-90'}`}
/>
</div>
{open && (
<div className="bg-card border border-border rounded-xl overflow-hidden p-4 space-y-3">
<div className="flex justify-end">
<Button
size="sm"
className="bg-primary hover:bg-primary/90 text-primary-foreground h-8 text-xs"
onClick={onAction}
>
{actionLabel}
</Button>
</div>
{children}
</div>
)}
</div>
)
}
// ─── EmptyState ───────────────────────────────────────────────────────────────
interface EmptyStateProps {
label: string
actionLabel: string
onAction: () => void
}
function EmptyState({ label, actionLabel, onAction }: EmptyStateProps) {
return (
<div className="flex flex-col items-center justify-center py-12 gap-4">
<div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center">
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" className="text-muted-foreground">
<rect x="4" y="8" width="24" height="18" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M4 13h24" stroke="currentColor" strokeWidth="1.5" />
<path d="M10 8V6M22 8V6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
<circle cx="16" cy="20" r="3" stroke="currentColor" strokeWidth="1.5" />
<path d="M19 23l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</div>
<p className="text-sm text-muted-foreground text-center">{label}</p>
<Button size="sm" variant="outline" className="h-8 text-xs" onClick={onAction}>
{actionLabel}
</Button>
</div>
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function ClientDetailPage() { export default function ClientDetailPage() {
const { id } = useParams<{ id: string }>() const { id } = useParams<{ id: string }>()
const clientId = Number(id) const clientId = Number(id)
const { t } = useTranslation() const { t } = useTranslation()
const navigate = useNavigate() const navigate = useNavigate()
const deleteMutation = useDeleteClient() const deleteMutation = useDeleteClient()
const { data: client, isLoading } = useClient(clientId) const { data: client, isLoading } = useClient(clientId)
const [deleteOpen, setDeleteOpen] = useState(false) const [deleteOpen, setDeleteOpen] = useState(false)
const [roleSearch, setRoleSearch] = useState('') const [roleSearch, setRoleSearch] = useState('')
const [permSearch, setPermSearch] = useState('') const [permSearch, setPermSearch] = useState('')
const [branchSearch, setBranchSearch] = useState('') const [branchSearch, setBranchSearch] = useState('')
const [loanSearch, setLoanSearch] = useState('') const [loanSearch, setLoanSearch] = useState('')
const [cardSearch, setCardSearch] = useState('') const [cardSearch, setCardSearch] = useState('')
// ── Role columns ──────────────────────────────────────────────────────────
const roleColumns: ColumnDef<ClientRole>[] = [ const roleColumns: ColumnDef<ClientRole>[] = [
{ {
@@ -71,6 +202,8 @@ export default function ClientDetailPage() {
}, },
] ]
// ── Branch columns ────────────────────────────────────────────────────────
const branchColumns: ColumnDef<ClientBranch>[] = [ const branchColumns: ColumnDef<ClientBranch>[] = [
{ {
accessorKey: 'id', accessorKey: 'id',
@@ -112,6 +245,8 @@ export default function ClientDetailPage() {
}, },
] ]
// ── Loading ───────────────────────────────────────────────────────────────
if (isLoading) { if (isLoading) {
return ( return (
<div className="p-6 space-y-4"> <div className="p-6 space-y-4">
@@ -125,104 +260,195 @@ export default function ClientDetailPage() {
if (!client) return null if (!client) return null
const auditLogs = (client.auditLogs ?? []).map((log: ClientAuditLog) => ({ const auditLogs = (client.auditLogs ?? []).map((log: ClientAuditLog) => ({
id: String(log.id), id: String(log.id),
action: log.actionName, action: log.actionName,
by: log.performedBy, by: log.performedBy,
target: log.target, target: log.target,
status: log.status, status: log.status,
date: log.createdAt, date: log.createdAt,
})) }))
const filteredRoles = (client.roles ?? []).filter((r) => const filteredRoles = (client.roles ?? []).filter((r) =>
r.name.toLowerCase().includes(roleSearch.toLowerCase()) || r.code.toLowerCase().includes(roleSearch.toLowerCase()), r.name.toLowerCase().includes(roleSearch.toLowerCase()) ||
r.code.toLowerCase().includes(roleSearch.toLowerCase()),
) )
const filteredBranches = (client.branches ?? []).filter((b) => const filteredBranches = (client.branches ?? []).filter((b) =>
b.name.toLowerCase().includes(branchSearch.toLowerCase()), b.name.toLowerCase().includes(branchSearch.toLowerCase()),
) )
return ( return (
<div className="p-6"> <div className="p-6 flex flex-col gap-6">
<div className="flex items-center justify-between mb-6"> {/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-center justify-between">
<h1 className="text-2xl font-semibold text-foreground"> <h1 className="text-2xl font-semibold text-foreground">
{t('clients.detailTitle', 'Müşderi giňişleýin')}: {client.name} {t('clients.detailTitle', 'Müşderi giňişleýin')}: {client.name}
</h1> </h1>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button size="icon" variant="ghost" className="h-8 w-8 text-muted-foreground hover:text-destructive" onClick={() => setDeleteOpen(true)}> <Button
size="icon" variant="ghost"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteOpen(true)}
>
<Trash2 size={15} /> <Trash2 size={15} />
</Button> </Button>
<Button size="icon" variant="ghost" className="h-8 w-8 text-muted-foreground hover:text-foreground" onClick={() => navigate(`/clients/${clientId}/edit`)}> <Button
size="icon" variant="ghost"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/clients/${clientId}/edit`)}
>
<Pencil size={15} /> <Pencil size={15} />
</Button> </Button>
</div> </div>
</div> </div>
<Section> {/* ── Row 1: Esasy maglumatlar + Kontakt ──────────────────────────── */}
<InfoRow label="ID" value={client.id} /> <BentoGrid cols={2}>
<InfoRow label={t('clients.fields.username', 'Ulanyjy ady')} value={client.username} /> <BentoCard title={t('clients.sections.basic', 'Esasy maglumatlar')}>
<InfoRow label={t('clients.fields.name', 'Ady')} value={client.name} /> <InfoRow label="ID" value={client.id} />
<InfoRow label={t('clients.fields.phone', 'Telefon')} value={client.phone ?? '—'} /> <InfoRow
<InfoRow label={t('clients.fields.email', 'E-poçta')} value={client.email ?? '—'} /> label={t('clients.fields.username', 'Ulanyjy ady')}
<InfoRow label={t('clients.fields.isActive', 'Işjeň')}> value={client.username}
{client.isActive ? ( />
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary"> <InfoRow
<svg width="12" height="12" viewBox="0 0 12 12" fill="none"> label={t('clients.fields.name', 'Ady')}
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /> value={client.name}
</svg> />
</span> <InfoRow label={t('clients.fields.isActive', 'Işjeň')}>
) : ( <ActiveIndicator active={client.isActive} />
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive"> </InfoRow>
<svg width="12" height="12" viewBox="0 0 12 12" fill="none"> </BentoCard>
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
)}
</InfoRow>
</Section>
<CollapsibleSection title={t('clients.sections.roles', 'Rollar')} actionLabel={t('clients.addRole', 'Rol birikdiriň')} onAction={() => {}}> <BentoCard title={t('clients.sections.contact', 'Kontakt')}>
<DataTableToolbar searchValue={roleSearch} onSearchChange={setRoleSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> <InfoRow
{(filteredRoles.length > 0) ? ( label={t('clients.fields.phone', 'Telefon')}
value={client.phone ?? '—'}
/>
<InfoRow
label={t('clients.fields.email', 'E-poçta')}
value={client.email ?? '—'}
/>
</BentoCard>
</BentoGrid>
{/* ── Rollar ───────────────────────────────────────────────────────── */}
<CollapsibleSection
title={t('clients.sections.roles', 'Rollar')}
actionLabel={t('clients.addRole', 'Rol birikdiriň')}
onAction={() => {}}
>
<DataTableToolbar
searchValue={roleSearch}
onSearchChange={setRoleSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}} hideAction
/>
{filteredRoles.length > 0 ? (
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection /> <DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
) : ( ) : (
<EmptyState label={t('clients.noRoles', 'Berlen kriterýalara Rol gabat gelmedi.')} actionLabel={t('clients.addRole', 'Rol birikdiriň')} onAction={() => {}} /> <EmptyState
label={t('clients.noRoles', 'Berlen kriterýalara Rol gabat gelmedi.')}
actionLabel={t('clients.addRole', 'Rol birikdiriň')}
onAction={() => {}}
/>
)} )}
</CollapsibleSection> </CollapsibleSection>
<CollapsibleSection title={t('clients.sections.permissions', 'Rugsatlar')} actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')} onAction={() => {}}> {/* ── Rugsatlar ────────────────────────────────────────────────────── */}
<DataTableToolbar searchValue={permSearch} onSearchChange={setPermSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> <CollapsibleSection
{(client.permissions ?? []).length === 0 ? ( title={t('clients.sections.permissions', 'Rugsatlar')}
<EmptyState label={t('clients.noPermissions', 'Berlen kriterýalara Rugsat gabat gelmedi.')} actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')} onAction={() => {}} /> actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')}
) : null} onAction={() => {}}
>
<DataTableToolbar
searchValue={permSearch}
onSearchChange={setPermSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}} hideAction
/>
{(client.permissions ?? []).length === 0 && (
<EmptyState
label={t('clients.noPermissions', 'Berlen kriterýalara Rugsat gabat gelmedi.')}
actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')}
onAction={() => {}}
/>
)}
</CollapsibleSection> </CollapsibleSection>
<CollapsibleSection title={t('clients.sections.branches', 'Şahamçalar')} actionLabel={t('clients.addBranch', 'Şahamça birikdiriň')} onAction={() => {}}> {/* ── Şahamçalar ───────────────────────────────────────────────────── */}
<DataTableToolbar searchValue={branchSearch} onSearchChange={setBranchSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> <CollapsibleSection
{(filteredBranches.length > 0) ? ( title={t('clients.sections.branches', 'Şahamçalar')}
actionLabel={t('clients.addBranch', 'Şahamça birikdiriň')}
onAction={() => {}}
>
<DataTableToolbar
searchValue={branchSearch}
onSearchChange={setBranchSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}} hideAction
/>
{filteredBranches.length > 0 ? (
<DataTable columns={branchColumns} data={filteredBranches} getRowId={(r) => String(r.id)} enableRowSelection /> <DataTable columns={branchColumns} data={filteredBranches} getRowId={(r) => String(r.id)} enableRowSelection />
) : ( ) : (
<EmptyState label={t('clients.noBranches', 'Berlen kriterýalara Şahamça gabat gelmedi.')} actionLabel={t('clients.addBranch', 'Şahamça birikdiriň')} onAction={() => {}} /> <EmptyState
label={t('clients.noBranches', 'Berlen kriterýalara Şahamça gabat gelmedi.')}
actionLabel={t('clients.addBranch', 'Şahamça birikdiriň')}
onAction={() => {}}
/>
)} )}
</CollapsibleSection> </CollapsibleSection>
<CollapsibleSection title={t('clients.sections.loanOrders', 'Karz sargyt')} actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')} onAction={() => {}}> {/* ── Karz sargyt ──────────────────────────────────────────────────── */}
<DataTableToolbar searchValue={loanSearch} onSearchChange={setLoanSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> <CollapsibleSection
{(client.loanOrders ?? []).length === 0 ? ( title={t('clients.sections.loanOrders', 'Karz sargyt')}
<EmptyState label={t('clients.noLoanOrders', 'Berlen kriterýalara Karz sargyt gabat gelmedi.')} actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')} onAction={() => {}} /> actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')}
) : null} onAction={() => {}}
>
<DataTableToolbar
searchValue={loanSearch}
onSearchChange={setLoanSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}} hideAction
/>
{(client.loanOrders ?? []).length === 0 && (
<EmptyState
label={t('clients.noLoanOrders', 'Berlen kriterýalara Karz sargyt gabat gelmedi.')}
actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')}
onAction={() => {}}
/>
)}
</CollapsibleSection> </CollapsibleSection>
<CollapsibleSection title={t('clients.sections.cardOrders', 'Kart sargyt')} actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')} onAction={() => {}}> {/* ── Kart sargyt ──────────────────────────────────────────────────── */}
<DataTableToolbar searchValue={cardSearch} onSearchChange={setCardSearch} searchPlaceholder={t('common.search', 'Gözlemek')} columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}} columnOrder={[]} onColumnOrderChange={() => {}} hideAction /> <CollapsibleSection
{(client.cardOrders ?? []).length === 0 ? ( title={t('clients.sections.cardOrders', 'Kart sargyt')}
<EmptyState label={t('clients.noCardOrders', 'Berlen kriterýalara Kart sargyt gabat gelmedi.')} actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')} onAction={() => {}} /> actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')}
) : null} onAction={() => {}}
>
<DataTableToolbar
searchValue={cardSearch}
onSearchChange={setCardSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}} hideAction
/>
{(client.cardOrders ?? []).length === 0 && (
<EmptyState
label={t('clients.noCardOrders', 'Berlen kriterýalara Kart sargyt gabat gelmedi.')}
actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')}
onAction={() => {}}
/>
)}
</CollapsibleSection> </CollapsibleSection>
{/* ── Audit log ────────────────────────────────────────────────────── */}
<AuditLog logs={auditLogs} /> <AuditLog logs={auditLogs} />
{/* ── Delete dialog ────────────────────────────────────────────────── */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}> <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
@@ -233,54 +459,16 @@ export default function ClientDetailPage() {
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel> <AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction className="bg-destructive hover:bg-destructive/90 text-destructive-foreground" onClick={() => deleteMutation.mutate(clientId, { onSuccess: () => navigate('/clients') })}> <AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-destructive-foreground"
onClick={() => deleteMutation.mutate(clientId, { onSuccess: () => navigate('/clients') })}
>
{t('common.delete', 'Poz')} {t('common.delete', 'Poz')}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
</div>
)
}
interface CollapsibleSectionProps { title: string; actionLabel: string; onAction: () => void; children: React.ReactNode }
function CollapsibleSection({ title, actionLabel, onAction, children }: CollapsibleSectionProps) {
const [open, setOpen] = useState(true)
return (
<div className="mb-6">
<div className="flex items-center justify-between mb-2 cursor-pointer select-none w-fit gap-2" onClick={() => setOpen((v) => !v)}>
<h2 className="text-base font-semibold text-foreground">{title}</h2>
<ChevronDown size={15} className={`text-muted-foreground transition-transform duration-200 ${open ? '' : '-rotate-90'}`} />
</div>
{open && (
<div className="bg-card border border-border rounded-xl overflow-hidden p-4 space-y-3">
<div className="flex justify-end">
<Button size="sm" className="bg-primary hover:bg-primary/90 text-primary-foreground h-8 text-xs" onClick={onAction}>
{actionLabel}
</Button>
</div>
{children}
</div>
)}
</div> </div>
) )
} }
interface EmptyStateProps { label: string; actionLabel: string; onAction: () => void }
function EmptyState({ label, actionLabel, onAction }: EmptyStateProps) {
return (
<div className="flex flex-col items-center justify-center py-12 gap-4">
<div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center">
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" className="text-muted-foreground">
<rect x="4" y="8" width="24" height="18" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M4 13h24" stroke="currentColor" strokeWidth="1.5" />
<path d="M10 8V6M22 8V6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
<circle cx="16" cy="20" r="3" stroke="currentColor" strokeWidth="1.5" />
<path d="M19 23l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</div>
<p className="text-sm text-muted-foreground text-center">{label}</p>
<Button size="sm" variant="outline" className="h-8 text-xs" onClick={onAction}>{actionLabel}</Button>
</div>
)
}
+2
View File
@@ -180,6 +180,7 @@ export default function OperatorsPage() {
{t('operators.title', 'Operatorlar')} {t('operators.title', 'Operatorlar')}
</h1> </h1>
</div> </div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */} {/* Toolbar */}
<DataTableToolbar <DataTableToolbar
@@ -230,6 +231,7 @@ export default function OperatorsPage() {
onPageChange={setPage} onPageChange={setPage}
enableRowSelection enableRowSelection
/> />
</div>
{/* Delete dialog */} {/* Delete dialog */}
<AlertDialog <AlertDialog
+250 -249
View File
@@ -1,8 +1,8 @@
import { useParams, useNavigate } from 'react-router-dom' import { useParams, useNavigate } from "react-router-dom";
import { useTranslation } from 'react-i18next' import { useTranslation } from "react-i18next";
import { Pencil, Trash2, ChevronDown } from 'lucide-react' import { Pencil, Trash2, ChevronDown } from "lucide-react";
import { useState } from 'react' import { useState } from "react";
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -12,57 +12,161 @@ import {
AlertDialogFooter, AlertDialogFooter,
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from '@/components/ui/alert-dialog' } from "@/components/ui/alert-dialog";
import { Section, InfoRow, AuditLog } from '@/components/viewPageComponents' import { InfoRow, AuditLog } from "@/components/viewPageComponents";
import { DataTable, type ColumnDef } from '@/components/dataTable' import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar } from '@/components/dataTableToolbar' import { DataTableToolbar } from "@/components/dataTableToolbar";
import { useOperator, useDeleteOperator } from '@/features/operators/hooks/useOperators' import { useOperator, useDeleteOperator } from "@/features/operators/hooks/useOperators";
import type { OperatorRole, OperatorBranch, OperatorAuditLog } from '@/features/operators/api/operatorsApi' import type { OperatorRole, OperatorBranch, OperatorAuditLog } from "@/features/operators/api/operatorsApi";
// ─── OperatorDetailPage ─────────────────────────────────────────────────────── // ─── Bento primitives ─────────────────────────────────────────────────────────
function BentoGrid({ cols = 2, children }: { cols?: 1 | 2 | 3 | 4; children: React.ReactNode }) {
const colClass = {
1: "grid-cols-1",
2: "grid-cols-1 sm:grid-cols-2",
3: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",
4: "grid-cols-1 sm:grid-cols-2 lg:grid-cols-4",
}[cols];
return <div className={`grid ${colClass} gap-4`}>{children}</div>;
}
function BentoCard({ title, span, children }: { title?: string; span?: "full" | 2 | 3; children: React.ReactNode }) {
const spanClass = span === "full" ? "sm:col-span-full" : span === 2 ? "sm:col-span-2" : span === 3 ? "sm:col-span-3" : "";
return (
<div className={`bg-card border border-border rounded-xl overflow-hidden ${spanClass}`}>
{title && (
<div className="px-4 py-2.5 border-b border-border">
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">{title}</p>
</div>
)}
{children}
</div>
);
}
// ─── IsActive indicator ───────────────────────────────────────────────────────
function ActiveIndicator({ active }: { active: boolean }) {
return active ? (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
);
}
// ─── CollapsibleSection ───────────────────────────────────────────────────────
interface CollapsibleSectionProps {
title: string;
actionLabel: string;
onAction: () => void;
children: React.ReactNode;
}
function CollapsibleSection({ title, actionLabel, onAction, children }: CollapsibleSectionProps) {
const [open, setOpen] = useState(true);
return (
<div>
<div className="flex items-center gap-2 mb-2 cursor-pointer select-none w-fit" onClick={() => setOpen((v) => !v)}>
<h2 className="text-base font-semibold text-foreground">{title}</h2>
<ChevronDown size={15} className={`text-muted-foreground transition-transform duration-200 ${open ? "" : "-rotate-90"}`} />
</div>
{open && (
<div className="bg-card border border-border rounded-xl overflow-hidden p-4 space-y-3">
<div className="flex justify-end">
<Button size="sm" className="bg-primary hover:bg-primary/90 text-primary-foreground h-8 text-xs" onClick={onAction}>
{actionLabel}
</Button>
</div>
{children}
</div>
)}
</div>
);
}
// ─── EmptyState ───────────────────────────────────────────────────────────────
interface EmptyStateProps {
label: string;
actionLabel: string;
onAction: () => void;
}
function EmptyState({ label, actionLabel, onAction }: EmptyStateProps) {
return (
<div className="flex flex-col items-center justify-center py-12 gap-4">
<div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center">
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" className="text-muted-foreground">
<rect x="4" y="8" width="24" height="18" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M4 13h24" stroke="currentColor" strokeWidth="1.5" />
<path d="M10 8V6M22 8V6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
<circle cx="16" cy="20" r="3" stroke="currentColor" strokeWidth="1.5" />
<path d="M19 23l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</div>
<p className="text-sm text-muted-foreground text-center">{label}</p>
<Button size="sm" variant="outline" className="h-8 text-xs" onClick={onAction}>
{actionLabel}
</Button>
</div>
);
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function OperatorDetailPage() { export default function OperatorDetailPage() {
const { id } = useParams<{ id: string }>() const { id } = useParams<{ id: string }>();
const operatorId = Number(id) const operatorId = Number(id);
const { t } = useTranslation() const { t } = useTranslation();
const navigate = useNavigate() const navigate = useNavigate();
const deleteMutation = useDeleteOperator() const deleteMutation = useDeleteOperator();
const { data: operator, isLoading } = useOperator(operatorId) const { data: operator, isLoading } = useOperator(operatorId);
const [deleteOpen, setDeleteOpen] = useState(false) const [deleteOpen, setDeleteOpen] = useState(false);
const [roleSearch, setRoleSearch] = useState('') const [roleSearch, setRoleSearch] = useState("");
const [permSearch, setPermSearch] = useState('') const [permSearch, setPermSearch] = useState("");
const [branchSearch, setBranchSearch] = useState('') const [branchSearch, setBranchSearch] = useState("");
// ── Role columns ────────────────────────────────────────────────────────── // ── Role columns ──────────────────────────────────────────────────────────
const roleColumns: ColumnDef<OperatorRole>[] = [ const roleColumns: ColumnDef<OperatorRole>[] = [
{ {
accessorKey: 'id', accessorKey: "id",
header: 'ID', header: "ID",
cell: ({ row }) => ( cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
<span className="text-primary font-semibold text-sm">{row.original.id}</span>
),
size: 80, size: 80,
}, },
{ {
accessorKey: 'code', accessorKey: "code",
header: t('roles.fields.code', 'KOD'), header: t("roles.fields.code", "KOD"),
cell: ({ row }) => <span className="text-sm">{row.original.code}</span>, cell: ({ row }) => <span className="text-sm">{row.original.code}</span>,
}, },
{ {
accessorKey: 'name', accessorKey: "name",
header: t('roles.fields.name', 'ADY'), header: t("roles.fields.name", "ADY"),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>, cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
}, },
{ {
accessorKey: 'guardName', accessorKey: "guardName",
header: t('roles.fields.guardName', 'GUARD NAME'), header: t("roles.fields.guardName", "GUARD NAME"),
cell: ({ row }) => <span className="text-sm">{row.original.guardName}</span>, cell: ({ row }) => <span className="text-sm">{row.original.guardName}</span>,
}, },
{ {
id: 'actions', id: "actions",
header: '', header: "",
cell: ({ row }) => ( cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end"> <div className="flex items-center gap-1 justify-end">
<Button <Button
@@ -71,105 +175,88 @@ export default function OperatorDetailPage() {
className="h-7 w-7 text-muted-foreground hover:text-foreground" className="h-7 w-7 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/roles/${row.original.id}`)} onClick={() => navigate(`/roles/${row.original.id}`)}
> >
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
</svg>
</Button> </Button>
<Button <Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-foreground">
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-foreground"
>
<Pencil size={13} /> <Pencil size={13} />
</Button> </Button>
<Button <Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-destructive"
>
<Trash2 size={13} /> <Trash2 size={13} />
</Button> </Button>
</div> </div>
), ),
size: 120, size: 120,
}, },
] ];
// ── Branch columns ──────────────────────────────────────────────────────── // ── Branch columns ────────────────────────────────────────────────────────
const branchColumns: ColumnDef<OperatorBranch>[] = [ const branchColumns: ColumnDef<OperatorBranch>[] = [
{ {
accessorKey: 'id', accessorKey: "id",
header: 'ID', header: "ID",
cell: ({ row }) => ( cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
<span className="text-primary font-semibold text-sm">{row.original.id}</span>
),
size: 60, size: 60,
}, },
{ {
accessorKey: 'name', accessorKey: "name",
header: t('branches.fields.name', 'ADY'), header: t("branches.fields.name", "ADY"),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>, cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
}, },
{ {
accessorKey: 'region', accessorKey: "region",
header: t('branches.fields.region', 'WELAÝAT'), header: t("branches.fields.region", "WELAÝAT"),
cell: ({ row }) => <span className="text-sm">{row.original.region}</span>, cell: ({ row }) => <span className="text-sm">{row.original.region}</span>,
}, },
{ {
accessorKey: 'district', accessorKey: "district",
header: t('branches.fields.district', 'ETRAP'), header: t("branches.fields.district", "ETRAP"),
cell: ({ row }) => <span className="text-sm">{row.original.district}</span>, cell: ({ row }) => <span className="text-sm">{row.original.district}</span>,
}, },
{ {
accessorKey: 'uniqueCode', accessorKey: "uniqueCode",
header: t('branches.fields.uniqueCode', 'UNIKAL BELGI'), header: t("branches.fields.uniqueCode", "UNIKAL BELGI"),
cell: ({ row }) => <span className="text-sm">{row.original.uniqueCode}</span>, cell: ({ row }) => <span className="text-sm">{row.original.uniqueCode}</span>,
}, },
{ {
accessorKey: 'isActive', accessorKey: "isActive",
header: t('branches.fields.isActive', 'IŞJEŇ'), header: t("branches.fields.isActive", "IŞJEŇ"),
cell: ({ row }) => cell: ({ row }) => <ActiveIndicator active={row.original.isActive} />,
row.original.isActive ? (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
),
size: 80, size: 80,
}, },
{ {
accessorKey: 'billingUsernameIbr', accessorKey: "billingUsernameIbr",
header: t('branches.fields.billingIbr', 'BILLING ULANYJY ADY'), header: t("branches.fields.billingIbr", "BILLING ULANYJY ADY"),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameIbr}</span>, cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameIbr}</span>,
}, },
{ {
accessorKey: 'billingUsernameSber', accessorKey: "billingUsernameSber",
header: t('branches.fields.billingSber', 'BILLING USERNAME (SBER)'), header: t("branches.fields.billingSber", "BILLING USERNAME (SBER)"),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameSber}</span>, cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameSber}</span>,
}, },
{ {
accessorKey: 'billingUsernameVisa', accessorKey: "billingUsernameVisa",
header: t('branches.fields.billingVisa', 'BILLING USERNAME (VISA)'), header: t("branches.fields.billingVisa", "BILLING USERNAME (VISA)"),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameVisa}</span>, cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameVisa}</span>,
}, },
{ {
id: 'actions', id: "actions",
header: '', header: "",
cell: () => ( cell: () => (
<div className="flex items-center gap-1 justify-end"> <div className="flex items-center gap-1 justify-end">
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-foreground"> <Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
<Trash2 size={13} /> <Trash2 size={13} />
</Button> </Button>
</div> </div>
), ),
size: 60, size: 60,
}, },
] ];
// ── Loading ───────────────────────────────────────────────────────────────
if (isLoading) { if (isLoading) {
return ( return (
@@ -178,12 +265,11 @@ export default function OperatorDetailPage() {
<div key={i} className="h-16 bg-muted rounded-xl animate-pulse" /> <div key={i} className="h-16 bg-muted rounded-xl animate-pulse" />
))} ))}
</div> </div>
) );
} }
if (!operator) return null if (!operator) return null;
// Map audit logs to AuditLog component format
const auditLogs = (operator.auditLogs ?? []).map((log: OperatorAuditLog) => ({ const auditLogs = (operator.auditLogs ?? []).map((log: OperatorAuditLog) => ({
id: String(log.id), id: String(log.id),
action: log.actionName, action: log.actionName,
@@ -191,24 +277,19 @@ export default function OperatorDetailPage() {
target: log.target, target: log.target,
status: log.status, status: log.status,
date: log.createdAt, date: log.createdAt,
})) }));
const filteredRoles = (operator.roles ?? []).filter( const filteredRoles = (operator.roles ?? []).filter(
(r) => (r) => r.name.toLowerCase().includes(roleSearch.toLowerCase()) || r.code.toLowerCase().includes(roleSearch.toLowerCase()),
r.name.toLowerCase().includes(roleSearch.toLowerCase()) || );
r.code.toLowerCase().includes(roleSearch.toLowerCase()), const filteredBranches = (operator.branches ?? []).filter((b) => b.name.toLowerCase().includes(branchSearch.toLowerCase()));
)
const filteredBranches = (operator.branches ?? []).filter((b) =>
b.name.toLowerCase().includes(branchSearch.toLowerCase()),
)
return ( return (
<div className="p-6"> <div className="p-6 flex flex-col gap-6">
{/* Page header */} {/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-center justify-between mb-6"> <div className="flex items-center justify-between">
<h1 className="text-2xl font-semibold text-foreground"> <h1 className="text-2xl font-semibold text-foreground">
{t('operators.detailTitle', 'Operator giňişleýin')}: {operator.name} {t("operators.detailTitle", "Operator giňişleýin")}: {operator.name}
</h1> </h1>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button
@@ -230,40 +311,33 @@ export default function OperatorDetailPage() {
</div> </div>
</div> </div>
{/* Basic info */} {/* ── Row 1: Esasy maglumatlar + Kontakt ──────────────────────────── */}
<Section> <BentoGrid cols={2}>
<InfoRow label="ID" value={operator.id} /> <BentoCard title={t("operators.sections.basic", "Esasy maglumatlar")}>
<InfoRow label={t('operators.fields.username', 'Ulanyjy ady')} value={operator.username} /> <InfoRow label="ID" value={operator.id} />
<InfoRow label={t('operators.fields.name', 'Ady')} value={operator.name} /> <InfoRow label={t("operators.fields.username", "Ulanyjy ady")} value={operator.username} />
<InfoRow label={t('operators.fields.phone', 'Telefon')} value={operator.phone ?? '—'} /> <InfoRow label={t("operators.fields.name", "Ady")} value={operator.name} />
<InfoRow label={t('operators.fields.email', 'E-poçta')} value={operator.email ?? '—'} /> <InfoRow label={t("operators.fields.isActive", "Işjeň")}>
<InfoRow label={t('operators.fields.isActive', 'Işjeň')}> <ActiveIndicator active={operator.isActive} />
{operator.isActive ? ( </InfoRow>
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-primary text-primary"> </BentoCard>
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
) : (
<span className="inline-flex items-center justify-center w-6 h-6 rounded-full border-2 border-destructive text-destructive">
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
<path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
</svg>
</span>
)}
</InfoRow>
</Section>
{/* Roles */} <BentoCard title={t("operators.sections.contact", "Kontakt")}>
<InfoRow label={t("operators.fields.phone", "Telefon")} value={operator.phone ?? "—"} />
<InfoRow label={t("operators.fields.email", "E-poçta")} value={operator.email ?? "—"} />
</BentoCard>
</BentoGrid>
{/* ── Rollar ───────────────────────────────────────────────────────── */}
<CollapsibleSection <CollapsibleSection
title={t('operators.sections.roles', 'Rollar')} title={t("operators.sections.roles", "Rollar")}
actionLabel={t('operators.addRole', 'Rol birikdiriň')} actionLabel={t("operators.addRole", "Rol birikdiriň")}
onAction={() => {/* open role assign modal */}} onAction={() => {}}
> >
<DataTableToolbar <DataTableToolbar
searchValue={roleSearch} searchValue={roleSearch}
onSearchChange={setRoleSearch} onSearchChange={setRoleSearch}
searchPlaceholder={t('common.search', 'Gözlemek')} searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]} columns={[]}
columnVisibility={{}} columnVisibility={{}}
onColumnVisibilityChange={() => {}} onColumnVisibilityChange={() => {}}
@@ -271,24 +345,19 @@ export default function OperatorDetailPage() {
onColumnOrderChange={() => {}} onColumnOrderChange={() => {}}
hideAction hideAction
/> />
<DataTable <DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
columns={roleColumns}
data={filteredRoles}
getRowId={(r) => String(r.id)}
enableRowSelection
/>
</CollapsibleSection> </CollapsibleSection>
{/* Permissions */} {/* ── Rugsatlar ────────────────────────────────────────────────────── */}
<CollapsibleSection <CollapsibleSection
title={t('operators.sections.permissions', 'Rugsatlar')} title={t("operators.sections.permissions", "Rugsatlar")}
actionLabel={t('operators.addPermission', 'Rugsat birikdiriň')} actionLabel={t("operators.addPermission", "Rugsat birikdiriň")}
onAction={() => {/* open permission modal */}} onAction={() => {}}
> >
<DataTableToolbar <DataTableToolbar
searchValue={permSearch} searchValue={permSearch}
onSearchChange={setPermSearch} onSearchChange={setPermSearch}
searchPlaceholder={t('common.search', 'Gözlemek')} searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]} columns={[]}
columnVisibility={{}} columnVisibility={{}}
onColumnVisibilityChange={() => {}} onColumnVisibilityChange={() => {}}
@@ -296,21 +365,25 @@ export default function OperatorDetailPage() {
onColumnOrderChange={() => {}} onColumnOrderChange={() => {}}
hideAction hideAction
/> />
{(operator.permissions ?? []).length === 0 ? ( {(operator.permissions ?? []).length === 0 && (
<EmptyState label={t('operators.noPermissions', 'Berlen kriterýalara Rugsat gabat gelmedi.')} actionLabel={t('operators.addPermission', 'Rugsat birikdiriň')} onAction={() => {}} /> <EmptyState
) : null} label={t("operators.noPermissions", "Berlen kriterýalara Rugsat gabat gelmedi.")}
actionLabel={t("operators.addPermission", "Rugsat birikdiriň")}
onAction={() => {}}
/>
)}
</CollapsibleSection> </CollapsibleSection>
{/* Branches */} {/* ── Şahamçalar ───────────────────────────────────────────────────── */}
<CollapsibleSection <CollapsibleSection
title={t('operators.sections.branches', 'Şahamçalar')} title={t("operators.sections.branches", "Şahamçalar")}
actionLabel={t('operators.addBranch', 'Şahamça birikdiriň')} actionLabel={t("operators.addBranch", "Şahamça birikdiriň")}
onAction={() => {}} onAction={() => {}}
> >
<DataTableToolbar <DataTableToolbar
searchValue={branchSearch} searchValue={branchSearch}
onSearchChange={setBranchSearch} onSearchChange={setBranchSearch}
searchPlaceholder={t('common.search', 'Gözlemek')} searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]} columns={[]}
columnVisibility={{}} columnVisibility={{}}
onColumnVisibilityChange={() => {}} onColumnVisibilityChange={() => {}}
@@ -318,140 +391,68 @@ export default function OperatorDetailPage() {
onColumnOrderChange={() => {}} onColumnOrderChange={() => {}}
hideAction hideAction
/> />
<DataTable <DataTable columns={branchColumns} data={filteredBranches} getRowId={(r) => String(r.id)} enableRowSelection />
columns={branchColumns}
data={filteredBranches}
getRowId={(r) => String(r.id)}
enableRowSelection
/>
</CollapsibleSection> </CollapsibleSection>
{/* Karz sargyt */} {/* ── Karz sargyt ──────────────────────────────────────────────────── */}
<CollapsibleSection <CollapsibleSection
title={t('operators.sections.loanLimits', 'Karz sargyt')} title={t("operators.sections.loanLimits", "Karz sargyt")}
actionLabel={t('operators.addLoanLimit', 'Karz sargyt döredin')} actionLabel={t("operators.addLoanLimit", "Karz sargyt döredin")}
onAction={() => {}} onAction={() => {}}
> >
{(operator.loanLimits ?? []).length === 0 ? ( {(operator.loanLimits ?? []).length === 0 && (
<EmptyState label={t('operators.noLoanLimits', 'Berlen kriterýalara Karz sargyt gabat gelmedi.')} actionLabel={t('operators.addLoanLimit', 'Karz sargyt döredin')} onAction={() => {}} /> <EmptyState
) : null} label={t("operators.noLoanLimits", "Berlen kriterýalara Karz sargyt gabat gelmedi.")}
actionLabel={t("operators.addLoanLimit", "Karz sargyt döredin")}
onAction={() => {}}
/>
)}
</CollapsibleSection> </CollapsibleSection>
{/* Kart sargyt */} {/* ── Kart sargyt ──────────────────────────────────────────────────── */}
<CollapsibleSection <CollapsibleSection
title={t('operators.sections.cardLimits', 'Kart sargyt')} title={t("operators.sections.cardLimits", "Kart sargyt")}
actionLabel={t('operators.addCardLimit', 'Kart sargyt döredin')} actionLabel={t("operators.addCardLimit", "Kart sargyt döredin")}
onAction={() => {}} onAction={() => {}}
> >
{(operator.cardLimits ?? []).length === 0 ? ( {(operator.cardLimits ?? []).length === 0 && (
<EmptyState label={t('operators.noCardLimits', 'Berlen kriterýalara Kart sargyt gabat gelmedi.')} actionLabel={t('operators.addCardLimit', 'Kart sargyt döredin')} onAction={() => {}} /> <EmptyState
) : null} label={t("operators.noCardLimits", "Berlen kriterýalara Kart sargyt gabat gelmedi.")}
actionLabel={t("operators.addCardLimit", "Kart sargyt döredin")}
onAction={() => {}}
/>
)}
</CollapsibleSection> </CollapsibleSection>
{/* Audit log */} {/* ── Audit log ────────────────────────────────────────────────────── */}
<AuditLog logs={auditLogs} /> <AuditLog logs={auditLogs} />
{/* Delete dialog */} {/* ── Delete dialog ────────────────────────────────────────────────── */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}> <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent> <AlertDialogContent>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle>{t('operators.deleteTitle', 'Operatory pozmak')}</AlertDialogTitle> <AlertDialogTitle>{t("operators.deleteTitle", "Operatory pozmak")}</AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
{t('operators.deleteConfirm', '{{name}} operatoryny pozmak isleýärsiňizmi?', { {t("operators.deleteConfirm", "{{name}} operatoryny pozmak isleýärsiňizmi?", {
name: operator.name, name: operator.name,
})} })}
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel> <AlertDialogCancel>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
<AlertDialogAction <AlertDialogAction
className="bg-destructive hover:bg-destructive/90 text-destructive-foreground" className="bg-destructive hover:bg-destructive/90 text-destructive-foreground"
onClick={() => onClick={() =>
deleteMutation.mutate(operatorId, { deleteMutation.mutate(operatorId, {
onSuccess: () => navigate('/operators'), onSuccess: () => navigate("/operators"),
}) })
} }
> >
{t('common.delete', 'Poz')} {t("common.delete", "Poz")}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
</div> </div>
) );
} }
// ─── CollapsibleSection ───────────────────────────────────────────────────────
interface CollapsibleSectionProps {
title: string
actionLabel: string
onAction: () => void
children: React.ReactNode
}
function CollapsibleSection({ title, actionLabel, onAction, children }: CollapsibleSectionProps) {
const [open, setOpen] = useState(true)
return (
<div className="mb-6">
<div
className="flex items-center justify-between mb-2 cursor-pointer select-none w-fit gap-2"
onClick={() => setOpen((v) => !v)}
>
<h2 className="text-base font-semibold text-foreground">{title}</h2>
<ChevronDown
size={15}
className={`text-muted-foreground transition-transform duration-200 ${open ? '' : '-rotate-90'}`}
/>
</div>
{open && (
<div className="bg-card border border-border rounded-xl overflow-hidden p-4 space-y-3">
<div className="flex justify-end">
<Button
size="sm"
className="bg-primary hover:bg-primary/90 text-primary-foreground h-8 text-xs"
onClick={onAction}
>
{actionLabel}
</Button>
</div>
{children}
</div>
)}
</div>
)
}
// ─── EmptyState ───────────────────────────────────────────────────────────────
interface EmptyStateProps {
label: string
actionLabel: string
onAction: () => void
}
function EmptyState({ label, actionLabel, onAction }: EmptyStateProps) {
return (
<div className="flex flex-col items-center justify-center py-12 gap-4">
<div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center">
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" className="text-muted-foreground">
<rect x="4" y="8" width="24" height="18" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M4 13h24" stroke="currentColor" strokeWidth="1.5" />
<path d="M10 8V6M22 8V6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
<circle cx="16" cy="20" r="3" stroke="currentColor" strokeWidth="1.5" />
<path d="M19 23l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</div>
<p className="text-sm text-muted-foreground text-center">{label}</p>
<Button
size="sm"
variant="outline"
className="h-8 text-xs"
onClick={onAction}
>
{actionLabel}
</Button>
</div>
)
}