fixed some ui

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

View File

@@ -145,27 +145,158 @@ export interface PaginatedResponse<T> {
// ─── Mock Data ─────────────────────────────────────────────────────────────────
const USE_MOCK = true // gerçek API hazır olunca false yap
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-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' },
{ 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' },
{ 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' },
{ 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' },
{ 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' },
{ 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' },
{ 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' },
{ 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' },
{ 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' },
{ 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' },
{
id: 'LOM-0001', loanType: 'Sarp ediş karzy', createdAt: '2025-01-15 09:42',
region: 'Aşgabat', branch: 'Merkezi şahamça',
firstName: 'Oraz', lastName: 'Annaýew', phone: '+99361123456', status: 'GARAŞYLÝAR',
note: 'Müşderi dokumentleri tassyklamady',
loanAmount: 15000, loanHistory: 'positive',
patronicName: 'Myradowiç', education: 'high', marriageStatus: 'MARRIED',
dateOfBirth: '1992-04-18',
residence: 'Aşgabat, Bitarap Türkmenistan şaýoly, 15',
currentResidence: 'Aşgabat, Garaşsyzlyk köçesi, 5',
passportSerie: 'I', passportNumber: '123456',
passportDateOfIssue: '2015-03-10',
passportGivenBy: 'Aşgabat şäheriniň Içeri işler müdirligi',
bornPlace: 'Aşgabat şäheri',
email: 'oraz.annayew@email.com',
phoneAdditional: '+99365443322',
workCompany: 'Türkmennebit', workHrPhone: '+99312456789',
workRegion: 'Aşgabat', workProvince: 'Büzmeýin etraby',
position: 'Inžener', salary: 2500, workStartedAt: '2018-06-01',
cardNumber: '4111111111111111', cardName: 'ORAZ ANNAÝEW',
cardExpMonth: '12', cardExpYear: '2027',
guarantor1Name: 'Berdi', guarantor1Surname: 'Berdiýew',
guarantor1Patronic: 'Annagulyýewiç',
guarantor1PassportSerie: 'II', guarantor1PassportNumber: '654321',
guarantor1CardNumber: '4222222222222222', guarantor1CardName: 'BERDI BERDIÝEW',
guarantor1CardExpMonth: '06', guarantor1CardExpYear: '2026', guarantor1Salary: 3000,
},
{
id: 'LOM-0002', loanType: 'Awtoulag karzy', createdAt: '2025-01-18 11:05',
region: 'Ahal', branch: 'Änew şahamçasy',
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(
params: LoanOrderMobileListParams,
): PaginatedResponse<LoanOrderMobile> {
let result = [...MOCK_DATA]
const page = params.page ?? 1
const perPage = params.perPage ?? 25
let result = [...mockStore]
if (params.search) {
const q = params.search.toLowerCase()
@@ -182,8 +313,6 @@ function applyMockFilters(
if (params.branch) result = result.filter((r) => r.branch === params.branch)
const total = result.length
const page = params.page ?? 1
const perPage = params.perPage ?? 25
const start = (page - 1) * perPage
return { data: result.slice(start, start + perPage), total }
@@ -194,8 +323,10 @@ function applyMockFilters(
export async function fetchLoanOrderMobiles(
params: LoanOrderMobileListParams,
): Promise<PaginatedResponse<LoanOrderMobile>> {
if (USE_MOCK) return applyMockFilters(params)
if (true) {
await delay(500)
return applyMockFilters(params)
}
const { data } = await apiClient.get<PaginatedResponse<LoanOrderMobile>>(
'/loan-order-mobiles',
{ params },
@@ -204,51 +335,78 @@ export async function fetchLoanOrderMobiles(
}
export async function deleteLoanOrderMobile(id: string): Promise<void> {
if (USE_MOCK) {
const idx = MOCK_DATA.findIndex((r) => r.id === id)
if (idx !== -1) MOCK_DATA.splice(idx, 1)
return
}
await apiClient.delete(`/loan-order-mobiles/${id}`)
await delay(300)
mockStore = mockStore.filter((r) => r.id !== id)
}
export async function getLoanOrderMobileById(id: string): Promise<LoanOrderMobile> {
if (USE_MOCK) {
const order = MOCK_DATA.find((r) => r.id === id)
if (!order) throw new Error('Not found')
return order
}
const { data } = await apiClient.get<LoanOrderMobile>(`/loan-order-mobiles/${id}`)
return data
await delay(300)
const order = mockStore.find((r) => r.id === id)
if (!order) throw new Error('Not found')
return { ...order }
}
export async function createLoanOrderMobile(
payload: LoanOrderMobilePayload
): Promise<LoanOrderMobile> {
if (USE_MOCK) {
const newOrder: LoanOrderMobile = {
...payload,
id: `LOM-${String(MOCK_DATA.length + 1).padStart(4, '0')}`,
createdAt: new Date().toISOString().slice(0, 16).replace('T', ' '),
status: payload.status as LoanOrderMobileStatus,
}
MOCK_DATA.unshift(newOrder)
return newOrder
await delay(500)
const newOrder: LoanOrderMobile = {
...payload,
id: `LOM-${String(nextId++).padStart(4, '0')}`,
createdAt: new Date().toISOString().slice(0, 16).replace('T', ' '),
status: payload.status as LoanOrderMobileStatus,
}
const { data } = await apiClient.post<LoanOrderMobile>('/loan-order-mobiles', payload)
return data
mockStore = [newOrder, ...mockStore]
return newOrder
}
export async function updateLoanOrderMobile(
id: string,
payload: Partial<LoanOrderMobilePayload>
): Promise<LoanOrderMobile> {
if (USE_MOCK) {
const idx = MOCK_DATA.findIndex((r) => r.id === id)
if (idx === -1) throw new Error('Not found')
MOCK_DATA[idx] = { ...MOCK_DATA[idx], ...payload } as LoanOrderMobile
return MOCK_DATA[idx]
}
const { data } = await apiClient.put<LoanOrderMobile>(`/loan-order-mobiles/${id}`, payload)
return data
}
await delay(500)
const idx = mockStore.findIndex((r) => r.id === id)
if (idx === -1) throw new Error('Not found')
const updated = { ...mockStore[idx], ...payload } as LoanOrderMobile
mockStore = mockStore.map((r) => (r.id === id ? updated : r))
return updated
}
// ─── Branch options by region ─────────────────────────────────────────────────
export const BRANCHES_BY_REGION_MOBILE: Record<string, { value: string; label: string }[]> = {
'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' },
],
}

View File

@@ -1,5 +1,3 @@
import { apiClient } from '@/lib/api/client'
// ─── Types ────────────────────────────────────────────────────────────────────
export type LoanOrderStatus =
@@ -9,7 +7,6 @@ export type LoanOrderStatus =
| 'IŞLENÝÄR'
export interface LoanOrder {
// ── List fields ──────────────────────────────────────────────────────────
id: string
loanType: string
createdAt: string
@@ -21,7 +18,6 @@ export interface LoanOrder {
status: LoanOrderStatus
note?: string | null
// ── Detail fields ─────────────────────────────────────────────────────────
loanAmount?: number | null
loanHistory?: string | null
patronicName?: string | null
@@ -31,7 +27,6 @@ export interface LoanOrder {
residence?: string | null
currentResidence?: string | null
// Passport
passportSerie?: string | null
passportNumber?: string | null
passportDateOfIssue?: string | null
@@ -42,12 +37,10 @@ export interface LoanOrder {
passportPage89Url?: string | null
passportPage32Url?: string | null
// Contact
email?: string | null
phoneAdditional?: string | null
homePhone?: string | null
// Employment
workCompany?: string | null
workHrPhone?: string | null
workRegion?: string | null
@@ -56,13 +49,11 @@ export interface LoanOrder {
salary?: number | null
workStartedAt?: string | null
// Card (Zähmet haky)
cardNumber?: string | null
cardName?: string | null
cardExpMonth?: string | null
cardExpYear?: string | null
// Guarantor (Zamun)
guarantor1Name?: string | null
guarantor1Surname?: string | null
guarantor1Patronic?: string | null
@@ -74,7 +65,6 @@ export interface LoanOrder {
guarantor1CardExpYear?: string | null
guarantor1Salary?: number | null
// ── Restored fields from previous version ───────────────────────────────
amount?: number | null
createdBy?: string | null
fullName?: string | null
@@ -172,6 +162,44 @@ const MOCK_DATA: LoanOrder[] = [
lastName: 'Amanow',
phone: '+993 65 112233',
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',
@@ -183,56 +211,159 @@ const MOCK_DATA: LoanOrder[] = [
lastName: 'Berdiýewa',
phone: '+993 61 445566',
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 ────────────────────────────────────────────────────────────
export async function fetchLoanOrders(
params: LoanOrdersParams
): Promise<LoanOrdersResponse> {
// Mock — real API hazır bolanda aşakdaky commentden çykar
await new Promise((resolve) => setTimeout(resolve, 800))
await delay(600)
const page = params.page || 1
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 })
// return data
let filtered = mockStore.filter((item) => {
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> {
const { data } = await apiClient.get<LoanOrder>(`/loan-orders/${id}`)
return data
await delay(300)
const item = mockStore.find((o) => o.id === id)
if (!item) throw new Error('Not found')
return { ...item }
}
export async function createLoanOrder(
payload: LoanOrderPayload
): Promise<LoanOrder> {
const { data } = await apiClient.post<LoanOrder>('/loan-orders', payload)
return data
await delay(500)
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(
id: string,
payload: Partial<LoanOrderPayload>
): Promise<LoanOrder> {
const { data } = await apiClient.put<LoanOrder>(`/loan-orders/${id}`, payload)
return data
await delay(500)
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> {
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' },
],
}

View File

@@ -13,6 +13,7 @@ import { FormActions } from '@/components/formActions'
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
import { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders'
import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi'
import { BRANCHES_BY_REGION } from '@/features/loanOrders/api/loanOrdersApi'
// ─── Static options ───────────────────────────────────────────────────────────
@@ -387,7 +388,7 @@ interface StepContentProps {
function StepStatus({ form, errors, set }: StepContentProps) {
return (
<BentoGrid cols={2}>
<BentoCard title="Ýagdaý">
<BentoCard>
<FormInput
type="select"
label="Status"
@@ -400,7 +401,7 @@ function StepStatus({ form, errors, set }: StepContentProps) {
/>
</BentoCard>
<BentoCard title="Bellik">
<BentoCard>
<FormInput
type="textarea"
label="Bellik"
@@ -417,7 +418,7 @@ function StepStatus({ form, errors, set }: StepContentProps) {
function StepLoan({ form, errors, set }: StepContentProps) {
return (
<BentoGrid cols={2}>
<BentoCard title="Karz görnüşi">
<BentoCard>
<FormInput
type="searchable-select"
label="Karz görnüşi"
@@ -430,7 +431,7 @@ function StepLoan({ form, errors, set }: StepContentProps) {
/>
</BentoCard>
<BentoCard title="Möçber">
<BentoCard>
<FormInput
type="number"
label="Karz möçberi"
@@ -446,9 +447,11 @@ function StepLoan({ form, errors, set }: StepContentProps) {
}
function StepLocation({ form, errors, set }: StepContentProps) {
const branchOptions = BRANCHES_BY_REGION[form.region] ?? []
return (
<BentoGrid cols={2}>
<BentoCard title="Welaýat">
<BentoCard>
<FormInput
type="searchable-select"
label="Welaýat"
@@ -459,19 +462,16 @@ function StepLocation({ form, errors, set }: StepContentProps) {
placeholder="Saýlamak üçin basyň"
error={errors.region}
/>
<p className="text-xs text-muted-foreground">
Welaýaty saýlasaňyz şahamçalar güncellenar.
</p>
</BentoCard>
<BentoCard title="Şahamça">
<BentoCard>
<FormInput
type="searchable-select"
label="Şahamça"
required
value={form.branch}
onChange={(v) => set('branch', v)}
options={[]}
options={branchOptions}
placeholder="Saýlamak üçin basyň"
disabled={!form.region}
error={errors.branch}
@@ -485,37 +485,37 @@ function StepPersonal({ form, errors, set }: StepContentProps) {
return (
<div className="space-y-4">
<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} />
</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} />
</BentoCard>
<BentoCard title="Atasynyň ady">
<BentoCard>
<FormInput type="text" label="Atasynyň ady" value={form.patronicName} onChange={(v) => set('patronicName', v)} placeholder="Atasynyň ady" />
</BentoCard>
</BentoGrid>
<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} />
</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} />
</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} />
</BentoCard>
</BentoGrid>
<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} />
</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" />
</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ň" />
</BentoCard>
</BentoGrid>
@@ -543,22 +543,22 @@ function StepPassport({ form, errors, set }: StepContentProps) {
return (
<div className="space-y-4">
<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} />
</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} />
</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} />
</BentoCard>
</BentoGrid>
<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} />
</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)" />
</BentoCard>
</BentoGrid>
@@ -586,25 +586,25 @@ function StepJob({ form, errors, set }: StepContentProps) {
return (
<div className="space-y-4">
<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="phone" label="Işgärler bölüminiň iş belgisi" value={form.workHrPhone} onChange={(v) => set('workHrPhone', v)} placeholder="61 097 651" />
</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 etrabyňyz" value={form.workProvince} onChange={(v) => set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" />
</BentoCard>
</BentoGrid>
<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} />
</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} />
</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} />
</BentoCard>
</BentoGrid>
@@ -644,7 +644,7 @@ function StepFiles({
)}
<BentoGrid cols={2}>
<BentoCard title="Pasport (sahypa 1)">
<BentoCard >
<FormInput
type="file"
label={mode === 'edit' ? 'Pasport (sahypa 1) (çalyşmak)' : 'Pasport (sahypa 1)'}
@@ -656,7 +656,7 @@ function StepFiles({
/>
</BentoCard>
<BentoCard title="Pasport (2-3-nji sahypa)">
<BentoCard>
<FormInput
type="file"
label={mode === 'edit' ? 'Pasport (2-3-nji sahypa) (çalyşmak)' : 'Pasport (2-3-nji sahypa)'}
@@ -668,7 +668,7 @@ function StepFiles({
/>
</BentoCard>
<BentoCard title="Pasport (8-9 sahypa)">
<BentoCard >
<FormInput
type="file"
label="Pasport (8-9 sahypa)"
@@ -678,7 +678,7 @@ function StepFiles({
/>
</BentoCard>
<BentoCard title="Pasport (32-nji sahypa)">
<BentoCard >
<FormInput
type="file"
label="Pasport (32-nji sahypa)"
@@ -696,33 +696,33 @@ function StepGuarantor({ form, errors, set }: StepContentProps) {
return (
<div className="space-y-4">
<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} />
</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} />
</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" />
</BentoCard>
</BentoGrid>
<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} />
</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} />
</BentoCard>
</BentoGrid>
<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="Kartdaky ady" required value={form.guarantor1CardName} onChange={(v) => set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} />
</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 (ý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} />
@@ -923,16 +923,6 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
</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 */}
{currentStep === 0 && <StepStatus {...stepProps} />}
{currentStep === 1 && <StepLoan {...stepProps} />}

View File

@@ -149,6 +149,7 @@ export default function CardBalancesPage() {
{t('Card balances', 'Kart galyndylary')}
</h1>
</div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
@@ -181,6 +182,7 @@ export default function CardBalancesPage() {
totalCount={total}
onPageChange={setPage}
/>
</div>
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialogContent>

View File

@@ -11,7 +11,14 @@ import type {
CardPinStatus,
} from "@/features/cardPins/api/cardPinApi";
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 {
AlertDialog,
AlertDialogAction,
@@ -25,33 +32,43 @@ import {
// ─── Status Badge ─────────────────────────────────────────────────────────────
import { StatusBadge, type StatusBadgeVariant } from '@/components/ui/statusBadge'
import {
StatusBadge,
type StatusBadgeVariant,
} from "@/components/ui/statusBadge";
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_CONFIG = {
pending: {
label: 'Garaşylýar',
variant: 'warning' as StatusBadgeVariant,
icon: AlertCircle,
label: "Garaşylýar",
variant: "warning" as StatusBadgeVariant,
icon: AlertCircle,
},
approved: {
label: 'Tassyklandy',
variant: 'success' as StatusBadgeVariant,
icon: CheckCircle2,
label: "Tassyklandy",
variant: "success" as StatusBadgeVariant,
icon: CheckCircle2,
},
rejected: {
label: 'Ýatyryldy',
variant: 'error' as StatusBadgeVariant,
icon: XCircle,
label: "Ýatyryldy",
variant: "error" as StatusBadgeVariant,
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 }) {
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} />
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} />
);
}
// ─── Page ─────────────────────────────────────────────────────────────────────
@@ -137,7 +154,9 @@ export default function CardPinsPage() {
{
accessorKey: "status",
header: t("cardPin.status", "Status"),
cell: ({ row }) => <CardPinStatusStatusBadge status={row.original.status} />,
cell: ({ row }) => (
<CardPinStatusStatusBadge status={row.original.status} />
),
},
{
id: "actions",
@@ -193,62 +212,64 @@ export default function CardPinsPage() {
{t("Card pins", "Kart pin bukjalary")}
</h1>
</div>
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => {
setSearch(v);
setPage(1);
}}
searchPlaceholder={t("cardPin.search", "Gözlemek")}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
filterFields={[
{
id: "status",
label: t("cardPin.status", "Status"),
options: [
{ value: "pending", label: "Garaşylýar" },
{ value: "approved", label: "Tassyklandy" },
{ value: "rejected", label: "Ret edildi" },
],
},
]}
activeFilters={[{ fieldId: "status", value: statusFilter }]}
onFilterChange={(fieldId, value) => {
if (fieldId === "status")
setStatusFilter(value as CardPinStatus | "");
setPage(1);
}}
onFilterReset={() => {
setStatusFilter("");
setPage(1);
}}
perPage={perPage}
onPerPageChange={(v) => {
setPerPage(v);
setPage(1);
}}
actionLabel={t("cardPin.createBtn", "Kart pin bukja dörediň")}
onAction={() => navigate("/card-pins/create")}
/>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => {
setSearch(v);
setPage(1);
}}
searchPlaceholder={t("cardPin.search", "Gözlemek")}
columns={columnMeta}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
filterFields={[
{
id: "status",
label: t("cardPin.status", "Status"),
options: [
{ value: "pending", label: "Garaşylýar" },
{ value: "approved", label: "Tassyklandy" },
{ value: "rejected", label: "Ret edildi" },
],
},
]}
activeFilters={[{ fieldId: "status", value: statusFilter }]}
onFilterChange={(fieldId, value) => {
if (fieldId === "status")
setStatusFilter(value as CardPinStatus | "");
setPage(1);
}}
onFilterReset={() => {
setStatusFilter("");
setPage(1);
}}
perPage={perPage}
onPerPageChange={(v) => {
setPerPage(v);
setPage(1);
}}
actionLabel={t("cardPin.createBtn", "Kart pin bukja dörediň")}
onAction={() => navigate("/card-pins/create")}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
currentPage={data?.meta?.current_page ?? 1}
totalPages={data?.meta?.last_page ?? 1}
totalCount={data?.meta?.total}
onPageChange={setPage}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
currentPage={data?.meta?.current_page ?? 1}
totalPages={data?.meta?.last_page ?? 1}
totalCount={data?.meta?.total}
onPageChange={setPage}
/>
</div>
{/* Delete confirmation */}
<AlertDialog

View File

@@ -25,56 +25,77 @@ import {
} from "@/components/ui/statusBadge";
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
import { InfoRow, PassportImage } from "@/components/viewPageComponents";
// ─── Status badge ─────────────────────────────────────────────────────────────
// ─── Status config ────────────────────────────────────────────────────────────
const STATUS_CONFIG = {
pending: {
label: "Garaşylýar",
variant: "warning" as StatusBadgeVariant,
icon: AlertCircle,
},
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 }
>;
pending: { label: "Garaşylýar", variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
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 }) {
const cfg = STATUS_CONFIG[status];
if (!cfg)
return (
<span className="text-xs text-muted-foreground">{String(status)}</span>
);
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,
}: {
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 (
<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 ─────────────────────────────────────────────────────────────────────
export default function CardPinViewPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { t } = useTranslation();
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { t } = useTranslation()
const { data, isLoading, isError } = useCardPin(id!);
const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin();
const { data, isLoading, isError } = useCardPin(id!)
const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin()
if (isLoading) {
return (
<div className="flex items-center justify-center py-24">
<Spinner className="size-8 text-primary" />
</div>
);
)
}
if (isError || !data) {
@@ -82,12 +103,13 @@ export default function CardPinViewPage() {
<div className="flex items-center justify-center py-24 text-muted-foreground">
{t("common.notFound", "Maglumat tapylmady")}
</div>
);
)
}
return (
<div className="mx-auto space-y-6">
{/* Header */}
<div className="mx-auto flex flex-col gap-6">
{/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-start justify-between">
<h1 className="text-xl font-bold text-foreground">
{t("cardPin.viewTitle", "Kart pin bukja giňişleýin")}: {data.id}
@@ -120,11 +142,7 @@ export default function CardPinViewPage() {
<AlertDialogAction
disabled={isDeleting}
className="bg-destructive hover:bg-destructive/90"
onClick={() =>
deletePin(data.id, {
onSuccess: () => navigate("/card-pins"),
})
}
onClick={() => deletePin(data.id, { onSuccess: () => navigate("/card-pins") })}
>
{t("common.delete", "Poz")}
</AlertDialogAction>
@@ -143,33 +161,27 @@ export default function CardPinViewPage() {
</div>
</div>
{/* Main Info */}
<section className="bg-card border border-border rounded-lg px-6">
<InfoRow label="ID">
<span className="font-mono">{data.id}</span>
</InfoRow>
<InfoRow label={t("cardPin.createdAt", "Döredilen wagty")}>
{data.created_at}
</InfoRow>
<InfoRow label={t("cardPin.status", "Status")}>
<CardPinStatusBadge status={data.status} />
</InfoRow>
<InfoRow label={t("cardPin.note", "Bellik")}>
{data.note || "—"}
</InfoRow>
<InfoRow label={t("cardPin.createdBy", "Sargyt eden")}>
<span className="text-primary font-medium">
{data.created_by_label}
</span>
</InfoRow>
</section>
{/* ── Row 1: Meta + Kart + Lokasiýa ───────────────────────────────── */}
<BentoGrid cols={3}>
<BentoCard title={t("cardPin.metaSection", "Esasy maglumatlar")}>
<InfoRow label="ID">
<span className="font-mono">{data.id}</span>
</InfoRow>
<InfoRow label={t("cardPin.createdAt", "Döredilen wagty")}>
{data.created_at}
</InfoRow>
<InfoRow label={t("cardPin.status", "Status")}>
<CardPinStatusBadge status={data.status} />
</InfoRow>
<InfoRow label={t("cardPin.note", "Bellik")}>
{data.note || "—"}
</InfoRow>
<InfoRow label={t("cardPin.createdBy", "Sargyt eden")}>
<span className="text-primary font-medium">{data.created_by_label}</span>
</InfoRow>
</BentoCard>
{/* 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">
<BentoCard title={t("cardPin.cardSection", "Kart")}>
<InfoRow label={t("cardPin.cardNumber", "Kart belgisi")}>
<span className="font-mono tracking-wider">{data.card_number}</span>
</InfoRow>
@@ -179,74 +191,70 @@ export default function CardPinViewPage() {
<InfoRow label={t("cardPin.cardExpireYear", "Kart Möhleti (ýyl)")}>
—
</InfoRow>
</div>
</section>
</BentoCard>
{/* 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">
<BentoCard title={t("cardPin.locationSection", "Lokasiýa")}>
<InfoRow label={t("cardPin.province", "Welaýat")}>
{data.province_label}
</InfoRow>
<InfoRow label={t("cardPin.branch", "Şahamça")}>
<span className="text-primary font-medium">
{data.branch_label}
</span>
<span className="text-primary font-medium">{data.branch_label}</span>
</InfoRow>
</div>
</section>
</BentoCard>
</BentoGrid>
{/* Şahsy maglumatlar */}
<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.personalSection", "Şahsy maglumatlar")}
</h2>
<div className="divide-y divide-border">
{/* ── Row 2: Şahsy + Pasport maglumatlary ─────────────────────────── */}
<BentoGrid cols={2}>
<BentoCard title={t("cardPin.personalSection", "Şahsy maglumatlar")}>
<InfoRow label={t("cardPin.fullName", "Doly ady")}>
{`${data.last_name} ${data.first_name} ${data.father_name}`}
</InfoRow>
<InfoRow label={t("cardPin.birthDate", "Doglan güni")}>
{data.birth_date}
</InfoRow>
<InfoRow label={t("cardPin.phone", "Telefon")}>+{data.phone}</InfoRow>
</div>
</section>
<InfoRow label={t("cardPin.phone", "Telefon")}>
+{data.phone}
</InfoRow>
</BentoCard>
{/* 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">
<BentoCard title={t("cardPin.passportSection", "Pasport")}>
<InfoRow label={t("cardPin.passportSeries", "Pasport seriýasy")}>
{data.passport_series}
</InfoRow>
<InfoRow label={t("cardPin.passportNumber", "Pasport belgisi")}>
{data.passport_number}
</InfoRow>
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
</BentoCard>
</BentoGrid>
{/* ── Row 3: Passport images ───────────────────────────────────────── */}
<BentoGrid cols={4}>
<BentoCard title={t("cardPin.passportFile1", "Sahypa 1")}>
<PassportImage
label={t("cardPin.passportFile1", "Pasport (sahypa 1)")}
url={data.passport_file_1}
/>
</BentoCard>
<BentoCard title={t("cardPin.passportFile2", "Sahypa 2-3")}>
<PassportImage
label={t("cardPin.passportFile2", "Pasport (2-3-nji sahypa)")}
url={data.passport_file_2}
/>
</BentoCard>
<BentoCard title={t("cardPin.passportFile3", "Sahypa 8-9")}>
<PassportImage
label={t("cardPin.passportFile3", "Pasport (8-9 sahypa)")}
url={data.passport_file_3}
/>
</BentoCard>
<BentoCard title={t("cardPin.passportFile4", "Sahypa 32")}>
<PassportImage
label={t("cardPin.passportFile4", "Pasport (32-nji sahypa)")}
url={data.passport_file_4}
/>
</div>
</section>
</BentoCard>
</BentoGrid>
</div>
);
}
)
}

View File

@@ -1,8 +1,8 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Download, Eye, Pencil, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Download, Eye, Pencil, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
@@ -12,60 +12,84 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar, type ColumnMeta } from '@/components/dataTableToolbar'
import type { VisibilityState } from '@tanstack/react-table'
} from "@/components/ui/alert-dialog";
import { DataTable, type ColumnDef } from "@/components/dataTable";
import {
DataTableToolbar,
type ColumnMeta,
} from "@/components/dataTableToolbar";
import type { VisibilityState } from "@tanstack/react-table";
import {
useCardRequisites,
useDeleteCardRequisite,
useDownloadCardRequisite,
} from '@/features/cardRequisites/hooks/useCardRequisites'
import type { CardRequisite, CardRequisiteStatus } from '@/features/cardRequisites/api/cardRequisitesApi'
} from "@/features/cardRequisites/hooks/useCardRequisites";
import type {
CardRequisite,
CardRequisiteStatus,
} from "@/features/cardRequisites/api/cardRequisitesApi";
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_BADGE: Record<CardRequisiteStatus, { label: string; className: string }> = {
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' },
}
const STATUS_BADGE: Record<
CardRequisiteStatus,
{ label: string; className: string }
> = {
pending: {
label: "Garaşylýar",
className: "bg-yellow-500/15 text-yellow-500 border-yellow-500/20",
},
approved: {
label: "Tassyklanan",
className: "bg-emerald-500/15 text-emerald-500 border-emerald-500/20",
},
rejected: {
label: "Ret edilen",
className: "bg-red-500/15 text-red-500 border-red-500/20",
},
};
function StatusBadge({ status }: { status: CardRequisiteStatus }) {
const cfg = STATUS_BADGE[status] ?? STATUS_BADGE.pending
const cfg = STATUS_BADGE[status] ?? STATUS_BADGE.pending;
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}
</span>
)
);
}
// ─── Page ─────────────────────────────────────────────────────────────────────
const PER_PAGE = 25
const PER_PAGE = 25;
export default function CardRequisitesPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { t } = useTranslation();
const navigate = useNavigate();
const [page, setPage] = useState(1)
const [perPage, setPerPage] = useState(PER_PAGE)
const [search, setSearch] = useState('')
const [deleteId, setDeleteId] = useState<string | null>(null)
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>([])
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE);
const [search, setSearch] = useState("");
const [deleteId, setDeleteId] = useState<string | null>(null);
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
const [columnOrder, setColumnOrder] = useState<string[]>([]);
const { data, isLoading } = useCardRequisites({ page, per_page: perPage, search })
const deleteMutation = useDeleteCardRequisite()
const downloadMutation = useDownloadCardRequisite()
const { data, isLoading } = useCardRequisites({
page,
per_page: perPage,
search,
});
const deleteMutation = useDeleteCardRequisite();
const downloadMutation = useDownloadCardRequisite();
// ── Columns ──────────────────────────────────────────────────────────────────
const columns: ColumnDef<CardRequisite>[] = [
{
id: 'id',
accessorKey: 'id',
header: t('ID', 'ID'),
id: "id",
accessorKey: "id",
header: t("ID", "ID"),
cell: ({ row }) => (
<button
className="text-primary font-medium hover:underline text-left"
@@ -76,81 +100,94 @@ export default function CardRequisitesPage() {
),
},
{
id: 'card_type',
accessorKey: 'card_type',
header: t('Card type', 'GÖRNÜŞI'),
id: "card_type",
accessorKey: "card_type",
header: t("Card type", "GÖRNÜŞI"),
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',
accessorKey: 'created_at',
header: t('Created at', 'DÖREDILEN WAGTY'),
id: "created_at",
accessorKey: "created_at",
header: t("Created at", "DÖREDILEN WAGTY"),
cell: ({ row }) => (
<span className="text-foreground">{row.original.created_at}</span>
),
},
{
id: 'province_name',
accessorKey: 'province_name',
header: t('Province', 'WELAÝAT'),
id: "province_name",
accessorKey: "province_name",
header: t("Province", "WELAÝAT"),
cell: ({ row }) => (
<span className="text-foreground">{row.original.province_name ?? '—'}</span>
<span className="text-foreground">
{row.original.province_name ?? "—"}
</span>
),
},
{
id: 'branch_name',
accessorKey: 'branch_name',
header: t('Branch', 'ŞAHAMÇA'),
id: "branch_name",
accessorKey: "branch_name",
header: t("Branch", "ŞAHAMÇA"),
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',
accessorKey: 'first_name',
header: t('First name', 'ADY'),
id: "first_name",
accessorKey: "first_name",
header: t("First name", "ADY"),
cell: ({ row }) => <span>{row.original.first_name}</span>,
},
{
id: 'last_name',
accessorKey: 'last_name',
header: t('Last name', 'FAMILIÝASY'),
id: "last_name",
accessorKey: "last_name",
header: t("Last name", "FAMILIÝASY"),
cell: ({ row }) => <span>{row.original.last_name}</span>,
},
{
id: 'status',
accessorKey: 'status',
header: t('Status', 'STATUS'),
id: "status",
accessorKey: "status",
header: t("Status", "STATUS"),
cell: ({ row }) => <StatusBadge status={row.original.status} />,
},
{
id: 'actions',
header: '',
id: "actions",
header: "",
enableHiding: false,
cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end">
<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)}
>
<Download size={14} />
</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}`)}
>
<Eye size={14} />
</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`)}
>
<Pencil size={14} />
</Button>
<Button
variant="ghost" size="icon"
variant="ghost"
size="icon"
className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setDeleteId(row.original.id)}
>
@@ -159,94 +196,109 @@ export default function CardRequisitesPage() {
</div>
),
},
]
];
// ── Column meta for toolbar ───────────────────────────────────────────────────
const columnMeta: ColumnMeta[] = columns
.filter((c) => c.id !== 'actions')
.filter((c) => c.id !== "actions")
.map((c) => ({
id: c.id!,
label: typeof c.header === 'string' ? c.header : c.id!,
}))
label: typeof c.header === "string" ? c.header : c.id!,
}));
// ── Pagination ────────────────────────────────────────────────────────────────
const total = data?.total ?? 0
const totalPages = Math.ceil(total / perPage)
const total = data?.total ?? 0;
const totalPages = Math.ceil(total / perPage);
const handleDelete = async () => {
if (!deleteId) return
await deleteMutation.mutateAsync(deleteId)
setDeleteId(null)
}
if (!deleteId) return;
await deleteMutation.mutateAsync(deleteId);
setDeleteId(null);
};
return (
<div className="space-y-4">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t('Card requisites', 'Kart rekwizitler')}
{t("Card requisites", "Kart rekwizitler")}
</h1>
</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 */}
<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) }}
/>
{/* 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}
/>
{/* 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}
/>
</div>
{/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialog
open={deleteId !== null}
onOpenChange={(open) => !open && setDeleteId(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('Are you sure?', 'Eminsiňizmi?')}</AlertDialogTitle>
<AlertDialogTitle>
{t("Are you sure?", "Eminsiňizmi?")}
</AlertDialogTitle>
<AlertDialogDescription>
{t(
'This action cannot be undone.',
'Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.',
"This action cannot be undone.",
"Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('Cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogCancel>{t("Cancel", "Ýatyr")}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
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>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
);
}

View File

@@ -157,6 +157,9 @@ export default function CardTransactionsPage() {
</h1>
</div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */}
<DataTableToolbar
searchValue={search}
@@ -190,6 +193,7 @@ export default function CardTransactionsPage() {
totalCount={total}
onPageChange={setPage}
/>
</div>
{/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>

View File

@@ -19,112 +19,127 @@ import {
useDeleteCardOrder,
} from "@/features/orderNewCard/hooks/useOrderNewCard";
import type { CardOrderStatus } from "@/features/orderNewCard/api/orderNewCardApi";
import {
InfoRow,
Section,
PassportImage,
} from "@/components/viewPageComponents";
import { InfoRow, PassportImage } from "@/components/viewPageComponents";
// ─── Status badge ─────────────────────────────────────────────────────────────
const STATUS_CFG: Record<
CardOrderStatus,
{ label: string; className: string; icon: string }
> = {
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",
},
};
const STATUS_CFG: Record<CardOrderStatus, { label: string; className: string; icon: string }> = {
PENDING: { label: "Garaşylýar", icon: "⏳", className: "bg-amber-500/10 text-amber-400 border border-amber-500/20" },
APPROVED: { label: "Tassyklandy", icon: "✓", className: "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20" },
REJECTED: { label: "Ýatyryldy", icon: "✕", className: "bg-red-500/10 text-red-400 border border-red-500/20" },
}
function StatusBadge({ status }: { status: CardOrderStatus }) {
const cfg = STATUS_CFG[status];
const cfg = STATUS_CFG[status]
return (
<span
className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-bold tracking-wide ${cfg.className}`}
>
<span 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>
{cfg.label}
</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() {
return (
<div className="space-y-6">
<div className="flex flex-col gap-4">
<Skeleton className="h-8 w-64" />
<div className="space-y-3">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-10 w-full" />
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{Array.from({ length: 4 }).map((_, i) => (
<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>
);
)
}
// ─── CardOrderDetailPage ──────────────────────────────────────────────────────
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function CardOrderDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { t } = useTranslation();
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const { t } = useTranslation()
const [deleteOpen, setDeleteOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false)
const { data: order, isLoading } = useCardOrderById(id ?? "");
const deleteMutation = useDeleteCardOrder();
const { data: order, isLoading } = useCardOrderById(id ?? "")
const deleteMutation = useDeleteCardOrder()
const handleDelete = async () => {
if (!id) return;
await deleteMutation.mutateAsync(id);
navigate("/order-new-card");
};
if (!id) return
await deleteMutation.mutateAsync(id)
navigate("/order-new-card")
}
if (isLoading) return <DetailSkeleton />;
if (isLoading) return <DetailSkeleton />
if (!order)
return (
<p className="text-muted-foreground text-sm">
{t("common.notFound", "Tapylmady")}
</p>
);
)
return (
<div>
{/* Header */}
<div className="flex items-start justify-between mb-6 gap-4">
<div>
<h1 className="text-xl font-semibold text-foreground">
{t("cardOrder.detailTitle", "Kart sargyt giriş üçin")}:{" "}
<span className="text-primary font-mono">{order.id}</span>
</h1>
</div>
<div className="flex flex-col gap-6">
{/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-start justify-between gap-4">
<h1 className="text-xl font-semibold text-foreground">
{t("cardOrder.detailTitle", "Kart sargyt giriş üçin")}:{" "}
<span className="text-primary font-mono">{order.id}</span>
</h1>
<div className="flex items-center gap-2 shrink-0">
<Button
variant="outline"
size="icon"
title={t("common.print", "Çap etmek")}
>
<Button variant="outline" size="icon" title={t("common.print", "Çap etmek")}>
<Printer size={15} />
</Button>
<Button
variant="outline"
size="icon"
title={t("common.export", "Eksport")}
>
<Button variant="outline" size="icon" title={t("common.export", "Eksport")}>
<Download size={15} />
</Button>
<Button
@@ -145,127 +160,110 @@ export default function CardOrderDetailPage() {
</div>
</div>
{/* Main info */}
<Section title="">
<InfoRow label="ID">{order.id}</InfoRow>
<InfoRow label={t("cardOrder.field.createdAt", "Döredilen wagty")}>
{order.createdAt}
</InfoRow>
<InfoRow label={t("cardOrder.field.isPaid", "Tölenen")}>
<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"
}`}
>
{order.isPaid ? "✓" : "✕"}
</span>
</InfoRow>
<InfoRow label={t("cardOrder.field.status", "Status")}>
<StatusBadge status={order.status} />
</InfoRow>
<InfoRow label={t("cardOrder.field.note", "Bellik")}>
{order.note ?? "—"}
</InfoRow>
<InfoRow label={t("cardOrder.field.createdBy", "Sargyt eden")}>
<span className="text-primary font-medium">{order.createdBy}</span>
</InfoRow>
</Section>
{/* ── Row 1: Meta + Kart + Lokasiýa ───────────────────────────────── */}
<BentoGrid cols={3}>
<BentoCard title={t("cardOrder.section.meta", "Esasy maglumatlar")}>
<InfoRow label="ID">{order.id}</InfoRow>
<InfoRow label={t("cardOrder.field.createdAt", "Döredilen wagty")}>
{order.createdAt}
</InfoRow>
<InfoRow label={t("cardOrder.field.status", "Status")}>
<StatusBadge status={order.status} />
</InfoRow>
<InfoRow label={t("cardOrder.field.isPaid", "Tölenen")}>
<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"}`}>
{order.isPaid ? "✓" : "✕"}
</span>
</InfoRow>
<InfoRow label={t("cardOrder.field.note", "Bellik")}>
{order.note ?? "—"}
</InfoRow>
<InfoRow label={t("cardOrder.field.createdBy", "Sargyt eden")}>
<span className="text-primary font-medium">{order.createdBy}</span>
</InfoRow>
</BentoCard>
{/* Kart */}
<Section title={t("cardOrder.section.card", "Kart")}>
<InfoRow
label={t(
"cardOrder.field.issuanceReason",
"Kartyň çykarylmagynyň sebäbi",
)}
>
<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>
<BentoCard title={t("cardOrder.section.card", "Kart")}>
<InfoRow label={t("cardOrder.field.issuanceReason", "Kartyň çykarylmagynyň sebäbi")}>
<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>
</BentoCard>
{/* Lokasiýa */}
<Section title={t("cardOrder.section.location", "Lokasiýa")}>
<InfoRow label={t("cardOrder.field.province", "Welaýat")}>
{order.provinceName}
</InfoRow>
<InfoRow label={t("cardOrder.field.branch", "Şahamça")}>
<span className="text-cyan-400 font-medium">{order.branchName}</span>
</InfoRow>
</Section>
<BentoCard title={t("cardOrder.section.location", "Lokasiýa")}>
<InfoRow label={t("cardOrder.field.province", "Welaýat")}>
{order.provinceName}
</InfoRow>
<InfoRow label={t("cardOrder.field.branch", "Şahamça")}>
<span className="text-cyan-400 font-medium">{order.branchName}</span>
</InfoRow>
</BentoCard>
</BentoGrid>
{/* Şahsy maglumatlar */}
<Section title={t("cardOrder.section.personal", "Şahsy maglumatlar")}>
<InfoRow label={t("cardOrder.field.fullName", "Doly ady")}>
{[order.lastName, order.firstName, order.middleName]
.filter(Boolean)
.join(" ")}
</InfoRow>
<InfoRow label={t("cardOrder.field.birthDate", "Doglan güni")}>
{order.birthDate}
</InfoRow>
<InfoRow label={t("cardOrder.field.phone", "Telefon")}>
{order.phone}
</InfoRow>
<InfoRow label={t("cardOrder.field.phoneExtra", "Telefon goşmaça")}>
{order.phoneExtra ?? "—"}
</InfoRow>
<InfoRow label={t("cardOrder.field.citizenship", "Raýatlyk")}>
{order.citizenship}
</InfoRow>
<InfoRow
label={t(
"cardOrder.field.registeredAddress",
"Ý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>
{/* ── Row 2: Şahsy maglumatlar (full width — many fields) ─────────── */}
<BentoGrid cols={2}>
<BentoCard title={t("cardOrder.section.personal", "Şahsy maglumatlar")}>
<InfoRow label={t("cardOrder.field.fullName", "Doly ady")}>
{[order.lastName, order.firstName, order.middleName].filter(Boolean).join(" ")}
</InfoRow>
<InfoRow label={t("cardOrder.field.birthDate", "Doglan güni")}>
{order.birthDate}
</InfoRow>
<InfoRow label={t("cardOrder.field.citizenship", "Raýatlyk")}>
{order.citizenship}
</InfoRow>
<InfoRow label={t("cardOrder.field.registeredAddress", "Ýazgy edilen salgy")}>
{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 we wezipesi")}>
{order.workplace}
</InfoRow>
</BentoCard>
{/* Pasport faýýlar */}
<Section title={t("cardOrder.section.passportFiles", "Pasport faýýlar")}>
<PassportImage
label={t("cardOrder.field.passportPage1", "Pasport (sahypa 1)")}
url={order.passportFiles.page1}
/>
<PassportImage
label={t(
"cardOrder.field.passportPage23",
"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>
<BentoCard title={t("cardOrder.section.contacts", "Kontakt")}>
<InfoRow label={t("cardOrder.field.phone", "Telefon")}>
{order.phone}
</InfoRow>
<InfoRow label={t("cardOrder.field.phoneExtra", "Telefon goşmaça")}>
{order.phoneExtra ?? "—"}
</InfoRow>
</BentoCard>
</BentoGrid>
{/* 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}>
<AlertDialogContent>
<AlertDialogHeader>
@@ -273,10 +271,7 @@ export default function CardOrderDetailPage() {
{t("cardOrder.deleteTitle", "Pozmak isleýärsiňizmi?")}
</AlertDialogTitle>
<AlertDialogDescription>
{t(
"cardOrder.deleteDescription",
"Bu kart sargyt hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.",
)}
{t("cardOrder.deleteDescription", "Bu kart sargyt hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -292,6 +287,7 @@ export default function CardOrderDetailPage() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
)
}

View File

@@ -1,12 +1,12 @@
// pages/CurrencyRatesPage.tsx
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Eye, Pencil, Trash2 } from 'lucide-react'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import { Button } from '@/components/ui/button'
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Eye, Pencil, Trash2 } from "lucide-react";
import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar } from "@/components/dataTableToolbar";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
@@ -16,52 +16,63 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { useGetCurrencyRates, useDeleteCurrencyRate } from '@/features/currencyRates/hooks/useCurrencyRates'
import type { CurrencyRate } from '@/features/currencyRates/api/currencyRatesApi'
} from "@/components/ui/alert-dialog";
import {
useGetCurrencyRates,
useDeleteCurrencyRate,
} from "@/features/currencyRates/hooks/useCurrencyRates";
import type { CurrencyRate } from "@/features/currencyRates/api/currencyRatesApi";
// ─── Column visibility defaults ───────────────────────────────────────────────
const DEFAULT_VISIBILITY = { id: true, currencyFrom: true, currencyTo: true, value: true }
const DEFAULT_ORDER = ['id', 'currencyFrom', 'currencyTo', 'value', 'actions']
const DEFAULT_VISIBILITY = {
id: true,
currencyFrom: true,
currencyTo: true,
value: true,
};
const DEFAULT_ORDER = ["id", "currencyFrom", "currencyTo", "value", "actions"];
// ─── CurrencyRatesPage ────────────────────────────────────────────────────────
export default function CurrencyRatesPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { t } = useTranslation();
const navigate = useNavigate();
const [page, setPage] = useState(1)
const [perPage] = useState(25)
const [search, setSearch] = useState('')
const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>(DEFAULT_VISIBILITY)
const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER)
const [deleteId, setDeleteId] = useState<number | null>(null)
const [page, setPage] = useState(1);
const [perPage] = useState(25);
const [search, setSearch] = useState("");
const [columnVisibility, setColumnVisibility] =
useState<Record<string, boolean>>(DEFAULT_VISIBILITY);
const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER);
const [deleteId, setDeleteId] = useState<number | null>(null);
const { data, isLoading } = useGetCurrencyRates({ page, perPage, search })
const deleteMutation = useDeleteCurrencyRate()
const { data, isLoading } = useGetCurrencyRates({ page, perPage, search });
const deleteMutation = useDeleteCurrencyRate();
const handleDeleteConfirm = async () => {
if (deleteId === null) return
await deleteMutation.mutateAsync(deleteId)
setDeleteId(null)
}
if (deleteId === null) return;
await deleteMutation.mutateAsync(deleteId);
setDeleteId(null);
};
const handleSearchChange = (val: string) => {
setSearch(val)
setPage(1)
}
setSearch(val);
setPage(1);
};
// ─── Columns ──────────────────────────────────────────────────────────────
const columns: ColumnDef<CurrencyRate>[] = [
{
accessorKey: 'id',
header: 'ID',
accessorKey: "id",
header: "ID",
cell: ({ row }) => (
<button
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}
</button>
@@ -69,29 +80,35 @@ export default function CurrencyRatesPage() {
size: 80,
},
{
accessorKey: 'currencyFrom',
header: t('currencyRates.columns.currencyFrom', 'CURRENCY FROM'),
accessorKey: "currencyFrom",
header: t("currencyRates.columns.currencyFrom", "CURRENCY FROM"),
cell: ({ row }) => (
<span className="font-medium text-foreground">{row.original.currencyFrom}</span>
<span className="font-medium text-foreground">
{row.original.currencyFrom}
</span>
),
},
{
accessorKey: 'currencyTo',
header: t('currencyRates.columns.currencyTo', 'CURRENCY TO'),
accessorKey: "currencyTo",
header: t("currencyRates.columns.currencyTo", "CURRENCY TO"),
cell: ({ row }) => (
<span className="font-medium text-foreground">{row.original.currencyTo}</span>
<span className="font-medium text-foreground">
{row.original.currencyTo}
</span>
),
},
{
accessorKey: 'value',
header: t('currencyRates.columns.value', 'VALUE'),
accessorKey: "value",
header: t("currencyRates.columns.value", "VALUE"),
cell: ({ row }) => (
<span className="text-foreground tabular-nums">{row.original.value}</span>
<span className="text-foreground tabular-nums">
{row.original.value}
</span>
),
},
{
id: 'actions',
header: '',
id: "actions",
header: "",
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
@@ -101,7 +118,7 @@ export default function CurrencyRatesPage() {
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/currency-rates/${row.original.id}`)}
title={t('common.view', 'Görmek')}
title={t("common.view", "Görmek")}
>
<Eye size={15} />
</Button>
@@ -110,7 +127,7 @@ export default function CurrencyRatesPage() {
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/currency-rates/${row.original.id}/edit`)}
title={t('common.edit', 'Üýtgetmek')}
title={t("common.edit", "Üýtgetmek")}
>
<Pencil size={15} />
</Button>
@@ -119,7 +136,7 @@ export default function CurrencyRatesPage() {
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteId(row.original.id)}
title={t('common.delete', 'Pozmak')}
title={t("common.delete", "Pozmak")}
>
<Trash2 size={15} />
</Button>
@@ -127,82 +144,92 @@ export default function CurrencyRatesPage() {
),
size: 120,
},
]
];
const columnMeta = columns
.filter((c) => 'accessorKey' in c && c.accessorKey)
.filter((c) => "accessorKey" in c && c.accessorKey)
.map((c) => ({
id: String(('accessorKey' in c ? c.accessorKey : c.id) ?? ''),
label: typeof c.header === 'string' ? c.header : String(('accessorKey' in c ? c.accessorKey : '') ?? ''),
}))
id: String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""),
label:
typeof c.header === "string"
? c.header
: String(("accessorKey" in c ? c.accessorKey : "") ?? ""),
}));
// ─── Render ───────────────────────────────────────────────────────────────
return (
<div className="p-6">
<h1 className="text-2xl font-semibold text-foreground mb-5">
{t('currencyRates.title', 'Walýuta kursy')}
{t("currencyRates.title", "Walýuta kursy")}
</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
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')}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
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}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
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}
/>
</div>
{/* Delete Confirmation Dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => { if (!open) setDeleteId(null) }}>
<AlertDialog
open={deleteId !== null}
onOpenChange={(open) => {
if (!open) setDeleteId(null);
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t('currencyRates.deleteDialog.title', 'Pozmak isleýärsiňizmi?')}
{t("currencyRates.deleteDialog.title", "Pozmak isleýärsiňizmi?")}
</AlertDialogTitle>
<AlertDialogDescription>
{t(
'currencyRates.deleteDialog.description',
'Bu amal yzyna gaýtarylyp bilinmez. Walýuta kursy hemişelik pozular.'
"currencyRates.deleteDialog.description",
"Bu amal yzyna gaýtarylyp bilinmez. Walýuta kursy hemişelik pozular.",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogCancel>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteConfirm}
disabled={deleteMutation.isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending
? t('common.deleting', 'Pozulýar...')
: t('common.delete', 'Pozmak')}
? t("common.deleting", "Pozulýar...")
: t("common.delete", "Pozmak")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
);
}

View File

@@ -1,9 +1,9 @@
// pages/VisaMasterSettingsPage.tsx
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Pencil, Trash2 } from 'lucide-react'
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Pencil, Trash2 } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
@@ -13,97 +13,82 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import {
useGetVisaMasterSettings,
useDeleteVisaMasterSetting,
} from '@/features/visaMasterSberSettings/hooks/useVisaMasterSettings'
import type { VisaMasterSetting } from '@/features/visaMasterSberSettings/api/visaMasterSberSettingsApi'
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar } from "@/components/dataTableToolbar";
import { useGetVisaMasterSettings, useDeleteVisaMasterSetting } from "@/features/visaMasterSberSettings/hooks/useVisaMasterSettings";
import type { VisaMasterSetting } from "@/features/visaMasterSberSettings/api/visaMasterSberSettingsApi";
// ─── Column defaults ──────────────────────────────────────────────────────────
const DEFAULT_VISIBILITY = { id: true, kod: true, ady: true, yazgy: true }
const DEFAULT_ORDER = ['id', 'kod', 'ady', 'yazgy', 'actions']
const DEFAULT_VISIBILITY = { id: true, kod: true, ady: true, yazgy: true };
const DEFAULT_ORDER = ["id", "kod", "ady", "yazgy", "actions"];
// ─── VisaMasterSettingsPage ───────────────────────────────────────────────────
export default function VisaMasterSettingsPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { t } = useTranslation();
const navigate = useNavigate();
const [page, setPage] = useState(1)
const [perPage] = useState(25)
const [search, setSearch] = useState('')
const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>(DEFAULT_VISIBILITY)
const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER)
const [deleteId, setDeleteId] = useState<number | null>(null)
const [page, setPage] = useState(1);
const [perPage] = useState(25);
const [search, setSearch] = useState("");
const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>(DEFAULT_VISIBILITY);
const [columnOrder, setColumnOrder] = useState(DEFAULT_ORDER);
const [deleteId, setDeleteId] = useState<number | null>(null);
const { data, isLoading } = useGetVisaMasterSettings({ page, perPage, search })
const deleteMutation = useDeleteVisaMasterSetting()
const { data, isLoading } = useGetVisaMasterSettings({ page, perPage, search });
const deleteMutation = useDeleteVisaMasterSetting();
const handleDeleteConfirm = async () => {
if (deleteId === null) return
await deleteMutation.mutateAsync(deleteId)
setDeleteId(null)
}
if (deleteId === null) return;
await deleteMutation.mutateAsync(deleteId);
setDeleteId(null);
};
const handleSearchChange = (val: string) => {
setSearch(val)
setPage(1)
}
setSearch(val);
setPage(1);
};
// ─── Columns ──────────────────────────────────────────────────────────────
const columns: ColumnDef<VisaMasterSetting>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="text-primary font-semibold">{row.original.id}</span>
),
accessorKey: "id",
header: "ID",
cell: ({ row }) => <span className="text-primary font-semibold">{row.original.id}</span>,
size: 80,
},
{
accessorKey: 'kod',
header: t('visaMasterSettings.columns.kod', 'KOD'),
cell: ({ row }) => (
<span className="font-medium text-foreground font-mono text-xs">
{row.original.kod}
</span>
),
accessorKey: "kod",
header: t("visaMasterSettings.columns.kod", "KOD"),
cell: ({ row }) => <span className="font-medium text-foreground font-mono text-xs">{row.original.kod}</span>,
},
{
accessorKey: 'ady',
header: t('visaMasterSettings.columns.ady', 'ADY'),
cell: ({ row }) => (
<span className="text-foreground">{row.original.ady}</span>
),
accessorKey: "ady",
header: t("visaMasterSettings.columns.ady", "ADY"),
cell: ({ row }) => <span className="text-foreground">{row.original.ady}</span>,
},
{
accessorKey: 'yazgy',
header: t('visaMasterSettings.columns.yazgy', 'YAZGY'),
cell: ({ row }) => (
<span className="text-foreground line-clamp-1 max-w-xs">{row.original.yazgy}</span>
),
accessorKey: "yazgy",
header: t("visaMasterSettings.columns.yazgy", "YAZGY"),
cell: ({ row }) => <span className="text-foreground line-clamp-1 max-w-xs">{row.original.yazgy}</span>,
},
{
id: 'actions',
header: '',
id: "actions",
header: "",
enableSorting: false,
enableHiding: false,
enableHiding: false,
cell: ({ row }) => (
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() =>
navigate(`/visa-master-sber-settings/${row.original.id}/edit`)
}
title={t('common.edit', 'Üýtgetmek')}
onClick={() => navigate(`/visa-master-sber-settings/${row.original.id}/edit`)}
title={t("common.edit", "Üýtgetmek")}
>
<Pencil size={15} />
</Button>
@@ -112,7 +97,7 @@ export default function VisaMasterSettingsPage() {
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteId(row.original.id)}
title={t('common.delete', 'Pozmak')}
title={t("common.delete", "Pozmak")}
>
<Trash2 size={15} />
</Button>
@@ -120,85 +105,78 @@ export default function VisaMasterSettingsPage() {
),
size: 100,
},
]
];
const columnMeta = columns
.filter((c) => 'accessorKey' in c && c.accessorKey)
.filter((c) => "accessorKey" in c && c.accessorKey)
.map((c) => ({
id: String(('accessorKey' in c ? c.accessorKey : c.id) ?? ''),
label: typeof c.header === 'string' ? c.header : String(('accessorKey' in c ? c.accessorKey : '') ?? ''),
}))
id: String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""),
label: typeof c.header === "string" ? c.header : String(("accessorKey" in c ? c.accessorKey : "") ?? ""),
}));
// ─── Render ───────────────────────────────────────────────────────────────
return (
<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">
{t('visaMasterSettings.title', 'Visa/Master, Sber sazlamalar')}
</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("visaMasterSettings.actions.create", "Visa/Master, Sber sazlamalar dörediň")}
onAction={() => navigate("/visa-master-sber-settings/create")}
/>
<DataTableToolbar
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')}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
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}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
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}
/>
</div>
{/* Delete Confirmation */}
<AlertDialog
open={deleteId !== null}
onOpenChange={(open) => { if (!open) setDeleteId(null) }}
onOpenChange={(open) => {
if (!open) setDeleteId(null);
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t('visaMasterSettings.deleteDialog.title', 'Pozmak isleýärsiňizmi?')}
</AlertDialogTitle>
<AlertDialogTitle>{t("visaMasterSettings.deleteDialog.title", "Pozmak isleýärsiňizmi?")}</AlertDialogTitle>
<AlertDialogDescription>
{t(
'visaMasterSettings.deleteDialog.description',
'Bu amal yzyna gaýtarylyp bilinmez. Sazlama hemişelik pozular.'
)}
{t("visaMasterSettings.deleteDialog.description", "Bu amal yzyna gaýtarylyp bilinmez. Sazlama hemişelik pozular.")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogCancel>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteConfirm}
disabled={deleteMutation.isPending}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleteMutation.isPending
? t('common.deleting', 'Pozulýar...')
: t('common.delete', 'Pozmak')}
{deleteMutation.isPending ? t("common.deleting", "Pozulýar...") : t("common.delete", "Pozmak")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
);
}

View File

@@ -303,7 +303,8 @@ export default function SberPaymentsListPage() {
<h1 className="text-xl font-semibold text-foreground">
Sber tolegier (talyplar ucin)
</h1>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */}
<DataTableToolbar
searchValue={search}
@@ -347,5 +348,6 @@ export default function SberPaymentsListPage() {
onPageChange={setPage}
/>
</div>
</div>
)
}

View File

@@ -215,6 +215,7 @@ export default function IntlPaymentsPage() {
</h1>
</div>
<MonthSelector value={month} onChange={(v) => { setMonth(v); setPage(1) }} />
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
@@ -262,6 +263,7 @@ export default function IntlPaymentsPage() {
totalCount={data?.meta?.total}
onPageChange={setPage}
/>
</div>
<AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>
<AlertDialogContent>

View File

@@ -1,6 +1,6 @@
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Trash2, Pencil, ChevronRight } from "lucide-react";
import { Trash2, Pencil } from "lucide-react";
import {
useLoanOrderMobileById,
useDeleteLoanOrderMobile,
@@ -14,57 +14,69 @@ import {
type StatusBadgeVariant,
} from "@/components/ui/statusBadge";
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
import {
InfoRow,
Section,
PassportImage,
AuditLog,
type AuditRowProps,
} from "@/components/viewPageComponents";
import { AuditRow, type AuditRowProps } from "@/components/viewPageComponents";
// ─── Status badge ─────────────────────────────────────────────────────────────
// ─── Status config ────────────────────────────────────────────────────────────
const STATUS_CONFIG = {
GARAŞYLÝAR: {
label: "Garaşylýar",
variant: "warning" as StatusBadgeVariant,
icon: AlertCircle,
},
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 }
>;
GARAŞYLÝAR: { label: "Garaşylýar", variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
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({
status,
}: {
status: LoanOrderMobileStatus;
}) {
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} />
);
function LoanOrderMobileStatusBadge({ status }: { status: LoanOrderMobileStatus }) {
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 ─────────────────────────────────────────────────────────────────
@@ -72,77 +84,72 @@ function LoanOrderMobilesViewSkeleton() {
return (
<div className="flex flex-col gap-4">
<Skeleton className="h-7 w-64" />
{[...Array(5)].map((_, i) => (
<div
key={i}
className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3"
>
<Skeleton className="h-4 w-32 mb-1" />
{[...Array(3)].map((_, j) => (
<Skeleton key={j} className="h-4 w-full" />
))}
</div>
))}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{[...Array(6)].map((_, i) => (
<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(3)].map((_, j) => (
<Skeleton key={j} className="h-4 w-full" />
))}
</div>
))}
</div>
</div>
);
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function LoanOrderMobilesViewPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const { id } = useParams<{ id: string }>();
const deleteMutation = useDeleteLoanOrderMobile();
const { t } = useTranslation()
const navigate = useNavigate()
const { id } = useParams<{ id: string }>()
const deleteMutation = useDeleteLoanOrderMobile()
const { data: order, isLoading } = useLoanOrderMobileById(id!);
const { data: order, isLoading } = useLoanOrderMobileById(id!)
const handleDelete = () => {
if (
!window.confirm(
t("loanOrderMobiles.deleteConfirm", "Bu sargyt pozulsynmy?"),
)
)
return;
if (!window.confirm(t("loanOrderMobiles.deleteConfirm", "Bu sargyt pozulsynmy?"))) return
deleteMutation.mutate(id!, {
onSuccess: () => {
toast.success(t("loanOrderMobiles.deleteSuccess", "Sargyt pozuldy"));
navigate("/loan-order-mobiles");
toast.success(t("loanOrderMobiles.deleteSuccess", "Sargyt pozuldy"))
navigate("/loan-order-mobiles")
},
onError: () => {
toast.error(
t("loanOrderMobiles.deleteError", "Pozma wagty ýalňyşlyk ýüze çykdy"),
);
toast.error(t("loanOrderMobiles.deleteError", "Pozma wagty ýalňyşlyk ýüze çykdy"))
},
});
};
})
}
if (isLoading) return <LoanOrderMobilesViewSkeleton />;
if (isLoading) return <LoanOrderMobilesViewSkeleton />
if (!order) {
return (
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
{t("common.notFound", "Tapylmady")}
</div>
);
)
}
// Replace with real audit data from API when available
const auditLogs: AuditRowProps[] = [
{
id: "44548",
id: "44548",
action: t("audit.actions.view", "Görmek"),
by: order.createdBy ?? "",
by: order.createdBy ?? "",
target: `${t("loanOrderMobiles.title", "Karz sargyt")}: ${order.id}`,
status: "FINISHED",
date: order.createdAt ?? "",
date: order.createdAt ?? "",
},
];
]
const hasCard = !!(order.cardNumber || order.cardName)
const hasGuarantor = !!(order.guarantor1Name || order.guarantor1CardNumber)
return (
<div className="flex flex-col">
{/* Page Header */}
<div className="flex items-center justify-between mb-5">
<div className="flex flex-col gap-6">
{/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t("loanOrderMobiles.view.title", "Karz sargyt giriş")}: {order.id}
</h1>
@@ -165,299 +172,270 @@ export default function LoanOrderMobilesViewPage() {
</div>
</div>
{/* ── Basic Info ─────────────────────────────────────────────────────── */}
<div className="bg-card border border-border rounded-xl overflow-hidden mb-6">
<InfoRow label="ID" value={order.id} />
{/* Status row — special render */}
<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>
{/* ── Row 1: Meta + Loan + Location ───────────────────────────────── */}
<BentoGrid cols={3}>
<BentoCard title={t("loanOrders.sections.meta", "Esasy maglumatlar")}>
<InfoRow label="ID" value={order.id} />
<InfoRow
label={t("loanOrders.fields.cardNumber", "Kart belgisi")}
value={order.cardNumber}
label={t("loanOrders.columns.status", "Status")}
>
<LoanOrderMobileStatusBadge status={order.status} />
</InfoRow>
<InfoRow
label={t("loanOrders.columns.createdAt", "Döredilen wagty")}
value={order.createdAt}
/>
<InfoRow
label={t("loanOrders.fields.cardName", "Kartdaky ady")}
value={order.cardName}
/>
</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()}
label={t("loanOrders.columns.branch", "Şahamça")}
value={order.branch}
isLink
/>
<InfoRow
label={t("loanOrders.fields.guarantorPassport", "Pasport")}
value={`${order.guarantor1PassportSerie || ""} ${order.guarantor1PassportNumber || ""}`.trim()}
label={t("loanOrders.fields.note", "Bellik")}
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
label={t("loanOrders.fields.guarantorSalary", "Ortaca zähmet haky")}
value={
order.guarantor1Salary
? String(order.guarantor1Salary)
: undefined
}
label={t("loanOrders.fields.loanAmount", "Karz möçberi")}
value={order.loanAmount ? String(order.loanAmount) : undefined}
/>
{order.guarantor1CardNumber && (
<div className="p-6 bg-slate-50 dark:bg-slate-900/50 border-t border-border flex items-center justify-center">
</BentoCard>
<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
cardNumber={order.guarantor1CardNumber}
cardName={order.guarantor1CardName}
expMonth={order.guarantor1CardExpMonth}
expYear={order.guarantor1CardExpYear}
variant="secondary"
cardNumber={order.cardNumber}
cardName={order.cardName}
expMonth={order.cardExpMonth}
expYear={order.cardExpYear}
variant="primary"
/>
</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 ──────────────────────────────────────────────────────── */}
<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>
{/* ── Row 3: Personal + Contacts ──────────────────────────────────── */}
<BentoGrid cols={2}>
<BentoCard 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")}
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
/>
</BentoCard>
<BentoCard title={t("loanOrders.sections.contacts", "Habarlaşmak")}>
<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}
/>
</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>
);
}
)
}

View File

@@ -1,6 +1,6 @@
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Trash2, Pencil, ChevronRight } from "lucide-react";
import { Trash2, Pencil } from "lucide-react";
import {
useLoanOrderById,
useDeleteLoanOrder,
@@ -15,50 +15,64 @@ import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
import type { LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi";
import {
InfoRow,
Section,
PassportImage,
AuditLog,
type AuditRowProps,
} from "@/components/viewPageComponents";
import { AuditRow, type AuditRowProps } from "@/components/viewPageComponents";
// ─── Status config ────────────────────────────────────────────────────────────
const STATUS_CONFIG = {
GARAŞYLÝAR: {
label: "Garaşylýar",
variant: "warning" as StatusBadgeVariant,
icon: AlertCircle,
},
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 }
>;
GARAŞYLÝAR: { label: "Garaşylýar", variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
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({
status,
function LoanOrderMobileStatusBadge({ status }: { status: LoanOrderMobileStatus }) {
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];
if (!cfg)
return (
<span className="text-xs text-muted-foreground">{String(status)}</span>
);
const spanClass =
span === "full" ? "sm:col-span-full" :
span === 2 ? "sm:col-span-2" :
span === 3 ? "sm:col-span-3" : ""
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 ─────────────────────────────────────────────────────────────────
@@ -67,73 +81,69 @@ function LoanOrderViewSkeleton() {
return (
<div className="flex flex-col gap-4">
<Skeleton className="h-7 w-64" />
{[...Array(5)].map((_, i) => (
<div
key={i}
className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3"
>
<Skeleton className="h-4 w-32 mb-1" />
{[...Array(3)].map((_, j) => (
<Skeleton key={j} className="h-4 w-full" />
))}
</div>
))}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{[...Array(6)].map((_, i) => (
<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(3)].map((_, j) => (
<Skeleton key={j} className="h-4 w-full" />
))}
</div>
))}
</div>
</div>
);
)
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function LoanOrderViewPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const { id } = useParams<{ id: string }>();
const deleteMutation = useDeleteLoanOrder();
const { t } = useTranslation()
const navigate = useNavigate()
const { id } = useParams<{ id: string }>()
const deleteMutation = useDeleteLoanOrder()
const { data: order, isLoading } = useLoanOrderById(id!);
const { data: order, isLoading } = useLoanOrderById(id!)
const handleDelete = () => {
if (!window.confirm(t("loanOrders.deleteConfirm", "Bu sargyt pozulsynmy?")))
return;
if (!window.confirm(t("loanOrders.deleteConfirm", "Bu sargyt pozulsynmy?"))) return
deleteMutation.mutate(id!, {
onSuccess: () => {
toast.success(t("loanOrders.deleteSuccess", "Sargyt pozuldy"));
navigate("/loan-orders");
toast.success(t("loanOrders.deleteSuccess", "Sargyt pozuldy"))
navigate("/loan-orders")
},
onError: () => {
toast.error(
t("loanOrders.deleteError", "Pozma wagty ýalňyşlyk ýüze çykdy"),
);
toast.error(t("loanOrders.deleteError", "Pozma wagty ýalňyşlyk ýüze çykdy"))
},
});
};
})
}
if (isLoading) return <LoanOrderViewSkeleton />;
if (isLoading) return <LoanOrderViewSkeleton />
if (!order) {
return (
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
{t("common.notFound", "Tapylmady")}
</div>
);
)
}
// Replace with real audit data from API when available
const auditLogs: AuditRowProps[] = [
{
id: "44548",
id: "44548",
action: t("audit.actions.view", "Görmek"),
by: order.createdBy ?? "",
by: order.createdBy ?? "",
target: `${t("loanOrders.title", "Karz sargyt")}: ${order.id}`,
status: "FINISHED",
date: order.createdAt ?? "",
date: order.createdAt ?? "",
},
];
]
return (
<div className="flex flex-col">
{/* Page Header */}
<div className="flex items-center justify-between mb-5">
<div className="flex flex-col gap-6">
{/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold text-foreground">
{t("loanOrders.view.title", "Karz sargyt giriş")}: {order.id}
</h1>
@@ -156,243 +166,192 @@ export default function LoanOrderViewPage() {
</div>
</div>
{/* ── Basic Info ─────────────────────────────────────────────────────── */}
<div className="bg-card border border-border rounded-xl overflow-hidden mb-6">
<InfoRow label="ID" value={order.id} />
<InfoRow
label={t("loanOrders.columns.createdAt", "Döredilen wagty")}
value={order.createdAt}
/>
{/* Status row — special render */}
<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.fields.amount", "Berlik")}
value={order.amount ? String(order.amount) : undefined}
/>
<InfoRow
label={t("loanOrders.fields.createdBy", "Sargyt eden")}
value={order.createdBy ?? undefined}
isLink
/>
</div>
{/* ── Row 1: Meta + Loan + Location ───────────────────────────────── */}
<BentoGrid cols={3}>
{/* Meta */}
<BentoCard title={t("loanOrders.sections.meta", "Esasy maglumatlar")}>
<InfoRow label="ID" value={order.id} />
<InfoRow
label={t("loanOrders.columns.createdAt", "Döredilen wagty")}
value={order.createdAt}
/>
<InfoRow
label={t("loanOrders.columns.status", "Status")}
>
<LoanOrderMobileStatusBadge status={order.status} />
</InfoRow>
<InfoRow
label={t("loanOrders.fields.amount", "Berlik")}
value={order.amount ? String(order.amount) : undefined}
/>
<InfoRow
label={t("loanOrders.fields.createdBy", "Sargyt eden")}
value={order.createdBy ?? undefined}
isLink
/>
</BentoCard>
{/* ── 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 mukdary")}
value={order.loanAmount ? String(order.loanAmount) : undefined}
/>
</Section>
{/* Loan */}
<BentoCard 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 mukdary")}
value={order.loanAmount ? String(order.loanAmount) : undefined}
/>
</BentoCard>
{/* ── Location ───────────────────────────────────────────────────────── */}
<Section title={t("loanOrders.sections.location", "Lokasiýa")}>
<InfoRow
label={t("loanOrders.columns.region", "Welaýat")}
value={order.region}
/>
<InfoRow
label={t("loanOrders.columns.branch", "Şahamça")}
value={order.branch}
isLink
/>
</Section>
{/* Location */}
<BentoCard title={t("loanOrders.sections.location", "Lokasiýa")}>
<InfoRow
label={t("loanOrders.columns.region", "Welaýat")}
value={order.region}
/>
<InfoRow
label={t("loanOrders.columns.branch", "Şahamça")}
value={order.branch}
isLink
/>
</BentoCard>
</BentoGrid>
{/* ── Personal Info ──────────────────────────────────────────────────── */}
<Section title={t("loanOrders.sections.personal", "Şahsy maglumatlar")}>
<InfoRow
label={t("loanOrders.fields.fullName", "Doly ady")}
value={order.fullName ?? `${order.firstName} ${order.lastName}`}
/>
<InfoRow
label={t("loanOrders.fields.education", "Bilimi")}
value={order.education ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.maritalStatus", "Maşgala ýagdaýy")}
value={order.maritalStatus ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.birthDate", "Doglan güni")}
value={order.birthDate ?? undefined}
/>
<InfoRow
label={t(
"loanOrders.fields.registeredAddress",
"Ýazgy edilen salgyňyz",
)}
value={order.registeredAddress ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.currentAddress", "Häzirki ýaşaýyş ýeri")}
value={order.currentAddress ?? undefined}
/>
</Section>
{/* ── Row 2: Personal + Contacts ──────────────────────────────────── */}
<BentoGrid cols={2}>
{/* Personal */}
<BentoCard title={t("loanOrders.sections.personal", "Şahsy maglumatlar")}>
<InfoRow
label={t("loanOrders.fields.fullName", "Doly ady")}
value={order.fullName ?? `${order.firstName} ${order.lastName}`}
/>
<InfoRow
label={t("loanOrders.fields.education", "Bilimi")}
value={order.education ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.maritalStatus", "Maşgala ýagdaýy")}
value={order.maritalStatus ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.birthDate", "Doglan güni")}
value={order.birthDate ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.registeredAddress", "Ýazgy edilen salgy")}
value={order.registeredAddress ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.currentAddress", "Häzirki ýaşaýyş ýeri")}
value={order.currentAddress ?? undefined}
/>
</BentoCard>
{/* ── 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.phoneAlt ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.homePhone", "Öý telefony")}
value={order.homePhone ?? undefined}
/>
</Section>
{/* Contacts */}
<BentoCard title={t("loanOrders.sections.contacts", "Habarlaşmak")}>
<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.phoneAlt ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.homePhone", "Öý telefony")}
value={order.homePhone ?? undefined}
/>
</BentoCard>
</BentoGrid>
{/* ── Employment ─────────────────────────────────────────────────────── */}
<Section title={t("loanOrders.sections.employment", "Iş")}>
<InfoRow
label={t(
"loanOrders.fields.employer",
"Işleýän edaranyň/kärhananyn ady",
)}
value={order.employer ?? undefined}
/>
<InfoRow
label={t(
"loanOrders.fields.deptPhone",
"Işgärler bölüminiň iş belgisi",
)}
value={order.deptPhone ?? 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.workCity ?? 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.employedSince ?? undefined}
/>
</Section>
{/* ── Row 3: Employment + Passport info ───────────────────────────── */}
<BentoGrid cols={2}>
{/* Employment */}
<BentoCard title={t("loanOrders.sections.employment", "Iş")}>
<InfoRow
label={t("loanOrders.fields.employer", "Kärhananyň ady")}
value={order.employer ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.deptPhone", "Işgärler bölüminiň belgisi")}
value={order.deptPhone ?? 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.workCity ?? 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.employedSince ?? undefined}
/>
</BentoCard>
{/* ── 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.passportIssuedBy ?? undefined}
/>
<InfoRow
label={t(
"loanOrders.fields.passportBirthPlace",
"Doglan ýeri (pasport)",
)}
value={order.passportBirthPlace ?? 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>
{/* Passport info */}
<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.passportIssuedBy ?? undefined}
/>
<InfoRow
label={t("loanOrders.fields.passportBirthPlace", "Doglan ýeri (pasport)")}
value={order.passportBirthPlace ?? undefined}
/>
</BentoCard>
</BentoGrid>
{/* ── Row 4: 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>
{/* ── 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>
);
}
)
}

View File

@@ -163,6 +163,8 @@ export default function OnlinePaymentHistoryPage() {
<h1 className="text-2xl font-semibold text-foreground mb-5">
{t("onlinePayments.title", "Onlaýn töleg taryhy")}
</h1>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
@@ -191,6 +193,7 @@ export default function OnlinePaymentHistoryPage() {
totalCount={data?.total ?? 0}
onPageChange={setPage}
/>
</div>
</div>
);
}

View File

@@ -172,6 +172,7 @@ export function CardTypesListPage() {
</h1>
</div>
</div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */}
<DataTableToolbar
@@ -209,6 +210,7 @@ export function CardTypesListPage() {
totalCount={data?.total}
onPageChange={setPage}
/>
</div>
{/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>

View File

@@ -180,6 +180,7 @@ export function CardReasonsListPage() {
</h1>
</div>
</div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */}
<DataTableToolbar
@@ -217,6 +218,7 @@ export function CardReasonsListPage() {
totalCount={data?.total}
onPageChange={setPage}
/>
</div>
{/* Delete dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>

View File

@@ -161,6 +161,7 @@ export default function LoanTypesListPage() {
<h1 className="text-xl font-semibold text-foreground mb-5">
{t('loanTypes.title', 'Karz görnüşleri')}
</h1>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
@@ -190,6 +191,7 @@ export default function LoanTypesListPage() {
totalCount={data?.total}
onPageChange={setPage}
/>
</div>
{/* Delete confirmation dialog */}
<AlertDialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>

View File

@@ -102,6 +102,7 @@ export default function RequiredDocumentsListPage() {
<h1 className="text-xl font-semibold text-foreground mb-4">
{t('loanDocuments.title', 'Karz gerekli resminamalary')}
</h1>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */}
<DataTableToolbar
@@ -134,5 +135,6 @@ export default function RequiredDocumentsListPage() {
onPageChange={setPage}
/>
</div>
</div>
)
}

View File

@@ -195,6 +195,7 @@ export function BranchesListPage() {
</h1>
</div>
</div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
@@ -230,6 +231,7 @@ export function BranchesListPage() {
totalCount={data?.total}
onPageChange={setPage}
/>
</div>
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
<AlertDialogContent>

View File

@@ -163,6 +163,7 @@ export function DistrictsListPage() {
</h1>
</div>
</div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
@@ -198,6 +199,7 @@ export function DistrictsListPage() {
totalCount={data?.total}
onPageChange={setPage}
/>
</div>
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
<AlertDialogContent>

View File

@@ -123,10 +123,9 @@ export default function PermissionsPage() {
<h1 className="text-2xl font-bold text-foreground">
{t('permissions.title', 'Rugsatlar')}
</h1>
<Button onClick={() => navigate('/settings/users/permissions/create')}>
{t('permissions.actions.create', 'Rugsat dörediň')}
</Button>
</div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */}
<DataTableToolbar
@@ -141,6 +140,8 @@ export default function PermissionsPage() {
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('permissions.actions.create', 'Rugsat dörediň')}
onAction={() => navigate('/settings/users/permissions/create')}
/>
{/* Table */}
@@ -158,6 +159,7 @@ export default function PermissionsPage() {
totalCount={data?.meta?.total ?? 0}
onPageChange={setPage}
/>
</div>
{/* Delete confirmation dialog */}
<AlertDialog

View File

@@ -123,10 +123,9 @@ export default function RolesPage() {
<h1 className="text-2xl font-bold text-foreground">
{t('roles.title', 'Rollar')}
</h1>
<Button onClick={() => navigate('/settings/users/roles/create')}>
{t('roles.actions.create', 'Rol dörediň')}
</Button>
</div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */}
<DataTableToolbar
@@ -141,6 +140,8 @@ export default function RolesPage() {
perPageOptions={[10, 25, 50, 100]}
perPage={perPage}
onPerPageChange={(v) => { setPerPage(v); setPage(1) }}
actionLabel={t('roles.actions.create', 'Rol dörediň')}
onAction={() => navigate('/settings/users/roles/create')}
/>
{/* Table */}
@@ -158,7 +159,7 @@ export default function RolesPage() {
totalCount={data?.meta?.total ?? 0}
onPageChange={setPage}
/>
</div>
{/* Delete confirmation dialog */}
<AlertDialog
open={deleteId !== null}

View File

@@ -190,8 +190,13 @@ export default function UsersListPage() {
// ── Render ─────────────────────────────────────────────────────────────────
return (
<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 */}
<DataTableToolbar
searchValue={search}
@@ -238,6 +243,7 @@ export default function UsersListPage() {
totalCount={data?.total}
onPageChange={setPage}
/>
</div>
{/* Delete confirm dialog */}
<AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>

View File

@@ -146,6 +146,7 @@ export default function ClientsPage() {
{t('clients.title', 'Müşderiler')}
</h1>
</div>
<div className="bg-card border border-border rounded-xl p-4">
<DataTableToolbar
searchValue={search}
@@ -194,6 +195,7 @@ export default function ClientsPage() {
onPageChange={setPage}
enableRowSelection
/>
</div>
<AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
<AlertDialogContent>

View File

@@ -13,27 +13,158 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} 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 { DataTableToolbar } from '@/components/dataTableToolbar'
import { useClient, useDeleteClient } from '@/features/clients/hooks/useClients'
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() {
const { id } = useParams<{ id: string }>()
const clientId = Number(id)
const { t } = useTranslation()
const navigate = useNavigate()
const { id } = useParams<{ id: string }>()
const clientId = Number(id)
const { t } = useTranslation()
const navigate = useNavigate()
const deleteMutation = useDeleteClient()
const { data: client, isLoading } = useClient(clientId)
const [deleteOpen, setDeleteOpen] = useState(false)
const [roleSearch, setRoleSearch] = useState('')
const [permSearch, setPermSearch] = useState('')
const [deleteOpen, setDeleteOpen] = useState(false)
const [roleSearch, setRoleSearch] = useState('')
const [permSearch, setPermSearch] = useState('')
const [branchSearch, setBranchSearch] = useState('')
const [loanSearch, setLoanSearch] = useState('')
const [cardSearch, setCardSearch] = useState('')
const [loanSearch, setLoanSearch] = useState('')
const [cardSearch, setCardSearch] = useState('')
// ── Role columns ──────────────────────────────────────────────────────────
const roleColumns: ColumnDef<ClientRole>[] = [
{
@@ -71,6 +202,8 @@ export default function ClientDetailPage() {
},
]
// ── Branch columns ────────────────────────────────────────────────────────
const branchColumns: ColumnDef<ClientBranch>[] = [
{
accessorKey: 'id',
@@ -112,6 +245,8 @@ export default function ClientDetailPage() {
},
]
// ── Loading ───────────────────────────────────────────────────────────────
if (isLoading) {
return (
<div className="p-6 space-y-4">
@@ -125,104 +260,195 @@ export default function ClientDetailPage() {
if (!client) return null
const auditLogs = (client.auditLogs ?? []).map((log: ClientAuditLog) => ({
id: String(log.id),
id: String(log.id),
action: log.actionName,
by: log.performedBy,
by: log.performedBy,
target: log.target,
status: log.status,
date: log.createdAt,
date: log.createdAt,
}))
const filteredRoles = (client.roles ?? []).filter((r) =>
r.name.toLowerCase().includes(roleSearch.toLowerCase()) || r.code.toLowerCase().includes(roleSearch.toLowerCase()),
const filteredRoles = (client.roles ?? []).filter((r) =>
r.name.toLowerCase().includes(roleSearch.toLowerCase()) ||
r.code.toLowerCase().includes(roleSearch.toLowerCase()),
)
const filteredBranches = (client.branches ?? []).filter((b) =>
b.name.toLowerCase().includes(branchSearch.toLowerCase()),
)
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">
{t('clients.detailTitle', 'Müşderi giňişleýin')}: {client.name}
</h1>
<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} />
</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} />
</Button>
</div>
</div>
<Section>
<InfoRow label="ID" value={client.id} />
<InfoRow label={t('clients.fields.username', 'Ulanyjy ady')} value={client.username} />
<InfoRow label={t('clients.fields.name', 'Ady')} value={client.name} />
<InfoRow label={t('clients.fields.phone', 'Telefon')} value={client.phone ?? '—'} />
<InfoRow label={t('clients.fields.email', 'E-poçta')} value={client.email ?? '—'} />
<InfoRow label={t('clients.fields.isActive', 'Işjeň')}>
{client.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>
)}
</InfoRow>
</Section>
{/* ── Row 1: Esasy maglumatlar + Kontakt ──────────────────────────── */}
<BentoGrid cols={2}>
<BentoCard title={t('clients.sections.basic', 'Esasy maglumatlar')}>
<InfoRow label="ID" value={client.id} />
<InfoRow
label={t('clients.fields.username', 'Ulanyjy ady')}
value={client.username}
/>
<InfoRow
label={t('clients.fields.name', 'Ady')}
value={client.name}
/>
<InfoRow label={t('clients.fields.isActive', 'Işjeň')}>
<ActiveIndicator active={client.isActive} />
</InfoRow>
</BentoCard>
<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) ? (
<BentoCard title={t('clients.sections.contact', 'Kontakt')}>
<InfoRow
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 />
) : (
<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 title={t('clients.sections.permissions', 'Rugsatlar')} actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')} 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={() => {}} />
) : null}
{/* ── Rugsatlar ────────────────────────────────────────────────────── */}
<CollapsibleSection
title={t('clients.sections.permissions', 'Rugsatlar')}
actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')}
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 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) ? (
{/* ── Şahamçalar ───────────────────────────────────────────────────── */}
<CollapsibleSection
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 />
) : (
<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 title={t('clients.sections.loanOrders', 'Karz sargyt')} actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')} 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={() => {}} />
) : null}
{/* ── Karz sargyt ──────────────────────────────────────────────────── */}
<CollapsibleSection
title={t('clients.sections.loanOrders', 'Karz sargyt')}
actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')}
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 title={t('clients.sections.cardOrders', 'Kart sargyt')} actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')} 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={() => {}} />
) : null}
{/* ── Kart sargyt ──────────────────────────────────────────────────── */}
<CollapsibleSection
title={t('clients.sections.cardOrders', 'Kart sargyt')}
actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')}
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>
{/* ── Audit log ────────────────────────────────────────────────────── */}
<AuditLog logs={auditLogs} />
{/* ── Delete dialog ────────────────────────────────────────────────── */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
@@ -233,54 +459,16 @@ export default function ClientDetailPage() {
</AlertDialogHeader>
<AlertDialogFooter>
<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')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</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>
)
}
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>
)
}
}

View File

@@ -180,6 +180,7 @@ export default function OperatorsPage() {
{t('operators.title', 'Operatorlar')}
</h1>
</div>
<div className="bg-card border border-border rounded-xl p-4">
{/* Toolbar */}
<DataTableToolbar
@@ -230,6 +231,7 @@ export default function OperatorsPage() {
onPageChange={setPage}
enableRowSelection
/>
</div>
{/* Delete dialog */}
<AlertDialog

View File

@@ -1,8 +1,8 @@
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Pencil, Trash2, ChevronDown } from 'lucide-react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { useParams, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Pencil, Trash2, ChevronDown } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
@@ -12,57 +12,161 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Section, InfoRow, AuditLog } from '@/components/viewPageComponents'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import { useOperator, useDeleteOperator } from '@/features/operators/hooks/useOperators'
import type { OperatorRole, OperatorBranch, OperatorAuditLog } from '@/features/operators/api/operatorsApi'
} from "@/components/ui/alert-dialog";
import { InfoRow, AuditLog } from "@/components/viewPageComponents";
import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar } from "@/components/dataTableToolbar";
import { useOperator, useDeleteOperator } from "@/features/operators/hooks/useOperators";
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() {
const { id } = useParams<{ id: string }>()
const operatorId = Number(id)
const { t } = useTranslation()
const navigate = useNavigate()
const deleteMutation = useDeleteOperator()
const { id } = useParams<{ id: string }>();
const operatorId = Number(id);
const { t } = useTranslation();
const navigate = useNavigate();
const deleteMutation = useDeleteOperator();
const { data: operator, isLoading } = useOperator(operatorId)
const { data: operator, isLoading } = useOperator(operatorId);
const [deleteOpen, setDeleteOpen] = useState(false)
const [roleSearch, setRoleSearch] = useState('')
const [permSearch, setPermSearch] = useState('')
const [branchSearch, setBranchSearch] = useState('')
const [deleteOpen, setDeleteOpen] = useState(false);
const [roleSearch, setRoleSearch] = useState("");
const [permSearch, setPermSearch] = useState("");
const [branchSearch, setBranchSearch] = useState("");
// ── Role columns ──────────────────────────────────────────────────────────
const roleColumns: ColumnDef<OperatorRole>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="text-primary font-semibold text-sm">{row.original.id}</span>
),
accessorKey: "id",
header: "ID",
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
size: 80,
},
{
accessorKey: 'code',
header: t('roles.fields.code', 'KOD'),
accessorKey: "code",
header: t("roles.fields.code", "KOD"),
cell: ({ row }) => <span className="text-sm">{row.original.code}</span>,
},
{
accessorKey: 'name',
header: t('roles.fields.name', 'ADY'),
accessorKey: "name",
header: t("roles.fields.name", "ADY"),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
},
{
accessorKey: 'guardName',
header: t('roles.fields.guardName', 'GUARD NAME'),
accessorKey: "guardName",
header: t("roles.fields.guardName", "GUARD NAME"),
cell: ({ row }) => <span className="text-sm">{row.original.guardName}</span>,
},
{
id: 'actions',
header: '',
id: "actions",
header: "",
cell: ({ row }) => (
<div className="flex items-center gap-1 justify-end">
<Button
@@ -71,105 +175,88 @@ export default function OperatorDetailPage() {
className="h-7 w-7 text-muted-foreground hover:text-foreground"
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
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-foreground">
<Pencil size={13} />
</Button>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 text-muted-foreground hover:text-destructive"
>
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
<Trash2 size={13} />
</Button>
</div>
),
size: 120,
},
]
];
// ── Branch columns ────────────────────────────────────────────────────────
const branchColumns: ColumnDef<OperatorBranch>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="text-primary font-semibold text-sm">{row.original.id}</span>
),
accessorKey: "id",
header: "ID",
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
size: 60,
},
{
accessorKey: 'name',
header: t('branches.fields.name', 'ADY'),
accessorKey: "name",
header: t("branches.fields.name", "ADY"),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
},
{
accessorKey: 'region',
header: t('branches.fields.region', 'WELAÝAT'),
accessorKey: "region",
header: t("branches.fields.region", "WELAÝAT"),
cell: ({ row }) => <span className="text-sm">{row.original.region}</span>,
},
{
accessorKey: 'district',
header: t('branches.fields.district', 'ETRAP'),
accessorKey: "district",
header: t("branches.fields.district", "ETRAP"),
cell: ({ row }) => <span className="text-sm">{row.original.district}</span>,
},
{
accessorKey: 'uniqueCode',
header: t('branches.fields.uniqueCode', 'UNIKAL BELGI'),
accessorKey: "uniqueCode",
header: t("branches.fields.uniqueCode", "UNIKAL BELGI"),
cell: ({ row }) => <span className="text-sm">{row.original.uniqueCode}</span>,
},
{
accessorKey: 'isActive',
header: t('branches.fields.isActive', 'IŞJEŇ'),
cell: ({ row }) =>
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>
),
accessorKey: "isActive",
header: t("branches.fields.isActive", "IŞJEŇ"),
cell: ({ row }) => <ActiveIndicator active={row.original.isActive} />,
size: 80,
},
{
accessorKey: 'billingUsernameIbr',
header: t('branches.fields.billingIbr', 'BILLING ULANYJY ADY'),
accessorKey: "billingUsernameIbr",
header: t("branches.fields.billingIbr", "BILLING ULANYJY ADY"),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameIbr}</span>,
},
{
accessorKey: 'billingUsernameSber',
header: t('branches.fields.billingSber', 'BILLING USERNAME (SBER)'),
accessorKey: "billingUsernameSber",
header: t("branches.fields.billingSber", "BILLING USERNAME (SBER)"),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameSber}</span>,
},
{
accessorKey: 'billingUsernameVisa',
header: t('branches.fields.billingVisa', 'BILLING USERNAME (VISA)'),
accessorKey: "billingUsernameVisa",
header: t("branches.fields.billingVisa", "BILLING USERNAME (VISA)"),
cell: ({ row }) => <span className="text-sm font-mono text-xs">{row.original.billingUsernameVisa}</span>,
},
{
id: 'actions',
header: '',
id: "actions",
header: "",
cell: () => (
<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} />
</Button>
</div>
),
size: 60,
},
]
];
// ── Loading ───────────────────────────────────────────────────────────────
if (isLoading) {
return (
@@ -178,12 +265,11 @@ export default function OperatorDetailPage() {
<div key={i} className="h-16 bg-muted rounded-xl animate-pulse" />
))}
</div>
)
);
}
if (!operator) return null
if (!operator) return null;
// Map audit logs to AuditLog component format
const auditLogs = (operator.auditLogs ?? []).map((log: OperatorAuditLog) => ({
id: String(log.id),
action: log.actionName,
@@ -191,24 +277,19 @@ export default function OperatorDetailPage() {
target: log.target,
status: log.status,
date: log.createdAt,
}))
}));
const filteredRoles = (operator.roles ?? []).filter(
(r) =>
r.name.toLowerCase().includes(roleSearch.toLowerCase()) ||
r.code.toLowerCase().includes(roleSearch.toLowerCase()),
)
const filteredBranches = (operator.branches ?? []).filter((b) =>
b.name.toLowerCase().includes(branchSearch.toLowerCase()),
)
(r) => r.name.toLowerCase().includes(roleSearch.toLowerCase()) || r.code.toLowerCase().includes(roleSearch.toLowerCase()),
);
const filteredBranches = (operator.branches ?? []).filter((b) => b.name.toLowerCase().includes(branchSearch.toLowerCase()));
return (
<div className="p-6">
{/* Page header */}
<div className="flex items-center justify-between mb-6">
<div className="p-6 flex flex-col gap-6">
{/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-center justify-between">
<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>
<div className="flex items-center gap-2">
<Button
@@ -230,40 +311,33 @@ export default function OperatorDetailPage() {
</div>
</div>
{/* Basic info */}
<Section>
<InfoRow label="ID" value={operator.id} />
<InfoRow label={t('operators.fields.username', 'Ulanyjy ady')} value={operator.username} />
<InfoRow label={t('operators.fields.name', 'Ady')} value={operator.name} />
<InfoRow label={t('operators.fields.phone', 'Telefon')} value={operator.phone ?? '—'} />
<InfoRow label={t('operators.fields.email', 'E-poçta')} value={operator.email ?? '—'} />
<InfoRow label={t('operators.fields.isActive', 'Işjeň')}>
{operator.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>
)}
</InfoRow>
</Section>
{/* ── Row 1: Esasy maglumatlar + Kontakt ──────────────────────────── */}
<BentoGrid cols={2}>
<BentoCard title={t("operators.sections.basic", "Esasy maglumatlar")}>
<InfoRow label="ID" value={operator.id} />
<InfoRow label={t("operators.fields.username", "Ulanyjy ady")} value={operator.username} />
<InfoRow label={t("operators.fields.name", "Ady")} value={operator.name} />
<InfoRow label={t("operators.fields.isActive", "Işjeň")}>
<ActiveIndicator active={operator.isActive} />
</InfoRow>
</BentoCard>
{/* 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
title={t('operators.sections.roles', 'Rollar')}
actionLabel={t('operators.addRole', 'Rol birikdiriň')}
onAction={() => {/* open role assign modal */}}
title={t("operators.sections.roles", "Rollar")}
actionLabel={t("operators.addRole", "Rol birikdiriň")}
onAction={() => {}}
>
<DataTableToolbar
searchValue={roleSearch}
onSearchChange={setRoleSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
@@ -271,24 +345,19 @@ export default function OperatorDetailPage() {
onColumnOrderChange={() => {}}
hideAction
/>
<DataTable
columns={roleColumns}
data={filteredRoles}
getRowId={(r) => String(r.id)}
enableRowSelection
/>
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
</CollapsibleSection>
{/* Permissions */}
{/* ── Rugsatlar ────────────────────────────────────────────────────── */}
<CollapsibleSection
title={t('operators.sections.permissions', 'Rugsatlar')}
actionLabel={t('operators.addPermission', 'Rugsat birikdiriň')}
onAction={() => {/* open permission modal */}}
title={t("operators.sections.permissions", "Rugsatlar")}
actionLabel={t("operators.addPermission", "Rugsat birikdiriň")}
onAction={() => {}}
>
<DataTableToolbar
searchValue={permSearch}
onSearchChange={setPermSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
@@ -296,21 +365,25 @@ export default function OperatorDetailPage() {
onColumnOrderChange={() => {}}
hideAction
/>
{(operator.permissions ?? []).length === 0 ? (
<EmptyState label={t('operators.noPermissions', 'Berlen kriterýalara Rugsat gabat gelmedi.')} actionLabel={t('operators.addPermission', 'Rugsat birikdiriň')} onAction={() => {}} />
) : null}
{(operator.permissions ?? []).length === 0 && (
<EmptyState
label={t("operators.noPermissions", "Berlen kriterýalara Rugsat gabat gelmedi.")}
actionLabel={t("operators.addPermission", "Rugsat birikdiriň")}
onAction={() => {}}
/>
)}
</CollapsibleSection>
{/* Branches */}
{/* ── Şahamçalar ───────────────────────────────────────────────────── */}
<CollapsibleSection
title={t('operators.sections.branches', 'Şahamçalar')}
actionLabel={t('operators.addBranch', 'Şahamça birikdiriň')}
title={t("operators.sections.branches", "Şahamçalar")}
actionLabel={t("operators.addBranch", "Şahamça birikdiriň")}
onAction={() => {}}
>
<DataTableToolbar
searchValue={branchSearch}
onSearchChange={setBranchSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
@@ -318,140 +391,68 @@ export default function OperatorDetailPage() {
onColumnOrderChange={() => {}}
hideAction
/>
<DataTable
columns={branchColumns}
data={filteredBranches}
getRowId={(r) => String(r.id)}
enableRowSelection
/>
<DataTable columns={branchColumns} data={filteredBranches} getRowId={(r) => String(r.id)} enableRowSelection />
</CollapsibleSection>
{/* Karz sargyt */}
{/* ── Karz sargyt ──────────────────────────────────────────────────── */}
<CollapsibleSection
title={t('operators.sections.loanLimits', 'Karz sargyt')}
actionLabel={t('operators.addLoanLimit', 'Karz sargyt döredin')}
title={t("operators.sections.loanLimits", "Karz sargyt")}
actionLabel={t("operators.addLoanLimit", "Karz sargyt döredin")}
onAction={() => {}}
>
{(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={() => {}} />
) : null}
{(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={() => {}}
/>
)}
</CollapsibleSection>
{/* Kart sargyt */}
{/* ── Kart sargyt ──────────────────────────────────────────────────── */}
<CollapsibleSection
title={t('operators.sections.cardLimits', 'Kart sargyt')}
actionLabel={t('operators.addCardLimit', 'Kart sargyt döredin')}
title={t("operators.sections.cardLimits", "Kart sargyt")}
actionLabel={t("operators.addCardLimit", "Kart sargyt döredin")}
onAction={() => {}}
>
{(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={() => {}} />
) : null}
{(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={() => {}}
/>
)}
</CollapsibleSection>
{/* Audit log */}
{/* ── Audit log ────────────────────────────────────────────────────── */}
<AuditLog logs={auditLogs} />
{/* Delete dialog */}
{/* ── Delete dialog ────────────────────────────────────────────────── */}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('operators.deleteTitle', 'Operatory pozmak')}</AlertDialogTitle>
<AlertDialogTitle>{t("operators.deleteTitle", "Operatory pozmak")}</AlertDialogTitle>
<AlertDialogDescription>
{t('operators.deleteConfirm', '{{name}} operatoryny pozmak isleýärsiňizmi?', {
{t("operators.deleteConfirm", "{{name}} operatoryny pozmak isleýärsiňizmi?", {
name: operator.name,
})}
</AlertDialogDescription>
</AlertDialogHeader>
<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(operatorId, {
onSuccess: () => navigate('/operators'),
onSuccess: () => navigate("/operators"),
})
}
>
{t('common.delete', 'Poz')}
{t("common.delete", "Poz")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</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>
)
}