added payment history, setting pages
This commit is contained in:
@@ -567,7 +567,7 @@ const routes: AppRoute[] = [
|
||||
element: page(VisaMasterSberSettingCreatePage),
|
||||
},
|
||||
{
|
||||
path: "/visa-master-sber-settings/:id/edit",
|
||||
path: "/visa-master-sber-settings/:code/edit",
|
||||
handle: { title: (t) => t("visaMasterSberSettings.editTitle", "Sazlama üýtgetmek") },
|
||||
element: page(VisaMasterSberSettingEditPage),
|
||||
},
|
||||
|
||||
@@ -65,6 +65,8 @@ interface DataTableToolbarProps {
|
||||
hideSearch?: boolean;
|
||||
hideAction?: boolean;
|
||||
|
||||
onFilterOpenChange?: (open: boolean) => void;
|
||||
|
||||
extraActions?: React.ReactNode;
|
||||
}
|
||||
|
||||
@@ -200,6 +202,7 @@ interface FilterDropdownProps {
|
||||
perPageOptions?: number[];
|
||||
perPage?: number;
|
||||
onPerPageChange?: (value: number) => void;
|
||||
onFilterOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
function FilterDropdown({
|
||||
@@ -210,17 +213,23 @@ function FilterDropdown({
|
||||
perPageOptions = [10, 25, 50, 100],
|
||||
perPage = 25,
|
||||
onPerPageChange,
|
||||
onFilterOpenChange,
|
||||
}: FilterDropdownProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
setOpen(nextOpen);
|
||||
onFilterOpenChange?.(nextOpen);
|
||||
};
|
||||
|
||||
const activeCount = activeFilters.filter((f) => f.value !== "").length;
|
||||
const hasActive = activeCount > 0;
|
||||
|
||||
const getActiveValue = (fieldId: string) => activeFilters.find((f) => f.fieldId === fieldId)?.value ?? "";
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<Popover open={open} onOpenChange={handleOpenChange}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
className={cn(
|
||||
@@ -402,6 +411,7 @@ export function DataTableToolbar({
|
||||
onAction,
|
||||
hideSearch = false,
|
||||
hideAction = false,
|
||||
onFilterOpenChange,
|
||||
extraActions,
|
||||
}: DataTableToolbarProps) {
|
||||
return (
|
||||
@@ -426,6 +436,7 @@ export function DataTableToolbar({
|
||||
perPageOptions={perPageOptions}
|
||||
perPage={perPage}
|
||||
onPerPageChange={onPerPageChange}
|
||||
onFilterOpenChange={onFilterOpenChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ export interface InfiniteSelectProps {
|
||||
onLoadMore?: () => void;
|
||||
searchValue?: string;
|
||||
onSearchChange?: (value: string) => void;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -51,6 +52,7 @@ export function InfiniteSelect({
|
||||
onLoadMore,
|
||||
searchValue,
|
||||
onSearchChange,
|
||||
onOpenChange,
|
||||
}: InfiniteSelectProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -128,7 +130,10 @@ export function InfiniteSelect({
|
||||
<PopoverPrimitive.Root
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!disabled) setOpen(next);
|
||||
if (!disabled) {
|
||||
setOpen(next);
|
||||
onOpenChange?.(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PopoverPrimitive.Trigger asChild>
|
||||
|
||||
@@ -40,7 +40,7 @@ const BRANCH_PAGE_SIZE = 25;
|
||||
* Paginated branches for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteBranches(search = "") {
|
||||
export function useInfiniteBranches(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||
|
||||
@@ -53,6 +53,7 @@ export function useInfiniteBranches(search = "") {
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -62,7 +63,7 @@ const PROVINCE_PAGE_SIZE = 25;
|
||||
* Paginated provinces for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteProvinces(search = "") {
|
||||
export function useInfiniteProvinces(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||
|
||||
@@ -75,6 +76,7 @@ export function useInfiniteProvinces(search = "") {
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ const CARD_TYPE_PAGE_SIZE = 25;
|
||||
* Paginated card types for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteCardTypes(search = "") {
|
||||
export function useInfiniteCardTypes(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||
|
||||
@@ -57,6 +57,7 @@ export function useInfiniteCardTypes(search = "") {
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ const DISTRICT_PAGE_SIZE = 25;
|
||||
* Paginated districts for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteDistricts(search = "") {
|
||||
export function useInfiniteDistricts(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||
|
||||
@@ -50,6 +50,7 @@ export function useInfiniteDistricts(search = "") {
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ const LOAN_TYPE_PAGE_SIZE = 25;
|
||||
* Paginated loan types for infinite-scroll searchable selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteLoanTypes(search = "") {
|
||||
export function useInfiniteLoanTypes(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||
|
||||
@@ -57,6 +57,7 @@ export function useInfiniteLoanTypes(search = "") {
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ const STAFF_PAGE_SIZE = 25;
|
||||
* Paginated staff users (GET /users/staff) for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteStaff(search = "") {
|
||||
export function useInfiniteStaff(search = "", enabled = true) {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch) || undefined;
|
||||
|
||||
@@ -58,6 +58,7 @@ export function useInfiniteStaff(search = "") {
|
||||
const count = lastPage?.count ?? 0;
|
||||
return loaded < count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,39 +1,91 @@
|
||||
// ─── Sber Payment Order Types ─────────────────────────────────────────────────
|
||||
import apiClient from "@/lib/api/client";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
// ─── Backend (real) types ─────────────────────────────────────────────────────
|
||||
|
||||
export type SberPaymentStatus = "pending" | "approved" | "rejected" | "completed";
|
||||
|
||||
export interface SberPaymentOrderItem {
|
||||
id: number;
|
||||
uniqueId: string;
|
||||
type: string;
|
||||
createdAt: string;
|
||||
region: string;
|
||||
regionName: LocalizedText;
|
||||
branch: {
|
||||
id: number;
|
||||
name: LocalizedText;
|
||||
};
|
||||
provinceName: LocalizedText;
|
||||
passportName: string;
|
||||
passportSurname: string;
|
||||
phone: string;
|
||||
status: SberPaymentStatus;
|
||||
paid: boolean;
|
||||
paidThisMonth: boolean;
|
||||
}
|
||||
|
||||
export interface SberPaymentListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
name?: string;
|
||||
status?: SberPaymentStatus | "";
|
||||
branch_id?: string;
|
||||
user_id?: string;
|
||||
region?: string;
|
||||
}
|
||||
|
||||
export interface SberPaymentListResponse {
|
||||
data: SberPaymentOrderItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface BackendSberListResponse {
|
||||
count: number;
|
||||
visaMasterPaymentOrders: SberPaymentOrderItem[];
|
||||
}
|
||||
|
||||
// ─── Form / payload types (carried over from the old mock API) ────────────────
|
||||
// NOTE: PaymentStatus is the FORM enum. The backend uses SberPaymentStatus.
|
||||
// Map between them before sending (see the note in the response).
|
||||
|
||||
export type PaymentStatus = "GARASYLYYAR" | "KANAGATLANDYRYLAN" | "RET_EDILEN";
|
||||
export type PaymentPaidStatus = "Tolenmedik" | "Tolendi";
|
||||
|
||||
export interface SberPaymentOrder {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
export interface SberPaymentFormData {
|
||||
welayat: string;
|
||||
sahamca: string;
|
||||
sahamcaId?: number | string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
address: string;
|
||||
status: PaymentStatus;
|
||||
paidStatus: PaymentPaidStatus;
|
||||
bellik: string;
|
||||
|
||||
// Payment info
|
||||
accountNumber: string;
|
||||
passportSeries: string;
|
||||
passportNumber: string;
|
||||
fullName: string;
|
||||
|
||||
// Documents
|
||||
documents: SberDocument[];
|
||||
|
||||
// Payment history
|
||||
paymentHistory: PaymentHistoryItem[];
|
||||
|
||||
// Activity log
|
||||
activityLog: ActivityLogItem[];
|
||||
}
|
||||
|
||||
export type CreateSberPaymentPayload = SberPaymentFormData;
|
||||
|
||||
export interface UpdateSberPaymentPayload extends SberPaymentFormData {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface SberPaymentFilters {
|
||||
search: string;
|
||||
welayat: string;
|
||||
sahamca: string;
|
||||
status: string;
|
||||
paidStatus: string;
|
||||
}
|
||||
|
||||
// ─── Legacy detail types (old mock shape) ─────────────────────────────────────
|
||||
// @deprecated The backend detail response is SberPaymentOrderItem.
|
||||
// Kept only so old imports keep compiling while the detail page is migrated.
|
||||
|
||||
export interface SberDocument {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -58,99 +110,81 @@ export interface ActivityLogItem {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
// ─── API Types ────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface SberPaymentOrdersResponse {
|
||||
data: SberPaymentOrder[];
|
||||
pagination: {
|
||||
currentPage: number;
|
||||
totalPages: number;
|
||||
totalCount: number;
|
||||
perPage: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CreateSberPaymentPayload {
|
||||
welayat: string;
|
||||
sahamca: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
address: string;
|
||||
status: PaymentStatus;
|
||||
bellik: string;
|
||||
accountNumber: string;
|
||||
passportSeries: string;
|
||||
passportNumber: string;
|
||||
fullName: string;
|
||||
}
|
||||
|
||||
export interface UpdateSberPaymentPayload extends CreateSberPaymentPayload {
|
||||
export interface SberPaymentOrder {
|
||||
id: string;
|
||||
}
|
||||
|
||||
// ─── Form Types ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface SberPaymentFormData {
|
||||
createdAt: string;
|
||||
welayat: string;
|
||||
sahamca: string;
|
||||
sahamcaId?: number | string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phone: string;
|
||||
email: string;
|
||||
address: string;
|
||||
status: PaymentStatus;
|
||||
paidStatus: PaymentPaidStatus;
|
||||
bellik: string;
|
||||
accountNumber: string;
|
||||
passportSeries: string;
|
||||
passportNumber: string;
|
||||
fullName: string;
|
||||
documents: SberDocument[];
|
||||
paymentHistory: PaymentHistoryItem[];
|
||||
activityLog: ActivityLogItem[];
|
||||
}
|
||||
|
||||
// ─── Filter Types ─────────────────────────────────────────────────────────────
|
||||
// ─── API ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface SberPaymentFilters {
|
||||
search: string;
|
||||
welayat: string;
|
||||
sahamca: string;
|
||||
status: string;
|
||||
paidStatus: string;
|
||||
}
|
||||
export const sberPaymentRealApi = {
|
||||
async list(params: SberPaymentListParams = {}): Promise<SberPaymentListResponse> {
|
||||
const page = params.page ?? 1;
|
||||
const limit = params.limit ?? 25;
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
const { data } = await apiClient.get<BackendSberListResponse>("/visa-master-payment-orders/sber", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
name: params.name || undefined,
|
||||
status: params.status || undefined,
|
||||
branch_id: params.branch_id || undefined,
|
||||
user_id: params.user_id || undefined,
|
||||
region: params.region || undefined,
|
||||
},
|
||||
});
|
||||
|
||||
const turkmenNames = [
|
||||
{ first: "Lale", last: "Agayewa" },
|
||||
{ first: "Agamyrat", last: "Hydyrow" },
|
||||
{ first: "Rusdem", last: "Jorayew" },
|
||||
{ first: "Agajan", last: "Rejepow" },
|
||||
{ first: "Cemen", last: "Mamedowa" },
|
||||
{ first: "Ussman", last: "Saberdiyew" },
|
||||
{ first: "Ogultagan", last: "Amanowa" },
|
||||
{ first: "Bahargul", last: "Dowranowa" },
|
||||
{ first: "Muhabet", last: "Hojakulyyewa" },
|
||||
{ first: "Yusupbay", last: "Orunow" },
|
||||
{ first: "Jumagul", last: "Hasanowa" },
|
||||
{ first: "Arazgul", last: "Akmedowa" },
|
||||
{ first: "Samsat", last: "Mamedowa" },
|
||||
{ first: "Anzela", last: "Metkumyan" },
|
||||
{ first: "Durmys", last: "Bahadurow" },
|
||||
{ first: "Serdar", last: "Nuryyew" },
|
||||
{ first: "Kseniya", last: "Hemrayewa" },
|
||||
{ first: "Orazgul", last: "Dowletowa" },
|
||||
{ first: "Salidahan", last: "Kazyyewa" },
|
||||
{ first: "Babamurad", last: "Abdyraimow" },
|
||||
{ first: "Ogulnar", last: "Babakulyyewa" },
|
||||
{ first: "Derman", last: "Hudaynazarow" },
|
||||
{ first: "Hasan", last: "Tasow" },
|
||||
{ first: "Yusupjan", last: "Tasow" },
|
||||
{ first: "Begnazar", last: "Weliyew" },
|
||||
];
|
||||
return {
|
||||
data: data.visaMasterPaymentOrders ?? [],
|
||||
total: data.count ?? 0,
|
||||
};
|
||||
},
|
||||
|
||||
const welayatlar = ["Mary", "Lebap", "Asgabat", "Dashoguz", "Balkan"];
|
||||
async getById(id: string): Promise<SberPaymentOrderItem> {
|
||||
const { data } = await apiClient.get<SberPaymentOrderItem>(`/visa-master-payment-orders/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
const sahamcalar: Record<string, string[]> = {
|
||||
// ASSUMPTION: create endpoint is POST /visa-master-payment-orders. Verify against the backend.
|
||||
async create(payload: object): Promise<SberPaymentOrderItem> {
|
||||
const { data } = await apiClient.post<SberPaymentOrderItem>("/visa-master-payment-orders", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
async update(id: string, payload: object): Promise<SberPaymentOrderItem> {
|
||||
const { data } = await apiClient.put<SberPaymentOrderItem>(`/visa-master-payment-orders/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
await apiClient.delete(`/visa-master-payment-orders/${id}`);
|
||||
},
|
||||
};
|
||||
|
||||
// ─── Constants for dropdowns ──────────────────────────────────────────────────
|
||||
// Static fallbacks from the old mock file. Prefer useInfiniteBranches in forms.
|
||||
|
||||
export const WELAYATLAR = ["Mary", "Lebap", "Asgabat", "Dashoguz", "Balkan"];
|
||||
|
||||
export const SAHAMCALAR: Record<string, string[]> = {
|
||||
Mary: ["Bayramaly", "Mary saheri", "Sakarçäge"],
|
||||
Lebap: ["Turkmenabat", "Garlyk", "Seydi", "Buzmeyin"],
|
||||
Asgabat: ["Buzmeyin", "Berkararlyk", "Köpetdag"],
|
||||
@@ -158,196 +192,6 @@ const sahamcalar: Record<string, string[]> = {
|
||||
Balkan: ["Balkanabat", "Turkmenbasy", "Serdar"],
|
||||
};
|
||||
|
||||
const statuses: Array<"GARASYLYYAR" | "KANAGATLANDYRYLAN" | "RET_EDILEN"> = ["GARASYLYYAR", "KANAGATLANDYRYLAN", "RET_EDILEN"];
|
||||
|
||||
const documentLabels = [
|
||||
{ id: "rekvezit", name: "Rekvezit.jpg", label: 'Talyba degisli walýuta "SBERBANK" kartyň rekwizitleri' },
|
||||
{
|
||||
id: "sprawka",
|
||||
name: "sprawka-2026.jpg",
|
||||
label: "Talybýň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwanamasy",
|
||||
},
|
||||
{ id: "bildirish", name: "bildirish.jpg", label: "Talybýň bildirisli göcürmesi" },
|
||||
{
|
||||
id: "passport-copy",
|
||||
name: "Tkm-pas-Agayewa-Mahllan-(1).jpg",
|
||||
label: "Talyba degisli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi",
|
||||
},
|
||||
{
|
||||
id: "zagran-1",
|
||||
name: "Zagran-(1).jpg",
|
||||
label: "Talybýň Türkmenistandan çykmak we Türkmenistana girmek üçin (zagran) pasportynyň göçürmesi",
|
||||
},
|
||||
{
|
||||
id: "zagran-2",
|
||||
name: "Zagran-(2).jpg",
|
||||
label:
|
||||
"Talybýň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportyndaky daşary ýurda çykmak üçin tälynjädägy baradaky beriim miiletti hereket edijan rughsatnamasyniyň (wizasynyň) bellenen sahypasynyň göçürmesi",
|
||||
},
|
||||
];
|
||||
|
||||
function generateMockPaymentOrder(index: number): SberPaymentOrder {
|
||||
const name = turkmenNames[index % turkmenNames.length];
|
||||
const welayat = welayatlar[index % welayatlar.length];
|
||||
const sahamcaList = sahamcalar[welayat];
|
||||
const sahamca = sahamcaList[index % sahamcaList.length];
|
||||
const status = statuses[index % statuses.length];
|
||||
|
||||
const baseDate = new Date(2026, 4, 7); // May 7, 2026
|
||||
const orderDate = new Date(baseDate.getTime() - index * 3 * 60 * 1000); // 3 min apart
|
||||
|
||||
const idPrefix = ["TB7369", "TB8319", "TB8318", "TB8311", "TB1308"][index % 5];
|
||||
const idNumber = 8137 - index;
|
||||
|
||||
return {
|
||||
id: `${idPrefix}-${idNumber}`,
|
||||
createdAt: orderDate.toISOString(),
|
||||
welayat,
|
||||
sahamca,
|
||||
sahamcaId: (index % 3) + 1,
|
||||
firstName: name.first,
|
||||
lastName: name.last,
|
||||
phone: `+993-${60 + (index % 5)}${index % 10}-${(42 + index) % 99}-${(28 + index * 2) % 99}-${(13 + index * 3) % 99}`,
|
||||
email: `${name.first.toLowerCase()}.${name.last.toLowerCase()}@mail.tm`,
|
||||
address: `Bayramaly saher 1-nji jay toolumy jay1 oy1`,
|
||||
status,
|
||||
paidStatus: index % 3 === 0 ? "Tolendi" : "Tolenmedik",
|
||||
bellik: "",
|
||||
accountNumber: `232080100002850`,
|
||||
passportSeries: `II-M${String.fromCharCode(65 + (index % 8))}`,
|
||||
passportNumber: String(100000 + index * 1234),
|
||||
fullName: `${name.first} ${name.last} Sadurdyyewna`,
|
||||
documents: documentLabels.map((doc, i) => ({
|
||||
id: `doc-${index}-${i}`,
|
||||
name: doc.name,
|
||||
label: doc.label,
|
||||
fileUrl: index % 2 === 0 ? `/uploads/${doc.name}` : null,
|
||||
fileType: doc.name.endsWith(".pdf") ? "pdf" : "image",
|
||||
})),
|
||||
paymentHistory: [],
|
||||
activityLog: [
|
||||
{
|
||||
id: `activity-${index}-1`,
|
||||
analysisName: "Gospmak",
|
||||
createdBy: `Agayewa ${name.first} Sadurdyyewna`,
|
||||
target: `Sber töleg (talyplar üçin): ${idPrefix}-${idNumber}`,
|
||||
status: "FINISHED",
|
||||
createdAt: orderDate.toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// Generate 100 mock records
|
||||
const mockPaymentOrders: SberPaymentOrder[] = Array.from({ length: 100 }, (_, i) => generateMockPaymentOrder(i));
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getSberPaymentOrders(params: {
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
search?: string;
|
||||
welayat?: string;
|
||||
sahamca?: string;
|
||||
status?: string;
|
||||
}): Promise<SberPaymentOrdersResponse> {
|
||||
// Simulate network delay
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
|
||||
let filtered = [...mockPaymentOrders];
|
||||
|
||||
// Apply filters
|
||||
if (params.search) {
|
||||
const q = params.search.toLowerCase();
|
||||
filtered = filtered.filter(
|
||||
(o) =>
|
||||
o.id.toLowerCase().includes(q) ||
|
||||
o.firstName.toLowerCase().includes(q) ||
|
||||
o.lastName.toLowerCase().includes(q) ||
|
||||
o.phone.includes(q),
|
||||
);
|
||||
}
|
||||
|
||||
if (params.welayat) {
|
||||
filtered = filtered.filter((o) => o.welayat === params.welayat);
|
||||
}
|
||||
|
||||
if (params.sahamca) {
|
||||
filtered = filtered.filter((o) => o.sahamca === params.sahamca);
|
||||
}
|
||||
|
||||
if (params.status) {
|
||||
filtered = filtered.filter((o) => o.status === params.status);
|
||||
}
|
||||
|
||||
const page = params.page ?? 1;
|
||||
const perPage = params.perPage ?? 25;
|
||||
const totalCount = filtered.length;
|
||||
const totalPages = Math.ceil(totalCount / perPage);
|
||||
const start = (page - 1) * perPage;
|
||||
const data = filtered.slice(start, start + perPage);
|
||||
|
||||
return {
|
||||
data,
|
||||
pagination: {
|
||||
currentPage: page,
|
||||
totalPages,
|
||||
totalCount,
|
||||
perPage,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getSberPaymentOrderById(id: string): Promise<SberPaymentOrder | null> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
return mockPaymentOrders.find((o) => o.id === id) ?? null;
|
||||
}
|
||||
|
||||
export async function createSberPaymentOrder(payload: CreateSberPaymentPayload): Promise<SberPaymentOrder> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 400));
|
||||
|
||||
const newOrder: SberPaymentOrder = {
|
||||
id: `TB${Math.floor(1000 + Math.random() * 9000)}-${Math.floor(1000 + Math.random() * 9000)}`,
|
||||
createdAt: new Date().toISOString(),
|
||||
...payload,
|
||||
paidStatus: "Tolenmedik",
|
||||
documents: [],
|
||||
paymentHistory: [],
|
||||
activityLog: [],
|
||||
};
|
||||
|
||||
mockPaymentOrders.unshift(newOrder);
|
||||
return newOrder;
|
||||
}
|
||||
|
||||
export async function updateSberPaymentOrder(payload: UpdateSberPaymentPayload): Promise<SberPaymentOrder> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 400));
|
||||
|
||||
const index = mockPaymentOrders.findIndex((o) => o.id === payload.id);
|
||||
if (index === -1) {
|
||||
throw new Error("Payment order not found");
|
||||
}
|
||||
|
||||
const updated = {
|
||||
...mockPaymentOrders[index],
|
||||
...payload,
|
||||
};
|
||||
mockPaymentOrders[index] = updated;
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function deleteSberPaymentOrder(id: string): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
const index = mockPaymentOrders.findIndex((o) => o.id === id);
|
||||
if (index !== -1) {
|
||||
mockPaymentOrders.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Constants for dropdowns ──────────────────────────────────────────────────
|
||||
|
||||
export const WELAYATLAR = welayatlar;
|
||||
export const SAHAMCALAR = sahamcalar;
|
||||
export const STATUSES = [
|
||||
{ value: "GARASYLYYAR", label: "Garasylyyar" },
|
||||
{ value: "KANAGATLANDYRYLAN", label: "Kanagatlandyrylan" },
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { User, MapPin, IdCard, CreditCard, Files } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
@@ -10,109 +9,123 @@ import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateSberPayment, useUpdateSberPayment } from "@/features/sberPayments/hooks/useSberPayments";
|
||||
import { WELAYATLAR, SAHAMCALAR, STATUSES, type SberPaymentOrder, type PaymentStatus } from "@/features/sberPayments/api/sberPaymentsApi";
|
||||
import { WELAYATLAR } from "@/features/sberPayments/api/sberPaymentsApi";
|
||||
import { useCreateIntlPayment, useUpdateIntlPayment } from "@/features/visaMasterPayments/hooks/useVisaMasterPayments";
|
||||
import type { IntlPaymentItem, IntlPaymentCreatePayload, IntlPaymentStatus } from "@/features/visaMasterPayments/api/visaMasterPaymentsApi";
|
||||
import {
|
||||
validateStep,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
type SberPaymentFormData,
|
||||
} from "@/features/sberPayments/schemas/sberPayment.schema";
|
||||
ACCEPTED_DOC_DEFS,
|
||||
SENT_DOC_DEFS,
|
||||
ALL_DOC_KEYS,
|
||||
docLabel,
|
||||
type DocKey,
|
||||
type TFn,
|
||||
} from "@/features/sberPayments/constants/documents";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Order `type` value the backend uses for sber orders (list endpoint is /sber). */
|
||||
const SBER_TYPE = "sber";
|
||||
|
||||
type DocValue = File | string | null; // File = new upload, string = existing file URL
|
||||
type FormState = Omit<IntlPaymentCreatePayload, DocKey> & Record<DocKey, DocValue>;
|
||||
type FlatErrors = Partial<Record<keyof FormState, string>>;
|
||||
type SetFn = <K extends keyof FormState>(k: K, v: FormState[K]) => void;
|
||||
type Option = { value: string; label: string };
|
||||
|
||||
interface SberPaymentFormProps {
|
||||
mode: "create" | "edit";
|
||||
initialData?: SberPaymentOrder | null;
|
||||
initialData?: IntlPaymentItem | null;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof SberPaymentFormData, string>>;
|
||||
// ─── Defaults / mapping ───────────────────────────────────────────────────────
|
||||
|
||||
// ─── Flatten RHF errors ──────────────────────────────────────────────────────
|
||||
const DEFAULT_FORM_VALUES: FormState = {
|
||||
client_id: "",
|
||||
status: "pending",
|
||||
note: "",
|
||||
currency_type: SBER_TYPE,
|
||||
province: "",
|
||||
branch: "",
|
||||
passport_first_name: "",
|
||||
passport_last_name: "",
|
||||
phone: "",
|
||||
email: "",
|
||||
home_address: "",
|
||||
passport_series: "",
|
||||
passport_number: "",
|
||||
payer_full_name: "",
|
||||
payer_account_number: "",
|
||||
receiver_info: "",
|
||||
...(Object.fromEntries(ALL_DOC_KEYS.map((k) => [k, null])) as Record<DocKey, DocValue>),
|
||||
};
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof SberPaymentFormData] = msg;
|
||||
function mapInitialData(d: IntlPaymentItem): FormState {
|
||||
const docs = Object.fromEntries(ALL_DOC_KEYS.map((k) => [k, d[k] ?? null])) as Record<DocKey, DocValue>;
|
||||
return {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
...docs,
|
||||
client_id: d.client_id,
|
||||
status: d.status,
|
||||
note: d.note ?? "",
|
||||
currency_type: d.currency_type ?? SBER_TYPE,
|
||||
province: d.province,
|
||||
branch: d.branch,
|
||||
passport_first_name: d.passport_first_name,
|
||||
passport_last_name: d.passport_last_name,
|
||||
phone: d.phone,
|
||||
email: d.email ?? "",
|
||||
home_address: d.home_address ?? "",
|
||||
passport_series: d.passport_series,
|
||||
passport_number: d.passport_number,
|
||||
payer_full_name: d.payer_full_name,
|
||||
payer_account_number: d.payer_account_number,
|
||||
receiver_info: d.receiver_info,
|
||||
};
|
||||
}
|
||||
|
||||
// The API layer uploads File instances and passes strings through (mapFileDocsToBackend).
|
||||
const buildPayload = (f: FormState) => f as unknown as IntlPaymentCreatePayload;
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
|
||||
const REQUIRED_BY_STEP: (keyof FormState)[][] = [
|
||||
["client_id", "status"],
|
||||
["province", "branch"],
|
||||
["passport_last_name", "passport_first_name", "phone"],
|
||||
["passport_series", "passport_number", "payer_full_name", "payer_account_number", "receiver_info"],
|
||||
[],
|
||||
];
|
||||
|
||||
const isEmpty = (v: unknown) => v == null || (typeof v === "string" && v.trim() === "");
|
||||
|
||||
function validateStep(step: number, f: FormState, t: TFn): FlatErrors {
|
||||
const errs: FlatErrors = {};
|
||||
for (const key of REQUIRED_BY_STEP[step] ?? []) {
|
||||
if (isEmpty(f[key])) errs[key] = t("common.errors.required", "Hökmany meýdan");
|
||||
}
|
||||
return result;
|
||||
if (step === 2 && f.email && !/^\S+@\S+\.\S+$/.test(f.email)) {
|
||||
errs.email = t("common.errors.invalidEmail", "E-poçta nädogry");
|
||||
}
|
||||
return errs;
|
||||
}
|
||||
|
||||
// ─── Document lists ───────────────────────────────────────────────────────────
|
||||
|
||||
type AcceptedDocKey =
|
||||
| "acc_sberbank_card"
|
||||
| "acc_enrollment"
|
||||
| "acc_summons"
|
||||
| "acc_passport_tm"
|
||||
| "acc_zagran_passport"
|
||||
| "acc_visa_page"
|
||||
| "acc_entry_stamp"
|
||||
| "acc_school_letter";
|
||||
|
||||
type SentDocKey =
|
||||
| "snt_passport_tm"
|
||||
| "snt_zagran_passport"
|
||||
| "snt_entry_stamp"
|
||||
| "snt_relation_doc"
|
||||
| "snt_new_passport_series"
|
||||
| "snt_old_passport_series";
|
||||
|
||||
const ACCEPTED_DOCS = (t: (key: string, fallback?: string) => string): { key: AcceptedDocKey; label: string }[] => [
|
||||
{ key: "acc_sberbank_card", label: t("sberPayments.documents.sberbankCard", "Talýba degişli SBERBANK kartynyň rekwizitleri") },
|
||||
{ key: "acc_enrollment", label: t("sberPayments.documents.enrollment", "Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy") },
|
||||
{ key: "acc_summons", label: t("sberPayments.documents.summons", "Çagyrylma hatynyn göçürmesi") },
|
||||
{ key: "acc_passport_tm", label: t("sberPayments.documents.passportTm", "TM içki pasportynyň asyl görnüşi we göçürmesi") },
|
||||
{ key: "acc_zagran_passport", label: t("sberPayments.documents.zagranPassport", "Daşary ýurt (zagran) pasportynyň göçürmesi") },
|
||||
{ key: "acc_visa_page", label: t("sberPayments.documents.visaPage", "Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi") },
|
||||
{
|
||||
key: "acc_entry_stamp",
|
||||
label: t("sberPayments.documents.entryStamp", "Daşary ýurt döwletine girenliği baradaky ştamply sahypasynyň göçürmesi"),
|
||||
},
|
||||
{ key: "acc_school_letter", label: t("sberPayments.documents.schoolLetter", "ÝOM-dan hat (daşary ýurt dilinde maglumatly)") },
|
||||
];
|
||||
|
||||
const SENT_DOCS = (t: (key: string, fallback?: string) => string): { key: SentDocKey; label: string }[] => [
|
||||
{
|
||||
key: "snt_passport_tm",
|
||||
label: t("sberPayments.documents.sentPassportTm", "Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi"),
|
||||
},
|
||||
{
|
||||
key: "snt_zagran_passport",
|
||||
label: t("sberPayments.documents.sentZagranPassport", "Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi"),
|
||||
},
|
||||
{
|
||||
key: "snt_entry_stamp",
|
||||
label: t("sberPayments.documents.sentEntryStamp", "Ugradyjynyň daşary döwletine girenliği ştamply sahypasynyň göçürmesi"),
|
||||
},
|
||||
{
|
||||
key: "snt_relation_doc",
|
||||
label: t("sberPayments.documents.sentRelationDoc", "Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi"),
|
||||
},
|
||||
{
|
||||
key: "snt_new_passport_series",
|
||||
label: t("sberPayments.documents.sentNewPassportSeries", "Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty"),
|
||||
},
|
||||
{
|
||||
key: "snt_old_passport_series",
|
||||
label: t("sberPayments.documents.sentOldPassportSeries", "Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy"),
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepGeneral({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData;
|
||||
interface StepProps {
|
||||
form: FormState;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
set: SetFn;
|
||||
t: TFn;
|
||||
}
|
||||
|
||||
function StepGeneral({ form, errors, set, t, clientOptions }: StepProps & { clientOptions: Option[] }) {
|
||||
const statusOptions: Option[] = [
|
||||
{ value: "pending", label: t("sberPayments.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("sberPayments.status.approved", "Tassyklandy") },
|
||||
{ value: "rejected", label: t("sberPayments.status.rejected", "Ýatyryldy") },
|
||||
{ value: "completed", label: t("sberPayments.status.completed", "Tamamlandy") },
|
||||
];
|
||||
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
@@ -121,8 +134,9 @@ function StepGeneral({
|
||||
label={t("sberPayments.fields.client_id", "Ulanyjy")}
|
||||
value={form.client_id}
|
||||
onChange={(v) => set("client_id", v)}
|
||||
options={[]}
|
||||
options={clientOptions}
|
||||
placeholder={t("sberPayments.placeholders.select", "Saýlamak üçin basyň")}
|
||||
error={errors.client_id}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -132,8 +146,8 @@ function StepGeneral({
|
||||
type="select"
|
||||
label={t("sberPayments.fields.status", "Status")}
|
||||
value={form.status}
|
||||
onChange={(v) => set("status", v as PaymentStatus)}
|
||||
options={STATUSES}
|
||||
onChange={(v) => set("status", v as IntlPaymentStatus)}
|
||||
options={statusOptions}
|
||||
error={errors.status}
|
||||
required
|
||||
/>
|
||||
@@ -143,8 +157,8 @@ function StepGeneral({
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("sberPayments.fields.bellik", "Bellik")}
|
||||
value={form.bellik}
|
||||
onChange={(v) => set("bellik", v)}
|
||||
value={form.note}
|
||||
onChange={(v) => set("note", v)}
|
||||
placeholder={t("sberPayments.placeholders.bellik", "Bellik...")}
|
||||
rows={2}
|
||||
/>
|
||||
@@ -158,28 +172,23 @@ function StepLocation({
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
const branches = form.welayat ? (SAHAMCALAR[form.welayat] ?? []) : [];
|
||||
|
||||
provinceOptions,
|
||||
branchOptions,
|
||||
}: StepProps & { provinceOptions: Option[]; branchOptions: Option[] }) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("sberPayments.fields.welayat", "Welaýat")}
|
||||
value={form.welayat}
|
||||
value={form.province}
|
||||
onChange={(v) => {
|
||||
set("welayat", v);
|
||||
set("sahamca", "");
|
||||
set("province", v);
|
||||
set("branch", "");
|
||||
}}
|
||||
options={WELAYATLAR.map((w) => ({ value: w, label: w }))}
|
||||
options={provinceOptions}
|
||||
placeholder={t("sberPayments.placeholders.welayat", "Aşgabat")}
|
||||
error={errors.welayat}
|
||||
error={errors.province}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -188,12 +197,12 @@ function StepLocation({
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("sberPayments.fields.sahamca", "Şahamça")}
|
||||
value={form.sahamca}
|
||||
onChange={(v) => set("sahamca", v)}
|
||||
options={branches.map((b) => ({ value: b, label: b }))}
|
||||
value={form.branch}
|
||||
onChange={(v) => set("branch", v)}
|
||||
options={branchOptions}
|
||||
placeholder={t("sberPayments.placeholders.select", "Saýlamak üçin basyň")}
|
||||
disabled={!form.welayat}
|
||||
error={errors.sahamca}
|
||||
disabled={!form.province}
|
||||
error={errors.branch}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -201,36 +210,26 @@ function StepLocation({
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
function StepPersonal({ form, errors, set, t }: StepProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("sberPayments.fields.lastName", "Pasportdaky familiýa")}
|
||||
value={form.lastName}
|
||||
onChange={(v) => set("lastName", v)}
|
||||
value={form.passport_last_name}
|
||||
onChange={(v) => set("passport_last_name", v)}
|
||||
placeholder={t("sberPayments.placeholders.lastName", "NURYYEW")}
|
||||
error={errors.lastName}
|
||||
error={errors.passport_last_name}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("sberPayments.fields.firstName", "Pasportdaky ady")}
|
||||
value={form.firstName}
|
||||
onChange={(v) => set("firstName", v)}
|
||||
value={form.passport_first_name}
|
||||
onChange={(v) => set("passport_first_name", v)}
|
||||
placeholder={t("sberPayments.placeholders.firstName", "HAÝDAR")}
|
||||
error={errors.firstName}
|
||||
error={errors.passport_first_name}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -250,6 +249,7 @@ function StepPersonal({
|
||||
value={form.email}
|
||||
onChange={(v) => set("email", v)}
|
||||
placeholder={t("sberPayments.placeholders.email", "email@example.com")}
|
||||
error={errors.email}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
@@ -257,53 +257,36 @@ function StepPersonal({
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("sberPayments.fields.address", "Salgy")}
|
||||
value={form.address}
|
||||
onChange={(v) => set("address", v)}
|
||||
value={form.home_address}
|
||||
onChange={(v) => set("home_address", v)}
|
||||
placeholder={t("sberPayments.placeholders.address", "Köçe, jaý belgisi...")}
|
||||
error={errors.address}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
);
|
||||
}
|
||||
|
||||
function StepPayment({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
function StepPayment({ form, errors, set, t }: StepProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("sberPayments.fields.passportSeries", "Pasport seriýasy")}
|
||||
value={form.passportSeries}
|
||||
onChange={(v) => set("passportSeries", v)}
|
||||
options={[
|
||||
{ value: "II-MA", label: "II-MA" },
|
||||
{ value: "II-MB", label: "II-MB" },
|
||||
{ value: "II-MC", label: "II-MC" },
|
||||
{ value: "II-MD", label: "II-MD" },
|
||||
]}
|
||||
value={form.passport_series}
|
||||
onChange={(v) => set("passport_series", v)}
|
||||
options={["II-MA", "II-MB", "II-MC", "II-MD"].map((s) => ({ value: s, label: s }))}
|
||||
placeholder={t("sberPayments.placeholders.select", "Saýlamak üçin basyň")}
|
||||
error={errors.passportSeries}
|
||||
error={errors.passport_series}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("sberPayments.fields.passportNumber", "Pasport nomeri")}
|
||||
value={form.passportNumber}
|
||||
onChange={(v) => set("passportNumber", v)}
|
||||
value={form.passport_number}
|
||||
onChange={(v) => set("passport_number", v)}
|
||||
placeholder={t("sberPayments.placeholders.passportNumber", "A123456")}
|
||||
error={errors.passportNumber}
|
||||
error={errors.passport_number}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -312,19 +295,31 @@ function StepPayment({
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("sberPayments.fields.fullName", "Ady Familiýasy Atasynyň ady")}
|
||||
value={form.fullName}
|
||||
onChange={(v) => set("fullName", v)}
|
||||
value={form.payer_full_name}
|
||||
onChange={(v) => set("payer_full_name", v)}
|
||||
placeholder={t("sberPayments.placeholders.fullName", "Doly ady...")}
|
||||
error={errors.fullName}
|
||||
error={errors.payer_full_name}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("sberPayments.fields.accountNumber", "Goýum hasaby")}
|
||||
value={form.accountNumber}
|
||||
onChange={(v) => set("accountNumber", v)}
|
||||
value={form.payer_account_number}
|
||||
onChange={(v) => set("payer_account_number", v)}
|
||||
placeholder={t("sberPayments.placeholders.accountNumber", "1234 5678 ...")}
|
||||
error={errors.accountNumber}
|
||||
error={errors.payer_account_number}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard span="full">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("sberPayments.fields.receiverInfo", "Töleg kabul edijiniň maglumatlary")}
|
||||
value={form.receiver_info}
|
||||
onChange={(v) => set("receiver_info", v)}
|
||||
placeholder={t("sberPayments.placeholders.receiverInfo", "Doly ady...")}
|
||||
error={errors.receiver_info}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -332,43 +327,41 @@ function StepPayment({
|
||||
);
|
||||
}
|
||||
|
||||
function StepDocs({
|
||||
form,
|
||||
set,
|
||||
t,
|
||||
}: {
|
||||
form: SberPaymentFormData;
|
||||
set: <K extends keyof SberPaymentFormData>(k: K, v: SberPaymentFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
}) {
|
||||
function DocField({ docKey, label, form, set }: { docKey: DocKey; label: string; form: FormState; set: SetFn }) {
|
||||
const value = form[docKey];
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<FormInput
|
||||
type="file"
|
||||
label={label}
|
||||
onFileChange={(f) => set(docKey, (f ?? null) as DocValue)}
|
||||
fileValue={value instanceof File ? value : null}
|
||||
accept="image/*,.pdf"
|
||||
/>
|
||||
{typeof value === "string" && value && (
|
||||
<a href={value} target="_blank" rel="noreferrer" className="text-xs text-primary hover:underline">
|
||||
{decodeURIComponent(value.split("?")[0].split("/").pop() ?? "")}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepDocs({ form, set, t }: Omit<StepProps, "errors">) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<div className="space-y-3">
|
||||
{ACCEPTED_DOCS(t).map(({ key, label }) => (
|
||||
<FormInput
|
||||
key={key}
|
||||
type="file"
|
||||
label={label}
|
||||
onFileChange={(f) => set(key, f as SberPaymentFormData[typeof key])}
|
||||
fileValue={form[key] as File | null}
|
||||
accept="image/*,.pdf"
|
||||
/>
|
||||
{ACCEPTED_DOC_DEFS.map((d) => (
|
||||
<DocField key={d.key} docKey={d.key} label={docLabel(d, t)} form={form} set={set} />
|
||||
))}
|
||||
</div>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<div className="space-y-3">
|
||||
{SENT_DOCS(t).map(({ key, label }) => (
|
||||
<FormInput
|
||||
key={key}
|
||||
type="file"
|
||||
label={label}
|
||||
onFileChange={(f) => set(key, f as SberPaymentFormData[typeof key])}
|
||||
fileValue={form[key] as File | null}
|
||||
accept="image/*,.pdf"
|
||||
/>
|
||||
{SENT_DOC_DEFS.map((d) => (
|
||||
<DocField key={d.key} docKey={d.key} label={docLabel(d, t)} form={form} set={set} />
|
||||
))}
|
||||
</div>
|
||||
</BentoCard>
|
||||
@@ -379,13 +372,12 @@ function StepDocs({
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
interface StepDef {
|
||||
id: string;
|
||||
id: "general" | "location" | "personal" | "payment" | "docs";
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: SberPaymentFormData, mode: "create" | "edit", t: (key: string, fallback?: string) => string) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -396,7 +388,6 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "sberPayments.steps.general.subtitle",
|
||||
subtitleFallback: "Status, müşderi",
|
||||
icon: User,
|
||||
validate: (f, m, t) => validateStep(0, f, m, t),
|
||||
},
|
||||
{
|
||||
id: "location",
|
||||
@@ -405,7 +396,6 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "sberPayments.steps.location.subtitle",
|
||||
subtitleFallback: "Welaýat, şahamça",
|
||||
icon: MapPin,
|
||||
validate: (f, m, t) => validateStep(1, f, m, t),
|
||||
},
|
||||
{
|
||||
id: "personal",
|
||||
@@ -414,7 +404,6 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "sberPayments.steps.personal.subtitle",
|
||||
subtitleFallback: "Pasport, kontakt",
|
||||
icon: IdCard,
|
||||
validate: (f, m, t) => validateStep(2, f, m, t),
|
||||
},
|
||||
{
|
||||
id: "payment",
|
||||
@@ -423,114 +412,91 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "sberPayments.steps.payment.subtitle",
|
||||
subtitleFallback: "Hasap, ugradyjy",
|
||||
icon: CreditCard,
|
||||
validate: (f, m, t) => validateStep(3, f, m, t),
|
||||
},
|
||||
{
|
||||
id: "docs",
|
||||
titleKey: "sberPayments.steps.docs.title",
|
||||
titleFallback: "Resminamalar",
|
||||
subtitleKey: "sberPayments.steps.docs.subtitle",
|
||||
subtitleFallback: "14 resminama",
|
||||
subtitleFallback: `${ALL_DOC_KEYS.length} resminama`,
|
||||
icon: Files,
|
||||
validate: () => ({}),
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Initial data mapper ──────────────────────────────────────────────────────
|
||||
|
||||
function mapInitialData(data: SberPaymentOrder): Partial<SberPaymentFormData> {
|
||||
return {
|
||||
welayat: data.welayat,
|
||||
sahamca: data.sahamca,
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
address: data.address,
|
||||
status: data.status,
|
||||
bellik: data.bellik,
|
||||
accountNumber: data.accountNumber,
|
||||
passportSeries: data.passportSeries,
|
||||
passportNumber: data.passportNumber,
|
||||
fullName: data.fullName,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Main component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function SberPaymentForm({ mode, initialData }: SberPaymentFormProps) {
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback((key, fallback) => _t(key, fallback ?? key) as string, [_t]);
|
||||
const t: TFn = useCallback((key, fallback) => _t(key, fallback ?? key) as string, [_t]);
|
||||
const navigate = useNavigate();
|
||||
const createMutation = useCreateSberPayment();
|
||||
const updateMutation = useUpdateSberPayment();
|
||||
|
||||
const createMutation = useCreateIntlPayment();
|
||||
const updateMutation = useUpdateIntlPayment(initialData?.id ?? "");
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<SberPaymentFormData>({
|
||||
defaultValues: mode === "edit" && initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitialData(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
const [form, setForm] = useState<FormState>(() => (mode === "edit" && initialData ? mapInitialData(initialData) : DEFAULT_FORM_VALUES));
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set());
|
||||
|
||||
const set: SetFn = useCallback((key, value) => setForm((prev) => ({ ...prev, [key]: value })), []);
|
||||
|
||||
// ── Select options (current values are injected so edit never shows a blank select) ──
|
||||
|
||||
const clientOptions = useMemo<Option[]>(
|
||||
() => (form.client_id ? [{ value: form.client_id, label: initialData?.client_label || form.client_id }] : []),
|
||||
[form.client_id, initialData?.client_label],
|
||||
);
|
||||
|
||||
const provinceOptions = useMemo<Option[]>(() => {
|
||||
const base = WELAYATLAR.map((w) => ({ value: w, label: w }));
|
||||
if (form.province && !base.some((o) => o.value === form.province)) {
|
||||
base.unshift({ value: form.province, label: initialData?.province_label || form.province });
|
||||
}
|
||||
return base;
|
||||
}, [form.province, initialData?.province_label]);
|
||||
|
||||
// TODO: wire your branches query here (e.g. useInfiniteBranches filtered by form.province)
|
||||
// and map to { value: String(branch.id), label: localizedName }. Values MUST be branch IDs.
|
||||
const branchOptions = useMemo<Option[]>(
|
||||
() => (initialData?.branch ? [{ value: initialData.branch, label: initialData.branch_label || initialData.branch }] : []),
|
||||
[initialData?.branch, initialData?.branch_label],
|
||||
);
|
||||
|
||||
// ── Validation state ──
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>();
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i);
|
||||
if (Object.keys(validateStep(i, form, t)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited, i18n.language, t]);
|
||||
|
||||
const set = useCallback(
|
||||
<K extends keyof SberPaymentFormData>(key: K, value: SberPaymentFormData[K]) => {
|
||||
(setValue as (name: K, val: SberPaymentFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const allSubmittedErrors = useMemo(() => {
|
||||
const result: FlatErrors = {};
|
||||
for (const stepIdx of submittedSteps) {
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode, t));
|
||||
}
|
||||
return result;
|
||||
}, [form, mode, submittedSteps, i18n.language, t]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form, visited, t, i18n.language]);
|
||||
|
||||
const errors = useMemo(() => {
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
const result: FlatErrors = {};
|
||||
submittedSteps.forEach((i) => Object.assign(result, validateStep(i, form, t)));
|
||||
return result;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form, submittedSteps, t, i18n.language]);
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||
// ── Navigation ──
|
||||
|
||||
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||
|
||||
const markSubmitted = (i: number) => setSubmittedSteps((prev) => new Set([...prev, i]));
|
||||
const scrollTop = () => window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
|
||||
const handleNext = () => {
|
||||
markVisited(currentStep);
|
||||
markSubmitted(currentStep);
|
||||
const errs = STEPS[currentStep].validate(form, mode, t);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
Object.entries(errs).forEach(([key, msg]) => {
|
||||
setError(key as keyof SberPaymentFormData, { type: "manual", message: msg });
|
||||
});
|
||||
if (Object.keys(validateStep(currentStep, form, t)).length > 0) {
|
||||
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||
return;
|
||||
}
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
scrollTop();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -538,64 +504,54 @@ export function SberPaymentForm({ mode, initialData }: SberPaymentFormProps) {
|
||||
if (currentStep > 0) {
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(currentStep - 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
scrollTop();
|
||||
}
|
||||
};
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(i);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
scrollTop();
|
||||
};
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
// ── Submit ──
|
||||
|
||||
const doSubmit = () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
|
||||
const all = new Set(STEPS.map((_, i) => i));
|
||||
setVisited(all);
|
||||
setSubmittedSteps(all);
|
||||
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode, t));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
setError(key as keyof SberPaymentFormData, { type: "manual", message: msg });
|
||||
});
|
||||
const firstBad = STEPS.findIndex((_, i) => Object.keys(validateStep(i, form, t)).length > 0);
|
||||
if (firstBad !== -1) {
|
||||
toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) {
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
setCurrentStep(firstBad);
|
||||
scrollTop();
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues());
|
||||
const payload = buildPayload(form);
|
||||
const onSuccess = () => navigate("/sber-payments");
|
||||
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate("/sber-payments") });
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate({ ...payload, id: initialData.id }, { onSuccess: () => navigate("/sber-payments") });
|
||||
}
|
||||
if (mode === "create") createMutation.mutate(payload, { onSuccess });
|
||||
else if (initialData) updateMutation.mutate(payload, { onSuccess });
|
||||
};
|
||||
|
||||
// ── StepBarCards data ──
|
||||
// ── Step bar ──
|
||||
|
||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||
const isActive = i === currentStep;
|
||||
const hasErrors = stepsWithErrors.has(i);
|
||||
const isDone = visited.has(i) && !hasErrors;
|
||||
return {
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
subtitle: t(s.subtitleKey) || s.subtitleFallback,
|
||||
title: t(s.titleKey, s.titleFallback),
|
||||
subtitle: t(s.subtitleKey, s.subtitleFallback),
|
||||
icon: s.icon,
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
status: i === currentStep ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1;
|
||||
const stepId = STEPS[currentStep].id;
|
||||
|
||||
return (
|
||||
<div className="mx-auto space-y-6 pb-8">
|
||||
@@ -605,19 +561,18 @@ export function SberPaymentForm({ mode, initialData }: SberPaymentFormProps) {
|
||||
: t("sberPayments.formTitle.edit", "Sber töleg redaktirläň")}
|
||||
</h1>
|
||||
|
||||
{/* Step bar */}
|
||||
<div className="bg-card border border-border rounded-xl p-3 overflow-x-auto">
|
||||
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{STEPS[currentStep].id === "general" && <StepGeneral form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "location" && <StepLocation form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "personal" && <StepPersonal form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "payment" && <StepPayment form={form} errors={errors} set={set} t={t} />}
|
||||
{STEPS[currentStep].id === "docs" && <StepDocs form={form} set={set} t={t} />}
|
||||
{stepId === "general" && <StepGeneral form={form} errors={errors} set={set} t={t} clientOptions={clientOptions} />}
|
||||
{stepId === "location" && (
|
||||
<StepLocation form={form} errors={errors} set={set} t={t} provinceOptions={provinceOptions} branchOptions={branchOptions} />
|
||||
)}
|
||||
{stepId === "personal" && <StepPersonal form={form} errors={errors} set={set} t={t} />}
|
||||
{stepId === "payment" && <StepPayment form={form} errors={errors} set={set} t={t} />}
|
||||
{stepId === "docs" && <StepDocs form={form} set={set} t={t} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onCancel={() => navigate("/sber-payments")}
|
||||
|
||||
84
src/features/sberPayments/constants/documents.ts
Normal file
84
src/features/sberPayments/constants/documents.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import type { IntlPaymentDocs } from "@/features/visaMasterPayments/api/visaMasterPaymentsApi";
|
||||
|
||||
export type DocKey = keyof IntlPaymentDocs;
|
||||
export type TFn = (key: string, fallback?: string) => string;
|
||||
|
||||
interface DocDef {
|
||||
key: DocKey;
|
||||
i18nKey: string;
|
||||
fallback: string;
|
||||
}
|
||||
|
||||
// Backend keys behind each field are in DOC_FILE_TO_KEY (visaMasterPaymentsApi.ts).
|
||||
export const ACCEPTED_DOC_DEFS: DocDef[] = [
|
||||
{
|
||||
key: "doc_sberbank_account",
|
||||
i18nKey: "sberPayments.documents.sberbankCard",
|
||||
fallback: "Talýba degişli SBERBANK kartynyň rekwizitleri",
|
||||
},
|
||||
{
|
||||
key: "doc_school_enrollment",
|
||||
i18nKey: "sberPayments.documents.enrollment",
|
||||
fallback: "Daşary ýurt ÝOM-da okaýandygy baradaky güwänamasy",
|
||||
},
|
||||
{ key: "doc_summons", i18nKey: "sberPayments.documents.summons", fallback: "Çagyrylma hatynyn göçürmesi" },
|
||||
{ key: "doc_passport_tm", i18nKey: "sberPayments.documents.passportTm", fallback: "TM içki pasportynyň asyl görnüşi we göçürmesi" },
|
||||
{ key: "doc_foreign_passport", i18nKey: "sberPayments.documents.zagranPassport", fallback: "Daşary ýurt (zagran) pasportynyň göçürmesi" },
|
||||
{
|
||||
key: "doc_foreign_passport_copy",
|
||||
i18nKey: "sberPayments.documents.visaPage",
|
||||
fallback: "Daşary ýurda rugsat (wizasy) bellenen sahypasynyň göçürmesi",
|
||||
},
|
||||
{
|
||||
key: "doc_exit_permission",
|
||||
i18nKey: "sberPayments.documents.entryStamp",
|
||||
fallback: "Daşary ýurt döwletine girenligi baradaky ştamply sahypasynyň göçürmesi",
|
||||
},
|
||||
{
|
||||
key: "doc_school_foreign_info",
|
||||
i18nKey: "sberPayments.documents.schoolLetter",
|
||||
fallback: "ÝOM-dan hat (daşary ýurt dilinde maglumatly)",
|
||||
},
|
||||
];
|
||||
|
||||
export const SENT_DOC_DEFS: DocDef[] = [
|
||||
{
|
||||
key: "doc_school_departure_info",
|
||||
i18nKey: "sberPayments.documents.sentPassportTm",
|
||||
fallback: "Ugradyjynyň TM içki pasportynyň asyl görnüşi we göçürmesi",
|
||||
},
|
||||
{
|
||||
key: "upd_doc_passport_tm",
|
||||
i18nKey: "sberPayments.documents.sentZagranPassport",
|
||||
fallback: "Ugradyjynyň daşary ýurt pasportynyň asyl görnüşi we göçürmesi",
|
||||
},
|
||||
{
|
||||
key: "upd_doc_foreign_passport",
|
||||
i18nKey: "sberPayments.documents.sentEntryStamp",
|
||||
fallback: "Ugradyjynyň daşary döwletine girenligi ştamply sahypasynyň göçürmesi",
|
||||
},
|
||||
{
|
||||
key: "upd_doc_visa",
|
||||
i18nKey: "sberPayments.documents.sentRelationDoc",
|
||||
fallback: "Ugradyjy we kabul edijiniň garyndaşlyk tassyklaýjy resminamasynyn göçürmesi",
|
||||
},
|
||||
{
|
||||
key: "upd_doc_acceptance_letter",
|
||||
i18nKey: "sberPayments.documents.sentNewPassportSeries",
|
||||
fallback: "Ugradyjy/kabul ediji täze (2015+) pasport seriýasy maglumaty",
|
||||
},
|
||||
{
|
||||
key: "upd_doc_passport_biometric",
|
||||
i18nKey: "sberPayments.documents.sentPolicePassportSeries",
|
||||
fallback: "Ugradyjy/kabul ediji pasport seriýasy (polisiýa) maglumaty",
|
||||
},
|
||||
{
|
||||
key: "upd_doc_passport_old",
|
||||
i18nKey: "sberPayments.documents.sentOldPassportSeries",
|
||||
fallback: "Ugradyjy/kabul ediji köne pasport seriýasy baradaky güwänamasy",
|
||||
},
|
||||
];
|
||||
|
||||
export const ALL_DOC_KEYS: DocKey[] = [...ACCEPTED_DOC_DEFS, ...SENT_DOC_DEFS].map((d) => d.key);
|
||||
|
||||
export const docLabel = (d: DocDef, t: TFn) => t(d.i18nKey, d.fallback);
|
||||
@@ -1,79 +1,105 @@
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import {
|
||||
getSberPaymentOrders,
|
||||
getSberPaymentOrderById,
|
||||
createSberPaymentOrder,
|
||||
updateSberPaymentOrder,
|
||||
deleteSberPaymentOrder,
|
||||
sberPaymentRealApi,
|
||||
type SberPaymentListParams,
|
||||
type CreateSberPaymentPayload,
|
||||
type UpdateSberPaymentPayload,
|
||||
} from '../api/sberPaymentsApi'
|
||||
} from "../api/sberPaymentsApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const sberPaymentKeys = {
|
||||
all: ['sber-payments'] as const,
|
||||
lists: () => [...sberPaymentKeys.all, 'list'] as const,
|
||||
list: (params: Record<string, unknown>) => [...sberPaymentKeys.lists(), params] as const,
|
||||
details: () => [...sberPaymentKeys.all, 'detail'] as const,
|
||||
detail: (id: string) => [...sberPaymentKeys.details(), id] as const,
|
||||
export const SBER_PAYMENT_KEYS = {
|
||||
all: ["sber-payments-real"] as const,
|
||||
lists: () => [...SBER_PAYMENT_KEYS.all, "list"] as const,
|
||||
list: (p: SberPaymentListParams) => [...SBER_PAYMENT_KEYS.lists(), p] as const,
|
||||
details: () => [...SBER_PAYMENT_KEYS.all, "detail"] as const,
|
||||
detail: (id: string) => [...SBER_PAYMENT_KEYS.details(), id] as const,
|
||||
};
|
||||
|
||||
/** @deprecated use SBER_PAYMENT_KEYS */
|
||||
export const sberPaymentKeys = SBER_PAYMENT_KEYS;
|
||||
|
||||
// ─── Queries ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useSberPayments(params: SberPaymentListParams) {
|
||||
const debouncedName = useDebouncedValue(params.name ?? "");
|
||||
const normalized = normalizeSearch(debouncedName);
|
||||
const queryParams: SberPaymentListParams = { ...params, name: normalized || undefined };
|
||||
|
||||
return useQuery({
|
||||
queryKey: SBER_PAYMENT_KEYS.list(queryParams),
|
||||
queryFn: () => sberPaymentRealApi.list(queryParams),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Hooks ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useSberPaymentOrders(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
welayat?: string
|
||||
sahamca?: string
|
||||
status?: string
|
||||
}) {
|
||||
export function useSberPayment(id: string) {
|
||||
return useQuery({
|
||||
queryKey: sberPaymentKeys.list(params),
|
||||
queryFn: () => getSberPaymentOrders(params),
|
||||
})
|
||||
}
|
||||
|
||||
export function useSberPaymentOrder(id: string) {
|
||||
return useQuery({
|
||||
queryKey: sberPaymentKeys.detail(id),
|
||||
queryFn: () => getSberPaymentOrderById(id),
|
||||
queryKey: SBER_PAYMENT_KEYS.detail(id),
|
||||
queryFn: () => sberPaymentRealApi.getById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
/** @deprecated use useSberPayment. Now returns SberPaymentOrderItem, not the old mock shape. */
|
||||
export const useSberPaymentOrder = useSberPayment;
|
||||
|
||||
// ─── Mutations ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateSberPayment() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateSberPaymentPayload) => createSberPaymentOrder(payload),
|
||||
mutationFn: (payload: CreateSberPaymentPayload) => sberPaymentRealApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: sberPaymentKeys.lists() })
|
||||
qc.invalidateQueries({ queryKey: SBER_PAYMENT_KEYS.lists() });
|
||||
toast.success(t("sberPayments.createSuccess", "Töleg döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
/** Legacy signature: payload carries `id`. */
|
||||
export function useUpdateSberPayment() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateSberPaymentPayload) => updateSberPaymentOrder(payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: sberPaymentKeys.lists() })
|
||||
queryClient.setQueryData(sberPaymentKeys.detail(data.id), data)
|
||||
mutationFn: ({ id, ...rest }: UpdateSberPaymentPayload) => sberPaymentRealApi.update(id, rest),
|
||||
onSuccess: (_data, vars) => {
|
||||
qc.invalidateQueries({ queryKey: SBER_PAYMENT_KEYS.lists() });
|
||||
qc.invalidateQueries({ queryKey: SBER_PAYMENT_KEYS.detail(vars.id) });
|
||||
toast.success(t("sberPayments.updateSuccess", "Töleg üýtgedildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteSberPayment() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
export function useDeleteSberPaymentReal() {
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => deleteSberPaymentOrder(id),
|
||||
mutationFn: (id: string) => sberPaymentRealApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: sberPaymentKeys.lists() })
|
||||
qc.invalidateQueries({ queryKey: SBER_PAYMENT_KEYS.lists() });
|
||||
toast.success(t("sberPayments.deleteSuccess", "Töleg pozuldy"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
/** @deprecated use useDeleteSberPaymentReal */
|
||||
export const useDeleteSberPayment = useDeleteSberPaymentReal;
|
||||
|
||||
/** Id bound to the hook; use when the id is known at render time. */
|
||||
export function useUpdateSberPaymentReal(id: string) {
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
return useMutation({
|
||||
mutationFn: (payload: Record<string, unknown>) => sberPaymentRealApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: SBER_PAYMENT_KEYS.lists() });
|
||||
qc.invalidateQueries({ queryKey: SBER_PAYMENT_KEYS.detail(id) });
|
||||
toast.success(t("sberPayments.updateSuccess", "Töleg üýtgedildi"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -99,6 +99,7 @@ export interface IntlPaymentItem extends IntlPaymentDocs {
|
||||
branch_label: string;
|
||||
status: IntlPaymentStatus;
|
||||
note: string | null;
|
||||
paid: boolean;
|
||||
|
||||
// Şahsy maglumatlar
|
||||
passport_first_name: string;
|
||||
@@ -293,6 +294,7 @@ function mapBackendToUI(o: BackendIntlPayment): IntlPaymentItem {
|
||||
branch_label: o.branch?.name ? resolveLocalizedName(o.branch.name) : "",
|
||||
status,
|
||||
note: o.notes ?? "",
|
||||
paid: Boolean(o.paid),
|
||||
passport_first_name: o.passportName ?? "",
|
||||
passport_last_name: o.passportSurname ?? "",
|
||||
phone: formatFromApiPhone(o.phone),
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Search } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useGetOnlinePaymentById } from "@/features/onlinePaymentHistory/hooks/useOnlinePaymentsHistory";
|
||||
import type { PaymentHistoryStep } from "@/features/onlinePaymentHistory/api/onlinePaymentsHistoryApi";
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function formatDateTime(value: string | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
|
||||
const d = new Date(value);
|
||||
|
||||
if (Number.isNaN(d.getTime())) return "—";
|
||||
|
||||
const p = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
return `${p(d.getDate())}/${p(d.getMonth() + 1)}/${d.getFullYear()}, ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function detailEntries(detail: PaymentHistoryStep["detail"] | null | undefined): [string, string][] {
|
||||
if (!detail || typeof detail !== "object") return [];
|
||||
|
||||
return Object.entries(detail).map(([key, value]) => [key, value == null ? "—" : String(value)]);
|
||||
}
|
||||
|
||||
function matches(row: PaymentHistoryStep, query: string): boolean {
|
||||
const haystack = [row.step, row.createdByName, ...detailEntries(row.detail).flat()].join(" ").toLowerCase();
|
||||
|
||||
return haystack.includes(query);
|
||||
}
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
interface PaymentHistoryTableProps {
|
||||
orderId: string | undefined;
|
||||
}
|
||||
|
||||
export function PaymentHistoryTable({ orderId }: PaymentHistoryTableProps) {
|
||||
const { t } = useTranslation();
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const { data, isLoading, isError } = useGetOnlinePaymentById(Number(orderId));
|
||||
|
||||
const rows = useMemo(() => {
|
||||
const sorted = [...(data ?? [])].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
|
||||
const query = search.trim().toLowerCase();
|
||||
|
||||
return query ? sorted.filter((row) => matches(row, query)) : sorted;
|
||||
}, [data, search]);
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
{/* Search */}
|
||||
<div className="relative mb-4 max-w-xs">
|
||||
<Search size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
className="
|
||||
h-9
|
||||
w-full
|
||||
rounded-md
|
||||
border
|
||||
border-border
|
||||
bg-background
|
||||
pl-9
|
||||
pr-3
|
||||
text-sm
|
||||
focus:outline-none
|
||||
focus:ring-2
|
||||
focus:ring-ring
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Loading */}
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{[...Array(4)].map((_, index) => (
|
||||
<Skeleton key={index} className="h-10 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : isError ? (
|
||||
/* Error */
|
||||
<div className="py-10 text-center text-sm text-destructive">
|
||||
{t("paymentHistory.loadError", "Töleg taryhyny ýüklemek başartmady")}
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
/* Empty */
|
||||
<div className="flex flex-col items-center justify-center py-10 text-muted-foreground/50">
|
||||
<div className="mb-3 flex h-12 w-12 items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/20">
|
||||
<svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth={1.5}>
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" />
|
||||
<line x1="3" y1="9" x2="21" y2="9" />
|
||||
<line x1="9" y1="21" x2="9" y2="9" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<p className="text-sm">{t("paymentHistory.empty", "Berlen kriteriýalara Töleg gabat gelmedi.")}</p>
|
||||
</div>
|
||||
) : (
|
||||
/* Table */
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50 text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-medium">{t("paymentHistory.col.id", "ID")}</th>
|
||||
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-medium">{t("paymentHistory.col.step", "Ädim")}</th>
|
||||
|
||||
<th className="px-4 py-2.5 font-medium">{t("paymentHistory.col.detail", "Jikme-jiklik")}</th>
|
||||
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-medium">{t("paymentHistory.col.createdBy", "Kim tarapyndan")}</th>
|
||||
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-medium">{t("paymentHistory.col.createdAt", "Wagty")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{rows.map((row) => {
|
||||
const entries = detailEntries(row.detail);
|
||||
|
||||
return (
|
||||
<tr key={row.id} className="border-t border-border align-top">
|
||||
{/* ID */}
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-muted-foreground">{row.id}</td>
|
||||
|
||||
{/* Step */}
|
||||
<td className="whitespace-nowrap px-4 py-2.5 font-medium">{t(`paymentHistory.steps.${row.step}`, row.step)}</td>
|
||||
|
||||
{/* Details */}
|
||||
<td className="px-4 py-2.5">
|
||||
{entries.length === 0 ? (
|
||||
<span className="text-muted-foreground/50">—</span>
|
||||
) : (
|
||||
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs">
|
||||
{entries.map(([key, value]) => (
|
||||
<div key={key} className="contents">
|
||||
<dt className="text-muted-foreground">{key}</dt>
|
||||
|
||||
<dd className="break-all">{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Created By */}
|
||||
<td className="whitespace-nowrap px-4 py-2.5">{row.createdByName || "—"}</td>
|
||||
|
||||
{/* Created At */}
|
||||
<td className="whitespace-nowrap px-4 py-2.5 text-muted-foreground">{formatDateTime(row.createdAt)}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,126 +1,96 @@
|
||||
// features/visaMasterSettings/api/visaMasterSettingsApi.ts
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
export interface PaymentTextI18n {
|
||||
en: string;
|
||||
ru: string;
|
||||
tm: string;
|
||||
}
|
||||
|
||||
export interface VisaMasterSetting {
|
||||
id: number
|
||||
kod: string
|
||||
ady: string
|
||||
yazgy: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
code: string;
|
||||
id: number;
|
||||
isActive: boolean;
|
||||
name: string;
|
||||
text: PaymentTextI18n;
|
||||
updatedAt: string;
|
||||
updatedById: number;
|
||||
updatedByName: string;
|
||||
}
|
||||
|
||||
export interface VisaMasterSettingListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
export interface VisaMasterSettingListResponse {
|
||||
data: VisaMasterSetting[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
data: VisaMasterSetting[];
|
||||
total: number;
|
||||
page: number;
|
||||
perPage: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export interface VisaMasterSettingPayload {
|
||||
kod: string
|
||||
ady: string
|
||||
yazgy: string
|
||||
export interface VisaMasterSettingCreatePayload {
|
||||
code: string;
|
||||
name: string;
|
||||
isActive: boolean;
|
||||
text: PaymentTextI18n;
|
||||
}
|
||||
|
||||
// ─── Mock Store ───────────────────────────────────────────────────────────────
|
||||
|
||||
let mockStore: VisaMasterSetting[] = [
|
||||
{
|
||||
id: 2,
|
||||
kod: 'sber_payment_warning',
|
||||
ady: 'Sber töleg duýduryş',
|
||||
yazgy: 'Sber töleg duýduryş',
|
||||
createdAt: '2026-03-10T08:00:00Z',
|
||||
updatedAt: '2026-05-01T08:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
kod: 'payment_warning_text',
|
||||
ady: 'Visa/Master töleg duýduryş',
|
||||
yazgy: 'Dogry töleg aýyny saýlamagyňyzy haýyş edýäris!!!!',
|
||||
createdAt: '2026-01-05T09:00:00Z',
|
||||
updatedAt: '2026-04-20T09:00:00Z',
|
||||
},
|
||||
]
|
||||
|
||||
let nextId = 3
|
||||
|
||||
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchVisaMasterSettings(
|
||||
params: VisaMasterSettingListParams = {}
|
||||
): Promise<VisaMasterSettingListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '' } = params
|
||||
|
||||
let filtered = [...mockStore]
|
||||
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(r) =>
|
||||
r.kod.toLowerCase().includes(q) ||
|
||||
r.ady.toLowerCase().includes(q) ||
|
||||
r.yazgy.toLowerCase().includes(q) ||
|
||||
String(r.id).includes(q)
|
||||
)
|
||||
}
|
||||
|
||||
filtered.sort((a, b) => b.id - a.id)
|
||||
|
||||
const total = filtered.length
|
||||
const totalPages = Math.ceil(total / perPage) || 1
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage, totalPages }
|
||||
export interface VisaMasterSettingUpdatePayload {
|
||||
name: string;
|
||||
isActive: boolean;
|
||||
text: PaymentTextI18n;
|
||||
}
|
||||
|
||||
export async function fetchVisaMasterSettingById(id: number): Promise<VisaMasterSetting> {
|
||||
await delay()
|
||||
const item = mockStore.find((r) => r.id === id)
|
||||
if (!item) throw new Error(`VisaMasterSetting with id ${id} not found`)
|
||||
return { ...item }
|
||||
interface ServerListResponse {
|
||||
count: number;
|
||||
items: VisaMasterSetting[];
|
||||
}
|
||||
|
||||
export async function createVisaMasterSetting(
|
||||
payload: VisaMasterSettingPayload
|
||||
): Promise<VisaMasterSetting> {
|
||||
await delay()
|
||||
const now = new Date().toISOString()
|
||||
const created: VisaMasterSetting = { id: nextId++, ...payload, createdAt: now, updatedAt: now }
|
||||
mockStore = [created, ...mockStore]
|
||||
return created
|
||||
async function fetchAll(search?: string): Promise<ServerListResponse> {
|
||||
const { data } = await apiClient.get<ServerListResponse>("/payment-texts", {
|
||||
params: search?.trim() ? { search: search.trim() } : undefined,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateVisaMasterSetting(
|
||||
id: number,
|
||||
payload: VisaMasterSettingPayload
|
||||
): Promise<VisaMasterSetting> {
|
||||
await delay()
|
||||
const idx = mockStore.findIndex((r) => r.id === id)
|
||||
if (idx === -1) throw new Error(`VisaMasterSetting with id ${id} not found`)
|
||||
const updated: VisaMasterSetting = {
|
||||
...mockStore[idx],
|
||||
...payload,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
mockStore = mockStore.map((r) => (r.id === id ? updated : r))
|
||||
return updated
|
||||
export async function fetchVisaMasterSettings(params: VisaMasterSettingListParams = {}): Promise<VisaMasterSettingListResponse> {
|
||||
const { page = 1, perPage = 25, search = "" } = params;
|
||||
const res = await fetchAll(search);
|
||||
|
||||
const items = res.items ?? [];
|
||||
const total = items.length;
|
||||
const totalPages = Math.ceil(total / perPage) || 1;
|
||||
const start = (page - 1) * perPage;
|
||||
|
||||
return {
|
||||
data: items.slice(start, start + perPage),
|
||||
total,
|
||||
page,
|
||||
perPage,
|
||||
totalPages,
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteVisaMasterSetting(id: number): Promise<void> {
|
||||
await delay()
|
||||
if (!mockStore.some((r) => r.id === id))
|
||||
throw new Error(`VisaMasterSetting with id ${id} not found`)
|
||||
mockStore = mockStore.filter((r) => r.id !== id)
|
||||
}
|
||||
export async function fetchVisaMasterSettingByCode(code: string): Promise<VisaMasterSetting> {
|
||||
const res = await fetchAll(code);
|
||||
const item = (res.items ?? []).find((r) => r.code === code);
|
||||
if (!item) throw new Error(`Payment text "${code}" not found`);
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function createVisaMasterSetting(payload: VisaMasterSettingCreatePayload): Promise<VisaMasterSetting> {
|
||||
const { data } = await apiClient.post<VisaMasterSetting>("/payment-texts", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateVisaMasterSetting(code: string, payload: VisaMasterSettingUpdatePayload): Promise<VisaMasterSetting> {
|
||||
const { data } = await apiClient.put<VisaMasterSetting>(`/payment-texts/${encodeURIComponent(code)}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteVisaMasterSetting(code: string): Promise<void> {
|
||||
await apiClient.delete(`/payment-texts/${encodeURIComponent(code)}`);
|
||||
}
|
||||
|
||||
@@ -9,23 +9,29 @@ import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { VisaMasterSetting } from "../api/visaMasterSberSettingsApi";
|
||||
import { useCreateVisaMasterSetting, useUpdateVisaMasterSetting } from "../hooks/useVisaMasterSettings";
|
||||
import { createVisaMasterSettingFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/visaMasterSberSetting.schema";
|
||||
import {
|
||||
createVisaMasterSettingFormSchema,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildCreatePayload,
|
||||
buildUpdatePayload,
|
||||
} from "../schemas/visaMasterSberSetting.schema";
|
||||
import type { VisaMasterSettingFormData } from "../schemas/visaMasterSberSetting.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
const LIST_PATH = "/visa-master-sber-settings";
|
||||
|
||||
export interface VisaMasterSettingFormProps {
|
||||
mode: "create" | "edit";
|
||||
initialData?: VisaMasterSetting;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function mapInitial(data: VisaMasterSetting): VisaMasterSettingFormData {
|
||||
return {
|
||||
kod: data.kod,
|
||||
ady: data.ady,
|
||||
yazgy: data.yazgy,
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
isActive: data.isActive,
|
||||
textTm: data.text?.tm ?? "",
|
||||
textRu: data.text?.ru ?? "",
|
||||
textEn: data.text?.en ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -40,8 +46,6 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── VisaMasterSettingForm ────────────────────────────────────────────────────
|
||||
|
||||
export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFormProps) {
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
@@ -53,8 +57,7 @@ export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFo
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateVisaMasterSetting();
|
||||
const updateMutation = useUpdateVisaMasterSetting(initialData?.id ?? 0);
|
||||
|
||||
const updateMutation = useUpdateVisaMasterSetting(initialData?.code ?? "");
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(
|
||||
@@ -79,14 +82,12 @@ export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFo
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) {
|
||||
trigger();
|
||||
}
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language]);
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof VisaMasterSettingFormData) => (value: string) => {
|
||||
(key: Exclude<keyof VisaMasterSettingFormData, "isActive">) => (value: string) => {
|
||||
setValue(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
@@ -100,20 +101,21 @@ export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFo
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues());
|
||||
const values = getValues();
|
||||
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(payload);
|
||||
navigate("/resources/visa-master-settings");
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate("/resources/visa-master-settings");
|
||||
try {
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(buildCreatePayload(values));
|
||||
} else {
|
||||
await updateMutation.mutateAsync(buildUpdatePayload(values));
|
||||
}
|
||||
navigate(LIST_PATH);
|
||||
} catch {
|
||||
// error toast is handled in the mutation hooks
|
||||
}
|
||||
}, [mode, createMutation, updateMutation, navigate, trigger, getValues, t]);
|
||||
|
||||
const handleCancel = () => navigate("/resources/visa-master-settings");
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
const handleCancel = () => navigate(LIST_PATH);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
@@ -122,16 +124,17 @@ export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFo
|
||||
? t("visaMasterSettings.createTitle", "Visa/Master, Sber sazlamalar dörediň")
|
||||
: t("visaMasterSettings.editTitle", "Visa/Master, Sber sazlamalar üýtgetmek")}
|
||||
</h1>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("visaMasterSettings.fields.kod", "Kod")}
|
||||
value={form.kod}
|
||||
onChange={set("kod")}
|
||||
value={form.code}
|
||||
onChange={set("code")}
|
||||
placeholder={t("visaMasterSettings.fields.kod", "Kod")}
|
||||
error={errMsg(errors.kod)}
|
||||
disabled={isPending}
|
||||
error={errMsg(errors.code)}
|
||||
disabled={isPending || mode === "edit"}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -139,28 +142,65 @@ export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFo
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("visaMasterSettings.fields.ady", "Ady")}
|
||||
value={form.ady}
|
||||
onChange={set("ady")}
|
||||
value={form.name}
|
||||
onChange={set("name")}
|
||||
placeholder={t("visaMasterSettings.fields.ady", "Ady")}
|
||||
error={errMsg(errors.ady)}
|
||||
error={errMsg(errors.name)}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("visaMasterSettings.fields.yazgy", "Yazgy")}
|
||||
value={form.yazgy}
|
||||
onChange={set("yazgy")}
|
||||
placeholder={t("visaMasterSettings.fields.yazgy", "Yazgy")}
|
||||
error={errMsg(errors.yazgy)}
|
||||
label={t("visaMasterSettings.fields.textTm", "Tekst (TM)")}
|
||||
value={form.textTm}
|
||||
onChange={set("textTm")}
|
||||
placeholder={t("visaMasterSettings.fields.textTm", "Tekst (TM)")}
|
||||
error={errMsg(errors.textTm)}
|
||||
disabled={isPending}
|
||||
rows={3}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("visaMasterSettings.fields.textRu", "Tekst (RU)")}
|
||||
value={form.textRu}
|
||||
onChange={set("textRu")}
|
||||
placeholder={t("visaMasterSettings.fields.textRu", "Tekst (RU)")}
|
||||
error={errMsg(errors.textRu)}
|
||||
disabled={isPending}
|
||||
rows={3}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("visaMasterSettings.fields.textEn", "Tekst (EN)")}
|
||||
value={form.textEn}
|
||||
onChange={set("textEn")}
|
||||
placeholder={t("visaMasterSettings.fields.textEn", "Tekst (EN)")}
|
||||
error={errMsg(errors.textEn)}
|
||||
disabled={isPending}
|
||||
rows={3}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<label className="flex items-center gap-2 text-sm text-foreground cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4"
|
||||
checked={form.isActive}
|
||||
disabled={isPending}
|
||||
onChange={(e) => setValue("isActive", e.target.checked)}
|
||||
/>
|
||||
{t("visaMasterSettings.fields.isActive", "Aktiw")}
|
||||
</label>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
|
||||
@@ -1,90 +1,90 @@
|
||||
// features/visaMasterSettings/hooks/useVisaMasterSettings.ts
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
fetchVisaMasterSettings,
|
||||
fetchVisaMasterSettingById,
|
||||
fetchVisaMasterSettingByCode,
|
||||
createVisaMasterSetting,
|
||||
updateVisaMasterSetting,
|
||||
deleteVisaMasterSetting,
|
||||
type VisaMasterSettingListParams,
|
||||
type VisaMasterSettingPayload,
|
||||
} from '../api/visaMasterSberSettingsApi'
|
||||
type VisaMasterSettingCreatePayload,
|
||||
type VisaMasterSettingUpdatePayload,
|
||||
} from "../api/visaMasterSberSettingsApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const visaMasterSettingKeys = {
|
||||
all: ['visaMasterSettings'] as const,
|
||||
lists: () => [...visaMasterSettingKeys.all, 'list'] as const,
|
||||
list: (params: VisaMasterSettingListParams) =>
|
||||
[...visaMasterSettingKeys.lists(), params] as const,
|
||||
detail: (id: number) =>
|
||||
[...visaMasterSettingKeys.all, 'detail', id] as const,
|
||||
}
|
||||
all: ["visaMasterSettings"] as const,
|
||||
lists: () => [...visaMasterSettingKeys.all, "list"] as const,
|
||||
list: (params: VisaMasterSettingListParams) => [...visaMasterSettingKeys.lists(), params] as const,
|
||||
detail: (code: string) => [...visaMasterSettingKeys.all, "detail", code] as const,
|
||||
};
|
||||
|
||||
// ─── useGetVisaMasterSettings ─────────────────────────────────────────────────
|
||||
// ─── Queries ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useGetVisaMasterSettings(params: VisaMasterSettingListParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: visaMasterSettingKeys.list(params),
|
||||
queryFn: () => fetchVisaMasterSettings(params),
|
||||
})
|
||||
queryFn: () => fetchVisaMasterSettings(params),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useGetVisaMasterSettingById ──────────────────────────────────────────────
|
||||
|
||||
export function useGetVisaMasterSettingById(id: number) {
|
||||
export function useGetVisaMasterSettingByCode(code: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: visaMasterSettingKeys.detail(id),
|
||||
queryFn: () => fetchVisaMasterSettingById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
queryKey: visaMasterSettingKeys.detail(code ?? ""),
|
||||
queryFn: () => fetchVisaMasterSettingByCode(code as string),
|
||||
enabled: !!code,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreateVisaMasterSetting ───────────────────────────────────────────────
|
||||
// ─── Mutations ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateVisaMasterSetting() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: VisaMasterSettingPayload) => createVisaMasterSetting(payload),
|
||||
mutationFn: (payload: VisaMasterSettingCreatePayload) => createVisaMasterSetting(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() })
|
||||
toast.success(t('visaMasterSettings.toast.created', 'Sazlama döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() });
|
||||
toast.success(t("visaMasterSettings.toast.created", "Sazlama döredildi"));
|
||||
},
|
||||
})
|
||||
onError: (err: any) => {
|
||||
toast.error(err?.response?.data?.message ?? t("common.errors.generic", "Ýalňyşlyk ýüze çykdy"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdateVisaMasterSetting ───────────────────────────────────────────────
|
||||
|
||||
export function useUpdateVisaMasterSetting(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
export function useUpdateVisaMasterSetting(code: string) {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: VisaMasterSettingPayload) => updateVisaMasterSetting(id, payload),
|
||||
mutationFn: (payload: VisaMasterSettingUpdatePayload) => updateVisaMasterSetting(code, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.detail(id) })
|
||||
toast.success(t('visaMasterSettings.toast.updated', 'Sazlama üýtgedildi'))
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.detail(code) });
|
||||
toast.success(t("visaMasterSettings.toast.updated", "Sazlama üýtgedildi"));
|
||||
},
|
||||
})
|
||||
onError: (err: any) => {
|
||||
toast.error(err?.response?.data?.message ?? t("common.errors.generic", "Ýalňyşlyk ýüze çykdy"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeleteVisaMasterSetting ───────────────────────────────────────────────
|
||||
|
||||
export function useDeleteVisaMasterSetting() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteVisaMasterSetting(id),
|
||||
mutationFn: (code: string) => deleteVisaMasterSetting(code),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() })
|
||||
toast.success(t('visaMasterSettings.toast.deleted', 'Sazlama pozuldy'))
|
||||
queryClient.invalidateQueries({ queryKey: visaMasterSettingKeys.lists() });
|
||||
toast.success(t("visaMasterSettings.toast.deleted", "Sazlama pozuldy"));
|
||||
},
|
||||
})
|
||||
}
|
||||
onError: (err: any) => {
|
||||
toast.error(err?.response?.data?.message ?? t("common.errors.generic", "Ýalňyşlyk ýüze çykdy"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,28 +1,47 @@
|
||||
import { z } from 'zod'
|
||||
import type { VisaMasterSettingPayload } from '../api/visaMasterSberSettingsApi'
|
||||
import { z } from "zod";
|
||||
import type { VisaMasterSettingCreatePayload, VisaMasterSettingUpdatePayload } from "../api/visaMasterSberSettingsApi";
|
||||
|
||||
export function createVisaMasterSettingFormSchema(
|
||||
t: (key: string, fallback?: string) => string,
|
||||
) {
|
||||
type TFn = (key: string, fallback?: string) => string;
|
||||
|
||||
export function createVisaMasterSettingFormSchema(t: TFn) {
|
||||
return z.object({
|
||||
kod: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
ady: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
yazgy: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
code: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, t("validation.required", "Hökmany meýdan"))
|
||||
.regex(/^[a-zA-Z0-9_]+$/, t("validation.codeFormat", "Diňe harplar, sanlar we _ ulanyň")),
|
||||
name: z.string().trim().min(1, t("validation.required", "Hökmany meýdan")),
|
||||
isActive: z.boolean(),
|
||||
textTm: z.string().trim().min(1, t("validation.required", "Hökmany meýdan")),
|
||||
textRu: z.string(),
|
||||
textEn: z.string(),
|
||||
});
|
||||
}
|
||||
|
||||
export type VisaMasterSettingFormData = z.infer<ReturnType<typeof createVisaMasterSettingFormSchema>>
|
||||
export type VisaMasterSettingFormData = z.infer<ReturnType<typeof createVisaMasterSettingFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: VisaMasterSettingFormData = {
|
||||
kod: '',
|
||||
ady: '',
|
||||
yazgy: '',
|
||||
code: "",
|
||||
name: "",
|
||||
isActive: true,
|
||||
textTm: "",
|
||||
textRu: "",
|
||||
textEn: "",
|
||||
};
|
||||
|
||||
export function buildCreatePayload(v: VisaMasterSettingFormData): VisaMasterSettingCreatePayload {
|
||||
return {
|
||||
code: v.code.trim(),
|
||||
name: v.name.trim(),
|
||||
isActive: v.isActive,
|
||||
text: { tm: v.textTm.trim(), ru: v.textRu.trim(), en: v.textEn.trim() },
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPayload(data: VisaMasterSettingFormData): VisaMasterSettingPayload {
|
||||
export function buildUpdatePayload(v: VisaMasterSettingFormData): VisaMasterSettingUpdatePayload {
|
||||
return {
|
||||
kod: data.kod.trim(),
|
||||
ady: data.ady.trim(),
|
||||
yazgy: data.yazgy.trim(),
|
||||
}
|
||||
name: v.name.trim(),
|
||||
isActive: v.isActive,
|
||||
text: { tm: v.textTm.trim(), ru: v.textRu.trim(), en: v.textEn.trim() },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -36,7 +36,8 @@ export default function CardBalancesPage() {
|
||||
{ fieldId: "created_by", value: "" },
|
||||
]);
|
||||
|
||||
// ── Infinite user dropdown for created_by filter ────────────────────────────
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const isUserFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "created_by")?.value);
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const {
|
||||
@@ -45,7 +46,7 @@ export default function CardBalancesPage() {
|
||||
hasNextPage: hasNextUsers,
|
||||
isFetchingNextPage: isFetchingNextUsers,
|
||||
isLoading: isUsersLoading,
|
||||
} = useInfiniteUsers(userSearch);
|
||||
} = useInfiniteUsers(userSearch, isUserFilterEnabled);
|
||||
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
@@ -286,6 +287,9 @@ export default function CardBalancesPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -48,6 +48,11 @@ export default function CardRequisitesPage() {
|
||||
|
||||
// ── Infinite dropdown hooks ─────────────────────────────────────────────────
|
||||
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const isBranchFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "branch_id")?.value);
|
||||
const isCardTypeFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "card_type_id")?.value);
|
||||
const isUserFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "user_id")?.value);
|
||||
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
@@ -55,7 +60,7 @@ export default function CardRequisitesPage() {
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
} = useInfiniteBranches(branchSearch, isBranchFilterEnabled);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
@@ -75,7 +80,7 @@ export default function CardRequisitesPage() {
|
||||
hasNextPage: hasNextCardTypes,
|
||||
isFetchingNextPage: isFetchingNextCardTypes,
|
||||
isLoading: isCardTypesLoading,
|
||||
} = useInfiniteCardTypes(cardTypeSearch);
|
||||
} = useInfiniteCardTypes(cardTypeSearch, isCardTypeFilterEnabled);
|
||||
|
||||
const cardTypeOptions = useMemo(
|
||||
() =>
|
||||
@@ -95,7 +100,7 @@ export default function CardRequisitesPage() {
|
||||
hasNextPage: hasNextClients,
|
||||
isFetchingNextPage: isFetchingNextClients,
|
||||
isLoading: isClientsLoading,
|
||||
} = useInfiniteClients(userSearch);
|
||||
} = useInfiniteClients(userSearch, isUserFilterEnabled);
|
||||
|
||||
const clientOptions = useMemo(
|
||||
() =>
|
||||
@@ -390,6 +395,9 @@ export default function CardRequisitesPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -34,6 +34,10 @@ export default function CardTransactionsPage() {
|
||||
]);
|
||||
|
||||
// ── Filter option sources ───────────────────────────────────────────────────
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const isUserFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "user_id")?.value);
|
||||
const isCardTypeFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "type")?.value);
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const {
|
||||
data: usersData,
|
||||
@@ -41,7 +45,7 @@ export default function CardTransactionsPage() {
|
||||
hasNextPage: hasNextUsers,
|
||||
isFetchingNextPage: isFetchingNextUsers,
|
||||
isLoading: isUsersLoading,
|
||||
} = useInfiniteClients(userSearch);
|
||||
} = useInfiniteClients(userSearch, isUserFilterEnabled);
|
||||
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
@@ -61,7 +65,7 @@ export default function CardTransactionsPage() {
|
||||
hasNextPage: hasNextCardTypes,
|
||||
isFetchingNextPage: isFetchingNextCardTypes,
|
||||
isLoading: isCardTypesLoading,
|
||||
} = useInfiniteCardTypes(typeSearch);
|
||||
} = useInfiniteCardTypes(typeSearch, isCardTypeFilterEnabled);
|
||||
|
||||
const cardTypeOptions = useMemo(() => {
|
||||
const langKey = i18n.language as "tm" | "ru" | "en";
|
||||
@@ -316,6 +320,9 @@ export default function CardTransactionsPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -48,17 +48,24 @@ export default function CardOrdersPage() {
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>(INITIAL_FILTERS);
|
||||
|
||||
// ── Query ──────────────────────────────────────────────────────────────────
|
||||
const getFilter = useCallback((id: FilterId) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
||||
|
||||
// ── Dropdown data ──────────────────────────────────────────────────────────
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const [cardTypeSearch, setCardTypeSearch] = useState("");
|
||||
|
||||
const isBranchFilterEnabled = filterEnabled || Boolean(getFilter("branch_id"));
|
||||
const isCardTypeFilterEnabled = filterEnabled || Boolean(getFilter("card_type_id"));
|
||||
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
} = useInfiniteBranches(branchSearch, isBranchFilterEnabled);
|
||||
|
||||
const {
|
||||
data: cardTypesInfiniteData,
|
||||
@@ -66,10 +73,7 @@ export default function CardOrdersPage() {
|
||||
hasNextPage: hasNextCardTypes,
|
||||
isFetchingNextPage: isFetchingNextCardTypes,
|
||||
isLoading: isCardTypesLoading,
|
||||
} = useInfiniteCardTypes(cardTypeSearch);
|
||||
|
||||
// ── Query ──────────────────────────────────────────────────────────────────
|
||||
const getFilter = useCallback((id: FilterId) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
||||
} = useInfiniteCardTypes(cardTypeSearch, isCardTypeFilterEnabled);
|
||||
|
||||
const queryParams = useMemo(
|
||||
() => ({
|
||||
@@ -384,6 +388,9 @@ export default function CardOrdersPage() {
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
// pages/VisaMasterSettingsPage.tsx
|
||||
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -13,12 +11,8 @@ import { CreateButton } from "@/components/createButton";
|
||||
import { useGetVisaMasterSettings, useDeleteVisaMasterSetting } from "@/features/visaMasterSberSettings/hooks/useVisaMasterSettings";
|
||||
import type { VisaMasterSetting } from "@/features/visaMasterSberSettings/api/visaMasterSberSettingsApi";
|
||||
|
||||
// ─── Column defaults ──────────────────────────────────────────────────────────
|
||||
|
||||
const DEFAULT_VISIBILITY = { id: true, kod: true, ady: true, yazgy: true };
|
||||
const DEFAULT_ORDER = ["id", "kod", "ady", "yazgy", "actions"];
|
||||
|
||||
// ─── VisaMasterSettingsPage ───────────────────────────────────────────────────
|
||||
const DEFAULT_VISIBILITY = { code: true, name: true, text: true, isActive: true, updatedAt: true, updatedByName: true };
|
||||
const DEFAULT_ORDER = ["code", "name", "text", "isActive", "updatedAt", "updatedByName", "actions"];
|
||||
|
||||
export default function VisaMasterSettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -29,15 +23,19 @@ export default function VisaMasterSettingsPage() {
|
||||
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 [deleteCode, setDeleteCode] = useState<string | null>(null);
|
||||
|
||||
const { data, isLoading } = useGetVisaMasterSettings({ page, perPage, search });
|
||||
const deleteMutation = useDeleteVisaMasterSetting();
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (deleteId === null) return;
|
||||
await deleteMutation.mutateAsync(deleteId);
|
||||
setDeleteId(null);
|
||||
if (deleteCode === null) return;
|
||||
try {
|
||||
await deleteMutation.mutateAsync(deleteCode);
|
||||
setDeleteCode(null);
|
||||
} catch {
|
||||
// error toast handled in hook
|
||||
}
|
||||
};
|
||||
|
||||
const handleSearchChange = (val: string) => {
|
||||
@@ -45,29 +43,43 @@ export default function VisaMasterSettingsPage() {
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
// ─── Columns ──────────────────────────────────────────────────────────────
|
||||
|
||||
const columns: ColumnDef<VisaMasterSetting>[] = [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: "ID",
|
||||
cell: ({ row }) => <span className="text-primary font-semibold">{row.original.id}</span>,
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
accessorKey: "kod",
|
||||
accessorKey: "code",
|
||||
header: t("visaMasterSettings.columns.kod", "KOD"),
|
||||
cell: ({ row }) => <span className="font-medium text-foreground font-mono text-xs">{row.original.kod}</span>,
|
||||
cell: ({ row }) => <span className="font-medium text-primary font-mono text-xs">{row.original.code}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "ady",
|
||||
accessorKey: "name",
|
||||
header: t("visaMasterSettings.columns.ady", "ADY"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.ady}</span>,
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.name}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "yazgy",
|
||||
id: "text",
|
||||
accessorFn: (row) => row.text?.tm ?? "",
|
||||
header: t("visaMasterSettings.columns.yazgy", "YAZGY"),
|
||||
cell: ({ row }) => <span className="text-foreground line-clamp-1 max-w-xs">{row.original.yazgy}</span>,
|
||||
cell: ({ row }) => <span className="text-foreground line-clamp-1 max-w-xs">{row.original.text?.tm}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "isActive",
|
||||
header: t("visaMasterSettings.columns.isActive", "AKTIW"),
|
||||
cell: ({ row }) => (
|
||||
<span className={row.original.isActive ? "text-green-600" : "text-muted-foreground"}>
|
||||
{row.original.isActive ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: t("visaMasterSettings.columns.updatedAt", "ÜÝTGEDILEN"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground text-xs">{row.original.updatedAt ? new Date(row.original.updatedAt).toLocaleString() : "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedByName",
|
||||
header: t("visaMasterSettings.columns.updatedBy", "ÜÝTGEDEN"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.updatedByName || "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -76,8 +88,8 @@ export default function VisaMasterSettingsPage() {
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onEdit={() => navigate(`/visa-master-sber-settings/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
onEdit={() => navigate(`/visa-master-sber-settings/${encodeURIComponent(row.original.code)}/edit`)}
|
||||
onDelete={() => setDeleteCode(row.original.code)}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
@@ -85,14 +97,12 @@ export default function VisaMasterSettingsPage() {
|
||||
];
|
||||
|
||||
const columnMeta = columns
|
||||
.filter((c) => "accessorKey" in c && c.accessorKey)
|
||||
.filter((c) => c.id !== "actions")
|
||||
.map((c) => ({
|
||||
id: String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""),
|
||||
label: typeof c.header === "string" ? c.header : String(("accessorKey" in c ? c.accessorKey : "") ?? ""),
|
||||
label: typeof c.header === "string" ? c.header : String(("accessorKey" in c ? c.accessorKey : c.id) ?? ""),
|
||||
}));
|
||||
|
||||
// ─── Render ───────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-2xl font-semibold text-foreground mb-5">{t("visaMasterSettings.title", "Visa/Master, Sber sazlamalar")}</h1>
|
||||
@@ -112,7 +122,7 @@ export default function VisaMasterSettingsPage() {
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
getRowId={(row) => String(row.id)}
|
||||
getRowId={(row) => row.code}
|
||||
currentPage={page}
|
||||
totalPages={data?.totalPages ?? 1}
|
||||
totalCount={data?.total ?? 0}
|
||||
@@ -133,11 +143,10 @@ export default function VisaMasterSettingsPage() {
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Delete Confirmation */}
|
||||
<DeleteDialog
|
||||
open={deleteId !== null}
|
||||
open={deleteCode !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDeleteId(null);
|
||||
if (!o) setDeleteCode(null);
|
||||
}}
|
||||
title={t("visaMasterSettings.deleteDialog.title", "Pozmak isleýärsiňizmi?")}
|
||||
description={t("visaMasterSettings.deleteDialog.description", "Bu amal yzyna gaýtarylyp bilinmez. Sazlama hemişelik pozular.")}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { VisaMasterSettingForm } from '@/features/visaMasterSberSettings/components/visaMasterSberSettingsForm'
|
||||
import { VisaMasterSettingForm } from "@/features/visaMasterSberSettings/components/visaMasterSberSettingsForm";
|
||||
|
||||
export default function VisaMasterSettingCreatePage() {
|
||||
return <VisaMasterSettingForm mode="create" />
|
||||
return <VisaMasterSettingForm mode="create" />;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PageSpinner } from '@/components/pageSpinner'
|
||||
import { PageError } from '@/components/pageError'
|
||||
import { VisaMasterSettingForm } from '@/features/visaMasterSberSettings/components/visaMasterSberSettingsForm'
|
||||
import { useGetVisaMasterSettingById } from '@/features/visaMasterSberSettings/hooks/useVisaMasterSettings'
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { VisaMasterSettingForm } from "@/features/visaMasterSberSettings/components/visaMasterSberSettingsForm";
|
||||
import { useGetVisaMasterSettingByCode } from "@/features/visaMasterSberSettings/hooks/useVisaMasterSettings";
|
||||
|
||||
export default function VisaMasterSettingEditPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const { t } = useTranslation()
|
||||
const numericId = Number(id)
|
||||
const { data: setting, isLoading } = useGetVisaMasterSettingById(numericId)
|
||||
const { t } = useTranslation();
|
||||
const { code } = useParams<{ code: string }>();
|
||||
const { data, isLoading, isError } = useGetVisaMasterSettingByCode(code);
|
||||
|
||||
if (isLoading) return <PageSpinner />
|
||||
if (!setting) return <PageError message={t('common.notFound', 'Tapylmady')} />
|
||||
if (isLoading) {
|
||||
return <div className="text-muted-foreground">{t("common.loading", "Ýüklenýär...")}</div>;
|
||||
}
|
||||
|
||||
return <VisaMasterSettingForm mode="edit" initialData={setting} />
|
||||
if (isError || !data) {
|
||||
return <div className="text-destructive">{t("common.notFound", "Maglumat tapylmady")}</div>;
|
||||
}
|
||||
|
||||
// key forces the form to re-init if the code changes
|
||||
return <VisaMasterSettingForm key={data.code} mode="edit" initialData={data} />;
|
||||
}
|
||||
|
||||
@@ -1,245 +1,257 @@
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { format } from "date-fns";
|
||||
import { Edit, ArrowUpDown } from "lucide-react";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ColumnMeta, type FilterField, type ActiveFilter } from "@/components/dataTableToolbar";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { MonthSelect } from "@/components/monthSelect";
|
||||
import { useSberPaymentOrders, useDeleteSberPayment } from "@/features/sberPayments/hooks/useSberPayments";
|
||||
import { type SberPaymentOrder, WELAYATLAR, STATUSES } from "@/features/sberPayments/api/sberPaymentsApi";
|
||||
import { InfiniteSelect } from "@/components/infiniteSelect";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { StatusCell } from "@/constants";
|
||||
import { StatusCell, REGION_CODES, REGION_LABELS } from "@/constants";
|
||||
import { formatFromApiDate } from "@/lib/utils/dateUtils";
|
||||
import { useSberPayments, useDeleteSberPaymentReal } from "@/features/sberPayments/hooks/useSberPayments";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
import type { SberPaymentOrderItem, SberPaymentStatus } from "@/features/sberPayments/api/sberPaymentsApi";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
// ─── Column Definitions ───────────────────────────────────────────────────────
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
// ─── Column Meta for Toolbar ──────────────────────────────────────────────────
|
||||
|
||||
function getColumnMeta(t: (key: string, fallback?: string) => string): ColumnMeta[] {
|
||||
return [
|
||||
{ id: "id", label: t("sberPayments.columns.id", "ID") },
|
||||
{ id: "createdAt", label: t("sberPayments.columns.createdAt", "Döredilen wagty") },
|
||||
{ id: "welayat", label: t("sberPayments.columns.welayat", "Welaýat") },
|
||||
{ id: "sahamca", label: t("sberPayments.columns.sahamca", "Şahamça") },
|
||||
{ id: "firstName", label: t("sberPayments.columns.firstName", "Ady") },
|
||||
{ id: "lastName", label: t("sberPayments.columns.lastName", "Familiýasy") },
|
||||
{ id: "phone", label: t("sberPayments.columns.phone", "Telefon") },
|
||||
{ id: "status", label: t("sberPayments.columns.status", "Status") },
|
||||
{ id: "paidStatus", label: t("sberPayments.columns.paidStatus", "Tölenen (şul aý)") },
|
||||
];
|
||||
function resolveLocalizedName(name: LocalizedText | string | null | undefined, lang: string): string {
|
||||
if (!name) return "";
|
||||
if (typeof name === "string") return name;
|
||||
const key = lang === "tk" ? "tm" : lang;
|
||||
return name[key as keyof LocalizedText] ?? name.tm ?? name.en ?? name.ru ?? "";
|
||||
}
|
||||
|
||||
// ─── Filter Fields ────────────────────────────────────────────────────────────
|
||||
const COLUMN_IDS = [
|
||||
"id",
|
||||
"uniqueId",
|
||||
"createdAt",
|
||||
"region",
|
||||
"branch",
|
||||
"passportName",
|
||||
"passportSurname",
|
||||
"phone",
|
||||
"status",
|
||||
"paid",
|
||||
] as const;
|
||||
|
||||
function getFilterFields(t: (key: string, fallback?: string) => string): FilterField[] {
|
||||
return [
|
||||
{
|
||||
id: "welayat",
|
||||
label: t("sberPayments.filters.welayat", "Welaýat"),
|
||||
options: WELAYATLAR.map((w) => ({ value: w, label: w })),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
label: t("sberPayments.filters.status", "Status"),
|
||||
options: STATUSES,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// ─── List Page Component ──────────────────────────────────────────────────────
|
||||
// ─── Page Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export default function SberPaymentsListPage() {
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback((key, fallback) => _t(key, fallback ?? key) as string, [_t]);
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = i18n.language;
|
||||
const navigate = useNavigate();
|
||||
const [deleteTarget, setDeleteTarget] = useState<SberPaymentOrder | null>(null);
|
||||
const deleteMutation = useDeleteSberPayment();
|
||||
const deleteMutation = useDeleteSberPaymentReal();
|
||||
|
||||
const colMeta = useMemo(() => getColumnMeta(t), [i18n.language]);
|
||||
const filterFlds = useMemo(() => getFilterFields(t), [i18n.language]);
|
||||
const [deleteTarget, setDeleteTarget] = useState<SberPaymentOrderItem | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
|
||||
const columns = useMemo<ColumnDef<SberPaymentOrder>[]>(() => {
|
||||
const colMetaLabels = getColumnMeta(t);
|
||||
const idLabel = colMetaLabels.find((c) => c.id === "id")?.label ?? "ID";
|
||||
const createdAtLabel = colMetaLabels.find((c) => c.id === "createdAt")?.label ?? "Döredilen wagty";
|
||||
const welayatLabel = colMetaLabels.find((c) => c.id === "welayat")?.label ?? "Welaýat";
|
||||
const sahamcaLabel = colMetaLabels.find((c) => c.id === "sahamca")?.label ?? "Şahamça";
|
||||
const firstNameLabel = colMetaLabels.find((c) => c.id === "firstName")?.label ?? "Ady";
|
||||
const lastNameLabel = colMetaLabels.find((c) => c.id === "lastName")?.label ?? "Familiýasy";
|
||||
const phoneLabel = colMetaLabels.find((c) => c.id === "phone")?.label ?? "Telefon";
|
||||
const statusLabel = colMetaLabels.find((c) => c.id === "status")?.label ?? "Status";
|
||||
const paidStatusLabel = colMetaLabels.find((c) => c.id === "paidStatus")?.label ?? "Tölenen (şul aý)";
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "region", value: "" },
|
||||
]);
|
||||
|
||||
return [
|
||||
// ── Lazy filter dropdowns ──────────────────────────────────────────────────
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const [branchFilter, setBranchFilter] = useState("");
|
||||
const [userFilter, setUserFilter] = useState("");
|
||||
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const [branchSelectOpen, setBranchSelectOpen] = useState(false);
|
||||
const isBranchEnabled = filterEnabled || branchSelectOpen || Boolean(branchFilter);
|
||||
const branchQuery = useInfiniteBranches(branchSearch, isBranchEnabled);
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
(branchQuery.data?.pages ?? []).flatMap((p) =>
|
||||
(p?.branches ?? []).map((b) => ({ value: String(b.id), label: resolveLocalizedName(b.name, lang) })),
|
||||
),
|
||||
[branchQuery.data, lang],
|
||||
);
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const [userSelectOpen, setUserSelectOpen] = useState(false);
|
||||
const isUserEnabled = filterEnabled || userSelectOpen || Boolean(userFilter);
|
||||
const userQuery = useInfiniteUsers(userSearch, isUserEnabled);
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
(userQuery.data?.pages ?? []).flatMap((p) =>
|
||||
(p?.users ?? []).map((u) => ({ value: String(u.id), label: u.name || u.username || String(u.id) })),
|
||||
),
|
||||
[userQuery.data],
|
||||
);
|
||||
|
||||
// ── Query params ──────────────────────────────────────────────────────────
|
||||
const getFilter = useCallback((id: string) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
||||
|
||||
const { data, isLoading } = useSberPayments({
|
||||
page,
|
||||
limit: perPage,
|
||||
name: search || undefined,
|
||||
status: (getFilter("status") as SberPaymentStatus) || undefined,
|
||||
region: getFilter("region") || undefined,
|
||||
branch_id: branchFilter || undefined,
|
||||
user_id: userFilter || undefined,
|
||||
});
|
||||
|
||||
const totalPages = data ? Math.ceil(data.total / perPage) : 1;
|
||||
|
||||
// ── Filter handlers ───────────────────────────────────────────────────────
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setBranchFilter("");
|
||||
setUserFilter("");
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
// ── Columns ───────────────────────────────────────────────────────────────
|
||||
const columns = useMemo<ColumnDef<SberPaymentOrderItem>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: ({ column }) => (
|
||||
<button
|
||||
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
{idLabel}
|
||||
<ArrowUpDown size={12} />
|
||||
</button>
|
||||
),
|
||||
cell: ({ row }) => <span className="font-medium text-foreground">{row.getValue("id")}</span>,
|
||||
header: "ID",
|
||||
cell: ({ row }) => <span className="font-mono text-xs text-muted-foreground">{row.original.id}</span>,
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "uniqueId",
|
||||
accessorKey: "uniqueId",
|
||||
header: t("sberPayments.col.uniqueId", "Unikal ID"),
|
||||
cell: ({ row }) => <span className="font-mono text-xs text-primary">{row.original.uniqueId}</span>,
|
||||
size: 130,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: createdAtLabel,
|
||||
cell: ({ row }) => {
|
||||
const date = new Date(row.getValue("createdAt"));
|
||||
return (
|
||||
<div className="text-sm">
|
||||
<div>{format(date, "HH:mm, dd.MM.yyyy")}</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "welayat",
|
||||
header: welayatLabel,
|
||||
cell: ({ row }) => <span>{row.getValue("welayat")}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "sahamca",
|
||||
header: ({ column }) => (
|
||||
<button
|
||||
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
{sahamcaLabel}
|
||||
<ArrowUpDown size={12} />
|
||||
</button>
|
||||
header: t("sberPayments.col.createdAt", "Döredilen wagty"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">{formatFromApiDate(row.original.createdAt)}</span>
|
||||
),
|
||||
cell: ({ row }) => <span className="text-primary font-medium">{row.getValue("sahamca")}</span>,
|
||||
size: 155,
|
||||
},
|
||||
{
|
||||
accessorKey: "firstName",
|
||||
header: firstNameLabel,
|
||||
cell: ({ row }) => <span>{row.getValue("firstName")}</span>,
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("sberPayments.col.region", "Welaýat"),
|
||||
cell: ({ row }) => <span className="text-sm">{resolveLocalizedName(row.original.regionName, lang) || row.original.region}</span>,
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
accessorKey: "lastName",
|
||||
header: lastNameLabel,
|
||||
cell: ({ row }) => <span>{row.getValue("lastName")}</span>,
|
||||
id: "branch",
|
||||
accessorKey: "branch",
|
||||
header: t("sberPayments.col.branch", "Şahamça"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-emerald-500 font-medium">{resolveLocalizedName(row.original.branch?.name, lang)}</span>
|
||||
),
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
id: "passportName",
|
||||
accessorKey: "passportName",
|
||||
header: t("sberPayments.col.firstName", "Ady"),
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.passportName}</span>,
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "passportSurname",
|
||||
accessorKey: "passportSurname",
|
||||
header: t("sberPayments.col.lastName", "Familiýasy"),
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.passportSurname}</span>,
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
id: "phone",
|
||||
accessorKey: "phone",
|
||||
header: phoneLabel,
|
||||
cell: ({ row }) => <span className="text-muted-foreground">{row.getValue("phone")}</span>,
|
||||
header: t("sberPayments.col.phone", "Telefon"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.phone}</span>,
|
||||
size: 130,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => (
|
||||
<button
|
||||
className="flex items-center gap-1 hover:text-foreground transition-colors"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
{statusLabel}
|
||||
<ArrowUpDown size={12} />
|
||||
</button>
|
||||
),
|
||||
header: t("sberPayments.col.status", "Status"),
|
||||
cell: ({ row }) => (
|
||||
<StatusCell
|
||||
status={row.getValue("status") as string}
|
||||
fallbackLabels={{
|
||||
GARASYLYYAR: t("sberPayments.status.pending", "Garaşylýar"),
|
||||
KANAGATLANDYRYLAN: t("sberPayments.status.approved", "Tassyklandy"),
|
||||
RET_EDILEN: t("sberPayments.status.rejected", "Ýatyryldy"),
|
||||
}}
|
||||
fallbackVariants={{ GARASYLYYAR: "warning", KANAGATLANDYRYLAN: "success", RET_EDILEN: "error" }}
|
||||
status={row.original.status}
|
||||
prefix="intlPayment.status"
|
||||
fallbackLabels={{ pending: "Garaşylýar", approved: "Tassyklandy", rejected: "Ret edildi", completed: "Tamamlandy" }}
|
||||
fallbackVariants={{ pending: "warning", approved: "success", rejected: "error", completed: "success" }}
|
||||
/>
|
||||
),
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
accessorKey: "paidStatus",
|
||||
header: paidStatusLabel,
|
||||
id: "paid",
|
||||
accessorKey: "paid",
|
||||
header: t("sberPayments.col.paid", "Tölendi"),
|
||||
cell: ({ row }) => (
|
||||
<StatusCell
|
||||
status={row.getValue("paidStatus") as string}
|
||||
fallbackLabels={{
|
||||
Tolenmedik: t("sberPayments.paidStatus.unpaid", "Tölenmedi"),
|
||||
Tolendi: t("sberPayments.paidStatus.paid", "Tölendi"),
|
||||
}}
|
||||
fallbackVariants={{ Tolenmedik: "error", Tolendi: "success" }}
|
||||
status={row.original.paid ? "paid" : "unpaid"}
|
||||
fallbackLabels={{ paid: t("sberPayments.paid.yes", "Tölendi"), unpaid: t("sberPayments.paid.no", "Tölenmedi") }}
|
||||
fallbackVariants={{ paid: "success", unpaid: "error" }}
|
||||
/>
|
||||
),
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
cell: ({ row }) => {
|
||||
const order = row.original;
|
||||
|
||||
return (
|
||||
<TableActions
|
||||
onView={() => navigate(`/sber-payments/${order.id}`)}
|
||||
onEdit={() => navigate(`/sber-payments/${order.id}/edit`)}
|
||||
onDelete={() => setDeleteTarget(order)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
editIcon={Edit}
|
||||
/>
|
||||
);
|
||||
},
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/sber-payments/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/sber-payments/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteTarget(row.original)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 90,
|
||||
},
|
||||
];
|
||||
}, [navigate, deleteMutation, t, i18n.language]);
|
||||
],
|
||||
[t, navigate, deleteMutation.isPending, lang],
|
||||
);
|
||||
|
||||
// Pagination state
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`sberPayments.columns.${id}`, id) })), [t]);
|
||||
|
||||
// Search state
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
// Filter state
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([]);
|
||||
|
||||
// Column visibility & order
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>(colMeta.map((c) => c.id));
|
||||
|
||||
// Month filter
|
||||
const [selectedMonth, setSelectedMonth] = useState<string>("");
|
||||
|
||||
// Get filter values
|
||||
const welayatFilter = activeFilters.find((f) => f.fieldId === "welayat")?.value ?? "";
|
||||
const statusFilter = activeFilters.find((f) => f.fieldId === "status")?.value ?? "";
|
||||
|
||||
// Fetch data
|
||||
const { data, isLoading } = useSberPaymentOrders({
|
||||
page,
|
||||
perPage,
|
||||
search,
|
||||
welayat: welayatFilter,
|
||||
status: statusFilter,
|
||||
});
|
||||
|
||||
const handleFilterChange = (fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => {
|
||||
const existing = prev.find((f) => f.fieldId === fieldId);
|
||||
if (existing) {
|
||||
return prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f));
|
||||
}
|
||||
return [...prev, { fieldId, value }];
|
||||
});
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleFilterReset = () => {
|
||||
setActiveFilters([]);
|
||||
setPage(1);
|
||||
};
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("sberPayments.filters.status", "Status"),
|
||||
options: [
|
||||
{ value: "pending", label: t("intlPayment.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("intlPayment.status.approved", "Tassyklandy") },
|
||||
{ value: "rejected", label: t("intlPayment.status.rejected", "Ret edildi") },
|
||||
{ value: "completed", label: t("intlPayment.status.completed", "Tamamlandy") },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
label: t("sberPayments.filters.region", "Welaýat"),
|
||||
options: REGION_CODES.map((code) => ({ value: code, label: REGION_LABELS[code] ?? code })),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Page Title */}
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("sberPayments.list.title", "Sber tölegler (talyplar üçin)")}</h1>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
<TableSearchInput
|
||||
value={search}
|
||||
@@ -249,12 +261,9 @@ export default function SberPaymentsListPage() {
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
/>
|
||||
<CreateButton
|
||||
label={t("sberPayments.list.actionLabel", "Sber töleg (talyplar üçin) dörediň")}
|
||||
onClick={() => navigate("/sber-payments/create")}
|
||||
/>
|
||||
<CreateButton label={t("sberPayments.list.actionLabel", "Sber töleg dörediň")} onClick={() => navigate("/sber-payments/create")} />
|
||||
</div>
|
||||
{/* Toolbar */}
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
@@ -264,48 +273,83 @@ export default function SberPaymentsListPage() {
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
getRowId={(row) => row.id}
|
||||
currentPage={data?.pagination.currentPage ?? 1}
|
||||
totalPages={data?.pagination.totalPages ?? 1}
|
||||
totalCount={data?.pagination.totalCount ?? 0}
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={data?.total}
|
||||
onPageChange={setPage}
|
||||
toolbar={
|
||||
<DataTableToolbar
|
||||
searchValue={search}
|
||||
onSearchChange={(val) => {
|
||||
setSearch(val);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={colMeta}
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue=""
|
||||
onSearchChange={() => {}}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
filterFields={filterFlds}
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(val) => {
|
||||
setPerPage(val);
|
||||
onPerPageChange={(v) => {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
extraActions={
|
||||
<MonthSelect
|
||||
value={selectedMonth}
|
||||
onChange={(v) => {
|
||||
setSelectedMonth(v);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-44">
|
||||
<InfiniteSelect
|
||||
value={branchFilter}
|
||||
onChange={(v) => {
|
||||
setBranchFilter(v);
|
||||
setPage(1);
|
||||
}}
|
||||
options={branchOptions}
|
||||
loading={branchQuery.isLoading}
|
||||
isLoadingMore={branchQuery.isFetchingNextPage}
|
||||
hasNextPage={!!branchQuery.hasNextPage}
|
||||
onLoadMore={() => branchQuery.fetchNextPage()}
|
||||
searchValue={branchSearch}
|
||||
onSearchChange={setBranchSearch}
|
||||
onOpenChange={(open) => {
|
||||
if (open) setBranchSelectOpen(true);
|
||||
}}
|
||||
placeholder={t("sberPayments.filters.branch", "Şahamça")}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-44">
|
||||
<InfiniteSelect
|
||||
value={userFilter}
|
||||
onChange={(v) => {
|
||||
setUserFilter(v);
|
||||
setPage(1);
|
||||
}}
|
||||
options={userOptions}
|
||||
loading={userQuery.isLoading}
|
||||
isLoadingMore={userQuery.isFetchingNextPage}
|
||||
hasNextPage={!!userQuery.hasNextPage}
|
||||
onLoadMore={() => userQuery.fetchNextPage()}
|
||||
searchValue={userSearch}
|
||||
onSearchChange={setUserSearch}
|
||||
onOpenChange={(open) => {
|
||||
if (open) setUserSelectOpen(true);
|
||||
}}
|
||||
placeholder={t("sberPayments.filters.user", "Ulanyjy")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{/* Delete confirmation dialog */}
|
||||
|
||||
<DeleteDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(o) => {
|
||||
@@ -314,7 +358,7 @@ export default function SberPaymentsListPage() {
|
||||
title={t("sberPayments.deleteDialog.title", "Bu tölegi pozmak isleýärsiňizmi?")}
|
||||
onConfirm={async () => {
|
||||
if (deleteTarget) {
|
||||
await deleteMutation.mutateAsync(deleteTarget.id);
|
||||
await deleteMutation.mutateAsync(String(deleteTarget.id));
|
||||
setDeleteTarget(null);
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PageSpinner } from '@/components/pageSpinner'
|
||||
import { PageError } from '@/components/pageError'
|
||||
import { SberPaymentForm } from '@/features/sberPayments/components/sberPaymentsForm'
|
||||
import { useSberPaymentOrder } from '@/features/sberPayments/hooks/useSberPayments'
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PageSpinner } from "@/components/pageSpinner";
|
||||
import { PageError } from "@/components/pageError";
|
||||
import { SberPaymentForm } from "@/features/sberPayments/components/sberPaymentsForm";
|
||||
import { useIntlPayment } from "@/features/visaMasterPayments/hooks/useVisaMasterPayments";
|
||||
|
||||
export default function SberPaymentEditPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const { t } = useTranslation()
|
||||
const { data: order, isLoading } = useSberPaymentOrder(id ?? '')
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const { t } = useTranslation();
|
||||
const { data: order, isLoading } = useIntlPayment(id ?? "");
|
||||
|
||||
if (isLoading) return <PageSpinner />
|
||||
if (!order) return <PageError message={t('common.notFound', 'Tapylmady')} />
|
||||
if (isLoading) return <PageSpinner />;
|
||||
if (!order) return <PageError message={t("common.notFound", "Tapylmady")} />;
|
||||
|
||||
return <SberPaymentForm mode="edit" initialData={order} />
|
||||
return <SberPaymentForm mode="edit" initialData={order} />;
|
||||
}
|
||||
|
||||
@@ -2,15 +2,33 @@ import { format } from "date-fns";
|
||||
import { Search, Download } from "lucide-react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useState } from "react";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { StatusCell } from "@/constants";
|
||||
import { BentoGrid, BentoCard, InfoRow, AuditLog, ViewActions, type AuditRowProps } from "@/components/viewPageComponents";
|
||||
import { useSberPaymentOrder, useDeleteSberPayment } from "@/features/sberPayments/hooks/useSberPayments";
|
||||
import { useState } from "react";
|
||||
import { useIntlPayment, useDeleteIntlPayment } from "@/features/visaMasterPayments/hooks/useVisaMasterPayments";
|
||||
import { ACCEPTED_DOC_DEFS, SENT_DOC_DEFS, docLabel, type TFn } from "@/features/sberPayments/constants/documents";
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function formatDate(value: string | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? "—" : format(d, "dd/MM/yyyy, HH:mm:ss") + " GMT+5";
|
||||
}
|
||||
|
||||
function fileNameFromUrl(url: string): string {
|
||||
const last = url.split("?")[0].split("/").pop() ?? "";
|
||||
try {
|
||||
return decodeURIComponent(last) || "faýl";
|
||||
} catch {
|
||||
return last || "faýl";
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Document row ─────────────────────────────────────────────────────────────
|
||||
|
||||
function DocumentRow({ label, fileName, fileUrl }: { label: string; fileName: string | null; fileUrl: string | null }) {
|
||||
function DocumentRow({ label, fileUrl }: { label: string; fileUrl: string | null }) {
|
||||
if (!fileUrl)
|
||||
return (
|
||||
<InfoRow label={label}>
|
||||
@@ -18,21 +36,25 @@ function DocumentRow({ label, fileName, fileUrl }: { label: string; fileName: st
|
||||
</InfoRow>
|
||||
);
|
||||
|
||||
const name = fileName ?? fileUrl.split("/").pop() ?? "faýl";
|
||||
|
||||
return (
|
||||
<InfoRow label={label}>
|
||||
<div className="flex items-center gap-2">
|
||||
<button className="p-1.5 rounded bg-muted hover:bg-accent transition-colors">
|
||||
<a
|
||||
href={fileUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="p-1.5 rounded bg-muted hover:bg-accent transition-colors"
|
||||
aria-label="Open"
|
||||
>
|
||||
<Search size={12} className="text-muted-foreground" />
|
||||
</button>
|
||||
</a>
|
||||
<a
|
||||
href={fileUrl}
|
||||
download
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-primary/10 hover:bg-primary/20 text-xs text-primary transition-colors"
|
||||
>
|
||||
<Download size={12} />
|
||||
<span className="max-w-[140px] truncate">{name}</span>
|
||||
<span className="max-w-[140px] truncate">{fileNameFromUrl(fileUrl)}</span>
|
||||
</a>
|
||||
</div>
|
||||
</InfoRow>
|
||||
@@ -62,13 +84,14 @@ function SberPaymentViewSkeleton() {
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function SberPaymentViewPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t: _t } = useTranslation();
|
||||
const t: TFn = (key, fallback) => _t(key, fallback ?? key) as string;
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [historySearch, setHistorySearch] = useState("");
|
||||
|
||||
const { data: order, isLoading } = useSberPaymentOrder(id!);
|
||||
const deleteMutation = useDeleteSberPayment();
|
||||
const { data: order, isLoading } = useIntlPayment(id ?? "");
|
||||
const deleteMutation = useDeleteIntlPayment();
|
||||
|
||||
const handleDelete = async () => {
|
||||
await deleteMutation.mutateAsync(id!);
|
||||
@@ -85,18 +108,21 @@ export default function SberPaymentViewPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const kabulDocs = order.documents?.slice(0, 6) ?? [];
|
||||
const ugradDocs = order.documents?.slice(6) ?? [];
|
||||
const payerInfo = [order.passport_series, order.passport_number, order.payer_full_name].filter(Boolean).join(" ");
|
||||
|
||||
const auditLogs: AuditRowProps[] =
|
||||
order.activityLog?.map((log) => ({
|
||||
id: log.id.split("-")[1] ?? log.id,
|
||||
action: log.analysisName,
|
||||
by: log.createdBy,
|
||||
target: log.target,
|
||||
status: log.status,
|
||||
date: format(new Date(log.createdAt), "dd/MM/yyyy, HH:mm:ss") + " GMT+5",
|
||||
})) ?? [];
|
||||
// Backend gives no activity log; only the creation event is derivable from real data.
|
||||
const auditLogs: AuditRowProps[] = order.created_at
|
||||
? [
|
||||
{
|
||||
id: order.id,
|
||||
action: t("sberPayments.audit.created", "Döredildi"),
|
||||
by: order.created_by_label || "—",
|
||||
target: order.id,
|
||||
status: "FINISHED" as AuditRowProps["status"],
|
||||
date: formatDate(order.created_at),
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
@@ -124,16 +150,17 @@ export default function SberPaymentViewPage() {
|
||||
<StatusCell
|
||||
status={order.status}
|
||||
fallbackLabels={{
|
||||
GARASYLYYAR: t("sberPayments.status.pending", "Garaşylýar"),
|
||||
KANAGATLANDYRYLAN: t("sberPayments.status.approved", "Tassyklandy"),
|
||||
RET_EDILEN: t("sberPayments.status.rejected", "Ýatyryldy"),
|
||||
pending: t("sberPayments.status.pending", "Garaşylýar"),
|
||||
approved: t("sberPayments.status.approved", "Tassyklandy"),
|
||||
rejected: t("sberPayments.status.rejected", "Ýatyryldy"),
|
||||
completed: t("sberPayments.status.completed", "Tamamlandy"),
|
||||
}}
|
||||
fallbackVariants={{ GARASYLYYAR: "warning", KANAGATLANDYRYLAN: "success", RET_EDILEN: "error" }}
|
||||
fallbackVariants={{ pending: "warning", approved: "success", rejected: "error", completed: "success" }}
|
||||
/>
|
||||
</InfoRow>
|
||||
<InfoRow label={t("sberPayments.columns.paidStatus", "Tölenen (şul aý)")}>
|
||||
<InfoRow label={t("sberPayments.columns.paidStatus", "Tölenen")}>
|
||||
<StatusCell
|
||||
status={order.paidStatus}
|
||||
status={order.paid ? "Tolendi" : "Tolenmedik"}
|
||||
fallbackLabels={{
|
||||
Tolenmedik: t("sberPayments.paidStatus.unpaid", "Tölenmedi"),
|
||||
Tolendi: t("sberPayments.paidStatus.paid", "Tölendi"),
|
||||
@@ -141,16 +168,16 @@ export default function SberPaymentViewPage() {
|
||||
fallbackVariants={{ Tolenmedik: "error", Tolendi: "success" }}
|
||||
/>
|
||||
</InfoRow>
|
||||
<InfoRow label={t("sberPayments.cards.bellik", "Bellik")} value={order.bellik} />
|
||||
<InfoRow label={t("sberPayments.cards.bellik", "Bellik")} value={order.note ?? ""} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("sberPayments.view.sections.location", "Lokasiýa")}>
|
||||
<InfoRow label={t("sberPayments.fields.welayat", "Welaýat")} value={order.welayat} />
|
||||
<InfoRow label={t("sberPayments.fields.welayat", "Welaýat")} value={order.province_label} />
|
||||
<InfoRow
|
||||
label={t("sberPayments.fields.sahamca", "Şahamça")}
|
||||
value={order.sahamca}
|
||||
value={order.branch_label}
|
||||
isLink
|
||||
href={order.sahamcaId ? `/settings/location/branches/${order.sahamcaId}` : "/settings/location/branches"}
|
||||
href={order.branch ? `/settings/location/branches/${order.branch}` : "/settings/location/branches"}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -158,48 +185,38 @@ export default function SberPaymentViewPage() {
|
||||
{/* ── Row 2: Şahsy maglumatlar + Töleg ─────────────────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("sberPayments.view.sections.personal", "Şahsy maglumatlar")}>
|
||||
<InfoRow label={t("sberPayments.fields.firstName", "Pasportdaky ady")} value={order.firstName} />
|
||||
<InfoRow label={t("sberPayments.fields.lastName", "Pasportdaky familiýa")} value={order.lastName} />
|
||||
<InfoRow label={t("sberPayments.fields.firstName", "Pasportdaky ady")} value={order.passport_first_name} />
|
||||
<InfoRow label={t("sberPayments.fields.lastName", "Pasportdaky familiýa")} value={order.passport_last_name} />
|
||||
<InfoRow label={t("sberPayments.fields.phone", "Telefon")} value={order.phone} />
|
||||
<InfoRow label={t("sberPayments.fields.email", "E-poçta")} value={order.email} />
|
||||
<InfoRow label={t("sberPayments.fields.address", "Salgy")} value={order.address} />
|
||||
<InfoRow label={t("sberPayments.fields.email", "E-poçta")} value={order.email ?? ""} />
|
||||
<InfoRow label={t("sberPayments.fields.address", "Salgy")} value={order.home_address ?? ""} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("sberPayments.view.sections.payment", "Töleg")}>
|
||||
<InfoRow
|
||||
label={t("sberPayments.payerInfo", "Töleg ugradyjynyň maglumatlary")}
|
||||
value={`I-M${order.passportNumber?.slice(0, 2) ?? "XX"}-${order.passportNumber ?? ""} ${order.fullName}`}
|
||||
/>
|
||||
<InfoRow label={t("sberPayments.fields.accountNumber", "Goýum hasaby")} value={order.accountNumber} />
|
||||
<InfoRow label={t("sberPayments.fields.passportSeries", "Pasport seriýasy")} value={order.passportSeries} />
|
||||
<InfoRow label={t("sberPayments.fields.passportNumber", "Pasport nomeri")} value={order.passportNumber} />
|
||||
<InfoRow label={t("sberPayments.fields.fullName", "Ady Familiýasy Atasynyň ady")} value={order.fullName} />
|
||||
<InfoRow label={t("sberPayments.payerInfo", "Töleg ugradyjynyň maglumatlary")} value={payerInfo} />
|
||||
<InfoRow label={t("sberPayments.fields.accountNumber", "Goýum hasaby")} value={order.payer_account_number} />
|
||||
<InfoRow label={t("sberPayments.fields.passportSeries", "Pasport seriýasy")} value={order.passport_series} />
|
||||
<InfoRow label={t("sberPayments.fields.passportNumber", "Pasport nomeri")} value={order.passport_number} />
|
||||
<InfoRow label={t("sberPayments.fields.fullName", "Ady Familiýasy Atasynyň ady")} value={order.payer_full_name} />
|
||||
<InfoRow label={t("sberPayments.fields.receiverInfo", "Töleg kabul edijiniň maglumatlary")} value={order.receiver_info} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 3: Kabul ediji resminamalary ─────────────────────────────── */}
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("sberPayments.view.sections.acceptedDocs", "Kabul ediji talyp boýunça resminamalary")}>
|
||||
{kabulDocs.length > 0 ? (
|
||||
kabulDocs.map((doc) => <DocumentRow key={doc.id} label={doc.label} fileName={doc.name} fileUrl={doc.fileUrl} />)
|
||||
) : (
|
||||
<div className="px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
{t("sberPayments.view.noDocuments", "Resminamalar ýok")}
|
||||
</div>
|
||||
)}
|
||||
{ACCEPTED_DOC_DEFS.map((d) => (
|
||||
<DocumentRow key={d.key} label={docLabel(d, t)} fileUrl={order[d.key]} />
|
||||
))}
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 4: Ugradyjy resminamalary ────────────────────────────────── */}
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("sberPayments.view.sections.sentDocs", "Ugradyjy boýunça resminamalary")}>
|
||||
{ugradDocs.length > 0 ? (
|
||||
ugradDocs.map((doc) => <DocumentRow key={doc.id} label={doc.label} fileName={doc.name} fileUrl={doc.fileUrl} />)
|
||||
) : (
|
||||
<div className="px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
{t("sberPayments.view.noDocuments", "Resminamalar ýok")}
|
||||
</div>
|
||||
)}
|
||||
{SENT_DOC_DEFS.map((d) => (
|
||||
<DocumentRow key={d.key} label={docLabel(d, t)} fileUrl={order[d.key]} />
|
||||
))}
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
|
||||
@@ -50,7 +50,9 @@ export default function IntlPaymentsPage() {
|
||||
const [payTarget, setPayTarget] = useState<IntlPaymentItem | null>(null);
|
||||
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const branchQuery = useInfiniteBranches(branchSearch);
|
||||
const [branchSelectOpen, setBranchSelectOpen] = useState(false);
|
||||
const isBranchEnabled = branchSelectOpen || Boolean(branchFilter);
|
||||
const branchQuery = useInfiniteBranches(branchSearch, isBranchEnabled);
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
(branchQuery.data?.pages ?? []).flatMap((p) =>
|
||||
@@ -60,7 +62,9 @@ export default function IntlPaymentsPage() {
|
||||
);
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const userQuery = useInfiniteUsers(userSearch);
|
||||
const [userSelectOpen, setUserSelectOpen] = useState(false);
|
||||
const isUserEnabled = userSelectOpen || Boolean(userFilter);
|
||||
const userQuery = useInfiniteUsers(userSearch, isUserEnabled);
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
(userQuery.data?.pages ?? []).flatMap((p) =>
|
||||
@@ -268,6 +272,9 @@ export default function IntlPaymentsPage() {
|
||||
onLoadMore={() => branchQuery.fetchNextPage()}
|
||||
searchValue={branchSearch}
|
||||
onSearchChange={setBranchSearch}
|
||||
onOpenChange={(open) => {
|
||||
if (open) setBranchSelectOpen(true);
|
||||
}}
|
||||
placeholder={t("intlPayment.branch", "Şahamça")}
|
||||
/>
|
||||
</div>
|
||||
@@ -285,6 +292,9 @@ export default function IntlPaymentsPage() {
|
||||
onLoadMore={() => userQuery.fetchNextPage()}
|
||||
searchValue={userSearch}
|
||||
onSearchChange={setUserSearch}
|
||||
onOpenChange={(open) => {
|
||||
if (open) setUserSelectOpen(true);
|
||||
}}
|
||||
placeholder={t("intlPayment.client", "Ulanyjy")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,22 +1,26 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download, Search } from "lucide-react";
|
||||
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { StatusCell } from "@/constants";
|
||||
import { BentoGrid, BentoCard, InfoRow, ViewActions } from "@/components/viewPageComponents";
|
||||
|
||||
import { useIntlPayment, useDeleteIntlPayment } from "@/features/visaMasterPayments/hooks/useVisaMasterPayments";
|
||||
|
||||
import { formatFromApiDate } from "@/lib/utils/dateUtils";
|
||||
import { PaymentHistoryTable } from "@/features/visaMasterPayments/components/PaymentHistoryTable";
|
||||
|
||||
// ─── DocFile row ──────────────────────────────────────────────────────────────
|
||||
|
||||
function DocFileRow({ label, url }: { label: string; url: string | null }) {
|
||||
if (!url)
|
||||
if (!url) {
|
||||
return (
|
||||
<InfoRow label={label}>
|
||||
<span className="text-muted-foreground/50">—</span>
|
||||
</InfoRow>
|
||||
);
|
||||
}
|
||||
|
||||
const filename = url.split("/").pop() ?? "faýl";
|
||||
const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
|
||||
@@ -29,18 +33,45 @@ function DocFileRow({ label, url }: { label: string; url: string | null }) {
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-muted/50 hover:bg-muted text-xs text-foreground transition-colors"
|
||||
className="
|
||||
flex
|
||||
items-center
|
||||
gap-1.5
|
||||
rounded-md
|
||||
bg-muted/50
|
||||
px-3
|
||||
py-1.5
|
||||
text-xs
|
||||
text-foreground
|
||||
transition-colors
|
||||
hover:bg-muted
|
||||
"
|
||||
>
|
||||
<Search size={12} />
|
||||
|
||||
<span className="max-w-[140px] truncate">{filename}</span>
|
||||
</a>
|
||||
)}
|
||||
|
||||
<a
|
||||
href={url}
|
||||
download
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-primary/10 hover:bg-primary/20 text-xs text-primary transition-colors"
|
||||
className="
|
||||
flex
|
||||
items-center
|
||||
gap-1.5
|
||||
rounded-md
|
||||
bg-primary/10
|
||||
px-3
|
||||
py-1.5
|
||||
text-xs
|
||||
text-primary
|
||||
transition-colors
|
||||
hover:bg-primary/20
|
||||
"
|
||||
>
|
||||
<Download size={12} />
|
||||
|
||||
<span className="max-w-[140px] truncate">{filename}</span>
|
||||
</a>
|
||||
</div>
|
||||
@@ -54,10 +85,24 @@ function IntlPaymentViewSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-7 w-64" />
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{[...Array(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" />
|
||||
<div
|
||||
key={i}
|
||||
className="
|
||||
flex
|
||||
flex-col
|
||||
gap-3
|
||||
rounded-xl
|
||||
border
|
||||
border-border
|
||||
bg-card
|
||||
p-4
|
||||
"
|
||||
>
|
||||
<Skeleton className="mb-1 h-3 w-24" />
|
||||
|
||||
{[...Array(3)].map((_, j) => (
|
||||
<Skeleton key={j} className="h-4 w-full" />
|
||||
))}
|
||||
@@ -74,32 +119,49 @@ export default function IntlPaymentViewPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
const [historySearch, setHistorySearch] = useState("");
|
||||
|
||||
const { data, isLoading, isError } = useIntlPayment(id!);
|
||||
const { mutate: deletePayment, isPending: isDeleting } = useDeleteIntlPayment();
|
||||
|
||||
const { mutateAsync: deletePayment, isPending: isDeleting } = useDeleteIntlPayment();
|
||||
|
||||
const handleDelete = async () => {
|
||||
await deletePayment(data!.id);
|
||||
await deletePayment(id!);
|
||||
navigate("/visa-master");
|
||||
};
|
||||
|
||||
if (isLoading) return <IntlPaymentViewSkeleton />;
|
||||
if (isLoading) {
|
||||
return <IntlPaymentViewSkeleton />;
|
||||
}
|
||||
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
|
||||
<div className="flex h-64 items-center justify-center text-sm text-muted-foreground">
|
||||
{t("common.notFound", "Maglumat tapylmady")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const KABUL_DOCS = [
|
||||
{ label: 'Talypyň degişli welaýata "SBERBANK" kartyň rekwizitleri', url: data.doc_sberbank_account },
|
||||
{ label: "Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamasy", url: data.doc_school_enrollment },
|
||||
{ label: "Talypyň bilendiriň göçürmesi", url: data.doc_summons },
|
||||
{ label: "Talypyň degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi", url: data.doc_passport_tm },
|
||||
{ label: "Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi", url: data.doc_foreign_passport },
|
||||
{
|
||||
label: 'Talypyň degişli welaýata "SBERBANK" kartyň rekwizitleri',
|
||||
url: data.doc_sberbank_account,
|
||||
},
|
||||
{
|
||||
label: "Talypyň daşary ýurt döwletiniň ýokary okuw mekdebinde okaýandygy baradaky güwänamasy",
|
||||
url: data.doc_school_enrollment,
|
||||
},
|
||||
{
|
||||
label: "Talypyň bilendiriň göçürmesi",
|
||||
url: data.doc_summons,
|
||||
},
|
||||
{
|
||||
label: "Talypyň degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi",
|
||||
url: data.doc_passport_tm,
|
||||
},
|
||||
{
|
||||
label: "Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi",
|
||||
url: data.doc_foreign_passport,
|
||||
},
|
||||
{
|
||||
label:
|
||||
"Talypyň Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurtda galan döwründe bakýan döwleti baradaky bellenen sahypasynyň göçürmesi",
|
||||
@@ -122,7 +184,10 @@ export default function IntlPaymentViewPage() {
|
||||
];
|
||||
|
||||
const UPGRAD_DOCS = [
|
||||
{ label: "Upgradyý degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi", url: data.upd_doc_passport_tm },
|
||||
{
|
||||
label: "Upgradyý degişli Türkmenistanyň raýatynyň içki milli pasportynyň asyl görnüşi we göçürmesi",
|
||||
url: data.upd_doc_passport_tm,
|
||||
},
|
||||
{
|
||||
label: "Upgradyý degişli Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň göçürmesi",
|
||||
url: data.upd_doc_foreign_passport,
|
||||
@@ -132,24 +197,32 @@ export default function IntlPaymentViewPage() {
|
||||
"Upgradyý Türkmenistandan çykmak we Türkmenistana girmek üçin pasportynyň daşary ýurt döwletinde galýandygy baradaky şaýmynyň bellenen sahypasynyň göçürmesi",
|
||||
url: data.upd_doc_visa,
|
||||
},
|
||||
{ label: "Upgradyýyň we kabul edijiniň resminamalarynyň göçürmesi", url: data.upd_doc_acceptance_letter },
|
||||
{
|
||||
label: "Upgradyýyň we kabul edijiniň resminamalarynyň göçürmesi",
|
||||
url: data.upd_doc_acceptance_letter,
|
||||
},
|
||||
{
|
||||
label: "Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky maglumatlary",
|
||||
url: data.upd_doc_passport_biometric,
|
||||
},
|
||||
{ label: "Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky göwnamasy", url: data.upd_doc_passport_old },
|
||||
{
|
||||
label: "Upgradyý we kabul ediji täze 2015-nji ýyldan soňra pasportynyň seriýasy baradaky göwnamasy",
|
||||
url: data.upd_doc_passport_old,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<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("intlPayment.viewTitle", "Halkara töleg")}: {data.id}
|
||||
</h1>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<ViewActions
|
||||
editTo={`/intl-payments/visa-master/${id}/edit`}
|
||||
editTo={`/visa-master/${id}/edit`}
|
||||
onDelete={handleDelete}
|
||||
deleting={isDeleting}
|
||||
deleteTitle={t("intlPayment.deleteTitle", "Pozmak isleýärsiňizmi?")}
|
||||
@@ -160,6 +233,7 @@ export default function IntlPaymentViewPage() {
|
||||
</div>
|
||||
|
||||
{/* ── Row 1: Meta + Ýüztuman + Lokasiýa ───────────────────────────── */}
|
||||
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard title={t("intlPayment.statusSection", "Esasy maglumatlar")}>
|
||||
<InfoRow
|
||||
@@ -168,16 +242,28 @@ export default function IntlPaymentViewPage() {
|
||||
isLink={Boolean(data.client_id)}
|
||||
href={data.client_id ? `/all-users/${data.client_id}` : undefined}
|
||||
/>
|
||||
|
||||
<InfoRow label={t("common.id", "ID")} value={data.id} />
|
||||
|
||||
<InfoRow label={t("intlPayment.status", "Status")}>
|
||||
<StatusCell
|
||||
status={data.status}
|
||||
prefix="intlPayment.status"
|
||||
fallbackLabels={{ pending: "Garaşylýar", approved: "Tassyklandy", rejected: "Ret edildi" }}
|
||||
fallbackVariants={{ pending: "warning", approved: "success", rejected: "error" }}
|
||||
fallbackLabels={{
|
||||
pending: "Garaşylýar",
|
||||
approved: "Tassyklandy",
|
||||
rejected: "Ret edildi",
|
||||
}}
|
||||
fallbackVariants={{
|
||||
pending: "warning",
|
||||
approved: "success",
|
||||
rejected: "error",
|
||||
}}
|
||||
/>
|
||||
</InfoRow>
|
||||
|
||||
<InfoRow label={t("intlPayment.tilowanMonth", "Tölewan (Aý/aý)")} value={formatFromApiDate(data.created_at)} />
|
||||
|
||||
<InfoRow label={t("intlPayment.note", "Bellik")} value={data.note} />
|
||||
</BentoCard>
|
||||
|
||||
@@ -187,6 +273,7 @@ export default function IntlPaymentViewPage() {
|
||||
|
||||
<BentoCard title={t("intlPayment.locationSection", "Lokasiýa")}>
|
||||
<InfoRow label={t("intlPayment.province", "Welaýat")} value={data.province_label} />
|
||||
|
||||
<InfoRow
|
||||
label={t("intlPayment.branch", "Şahamça")}
|
||||
value={data.branch_label}
|
||||
@@ -197,69 +284,62 @@ export default function IntlPaymentViewPage() {
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 2: Şahsy maglumatlar + Töleg ─────────────────────────────── */}
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("intlPayment.personalSection", "Şahsy maglumatlar")}>
|
||||
<InfoRow label={t("intlPayment.passportFirstName", "Pasportdaky ady")} value={data.passport_first_name} />
|
||||
|
||||
<InfoRow label={t("intlPayment.passportLastName", "Pasportdaky familiýa")} value={data.passport_last_name} />
|
||||
|
||||
<InfoRow label={t("intlPayment.phone", "Telefon")} value={data.phone} />
|
||||
|
||||
<InfoRow label={t("intlPayment.email", "E-poçta")} value={data.email} />
|
||||
|
||||
<InfoRow label={t("intlPayment.homeAddress", "Häzirki ýaşyş ýeri")} value={data.home_address} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("intlPayment.paymentSection", "Töleg")}>
|
||||
<InfoRow label={t("intlPayment.payerFullName", "Töleg upgradyjynyň maglumatlary")} value={data.payer_full_name} />
|
||||
|
||||
<InfoRow label={t("intlPayment.payerAccount", "Töleg upgradyjynyň goşun hasaby")} value={data.payer_account_number} />
|
||||
|
||||
<InfoRow label={t("intlPayment.passportSeries", "Pasport seriýasy")} value={data.passport_series} />
|
||||
|
||||
<InfoRow label={t("intlPayment.passportNumber", "Pasport nomeri")} value={data.passport_number} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 3: Kabul ediji resminamalar ──────────────────────────────── */}
|
||||
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("intlPayment.kabulDocsSection", "Kabul ediji talyp boyunca resminamalar")}>
|
||||
{KABUL_DOCS.map((doc, i) => (
|
||||
<DocFileRow key={i} label={doc.label} url={doc.url} />
|
||||
{KABUL_DOCS.map((doc, index) => (
|
||||
<DocFileRow key={index} label={doc.label} url={doc.url} />
|
||||
))}
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 4: Upgradyý resminamalar ─────────────────────────────────── */}
|
||||
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("intlPayment.upgradDocsSection", "Upgradyý boyunca resminamalar")}>
|
||||
{UPGRAD_DOCS.map((doc, i) => (
|
||||
<DocFileRow key={i} label={doc.label} url={doc.url} />
|
||||
{UPGRAD_DOCS.map((doc, index) => (
|
||||
<DocFileRow key={index} label={doc.label} url={doc.url} />
|
||||
))}
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 5: Töleg taryhy ───────────────────────────────────────────── */}
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("intlPayment.paymentHistory", "Töleg taryhy")}>
|
||||
<div className="p-4">
|
||||
<div className="relative max-w-xs mb-4">
|
||||
<Search size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||
<input
|
||||
type="text"
|
||||
value={historySearch}
|
||||
onChange={(e) => setHistorySearch(e.target.value)}
|
||||
placeholder={t("intlPayment.search", "Gözlemek")}
|
||||
className="h-9 w-full pl-9 pr-3 rounded-md border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center justify-center py-10 text-muted-foreground/50">
|
||||
<div className="w-12 h-12 mb-3 rounded-lg border-2 border-dashed border-muted-foreground/20 flex items-center justify-center">
|
||||
<svg viewBox="0 0 24 24" className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={1.5}>
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" />
|
||||
<line x1="3" y1="9" x2="21" y2="9" />
|
||||
<line x1="9" y1="9" x2="9" y2="21" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-sm">{t("intlPayment.noHistory", "Beriilen kriteriýalara Töleg gabat gelmedi")}</p>
|
||||
</div>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<section className="overflow-hidden rounded-xl border border-border bg-card">
|
||||
{/* Single history header */}
|
||||
<div className="border-b border-border px-4 py-3">
|
||||
<h2 className="text-sm font-medium text-foreground">{t("intlPayment.paymentHistory", "Töleg taryhy")}</h2>
|
||||
</div>
|
||||
|
||||
{/* Single history table */}
|
||||
<PaymentHistoryTable orderId={id} />
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -29,14 +29,24 @@ export default function LoanOrderMobilesPage() {
|
||||
const deleteMutation = useDeleteLoanOrderMobile();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "region", value: "" },
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "branch", value: "" },
|
||||
{ fieldId: "archived", value: "" },
|
||||
]);
|
||||
|
||||
const isBranchFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "branch")?.value);
|
||||
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
} = useInfiniteBranches(branchSearch, isBranchFilterEnabled);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
@@ -54,12 +64,6 @@ export default function LoanOrderMobilesPage() {
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "region", value: "" },
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "branch", value: "" },
|
||||
{ fieldId: "archived", value: "" },
|
||||
]);
|
||||
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
@@ -268,6 +272,9 @@ export default function LoanOrderMobilesPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
columns={columns}
|
||||
|
||||
@@ -28,14 +28,23 @@ export default function LoanOrdersPage() {
|
||||
const deleteMutation = useDeleteLoanOrder();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "region", value: "" },
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "branch", value: "" },
|
||||
]);
|
||||
|
||||
const isBranchFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "branch")?.value);
|
||||
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
} = useInfiniteBranches(branchSearch, isBranchFilterEnabled);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
@@ -52,11 +61,6 @@ export default function LoanOrdersPage() {
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "region", value: "" },
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "branch", value: "" },
|
||||
]);
|
||||
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
@@ -252,6 +256,9 @@ export default function LoanOrdersPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -71,16 +71,23 @@ export default function LoanPaidOffLettersPage() {
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>(INITIAL_FILTERS);
|
||||
|
||||
// ── Dropdown data ──────────────────────────────────────────────────────────
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const [districtSearch, setDistrictSearch] = useState("");
|
||||
|
||||
// ── Query ──────────────────────────────────────────────────────────────────
|
||||
const getFilter = useCallback((id: FilterId) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
||||
|
||||
const isBranchFilterEnabled = filterEnabled || Boolean(getFilter("branch_id"));
|
||||
const isDistrictFilterEnabled = filterEnabled || Boolean(getFilter("region"));
|
||||
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
} = useInfiniteBranches(branchSearch, isBranchFilterEnabled);
|
||||
|
||||
const {
|
||||
data: districtsInfiniteData,
|
||||
@@ -88,10 +95,7 @@ export default function LoanPaidOffLettersPage() {
|
||||
hasNextPage: hasNextDistricts,
|
||||
isFetchingNextPage: isFetchingNextDistricts,
|
||||
isLoading: isDistrictsLoading,
|
||||
} = useInfiniteDistricts(districtSearch);
|
||||
|
||||
// ── Query ──────────────────────────────────────────────────────────────────
|
||||
const getFilter = useCallback((id: FilterId) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
||||
} = useInfiniteDistricts(districtSearch, isDistrictFilterEnabled);
|
||||
|
||||
const queryParams = useMemo(
|
||||
() => ({
|
||||
@@ -332,6 +336,9 @@ export default function LoanPaidOffLettersPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
/>
|
||||
|
||||
@@ -83,6 +83,9 @@ export default function OnlinePaymentHistoryPage() {
|
||||
]);
|
||||
|
||||
// ─── Branch infinite-select data
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const isBranchFilterEnabled = filterEnabled || Boolean(activeFilters.find((f) => f.fieldId === "branchId")?.value);
|
||||
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
@@ -90,7 +93,7 @@ export default function OnlinePaymentHistoryPage() {
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
} = useInfiniteBranches(branchSearch, isBranchFilterEnabled);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
@@ -306,6 +309,9 @@ export default function OnlinePaymentHistoryPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
columns={columns}
|
||||
|
||||
@@ -53,14 +53,17 @@ export function BranchesListPage() {
|
||||
uniqueCode: uniqueCodeFilter,
|
||||
});
|
||||
|
||||
const [filterEnabled, setFilterEnabled] = useState(false);
|
||||
const [provinceSearch, setProvinceSearch] = useState("");
|
||||
const isProvinceFilterEnabled = filterEnabled || Boolean(provinceIdFilter);
|
||||
|
||||
const {
|
||||
data: provincesInfiniteData,
|
||||
fetchNextPage: fetchNextProvinces,
|
||||
hasNextPage: hasNextProvinces,
|
||||
isFetchingNextPage: isFetchingNextProvinces,
|
||||
isLoading: isProvincesLoading,
|
||||
} = useInfiniteProvinces(provinceSearch);
|
||||
} = useInfiniteProvinces(provinceSearch, isProvinceFilterEnabled);
|
||||
|
||||
const provinceOptions = useMemo(
|
||||
() =>
|
||||
@@ -233,6 +236,9 @@ export function BranchesListPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterOpenChange={(open) => {
|
||||
if (open) setFilterEnabled(true);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user