added payment setting page and quota
This commit is contained in:
@@ -112,6 +112,7 @@ const ActivityLogViewPage = lazy(() => import("@/pages/logs/view"));
|
||||
const BranchCreatePage = lazy(() => import("@/pages/settings/location/branchesCreate"));
|
||||
const BranchesViewPage = lazy(() => import("@/pages/settings/location/branchesView"));
|
||||
const BranchEditPage = lazy(() => import("@/pages/settings/location/branchesEdit"));
|
||||
const PaymentSettingsPage = lazy(() => import("@/pages/settings/payment"));
|
||||
const ProfilePage = lazy(() => import("@/pages/profile"));
|
||||
|
||||
// ─── Guards ───────────────────────────────────────────────────────────────────
|
||||
@@ -800,6 +801,11 @@ const routes: AppRoute[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
// Payment settings
|
||||
{
|
||||
...bc((t) => t("paymentSettings.title", "Töleg sazlamalary"), "/settings/payment"),
|
||||
children: [{ path: "/settings/payment", element: page(PaymentSettingsPage) }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -53,7 +53,31 @@ export function InfiniteSelect({
|
||||
onSearchChange,
|
||||
}: InfiniteSelectProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
const [portalContainer, setPortalContainer] = useState<HTMLElement | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
if (containerRef.current) {
|
||||
const dialog = containerRef.current.closest<HTMLElement>(
|
||||
'[role="dialog"], [role="alertdialog"], [data-slot="alert-dialog-content"], [data-slot="dialog-content"]',
|
||||
);
|
||||
if (dialog) {
|
||||
setPortalContainer(dialog);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = scrollContainerRef.current;
|
||||
if (!el || !open) return;
|
||||
const handleWheel = (e: WheelEvent) => {
|
||||
e.stopPropagation();
|
||||
};
|
||||
el.addEventListener("wheel", handleWheel, { passive: true });
|
||||
return () => el.removeEventListener("wheel", handleWheel);
|
||||
}, [open]);
|
||||
|
||||
const selected = options.find((o) => o.value === value);
|
||||
|
||||
@@ -93,7 +117,7 @@ export function InfiniteSelect({
|
||||
}, [open, hasNextPage, isLoadingMore, onLoadMore]);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div ref={containerRef} className="relative">
|
||||
{label && (
|
||||
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 select-none">
|
||||
{label}
|
||||
@@ -143,7 +167,7 @@ export function InfiniteSelect({
|
||||
</button>
|
||||
</PopoverPrimitive.Trigger>
|
||||
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Portal container={portalContainer}>
|
||||
<PopoverPrimitive.Content
|
||||
align="start"
|
||||
side="bottom"
|
||||
@@ -152,6 +176,8 @@ export function InfiniteSelect({
|
||||
avoidCollisions
|
||||
style={{ width: "var(--radix-popover-trigger-width)" }}
|
||||
className="z-50 rounded-md border border-border bg-card shadow-lg overflow-hidden max-h-[var(--radix-popover-content-available-height)] flex flex-col"
|
||||
onWheel={(e) => e.stopPropagation()}
|
||||
onTouchMove={(e) => e.stopPropagation()}
|
||||
>
|
||||
{onSearchChange && (
|
||||
<div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/20 shrink-0">
|
||||
@@ -176,7 +202,12 @@ export function InfiniteSelect({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-h-60 overflow-y-auto scrollbar-thin py-1">
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
onWheel={(e) => e.stopPropagation()}
|
||||
onTouchMove={(e) => e.stopPropagation()}
|
||||
className="max-h-60 overflow-y-auto overscroll-contain scrollbar-thin py-1"
|
||||
>
|
||||
{loading && options.length === 0 ? (
|
||||
<p className="px-3 py-4 text-sm text-muted-foreground text-center flex items-center justify-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" /> Loading...
|
||||
|
||||
@@ -9,7 +9,7 @@ const buttonVariants = cva(
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-[#18b69b] dark:bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||
default: "bg-[#18b69b] hover:bg-[#149e87] active:bg-[#118a76] dark:bg-primary dark:hover:bg-primary/80 text-primary-foreground",
|
||||
outline:
|
||||
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import type { SelectOption } from "@/components/formInput";
|
||||
|
||||
export const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
|
||||
export const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR", "BL"] as const;
|
||||
|
||||
export type RegionCode = (typeof REGION_CODES)[number];
|
||||
|
||||
@@ -14,6 +14,7 @@ export const REGION_LABELS: Record<string, string> = {
|
||||
AG: "Aşgabat",
|
||||
AH: "Ahal",
|
||||
BN: "Balkan",
|
||||
BL: "Balkan",
|
||||
DZ: "Daşoguz",
|
||||
LB: "Lebap",
|
||||
MR: "Mary",
|
||||
|
||||
34
src/features/paymentSettings/api/paymentSettingsApi.ts
Normal file
34
src/features/paymentSettings/api/paymentSettingsApi.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PaymentSettings {
|
||||
bankFeeTmt: number;
|
||||
gbusFeeTmt: number;
|
||||
sberBankFeeTmt: number;
|
||||
tvebFeeUsd: number;
|
||||
maxAmountUsd: number;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface PaymentSettingsPayload {
|
||||
bankFeeTmt: number;
|
||||
gbusFeeTmt: number;
|
||||
sberBankFeeTmt: number;
|
||||
tvebFeeUsd: number;
|
||||
maxAmountUsd: number;
|
||||
}
|
||||
|
||||
// ─── API ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const paymentSettingsApi = {
|
||||
async get(): Promise<PaymentSettings> {
|
||||
const { data } = await apiClient.get<PaymentSettings>("/payment-settings");
|
||||
return data;
|
||||
},
|
||||
|
||||
async update(payload: PaymentSettingsPayload): Promise<PaymentSettings> {
|
||||
const { data } = await apiClient.put<PaymentSettings>("/payment-settings", payload);
|
||||
return data;
|
||||
},
|
||||
};
|
||||
33
src/features/paymentSettings/hooks/usePaymentSettings.ts
Normal file
33
src/features/paymentSettings/hooks/usePaymentSettings.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { paymentSettingsApi, type PaymentSettingsPayload } from "../api/paymentSettingsApi";
|
||||
|
||||
// ─── Keys ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const PAYMENT_SETTINGS_KEY = ["payment-settings"] as const;
|
||||
|
||||
// ─── Hooks ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function usePaymentSettings() {
|
||||
return useQuery({
|
||||
queryKey: PAYMENT_SETTINGS_KEY,
|
||||
queryFn: () => paymentSettingsApi.get(),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdatePaymentSettings() {
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: PaymentSettingsPayload) => paymentSettingsApi.update(payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: PAYMENT_SETTINGS_KEY });
|
||||
toast.success(t("paymentSettings.updateSuccess", "Sazlamalar üýtgedildi"));
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t("paymentSettings.updateError", "Ýalňyşlyk ýüze çykdy"));
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -14,15 +14,15 @@ export interface AddRoleUserPayload {
|
||||
}
|
||||
|
||||
export interface AddPermissionRolePayload {
|
||||
permissionId: number;
|
||||
permissionIds: number[];
|
||||
roleId: number;
|
||||
}
|
||||
|
||||
export interface AddPermissionUserPayload {
|
||||
permissionId: number;
|
||||
userId: number;
|
||||
effect?: string;
|
||||
}
|
||||
// export interface AddPermissionUserPayload {
|
||||
// permissionId: number;
|
||||
// userId: number;
|
||||
// effect?: string;
|
||||
// }
|
||||
|
||||
// Re-export so shared hooks can import from one place
|
||||
export type { BranchListParams, BranchListResponse };
|
||||
@@ -73,24 +73,24 @@ export async function postRoleUser(payload: AddRoleUserPayload): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /permission-roles
|
||||
* Assigns a permission to a role.
|
||||
* POST /permission-roles/bulk
|
||||
* Assigns permissions to a role.
|
||||
*/
|
||||
export async function postPermissionRole(payload: AddPermissionRolePayload): Promise<void> {
|
||||
await apiClient.post("/permission-roles", payload);
|
||||
await apiClient.post("/permission-roles/bulk", payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /permission-users
|
||||
* Assigns a permission to a user.
|
||||
*/
|
||||
export async function postPermissionUser(payload: AddPermissionUserPayload): Promise<void> {
|
||||
await apiClient.post("/permission-users", {
|
||||
permissionId: payload.permissionId,
|
||||
userId: payload.userId,
|
||||
effect: payload.effect ?? "allow",
|
||||
});
|
||||
}
|
||||
// /**
|
||||
// * POST /permission-users
|
||||
// * Assigns a permission to a user.
|
||||
// */
|
||||
// export async function postPermissionUser(payload: AddPermissionUserPayload): Promise<void> {
|
||||
// await apiClient.post("/permission-users", {
|
||||
// permissionId: payload.permissionId,
|
||||
// userId: payload.userId,
|
||||
// effect: payload.effect ?? "allow",
|
||||
// });
|
||||
// }
|
||||
|
||||
/**
|
||||
* Proxy for branch list fetching — kept here so shared hooks
|
||||
|
||||
@@ -15,7 +15,7 @@ import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useAssignRoleToUser, useAssignPermissionToUser, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import { useAssignRoleToUser, useAssignPermissionToRole, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
export type AssignDialogKind = "role" | "permission" | "branch";
|
||||
@@ -25,6 +25,8 @@ export interface AssignDialogProps {
|
||||
onClose: () => void;
|
||||
targetUserId?: number;
|
||||
targetUserName?: string;
|
||||
targetRoleId?: number;
|
||||
targetRoleName?: string;
|
||||
onAssigned?: () => void;
|
||||
}
|
||||
|
||||
@@ -41,21 +43,28 @@ const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Dialog for assigning a role, permission, or branch to a user (staff).
|
||||
* Permissions are assigned directly to users via POST /permission-users.
|
||||
* Dialog for assigning a role / branch to a staff user, or assigning a permission to a role.
|
||||
* Permissions are assigned to roles via POST /permission-roles/bulk: { permissionIds: [...], roleId }.
|
||||
*/
|
||||
export function AssignDialog({ kind, onClose, targetUserId, targetUserName, onAssigned }: AssignDialogProps) {
|
||||
export function AssignDialog({ kind, onClose, targetUserId, targetUserName, targetRoleId, targetRoleName, onAssigned }: AssignDialogProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||
|
||||
const isPermission = kind === "permission";
|
||||
|
||||
const [targetSearch, setTargetSearch] = useState("");
|
||||
const [targetValue, setTargetValue] = useState<string>(() => (targetUserId ? String(targetUserId) : ""));
|
||||
const [targetValue, setTargetValue] = useState<string>(() => {
|
||||
if (isPermission && targetRoleId) return String(targetRoleId);
|
||||
if (!isPermission && targetUserId) return String(targetUserId);
|
||||
return "";
|
||||
});
|
||||
const [resourceSearch, setResourceSearch] = useState("");
|
||||
const [resourceValue, setResourceValue] = useState("");
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
|
||||
// Target query: admin users list (GET /users)
|
||||
const staffQuery = useInfiniteUsers(targetSearch);
|
||||
// Target query: admin users list for role/branch; roles list for permission
|
||||
const staffQuery = useInfiniteUsers(targetSearch, !isPermission);
|
||||
const targetRolesQuery = useInfiniteRoles(targetSearch, isPermission);
|
||||
|
||||
// Resource queries
|
||||
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
||||
@@ -63,11 +72,25 @@ export function AssignDialog({ kind, onClose, targetUserId, targetUserName, onAs
|
||||
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
||||
|
||||
const roleMutation = useAssignRoleToUser();
|
||||
const permissionMutation = useAssignPermissionToUser();
|
||||
const permissionRoleMutation = useAssignPermissionToRole();
|
||||
const branchMutation = useAssignBranchToUser();
|
||||
const isPending = roleMutation.isPending || permissionMutation.isPending || branchMutation.isPending;
|
||||
const isPending = roleMutation.isPending || permissionRoleMutation.isPending || branchMutation.isPending;
|
||||
|
||||
const targetOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
if (isPermission) {
|
||||
const opts: InfiniteSelectOption[] = (targetRolesQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.roles ?? [])
|
||||
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) }));
|
||||
|
||||
if (targetRoleId) {
|
||||
const valStr = String(targetRoleId);
|
||||
if (!opts.some((o) => o.value === valStr)) {
|
||||
opts.unshift({ value: valStr, label: targetRoleName || valStr });
|
||||
}
|
||||
}
|
||||
return opts;
|
||||
}
|
||||
|
||||
const opts: InfiniteSelectOption[] = (staffQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.users ?? [])
|
||||
.map((u) => ({
|
||||
@@ -82,13 +105,16 @@ export function AssignDialog({ kind, onClose, targetUserId, targetUserName, onAs
|
||||
}
|
||||
}
|
||||
return opts;
|
||||
}, [staffQuery.data, targetUserId, targetUserName]);
|
||||
}, [isPermission, targetRolesQuery.data, targetRoleId, targetRoleName, staffQuery.data, targetUserId, targetUserName]);
|
||||
|
||||
const targetLabel = t("profile.assign.userLabel", "Ulanyjy");
|
||||
const targetLoading = staffQuery.isLoading;
|
||||
const targetLoadingMore = staffQuery.isFetchingNextPage;
|
||||
const targetHasNextPage = !!staffQuery.hasNextPage;
|
||||
const loadMoreTargets = () => staffQuery.fetchNextPage();
|
||||
const targetLabel = isPermission ? t("users.fields.role", "Rol") : t("profile.assign.userLabel", "Ulanyjy");
|
||||
const targetLoading = isPermission ? targetRolesQuery.isLoading : staffQuery.isLoading;
|
||||
const targetLoadingMore = isPermission ? targetRolesQuery.isFetchingNextPage : staffQuery.isFetchingNextPage;
|
||||
const targetHasNextPage = isPermission ? !!targetRolesQuery.hasNextPage : !!staffQuery.hasNextPage;
|
||||
const loadMoreTargets = () => {
|
||||
if (isPermission) targetRolesQuery.fetchNextPage();
|
||||
else staffQuery.fetchNextPage();
|
||||
};
|
||||
|
||||
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
if (kind === "role") {
|
||||
@@ -132,7 +158,7 @@ export function AssignDialog({ kind, onClose, targetUserId, targetUserName, onAs
|
||||
}
|
||||
setError(undefined);
|
||||
|
||||
const userId = Number(targetValue);
|
||||
const firstId = Number(targetValue);
|
||||
const secondId = Number(resourceValue);
|
||||
const onSuccess = () => {
|
||||
setResourceValue("");
|
||||
@@ -141,11 +167,13 @@ export function AssignDialog({ kind, onClose, targetUserId, targetUserName, onAs
|
||||
};
|
||||
|
||||
if (kind === "role") {
|
||||
roleMutation.mutate({ userId, roleId: secondId }, { onSuccess });
|
||||
roleMutation.mutate({ userId: firstId, roleId: secondId }, { onSuccess });
|
||||
} else if (kind === "permission") {
|
||||
permissionMutation.mutate({ userId, permissionId: secondId, effect: "allow" }, { onSuccess });
|
||||
// Usere permission berilýän ýeri comment-e alyndy: permission user-e däl, role-a assign edilýär ({ permissionIds: [id], roleId })
|
||||
// permissionMutation.mutate({ userId: firstId, permissionId: secondId, effect: "allow" }, { onSuccess });
|
||||
permissionRoleMutation.mutate({ roleId: firstId, permissionIds: [secondId] }, { onSuccess });
|
||||
} else {
|
||||
branchMutation.mutate({ userId, branchId: secondId }, { onSuccess });
|
||||
branchMutation.mutate({ userId: firstId, branchId: secondId }, { onSuccess });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -5,11 +5,11 @@ import {
|
||||
postBranchUser,
|
||||
postRoleUser,
|
||||
postPermissionRole,
|
||||
postPermissionUser,
|
||||
// postPermissionUser,
|
||||
type AddBranchUserPayload,
|
||||
type AddRoleUserPayload,
|
||||
type AddPermissionRolePayload,
|
||||
type AddPermissionUserPayload,
|
||||
// type AddPermissionUserPayload,
|
||||
} from "../api/sharedApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
@@ -67,23 +67,24 @@ export function useAssignPermissionToRole() {
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useAssignPermissionToUser ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* POST /permission-users — assigns a permission to the given staff user and refreshes the caches.
|
||||
*/
|
||||
export function useAssignPermissionToUser() {
|
||||
const { t } = useTranslation();
|
||||
const invalidateProfile = useInvalidateProfile();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: AddPermissionUserPayload) => postPermissionUser(payload),
|
||||
onSuccess: () => {
|
||||
invalidateProfile();
|
||||
toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
},
|
||||
});
|
||||
}
|
||||
// // ─── useAssignPermissionToUser ────────────────────────────────────────────────
|
||||
//
|
||||
// /**
|
||||
// * POST /permission-users — assigns a permission to the given staff user and refreshes the caches.
|
||||
// * Commented out: permissions are assigned to roles, not users.
|
||||
// */
|
||||
// export function useAssignPermissionToUser() {
|
||||
// const { t } = useTranslation();
|
||||
// const invalidateProfile = useInvalidateProfile();
|
||||
//
|
||||
// return useMutation({
|
||||
// mutationFn: (payload: AddPermissionUserPayload) => postPermissionUser(payload),
|
||||
// onSuccess: () => {
|
||||
// invalidateProfile();
|
||||
// toast.success(t("profile.assign.success", "Üstünlikli birikdirildi"));
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
|
||||
// ─── useAssignBranchToUser ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -9,6 +9,22 @@ import { postFile, buildFileUrl } from "@/features/shared/api/sharedApi";
|
||||
export type IntlPaymentStatus = "pending" | "approved" | "rejected";
|
||||
export type CurrencyType = "visa" | "mastercard";
|
||||
|
||||
// ─── Quote / Pay types ────────────────────────────────────────────────────────
|
||||
|
||||
export interface QuoteResponse {
|
||||
type: string;
|
||||
exchangeRateUsd: number;
|
||||
bankFeeTmt: number;
|
||||
gbusFeeTmt: number;
|
||||
maxAmountTmt: number;
|
||||
payableToday: boolean;
|
||||
}
|
||||
|
||||
export interface PayPayload {
|
||||
amountTmt: number;
|
||||
paymentPeriod: string; // "YYYY-MM-DD"
|
||||
}
|
||||
|
||||
/** Kabul ediji + Upgradyý resminamalar (15 sany) — hem UI hem Payload ortak */
|
||||
export interface IntlPaymentDocs {
|
||||
doc_sberbank_account: string | null;
|
||||
@@ -360,4 +376,13 @@ export const intlPaymentApi = {
|
||||
async delete(id: string): Promise<void> {
|
||||
await apiClient.delete(`/visa-master-payment-orders/${id}`);
|
||||
},
|
||||
|
||||
async quote(id: string): Promise<QuoteResponse> {
|
||||
const { data } = await apiClient.get<QuoteResponse>(`/visa-master-payment-orders/${id}/quote`);
|
||||
return data;
|
||||
},
|
||||
|
||||
async pay(id: string, payload: PayPayload): Promise<void> {
|
||||
await apiClient.post(`/visa-master-payment-orders/${id}/pay`, payload);
|
||||
},
|
||||
};
|
||||
|
||||
240
src/features/visaMasterPayments/components/PayDialog.tsx
Normal file
240
src/features/visaMasterPayments/components/PayDialog.tsx
Normal file
@@ -0,0 +1,240 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle, Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { useQuoteIntlPayment, usePayIntlPayment } from "../hooks/useVisaMasterPayments";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
// ─── Months ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const MONTHS = [
|
||||
{ value: "01", label: "Ýanwar" },
|
||||
{ value: "02", label: "Fewral" },
|
||||
{ value: "03", label: "Mart" },
|
||||
{ value: "04", label: "Aprel" },
|
||||
{ value: "05", label: "Maý" },
|
||||
{ value: "06", label: "Iýun" },
|
||||
{ value: "07", label: "Iýul" },
|
||||
{ value: "08", label: "Awgust" },
|
||||
{ value: "09", label: "Sentýabr" },
|
||||
{ value: "10", label: "Oktýabr" },
|
||||
{ value: "11", label: "Noýabr" },
|
||||
{ value: "12", label: "Dekabr" },
|
||||
];
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function currentMonthValue(): string {
|
||||
const d = new Date();
|
||||
return String(d.getMonth() + 1).padStart(2, "0");
|
||||
}
|
||||
|
||||
function currentYear(): number {
|
||||
return new Date().getFullYear();
|
||||
}
|
||||
|
||||
/** Build last-day-of-month date string YYYY-MM-DD */
|
||||
function buildPaymentPeriod(monthValue: string): string {
|
||||
const year = currentYear();
|
||||
const month = parseInt(monthValue, 10);
|
||||
const lastDay = new Date(year, month, 0).getDate();
|
||||
return `${year}-${monthValue}-${String(lastDay).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
// ─── Dialog ───────────────────────────────────────────────────────────────────
|
||||
|
||||
interface PayDialogProps {
|
||||
id: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function PayDialog({ id, open, onOpenChange }: PayDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [selectedMonth, setSelectedMonth] = useState<string>(currentMonthValue());
|
||||
const [amountStr, setAmountStr] = useState<string>("");
|
||||
|
||||
// Reset when dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelectedMonth(currentMonthValue());
|
||||
setAmountStr("");
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const { data: quote, isLoading: quoteLoading } = useQuoteIntlPayment(open ? id : "");
|
||||
const { mutate: pay, isPending: isPaying } = usePayIntlPayment();
|
||||
|
||||
// Live-calculated fields
|
||||
const amountTmt = parseFloat(amountStr) || 0;
|
||||
|
||||
const usdEquivalent = useMemo(() => {
|
||||
if (!quote || amountTmt <= 0) return "";
|
||||
const val = amountTmt / quote.exchangeRateUsd;
|
||||
return val.toFixed(2);
|
||||
}, [amountTmt, quote]);
|
||||
|
||||
const totalTmt = useMemo(() => {
|
||||
if (!quote || amountTmt <= 0) return "";
|
||||
const val = amountTmt + quote.bankFeeTmt + quote.gbusFeeTmt;
|
||||
return val.toFixed(2);
|
||||
}, [amountTmt, quote]);
|
||||
|
||||
const isMonthCorrect = selectedMonth === currentMonthValue();
|
||||
|
||||
function handleSubmit() {
|
||||
if (!amountTmt || amountTmt <= 0) {
|
||||
toast.error(t("intlPayment.pay.amountRequired", "Töleg möçberini giriziň"));
|
||||
return;
|
||||
}
|
||||
if (quote && amountTmt > quote.maxAmountTmt) {
|
||||
toast.error(t("intlPayment.pay.amountExceedsMax", "Möçber iň ýokary möçberden geçýär"));
|
||||
return;
|
||||
}
|
||||
const paymentPeriod = buildPaymentPeriod(selectedMonth);
|
||||
pay({ id, payload: { amountTmt, paymentPeriod } }, { onSuccess: () => onOpenChange(false) });
|
||||
}
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
/* Overlay */
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{/* Backdrop */}
|
||||
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" />
|
||||
|
||||
{/* Panel */}
|
||||
<div className="relative z-10 w-full max-w-lg mx-4 bg-white rounded-2xl shadow-2xl overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="px-6 pt-6 pb-4 border-b border-gray-100">
|
||||
<h2 className="text-base font-bold uppercase tracking-widest text-gray-800">{t("intlPayment.pay.title", "Töleg")}</h2>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="px-6 py-5 space-y-5">
|
||||
{/* Instruction */}
|
||||
<p className="text-sm text-gray-600">{t("intlPayment.pay.instruction", 'Ýerine ýetirmek üçin "dowam et" düwmä basyň.')}</p>
|
||||
|
||||
{/* Quote info */}
|
||||
{quoteLoading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-gray-400">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
{t("common.loading", "Ýüklenýär...")}
|
||||
</div>
|
||||
) : quote ? (
|
||||
<div className="text-xs font-semibold uppercase tracking-wide text-gray-700 space-y-0.5">
|
||||
<p>1 USD = {quote.exchangeRateUsd} TMT</p>
|
||||
<p>
|
||||
{t("intlPayment.pay.bankFee", "BANKYŇ TUTUMY")}: {quote.bankFeeTmt} TMT
|
||||
</p>
|
||||
<p>
|
||||
{t("intlPayment.pay.gbusFee", "GBÜS TUTUMY")}: {quote.gbusFeeTmt} TMT
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Töleg aý */}
|
||||
<div className="flex items-start gap-6">
|
||||
<label className="min-w-[120px] pt-2.5 text-sm text-gray-600">{t("intlPayment.pay.month", "Töleg aý")}</label>
|
||||
<div className="flex-1">
|
||||
<Select value={selectedMonth} onValueChange={setSelectedMonth}>
|
||||
<SelectTrigger className="w-full h-10 border-gray-200 rounded-lg text-sm focus:ring-1 focus:ring-primary focus:border-primary">
|
||||
<SelectValue placeholder={t("intlPayment.pay.selectMonth", "Aý saýlaň")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MONTHS.map((m) => (
|
||||
<SelectItem key={m.value} value={m.value}>
|
||||
{m.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Töleg möçberi */}
|
||||
<div className="flex items-start gap-6">
|
||||
<label className="min-w-[120px] pt-2.5 text-sm text-gray-600">
|
||||
<span className="text-red-500 mr-1">*</span>
|
||||
{t("intlPayment.pay.amount", "Töleg möçberi (TMT)")}
|
||||
</label>
|
||||
<div className="flex-1">
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
max={quote?.maxAmountTmt}
|
||||
value={amountStr}
|
||||
onChange={(e) => setAmountStr(e.target.value)}
|
||||
className="w-full h-10 px-3 border-2 border-primary rounded-lg text-sm outline-none focus:ring-1 focus:ring-primary/40"
|
||||
placeholder="0"
|
||||
/>
|
||||
{quote && (
|
||||
<p className="mt-1 text-xs text-gray-400 italic">
|
||||
{t("intlPayment.pay.maxAmount", "Iň ýokary möçberi")}: {quote.maxAmountTmt} TMT
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* USD ekwalendi */}
|
||||
<div className="flex items-start gap-6">
|
||||
<label className="min-w-[120px] pt-2.5 text-sm text-gray-600">{t("intlPayment.pay.usdEquiv", "USD ekwalendi")}</label>
|
||||
<div className="flex-1">
|
||||
<input
|
||||
readOnly
|
||||
value={usdEquivalent}
|
||||
placeholder="0"
|
||||
className="w-full h-10 px-3 border border-gray-200 rounded-lg text-sm text-gray-400 bg-gray-50 outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Jemi */}
|
||||
<div className="flex items-start gap-6">
|
||||
<label className="min-w-[120px] pt-2.5 text-sm text-gray-600">{t("intlPayment.pay.total", "Jemi (TMT)")}</label>
|
||||
<div className="flex-1">
|
||||
<input
|
||||
readOnly
|
||||
value={totalTmt}
|
||||
placeholder="0"
|
||||
className="w-full h-10 px-3 border border-gray-200 rounded-lg text-sm text-gray-400 bg-gray-50 outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Wrong month warning */}
|
||||
{!isMonthCorrect && (
|
||||
<div className="flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg px-4 py-2.5 text-sm text-amber-700">
|
||||
<AlertCircle size={14} className="shrink-0" />
|
||||
{t("intlPayment.pay.wrongMonth", "Dogry töleg aýyny saýlamagyňyzy haýyş edýäris!!!!")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-6 pb-6 flex items-center justify-end gap-3">
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isPaying}>
|
||||
{t("intlPayment.pay.cancel", "Ýatyr")}
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSubmit} disabled={isPaying || quoteLoading}>
|
||||
{isPaying ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
{t("common.saving", "Saklanýar...")}
|
||||
</span>
|
||||
) : (
|
||||
t("intlPayment.pay.confirm", "Dowam et")
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type IntlPaymentListParams,
|
||||
type IntlPaymentCreatePayload,
|
||||
type IntlPaymentUpdatePayload,
|
||||
type PayPayload,
|
||||
} from "../api/visaMasterPaymentsApi";
|
||||
|
||||
export const INTL_PAYMENT_KEYS = {
|
||||
@@ -72,3 +73,24 @@ export function useDeleteIntlPayment() {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useQuoteIntlPayment(id: string) {
|
||||
return useQuery({
|
||||
queryKey: [...INTL_PAYMENT_KEYS.detail(id), "quote"] as const,
|
||||
queryFn: () => intlPaymentApi.quote(id),
|
||||
enabled: !!id,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function usePayIntlPayment() {
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
return useMutation({
|
||||
mutationFn: ({ id, payload }: { id: string; payload: PayPayload }) => intlPaymentApi.pay(id, payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: INTL_PAYMENT_KEYS.lists() });
|
||||
toast.success(t("intlPayment.paySuccess", "Töleg üstünlikli amala aşyryldy"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -406,6 +406,15 @@ function AppSidebar() {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t("Payment", "Töleg"),
|
||||
items: [
|
||||
{
|
||||
title: t("Payment settings", "Töleg sazlamalary"),
|
||||
url: "/settings/payment",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -663,6 +663,15 @@
|
||||
"cardOrder.col.phone": "Phone",
|
||||
"cardOrder.col.region": "Region",
|
||||
"cardOrder.col.uniqueId": "Order ID",
|
||||
"cardOrder.col.cardState": "Card state",
|
||||
"cardOrder.col.passport": "Passport",
|
||||
"cardOrder.col.citizenship": "Citizenship",
|
||||
"cardOrder.col.bornAt": "Date of birth",
|
||||
"cardOrder.col.jobLocation": "Job location",
|
||||
"cardOrder.col.realAddress": "Residential address",
|
||||
"cardOrder.col.user": "User",
|
||||
"cardOrder.col.notes": "Notes",
|
||||
"cardOrder.col.phoneAdditional": "Additional phone",
|
||||
"cardOrder.filter.branch": "Branch",
|
||||
"cardOrder.filter.cardStateId": "Card state ID",
|
||||
"cardOrder.filter.cardTypeId": "Card type",
|
||||
@@ -1558,6 +1567,7 @@
|
||||
"profile.title": "My Profile",
|
||||
"profile.actions.assignRole": "Assign role",
|
||||
"profile.actions.assignPermission": "Assign permission",
|
||||
"profile.actions.assignPermissionRole": "Assign permission to role",
|
||||
"profile.editTitle": "Edit profile",
|
||||
"profile.sections.account": "Account details",
|
||||
"profile.sections.actions": "Actions",
|
||||
@@ -1615,5 +1625,16 @@
|
||||
"dashboard.months.9": "Sep",
|
||||
"dashboard.months.10": "Oct",
|
||||
"dashboard.months.11": "Nov",
|
||||
"dashboard.months.12": "Dec"
|
||||
"dashboard.months.12": "Dec",
|
||||
"paymentSettings.title": "Payment settings",
|
||||
"paymentSettings.edit": "Edit",
|
||||
"paymentSettings.editTitle": "Edit settings",
|
||||
"paymentSettings.lastUpdated": "Last updated",
|
||||
"paymentSettings.bankFeeTmt": "Bank fee",
|
||||
"paymentSettings.gbusFeeTmt": "GBUS fee",
|
||||
"paymentSettings.sberBankFeeTmt": "Sberbank fee",
|
||||
"paymentSettings.tvebFeeUsd": "TVEB fee",
|
||||
"paymentSettings.maxAmountUsd": "Maximum amount",
|
||||
"paymentSettings.updateSuccess": "Settings updated successfully",
|
||||
"paymentSettings.updateError": "An error occurred"
|
||||
}
|
||||
|
||||
@@ -663,6 +663,15 @@
|
||||
"cardOrder.col.phone": "Телефон",
|
||||
"cardOrder.col.region": "Регион",
|
||||
"cardOrder.col.uniqueId": "Номер заказа",
|
||||
"cardOrder.col.cardState": "Состояние карты",
|
||||
"cardOrder.col.passport": "Паспорт",
|
||||
"cardOrder.col.citizenship": "Гражданство",
|
||||
"cardOrder.col.bornAt": "Дата рождения",
|
||||
"cardOrder.col.jobLocation": "Место работы",
|
||||
"cardOrder.col.realAddress": "Адрес проживания",
|
||||
"cardOrder.col.user": "Пользователь",
|
||||
"cardOrder.col.notes": "Заметка",
|
||||
"cardOrder.col.phoneAdditional": "Доп. телефон",
|
||||
"cardOrder.filter.branch": "Филиал",
|
||||
"cardOrder.filter.cardStateId": "ID состояния карты",
|
||||
"cardOrder.filter.cardTypeId": "Тип карты",
|
||||
@@ -1559,6 +1568,7 @@
|
||||
"profile.title": "Мой профиль",
|
||||
"profile.actions.assignRole": "Назначить роль",
|
||||
"profile.actions.assignPermission": "Назначить разрешение",
|
||||
"profile.actions.assignPermissionRole": "Назначить разрешение роли",
|
||||
"profile.editTitle": "Редактирование профиля",
|
||||
"profile.sections.account": "Данные аккаунта",
|
||||
"profile.sections.actions": "Действия",
|
||||
@@ -1616,5 +1626,16 @@
|
||||
"dashboard.months.9": "Сен",
|
||||
"dashboard.months.10": "Окт",
|
||||
"dashboard.months.11": "Ноя",
|
||||
"dashboard.months.12": "Дек"
|
||||
"dashboard.months.12": "Дек",
|
||||
"paymentSettings.title": "Настройки платежей",
|
||||
"paymentSettings.edit": "Изменить",
|
||||
"paymentSettings.editTitle": "Изменить настройки",
|
||||
"paymentSettings.lastUpdated": "Последнее обновление",
|
||||
"paymentSettings.bankFeeTmt": "Комиссия банка",
|
||||
"paymentSettings.gbusFeeTmt": "Комиссия ГБУС",
|
||||
"paymentSettings.sberBankFeeTmt": "Комиссия Сбербанка",
|
||||
"paymentSettings.tvebFeeUsd": "Комиссия ТВЭБ",
|
||||
"paymentSettings.maxAmountUsd": "Максимальная сумма",
|
||||
"paymentSettings.updateSuccess": "Настройки обновлены",
|
||||
"paymentSettings.updateError": "Произошла ошибка"
|
||||
}
|
||||
|
||||
@@ -647,7 +647,7 @@
|
||||
"cardOrder.col.id": "ID",
|
||||
"cardOrder.col.reason": "Sebäp",
|
||||
"cardOrder.col.createdAt": "Döredilen wagty",
|
||||
"cardOrder.col.cardType": "Görnüşi",
|
||||
"cardOrder.col.cardType": "Kart görnüşi",
|
||||
"cardOrder.col.province": "Welaýat",
|
||||
"cardOrder.col.branch": "Şahamça",
|
||||
"cardOrder.col.name": "Ady",
|
||||
@@ -662,6 +662,15 @@
|
||||
"cardOrder.col.phone": "Telefon",
|
||||
"cardOrder.col.region": "Sebit",
|
||||
"cardOrder.col.uniqueId": "Sargyt belgisi",
|
||||
"cardOrder.col.cardState": "Kart ýagdaýy",
|
||||
"cardOrder.col.passport": "Pasport",
|
||||
"cardOrder.col.citizenship": "Raýatlyk",
|
||||
"cardOrder.col.bornAt": "Doglan güni",
|
||||
"cardOrder.col.jobLocation": "Işleýän ýeri",
|
||||
"cardOrder.col.realAddress": "Ýaşaýan ýeri",
|
||||
"cardOrder.col.user": "Ulanyjy",
|
||||
"cardOrder.col.notes": "Bellik",
|
||||
"cardOrder.col.phoneAdditional": "Goşmaça telefon",
|
||||
"cardOrder.filter.branch": "Şahamça",
|
||||
"cardOrder.filter.cardStateId": "Kart ýagdaýy ID",
|
||||
"cardOrder.filter.cardTypeId": "Kart görnüşi",
|
||||
@@ -1557,6 +1566,7 @@
|
||||
"profile.title": "Meniň profilim",
|
||||
"profile.actions.assignRole": "Rol birikdiriň",
|
||||
"profile.actions.assignPermission": "Rugsat birikdiriň",
|
||||
"profile.actions.assignPermissionRole": "Rola rugsat birikdiriň",
|
||||
"profile.editTitle": "Profili üýtgetmek",
|
||||
"profile.sections.account": "Hasap maglumatlary",
|
||||
"profile.sections.actions": "Amallar",
|
||||
@@ -1614,5 +1624,16 @@
|
||||
"dashboard.months.9": "Sen",
|
||||
"dashboard.months.10": "Okt",
|
||||
"dashboard.months.11": "Noý",
|
||||
"dashboard.months.12": "Dek"
|
||||
"dashboard.months.12": "Dek",
|
||||
"paymentSettings.title": "Töleg sazlamalary",
|
||||
"paymentSettings.edit": "Üýtget",
|
||||
"paymentSettings.editTitle": "Tölegleri üýtget",
|
||||
"paymentSettings.lastUpdated": "Soňky üýtgeşme",
|
||||
"paymentSettings.bankFeeTmt": "Bankyň tutumy",
|
||||
"paymentSettings.gbusFeeTmt": "GBÜS tutumy",
|
||||
"paymentSettings.sberBankFeeTmt": "Sber bank tutumy",
|
||||
"paymentSettings.tvebFeeUsd": "TVEB tutumy",
|
||||
"paymentSettings.maxAmountUsd": "Iň ýokary möçber",
|
||||
"paymentSettings.updateSuccess": "Sazlamalar üýtgedildi",
|
||||
"paymentSettings.updateError": "Ýalňyşlyk ýüze çykdy"
|
||||
}
|
||||
|
||||
@@ -12,11 +12,18 @@ import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { useCards, useDeleteCard } from "@/features/orderNewCard/hooks/useOrderNewCard";
|
||||
import type { CardOrder } from "@/features/orderNewCard/api/orderNewCardApi";
|
||||
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useInfiniteDistricts } from "@/features/districts/hooks/useDistricts";
|
||||
import { useInfiniteCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
import { getStatusOptions, StatusCell, ActiveStatusCell } from "@/constants";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
import { getStatusOptions, getRegionOptions, StatusCell, ActiveStatusCell } from "@/constants";
|
||||
import { formatFromApiDate } from "@/lib/utils/dateUtils";
|
||||
|
||||
function resolveLocalizedName(name: LocalizedText | string | null | undefined, lang = "tm"): string {
|
||||
if (!name) return "—";
|
||||
if (typeof name === "string") return name;
|
||||
const key = (lang === "ru" ? "ru" : lang === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||
return name[key] ?? name.tm ?? name.en ?? name.ru ?? "—";
|
||||
}
|
||||
|
||||
const PER_PAGE = 25;
|
||||
|
||||
// ─── Filter field IDs ──────────────────────────────────────────────────────────
|
||||
@@ -43,7 +50,6 @@ export default function CardOrdersPage() {
|
||||
|
||||
// ── Dropdown data ──────────────────────────────────────────────────────────
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const [districtSearch, setDistrictSearch] = useState("");
|
||||
const [cardTypeSearch, setCardTypeSearch] = useState("");
|
||||
|
||||
const {
|
||||
@@ -54,14 +60,6 @@ export default function CardOrdersPage() {
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
|
||||
const {
|
||||
data: districtsInfiniteData,
|
||||
fetchNextPage: fetchNextDistricts,
|
||||
hasNextPage: hasNextDistricts,
|
||||
isFetchingNextPage: isFetchingNextDistricts,
|
||||
isLoading: isDistrictsLoading,
|
||||
} = useInfiniteDistricts(districtSearch);
|
||||
|
||||
const {
|
||||
data: cardTypesInfiniteData,
|
||||
fetchNextPage: fetchNextCardTypes,
|
||||
@@ -100,35 +98,80 @@ export default function CardOrdersPage() {
|
||||
{row.original.id}
|
||||
</Link>
|
||||
),
|
||||
size: 80,
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "uniqueId",
|
||||
accessorKey: "uniqueId",
|
||||
header: t("cardOrder.col.uniqueId", "Sargyt belgisi"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground font-mono">{row.original.uniqueId}</span>,
|
||||
cell: ({ row }) => <span className="text-sm text-foreground font-mono whitespace-nowrap">{row.original.uniqueId}</span>,
|
||||
},
|
||||
{
|
||||
id: "customerName",
|
||||
accessorKey: "customerName",
|
||||
header: t("cardOrder.col.customer", "Müşderi"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">
|
||||
{row.original.customerName} {row.original.customerSurname}
|
||||
</span>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const fullName = [row.original.customerSurname, row.original.customerName, row.original.customerPatronicName]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
return <span className="text-sm text-foreground font-medium whitespace-nowrap">{fullName || "—"}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "phone",
|
||||
accessorKey: "phone",
|
||||
header: t("cardOrder.col.phone", "Telefon"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.phone}</span>,
|
||||
cell: ({ row }) => <span className="font-mono text-sm whitespace-nowrap">{row.original.phone || "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "cardType",
|
||||
header: t("cardOrder.col.cardType", "Kart görnüşi"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground whitespace-nowrap">
|
||||
{resolveLocalizedName(row.original.cardType?.name, i18n.language)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "cardState",
|
||||
header: t("cardOrder.col.cardState", "Kart ýagdaýy"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{resolveLocalizedName(row.original.cardState?.name, i18n.language)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "branch",
|
||||
header: t("cardOrder.col.branch", "Şahamça"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground whitespace-nowrap">{resolveLocalizedName(row.original.branch?.name, i18n.language)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("cardOrder.col.region", "Sebit"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.region}</span>,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground whitespace-nowrap">
|
||||
{row.original.region ? t(`loanOrders.regions.${row.original.region}`, row.original.region) : "—"}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "passport",
|
||||
header: t("cardOrder.col.passport", "Pasport"),
|
||||
cell: ({ row }) => {
|
||||
const pass = [row.original.passportSerie, row.original.passportId].filter(Boolean).join(" ");
|
||||
return <span className="font-mono text-sm whitespace-nowrap">{pass || "—"}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
header: t("cardOrder.col.user", "Ulanyjy"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground whitespace-nowrap">{row.original.user?.name || row.original.user?.username || "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
@@ -152,7 +195,7 @@ export default function CardOrdersPage() {
|
||||
{row.original.createdAt ? formatFromApiDate(row.original.createdAt) : "—"}
|
||||
</span>
|
||||
),
|
||||
size: 180,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -191,16 +234,7 @@ export default function CardOrdersPage() {
|
||||
[branchesInfiniteData, lang],
|
||||
);
|
||||
|
||||
const districtOptions = useMemo(
|
||||
() =>
|
||||
(districtsInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.provinces ?? []).map((d) => ({
|
||||
value: d.region?.tm || d.name.tm,
|
||||
label: d.name[lang] || d.name.tm,
|
||||
})),
|
||||
),
|
||||
[districtsInfiniteData, lang],
|
||||
);
|
||||
const regionOptions = useMemo(() => getRegionOptions(t), [t]);
|
||||
|
||||
const cardTypeOptions = useMemo(
|
||||
() =>
|
||||
@@ -236,14 +270,7 @@ export default function CardOrdersPage() {
|
||||
{
|
||||
id: "region",
|
||||
label: t("cardOrder.filter.region", "Sebit"),
|
||||
type: "infinite-select",
|
||||
options: districtOptions,
|
||||
loading: isDistrictsLoading,
|
||||
isLoadingMore: isFetchingNextDistricts,
|
||||
hasNextPage: hasNextDistricts,
|
||||
onLoadMore: fetchNextDistricts,
|
||||
searchValue: districtSearch,
|
||||
onSearchChange: setDistrictSearch,
|
||||
options: regionOptions,
|
||||
},
|
||||
{
|
||||
id: "user_id",
|
||||
@@ -275,11 +302,7 @@ export default function CardOrdersPage() {
|
||||
isFetchingNextBranches,
|
||||
hasNextBranches,
|
||||
branchSearch,
|
||||
districtOptions,
|
||||
isDistrictsLoading,
|
||||
isFetchingNextDistricts,
|
||||
hasNextDistricts,
|
||||
districtSearch,
|
||||
regionOptions,
|
||||
cardTypeOptions,
|
||||
isCardTypesLoading,
|
||||
isFetchingNextCardTypes,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CreditCard } from "lucide-react";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
@@ -17,6 +18,7 @@ import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUser
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
import { formatFromApiDate } from "@/lib/utils/dateUtils";
|
||||
import { PayDialog } from "@/features/visaMasterPayments/components/PayDialog";
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -46,6 +48,7 @@ export default function IntlPaymentsPage() {
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
|
||||
const [deleteTarget, setDeleteTarget] = useState<IntlPaymentItem | null>(null);
|
||||
const [payTarget, setPayTarget] = useState<IntlPaymentItem | null>(null);
|
||||
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const branchQuery = useInfiniteBranches(branchSearch);
|
||||
@@ -140,6 +143,17 @@ export default function IntlPaymentsPage() {
|
||||
onEdit={() => navigate(`/visa-master/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteTarget(row.original)}
|
||||
isDeleting={isDeleting}
|
||||
extraActions={
|
||||
row.original.status === "approved"
|
||||
? [
|
||||
{
|
||||
icon: CreditCard,
|
||||
title: t("intlPayment.pay.action", "Töleg et"),
|
||||
onClick: () => setPayTarget(row.original),
|
||||
},
|
||||
]
|
||||
: []
|
||||
}
|
||||
/>
|
||||
),
|
||||
},
|
||||
@@ -303,6 +317,14 @@ export default function IntlPaymentsPage() {
|
||||
}}
|
||||
isLoading={isDeleting}
|
||||
/>
|
||||
|
||||
<PayDialog
|
||||
id={payTarget?.id ?? ""}
|
||||
open={payTarget !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setPayTarget(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -269,7 +269,7 @@ export default function ProfilePage() {
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("permission")}>
|
||||
<KeyRound size={14} />
|
||||
{t("profile.actions.assignPermission", "Rugsat birikdiriň")}
|
||||
{t("profile.actions.assignPermissionRole", "Rola rugsat birikdiriň")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="gap-1.5" onClick={() => setAssignDialog("branch")}>
|
||||
<Building2 size={14} />
|
||||
@@ -340,7 +340,7 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Assign dialog (staff user + role/permission/branch) ─────────────── */}
|
||||
{/* ── Assign dialog (role/permission/branch) ─────────────── */}
|
||||
{assignDialog && <AssignDialog kind={assignDialog} onClose={() => setAssignDialog(null)} />}
|
||||
</div>
|
||||
);
|
||||
|
||||
173
src/pages/settings/payment/index.tsx
Normal file
173
src/pages/settings/payment/index.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Pencil, Loader2, Settings2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { usePaymentSettings, useUpdatePaymentSettings } from "@/features/paymentSettings/hooks/usePaymentSettings";
|
||||
import type { PaymentSettingsPayload } from "@/features/paymentSettings/api/paymentSettingsApi";
|
||||
import { formatFromApiDate } from "@/lib/utils/dateUtils";
|
||||
|
||||
// ─── Field row ────────────────────────────────────────────────────────────────
|
||||
|
||||
function InfoRow({ label, value, unit }: { label: string; value?: number | string | null; unit?: string }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between py-3.5 border-b border-border last:border-0">
|
||||
<span className="text-sm text-muted-foreground">{label}</span>
|
||||
<span className="text-sm font-semibold text-foreground tabular-nums">
|
||||
{value ?? "—"}
|
||||
{unit ? ` ${unit}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Edit dialog ──────────────────────────────────────────────────────────────
|
||||
|
||||
interface EditDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
initial: PaymentSettingsPayload;
|
||||
}
|
||||
|
||||
function EditDialog({ open, onOpenChange, initial }: EditDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { mutate, isPending } = useUpdatePaymentSettings();
|
||||
|
||||
const [form, setForm] = useState<PaymentSettingsPayload>(initial);
|
||||
|
||||
// sync when initial changes (e.g. dialog re-opened)
|
||||
useEffect(() => {
|
||||
if (open) setForm(initial);
|
||||
}, [open, initial]);
|
||||
|
||||
function set(key: keyof PaymentSettingsPayload, raw: string) {
|
||||
const n = parseFloat(raw);
|
||||
setForm((prev) => ({ ...prev, [key]: isNaN(n) ? 0 : n }));
|
||||
}
|
||||
|
||||
function handleSave() {
|
||||
mutate(form, { onSuccess: () => onOpenChange(false) });
|
||||
}
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const fields: { key: keyof PaymentSettingsPayload; label: string; unit: string }[] = [
|
||||
{ key: "bankFeeTmt", label: t("paymentSettings.bankFeeTmt", "Bankyň tutumy"), unit: "TMT" },
|
||||
{ key: "gbusFeeTmt", label: t("paymentSettings.gbusFeeTmt", "GBÜS tutumy"), unit: "TMT" },
|
||||
{ key: "sberBankFeeTmt", label: t("paymentSettings.sberBankFeeTmt", "Sber bank tutumy"), unit: "TMT" },
|
||||
{ key: "tvebFeeUsd", label: t("paymentSettings.tvebFeeUsd", "TVEB tutumy"), unit: "USD" },
|
||||
{ key: "maxAmountUsd", label: t("paymentSettings.maxAmountUsd", "Iň ýokary möçber"), unit: "USD" },
|
||||
];
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" />
|
||||
<div className="relative z-10 w-full max-w-md mx-4 bg-card rounded-2xl shadow-2xl overflow-hidden border border-border">
|
||||
{/* Header */}
|
||||
<div className="px-6 pt-6 pb-4 border-b border-border flex items-center gap-2">
|
||||
<Settings2 size={16} className="text-primary" />
|
||||
<h2 className="text-sm font-bold uppercase tracking-widest text-foreground">
|
||||
{t("paymentSettings.editTitle", "Sazlamalary üýtget")}
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="px-6 py-5 space-y-4">
|
||||
{fields.map(({ key, label, unit }) => (
|
||||
<div key={key} className="flex items-center gap-4">
|
||||
<label className="min-w-40 text-sm text-muted-foreground">{label}</label>
|
||||
<div className="flex-1 relative">
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={form[key]}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
className="w-full h-9 px-3 pr-12 border border-border rounded-lg text-sm outline-none bg-background focus:border-primary focus:ring-1 focus:ring-primary/30 transition-colors"
|
||||
/>
|
||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-medium">{unit}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-6 pb-6 flex items-center justify-end gap-3">
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isPending}>
|
||||
{t("common.cancel", "Ýatyr")}
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSave} disabled={isPending}>
|
||||
{isPending ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
{t("common.saving", "Saklanýar...")}
|
||||
</span>
|
||||
) : (
|
||||
t("common.save", "Sakla")
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function PaymentSettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { data, isLoading } = usePaymentSettings();
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
|
||||
const initial: PaymentSettingsPayload = {
|
||||
bankFeeTmt: data?.bankFeeTmt ?? 0,
|
||||
gbusFeeTmt: data?.gbusFeeTmt ?? 0,
|
||||
sberBankFeeTmt: data?.sberBankFeeTmt ?? 0,
|
||||
tvebFeeUsd: data?.tvebFeeUsd ?? 0,
|
||||
maxAmountUsd: data?.maxAmountUsd ?? 0,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">{t("paymentSettings.title", "Töleg sazlamalary")}</h1>
|
||||
{data?.updatedAt && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{t("paymentSettings.lastUpdated", "Soňky üýtgeşme")}: {formatFromApiDate(data.updatedAt)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Button type="button" onClick={() => setEditOpen(true)} disabled={isLoading}>
|
||||
<Pencil size={14} />
|
||||
{t("paymentSettings.edit", "Üýtget")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Info card */}
|
||||
<div className="bg-card border border-border rounded-xl px-5 py-1">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-10 text-muted-foreground gap-2">
|
||||
<Loader2 size={16} className="animate-spin" />
|
||||
<span className="text-sm">{t("common.loading", "Ýüklenýär...")}</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<InfoRow label={t("paymentSettings.bankFeeTmt", "Bankyň tutumy")} value={data?.bankFeeTmt} unit="TMT" />
|
||||
<InfoRow label={t("paymentSettings.gbusFeeTmt", "GBÜS tutumy")} value={data?.gbusFeeTmt} unit="TMT" />
|
||||
<InfoRow label={t("paymentSettings.sberBankFeeTmt", "Sber bank tutumy")} value={data?.sberBankFeeTmt} unit="TMT" />
|
||||
<InfoRow label={t("paymentSettings.tvebFeeUsd", "TVEB tutumy")} value={data?.tvebFeeUsd} unit="USD" />
|
||||
<InfoRow label={t("paymentSettings.maxAmountUsd", "Iň ýokary möçber")} value={data?.maxAmountUsd} unit="USD" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Edit dialog */}
|
||||
<EditDialog open={editOpen} onOpenChange={setEditOpen} initial={initial} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user