updated managment frontedn

This commit is contained in:
Berkay 2025-05-15 16:07:43 +03:00
parent f73b54613e
commit 4606f0721d
30 changed files with 1398 additions and 8 deletions

View File

@ -5,9 +5,9 @@ import { managementAccountTenantMainSecond } from "./management/account/tenantSo
import { buildingPartsTenantSomething } from "./building/parts/tenantSomething/index";
const dynamicPagesIndex: Record<string, Record<LanguageTypes, DynamicPage>> = {
"main/pages/user/dashboard": managementAccountTenantMain,
"management/account/tenant/something": managementAccountTenantMain,
"management/account/tenant/somethingSecond":
managementAccountTenantMainSecond,
"management/account/tenant/somethingSecond": managementAccountTenantMainSecond,
"building/parts/tenant/something": buildingPartsTenantSomething,
};

View File

@ -4,6 +4,9 @@ import superUserTenantSomethingSecond from "./management/account/tenantSomething
import superUserBuildingPartsTenantSomething from "./building/parts/tenantSomething/page";
const pageIndexMulti: Record<string, Record<string, React.FC<ContentProps>>> = {
"main/pages/user/dashboard": {
superUserTenantSomething: superUserTenantSomething,
},
"management/account/tenant/something": {
superUserTenantSomething: superUserTenantSomething,
},

View File

@ -1,5 +1,9 @@
import { LanguageTypes } from "@/validations/mutual/language/validations";
const afterLoginDirectUrl = (lang: LanguageTypes) => {
return `/panel/${lang}/main/pages/user/dashboard`;
};
function selectEmployeeHook(
startTransition: any,
data: any,
@ -10,7 +14,6 @@ function selectEmployeeHook(
) {
try {
const sendData = { ...data };
const urlToDirect = `/panel/${lang}/building/parts/tenant/something`;
startTransition(() => {
fetch("/api/selection/employee", {
method: "POST",
@ -20,9 +23,9 @@ function selectEmployeeHook(
.then((response) => {
if (response.status === 200) {
response.json().then((data) => {
console.log("data", data); // setJsonText(JSON.stringify(data));
console.log("data", data);
setTimeout(() => {
Router.push(urlToDirect);
Router.push(afterLoginDirectUrl(lang));
}, 100);
});
} else {
@ -48,7 +51,6 @@ function selectOccupantHook(
) {
try {
const sendData = { ...data };
const urlToDirect = `/auth/${lang}/panel/building/parts/tenant/something`;
startTransition(() => {
fetch("/api/selection/occupant", {
method: "POST",
@ -58,9 +60,9 @@ function selectOccupantHook(
.then((response) => {
if (response.status === 200) {
response.json().then((data) => {
console.log("data", data); // setJsonText(JSON.stringify(data));
console.log("data", data);
setTimeout(() => {
Router.push(urlToDirect);
Router.push(afterLoginDirectUrl(lang));
}, 100);
});
} else {

View File

@ -0,0 +1,259 @@
"use server";
import { fetchData, fetchDataWithToken } from "@/apicalls/api-fetcher";
import { baseUrlApplication } from "@/apicalls/basics";
import {
collectPaginationFromApiResponse,
defaultPaginationResponse,
type PaginatedApiResponse
} from "@/app/api/utils/types";
import { PaginationParams } from "@/apicalls/schemas/list";
const applicationListEndpoint = `${baseUrlApplication}/application/list/all`;
const applicationListAvailableEndpoint = `${baseUrlApplication}/application/list/available`;
const applicationListAppendedEndpoint = `${baseUrlApplication}/application/list/appended`;
const applicationRegisterServiceEndpoint = `${baseUrlApplication}/application/register/service`;
const applicationUnregisterServiceEndpoint = `${baseUrlApplication}/application/unregister/service`;
const applicationUpdateEndpoint = `${baseUrlApplication}/application/update`;
const applicationCreateEndpoint = `${baseUrlApplication}/application/create`;
const applicationDeleteEndpoint = `${baseUrlApplication}/application/delete`;
interface AppendApplicationToService {
application_uu_id: string;
service_uu_id: string;
}
interface RemoveApplicationFromService extends AppendApplicationToService { }
async function listApplicationsAvailable(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
if (!payload.query.service_uu_id__ilike) {
console.warn('Missing service_uu_id in query parameters');
return {
data: [],
pagination: defaultPaginationResponse,
};
}
try {
const requestBody = {
page: payload.page,
size: payload.size,
order_field: payload.orderField,
order_type: payload.orderType,
query: payload.query,
};
console.log('Sending request to backend with service_uu_id:', payload.query.service_uu_id);
console.log('Full request body:', JSON.stringify(requestBody, null, 2));
const response = await fetchDataWithToken(
applicationListAvailableEndpoint,
requestBody,
"POST",
false
);
if (response?.status === 200 || response?.status === 202) {
const responseData = response.data as PaginatedApiResponse<any>;
console.log('list_events_available responseData:', JSON.stringify(responseData, null, 2));
return {
data: responseData.data || [],
pagination: collectPaginationFromApiResponse(responseData)
};
}
return {
data: [],
pagination: defaultPaginationResponse,
};
} catch (error) {
console.error("Error fetching events list:", error);
return {
data: [],
pagination: defaultPaginationResponse,
};
}
}
async function listApplicationsAppended(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
if (!payload.query.service_uu_id__ilike) {
console.warn('Missing service_uu_id in query parameters');
return {
data: [],
pagination: defaultPaginationResponse,
};
}
try {
const requestBody = {
page: payload.page,
size: payload.size,
order_field: payload.orderField,
order_type: payload.orderType,
query: payload.query,
};
console.log('Sending request to backend with service_uu_id:', payload.query.service_uu_id);
console.log('Full request body:', JSON.stringify(requestBody, null, 2));
const response = await fetchDataWithToken(
applicationListAppendedEndpoint,
requestBody,
"POST",
false
);
if (response?.status === 200 || response?.status === 202) {
const responseData = response.data as PaginatedApiResponse<any>;
console.log('list_events_available responseData:', JSON.stringify(responseData, null, 2));
return {
data: responseData.data || [],
pagination: collectPaginationFromApiResponse(responseData)
};
}
return {
data: [],
pagination: defaultPaginationResponse,
};
} catch (error) {
console.error("Error fetching events list:", error);
return {
data: [],
pagination: defaultPaginationResponse,
};
}
}
async function listAllApplications(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
try {
const requestBody = {
page: payload.page,
size: payload.size,
order_field: payload.orderField,
order_type: payload.orderType,
query: payload.query,
};
console.log('Sending request to backend with service_uu_id:', payload.query.service_uu_id);
console.log('Full request body:', JSON.stringify(requestBody, null, 2));
const response = await fetchDataWithToken(
applicationListEndpoint,
requestBody,
"POST",
false
);
if (response?.status === 200 || response?.status === 202) {
const responseData = response.data as PaginatedApiResponse<any>;
console.log('list_events_available responseData:', JSON.stringify(responseData, null, 2));
return {
data: responseData.data || [],
pagination: collectPaginationFromApiResponse(responseData)
};
}
return {
data: [],
pagination: defaultPaginationResponse,
};
} catch (error) {
console.error("Error fetching events list:", error);
return {
data: [],
pagination: defaultPaginationResponse,
};
}
}
async function appendApplicationToService(payload: AppendApplicationToService) {
try {
const response = await fetchDataWithToken(
applicationRegisterServiceEndpoint,
payload,
"POST",
false
);
return response?.status === 200 || response?.status === 202 ? response.data : null;
} catch (error) {
console.error("Error appending event to service:", error);
}
}
async function removeApplicationFromService(payload: RemoveApplicationFromService) {
try {
const response = await fetchDataWithToken(
applicationUnregisterServiceEndpoint,
payload,
"POST",
false
);
return response?.status === 200 || response?.status === 202 ? response.data : null;
} catch (error) {
console.error("Error removing event from service:", error);
}
}
async function createApplication(payload: any) {
console.log("Creating application with payload:", payload);
try {
const response = await fetchDataWithToken(
applicationCreateEndpoint,
payload,
"POST",
false
);
return response?.status === 200 || response?.status === 202
? response.data
: null;
} catch (error) {
console.error("Error creating application:", error);
return null;
}
}
async function updateApplication(payload: any, uuId: string) {
console.log("Updating application with payload:", payload, 'uuId:', uuId);
try {
const response = await fetchDataWithToken(
`${applicationUpdateEndpoint}/${uuId}`,
payload,
"POST",
false
);
return response?.status === 200 || response?.status === 202
? response.data
: null;
} catch (error) {
console.error("Error updating application:", error);
return null;
}
}
async function deleteApplication(uuId: string) {
try {
const response = await fetchDataWithToken(
`${applicationDeleteEndpoint}/${uuId}`,
{},
"DELETE",
false
);
return response?.status === 200 || response?.status === 202
? response.data
: null;
} catch (error) {
console.error("Error deleting application:", error);
return null;
}
}
export {
listApplicationsAvailable,
listApplicationsAppended,
listAllApplications,
appendApplicationToService,
removeApplicationFromService,
createApplication,
updateApplication,
deleteApplication,
};

View File

@ -0,0 +1,153 @@
"use server";
import { fetchDataWithToken } from "../api-fetcher";
import { baseUrlApplication } from "../basics";
import { PaginationParams } from "../schemas/list";
import { PaginatedApiResponse, collectPaginationFromApiResponse, defaultPaginationResponse } from "@/app/api/utils/types";
const eventsListAvailableEndpoint = `${baseUrlApplication}/events/list/available`;
const eventsListAppendedEndpoint = `${baseUrlApplication}/events/list/appended`;
const appendEventToServiceEndpoint = `${baseUrlApplication}/events/register/service`;
const removeEventFromServiceEndpoint = `${baseUrlApplication}/events/unregister/service`;
interface AppendEventToService {
service_uu_id: string;
event_uu_id: string;
}
interface RemoveEventFromService extends AppendEventToService { }
async function list_events_available(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
if (!payload.query.service_uu_id__ilike) {
console.warn('Missing service_uu_id in query parameters');
return {
data: [],
pagination: defaultPaginationResponse,
};
}
try {
const requestBody = {
page: payload.page,
size: payload.size,
order_field: payload.orderField,
order_type: payload.orderType,
query: payload.query,
};
console.log('Sending request to backend with service_uu_id:', payload.query.service_uu_id);
console.log('Full request body:', JSON.stringify(requestBody, null, 2));
const response = await fetchDataWithToken(
eventsListAvailableEndpoint,
requestBody,
"POST",
false
);
if (response?.status === 200 || response?.status === 202) {
const responseData = response.data as PaginatedApiResponse<any>;
console.log('list_events_available responseData:', JSON.stringify(responseData, null, 2));
return {
data: responseData.data || [],
pagination: collectPaginationFromApiResponse(responseData)
};
}
return {
data: [],
pagination: defaultPaginationResponse,
};
} catch (error) {
console.error("Error fetching events list:", error);
return {
data: [],
pagination: defaultPaginationResponse,
};
}
}
async function list_events_appended(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
if (!payload.query.service_uu_id__ilike) {
console.warn('Missing service_uu_id in query parameters for list_events_appended');
return {
data: [],
pagination: defaultPaginationResponse,
};
}
try {
const requestBody = {
page: payload.page,
size: payload.size,
order_field: payload.orderField,
order_type: payload.orderType,
query: payload.query,
};
console.log('Sending request to backend with service_uu_id:', payload.query.service_uu_id);
console.log('Full request body:', JSON.stringify(requestBody, null, 2));
const response = await fetchDataWithToken(
eventsListAppendedEndpoint,
requestBody,
"POST",
false
);
if (response?.status === 200 || response?.status === 202) {
const responseData = response.data as PaginatedApiResponse<any>;
console.log('list_events_appended responseData:', JSON.stringify(responseData, null, 2));
return {
data: responseData.data || [],
pagination: collectPaginationFromApiResponse(responseData)
};
}
return {
data: [],
pagination: defaultPaginationResponse,
};
} catch (error) {
console.error("Error fetching events list:", error);
return {
data: [],
pagination: defaultPaginationResponse,
};
}
}
async function appendEventToService(payload: AppendEventToService) {
try {
const response = await fetchDataWithToken(
appendEventToServiceEndpoint,
payload,
"POST",
false
);
return response?.status === 200 || response?.status === 202 ? response.data : null;
} catch (error) {
console.error("Error appending event to service:", error);
}
}
async function removeEventFromService(payload: RemoveEventFromService) {
try {
const response = await fetchDataWithToken(
removeEventFromServiceEndpoint,
payload,
"POST",
false
);
return response?.status === 200 || response?.status === 202 ? response.data : null;
} catch (error) {
console.error("Error removing event from service:", error);
}
}
export {
list_events_available,
list_events_appended,
appendEventToService,
removeEventFromService,
};

View File

@ -0,0 +1,157 @@
"use server";
import { fetchDataWithToken } from "../api-fetcher";
import { baseUrlApplication } from "../basics";
import { PaginationParams } from "../schemas/list";
import type { PaginatedApiResponse } from "@/app/api/utils/types";
const servicesListEndpoint = `${baseUrlApplication}/service/list`;
const servicesToEventsEndpoint = `${baseUrlApplication}/service/to/events`;
async function listServices(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
try {
const response = await fetchDataWithToken(
servicesListEndpoint,
{
page: payload.page,
size: payload.size,
order_field: payload.orderField,
order_type: payload.orderType,
query: payload.query,
},
"POST",
false
);
if (response?.status === 200 || response?.status === 202) {
const responseData = response.data as PaginatedApiResponse<any>;
return {
data: responseData.data || [],
pagination: {
page: responseData.pagination?.page || 1,
size: responseData.pagination?.size || 10,
totalCount: responseData.pagination?.totalCount || 0,
totalItems: responseData.pagination?.totalItems || 0,
totalPages: responseData.pagination?.totalPages || 0,
pageCount: responseData.pagination?.pageCount || 0,
orderField: responseData.pagination?.orderField || ['name'],
orderType: responseData.pagination?.orderType || ['asc'],
query: responseData.pagination?.query || {},
next: responseData.pagination?.next || false,
back: responseData.pagination?.back || false
}
};
}
return {
data: [],
pagination: {
page: 1,
size: 10,
totalCount: 0,
totalItems: 0,
totalPages: 0,
pageCount: 0,
orderField: ['name'],
orderType: ['asc'],
query: {},
next: false,
back: false
}
};
} catch (error) {
console.error("Error fetching application list:", error);
// Return a default empty response instead of null to match the expected return type
return {
data: [],
pagination: {
page: 1,
size: 10,
totalCount: 0,
totalItems: 0,
totalPages: 0,
pageCount: 0,
orderField: ['name'],
orderType: ['asc'],
query: {},
next: false,
back: false
}
};
}
}
async function listEventsToService(payload: PaginationParams): Promise<PaginatedApiResponse<any>> {
try {
const response = await fetchDataWithToken(
servicesToEventsEndpoint,
{
page: payload.page,
size: payload.size,
order_field: payload.orderField,
order_type: payload.orderType,
query: payload.query,
},
"POST",
false,
);
if (response?.status === 200 || response?.status === 202) {
const responseData = response.data as PaginatedApiResponse<any>;
return {
data: responseData.data || [],
pagination: {
page: responseData.pagination?.page || 1,
size: responseData.pagination?.size || 10,
totalCount: responseData.pagination?.totalCount || 0,
totalItems: responseData.pagination?.totalItems || 0,
totalPages: responseData.pagination?.totalPages || 0,
pageCount: responseData.pagination?.pageCount || 0,
orderField: responseData.pagination?.orderField || ['name'],
orderType: responseData.pagination?.orderType || ['asc'],
query: responseData.pagination?.query || {},
next: responseData.pagination?.next || false,
back: responseData.pagination?.back || false
}
};
}
return {
data: [],
pagination: {
page: 1,
size: 10,
totalCount: 0,
totalItems: 0,
totalPages: 0,
pageCount: 0,
orderField: ['name'],
orderType: ['asc'],
query: {},
next: false,
back: false
}
};
} catch (error) {
console.error("Error fetching application list:", error);
// Return a default empty response instead of null to match the expected return type
return {
data: [],
pagination: {
page: 1,
size: 10,
totalCount: 0,
totalItems: 0,
totalPages: 0,
pageCount: 0,
orderField: ['name'],
orderType: ['asc'],
query: {},
next: false,
back: false
}
};
}
}
export {
listServices,
listEventsToService,
};

View File

@ -0,0 +1,19 @@
interface PaginateOnly {
page?: number;
size?: number;
orderField?: string[];
orderType?: string[];
}
interface PaginationParams {
page?: number;
size?: number;
orderField?: string[];
orderType?: string[];
query?: any;
}
export type {
PaginateOnly,
PaginationParams,
}

View File

@ -0,0 +1,22 @@
import { appendApplicationToService } from "@/apicalls/custom/application/apicall";
import { NextRequest } from "next/server";
import { withErrorHandling } from "@/app/api/utils/requestHandlers";
import {
successResponse,
errorResponse,
} from "@/app/api/utils/responseHandlers";
export const POST = withErrorHandling(
async (request: NextRequest, body: any) => {
const payload = {
application_uu_id: body.application_uu_id,
service_uu_id: body.service_uu_id,
};
const result = await appendApplicationToService(payload);
if (!result) {
return errorResponse("Error appending application to service");
} else {
return successResponse(result);
}
}
);

View File

@ -0,0 +1,22 @@
import { removeApplicationFromService } from "@/apicalls/custom/application/apicall";
import { NextRequest } from "next/server";
import { withErrorHandling } from "@/app/api/utils/requestHandlers";
import {
successResponse,
errorResponse,
} from "@/app/api/utils/responseHandlers";
export const POST = withErrorHandling(
async (request: NextRequest, body: any) => {
const payload = {
application_uu_id: body.application_uu_id,
service_uu_id: body.service_uu_id,
};
const result = await removeApplicationFromService(payload);
if (!result) {
return errorResponse("Error removing application from service");
} else {
return successResponse(result);
}
}
);

View File

@ -0,0 +1,4 @@
import { listApplicationsAppended } from "@/apicalls/custom/application/apicall";
import { createListHandler } from "@/app/api/utils";
export const POST = createListHandler(listApplicationsAppended);

View File

@ -0,0 +1,22 @@
import { appendEventToService } from "@/apicalls/custom/events/endpoints";
import { NextRequest } from "next/server";
import { withErrorHandling } from "@/app/api/utils/requestHandlers";
import {
successResponse,
errorResponse,
} from "@/app/api/utils/responseHandlers";
export const POST = withErrorHandling(
async (request: NextRequest, body: any) => {
const payload = {
event_uu_id: body.event_uu_id,
service_uu_id: body.service_uu_id,
};
const result = await appendEventToService(payload);
if (!result) {
return errorResponse("Error appending event to service");
} else {
return successResponse(result);
}
}
);

View File

@ -0,0 +1,22 @@
import { removeEventFromService } from "@/apicalls/custom/events/endpoints";
import { NextRequest } from "next/server";
import { withErrorHandling } from "@/app/api/utils/requestHandlers";
import {
successResponse,
errorResponse,
} from "@/app/api/utils/responseHandlers";
export const POST = withErrorHandling(
async (request: NextRequest, body: any) => {
const payload = {
event_uu_id: body.event_uu_id,
service_uu_id: body.service_uu_id,
};
const result = await removeEventFromService(payload);
if (!result) {
return errorResponse("Error removing event from service");
} else {
return successResponse(result);
}
}
);

View File

@ -0,0 +1,4 @@
import { list_events_appended } from "@/apicalls/custom/events/endpoints";
import { createListHandler } from "@/app/api/utils";
export const POST = createListHandler(list_events_appended);

View File

@ -0,0 +1,4 @@
import { createCreateHandler } from "@/app/api/utils";
import { appendApplicationToService } from "@/apicalls/custom/application/apicall";
export const POST = createCreateHandler(appendApplicationToService);

View File

@ -0,0 +1,4 @@
import { createCreateHandler } from "@/app/api/utils";
import { createApplication } from "@/apicalls/custom/application/apicall";
export const POST = createCreateHandler(createApplication);

View File

@ -0,0 +1,4 @@
import { listApplicationsAvailable } from "@/apicalls/custom/application/apicall";
import { createListHandler } from "@/app/api/utils";
export const POST = createListHandler(listApplicationsAvailable);

View File

@ -0,0 +1,4 @@
import { listAllApplications } from "@/apicalls/custom/application/apicall";
import { createListHandler } from "@/app/api/utils";
export const POST = createListHandler(listAllApplications);

View File

@ -0,0 +1,4 @@
import { createCreateHandler } from "@/app/api/utils";
import { removeApplicationFromService } from "@/apicalls/custom/application/apicall";
export const POST = createCreateHandler(removeApplicationFromService);

View File

@ -0,0 +1,4 @@
import { createUpdateHandler } from "../../utils";
import { updateApplication } from "@/apicalls/custom/application/apicall";
export const POST = createUpdateHandler(updateApplication);

View File

@ -0,0 +1,4 @@
import { list_events_available } from "@/apicalls/custom/events/endpoints";
import { createListHandler } from "@/app/api/utils";
export const POST = createListHandler(list_events_available);

View File

@ -0,0 +1,4 @@
import { listServices } from "@/apicalls/custom/services/endpoints";
import { createListHandler } from "@/app/api/utils";
export const POST = createListHandler(listServices);

View File

@ -0,0 +1,169 @@
import { NextRequest } from "next/server";
import {
successResponse,
errorResponse,
paginationResponse,
createResponse,
updateResponse,
deleteResponse,
} from "./responseHandlers";
import { withErrorHandling, validateRequiredFields } from "./requestHandlers";
import {
ApiHandler,
PaginationParams,
ListFunction,
CreateFunction,
UpdateFunction,
DeleteFunction,
} from "./types";
/**
* Generic list operation handler
* @param request NextRequest object
* @param body Request body
* @param listFunction The function to call to get the list data
*/
export async function handleListOperation(
request: NextRequest,
body: any,
listFunction: ListFunction
) {
const page = body.page || 1;
const size = body.size || 10;
const orderField = body.orderField || ["uu_id"];
const orderType = body.orderType || ["asc"];
const query = body.query || {};
const response = await listFunction({
page,
size,
orderField,
orderType,
query,
} as PaginationParams);
return paginationResponse(response.data, response.pagination);
}
/**
* Generic create operation handler
* @param request NextRequest object
* @param body Request body
* @param createFunction The function to call to create the item
* @param requiredFields Array of required field names
*/
export async function handleCreateOperation(
body: any,
createFunction?: CreateFunction,
requiredFields: string[] = []
) {
if (requiredFields.length > 0) {
const validation = validateRequiredFields(body, requiredFields);
if (!validation.valid) {
return errorResponse(validation.error as string, 400);
}
}
if (createFunction) {
console.log("Body:", body);
const result = await createFunction(body);
return createResponse(result);
}
return createResponse({
uuid: Math.floor(Math.random() * 1000),
...body,
});
}
/**
* Generic update operation handler
* @param request NextRequest object
* @param body Request body
* @param updateFunction The function to call to update the item
*/
export async function handleUpdateOperation(
request: NextRequest,
body: any,
updateFunction?: UpdateFunction
) {
const uuid = request.nextUrl.searchParams.get("uuid");
if (!uuid) {
return errorResponse("UUID not found", 400);
}
if (updateFunction) {
console.log("Body:", body);
const result = await updateFunction(body, uuid);
return updateResponse(result);
}
return updateResponse(body);
}
/**
* Generic delete operation handler
* @param request NextRequest object
* @param deleteFunction The function to call to delete the item
*/
export async function handleDeleteOperation(
request: NextRequest,
deleteFunction?: DeleteFunction
) {
const uuid = request.nextUrl.searchParams.get("uuid");
if (!uuid) {
return errorResponse("UUID not found", 400);
}
if (deleteFunction) {
await deleteFunction(uuid);
}
return deleteResponse();
}
/**
* Create a wrapped list handler with error handling
* @param listFunction The function to call to get the list data
*/
export function createListHandler(listFunction: ListFunction) {
return withErrorHandling((request: NextRequest, body: any) =>
handleListOperation(request, body, listFunction)
);
}
/**
* Create a wrapped create handler with error handling
* @param createFunction The function to call to create the item
* @param requiredFields Array of required field names
*/
export function createCreateHandler(
createFunction?: CreateFunction,
requiredFields: string[] = []
) {
console.log("Required fields:", requiredFields);
// This handler only takes the body parameter, not the request
return withErrorHandling((body: any) => {
// Ensure we're only passing the actual body data to the create function
if (body && typeof body === 'object' && body.body) {
console.log("Extracting body from request body");
return handleCreateOperation(body.body, createFunction, requiredFields);
}
return handleCreateOperation(body, createFunction, requiredFields);
});
}
/**
* Create a wrapped update handler with error handling
* @param updateFunction The function to call to update the item
*/
export function createUpdateHandler(updateFunction?: UpdateFunction) {
return withErrorHandling((request: NextRequest, body: any) =>
handleUpdateOperation(request, body, updateFunction)
);
}
/**
* Create a wrapped delete handler with error handling
* @param deleteFunction The function to call to delete the item
*/
export function createDeleteHandler(deleteFunction?: DeleteFunction) {
return withErrorHandling((request: NextRequest) =>
handleDeleteOperation(request, deleteFunction)
);
}

View File

@ -0,0 +1,4 @@
// Export all utility functions from a single entry point
export * from './responseHandlers';
export * from './requestHandlers';
export * from './apiOperations';

View File

@ -0,0 +1,70 @@
import { NextRequest } from "next/server";
import { errorResponse } from "./responseHandlers";
import { ValidationResult, ApiHandler, ApiHandlerBodyOnly, ApiHandlerWithRequest } from "./types";
/**
* Safely parse JSON request body with error handling
* @param request NextRequest object
* @returns Parsed request body or null if parsing fails
*/
export async function parseRequestBody(request: NextRequest) {
try {
return await request.json();
} catch (error) {
return null;
}
}
/**
* Wrapper for API route handlers with built-in error handling
* @param handler The handler function to wrap
*/
export function withErrorHandling(
handler: ApiHandler
) {
return async (request: NextRequest) => {
try {
const body = await parseRequestBody(request);
if (body === null) {
return errorResponse("Invalid request body", 400);
}
// Check handler parameter count to determine if it needs request object
// If handler has only 1 parameter, it's likely a create operation that only needs body
if (handler.length === 1) {
// Cast to the appropriate handler type
return await (handler as ApiHandlerBodyOnly)(body);
} else {
// Otherwise pass both request and body (for list, update, delete operations)
return await (handler as ApiHandlerWithRequest)(request, body);
}
} catch (error: any) {
return errorResponse(
error.message || "Internal Server Error",
error.status || 500
);
}
};
}
/**
* Validate that required fields are present in the request body
* @param body Request body
* @param requiredFields Array of required field names
* @returns Object with validation result and error message if validation fails
*/
export function validateRequiredFields(body: any, requiredFields: string[]): ValidationResult {
const missingFields = requiredFields.filter(field =>
body[field] === undefined || body[field] === null || body[field] === ''
);
if (missingFields.length > 0) {
return {
valid: false,
error: `Missing required fields: ${missingFields.join(', ')}`
};
}
return { valid: true };
}

View File

@ -0,0 +1,91 @@
import { NextResponse } from "next/server";
import { ApiResponse, PaginationResponse, PaginatedApiResponse } from "./types";
/**
* Standard success response handler
* @param data The data to return in the response
* @param status HTTP status code (default: 200)
*/
export function successResponse<T>(data: T, status: number = 200) {
return NextResponse.json(
{
success: true,
data,
} as ApiResponse<T>,
{ status }
);
}
/**
* Standard error response handler
* @param message Error message
* @param status HTTP status code (default: 500)
*/
export function errorResponse(message: string, status: number = 500) {
console.error(`API error: ${message}`);
return NextResponse.json(
{
success: false,
error: message
} as ApiResponse<never>,
{ status }
);
}
/**
* Standard pagination response format
* @param data Array of items to return
* @param pagination Pagination information
*/
export function paginationResponse<T>(data: T[], pagination: PaginationResponse | null) {
return NextResponse.json({
data: data || [],
pagination: pagination || {
page: 1,
size: 10,
totalCount: 0,
totalItems: 0,
totalPages: 0,
pageCount: 0,
orderField: ["name"],
orderType: ["asc"],
query: {},
next: false,
back: false,
},
} as PaginatedApiResponse<T>);
}
/**
* Create response handler
* @param data The created item data
*/
export function createResponse<T>(data: T) {
return successResponse(
{
...data as any,
createdAt: new Date().toISOString(),
} as T,
201
);
}
/**
* Update response handler
* @param data The updated item data
*/
export function updateResponse<T>(data: T) {
return successResponse(
{
...data as any,
updatedAt: new Date().toISOString(),
} as T
);
}
/**
* Delete response handler
*/
export function deleteResponse() {
return successResponse({ message: "Item deleted successfully" }, 204);
}

View File

@ -0,0 +1,119 @@
/**
* Type definitions for API utilities
*/
import { NextRequest } from "next/server";
/**
* Validation result interface
*/
export interface ValidationResult {
valid: boolean;
error?: string;
}
/**
* Pagination parameters interface
*/
export interface PaginationParams {
page: number;
size: number;
orderField: string[];
orderType: string[];
query: Record<string, any>;
}
/**
* Pagination response interface
*/
export interface PaginationResponse {
page: number;
size: number;
totalCount: number;
totalItems: number;
totalPages: number;
pageCount: number;
orderField: string[];
orderType: string[];
query: Record<string, any>;
next: boolean;
back: boolean;
}
export const defaultPaginationResponse: PaginationResponse = {
page: 1,
size: 10,
totalCount: 0,
totalItems: 0,
totalPages: 0,
pageCount: 0,
orderField: ["uu_id"],
orderType: ["asc"],
query: {},
next: false,
back: false,
};
/**
* API response interface
*/
export interface ApiResponse<T> {
success: boolean;
data?: T;
error?: string;
}
/**
* Paginated API response interface
*/
export interface PaginatedApiResponse<T> {
data: T[];
pagination: PaginationResponse;
}
export const collectPaginationFromApiResponse = (
response: PaginatedApiResponse<any>
): PaginationResponse => {
return {
page: response.pagination?.page || 1,
size: response.pagination?.size || 10,
totalCount: response.pagination?.totalCount || 0,
totalItems: response.pagination?.totalItems || 0,
totalPages: response.pagination?.totalPages || 0,
pageCount: response.pagination?.pageCount || 0,
orderField: response.pagination?.orderField || ["uu_id"],
orderType: response.pagination?.orderType || ["asc"],
query: response.pagination?.query || {},
next: response.pagination?.next || false,
back: response.pagination?.back || false,
};
};
/**
* API handler function types
*/
export type ApiHandlerWithRequest = (request: NextRequest, body: any) => Promise<Response>;
export type ApiHandlerBodyOnly = (body: any) => Promise<Response>;
export type ApiHandler = ApiHandlerWithRequest | ApiHandlerBodyOnly;
/**
* List function type
*/
export type ListFunction = (
params: PaginationParams
) => Promise<PaginatedApiResponse<any>>;
/**
* Create function type
*/
export type CreateFunction = (data: any) => Promise<any>;
/**
* Update function type
*/
export type UpdateFunction = (id: any, data: any) => Promise<any>;
/**
* Delete function type
*/
export type DeleteFunction = (id: any) => Promise<any>;

View File

@ -0,0 +1,7 @@
import Link from "next/link"
const renderLastRowComponent = (reDirectUrl: string, IconToWrap: any, key: string) => {
return <Link key={key} className="flex items-center gap-2" replace href={reDirectUrl} ><IconToWrap /></Link>
}
export { renderLastRowComponent }

View File

@ -0,0 +1,73 @@
'use client';
import React, { useState } from "react";
import TableComponent from "@/components/mutual/tableView/FullTableComp/component";
import CreateForm from "@/components/mutual/tableView/mutual/CreateForm";
import UpdateForm from "@/components/mutual/tableView/mutual/UpdateForm";
import ViewForm from "@/components/mutual/tableView/mutual/ViewForm";
import { EyeIcon, PencilIcon, PlusCircle, ArrowLeftFromLineIcon, ExpandIcon } from "lucide-react";
import { ContentProps } from "@/validations/mutual/dashboard/props";
import { getSchemaByLanguage } from "@/schemas/custom/application/schemas";
import { API_BASE_URL } from "@/config/config";
import { renderLastRowComponent } from "@/components/mutual/navigators/component";
// This is a mock page dont use it
const superUserApplicationRegister: React.FC<ContentProps> = ({ lang, translations, activePageUrl, mode }) => {
const [selectedRow, setSelectedRow] = useState<any>(null);
const getSchema = getSchemaByLanguage(lang)
const basePageUrl = `/panel/${lang}/${activePageUrl}?mode=`
const isList = mode === 'shortList' || mode === 'fullList'
const changeList = mode === 'shortList' ? `${basePageUrl}fullList` : `${basePageUrl}shortList`
const RenderBackToList = renderLastRowComponent(`${basePageUrl}shortList`, ArrowLeftFromLineIcon, "backToList")
const redirectUrls = {
table: {
update: renderLastRowComponent(`${basePageUrl}update`, PencilIcon, "update"),
view: renderLastRowComponent(`${basePageUrl}view`, EyeIcon, "view"),
},
page: {
create: renderLastRowComponent(`${basePageUrl}create`, PlusCircle, "create"),
size: renderLastRowComponent(changeList, ExpandIcon, "size-table"),
}
}
const listWithTableProps = {
urls: { list: `${API_BASE_URL}/application/register` },
translations: translations,
redirectUrls: redirectUrls,
initPagination: { page: 1, size: 10, orderFields: [], orderTypes: [], query: {} },
setSelectedRow: setSelectedRow,
}
const CreateFormProps = {
schemas: { create: getSchema.createSchema },
labels: getSchema.labels,
selectedRow: selectedRow,
}
const UpdateFormProps = {
rollbackTo: changeList,
schemas: { update: getSchema.updateSchema },
labels: getSchema.labels,
selectedRow: selectedRow,
}
const ViewFormProps = {
rollbackTo: changeList,
schemas: { view: getSchema.detailSchema },
selectedRow: selectedRow,
labels: getSchema.labels,
}
const shortAddProps = { ...listWithTableProps, schemas: { table: getSchema.shortSchema }, columns: { table: getSchema.shortColumns } }
const fullAddProps = { ...listWithTableProps, schemas: { table: getSchema.detailSchema }, columns: { table: getSchema.columns } }
return (
<div>
{!isList && RenderBackToList}
{isList && mode === 'shortList' && <TableComponent {...shortAddProps} />}
{isList && mode === 'fullList' && <TableComponent {...fullAddProps} />}
{mode === 'create' && <CreateForm {...CreateFormProps} />}
{mode === 'update' && <UpdateForm {...UpdateFormProps} />}
{mode === 'view' && <ViewForm {...ViewFormProps} />}
</div>
);
}
export default superUserApplicationRegister

View File

@ -0,0 +1,136 @@
import { z } from "zod";
import { LanguageTypes } from "@/validations/mutual/language/validations";
import { buildingPartsFieldsTr } from "@/languages/custom/building/turkish";
import { buildingPartsFieldsEn } from "@/languages/custom/building/english";
interface ApplicationData {
uu_id: string;
name: string;
application_code: string;
site_url: string;
application_type: string;
application_for?: string;
description?: string;
active: boolean;
deleted?: boolean;
created_at?: string;
updated_at?: string;
}
const labelTranslations = {
tr: buildingPartsFieldsTr,
en: buildingPartsFieldsEn,
};
const errorMessages = {
en: {
nameRequired: "Name is required",
applicationCodeRequired: "Application code is required",
siteUrlRequired: "Site URL is required",
applicationTypeRequired: "Application type is required",
},
tr: {
nameRequired: "İsim gereklidir",
applicationCodeRequired: "Uygulama kodu gereklidir",
siteUrlRequired: "Site URL'si gereklidir",
applicationTypeRequired: "Uygulama tipi gereklidir",
},
};
function getSchemaByLanguage(lang: LanguageTypes) {
const createSchema = z.object({
// Identification fields
uu_id: z.string().optional(),
name: z.string().min(1, errorMessages[lang].nameRequired),
application_code: z
.string()
.min(1, errorMessages[lang].applicationCodeRequired),
// Application details
site_url: z.string().min(1, errorMessages[lang].siteUrlRequired),
application_type: z
.string()
.min(1, errorMessages[lang].applicationTypeRequired),
application_for: z.string().optional(),
description: z.string().optional(),
// Status fields
active: z.boolean().default(true),
deleted: z.boolean().default(false),
// System fields
created_at: z.string().optional(),
updated_at: z.string().optional(),
});
const updateSchema = z.object({
// Identification fields
uu_id: z.string().optional(),
name: z.string().min(1, errorMessages[lang].nameRequired),
application_code: z
.string()
.min(1, errorMessages[lang].applicationCodeRequired),
// Application details
site_url: z.string().min(1, errorMessages[lang].siteUrlRequired),
application_type: z
.string()
.min(1, errorMessages[lang].applicationTypeRequired),
application_for: z.string().optional(),
description: z.string().optional(),
// Status fields
active: z.boolean().default(true),
deleted: z.boolean().default(false),
// System fields
created_at: z.string().optional(),
updated_at: z.string().optional(),
});
const detailSchema = z.object({
uu_id: z.string(),
name: z.string(),
application_code: z.string(),
site_url: z.string(),
application_type: z.string(),
application_for: z.string().optional(),
description: z.string().optional(),
active: z.boolean(),
deleted: z.boolean(),
created_at: z.string(),
updated_at: z.string(),
});
const shortSchema = z.object({
uu_id: z.string(),
name: z.string(),
application_code: z.string(),
site_url: z.string(),
});
const columns = Object.keys(detailSchema.shape);
const shortColumns = Object.keys(shortSchema.shape);
const setColumns = columns.map((column) => {
return labelTranslations[lang][
column as keyof (typeof labelTranslations)[typeof lang]
];
});
const setShortColumns = shortColumns.map((column) => {
return labelTranslations[lang][
column as keyof (typeof labelTranslations)[typeof lang]
];
});
return {
createSchema,
updateSchema,
detailSchema,
shortSchema,
labels: labelTranslations[lang],
columns: setColumns,
shortColumns: setShortColumns,
};
}
export { getSchemaByLanguage };