Merge pull request 'feat/build-branch' (#3) from feat/build-branch into main
Reviewed-on: #3
This commit is contained in:
commit
9582fe89ed
@ -24,7 +24,14 @@ export async function POST(request: Request) {
|
|||||||
let mustChangePassword = false;
|
let mustChangePassword = false;
|
||||||
try {
|
try {
|
||||||
const payload = decodeJwt(token);
|
const payload = decodeJwt(token);
|
||||||
mustChangePassword = payload.MustChangePassword || false;
|
const mustChangeClaim = payload.MustChangePassword;
|
||||||
|
if (typeof mustChangeClaim === "boolean") {
|
||||||
|
mustChangePassword = mustChangeClaim;
|
||||||
|
} else if (typeof mustChangeClaim === "string") {
|
||||||
|
mustChangePassword = mustChangeClaim.toLowerCase() === "true";
|
||||||
|
} else {
|
||||||
|
mustChangePassword = false;
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("❌ Failed to decode current JWT:", err);
|
console.error("❌ Failed to decode current JWT:", err);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,6 +16,8 @@ export async function POST(request: Request) {
|
|||||||
body: JSON.stringify({ email, password }),
|
body: JSON.stringify({ email, password }),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log("[LOGIN] resp", resp);
|
||||||
|
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
const errJson = await safeJson(resp);
|
const errJson = await safeJson(resp);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@ -1,15 +1,17 @@
|
|||||||
import { NextResponse } from "next/server";
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore
|
||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
|
|
||||||
const BE_BASE_URL = process.env.BE_BASE_URL || "http://localhost:8583";
|
const BE_BASE_URL = process.env.BE_BASE_URL || "http://localhost:8583";
|
||||||
const COOKIE_NAME = "auth_token";
|
const COOKIE_NAME = "auth_token";
|
||||||
|
|
||||||
export async function PUT(
|
export async function PUT(
|
||||||
request: Request,
|
request: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
context: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = params;
|
const { id } = await context.params;
|
||||||
|
|
||||||
if (!id) {
|
if (!id) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@ -39,15 +41,14 @@ export async function PUT(
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// Attempt to parse JSON; fall back to status-only response
|
let data;
|
||||||
let data: unknown = null;
|
|
||||||
try {
|
try {
|
||||||
data = await resp.json();
|
data = await resp.json();
|
||||||
} catch {
|
} catch {
|
||||||
data = { success: resp.ok };
|
data = { success: resp.ok };
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(data ?? { success: resp.ok }, {
|
return NextResponse.json(data, {
|
||||||
status: resp.status,
|
status: resp.status,
|
||||||
});
|
});
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
|
|||||||
73
app/api/dashboard/admin/groups/route.ts
Normal file
73
app/api/dashboard/admin/groups/route.ts
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { buildFilterParam } from "../utils";
|
||||||
|
|
||||||
|
const BE_BASE_URL = process.env.BE_BASE_URL || "http://localhost:5000";
|
||||||
|
const COOKIE_NAME = "auth_token";
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const { cookies } = await import("next/headers");
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Missing Authorization header" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const { filters = {}, pagination = { page: 1, limit: 10 }, sort } = body;
|
||||||
|
|
||||||
|
const queryParams = new URLSearchParams();
|
||||||
|
queryParams.set("limit", String(pagination.limit ?? 10));
|
||||||
|
queryParams.set("page", String(pagination.page ?? 1));
|
||||||
|
|
||||||
|
if (sort?.field && sort?.order) {
|
||||||
|
queryParams.set("sort", `${sort.field}:${sort.order}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const filterParam = buildFilterParam(filters);
|
||||||
|
if (filterParam) {
|
||||||
|
queryParams.set("filter", filterParam);
|
||||||
|
}
|
||||||
|
|
||||||
|
const backendUrl = `${BE_BASE_URL}/api/v1/groups${
|
||||||
|
queryParams.size ? `?${queryParams.toString()}` : ""
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const response = await fetch(backendUrl, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response
|
||||||
|
.json()
|
||||||
|
.catch(() => ({ message: "Failed to fetch groups" }));
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
success: false,
|
||||||
|
message: errorData?.message || "Failed to fetch groups",
|
||||||
|
},
|
||||||
|
{ status: response.status }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return NextResponse.json(data, { status: response.status });
|
||||||
|
} catch (err: unknown) {
|
||||||
|
console.error("Proxy POST /api/dashboard/admin/groups error:", err);
|
||||||
|
const errorMessage = err instanceof Error ? err.message : "Unknown error";
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Internal server error", error: errorMessage },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
73
app/api/dashboard/admin/permissions/route.ts
Normal file
73
app/api/dashboard/admin/permissions/route.ts
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { buildFilterParam } from "../utils";
|
||||||
|
|
||||||
|
const BE_BASE_URL = process.env.BE_BASE_URL || "http://localhost:5000";
|
||||||
|
const COOKIE_NAME = "auth_token";
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const { cookies } = await import("next/headers");
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Missing Authorization header" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const { filters = {}, pagination = { page: 1, limit: 10 }, sort } = body;
|
||||||
|
|
||||||
|
const queryParams = new URLSearchParams();
|
||||||
|
queryParams.set("limit", String(pagination.limit ?? 10));
|
||||||
|
queryParams.set("page", String(pagination.page ?? 1));
|
||||||
|
|
||||||
|
if (sort?.field && sort?.order) {
|
||||||
|
queryParams.set("sort", `${sort.field}:${sort.order}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const filterParam = buildFilterParam(filters);
|
||||||
|
if (filterParam) {
|
||||||
|
queryParams.set("filter", filterParam);
|
||||||
|
}
|
||||||
|
|
||||||
|
const backendUrl = `${BE_BASE_URL}/api/v1/permissions${
|
||||||
|
queryParams.size ? `?${queryParams.toString()}` : ""
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const response = await fetch(backendUrl, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response
|
||||||
|
.json()
|
||||||
|
.catch(() => ({ message: "Failed to fetch permissions" }));
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
success: false,
|
||||||
|
message: errorData?.message || "Failed to fetch permissions",
|
||||||
|
},
|
||||||
|
{ status: response.status }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return NextResponse.json(data, { status: response.status });
|
||||||
|
} catch (err: unknown) {
|
||||||
|
console.error("Proxy POST /api/dashboard/admin/permissions error:", err);
|
||||||
|
const errorMessage = err instanceof Error ? err.message : "Unknown error";
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Internal server error", error: errorMessage },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
73
app/api/dashboard/admin/sessions/route.ts
Normal file
73
app/api/dashboard/admin/sessions/route.ts
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { buildFilterParam } from "../utils";
|
||||||
|
|
||||||
|
const BE_BASE_URL = process.env.BE_BASE_URL || "http://localhost:5000";
|
||||||
|
const COOKIE_NAME = "auth_token";
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const { cookies } = await import("next/headers");
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Missing Authorization header" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const { filters = {}, pagination = { page: 1, limit: 10 }, sort } = body;
|
||||||
|
|
||||||
|
const queryParams = new URLSearchParams();
|
||||||
|
queryParams.set("limit", String(pagination.limit ?? 10));
|
||||||
|
queryParams.set("page", String(pagination.page ?? 1));
|
||||||
|
|
||||||
|
if (sort?.field && sort?.order) {
|
||||||
|
queryParams.set("sort", `${sort.field}:${sort.order}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const filterParam = buildFilterParam(filters);
|
||||||
|
if (filterParam) {
|
||||||
|
queryParams.set("filter", filterParam);
|
||||||
|
}
|
||||||
|
|
||||||
|
const backendUrl = `${BE_BASE_URL}/api/v1/sessions${
|
||||||
|
queryParams.size ? `?${queryParams.toString()}` : ""
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const response = await fetch(backendUrl, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response
|
||||||
|
.json()
|
||||||
|
.catch(() => ({ message: "Failed to fetch sessions" }));
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
success: false,
|
||||||
|
message: errorData?.message || "Failed to fetch sessions",
|
||||||
|
},
|
||||||
|
{ status: response.status }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return NextResponse.json(data, { status: response.status });
|
||||||
|
} catch (err: unknown) {
|
||||||
|
console.error("Proxy POST /api/dashboard/admin/sessions error:", err);
|
||||||
|
const errorMessage = err instanceof Error ? err.message : "Unknown error";
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Internal server error", error: errorMessage },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -63,10 +63,10 @@ function transformUserUpdateData(updates: Record<string, unknown>): {
|
|||||||
|
|
||||||
export async function PUT(
|
export async function PUT(
|
||||||
request: Request,
|
request: Request,
|
||||||
{ params }: { params: { id: string } }
|
context: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await context.params;
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
|
|
||||||
// Transform the request body to match backend format
|
// Transform the request body to match backend format
|
||||||
@ -108,10 +108,10 @@ export async function PUT(
|
|||||||
|
|
||||||
export async function DELETE(
|
export async function DELETE(
|
||||||
_request: Request,
|
_request: Request,
|
||||||
{ params }: { params: { id: string } }
|
context: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await context.params;
|
||||||
const { cookies } = await import("next/headers");
|
const { cookies } = await import("next/headers");
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const token = cookieStore.get(COOKIE_NAME)?.value;
|
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||||
|
|||||||
34
app/api/dashboard/admin/utils.ts
Normal file
34
app/api/dashboard/admin/utils.ts
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
export type FilterValue =
|
||||||
|
| string
|
||||||
|
| {
|
||||||
|
operator?: string;
|
||||||
|
value: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const buildFilterParam = (filters: Record<string, FilterValue>) => {
|
||||||
|
const filterExpressions: string[] = [];
|
||||||
|
|
||||||
|
for (const [key, filterValue] of Object.entries(filters)) {
|
||||||
|
if (!filterValue) continue;
|
||||||
|
|
||||||
|
let operator = "==";
|
||||||
|
let value: string;
|
||||||
|
|
||||||
|
if (typeof filterValue === "string") {
|
||||||
|
value = filterValue;
|
||||||
|
} else {
|
||||||
|
operator = filterValue.operator || "==";
|
||||||
|
value = filterValue.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value) continue;
|
||||||
|
|
||||||
|
const encodedValue = encodeURIComponent(value);
|
||||||
|
const needsEqualsPrefix = /^[A-Za-z]/.test(operator);
|
||||||
|
const operatorSegment = needsEqualsPrefix ? `=${operator}` : operator;
|
||||||
|
|
||||||
|
filterExpressions.push(`${key}${operatorSegment}/${encodedValue}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return filterExpressions.length > 0 ? filterExpressions.join(",") : undefined;
|
||||||
|
};
|
||||||
@ -5,10 +5,10 @@ const COOKIE_NAME = "auth_token";
|
|||||||
|
|
||||||
export async function PUT(
|
export async function PUT(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: { id: string } }
|
context: { params: Promise<{ id: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await context.params;
|
||||||
const { cookies } = await import("next/headers");
|
const { cookies } = await import("next/headers");
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
const token = cookieStore.get(COOKIE_NAME)?.value;
|
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||||
|
|||||||
@ -32,10 +32,32 @@ export async function POST(request: NextRequest) {
|
|||||||
queryParts.push(`sort=${sort.field}:${sort.order}`);
|
queryParts.push(`sort=${sort.field}:${sort.order}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Track date ranges separately so we can emit BETWEEN/>/< syntax
|
||||||
|
const dateRanges: Record<string, { start?: string; end?: string }> = {};
|
||||||
|
|
||||||
// Process filters - convert FilterValue objects to operator/value format
|
// Process filters - convert FilterValue objects to operator/value format
|
||||||
for (const [key, filterValue] of Object.entries(filters)) {
|
for (const [key, filterValue] of Object.entries(filters)) {
|
||||||
if (!filterValue) continue;
|
if (!filterValue) continue;
|
||||||
|
|
||||||
|
// Handle date range helpers (e.g. Created_start / Created_end)
|
||||||
|
if (/_start$|_end$/.test(key)) {
|
||||||
|
const baseField = key.replace(/_(start|end)$/, "");
|
||||||
|
if (!dateRanges[baseField]) {
|
||||||
|
dateRanges[baseField] = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetKey = key.endsWith("_start") ? "start" : "end";
|
||||||
|
const stringValue =
|
||||||
|
typeof filterValue === "string"
|
||||||
|
? filterValue
|
||||||
|
: (filterValue as { value?: string }).value;
|
||||||
|
|
||||||
|
if (stringValue) {
|
||||||
|
dateRanges[baseField][targetKey] = stringValue;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
let op: string;
|
let op: string;
|
||||||
let value: string;
|
let value: string;
|
||||||
|
|
||||||
@ -57,6 +79,24 @@ export async function POST(request: NextRequest) {
|
|||||||
queryParts.push(`${key}=${op}/${encodedValue}`);
|
queryParts.push(`${key}=${op}/${encodedValue}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Emit date range filters using backend format
|
||||||
|
for (const [field, { start, end }] of Object.entries(dateRanges)) {
|
||||||
|
if (start && end) {
|
||||||
|
queryParts.push(
|
||||||
|
`${field}=BETWEEN/${encodeURIComponent(start)}/${encodeURIComponent(
|
||||||
|
end
|
||||||
|
)}`
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start) {
|
||||||
|
queryParts.push(`${field}=>/${encodeURIComponent(start)}`);
|
||||||
|
} else if (end) {
|
||||||
|
queryParts.push(`${field}=</${encodeURIComponent(end)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const queryString = queryParts.join("&");
|
const queryString = queryParts.join("&");
|
||||||
const backendUrl = `${BE_BASE_URL}/api/v1/transactions${queryString ? `?${queryString}` : ""}`;
|
const backendUrl = `${BE_BASE_URL}/api/v1/transactions${queryString ? `?${queryString}` : ""}`;
|
||||||
|
|
||||||
|
|||||||
108
app/api/dashboard/transactions/withdrawals/route.ts
Normal file
108
app/api/dashboard/transactions/withdrawals/route.ts
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
const BE_BASE_URL = process.env.BE_BASE_URL || "http://localhost:5000";
|
||||||
|
const COOKIE_NAME = "auth_token";
|
||||||
|
|
||||||
|
type FilterValue =
|
||||||
|
| string
|
||||||
|
| {
|
||||||
|
operator?: string;
|
||||||
|
value: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const { cookies } = await import("next/headers");
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Missing Authorization header" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const { filters = {}, pagination = { page: 1, limit: 10 }, sort } = body;
|
||||||
|
|
||||||
|
// Force withdrawals filter while allowing other filters to stack
|
||||||
|
const mergedFilters: Record<string, FilterValue> = {
|
||||||
|
...filters,
|
||||||
|
Type: {
|
||||||
|
operator: "==",
|
||||||
|
value: "withdrawal",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const queryParts: string[] = [];
|
||||||
|
queryParts.push(`limit=${pagination.limit}`);
|
||||||
|
queryParts.push(`page=${pagination.page}`);
|
||||||
|
|
||||||
|
if (sort) {
|
||||||
|
queryParts.push(`sort=${sort.field}:${sort.order}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [key, filterValue] of Object.entries(mergedFilters)) {
|
||||||
|
if (!filterValue) continue;
|
||||||
|
|
||||||
|
let operator: string;
|
||||||
|
let value: string;
|
||||||
|
|
||||||
|
if (typeof filterValue === "string") {
|
||||||
|
operator = "==";
|
||||||
|
value = filterValue;
|
||||||
|
} else {
|
||||||
|
operator = filterValue.operator || "==";
|
||||||
|
value = filterValue.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value) continue;
|
||||||
|
|
||||||
|
const encodedValue = encodeURIComponent(value);
|
||||||
|
const needsEqualsPrefix = /^[A-Za-z]/.test(operator);
|
||||||
|
const operatorSegment = needsEqualsPrefix ? `=${operator}` : operator;
|
||||||
|
|
||||||
|
queryParts.push(`${key}${operatorSegment}/${encodedValue}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const queryString = queryParts.join("&");
|
||||||
|
const backendUrl = `${BE_BASE_URL}/api/v1/transactions${
|
||||||
|
queryString ? `?${queryString}` : ""
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const response = await fetch(backendUrl, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response
|
||||||
|
.json()
|
||||||
|
.catch(() => ({ message: "Failed to fetch withdrawals" }));
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
success: false,
|
||||||
|
message: errorData?.message || "Failed to fetch withdrawals",
|
||||||
|
},
|
||||||
|
{ status: response.status }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return NextResponse.json(data, { status: response.status });
|
||||||
|
} catch (err: unknown) {
|
||||||
|
console.error(
|
||||||
|
"Proxy POST /api/dashboard/transactions/withdrawals error:",
|
||||||
|
err
|
||||||
|
);
|
||||||
|
const errorMessage = err instanceof Error ? err.message : "Unknown error";
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Internal server error", error: errorMessage },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,13 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placeholder Settings API route.
|
||||||
|
* Keeps the module valid while the real implementation
|
||||||
|
* is being built, and makes the intent obvious to clients.
|
||||||
|
*/
|
||||||
|
export async function GET() {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Settings endpoint not implemented" },
|
||||||
|
{ status: 501 }
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -4,7 +4,7 @@ import React from "react";
|
|||||||
import { useDispatch } from "react-redux";
|
import { useDispatch } from "react-redux";
|
||||||
import { Button, Box, Typography, Stack } from "@mui/material";
|
import { Button, Box, Typography, Stack } from "@mui/material";
|
||||||
import { AppDispatch } from "@/app/redux/types";
|
import { AppDispatch } from "@/app/redux/types";
|
||||||
import { autoLogout, refreshAuthStatus } from "@/app/redux/auth/authSlice";
|
import { autoLogout, validateAuth } from "@/app/redux/auth/authSlice";
|
||||||
|
|
||||||
export default function TestTokenExpiration() {
|
export default function TestTokenExpiration() {
|
||||||
const dispatch = useDispatch<AppDispatch>();
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
@ -14,7 +14,7 @@ export default function TestTokenExpiration() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleRefreshAuth = () => {
|
const handleRefreshAuth = () => {
|
||||||
dispatch(refreshAuthStatus());
|
dispatch(validateAuth());
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
13
app/dashboard/admin/groups/page.tsx
Normal file
13
app/dashboard/admin/groups/page.tsx
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import AdminResourceList from "@/app/features/AdminList/AdminResourceList";
|
||||||
|
|
||||||
|
export default function GroupsPage() {
|
||||||
|
return (
|
||||||
|
<AdminResourceList
|
||||||
|
title="Groups"
|
||||||
|
endpoint="/api/dashboard/admin/groups"
|
||||||
|
responseCollectionKeys={["groups", "data", "items"]}
|
||||||
|
primaryLabelKeys={["name", "groupName", "title"]}
|
||||||
|
chipKeys={["status", "role", "permissions"]}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
15
app/dashboard/admin/permissions/page.tsx
Normal file
15
app/dashboard/admin/permissions/page.tsx
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import AdminResourceList from "@/app/features/AdminList/AdminResourceList";
|
||||||
|
|
||||||
|
export default function PermissionsPage() {
|
||||||
|
return (
|
||||||
|
<AdminResourceList
|
||||||
|
title="Permissions"
|
||||||
|
endpoint="/api/dashboard/admin/permissions"
|
||||||
|
responseCollectionKeys={["permissions", "data", "items"]}
|
||||||
|
primaryLabelKeys={["name", "permissionName", "title", "description"]}
|
||||||
|
chipKeys={["status", "scope", "category"]}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
13
app/dashboard/admin/sessions/page.tsx
Normal file
13
app/dashboard/admin/sessions/page.tsx
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import AdminResourceList from "@/app/features/AdminList/AdminResourceList";
|
||||||
|
|
||||||
|
export default function SessionsPage() {
|
||||||
|
return (
|
||||||
|
<AdminResourceList
|
||||||
|
title="Sessions"
|
||||||
|
endpoint="/api/dashboard/admin/sessions"
|
||||||
|
responseCollectionKeys={["sessions", "data", "items"]}
|
||||||
|
primaryLabelKeys={["sessionId", "id", "userId", "name", "title"]}
|
||||||
|
chipKeys={["status", "channel", "platform"]}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -30,7 +30,7 @@
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
|
||||||
.scroll-wrapper {
|
.scroll-wrapper {
|
||||||
width: 100dvw;
|
width: 85dvw;
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
overflow-y: hidden;
|
overflow-y: hidden;
|
||||||
|
|
||||||
|
|||||||
@ -9,6 +9,8 @@ import {
|
|||||||
} from "@mui/x-data-grid";
|
} from "@mui/x-data-grid";
|
||||||
import { getAudits } from "@/app/services/audits";
|
import { getAudits } from "@/app/services/audits";
|
||||||
import "./page.scss";
|
import "./page.scss";
|
||||||
|
import TextField from "@mui/material/TextField";
|
||||||
|
import { Box, debounce } from "@mui/material";
|
||||||
|
|
||||||
type AuditRow = Record<string, unknown> & { id: string | number };
|
type AuditRow = Record<string, unknown> & { id: string | number };
|
||||||
|
|
||||||
@ -178,6 +180,8 @@ export default function AuditPage() {
|
|||||||
pageSize: DEFAULT_PAGE_SIZE,
|
pageSize: DEFAULT_PAGE_SIZE,
|
||||||
});
|
});
|
||||||
const [sortModel, setSortModel] = useState<GridSortModel>([]);
|
const [sortModel, setSortModel] = useState<GridSortModel>([]);
|
||||||
|
const [entitySearch, setEntitySearch] = useState<string>("");
|
||||||
|
const [entitySearchInput, setEntitySearchInput] = useState<string>("");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
@ -191,11 +195,16 @@ export default function AuditPage() {
|
|||||||
? `${sortModel[0].field}:${sortModel[0].sort}`
|
? `${sortModel[0].field}:${sortModel[0].sort}`
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
|
const entityParam = entitySearch.trim()
|
||||||
|
? `LIKE/${entitySearch.trim()}`
|
||||||
|
: undefined;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = (await getAudits({
|
const payload = (await getAudits({
|
||||||
limit: paginationModel.pageSize,
|
limit: paginationModel.pageSize,
|
||||||
page: paginationModel.page + 1,
|
page: paginationModel.page + 1,
|
||||||
sort: sortParam,
|
sort: sortParam,
|
||||||
|
entity: entityParam,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
})) as AuditApiResponse;
|
})) as AuditApiResponse;
|
||||||
|
|
||||||
@ -229,7 +238,7 @@ export default function AuditPage() {
|
|||||||
fetchAudits();
|
fetchAudits();
|
||||||
|
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [paginationModel, sortModel]);
|
}, [paginationModel, sortModel, entitySearch]);
|
||||||
|
|
||||||
const handlePaginationChange = (model: GridPaginationModel) => {
|
const handlePaginationChange = (model: GridPaginationModel) => {
|
||||||
setPaginationModel(model);
|
setPaginationModel(model);
|
||||||
@ -240,6 +249,26 @@ export default function AuditPage() {
|
|||||||
setPaginationModel(prev => ({ ...prev, page: 0 }));
|
setPaginationModel(prev => ({ ...prev, page: 0 }));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const debouncedSetEntitySearch = useMemo(
|
||||||
|
() =>
|
||||||
|
debounce((value: string) => {
|
||||||
|
setEntitySearch(value);
|
||||||
|
setPaginationModel(prev => ({ ...prev, page: 0 }));
|
||||||
|
}, 500),
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
debouncedSetEntitySearch.clear();
|
||||||
|
};
|
||||||
|
}, [debouncedSetEntitySearch]);
|
||||||
|
|
||||||
|
const handleEntitySearchChange = (value: string) => {
|
||||||
|
setEntitySearchInput(value);
|
||||||
|
debouncedSetEntitySearch(value);
|
||||||
|
};
|
||||||
|
|
||||||
const pageTitle = useMemo(
|
const pageTitle = useMemo(
|
||||||
() =>
|
() =>
|
||||||
sortModel.length && sortModel[0].field
|
sortModel.length && sortModel[0].field
|
||||||
@ -250,6 +279,16 @@ export default function AuditPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="audits-page">
|
<div className="audits-page">
|
||||||
|
<Box sx={{ display: "flex", gap: 2, mt: 5 }}>
|
||||||
|
<TextField
|
||||||
|
label="Search by Entity"
|
||||||
|
variant="outlined"
|
||||||
|
size="small"
|
||||||
|
value={entitySearchInput}
|
||||||
|
onChange={e => handleEntitySearchChange(e.target.value)}
|
||||||
|
sx={{ width: 300, backgroundColor: "#f0f0f0" }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
<h1 className="page-title">{pageTitle}</h1>
|
<h1 className="page-title">{pageTitle}</h1>
|
||||||
{error && (
|
{error && (
|
||||||
<div className="error-alert" role="alert">
|
<div className="error-alert" role="alert">
|
||||||
|
|||||||
@ -18,11 +18,17 @@ export default function AllTransactionPage() {
|
|||||||
const pagination = useSelector(selectPagination);
|
const pagination = useSelector(selectPagination);
|
||||||
const sort = useSelector(selectSort);
|
const sort = useSelector(selectSort);
|
||||||
|
|
||||||
const [tableRows, setTableRows] = useState<TransactionRow[]>([]);
|
const [tableData, setTableData] = useState<{
|
||||||
|
transactions: TransactionRow[];
|
||||||
|
total: number;
|
||||||
|
}>({ transactions: [], total: 0 });
|
||||||
const extraColumns: string[] = []; // static for now
|
const extraColumns: string[] = []; // static for now
|
||||||
|
|
||||||
// Memoize rows to avoid new reference each render
|
// Memoize rows to avoid new reference each render
|
||||||
const memoizedRows = useMemo(() => tableRows, [tableRows]);
|
const memoizedRows = useMemo(
|
||||||
|
() => tableData.transactions,
|
||||||
|
[tableData.transactions]
|
||||||
|
);
|
||||||
|
|
||||||
// Fetch data when filters, pagination, or sort changes
|
// Fetch data when filters, pagination, or sort changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -37,12 +43,12 @@ export default function AllTransactionPage() {
|
|||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
dispatch(setAdvancedSearchError("Failed to fetch transactions"));
|
dispatch(setAdvancedSearchError("Failed to fetch transactions"));
|
||||||
setTableRows([]);
|
setTableData({ transactions: [], total: 0 });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const backendData = await response.json();
|
const data = await response.json();
|
||||||
const transactions = backendData.transactions || [];
|
const transactions = data.transactions || [];
|
||||||
|
|
||||||
const rows = transactions.map((tx: BackendTransaction) => ({
|
const rows = transactions.map((tx: BackendTransaction) => ({
|
||||||
id: tx.id || 0,
|
id: tx.id || 0,
|
||||||
@ -59,19 +65,25 @@ export default function AllTransactionPage() {
|
|||||||
modified: tx.modified,
|
modified: tx.modified,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
setTableRows(rows);
|
setTableData({ transactions: rows, total: data?.total });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
dispatch(
|
dispatch(
|
||||||
setAdvancedSearchError(
|
setAdvancedSearchError(
|
||||||
error instanceof Error ? error.message : "Unknown error"
|
error instanceof Error ? error.message : "Unknown error"
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
setTableRows([]);
|
setTableData({ transactions: [], total: 0 });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
fetchData();
|
fetchData();
|
||||||
}, [dispatch, filters, pagination, sort]);
|
}, [dispatch, filters, pagination, sort]);
|
||||||
|
|
||||||
return <DataTable rows={memoizedRows} extraColumns={extraColumns} />;
|
return (
|
||||||
|
<DataTable
|
||||||
|
rows={memoizedRows}
|
||||||
|
extraColumns={extraColumns}
|
||||||
|
totalRows={tableData.total}
|
||||||
|
/>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -21,6 +21,7 @@ export default function DepositTransactionPage() {
|
|||||||
const pagination = useSelector(selectPagination);
|
const pagination = useSelector(selectPagination);
|
||||||
const sort = useSelector(selectSort);
|
const sort = useSelector(selectSort);
|
||||||
const [tableRows, setTableRows] = useState<TransactionRow[]>([]);
|
const [tableRows, setTableRows] = useState<TransactionRow[]>([]);
|
||||||
|
const [rowCount, setRowCount] = useState(0);
|
||||||
|
|
||||||
const memoizedRows = useMemo(() => tableRows, [tableRows]);
|
const memoizedRows = useMemo(() => tableRows, [tableRows]);
|
||||||
|
|
||||||
@ -75,6 +76,7 @@ export default function DepositTransactionPage() {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
setTableRows(rows);
|
setTableRows(rows);
|
||||||
|
setRowCount(100);
|
||||||
dispatch(setStatus("succeeded"));
|
dispatch(setStatus("succeeded"));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
dispatch(
|
dispatch(
|
||||||
@ -89,5 +91,7 @@ export default function DepositTransactionPage() {
|
|||||||
fetchDeposits();
|
fetchDeposits();
|
||||||
}, [dispatch, depositFilters, pagination, sort]);
|
}, [dispatch, depositFilters, pagination, sort]);
|
||||||
|
|
||||||
return <DataTable rows={memoizedRows} enableStatusActions />;
|
return (
|
||||||
|
<DataTable rows={memoizedRows} enableStatusActions totalRows={rowCount} />
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,23 +1,100 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
import DataTable from "@/app/features/DataTable/DataTable";
|
import DataTable from "@/app/features/DataTable/DataTable";
|
||||||
import { getTransactions } from "@/app/services/transactions";
|
import { useDispatch, useSelector } from "react-redux";
|
||||||
|
import { AppDispatch } from "@/app/redux/store";
|
||||||
|
import {
|
||||||
|
selectFilters,
|
||||||
|
selectPagination,
|
||||||
|
selectSort,
|
||||||
|
} from "@/app/redux/advanedSearch/selectors";
|
||||||
|
import {
|
||||||
|
setStatus,
|
||||||
|
setError as setAdvancedSearchError,
|
||||||
|
} from "@/app/redux/advanedSearch/advancedSearchSlice";
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { TransactionRow, BackendTransaction } from "../interface";
|
||||||
|
|
||||||
export default async function WithdrawalTransactionPage({
|
export default function WithdrawalTransactionPage() {
|
||||||
searchParams,
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
}: {
|
const filters = useSelector(selectFilters);
|
||||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
const pagination = useSelector(selectPagination);
|
||||||
}) {
|
const sort = useSelector(selectSort);
|
||||||
// Await searchParams before processing
|
const [tableRows, setTableRows] = useState<TransactionRow[]>([]);
|
||||||
const params = await searchParams;
|
const [rowCount, setRowCount] = useState(0);
|
||||||
// Create a safe query string by filtering only string values
|
|
||||||
const safeParams: Record<string, string> = {};
|
|
||||||
for (const [key, value] of Object.entries(params)) {
|
|
||||||
if (typeof value === "string") {
|
|
||||||
safeParams[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const query = new URLSearchParams(safeParams).toString();
|
|
||||||
const transactionType = "withdrawal";
|
|
||||||
const data = await getTransactions({ transactionType, query });
|
|
||||||
|
|
||||||
return <DataTable data={data} />;
|
const memoizedRows = useMemo(() => tableRows, [tableRows]);
|
||||||
|
|
||||||
|
const withdrawalFilters = useMemo(() => {
|
||||||
|
return {
|
||||||
|
...filters,
|
||||||
|
Type: {
|
||||||
|
operator: "==",
|
||||||
|
value: "withdrawal",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}, [filters]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchWithdrawals = async () => {
|
||||||
|
dispatch(setStatus("loading"));
|
||||||
|
dispatch(setAdvancedSearchError(null));
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
"/api/dashboard/transactions/withdrawals",
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
filters: withdrawalFilters,
|
||||||
|
pagination,
|
||||||
|
sort,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
dispatch(setAdvancedSearchError("Failed to fetch withdrawals"));
|
||||||
|
setTableRows([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const backendData = await response.json();
|
||||||
|
const transactions: BackendTransaction[] =
|
||||||
|
backendData.transactions || [];
|
||||||
|
|
||||||
|
const rows: TransactionRow[] = transactions.map(tx => ({
|
||||||
|
id: tx.id,
|
||||||
|
userId: tx.customer,
|
||||||
|
transactionId: String(tx.external_id ?? tx.id),
|
||||||
|
type: tx.type,
|
||||||
|
currency: tx.currency,
|
||||||
|
amount: tx.amount,
|
||||||
|
status: tx.status,
|
||||||
|
dateTime: tx.created || tx.modified,
|
||||||
|
merchantId: tx.merchant_id,
|
||||||
|
pspId: tx.psp_id,
|
||||||
|
methodId: tx.method_id,
|
||||||
|
modified: tx.modified,
|
||||||
|
}));
|
||||||
|
|
||||||
|
setTableRows(rows);
|
||||||
|
setRowCount(100);
|
||||||
|
dispatch(setStatus("succeeded"));
|
||||||
|
} catch (error) {
|
||||||
|
dispatch(
|
||||||
|
setAdvancedSearchError(
|
||||||
|
error instanceof Error ? error.message : "Unknown error"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
setTableRows([]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchWithdrawals();
|
||||||
|
}, [dispatch, withdrawalFilters, pagination, sort]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DataTable rows={memoizedRows} enableStatusActions totalRows={rowCount} />
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
290
app/features/AdminList/AdminResourceList.tsx
Normal file
290
app/features/AdminList/AdminResourceList.tsx
Normal file
@ -0,0 +1,290 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Spinner from "@/app/components/Spinner/Spinner";
|
||||||
|
import { DataRowBase } from "@/app/features/DataTable/types";
|
||||||
|
import {
|
||||||
|
setError as setAdvancedSearchError,
|
||||||
|
setStatus,
|
||||||
|
} from "@/app/redux/advanedSearch/advancedSearchSlice";
|
||||||
|
import {
|
||||||
|
selectError,
|
||||||
|
selectFilters,
|
||||||
|
selectPagination,
|
||||||
|
selectSort,
|
||||||
|
selectStatus,
|
||||||
|
} from "@/app/redux/advanedSearch/selectors";
|
||||||
|
import { AppDispatch } from "@/app/redux/store";
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Box,
|
||||||
|
Chip,
|
||||||
|
Divider,
|
||||||
|
List,
|
||||||
|
ListItem,
|
||||||
|
Typography,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { useDispatch, useSelector } from "react-redux";
|
||||||
|
|
||||||
|
type ResourceRow = DataRowBase & Record<string, unknown>;
|
||||||
|
|
||||||
|
type FilterValue =
|
||||||
|
| string
|
||||||
|
| {
|
||||||
|
operator?: string;
|
||||||
|
value: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface AdminResourceListProps {
|
||||||
|
title: string;
|
||||||
|
endpoint: string;
|
||||||
|
responseCollectionKeys?: string[];
|
||||||
|
primaryLabelKeys: string[];
|
||||||
|
chipKeys?: string[];
|
||||||
|
excludeKeys?: string[];
|
||||||
|
filterOverrides?: Record<string, FilterValue>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_COLLECTION_KEYS = ["data", "items"];
|
||||||
|
|
||||||
|
const ensureRowId = (
|
||||||
|
row: Record<string, unknown>,
|
||||||
|
fallbackId: number
|
||||||
|
): ResourceRow => {
|
||||||
|
const currentId = row.id;
|
||||||
|
|
||||||
|
if (typeof currentId === "number") {
|
||||||
|
return row as ResourceRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
const numericId = Number(currentId);
|
||||||
|
|
||||||
|
if (!Number.isNaN(numericId) && numericId !== 0) {
|
||||||
|
return { ...row, id: numericId } as ResourceRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...row, id: fallbackId } as ResourceRow;
|
||||||
|
};
|
||||||
|
|
||||||
|
const resolveCollection = (
|
||||||
|
payload: Record<string, unknown>,
|
||||||
|
preferredKeys: string[] = []
|
||||||
|
) => {
|
||||||
|
for (const key of [...preferredKeys, ...DEFAULT_COLLECTION_KEYS]) {
|
||||||
|
const maybeCollection = payload?.[key];
|
||||||
|
if (Array.isArray(maybeCollection)) {
|
||||||
|
return maybeCollection as Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(payload)) {
|
||||||
|
return payload as Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const AdminResourceList = ({
|
||||||
|
title,
|
||||||
|
endpoint,
|
||||||
|
responseCollectionKeys = [],
|
||||||
|
primaryLabelKeys,
|
||||||
|
chipKeys = [],
|
||||||
|
excludeKeys = [],
|
||||||
|
}: AdminResourceListProps) => {
|
||||||
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
|
const filters = useSelector(selectFilters);
|
||||||
|
const pagination = useSelector(selectPagination);
|
||||||
|
const sort = useSelector(selectSort);
|
||||||
|
const status = useSelector(selectStatus);
|
||||||
|
const errorMessage = useSelector(selectError);
|
||||||
|
|
||||||
|
const [rows, setRows] = useState<ResourceRow[]>([]);
|
||||||
|
|
||||||
|
const normalizedTitle = title.toLowerCase();
|
||||||
|
|
||||||
|
const excludedKeys = useMemo(() => {
|
||||||
|
const baseExcluded = new Set(["id", ...primaryLabelKeys, ...chipKeys]);
|
||||||
|
excludeKeys.forEach(key => baseExcluded.add(key));
|
||||||
|
return Array.from(baseExcluded);
|
||||||
|
}, [primaryLabelKeys, chipKeys, excludeKeys]);
|
||||||
|
|
||||||
|
const getPrimaryLabel = (row: ResourceRow) => {
|
||||||
|
for (const key of primaryLabelKeys) {
|
||||||
|
if (row[key]) {
|
||||||
|
return String(row[key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return `${title} #${row.id}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getMetaChips = (row: ResourceRow) =>
|
||||||
|
chipKeys
|
||||||
|
.filter(key => row[key])
|
||||||
|
.map(key => ({
|
||||||
|
key,
|
||||||
|
value: String(row[key]),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const getSecondaryDetails = (row: ResourceRow) =>
|
||||||
|
Object.entries(row).filter(([key]) => !excludedKeys.includes(key));
|
||||||
|
|
||||||
|
const resolvedCollectionKeys = useMemo(
|
||||||
|
() => [...responseCollectionKeys],
|
||||||
|
[responseCollectionKeys]
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchResources = async () => {
|
||||||
|
dispatch(setStatus("loading"));
|
||||||
|
dispatch(setAdvancedSearchError(null));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(endpoint, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
filters,
|
||||||
|
pagination,
|
||||||
|
sort,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
dispatch(
|
||||||
|
setAdvancedSearchError(`Failed to fetch ${normalizedTitle}`)
|
||||||
|
);
|
||||||
|
setRows([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const backendData = await response.json();
|
||||||
|
const collection = resolveCollection(
|
||||||
|
backendData,
|
||||||
|
resolvedCollectionKeys
|
||||||
|
);
|
||||||
|
|
||||||
|
const nextRows = collection.map((item, index) =>
|
||||||
|
ensureRowId(item, index + 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
setRows(nextRows);
|
||||||
|
dispatch(setStatus("succeeded"));
|
||||||
|
} catch (error) {
|
||||||
|
dispatch(
|
||||||
|
setAdvancedSearchError(
|
||||||
|
error instanceof Error ? error.message : "Unknown error"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
setRows([]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchResources();
|
||||||
|
}, [
|
||||||
|
dispatch,
|
||||||
|
endpoint,
|
||||||
|
filters,
|
||||||
|
pagination,
|
||||||
|
sort,
|
||||||
|
resolvedCollectionKeys,
|
||||||
|
normalizedTitle,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box sx={{ p: 3, width: "100%", maxWidth: 900 }}>
|
||||||
|
<Typography variant="h5" sx={{ mb: 2 }}>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{status === "loading" && (
|
||||||
|
<Box sx={{ display: "flex", gap: 1, alignItems: "center", mb: 2 }}>
|
||||||
|
<Spinner size="small" color="#000" />
|
||||||
|
<Typography variant="body2">
|
||||||
|
{`Loading ${normalizedTitle}...`}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === "failed" && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
|
{errorMessage || `Failed to load ${normalizedTitle}`}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!rows.length && status === "succeeded" && (
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
{`No ${normalizedTitle} found.`}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{rows.length > 0 && (
|
||||||
|
<List
|
||||||
|
sx={{ bgcolor: "background.paper", borderRadius: 2, boxShadow: 1 }}
|
||||||
|
>
|
||||||
|
{rows.map(row => {
|
||||||
|
const chips = getMetaChips(row);
|
||||||
|
const secondary = getSecondaryDetails(row);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box key={row.id}>
|
||||||
|
<ListItem alignItems="flex-start">
|
||||||
|
<Box sx={{ width: "100%" }}>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
flexWrap: "wrap",
|
||||||
|
gap: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant="subtitle1" fontWeight={600}>
|
||||||
|
{getPrimaryLabel(row)}
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
ID: {row.id}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{chips.length > 0 && (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
gap: 1,
|
||||||
|
flexWrap: "wrap",
|
||||||
|
my: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{chips.map(chip => (
|
||||||
|
<Chip
|
||||||
|
key={`${row.id}-${chip.key}`}
|
||||||
|
label={`${chip.key}: ${chip.value}`}
|
||||||
|
size="small"
|
||||||
|
color="primary"
|
||||||
|
variant="outlined"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{secondary.length > 0 && (
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
{secondary
|
||||||
|
.map(([key, value]) => `${key}: ${String(value)}`)
|
||||||
|
.join(" • ")}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</ListItem>
|
||||||
|
<Divider component="li" />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</List>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AdminResourceList;
|
||||||
@ -28,6 +28,7 @@ import {
|
|||||||
} from "@/app/redux/advanedSearch/advancedSearchSlice";
|
} from "@/app/redux/advanedSearch/advancedSearchSlice";
|
||||||
import { selectFilters } from "@/app/redux/advanedSearch/selectors";
|
import { selectFilters } from "@/app/redux/advanedSearch/selectors";
|
||||||
import { normalizeValue, defaultOperatorForField } from "./utils/utils";
|
import { normalizeValue, defaultOperatorForField } from "./utils/utils";
|
||||||
|
import { selectConditionOperators } from "@/app/redux/metadata/selectors";
|
||||||
|
|
||||||
// -----------------------------------------------------
|
// -----------------------------------------------------
|
||||||
// COMPONENT
|
// COMPONENT
|
||||||
@ -42,7 +43,9 @@ export default function AdvancedSearch({ labels }: { labels: ISearchLabel[] }) {
|
|||||||
// Local form state for UI (synced with Redux)
|
// Local form state for UI (synced with Redux)
|
||||||
const [formValues, setFormValues] = useState<Record<string, string>>({});
|
const [formValues, setFormValues] = useState<Record<string, string>>({});
|
||||||
const [operators, setOperators] = useState<Record<string, string>>({});
|
const [operators, setOperators] = useState<Record<string, string>>({});
|
||||||
|
const conditionOperators = useSelector(selectConditionOperators);
|
||||||
|
|
||||||
|
console.log("[conditionOperators]", conditionOperators);
|
||||||
// -----------------------------------------------------
|
// -----------------------------------------------------
|
||||||
// SYNC REDUX FILTERS TO LOCAL STATE ON LOAD
|
// SYNC REDUX FILTERS TO LOCAL STATE ON LOAD
|
||||||
// -----------------------------------------------------
|
// -----------------------------------------------------
|
||||||
@ -255,12 +258,14 @@ export default function AdvancedSearch({ labels }: { labels: ISearchLabel[] }) {
|
|||||||
updateOperator(field, e.target.value)
|
updateOperator(field, e.target.value)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<MenuItem value=">=">Greater or equal</MenuItem>
|
{Object.entries(conditionOperators ?? {}).map(
|
||||||
<MenuItem value="<=">Less or equal</MenuItem>
|
([key, value]) => (
|
||||||
<MenuItem value="=">Equal</MenuItem>
|
<MenuItem key={key} value={value}>
|
||||||
<MenuItem value="!=">Not equal</MenuItem>
|
{key.replace(/_/g, " ")}{" "}
|
||||||
<MenuItem value=">">Greater</MenuItem>
|
{/* Optional: make it readable */}
|
||||||
<MenuItem value="<">Less</MenuItem>
|
</MenuItem>
|
||||||
|
)
|
||||||
|
)}
|
||||||
</Select>
|
</Select>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
|
|
||||||
|
|||||||
@ -1,17 +1,4 @@
|
|||||||
// -----------------------------------------------------
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
// UTILITIES
|
|
||||||
// -----------------------------------------------------
|
|
||||||
|
|
||||||
export const extractOperator = (val?: string | null): string | null => {
|
|
||||||
if (!val) return null;
|
|
||||||
|
|
||||||
const match = val.match(/^(==|!=|>=|<=|LIKE|>|<)/);
|
|
||||||
return match ? match[0] : null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const formatWithOperator = (operator: string, value: string) =>
|
|
||||||
`${operator}/${value}`;
|
|
||||||
|
|
||||||
export const normalizeValue = (input: any): string => {
|
export const normalizeValue = (input: any): string => {
|
||||||
if (input == null) return "";
|
if (input == null) return "";
|
||||||
if (typeof input === "string" || typeof input === "number")
|
if (typeof input === "string" || typeof input === "number")
|
||||||
@ -27,22 +14,6 @@ export const normalizeValue = (input: any): string => {
|
|||||||
return "";
|
return "";
|
||||||
};
|
};
|
||||||
|
|
||||||
export const encodeFilter = (fullValue: string): string => {
|
|
||||||
// Split ONLY on the first slash
|
|
||||||
const index = fullValue.indexOf("/");
|
|
||||||
if (index === -1) return fullValue;
|
|
||||||
|
|
||||||
const operator = fullValue.slice(0, index);
|
|
||||||
const rawValue = fullValue.slice(index + 1);
|
|
||||||
|
|
||||||
return `${operator}/${encodeURIComponent(rawValue)}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const decodeFilter = (encoded: string): string => {
|
|
||||||
const [operator, encodedValue] = encoded.split("/");
|
|
||||||
return `${operator}/${decodeURIComponent(encodedValue)}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Default operator based on field and type
|
// Default operator based on field and type
|
||||||
export const defaultOperatorForField = (
|
export const defaultOperatorForField = (
|
||||||
field: string,
|
field: string,
|
||||||
|
|||||||
@ -1,29 +1,38 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useState, useEffect, useCallback } from "react";
|
import React, { useState, useCallback, useMemo } from "react";
|
||||||
import { DataGrid } from "@mui/x-data-grid";
|
import { DataGrid, GridPaginationModel } from "@mui/x-data-grid";
|
||||||
import { Box, Paper, Alert } from "@mui/material";
|
import { Box, Paper, Alert } from "@mui/material";
|
||||||
import DataTableHeader from "./DataTableHeader";
|
import DataTableHeader from "./DataTableHeader";
|
||||||
import StatusChangeDialog from "./StatusChangeDialog";
|
import StatusChangeDialog from "./StatusChangeDialog";
|
||||||
import Spinner from "@/app/components/Spinner/Spinner";
|
import Spinner from "@/app/components/Spinner/Spinner";
|
||||||
import { selectStatus, selectError } from "@/app/redux/advanedSearch/selectors";
|
import {
|
||||||
import { selectEnhancedColumns } from "./re-selectors";
|
selectStatus,
|
||||||
import { useSelector } from "react-redux";
|
selectError,
|
||||||
|
selectPagination,
|
||||||
|
selectPaginationModel,
|
||||||
|
} from "@/app/redux/advanedSearch/selectors";
|
||||||
|
import { makeSelectEnhancedColumns } from "./re-selectors";
|
||||||
|
import { useDispatch, useSelector } from "react-redux";
|
||||||
import { DataRowBase } from "./types";
|
import { DataRowBase } from "./types";
|
||||||
|
import { setPagination } from "@/app/redux/advanedSearch/advancedSearchSlice";
|
||||||
|
import { AppDispatch } from "@/app/redux/store";
|
||||||
|
|
||||||
interface DataTableProps<TRow extends DataRowBase> {
|
interface DataTableProps<TRow extends DataRowBase> {
|
||||||
rows: TRow[];
|
rows: TRow[];
|
||||||
extraColumns?: string[];
|
extraColumns?: string[];
|
||||||
enableStatusActions?: boolean;
|
enableStatusActions?: boolean;
|
||||||
|
totalRows?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DataTable = <TRow extends DataRowBase>({
|
const DataTable = <TRow extends DataRowBase>({
|
||||||
rows,
|
rows: localRows,
|
||||||
extraColumns,
|
extraColumns,
|
||||||
enableStatusActions = false,
|
enableStatusActions = false,
|
||||||
|
totalRows: totalRows,
|
||||||
}: DataTableProps<TRow>) => {
|
}: DataTableProps<TRow>) => {
|
||||||
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
const [showExtraColumns, setShowExtraColumns] = useState(false);
|
const [showExtraColumns, setShowExtraColumns] = useState(false);
|
||||||
const [localRows, setLocalRows] = useState(rows);
|
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [selectedRowId, setSelectedRowId] = useState<number | null>(null);
|
const [selectedRowId, setSelectedRowId] = useState<number | null>(null);
|
||||||
const [pendingStatus, setPendingStatus] = useState<string>("");
|
const [pendingStatus, setPendingStatus] = useState<string>("");
|
||||||
@ -35,9 +44,21 @@ const DataTable = <TRow extends DataRowBase>({
|
|||||||
|
|
||||||
const status = useSelector(selectStatus);
|
const status = useSelector(selectStatus);
|
||||||
const errorMessage = useSelector(selectError);
|
const errorMessage = useSelector(selectError);
|
||||||
useEffect(() => {
|
const pagination = useSelector(selectPagination);
|
||||||
setLocalRows(rows);
|
const paginationModel = useSelector(selectPaginationModel);
|
||||||
}, [rows]);
|
|
||||||
|
const handlePaginationModelChange = useCallback(
|
||||||
|
(model: GridPaginationModel) => {
|
||||||
|
console.log("model", model);
|
||||||
|
const nextPage = model.page + 1;
|
||||||
|
const nextLimit = model.pageSize;
|
||||||
|
|
||||||
|
if (nextPage !== pagination.page || nextLimit !== pagination.limit) {
|
||||||
|
dispatch(setPagination({ page: nextPage, limit: nextLimit }));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[dispatch, pagination.page, pagination.limit]
|
||||||
|
);
|
||||||
|
|
||||||
const handleStatusChange = useCallback((rowId: number, newStatus: string) => {
|
const handleStatusChange = useCallback((rowId: number, newStatus: string) => {
|
||||||
setSelectedRowId(rowId);
|
setSelectedRowId(rowId);
|
||||||
@ -78,11 +99,6 @@ const DataTable = <TRow extends DataRowBase>({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
setLocalRows(prev =>
|
|
||||||
prev.map(row =>
|
|
||||||
row.id === selectedRowId ? { ...row, status: pendingStatus } : row
|
|
||||||
)
|
|
||||||
);
|
|
||||||
setModalOpen(false);
|
setModalOpen(false);
|
||||||
setReason("");
|
setReason("");
|
||||||
setPendingStatus("");
|
setPendingStatus("");
|
||||||
@ -97,18 +113,17 @@ const DataTable = <TRow extends DataRowBase>({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Columns with custom renderers
|
const selectEnhancedColumns = useMemo(makeSelectEnhancedColumns, []);
|
||||||
|
|
||||||
const enhancedColumns = useSelector(state =>
|
const enhancedColumns = useSelector(state =>
|
||||||
selectEnhancedColumns(
|
selectEnhancedColumns(state, {
|
||||||
state,
|
|
||||||
enableStatusActions,
|
enableStatusActions,
|
||||||
extraColumns,
|
extraColumns,
|
||||||
showExtraColumns,
|
showExtraColumns,
|
||||||
localRows,
|
localRows,
|
||||||
handleStatusChange
|
handleStatusChange,
|
||||||
)
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{status === "loading" && <Spinner size="small" color="#fff" />}
|
{status === "loading" && <Spinner size="small" color="#fff" />}
|
||||||
@ -125,11 +140,15 @@ const DataTable = <TRow extends DataRowBase>({
|
|||||||
onOpenExport={() => {}}
|
onOpenExport={() => {}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Box sx={{ width: "100%", overflowX: "auto" }}>
|
<Box sx={{ width: "85vw" }}>
|
||||||
<Box sx={{ minWidth: 1200 }}>
|
<Box sx={{ minWidth: 1200 }}>
|
||||||
<DataGrid
|
<DataGrid
|
||||||
rows={localRows}
|
rows={localRows}
|
||||||
columns={enhancedColumns}
|
columns={enhancedColumns}
|
||||||
|
paginationModel={paginationModel}
|
||||||
|
onPaginationModelChange={handlePaginationModelChange}
|
||||||
|
paginationMode={totalRows ? "server" : "client"}
|
||||||
|
rowCount={totalRows}
|
||||||
pageSizeOptions={[10, 25, 50, 100]}
|
pageSizeOptions={[10, 25, 50, 100]}
|
||||||
sx={{
|
sx={{
|
||||||
border: 0,
|
border: 0,
|
||||||
|
|||||||
@ -33,5 +33,5 @@ export const TABLE_SEARCH_LABELS: ISearchLabel[] = [
|
|||||||
options: ["pending", "completed", "failed"],
|
options: ["pending", "completed", "failed"],
|
||||||
},
|
},
|
||||||
{ label: "Amount", field: "Amount", type: "text" },
|
{ label: "Amount", field: "Amount", type: "text" },
|
||||||
{ label: "Date / Time", field: "created", type: "date" },
|
{ label: "Date / Time", field: "Created", type: "date" },
|
||||||
];
|
];
|
||||||
|
|||||||
@ -15,224 +15,319 @@ const TRANSACTION_STATUS_FALLBACK: string[] = [
|
|||||||
"error",
|
"error",
|
||||||
];
|
];
|
||||||
|
|
||||||
type StatusChangeHandler = (rowId: number, newStatus: string) => void;
|
type SelectorProps = {
|
||||||
|
enableStatusActions: boolean;
|
||||||
|
extraColumns?: string[] | null;
|
||||||
|
showExtraColumns?: boolean;
|
||||||
|
localRows: DataRowBase[];
|
||||||
|
handleStatusChange: (rowId: number, newStatus: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
const selectEnableStatusActions = (
|
// -------------------------
|
||||||
_state: RootState,
|
// Basic Selectors (props-driven)
|
||||||
enableStatusActions: boolean
|
// -------------------------
|
||||||
) => enableStatusActions;
|
|
||||||
|
|
||||||
const selectExtraColumns = (
|
const propsEnableStatusActions = (_: RootState, props: SelectorProps) =>
|
||||||
_state: RootState,
|
props.enableStatusActions;
|
||||||
_enableStatusActions: boolean,
|
|
||||||
extraColumns?: string[] | null
|
|
||||||
) => extraColumns ?? null;
|
|
||||||
|
|
||||||
const selectShowExtraColumns = (
|
const propsExtraColumns = (_: RootState, props: SelectorProps) =>
|
||||||
_state: RootState,
|
props.extraColumns ?? null;
|
||||||
_enableStatusActions: boolean,
|
|
||||||
_extraColumns?: string[] | null,
|
|
||||||
showExtraColumns = false
|
|
||||||
) => showExtraColumns;
|
|
||||||
|
|
||||||
const selectLocalRows = (
|
const propsShowExtraColumns = (_: RootState, props: SelectorProps) =>
|
||||||
_state: RootState,
|
props.showExtraColumns ?? false;
|
||||||
_enableStatusActions: boolean,
|
|
||||||
_extraColumns?: string[] | null,
|
|
||||||
_showExtraColumns?: boolean,
|
|
||||||
localRows?: DataRowBase[]
|
|
||||||
) => localRows ?? [];
|
|
||||||
|
|
||||||
const noopStatusChangeHandler: StatusChangeHandler = () => {};
|
const propsLocalRows = (_: RootState, props: SelectorProps) =>
|
||||||
|
props.localRows ?? [];
|
||||||
|
|
||||||
const selectStatusChangeHandler = (
|
const propsStatusChangeHandler = (_: RootState, props: SelectorProps) =>
|
||||||
_state: RootState,
|
props.handleStatusChange;
|
||||||
_enableStatusActions: boolean,
|
|
||||||
_extraColumns?: string[] | null,
|
|
||||||
_showExtraColumns?: boolean,
|
|
||||||
_localRows?: DataRowBase[],
|
|
||||||
handleStatusChange?: StatusChangeHandler
|
|
||||||
) => handleStatusChange ?? noopStatusChangeHandler;
|
|
||||||
|
|
||||||
export const selectBaseColumns = createSelector(
|
// -------------------------
|
||||||
[selectEnableStatusActions],
|
// Helper: Format field name to header name
|
||||||
enableStatusActions => {
|
// -------------------------
|
||||||
if (!enableStatusActions) {
|
|
||||||
|
/**
|
||||||
|
* Converts a field name to a readable header name
|
||||||
|
* e.g., "userId" -> "User ID", "transactionId" -> "Transaction ID"
|
||||||
|
*/
|
||||||
|
const formatFieldNameToHeader = (fieldName: string): string => {
|
||||||
|
// Handle camelCase: insert space before capital letters and capitalize first letter
|
||||||
|
return fieldName
|
||||||
|
.replace(/([A-Z])/g, " $1") // Add space before capital letters
|
||||||
|
.replace(/^./, str => str.toUpperCase()) // Capitalize first letter
|
||||||
|
.trim();
|
||||||
|
};
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Dynamic Columns from Row Data
|
||||||
|
// -------------------------
|
||||||
|
|
||||||
|
const makeSelectDynamicColumns = () =>
|
||||||
|
createSelector([propsLocalRows], (localRows): GridColDef[] => {
|
||||||
|
// If no rows, fall back to static columns
|
||||||
|
if (!localRows || localRows.length === 0) {
|
||||||
return TABLE_COLUMNS;
|
return TABLE_COLUMNS;
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
// Get all unique field names from the row data
|
||||||
...TABLE_COLUMNS,
|
const fieldSet = new Set<string>();
|
||||||
{
|
localRows.forEach(row => {
|
||||||
field: "actions",
|
Object.keys(row).forEach(key => {
|
||||||
headerName: "Actions",
|
if (key !== "options") {
|
||||||
width: 160,
|
// Exclude internal fields
|
||||||
sortable: false,
|
fieldSet.add(key);
|
||||||
filterable: false,
|
}
|
||||||
} as GridColDef,
|
});
|
||||||
];
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
export const selectVisibleColumns = createSelector(
|
// Build columns from actual row data fields
|
||||||
[selectBaseColumns, selectExtraColumns, selectShowExtraColumns],
|
const dynamicColumns: GridColDef[] = Array.from(fieldSet).map(field => {
|
||||||
(baseColumns, extraColumns, showExtraColumns) => {
|
// Format field name to readable header
|
||||||
if (!extraColumns || extraColumns.length === 0) {
|
const headerName = formatFieldNameToHeader(field);
|
||||||
return baseColumns;
|
|
||||||
|
// Set default widths based on field type
|
||||||
|
let width = 150;
|
||||||
|
if (field.includes("id") || field.includes("Id")) {
|
||||||
|
width = 180;
|
||||||
|
} else if (field === "amount" || field === "currency") {
|
||||||
|
width = 120;
|
||||||
|
} else if (field === "status") {
|
||||||
|
width = 120;
|
||||||
|
} else if (
|
||||||
|
field.includes("date") ||
|
||||||
|
field.includes("Date") ||
|
||||||
|
field === "dateTime" ||
|
||||||
|
field === "created" ||
|
||||||
|
field === "modified"
|
||||||
|
) {
|
||||||
|
width = 180;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
field,
|
||||||
|
headerName,
|
||||||
|
width,
|
||||||
|
sortable: true,
|
||||||
|
filterable: true,
|
||||||
|
} as GridColDef;
|
||||||
|
});
|
||||||
|
|
||||||
|
return dynamicColumns;
|
||||||
|
});
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Base Columns
|
||||||
|
// -------------------------
|
||||||
|
|
||||||
|
const makeSelectBaseColumns = () =>
|
||||||
|
createSelector(
|
||||||
|
[makeSelectDynamicColumns(), propsEnableStatusActions],
|
||||||
|
(dynamicColumns, enableStatusActions) => {
|
||||||
|
const baseColumns = dynamicColumns;
|
||||||
|
|
||||||
|
if (!enableStatusActions) return baseColumns;
|
||||||
|
|
||||||
|
return [
|
||||||
|
...baseColumns,
|
||||||
|
{
|
||||||
|
field: "actions",
|
||||||
|
headerName: "Actions",
|
||||||
|
width: 160,
|
||||||
|
sortable: false,
|
||||||
|
filterable: false,
|
||||||
|
} as GridColDef,
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
|
||||||
return showExtraColumns
|
// -------------------------
|
||||||
? baseColumns
|
// Visible Columns
|
||||||
: baseColumns.filter(col => !extraColumns.includes(col.field));
|
// -------------------------
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
export const selectResolvedTransactionStatuses = createSelector(
|
const makeSelectVisibleColumns = () =>
|
||||||
[selectTransactionStatuses],
|
createSelector(
|
||||||
statuses => (statuses.length > 0 ? statuses : TRANSACTION_STATUS_FALLBACK)
|
[makeSelectBaseColumns(), propsExtraColumns, propsShowExtraColumns],
|
||||||
);
|
(baseColumns, extraColumns, showExtraColumns) => {
|
||||||
|
// Columns are already built from row data, so they're all valid
|
||||||
|
if (!extraColumns || extraColumns.length === 0) return baseColumns;
|
||||||
|
|
||||||
export const selectEnhancedColumns = createSelector(
|
const visibleColumns = showExtraColumns
|
||||||
[
|
? baseColumns
|
||||||
selectVisibleColumns,
|
: baseColumns.filter(col => !extraColumns.includes(col.field));
|
||||||
selectLocalRows,
|
|
||||||
selectStatusChangeHandler,
|
console.log("visibleColumns", visibleColumns);
|
||||||
selectResolvedTransactionStatuses,
|
return visibleColumns;
|
||||||
],
|
}
|
||||||
(
|
);
|
||||||
visibleColumns,
|
// -------------------------
|
||||||
localRows,
|
// Resolved Statuses (STATE-based)
|
||||||
handleStatusChange,
|
// -------------------------
|
||||||
resolvedStatusOptions
|
|
||||||
): GridColDef[] => {
|
const makeSelectResolvedStatuses = () =>
|
||||||
return visibleColumns.map(col => {
|
createSelector([selectTransactionStatuses], statuses =>
|
||||||
if (col.field === "status") {
|
statuses.length > 0 ? statuses : TRANSACTION_STATUS_FALLBACK
|
||||||
return {
|
);
|
||||||
...col,
|
|
||||||
renderCell: (params: GridRenderCellParams) => {
|
// -------------------------
|
||||||
const value = params.value?.toLowerCase();
|
// Enhanced Columns
|
||||||
let bgColor = "#e0e0e0";
|
// -------------------------
|
||||||
let textColor = "#000";
|
|
||||||
switch (value) {
|
export const makeSelectEnhancedColumns = () =>
|
||||||
case "completed":
|
createSelector(
|
||||||
bgColor = "#d0f0c0";
|
[
|
||||||
textColor = "#1b5e20";
|
makeSelectVisibleColumns(),
|
||||||
break;
|
propsLocalRows,
|
||||||
case "pending":
|
propsStatusChangeHandler,
|
||||||
bgColor = "#fff4cc";
|
makeSelectResolvedStatuses(),
|
||||||
textColor = "#9e7700";
|
],
|
||||||
break;
|
(
|
||||||
case "inprogress":
|
visibleColumns,
|
||||||
bgColor = "#cce5ff";
|
localRows,
|
||||||
textColor = "#004085";
|
handleStatusChange,
|
||||||
break;
|
resolvedStatusOptions
|
||||||
case "error":
|
): GridColDef[] => {
|
||||||
bgColor = "#ffcdd2";
|
console.log("visibleColumns", visibleColumns);
|
||||||
textColor = "#c62828";
|
return visibleColumns.map(col => {
|
||||||
break;
|
// --------------------------------
|
||||||
}
|
// 1. STATUS COLUMN RENDERER
|
||||||
return (
|
// --------------------------------
|
||||||
|
if (col.field === "status") {
|
||||||
|
return {
|
||||||
|
...col,
|
||||||
|
renderCell: (params: GridRenderCellParams) => {
|
||||||
|
const value = params.value?.toLowerCase();
|
||||||
|
let bgColor = "#e0e0e0";
|
||||||
|
let textColor = "#000";
|
||||||
|
|
||||||
|
switch (value) {
|
||||||
|
case "completed":
|
||||||
|
bgColor = "#d0f0c0";
|
||||||
|
textColor = "#1b5e20";
|
||||||
|
break;
|
||||||
|
case "pending":
|
||||||
|
bgColor = "#fff4cc";
|
||||||
|
textColor = "#9e7700";
|
||||||
|
break;
|
||||||
|
case "inprogress":
|
||||||
|
bgColor = "#cce5ff";
|
||||||
|
textColor = "#004085";
|
||||||
|
break;
|
||||||
|
case "error":
|
||||||
|
bgColor = "#ffcdd2";
|
||||||
|
textColor = "#c62828";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
backgroundColor: bgColor,
|
||||||
|
color: textColor,
|
||||||
|
px: 1.5,
|
||||||
|
py: 0.5,
|
||||||
|
borderRadius: 1,
|
||||||
|
fontWeight: 500,
|
||||||
|
textTransform: "capitalize",
|
||||||
|
display: "inline-block",
|
||||||
|
width: "100%",
|
||||||
|
textAlign: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{params.value}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------------
|
||||||
|
// 2. USER ID COLUMN
|
||||||
|
// --------------------------------
|
||||||
|
if (col.field === "userId") {
|
||||||
|
return {
|
||||||
|
...col,
|
||||||
|
headerAlign: "center",
|
||||||
|
align: "center",
|
||||||
|
renderCell: (params: GridRenderCellParams) => (
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
backgroundColor: bgColor,
|
display: "grid",
|
||||||
color: textColor,
|
gridTemplateColumns: "1fr auto",
|
||||||
px: 1.5,
|
alignItems: "center",
|
||||||
py: 0.5,
|
|
||||||
borderRadius: 1,
|
|
||||||
fontWeight: 500,
|
|
||||||
textTransform: "capitalize",
|
|
||||||
display: "inline-block",
|
|
||||||
width: "100%",
|
width: "100%",
|
||||||
textAlign: "center",
|
px: 1,
|
||||||
}}
|
|
||||||
>
|
|
||||||
{params.value}
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (col.field === "userId") {
|
|
||||||
return {
|
|
||||||
...col,
|
|
||||||
headerAlign: "center",
|
|
||||||
align: "center",
|
|
||||||
renderCell: (params: GridRenderCellParams) => (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "grid",
|
|
||||||
gridTemplateColumns: "1fr auto",
|
|
||||||
alignItems: "center",
|
|
||||||
width: "100%",
|
|
||||||
px: 1,
|
|
||||||
}}
|
|
||||||
onClick={e => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
fontWeight: 500,
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
color: "text.primary",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{params.value}
|
|
||||||
</Box>
|
|
||||||
<IconButton
|
|
||||||
href={`/users/${params.value}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
size="small"
|
|
||||||
sx={{ p: 0.5, ml: 1 }}
|
|
||||||
onClick={e => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<OpenInNewIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (col.field === "actions") {
|
|
||||||
return {
|
|
||||||
...col,
|
|
||||||
renderCell: (params: GridRenderCellParams) => {
|
|
||||||
const currentRow = localRows.find(row => row.id === params.id);
|
|
||||||
const options =
|
|
||||||
currentRow?.options?.map(option => option.value) ??
|
|
||||||
resolvedStatusOptions;
|
|
||||||
const uniqueOptions: string[] = Array.from(new Set(options));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Select<string>
|
|
||||||
value={currentRow?.status ?? ""}
|
|
||||||
onChange={e =>
|
|
||||||
handleStatusChange(
|
|
||||||
params.id as number,
|
|
||||||
e.target.value as string
|
|
||||||
)
|
|
||||||
}
|
|
||||||
size="small"
|
|
||||||
fullWidth
|
|
||||||
displayEmpty
|
|
||||||
sx={{
|
|
||||||
"& .MuiOutlinedInput-notchedOutline": { border: "none" },
|
|
||||||
"& .MuiSelect-select": { py: 0.5 },
|
|
||||||
}}
|
}}
|
||||||
onClick={e => e.stopPropagation()}
|
onClick={e => e.stopPropagation()}
|
||||||
>
|
>
|
||||||
{uniqueOptions.map(option => (
|
<Box
|
||||||
<MenuItem key={option} value={option}>
|
sx={{
|
||||||
{option}
|
fontWeight: 500,
|
||||||
</MenuItem>
|
fontSize: "0.875rem",
|
||||||
))}
|
color: "text.primary",
|
||||||
</Select>
|
}}
|
||||||
);
|
>
|
||||||
},
|
{params.value}
|
||||||
};
|
</Box>
|
||||||
}
|
<IconButton
|
||||||
|
href={`/users/${params.value}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
size="small"
|
||||||
|
sx={{ p: 0.5, ml: 1 }}
|
||||||
|
onClick={e => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<OpenInNewIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
return col;
|
// --------------------------------
|
||||||
}) as GridColDef[];
|
// 3. ACTIONS COLUMN
|
||||||
}
|
// --------------------------------
|
||||||
);
|
if (col.field === "actions") {
|
||||||
|
return {
|
||||||
|
...col,
|
||||||
|
renderCell: (params: GridRenderCellParams) => {
|
||||||
|
const currentRow = localRows.find(row => row.id === params.id);
|
||||||
|
|
||||||
|
const options =
|
||||||
|
currentRow?.options?.map(option => option.value) ??
|
||||||
|
resolvedStatusOptions;
|
||||||
|
|
||||||
|
const uniqueOptions = Array.from(new Set(options));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Select<string>
|
||||||
|
value={currentRow?.status ?? ""}
|
||||||
|
onChange={e =>
|
||||||
|
handleStatusChange(
|
||||||
|
params.id as number,
|
||||||
|
e.target.value as string
|
||||||
|
)
|
||||||
|
}
|
||||||
|
size="small"
|
||||||
|
fullWidth
|
||||||
|
displayEmpty
|
||||||
|
sx={{
|
||||||
|
"& .MuiOutlinedInput-notchedOutline": { border: "none" },
|
||||||
|
"& .MuiSelect-select": { py: 0.5 },
|
||||||
|
}}
|
||||||
|
onClick={e => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{uniqueOptions.map(option => (
|
||||||
|
<MenuItem key={option} value={option}>
|
||||||
|
{option}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return col;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|||||||
@ -17,3 +17,21 @@ export interface DataRowBase {
|
|||||||
status?: string;
|
status?: string;
|
||||||
options?: { value: string; label: string }[];
|
options?: { value: string; label: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ITransactions {
|
||||||
|
id: string;
|
||||||
|
psp_id: string;
|
||||||
|
method_id: string;
|
||||||
|
merchant_id: string;
|
||||||
|
external_id?: string; // optional: may not always be present
|
||||||
|
customer?: string; // keep as string unless you provide structure
|
||||||
|
type?: string;
|
||||||
|
currency?: string;
|
||||||
|
amount: number | string; // sometimes APIs return strings for money
|
||||||
|
status?: string;
|
||||||
|
notes?: string;
|
||||||
|
creator?: string;
|
||||||
|
created: string; // ISO datetime string from API
|
||||||
|
modifier?: string;
|
||||||
|
modified?: string; // ISO datetime string or undefined
|
||||||
|
}
|
||||||
|
|||||||
@ -31,6 +31,8 @@ const SettingsAccountSecurity: React.FC = () => {
|
|||||||
currentPassword: passwordData.currentPassword,
|
currentPassword: passwordData.currentPassword,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
// Error handling is now done by the epic
|
// Error handling is now done by the epic
|
||||||
console.error("Password change error:", err);
|
console.error("Password change error:", err);
|
||||||
|
|||||||
@ -20,11 +20,9 @@ const SettingsPageClient: React.FC = () => {
|
|||||||
<Box sx={{ display: "flex", gap: 3 }}>
|
<Box sx={{ display: "flex", gap: 3 }}>
|
||||||
<SettingsSidebar
|
<SettingsSidebar
|
||||||
active={activeSection}
|
active={activeSection}
|
||||||
onChange={(
|
onChange={(section: "personal" | "account") =>
|
||||||
section:
|
setActiveSection(section)
|
||||||
| string
|
}
|
||||||
| ((prevState: "personal" | "account") => "personal" | "account")
|
|
||||||
) => setActiveSection(section)}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Box sx={{ flex: 1 }}>
|
<Box sx={{ flex: 1 }}>
|
||||||
|
|||||||
@ -15,6 +15,7 @@ import { updateUserDetails } from "@/app/redux/user/userSlice";
|
|||||||
|
|
||||||
const SettingsPersonalInfo: React.FC = () => {
|
const SettingsPersonalInfo: React.FC = () => {
|
||||||
const user = useSelector((state: RootState) => state.auth.user);
|
const user = useSelector((state: RootState) => state.auth.user);
|
||||||
|
console.log("[SettingsPersonalInfo] user", user);
|
||||||
const dispatch = useDispatch<AppDispatch>();
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
|
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
@ -28,8 +29,8 @@ const SettingsPersonalInfo: React.FC = () => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user) {
|
if (user) {
|
||||||
setFormData({
|
setFormData({
|
||||||
first_name: user.firstName ?? "",
|
first_name: user.first_name ?? "",
|
||||||
last_name: user.lastName ?? "",
|
last_name: user.last_name ?? "",
|
||||||
username: user.username ?? "",
|
username: user.username ?? "",
|
||||||
email: user.email ?? "",
|
email: user.email ?? "",
|
||||||
});
|
});
|
||||||
@ -66,17 +67,20 @@ const SettingsPersonalInfo: React.FC = () => {
|
|||||||
<TextField
|
<TextField
|
||||||
label="First Name"
|
label="First Name"
|
||||||
value={formData.first_name}
|
value={formData.first_name}
|
||||||
|
disabled={true}
|
||||||
onChange={handleChange("first_name")}
|
onChange={handleChange("first_name")}
|
||||||
fullWidth
|
fullWidth
|
||||||
/>
|
/>
|
||||||
<TextField
|
<TextField
|
||||||
label="Last Name"
|
label="Last Name"
|
||||||
value={formData.last_name}
|
value={formData.last_name}
|
||||||
|
disabled={true}
|
||||||
onChange={handleChange("last_name")}
|
onChange={handleChange("last_name")}
|
||||||
fullWidth
|
fullWidth
|
||||||
/>
|
/>
|
||||||
<TextField
|
<TextField
|
||||||
label="Username"
|
label="Username"
|
||||||
|
disabled={true}
|
||||||
value={formData.username}
|
value={formData.username}
|
||||||
onChange={handleChange("username")}
|
onChange={handleChange("username")}
|
||||||
fullWidth
|
fullWidth
|
||||||
|
|||||||
@ -1,18 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useState } from "react";
|
import React, { useState } from "react";
|
||||||
import { useDispatch, useSelector } from "react-redux";
|
|
||||||
import { AppDispatch } from "@/app/redux/store";
|
|
||||||
import "./AddUser.scss";
|
|
||||||
import { addUser } from "@/app/redux/auth/authSlice";
|
|
||||||
import { IEditUserForm } from "../User.interfaces";
|
|
||||||
import { COUNTRY_CODES } from "../constants";
|
|
||||||
import { formatPhoneDisplay, validatePhone } from "../utils";
|
|
||||||
import Spinner from "../../../components/Spinner/Spinner";
|
|
||||||
import { RootState } from "@/app/redux/store";
|
import { RootState } from "@/app/redux/store";
|
||||||
import toast from "react-hot-toast";
|
import toast from "react-hot-toast";
|
||||||
|
import { useDispatch, useSelector } from "react-redux";
|
||||||
|
import { AppDispatch } from "@/app/redux/store";
|
||||||
|
import { addUser } from "@/app/redux/auth/authSlice";
|
||||||
|
import { IEditUserForm } from "../User.interfaces";
|
||||||
|
import { formatPhoneDisplay, validatePhone } from "../utils";
|
||||||
|
import Spinner from "../../../components/Spinner/Spinner";
|
||||||
import Modal from "@/app/components/Modal/Modal";
|
import Modal from "@/app/components/Modal/Modal";
|
||||||
import { selectAppMetadata } from "@/app/redux/metadata/selectors";
|
import {
|
||||||
|
selectAppMetadata,
|
||||||
|
selectPhoneNumberCountries,
|
||||||
|
} from "@/app/redux/metadata/selectors";
|
||||||
|
import "./AddUser.scss";
|
||||||
|
|
||||||
interface AddUserProps {
|
interface AddUserProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@ -42,6 +44,8 @@ const AddUser: React.FC<AddUserProps> = ({ open, onClose }) => {
|
|||||||
|
|
||||||
const loading = status === "loading";
|
const loading = status === "loading";
|
||||||
|
|
||||||
|
const COUNTRY_CODES = useSelector(selectPhoneNumberCountries);
|
||||||
|
|
||||||
const handleChange = (
|
const handleChange = (
|
||||||
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
|
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
|
||||||
) => {
|
) => {
|
||||||
@ -115,7 +119,6 @@ const AddUser: React.FC<AddUserProps> = ({ open, onClose }) => {
|
|||||||
|
|
||||||
if (result && resultAction.payload.success) {
|
if (result && resultAction.payload.success) {
|
||||||
toast.success(resultAction.payload.message);
|
toast.success(resultAction.payload.message);
|
||||||
// router.refresh();
|
|
||||||
onClose();
|
onClose();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@ -255,9 +258,12 @@ const AddUser: React.FC<AddUserProps> = ({ open, onClose }) => {
|
|||||||
onChange={handleCountryCodeChange}
|
onChange={handleCountryCodeChange}
|
||||||
className="country-code-select"
|
className="country-code-select"
|
||||||
>
|
>
|
||||||
{COUNTRY_CODES.map(country => (
|
{COUNTRY_CODES.map((country, i) => (
|
||||||
<option key={country.code} value={country.code}>
|
<option
|
||||||
{country.flag} {country.code} {country.country}
|
key={`${country.code}-${country.name} ${i}`}
|
||||||
|
value={country.code}
|
||||||
|
>
|
||||||
|
{country.flag} {country.code} {country.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
|
|||||||
@ -47,6 +47,7 @@ const DeleteUser: React.FC<DeleteUserProps> = ({ open, onClose, user }) => {
|
|||||||
(resultAction.payload as string) || "Failed to delete user"
|
(resultAction.payload as string) || "Failed to delete user"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
toast.error(error.message || "An unexpected error occurred");
|
toast.error(error.message || "An unexpected error occurred");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,8 +5,6 @@ import AccountMenu from "./accountMenu/AccountMenu";
|
|||||||
import "./Header.scss";
|
import "./Header.scss";
|
||||||
|
|
||||||
const Header = () => {
|
const Header = () => {
|
||||||
const handleChange = () => {};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppBar
|
<AppBar
|
||||||
className="header"
|
className="header"
|
||||||
@ -17,7 +15,7 @@ const Header = () => {
|
|||||||
>
|
>
|
||||||
<Toolbar className="header__toolbar">
|
<Toolbar className="header__toolbar">
|
||||||
<div className="header__left-group">
|
<div className="header__left-group">
|
||||||
<Dropdown onChange={handleChange} />
|
<Dropdown />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="header__right-group">
|
<div className="header__right-group">
|
||||||
|
|||||||
@ -1,57 +1,137 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import {
|
import {
|
||||||
FormControl,
|
Button,
|
||||||
InputLabel,
|
Menu,
|
||||||
Select,
|
|
||||||
MenuItem,
|
MenuItem,
|
||||||
SelectChangeEvent,
|
ListItemText,
|
||||||
|
ListItemIcon,
|
||||||
|
Divider,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import PageLinks from "../../../../components/PageLinks/PageLinks";
|
|
||||||
import { useSelector } from "react-redux";
|
import { useSelector } from "react-redux";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import KeyboardArrowRightIcon from "@mui/icons-material/KeyboardArrowRight";
|
||||||
|
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||||
import { selectNavigationSidebar } from "@/app/redux/metadata/selectors";
|
import { selectNavigationSidebar } from "@/app/redux/metadata/selectors";
|
||||||
|
import { SidebarLink } from "@/app/redux/metadata/metadataSlice";
|
||||||
|
import { resolveIcon } from "@/app/utils/iconMap";
|
||||||
import "./DropDown.scss";
|
import "./DropDown.scss";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onChange?: (event: SelectChangeEvent<string>) => void;
|
onChange?: (path: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function SidebarDropdown({ onChange }: Props) {
|
export default function SidebarDropdown({ onChange }: Props) {
|
||||||
const [value, setValue] = React.useState("");
|
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||||
const sidebar = useSelector(selectNavigationSidebar)?.links;
|
const [openMenus, setOpenMenus] = React.useState<Record<string, boolean>>({});
|
||||||
const handleChange = (event: SelectChangeEvent<string>) => {
|
const sidebar = useSelector(selectNavigationSidebar);
|
||||||
setValue(event.target.value);
|
const router = useRouter();
|
||||||
onChange?.(event);
|
const open = Boolean(anchorEl);
|
||||||
|
|
||||||
|
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
|
||||||
|
setAnchorEl(event.currentTarget);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
setAnchorEl(null);
|
||||||
|
setOpenMenus({});
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleMenu = (title: string) => {
|
||||||
|
setOpenMenus(prev => ({ ...prev, [title]: !prev[title] }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNavigation = (path: string) => {
|
||||||
|
router.push(path);
|
||||||
|
onChange?.(path);
|
||||||
|
handleClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderMenuItem = (
|
||||||
|
link: SidebarLink,
|
||||||
|
level: number = 0
|
||||||
|
): React.ReactNode => {
|
||||||
|
const Icon = link.icon ? resolveIcon(link.icon as string) : undefined;
|
||||||
|
const hasChildren = link.children && link.children.length > 0;
|
||||||
|
const isOpen = openMenus[link.title];
|
||||||
|
const indent = level * 24;
|
||||||
|
|
||||||
|
if (hasChildren) {
|
||||||
|
return (
|
||||||
|
<React.Fragment key={link.title || link.path}>
|
||||||
|
<MenuItem
|
||||||
|
onClick={() => toggleMenu(link.title)}
|
||||||
|
sx={{
|
||||||
|
pl: `${8 + indent}px`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{Icon && (
|
||||||
|
<ListItemIcon sx={{ minWidth: 36 }}>
|
||||||
|
<Icon fontSize="small" />
|
||||||
|
</ListItemIcon>
|
||||||
|
)}
|
||||||
|
<ListItemText primary={link.title} />
|
||||||
|
{isOpen ? (
|
||||||
|
<KeyboardArrowDownIcon fontSize="small" />
|
||||||
|
) : (
|
||||||
|
<KeyboardArrowRightIcon fontSize="small" />
|
||||||
|
)}
|
||||||
|
</MenuItem>
|
||||||
|
{isOpen &&
|
||||||
|
link.children?.map(child => renderMenuItem(child, level + 1))}
|
||||||
|
</React.Fragment>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MenuItem
|
||||||
|
key={link.path}
|
||||||
|
onClick={() => handleNavigation(link.path)}
|
||||||
|
sx={{
|
||||||
|
pl: `${8 + indent}px`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{Icon && (
|
||||||
|
<ListItemIcon sx={{ minWidth: 36 }}>
|
||||||
|
<Icon fontSize="small" />
|
||||||
|
</ListItemIcon>
|
||||||
|
)}
|
||||||
|
<ListItemText primary={link.title} />
|
||||||
|
</MenuItem>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FormControl fullWidth variant="outlined" sx={{ minWidth: 200 }}>
|
<div>
|
||||||
<InputLabel id="sidebar-dropdown-label">Navigate To</InputLabel>
|
<Button
|
||||||
<Select
|
variant="outlined"
|
||||||
labelId="sidebar-dropdown-label"
|
onClick={handleClick}
|
||||||
value={value}
|
sx={{ minWidth: 200, justifyContent: "space-between" }}
|
||||||
onChange={handleChange}
|
>
|
||||||
label="Navigate To"
|
Navigate To
|
||||||
MenuProps={{
|
{open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
|
||||||
PaperProps: {
|
</Button>
|
||||||
style: {
|
<Menu
|
||||||
maxHeight: 200,
|
anchorEl={anchorEl}
|
||||||
},
|
open={open}
|
||||||
|
onClose={handleClose}
|
||||||
|
MenuListProps={{
|
||||||
|
"aria-labelledby": "sidebar-dropdown-button",
|
||||||
|
}}
|
||||||
|
PaperProps={{
|
||||||
|
style: {
|
||||||
|
maxHeight: 400,
|
||||||
|
width: "250px",
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<em className="em">Select a page</em>
|
<MenuItem disabled>
|
||||||
<MenuItem value="" disabled></MenuItem>
|
<ListItemText primary="Select a page" />
|
||||||
|
</MenuItem>
|
||||||
|
<Divider />
|
||||||
<div className="sidebar-dropdown__container">
|
<div className="sidebar-dropdown__container">
|
||||||
{sidebar?.map((link: SidebarItem) => (
|
{sidebar?.map(link => renderMenuItem(link))}
|
||||||
<PageLinks
|
|
||||||
key={link.path}
|
|
||||||
title={link.title}
|
|
||||||
path={link.path}
|
|
||||||
icon={link.icon as string}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
</Select>
|
</Menu>
|
||||||
</FormControl>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,7 +10,7 @@ export const MainContent = ({ children }: MainContentProps) => {
|
|||||||
const isSidebarOpen = useSelector((state: RootState) => state.ui.sidebarOpen);
|
const isSidebarOpen = useSelector((state: RootState) => state.ui.sidebarOpen);
|
||||||
|
|
||||||
const style: React.CSSProperties = {
|
const style: React.CSSProperties = {
|
||||||
marginLeft: isSidebarOpen ? "240px" : "30px",
|
marginLeft: isSidebarOpen ? "230px" : "30px",
|
||||||
padding: "24px",
|
padding: "24px",
|
||||||
minHeight: "100vh",
|
minHeight: "100vh",
|
||||||
width: isSidebarOpen ? "calc(100% - 240px)" : "calc(100% - 30px)",
|
width: isSidebarOpen ? "calc(100% - 240px)" : "calc(100% - 30px)",
|
||||||
|
|||||||
@ -2,14 +2,14 @@
|
|||||||
|
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useDispatch } from "react-redux";
|
import { useDispatch } from "react-redux";
|
||||||
import { initializeAuth } from "./auth/authSlice";
|
import { validateAuth } from "./auth/authSlice";
|
||||||
import { AppDispatch } from "./types";
|
import { AppDispatch } from "./types";
|
||||||
|
|
||||||
export function InitializeAuth() {
|
export function InitializeAuth() {
|
||||||
const dispatch = useDispatch<AppDispatch>();
|
const dispatch = useDispatch<AppDispatch>();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dispatch(initializeAuth());
|
dispatch(validateAuth());
|
||||||
}, [dispatch]);
|
}, [dispatch]);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
import React, { useEffect, useRef } from "react";
|
import React, { useEffect, useRef } from "react";
|
||||||
import { Provider } from "react-redux";
|
import { Provider } from "react-redux";
|
||||||
import { store } from "./store";
|
import { store } from "./store";
|
||||||
import { checkAuthStatus } from "./auth/authSlice";
|
import { validateAuth } from "./auth/authSlice";
|
||||||
|
|
||||||
export default function ReduxProvider({
|
export default function ReduxProvider({
|
||||||
children,
|
children,
|
||||||
@ -16,17 +16,17 @@ export default function ReduxProvider({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Check authentication status when the ReduxProvider component mounts on the client.
|
// Check authentication status when the ReduxProvider component mounts on the client.
|
||||||
// This ensures your Redux auth state is synced with the server-side token.
|
// This ensures your Redux auth state is synced with the server-side token.
|
||||||
store.dispatch(checkAuthStatus());
|
store.dispatch(validateAuth());
|
||||||
|
|
||||||
// Do an additional check after 2 seconds to ensure we have the latest token info
|
// Do an additional check after 2 seconds to ensure we have the latest token info
|
||||||
initialCheckRef.current = setTimeout(() => {
|
initialCheckRef.current = setTimeout(() => {
|
||||||
store.dispatch(checkAuthStatus());
|
store.dispatch(validateAuth());
|
||||||
}, 2000);
|
}, 2000);
|
||||||
|
|
||||||
// Set up periodic token validation every 5 minutes
|
// Set up periodic token validation every 5 minutes
|
||||||
intervalRef.current = setInterval(
|
intervalRef.current = setInterval(
|
||||||
() => {
|
() => {
|
||||||
store.dispatch(checkAuthStatus());
|
store.dispatch(validateAuth());
|
||||||
},
|
},
|
||||||
5 * 60 * 1000
|
5 * 60 * 1000
|
||||||
); // 5 minutes
|
); // 5 minutes
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
|
import { createSelector } from "@reduxjs/toolkit";
|
||||||
import { RootState } from "../store";
|
import { RootState } from "../store";
|
||||||
import {
|
import {
|
||||||
AdvancedSearchFilters,
|
AdvancedSearchFilters,
|
||||||
@ -11,6 +12,14 @@ export const selectFilters = (state: RootState): AdvancedSearchFilters =>
|
|||||||
export const selectPagination = (state: RootState) =>
|
export const selectPagination = (state: RootState) =>
|
||||||
state.advancedSearch.pagination;
|
state.advancedSearch.pagination;
|
||||||
|
|
||||||
|
export const selectPaginationModel = createSelector(
|
||||||
|
[selectPagination],
|
||||||
|
pagination => ({
|
||||||
|
page: Math.max(0, (pagination.page ?? 1) - 1),
|
||||||
|
pageSize: pagination.limit ?? 10,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
export const selectSort = (state: RootState) => state.advancedSearch.sort;
|
export const selectSort = (state: RootState) => state.advancedSearch.sort;
|
||||||
|
|
||||||
export const selectFilterValue = (
|
export const selectFilterValue = (
|
||||||
|
|||||||
240
app/redux/metadata/constants.ts
Normal file
240
app/redux/metadata/constants.ts
Normal file
@ -0,0 +1,240 @@
|
|||||||
|
// Country codes for phone prefixes
|
||||||
|
export const COUNTRY_CODES = [
|
||||||
|
{ code: "+233", flag: "🇬🇭", country: "Ghana" },
|
||||||
|
{ code: "+672", flag: "🇳🇫", country: "Norfolk Island" },
|
||||||
|
{ code: "+226", flag: "🇧🇫", country: "Burkina Faso" },
|
||||||
|
{ code: "+591", flag: "🇧🇴", country: "Bolivia" },
|
||||||
|
{ code: "+33", flag: "🇫🇷", country: "France" },
|
||||||
|
{ code: "+1-876", flag: "🇯🇲", country: "Jamaica" },
|
||||||
|
{ code: "+249", flag: "🇸🇩", country: "Sudan" },
|
||||||
|
{
|
||||||
|
code: "+243",
|
||||||
|
flag: "🇨🇩",
|
||||||
|
country: "Congo, Democratic Republic Of (Was Zaire)",
|
||||||
|
},
|
||||||
|
{ code: "+679", flag: "🇫🇯", country: "Fiji" },
|
||||||
|
{ code: "+44", flag: "🇮🇲", country: "Isle Of Man" },
|
||||||
|
{ code: "+382", flag: "🇲🇪", country: "Montenegro" },
|
||||||
|
{ code: "+353", flag: "🇮🇪", country: "Ireland" },
|
||||||
|
{ code: "+237", flag: "🇨🇲", country: "Cameroon" },
|
||||||
|
{ code: "+592", flag: "🇬🇾", country: "Guyana" },
|
||||||
|
{ code: "+234", flag: "🇳🇬", country: "Nigeria" },
|
||||||
|
{ code: "+1-868", flag: "🇹🇹", country: "Trinidad And Tobago" },
|
||||||
|
{ code: "+45", flag: "🇩🇰", country: "Denmark" },
|
||||||
|
{ code: "+852", flag: "🇭🇰", country: "Hong Kong" },
|
||||||
|
{ code: "+223", flag: "🇲🇱", country: "Mali" },
|
||||||
|
{ code: "+239", flag: "🇸🇹", country: "Sao Tome And Principe" },
|
||||||
|
{ code: "+690", flag: "🇹🇰", country: "Tokelau" },
|
||||||
|
{ code: "+590", flag: "🇬🇵", country: "Guadeloupe" },
|
||||||
|
{ code: "+66", flag: "🇹🇭", country: "Thailand" },
|
||||||
|
{ code: "+504", flag: "🇭🇳", country: "Honduras" },
|
||||||
|
{ code: "+27", flag: "🇿🇦", country: "South Africa" },
|
||||||
|
{ code: "+358", flag: "🇫🇮", country: "Finland" },
|
||||||
|
{ code: "+1-264", flag: "🇦🇮", country: "Anguilla" },
|
||||||
|
{ code: "+262", flag: "🇷🇪", country: "Reunion" },
|
||||||
|
{ code: "+992", flag: "🇹🇯", country: "Tajikistan" },
|
||||||
|
{ code: "+971", flag: "🇦🇪", country: "United Arab Emirates" },
|
||||||
|
{ code: "+212", flag: "🇪🇭", country: "Western Sahara" },
|
||||||
|
{ code: "+692", flag: "🇲🇭", country: "Marshall Islands" },
|
||||||
|
{ code: "+674", flag: "🇳🇷", country: "Nauru" },
|
||||||
|
{ code: "+229", flag: "🇧🇯", country: "Benin" },
|
||||||
|
{ code: "+55", flag: "🇧🇷", country: "Brazil" },
|
||||||
|
{ code: "+299", flag: "🇬🇱", country: "Greenland" },
|
||||||
|
{ code: "+61", flag: "🇭🇲", country: "Heard and Mc Donald Islands" },
|
||||||
|
{ code: "+98", flag: "🇮🇷", country: "Iran (Islamic Republic Of)" },
|
||||||
|
{ code: "+231", flag: "🇱🇷", country: "Liberia" },
|
||||||
|
{ code: "+370", flag: "🇱🇹", country: "Lithuania" },
|
||||||
|
{ code: "+377", flag: "🇲🇨", country: "Monaco" },
|
||||||
|
{ code: "+222", flag: "🇲🇷", country: "Mauritania" },
|
||||||
|
{ code: "+57", flag: "🇨🇴", country: "Colombia" },
|
||||||
|
{ code: "+216", flag: "🇹🇳", country: "Tunisia" },
|
||||||
|
{ code: "+1-345", flag: "🇰🇾", country: "Cayman Islands" },
|
||||||
|
{ code: "+62", flag: "🇮🇩", country: "Indonesia" },
|
||||||
|
{ code: "+378", flag: "🇸🇲", country: "San Marino" },
|
||||||
|
{ code: "+1", flag: "🇺🇸", country: "United States" },
|
||||||
|
{ code: "+383", flag: "🇽🇰", country: "Kosovo" },
|
||||||
|
{ code: "+376", flag: "🇦🇩", country: "Andorra" },
|
||||||
|
{ code: "+1-246", flag: "🇧🇧", country: "Barbados" },
|
||||||
|
{ code: "+963", flag: "🇸🇾", country: "Syrian Arab Republic" },
|
||||||
|
{ code: "+359", flag: "🇧🇬", country: "Bulgaria" },
|
||||||
|
{ code: "+213", flag: "🇩🇿", country: "Algeria" },
|
||||||
|
{ code: "+593", flag: "🇪🇨", country: "Ecuador" },
|
||||||
|
{ code: "+240", flag: "🇬🇶", country: "Equatorial Guinea" },
|
||||||
|
{ code: "+44", flag: "🇯🇪", country: "Jersey" },
|
||||||
|
{ code: "+254", flag: "🇰🇪", country: "Kenya" },
|
||||||
|
{ code: "+64", flag: "🇳🇿", country: "New Zealand" },
|
||||||
|
{ code: "+250", flag: "🇷🇼", country: "Rwanda" },
|
||||||
|
{ code: "+291", flag: "🇪🇷", country: "Eritrea" },
|
||||||
|
{ code: "+47", flag: "🇳🇴", country: "Norway" },
|
||||||
|
{ code: "+51", flag: "🇵🇪", country: "Peru" },
|
||||||
|
{ code: "+290", flag: "🇸🇭", country: "Saint Helena" },
|
||||||
|
{ code: "+508", flag: "🇵🇲", country: "Saint Pierre And Miquelon" },
|
||||||
|
{ code: "+260", flag: "🇿🇲", country: "Zambia" },
|
||||||
|
{ code: "+354", flag: "🇮🇸", country: "Iceland" },
|
||||||
|
{ code: "+39", flag: "🇮🇹", country: "Italy" },
|
||||||
|
{ code: "+977", flag: "🇳🇵", country: "Nepal" },
|
||||||
|
{ code: "+386", flag: "🇸🇮", country: "Slovenia" },
|
||||||
|
{ code: "+218", flag: "🇱🇾", country: "Libyan Arab Jamahiriya" },
|
||||||
|
{ code: "+505", flag: "🇳🇮", country: "Nicaragua" },
|
||||||
|
{ code: "+248", flag: "🇸🇨", country: "Seychelles" },
|
||||||
|
{ code: "+594", flag: "🇬🇫", country: "French Guiana" },
|
||||||
|
{ code: "+972", flag: "🇮🇱", country: "Israel" },
|
||||||
|
{ code: "+1-670", flag: "🇲🇵", country: "Northern Mariana Islands" },
|
||||||
|
{ code: "+1-64", flag: "🇵🇳", country: "Pitcairn" },
|
||||||
|
{ code: "+351", flag: "🇵🇹", country: "Portugal" },
|
||||||
|
{ code: "+503", flag: "🇸🇻", country: "El Salvador" },
|
||||||
|
{ code: "+44", flag: "🇬🇧", country: "United Kingdom" },
|
||||||
|
{ code: "+689", flag: "🇵🇫", country: "French Polynesia" },
|
||||||
|
{ code: "+1-721", flag: "🇸🇽", country: "Sint Maarten" },
|
||||||
|
{ code: "+380", flag: "🇺🇦", country: "Ukraine" },
|
||||||
|
{ code: "+599", flag: "🇧🇶", country: "Bonaire, Saint Eustatius and Saba" },
|
||||||
|
{ code: "+500", flag: "🇫🇰", country: "Falkland Islands (Malvinas)" },
|
||||||
|
{ code: "+995", flag: "🇬🇪", country: "Georgia" },
|
||||||
|
{ code: "+1-671", flag: "🇬🇺", country: "Guam" },
|
||||||
|
{ code: "+82", flag: "🇰🇷", country: "Korea, Republic Of" },
|
||||||
|
{ code: "+507", flag: "🇵🇦", country: "Panama" },
|
||||||
|
{ code: "+1", flag: "🇺🇸", country: "United States Minor Outlying Islands" },
|
||||||
|
{ code: "+964", flag: "🇮🇶", country: "Iraq" },
|
||||||
|
{ code: "+965", flag: "🇰🇼", country: "Kuwait" },
|
||||||
|
{ code: "+39", flag: "🇻🇦", country: "Vatican City State (Holy See)" },
|
||||||
|
{ code: "+385", flag: "🇭🇷", country: "Croatia (Local Name: Hrvatska)" },
|
||||||
|
{ code: "+92", flag: "🇵🇰", country: "Pakistan" },
|
||||||
|
{ code: "+967", flag: "🇾🇪", country: "Yemen" },
|
||||||
|
{ code: "+267", flag: "🇧🇼", country: "Botswana" },
|
||||||
|
{ code: "+970", flag: "🇵🇸", country: "Palestinian Territory, Occupied" },
|
||||||
|
{ code: "+90", flag: "🇹🇷", country: "Turkey" },
|
||||||
|
{ code: "+1-473", flag: "🇬🇩", country: "Grenada" },
|
||||||
|
{ code: "+356", flag: "🇲🇹", country: "Malta" },
|
||||||
|
{
|
||||||
|
code: "+995",
|
||||||
|
flag: "🇬🇪",
|
||||||
|
country: "South Georgia And The South Sandwich Islands",
|
||||||
|
},
|
||||||
|
{ code: "+236", flag: "🇨🇫", country: "Central African Republic" },
|
||||||
|
{ code: "+371", flag: "🇱🇻", country: "Latvia" },
|
||||||
|
{
|
||||||
|
code: "+850",
|
||||||
|
flag: "🇰🇵",
|
||||||
|
country: "Korea, Democratic People's Republic Of",
|
||||||
|
},
|
||||||
|
{ code: "+1-649", flag: "🇹🇨", country: "Turks And Caicos Islands" },
|
||||||
|
{ code: "+599", flag: "🇨🇼", country: "Curacao" },
|
||||||
|
{ code: "+245", flag: "🇬🇼", country: "Guinea-Bissau" },
|
||||||
|
{ code: "+94", flag: "🇱🇰", country: "Sri Lanka" },
|
||||||
|
{ code: "+596", flag: "🇲🇶", country: "Martinique" },
|
||||||
|
{ code: "+262", flag: "🇾🇹", country: "Mayotte" },
|
||||||
|
{ code: "+688", flag: "🇹🇻", country: "Tuvalu" },
|
||||||
|
{ code: "+49", flag: "🇩🇪", country: "Germany" },
|
||||||
|
{ code: "+65", flag: "🇸🇬", country: "Singapore" },
|
||||||
|
{ code: "+381", flag: "🇷🇸", country: "Serbia" },
|
||||||
|
{ code: "+975", flag: "🇧🇹", country: "Bhutan" },
|
||||||
|
{ code: "+266", flag: "🇱🇸", country: "Lesotho" },
|
||||||
|
{ code: "+421", flag: "🇸🇰", country: "Slovakia" },
|
||||||
|
{ code: "+1-784", flag: "🇻🇨", country: "Saint Vincent And The Grenadines" },
|
||||||
|
{ code: "+673", flag: "🇧🇳", country: "Brunei Darussalam" },
|
||||||
|
{ code: "+509", flag: "🇭🇹", country: "Haiti" },
|
||||||
|
{
|
||||||
|
code: "+389",
|
||||||
|
flag: "🇲🇰",
|
||||||
|
country: "Macedonia, The Former Yugoslav Republic Of",
|
||||||
|
},
|
||||||
|
{ code: "+886", flag: "🇹🇼", country: "Taiwan" },
|
||||||
|
{ code: "+670", flag: "🇹🇱", country: "Cocos (Keeling) Islands" },
|
||||||
|
{ code: "+352", flag: "🇱🇺", country: "Luxembourg" },
|
||||||
|
{ code: "+880", flag: "🇧🇩", country: "Bangladesh" },
|
||||||
|
{ code: "+676", flag: "🇹🇴", country: "Tonga" },
|
||||||
|
{ code: "+681", flag: "🇼🇫", country: "Wallis And Futuna Islands" },
|
||||||
|
{ code: "+257", flag: "🇧🇮", country: "Burundi" },
|
||||||
|
{ code: "+502", flag: "🇬🇹", country: "Guatemala" },
|
||||||
|
{ code: "+855", flag: "🇰🇭", country: "Cambodia" },
|
||||||
|
{ code: "+235", flag: "🇹🇩", country: "Chad" },
|
||||||
|
{ code: "+216", flag: "🇹🇳", country: "Tunisia" },
|
||||||
|
{ code: "+1-242", flag: "🇧🇸", country: "Bahamas" },
|
||||||
|
{ code: "+350", flag: "🇬🇮", country: "Gibraltar" },
|
||||||
|
{ code: "+52", flag: "🇲🇽", country: "Mexico" },
|
||||||
|
{ code: "+856", flag: "🇱🇦", country: "Lao People's Democratic Republic" },
|
||||||
|
{ code: "+680", flag: "🇵🇼", country: "Palau" },
|
||||||
|
{ code: "+249", flag: "🇸🇩", country: "South Sudan" },
|
||||||
|
{ code: "+1-340", flag: "🇻🇮", country: "Virgin Islands (U.S.)" },
|
||||||
|
{ code: "+355", flag: "🇦🇱", country: "Albania" },
|
||||||
|
{ code: "+246", flag: "🇮🇴", country: "British Indian Ocean Territory" },
|
||||||
|
{ code: "+235", flag: "🇹🇩", country: "Chad" },
|
||||||
|
{ code: "+263", flag: "🇿🇼", country: "Zimbabwe" },
|
||||||
|
{ code: "+357", flag: "🇨🇾", country: "Cyprus" },
|
||||||
|
{ code: "+350", flag: "🇬🇮", country: "Gibraltar" },
|
||||||
|
{ code: "+256", flag: "🇺🇬", country: "Uganda" },
|
||||||
|
{ code: "+685", flag: "🇼🇸", country: "Samoa" },
|
||||||
|
{ code: "+1", flag: "🇺🇸", country: "Canada" },
|
||||||
|
{ code: "+506", flag: "🇨🇷", country: "Costa Rica" },
|
||||||
|
{ code: "+34", flag: "🇪🇸", country: "Spain" },
|
||||||
|
{ code: "+684", flag: "🇦🇸", country: "American Samoa" },
|
||||||
|
{ code: "+1-268", flag: "🇦🇬", country: "Antigua and Barbuda" },
|
||||||
|
{ code: "+86", flag: "🇨🇳", country: "China" },
|
||||||
|
{ code: "+48", flag: "🇵🇱", country: "Poland" },
|
||||||
|
{ code: "+974", flag: "🇶🇦", country: "Qatar" },
|
||||||
|
{ code: "+36", flag: "🇭🇺", country: "Hungary" },
|
||||||
|
{ code: "+996", flag: "🇰🇬", country: "Kyrgyzstan" },
|
||||||
|
{ code: "+258", flag: "🇲🇿", country: "Mozambique" },
|
||||||
|
{ code: "+675", flag: "🇵🇬", country: "Papua New Guinea" },
|
||||||
|
{ code: "+41", flag: "🇨🇭", country: "Switzerland" },
|
||||||
|
{ code: "+269", flag: "🇰🇲", country: "Comoros" },
|
||||||
|
{ code: "+230", flag: "🇲🇺", country: "Mauritius" },
|
||||||
|
{ code: "+60", flag: "🇲🇾", country: "Malaysia" },
|
||||||
|
{ code: "+228", flag: "🇹🇬", country: "Togo" },
|
||||||
|
{ code: "+994", flag: "🇦🇿", country: "Azerbaijan" },
|
||||||
|
{ code: "+501", flag: "🇧🇿", country: "Belize" },
|
||||||
|
{ code: "+682", flag: "🇨🇰", country: "Cook Islands" },
|
||||||
|
{ code: "+1-767", flag: "🇩🇲", country: "Dominica" },
|
||||||
|
{ code: "+372", flag: "🇪🇪", country: "Estonia" },
|
||||||
|
{ code: "+220", flag: "🇬🇲", country: "Gambia" },
|
||||||
|
{ code: "+423", flag: "🇱🇮", country: "Liechtenstein" },
|
||||||
|
{ code: "+683", flag: "🇳🇺", country: "Niue" },
|
||||||
|
{ code: "+244", flag: "🇦🇴", country: "Angola" },
|
||||||
|
{ code: "+241", flag: "🇬🇦", country: "Gabon" },
|
||||||
|
{ code: "+40", flag: "🇷🇴", country: "Romania" },
|
||||||
|
{ code: "+966", flag: "🇸🇦", country: "Saudi Arabia" },
|
||||||
|
{ code: "+221", flag: "🇸🇳", country: "Senegal" },
|
||||||
|
{ code: "+232", flag: "🇸🇱", country: "Sierra Leone" },
|
||||||
|
{ code: "+262", flag: "🇹🇫", country: "French Southern Territories" },
|
||||||
|
{ code: "+670", flag: "🇹🇱", country: "Timor-Leste" },
|
||||||
|
{ code: "+1-284", flag: "🇻🇬", country: "Virgin Islands (British)" },
|
||||||
|
{ code: "+297", flag: "🇦🇼", country: "Aruba" },
|
||||||
|
{ code: "+56", flag: "🇨🇱", country: "Chile" },
|
||||||
|
{ code: "+53", flag: "🇨🇺", country: "Cuba" },
|
||||||
|
{ code: "+595", flag: "🇵🇾", country: "Paraguay" },
|
||||||
|
{ code: "+43", flag: "🇦🇹", country: "Austria" },
|
||||||
|
{ code: "+590", flag: "🇧🇱", country: "Saint Barthélemy" },
|
||||||
|
{ code: "+238", flag: "🇨🇻", country: "Cape Verde" },
|
||||||
|
{ code: "+853", flag: "🇲🇴", country: "Macau" },
|
||||||
|
{ code: "+1-664", flag: "🇲🇸", country: "Montserrat" },
|
||||||
|
{ code: "+265", flag: "🇲🇼", country: "Malawi" },
|
||||||
|
{ code: "+678", flag: "🇻🇺", country: "Vanuatu" },
|
||||||
|
{ code: "+251", flag: "🇪🇹", country: "Ethiopia" },
|
||||||
|
{ code: "+298", flag: "🇫🇴", country: "Faroe Islands" },
|
||||||
|
{ code: "+224", flag: "🇬🇳", country: "Guinea" },
|
||||||
|
{ code: "+30", flag: "🇬🇷", country: "Greece" },
|
||||||
|
{ code: "+370", flag: "🇱🇹", country: "Aaland Islands" },
|
||||||
|
{ code: "+84", flag: "🇻🇳", country: "Viet Nam" },
|
||||||
|
{ code: "+960", flag: "🇲🇻", country: "Maldives" },
|
||||||
|
{ code: "+264", flag: "🇳🇦", country: "Namibia" },
|
||||||
|
{ code: "+31", flag: "🇳🇱", country: "Netherlands" },
|
||||||
|
{ code: "+1-340", flag: "🇻🇮", country: "Virgin Islands (U.S.)" },
|
||||||
|
{ code: "+374", flag: "🇦🇲", country: "Armenia" },
|
||||||
|
{ code: "+255", flag: "🇹🇿", country: "Tanzania, United Republic Of" },
|
||||||
|
{ code: "+373", flag: "🇲🇩", country: "Moldova, Republic Of" },
|
||||||
|
{ code: "+681", flag: "🇼🇫", country: "Wallis And Futuna Islands" },
|
||||||
|
{ code: "+46", flag: "🇸🇪", country: "Sweden" },
|
||||||
|
{ code: "+973", flag: "🇧🇭", country: "Bahrain" },
|
||||||
|
{ code: "+32", flag: "🇧🇪", country: "Belgium" },
|
||||||
|
{ code: "+61", flag: "🇦🇶", country: "Christmas Island" },
|
||||||
|
{ code: "+20", flag: "🇪🇬", country: "Egypt" },
|
||||||
|
{ code: "+420", flag: "🇨🇿", country: "Czech Republic" },
|
||||||
|
{ code: "+61", flag: "🇦🇺", country: "Australia" },
|
||||||
|
{ code: "+1-441", flag: "🇧🇸", country: "Bermuda" },
|
||||||
|
{ code: "+228", flag: "🇬🇲", country: "Guernsey" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export type CountryCodeEntry = (typeof COUNTRY_CODES)[number];
|
||||||
|
|
||||||
|
// Phone number validation regex
|
||||||
|
export const PHONE_REGEX = /^[\+]?[1-9][\d]{0,15}$/;
|
||||||
@ -1,5 +1,7 @@
|
|||||||
|
import { createSelector } from "@reduxjs/toolkit";
|
||||||
import { RootState } from "../store";
|
import { RootState } from "../store";
|
||||||
import { FieldGroupMap, SidebarLink } from "./metadataSlice";
|
import { FieldGroupMap, SidebarLink } from "./metadataSlice";
|
||||||
|
import { COUNTRY_CODES, CountryCodeEntry } from "./constants";
|
||||||
|
|
||||||
export const selectMetadataState = (state: RootState) => state.metadata;
|
export const selectMetadataState = (state: RootState) => state.metadata;
|
||||||
|
|
||||||
@ -33,3 +35,64 @@ export const selectTransactionStatuses = (state: RootState): string[] =>
|
|||||||
|
|
||||||
export const selectNavigationSidebar = (state: RootState): SidebarLink[] =>
|
export const selectNavigationSidebar = (state: RootState): SidebarLink[] =>
|
||||||
state.metadata.data?.sidebar?.links ?? [];
|
state.metadata.data?.sidebar?.links ?? [];
|
||||||
|
|
||||||
|
export const selectConditionOperators = (
|
||||||
|
state: RootState
|
||||||
|
): Record<string, string> | undefined =>
|
||||||
|
state.metadata.data?.field_names?.conditions;
|
||||||
|
|
||||||
|
export const selectTransactionFieldNames = (
|
||||||
|
state: RootState
|
||||||
|
): Record<string, string> | undefined =>
|
||||||
|
state.metadata.data?.field_names?.transactions;
|
||||||
|
|
||||||
|
// Re-Selectcrors
|
||||||
|
const normalizeCountryName = (value: string): string =>
|
||||||
|
value
|
||||||
|
.normalize("NFD")
|
||||||
|
.replace(/[\u0300-\u036f]/g, "")
|
||||||
|
.replace(/[^a-z0-9]/gi, "")
|
||||||
|
.toLowerCase();
|
||||||
|
|
||||||
|
const COUNTRY_CODE_LOOKUP = COUNTRY_CODES.reduce<
|
||||||
|
Record<string, CountryCodeEntry>
|
||||||
|
>((acc, entry) => {
|
||||||
|
acc[normalizeCountryName(entry.country)] = entry;
|
||||||
|
return acc;
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
const findCountryMetadata = (
|
||||||
|
countryName: string
|
||||||
|
): CountryCodeEntry | undefined => {
|
||||||
|
const normalized = normalizeCountryName(countryName);
|
||||||
|
if (!normalized) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (COUNTRY_CODE_LOOKUP[normalized]) {
|
||||||
|
return COUNTRY_CODE_LOOKUP[normalized];
|
||||||
|
}
|
||||||
|
|
||||||
|
return COUNTRY_CODES.find(entry => {
|
||||||
|
const normalizedCountry = normalizeCountryName(entry.country);
|
||||||
|
return (
|
||||||
|
normalizedCountry &&
|
||||||
|
(normalizedCountry.includes(normalized) ||
|
||||||
|
normalized.includes(normalizedCountry))
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const selectPhoneNumberCountries = createSelector(
|
||||||
|
[selectCountries],
|
||||||
|
countries =>
|
||||||
|
countries.map(country => {
|
||||||
|
const metadata = findCountryMetadata(country);
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: metadata?.code ?? "",
|
||||||
|
flag: metadata?.flag ?? "",
|
||||||
|
name: country,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|||||||
@ -5,6 +5,7 @@ import toast from "react-hot-toast";
|
|||||||
import { filter, switchMap } from "rxjs/operators";
|
import { filter, switchMap } from "rxjs/operators";
|
||||||
import { of } from "rxjs";
|
import { of } from "rxjs";
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
export const changePasswordEpic: Epic<any, any, RootState> = action$ =>
|
export const changePasswordEpic: Epic<any, any, RootState> = action$ =>
|
||||||
action$.pipe(
|
action$.pipe(
|
||||||
// Listen for any action related to changePassword (pending, fulfilled, rejected)
|
// Listen for any action related to changePassword (pending, fulfilled, rejected)
|
||||||
|
|||||||
@ -3,6 +3,7 @@ interface GetAuditsParams {
|
|||||||
page?: number;
|
page?: number;
|
||||||
sort?: string;
|
sort?: string;
|
||||||
filter?: string;
|
filter?: string;
|
||||||
|
entity?: string;
|
||||||
signal?: AbortSignal;
|
signal?: AbortSignal;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -11,6 +12,7 @@ export async function getAudits({
|
|||||||
page,
|
page,
|
||||||
sort,
|
sort,
|
||||||
filter,
|
filter,
|
||||||
|
entity,
|
||||||
signal,
|
signal,
|
||||||
}: GetAuditsParams = {}) {
|
}: GetAuditsParams = {}) {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@ -19,6 +21,7 @@ export async function getAudits({
|
|||||||
if (page) params.set("page", String(page));
|
if (page) params.set("page", String(page));
|
||||||
if (sort) params.set("sort", sort);
|
if (sort) params.set("sort", sort);
|
||||||
if (filter) params.set("filter", filter);
|
if (filter) params.set("filter", filter);
|
||||||
|
if (entity) params.set("Entity", entity);
|
||||||
|
|
||||||
const queryString = params.toString();
|
const queryString = params.toString();
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
|
|||||||
@ -5,6 +5,46 @@ import { jwtVerify } from "jose";
|
|||||||
const COOKIE_NAME = "auth_token";
|
const COOKIE_NAME = "auth_token";
|
||||||
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET!);
|
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET!);
|
||||||
|
|
||||||
|
// Define route-to-role mappings
|
||||||
|
// Routes can be protected by specific roles/groups or left open to all authenticated users
|
||||||
|
// Users can have multiple groups, and access is granted if ANY of their groups match
|
||||||
|
const ROUTE_ROLES: Record<string, string[]> = {
|
||||||
|
// Admin routes - only accessible by Super Admin or admin groups
|
||||||
|
"/dashboard/admin": ["Super Admin", "Admin"],
|
||||||
|
"/admin": ["Super Admin", "Admin"],
|
||||||
|
|
||||||
|
// Add more route guards here as needed
|
||||||
|
// Example: "/dashboard/settings": ["Super Admin", "admin", "manager"],
|
||||||
|
// Example: "/dashboard/transactions": ["Super Admin", "admin", "operator", "viewer"],
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a user's groups have access to a specific route
|
||||||
|
* Returns true if ANY of the user's groups match ANY of the required roles
|
||||||
|
*/
|
||||||
|
function hasRouteAccess(
|
||||||
|
userGroups: string[] | undefined,
|
||||||
|
pathname: string
|
||||||
|
): boolean {
|
||||||
|
// If no role is required for this route, allow access
|
||||||
|
const requiredRoles = Object.entries(ROUTE_ROLES).find(([route]) =>
|
||||||
|
pathname.startsWith(route)
|
||||||
|
)?.[1];
|
||||||
|
|
||||||
|
// If no role requirement found, allow access (route is open to all authenticated users)
|
||||||
|
if (!requiredRoles) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If user has no groups, deny access
|
||||||
|
if (!userGroups || userGroups.length === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if ANY of the user's groups match ANY of the required roles
|
||||||
|
return userGroups.some(group => requiredRoles.includes(group));
|
||||||
|
}
|
||||||
|
|
||||||
function isExpired(exp?: number) {
|
function isExpired(exp?: number) {
|
||||||
return exp ? exp * 1000 <= Date.now() : false;
|
return exp ? exp * 1000 <= Date.now() : false;
|
||||||
}
|
}
|
||||||
@ -17,9 +57,11 @@ async function validateToken(token: string) {
|
|||||||
algorithms: ["HS256"],
|
algorithms: ["HS256"],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log("[middleware] payload", payload);
|
||||||
return payload as {
|
return payload as {
|
||||||
exp?: number;
|
exp?: number;
|
||||||
MustChangePassword?: boolean;
|
MustChangePassword?: boolean;
|
||||||
|
Groups?: string[];
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@ -67,6 +109,19 @@ export async function middleware(request: NextRequest) {
|
|||||||
return NextResponse.redirect(loginUrl);
|
return NextResponse.redirect(loginUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 5️⃣ Role-based route guard (checking Groups array)
|
||||||
|
const userGroups = (payload.Groups as string[] | undefined) || [];
|
||||||
|
if (!hasRouteAccess(userGroups, currentPath)) {
|
||||||
|
// Redirect to dashboard home or unauthorized page
|
||||||
|
const unauthorizedUrl = new URL("/dashboard", request.url);
|
||||||
|
unauthorizedUrl.searchParams.set("reason", "unauthorized");
|
||||||
|
unauthorizedUrl.searchParams.set(
|
||||||
|
"message",
|
||||||
|
"You don't have permission to access this page"
|
||||||
|
);
|
||||||
|
return NextResponse.redirect(unauthorizedUrl);
|
||||||
|
}
|
||||||
|
|
||||||
// ✅ All good
|
// ✅ All good
|
||||||
return NextResponse.next();
|
return NextResponse.next();
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user