management frontend menu and content get tested
This commit is contained in:
parent
1560d6e68b
commit
f73b54613e
|
|
@ -0,0 +1,177 @@
|
|||
"use server";
|
||||
import { retrieveAccessToken } from "@/apicalls/mutual/cookies/token";
|
||||
import {
|
||||
DEFAULT_RESPONSE,
|
||||
defaultHeaders,
|
||||
FetchOptions,
|
||||
HttpMethod,
|
||||
ApiResponse,
|
||||
DEFAULT_TIMEOUT,
|
||||
} from "./basics";
|
||||
|
||||
/**
|
||||
* Creates a promise that rejects after a specified timeout
|
||||
* @param ms Timeout in milliseconds
|
||||
* @param controller AbortController to abort the fetch request
|
||||
* @returns A promise that rejects after the timeout
|
||||
*/
|
||||
const createTimeoutPromise = (
|
||||
ms: number,
|
||||
controller: AbortController
|
||||
): Promise<never> => {
|
||||
return new Promise((_, reject) => {
|
||||
setTimeout(() => {
|
||||
controller.abort();
|
||||
reject(new Error(`Request timed out after ${ms}ms`));
|
||||
}, ms);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Prepares a standardized API response
|
||||
* @param response The response data
|
||||
* @param statusCode HTTP status code
|
||||
* @returns Standardized API response
|
||||
*/
|
||||
const prepareResponse = <T>(
|
||||
response: T,
|
||||
statusCode: number
|
||||
): ApiResponse<T> => {
|
||||
try {
|
||||
return {
|
||||
status: statusCode,
|
||||
data: response || ({} as T),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error preparing response:", error);
|
||||
return {
|
||||
...DEFAULT_RESPONSE,
|
||||
error: "Response parsing error",
|
||||
} as ApiResponse<T>;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Core fetch function with timeout and error handling
|
||||
* @param url The URL to fetch
|
||||
* @param options Fetch options
|
||||
* @param headers Request headers
|
||||
* @param payload Request payload
|
||||
* @returns API response
|
||||
*/
|
||||
async function coreFetch<T>(
|
||||
url: string,
|
||||
options: FetchOptions = {},
|
||||
headers: Record<string, string> = defaultHeaders,
|
||||
payload?: any
|
||||
): Promise<ApiResponse<T>> {
|
||||
const { method = "POST", cache = false, timeout = DEFAULT_TIMEOUT } = options;
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const signal = controller.signal;
|
||||
|
||||
const fetchOptions: RequestInit = {
|
||||
method,
|
||||
headers,
|
||||
cache: cache ? "force-cache" : "no-cache",
|
||||
signal,
|
||||
};
|
||||
|
||||
// Add body if needed
|
||||
if (method !== "GET" && payload) {
|
||||
fetchOptions.body = JSON.stringify(
|
||||
// Handle special case for updateDataWithToken
|
||||
payload.payload ? payload.payload : payload
|
||||
);
|
||||
}
|
||||
|
||||
// Create timeout promise
|
||||
const timeoutPromise = createTimeoutPromise(timeout, controller);
|
||||
|
||||
// Race between fetch and timeout
|
||||
const response = (await Promise.race([
|
||||
fetch(url, fetchOptions),
|
||||
timeoutPromise,
|
||||
])) as Response;
|
||||
|
||||
const responseJson = await response.json();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
console.log("Fetching:", url, fetchOptions);
|
||||
console.log("Response:", responseJson);
|
||||
}
|
||||
|
||||
return prepareResponse(responseJson, response.status);
|
||||
} catch (error) {
|
||||
console.error(`Fetch error (${url}):`, error);
|
||||
return {
|
||||
...DEFAULT_RESPONSE,
|
||||
error: error instanceof Error ? error.message : "Network error",
|
||||
} as ApiResponse<T>;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch data without authentication
|
||||
*/
|
||||
async function fetchData<T>(
|
||||
endpoint: string,
|
||||
payload?: any,
|
||||
method: HttpMethod = "POST",
|
||||
cache: boolean = false,
|
||||
timeout: number = DEFAULT_TIMEOUT
|
||||
): Promise<ApiResponse<T>> {
|
||||
return coreFetch<T>(
|
||||
endpoint,
|
||||
{ method, cache, timeout },
|
||||
defaultHeaders,
|
||||
payload
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch data with authentication token
|
||||
*/
|
||||
async function fetchDataWithToken<T>(
|
||||
endpoint: string,
|
||||
payload?: any,
|
||||
method: HttpMethod = "POST",
|
||||
cache: boolean = false,
|
||||
timeout: number = DEFAULT_TIMEOUT
|
||||
): Promise<ApiResponse<T>> {
|
||||
const accessToken = (await retrieveAccessToken()) || "";
|
||||
const headers = {
|
||||
...defaultHeaders,
|
||||
"eys-acs-tkn": accessToken,
|
||||
};
|
||||
|
||||
return coreFetch<T>(endpoint, { method, cache, timeout }, headers, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update data with authentication token and UUID
|
||||
*/
|
||||
async function updateDataWithToken<T>(
|
||||
endpoint: string,
|
||||
uuid: string,
|
||||
payload?: any,
|
||||
method: HttpMethod = "POST",
|
||||
cache: boolean = false,
|
||||
timeout: number = DEFAULT_TIMEOUT
|
||||
): Promise<ApiResponse<T>> {
|
||||
const accessToken = (await retrieveAccessToken()) || "";
|
||||
const headers = {
|
||||
...defaultHeaders,
|
||||
"eys-acs-tkn": accessToken,
|
||||
};
|
||||
|
||||
return coreFetch<T>(
|
||||
`${endpoint}/${uuid}`,
|
||||
{ method, cache, timeout },
|
||||
headers,
|
||||
payload
|
||||
);
|
||||
}
|
||||
|
||||
export { fetchData, fetchDataWithToken, updateDataWithToken };
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
const formatServiceUrl = (url: string) => {
|
||||
if (!url) return "";
|
||||
return url.startsWith("http") ? url : `http://${url}`;
|
||||
};
|
||||
|
||||
const baseUrlAuth = formatServiceUrl(
|
||||
process.env.NEXT_PUBLIC_AUTH_SERVICE_URL || "auth_service:8001"
|
||||
);
|
||||
const baseUrlPeople = formatServiceUrl(
|
||||
process.env.NEXT_PUBLIC_VALIDATION_SERVICE_URL || "identity_service:8002"
|
||||
);
|
||||
const baseUrlApplication = formatServiceUrl(
|
||||
process.env.NEXT_PUBLIC_MANAGEMENT_SERVICE_URL || "management_service:8004"
|
||||
);
|
||||
|
||||
// Types for better type safety
|
||||
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
|
||||
|
||||
interface ApiResponse<T = any> {
|
||||
status: number;
|
||||
data: T;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface FetchOptions {
|
||||
method?: HttpMethod;
|
||||
cache?: boolean;
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
const tokenSecret = process.env.TOKENSECRET_90 || "";
|
||||
|
||||
const cookieObject: any = {
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
sameSite: "none",
|
||||
secure: true,
|
||||
maxAge: 3600,
|
||||
priority: "high",
|
||||
};
|
||||
|
||||
// Constants
|
||||
const DEFAULT_TIMEOUT = 10000; // 10 seconds
|
||||
const defaultHeaders = {
|
||||
accept: "application/json",
|
||||
language: "tr",
|
||||
domain: "management.com.tr",
|
||||
tz: "GMT+3",
|
||||
"Content-type": "application/json",
|
||||
};
|
||||
const DEFAULT_RESPONSE: ApiResponse = {
|
||||
error: "Hata tipi belirtilmedi",
|
||||
status: 500,
|
||||
data: {},
|
||||
};
|
||||
|
||||
export type { HttpMethod, ApiResponse, FetchOptions };
|
||||
export {
|
||||
DEFAULT_TIMEOUT,
|
||||
DEFAULT_RESPONSE,
|
||||
defaultHeaders,
|
||||
baseUrlAuth,
|
||||
baseUrlPeople,
|
||||
baseUrlApplication,
|
||||
tokenSecret,
|
||||
cookieObject,
|
||||
};
|
||||
|
|
@ -0,0 +1,182 @@
|
|||
"use server";
|
||||
import NextCrypto from "next-crypto";
|
||||
import { fetchData, fetchDataWithToken } from "@/apicalls/api-fetcher";
|
||||
import { baseUrlAuth, cookieObject, tokenSecret } from "@/apicalls/basics";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
const loginEndpoint = `${baseUrlAuth}/authentication/login`;
|
||||
const loginSelectEndpoint = `${baseUrlAuth}/authentication/select`;
|
||||
const logoutEndpoint = `${baseUrlAuth}/authentication/logout`;
|
||||
|
||||
console.log("loginEndpoint", loginEndpoint);
|
||||
console.log("loginSelectEndpoint", loginSelectEndpoint);
|
||||
|
||||
interface LoginViaAccessKeys {
|
||||
accessKey: string;
|
||||
password: string;
|
||||
rememberMe: boolean;
|
||||
}
|
||||
|
||||
interface LoginSelectEmployee {
|
||||
company_uu_id: string;
|
||||
}
|
||||
|
||||
interface LoginSelectOccupant {
|
||||
build_living_space_uu_id: any;
|
||||
}
|
||||
|
||||
async function logoutActiveSession() {
|
||||
const cookieStore = await cookies();
|
||||
const response = await fetchDataWithToken(logoutEndpoint, {}, "GET", false);
|
||||
cookieStore.delete("accessToken");
|
||||
cookieStore.delete("accessObject");
|
||||
cookieStore.delete("userProfile");
|
||||
cookieStore.delete("userSelection");
|
||||
return response;
|
||||
}
|
||||
|
||||
async function loginViaAccessKeys(payload: LoginViaAccessKeys) {
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
const nextCrypto = new NextCrypto(tokenSecret);
|
||||
|
||||
const response = await fetchData(
|
||||
loginEndpoint,
|
||||
{
|
||||
access_key: payload.accessKey,
|
||||
password: payload.password,
|
||||
remember_me: payload.rememberMe,
|
||||
},
|
||||
"POST",
|
||||
false
|
||||
);
|
||||
console.log("response", response);
|
||||
if (response.status === 200 || response.status === 202) {
|
||||
const loginRespone: any = response?.data;
|
||||
const accessToken = await nextCrypto.encrypt(loginRespone.access_token);
|
||||
const accessObject = await nextCrypto.encrypt(
|
||||
JSON.stringify({
|
||||
userType: loginRespone.user_type,
|
||||
selectionList: loginRespone.selection_list,
|
||||
})
|
||||
);
|
||||
const userProfile = await nextCrypto.encrypt(
|
||||
JSON.stringify(loginRespone.user)
|
||||
);
|
||||
|
||||
cookieStore.set({
|
||||
name: "accessToken",
|
||||
value: accessToken,
|
||||
...cookieObject,
|
||||
});
|
||||
cookieStore.set({
|
||||
name: "accessObject",
|
||||
value: accessObject,
|
||||
...cookieObject,
|
||||
});
|
||||
cookieStore.set({
|
||||
name: "userProfile",
|
||||
value: JSON.stringify(userProfile),
|
||||
...cookieObject,
|
||||
});
|
||||
try {
|
||||
return {
|
||||
completed: true,
|
||||
message: "Login successful",
|
||||
status: 200,
|
||||
data: loginRespone,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("JSON parse error:", error);
|
||||
return {
|
||||
completed: false,
|
||||
message: "Login NOT successful",
|
||||
status: 401,
|
||||
data: "{}",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
completed: false,
|
||||
// error: response.error || "Login failed",
|
||||
// message: response.message || "Authentication failed",
|
||||
status: response.status || 500,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Login error:", error);
|
||||
return {
|
||||
completed: false,
|
||||
// error: error instanceof Error ? error.message : "Login error",
|
||||
// message: "An error occurred during login",
|
||||
status: 500,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function loginSelectEmployee(payload: LoginSelectEmployee) {
|
||||
const cookieStore = await cookies();
|
||||
const nextCrypto = new NextCrypto(tokenSecret);
|
||||
const companyUUID = payload.company_uu_id;
|
||||
const selectResponse: any = await fetchDataWithToken(
|
||||
loginSelectEndpoint,
|
||||
{
|
||||
company_uu_id: companyUUID,
|
||||
},
|
||||
"POST",
|
||||
false
|
||||
);
|
||||
cookieStore.delete("userSelection");
|
||||
|
||||
if (selectResponse.status === 200 || selectResponse.status === 202) {
|
||||
const usersSelection = await nextCrypto.encrypt(
|
||||
JSON.stringify({
|
||||
selected: companyUUID,
|
||||
user_type: "employee",
|
||||
})
|
||||
);
|
||||
cookieStore.set({
|
||||
name: "userSelection",
|
||||
value: usersSelection,
|
||||
...cookieObject,
|
||||
});
|
||||
}
|
||||
return selectResponse;
|
||||
}
|
||||
|
||||
async function loginSelectOccupant(payload: LoginSelectOccupant) {
|
||||
const livingSpaceUUID = payload.build_living_space_uu_id;
|
||||
const cookieStore = await cookies();
|
||||
const nextCrypto = new NextCrypto(tokenSecret);
|
||||
const selectResponse: any = await fetchDataWithToken(
|
||||
loginSelectEndpoint,
|
||||
{
|
||||
build_living_space_uu_id: livingSpaceUUID,
|
||||
},
|
||||
"POST",
|
||||
false
|
||||
);
|
||||
cookieStore.delete("userSelection");
|
||||
|
||||
if (selectResponse.status === 200 || selectResponse.status === 202) {
|
||||
const usersSelection = await nextCrypto.encrypt(
|
||||
JSON.stringify({
|
||||
selected: livingSpaceUUID,
|
||||
user_type: "occupant",
|
||||
})
|
||||
);
|
||||
cookieStore.set({
|
||||
name: "userSelection",
|
||||
value: usersSelection,
|
||||
...cookieObject,
|
||||
});
|
||||
}
|
||||
return selectResponse;
|
||||
}
|
||||
|
||||
export {
|
||||
loginViaAccessKeys,
|
||||
loginSelectEmployee,
|
||||
loginSelectOccupant,
|
||||
logoutActiveSession,
|
||||
};
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
"use server";
|
||||
import { fetchDataWithToken } from "@/apicalls/api-fetcher";
|
||||
import { baseUrlAuth, tokenSecret } from "@/apicalls/basics";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
import NextCrypto from "next-crypto";
|
||||
|
||||
const checkToken = `${baseUrlAuth}/authentication/token/check`;
|
||||
const pageValid = `${baseUrlAuth}/authentication/page/valid`;
|
||||
const siteUrls = `${baseUrlAuth}/authentication/sites/list`;
|
||||
|
||||
const nextCrypto = new NextCrypto(tokenSecret);
|
||||
|
||||
async function checkAccessTokenIsValid() {
|
||||
const response = await fetchDataWithToken(checkToken, {}, "GET", false);
|
||||
return response?.status === 200 || response?.status === 202 ? true : false;
|
||||
}
|
||||
|
||||
async function retrievePageList() {
|
||||
const response: any = await fetchDataWithToken(siteUrls, {}, "GET", false);
|
||||
return response?.status === 200 || response?.status === 202
|
||||
? response.data?.sites
|
||||
: null;
|
||||
}
|
||||
|
||||
async function retrieveApplicationbyUrl(pageUrl: string) {
|
||||
const response: any = await fetchDataWithToken(
|
||||
pageValid,
|
||||
{
|
||||
page_url: pageUrl,
|
||||
},
|
||||
"POST",
|
||||
false
|
||||
);
|
||||
return response?.status === 200 || response?.status === 202
|
||||
? response.data?.application
|
||||
: null;
|
||||
}
|
||||
|
||||
async function retrieveAccessToken() {
|
||||
const cookieStore = await cookies();
|
||||
const encrpytAccessToken = cookieStore.get("accessToken")?.value || "";
|
||||
return encrpytAccessToken
|
||||
? await nextCrypto.decrypt(encrpytAccessToken)
|
||||
: null;
|
||||
}
|
||||
|
||||
async function retrieveUserType() {
|
||||
const cookieStore = await cookies();
|
||||
const encrpytaccessObject = cookieStore.get("accessObject")?.value || "{}";
|
||||
const decrpytUserType = JSON.parse(
|
||||
(await nextCrypto.decrypt(encrpytaccessObject)) || "{}"
|
||||
);
|
||||
return decrpytUserType ? decrpytUserType : null;
|
||||
}
|
||||
|
||||
async function retrieveAccessObjects() {
|
||||
const cookieStore = await cookies();
|
||||
const encrpytAccessObject = cookieStore.get("accessObject")?.value || "";
|
||||
const decrpytAccessObject = await nextCrypto.decrypt(encrpytAccessObject);
|
||||
return decrpytAccessObject ? JSON.parse(decrpytAccessObject) : null;
|
||||
}
|
||||
|
||||
async function retrieveUserSelection() {
|
||||
const cookieStore = await cookies();
|
||||
const encrpytUserSelection = cookieStore.get("userSelection")?.value || "";
|
||||
|
||||
let objectUserSelection = {};
|
||||
let decrpytUserSelection: any = await nextCrypto.decrypt(
|
||||
encrpytUserSelection
|
||||
);
|
||||
decrpytUserSelection = decrpytUserSelection
|
||||
? JSON.parse(decrpytUserSelection)
|
||||
: null;
|
||||
console.log("decrpytUserSelection", decrpytUserSelection);
|
||||
const userSelection = decrpytUserSelection?.selected;
|
||||
const accessObjects = (await retrieveAccessObjects()) || {};
|
||||
console.log("accessObjects", accessObjects);
|
||||
|
||||
if (decrpytUserSelection?.user_type === "employee") {
|
||||
const companyList = accessObjects?.selectionList;
|
||||
const selectedCompany = companyList.find(
|
||||
(company: any) => company.uu_id === userSelection
|
||||
);
|
||||
if (selectedCompany) {
|
||||
objectUserSelection = { userType: "employee", selected: selectedCompany };
|
||||
}
|
||||
} else if (decrpytUserSelection?.user_type === "occupant") {
|
||||
const buildingsList = accessObjects?.selectionList;
|
||||
|
||||
// Iterate through all buildings
|
||||
if (buildingsList) {
|
||||
// Loop through each building
|
||||
for (const buildKey in buildingsList) {
|
||||
const building = buildingsList[buildKey];
|
||||
|
||||
// Check if the building has occupants
|
||||
if (building.occupants && building.occupants.length > 0) {
|
||||
// Find the occupant with the matching build_living_space_uu_id
|
||||
const occupant = building.occupants.find(
|
||||
(occ: any) => occ.build_living_space_uu_id === userSelection
|
||||
);
|
||||
|
||||
if (occupant) {
|
||||
objectUserSelection = {
|
||||
userType: "occupant",
|
||||
selected: {
|
||||
...occupant,
|
||||
buildName: building.build_name,
|
||||
buildNo: building.build_no,
|
||||
},
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
...objectUserSelection,
|
||||
};
|
||||
}
|
||||
|
||||
// const avatarInfo = await retrieveAvatarInfo();
|
||||
// lang: avatarInfo?.data?.lang
|
||||
// ? String(avatarInfo?.data?.lang).toLowerCase()
|
||||
// : undefined,
|
||||
// avatar: avatarInfo?.data?.avatar,
|
||||
// fullName: avatarInfo?.data?.full_name,
|
||||
// async function retrieveAvatarInfo() {
|
||||
// const response = await fetchDataWithToken(
|
||||
// `${baseUrlAuth}/authentication/avatar`,
|
||||
// {},
|
||||
// "POST"
|
||||
// );
|
||||
// return response;
|
||||
// }
|
||||
|
||||
export {
|
||||
checkAccessTokenIsValid,
|
||||
retrieveAccessToken,
|
||||
retrieveUserType,
|
||||
retrieveAccessObjects,
|
||||
retrieveUserSelection,
|
||||
retrieveApplicationbyUrl,
|
||||
retrievePageList,
|
||||
// retrieveavailablePages,
|
||||
};
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { retrieveUserSelection } from "@/apicalls/cookies/token";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST(): Promise<NextResponse> {
|
||||
try {
|
||||
const userSelection = await retrieveUserSelection();
|
||||
console.log("userSelection", userSelection);
|
||||
if (userSelection) {
|
||||
return NextResponse.json({
|
||||
status: 200,
|
||||
message: "User selection found",
|
||||
data: userSelection,
|
||||
});
|
||||
}
|
||||
} catch (error) {}
|
||||
return NextResponse.json({
|
||||
status: 500,
|
||||
message: "User selection not found",
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import { loginViaAccessKeys } from "@/apicalls/custom/login/login";
|
||||
import { NextResponse } from "next/server";
|
||||
import { loginSchemaEmail } from "@/webPages/auth/login/schemas";
|
||||
|
||||
export async function POST(req: Request): Promise<NextResponse> {
|
||||
try {
|
||||
const headers = req.headers;
|
||||
console.log("headers", Object.entries(headers));
|
||||
const body = await req.json();
|
||||
const dataValidated = {
|
||||
accessKey: body.email,
|
||||
password: body.password,
|
||||
rememberMe: body.rememberMe,
|
||||
};
|
||||
const validatedLoginBody = loginSchemaEmail.safeParse(body);
|
||||
if (!validatedLoginBody.success) {
|
||||
return NextResponse.json({
|
||||
status: 422,
|
||||
message: validatedLoginBody.error.message,
|
||||
});
|
||||
}
|
||||
|
||||
const userLogin = await loginViaAccessKeys(dataValidated);
|
||||
if (userLogin.status === 200 || userLogin.status === 202) {
|
||||
return NextResponse.json({
|
||||
status: 200,
|
||||
message: "Login successfully completed",
|
||||
data: userLogin.data,
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json({
|
||||
status: userLogin.status,
|
||||
message: userLogin.message,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return NextResponse.json({ status: 401, message: "Invalid credentials" });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import { z } from "zod";
|
||||
import { loginSelectEmployee } from "@/apicalls/custom/login/login";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
const loginSchemaEmployee = z.object({
|
||||
company_uu_id: z.string(),
|
||||
});
|
||||
|
||||
export async function POST(req: Request): Promise<NextResponse> {
|
||||
try {
|
||||
const headers = req.headers;
|
||||
console.log("headers", Object.entries(headers));
|
||||
const body = await req.json();
|
||||
const dataValidated = {
|
||||
company_uu_id: body.company_uu_id,
|
||||
};
|
||||
const validatedLoginBody = loginSchemaEmployee.safeParse(body);
|
||||
if (!validatedLoginBody.success) {
|
||||
return NextResponse.json({
|
||||
status: 422,
|
||||
message: validatedLoginBody.error.message,
|
||||
});
|
||||
}
|
||||
|
||||
const userLogin = await loginSelectEmployee(dataValidated);
|
||||
if (userLogin.status === 200 || userLogin.status === 202) {
|
||||
return NextResponse.json({
|
||||
status: 200,
|
||||
message: "Selection successfully completed",
|
||||
data: userLogin.data,
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json({
|
||||
status: userLogin.status,
|
||||
message: userLogin.message,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return NextResponse.json({ status: 401, message: "Invalid credentials" });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import { z } from "zod";
|
||||
import { loginSelectOccupant } from "@/apicalls/custom/login/login";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
const loginSchemaOccupant = z.object({
|
||||
build_living_space_uu_id: z.string(),
|
||||
});
|
||||
|
||||
export async function POST(req: Request): Promise<NextResponse> {
|
||||
try {
|
||||
const headers = req.headers;
|
||||
console.log("headers", Object.entries(headers));
|
||||
const body = await req.json();
|
||||
const dataValidated = {
|
||||
build_living_space_uu_id: body.build_living_space_uu_id,
|
||||
};
|
||||
const validatedLoginBody = loginSchemaOccupant.safeParse(body);
|
||||
if (!validatedLoginBody.success) {
|
||||
return NextResponse.json({
|
||||
status: 422,
|
||||
message: validatedLoginBody.error.message,
|
||||
});
|
||||
}
|
||||
|
||||
const userLogin = await loginSelectOccupant(dataValidated);
|
||||
if (userLogin.status === 200 || userLogin.status === 202) {
|
||||
return NextResponse.json({
|
||||
status: 200,
|
||||
message: "Selection successfully completed",
|
||||
data: userLogin.data,
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json({
|
||||
status: userLogin.status,
|
||||
message: userLogin.message,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return NextResponse.json({ status: 401, message: "Invalid credentials" });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
'use server';
|
||||
import { AuthLayout } from "@/layouts/auth/layout";
|
||||
import { AuthServerProps } from "@/validations/mutual/pages/props";
|
||||
import getPage from "@/webPages/getPage";
|
||||
|
||||
const AuthPageEn = async ({ params, searchParams }: AuthServerProps) => {
|
||||
const lang = "en";
|
||||
const awaitedParams = await params;
|
||||
const awaitedSearchParams = await searchParams;
|
||||
const pageUrlFromParams = `/${awaitedParams.page?.join("/")}` || "/login";
|
||||
const FoundPage = getPage(pageUrlFromParams, { language: lang, query: awaitedSearchParams });
|
||||
return <AuthLayout lang={lang} page={FoundPage} activePageUrl={pageUrlFromParams} />
|
||||
}
|
||||
|
||||
export default AuthPageEn;
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
'use server';
|
||||
import { AuthServerProps } from "@/validations/mutual/pages/props";
|
||||
import { AuthLayout } from "@/layouts/auth/layout";
|
||||
import getPage from "@/webPages/getPage";
|
||||
|
||||
const AuthPageTr = async ({ params, searchParams }: AuthServerProps) => {
|
||||
const lang = "tr";
|
||||
const awaitedParams = await params;
|
||||
const awaitedSearchParams = await searchParams;
|
||||
const pageUrlFromParams = `/${awaitedParams.page?.join("/")}` || "/login";
|
||||
const FoundPage = getPage(pageUrlFromParams, { language: lang, query: awaitedSearchParams });
|
||||
return <AuthLayout lang={lang} page={FoundPage} activePageUrl={pageUrlFromParams} />
|
||||
}
|
||||
|
||||
export default AuthPageTr;
|
||||
|
|
@ -4,7 +4,7 @@ import { HeaderProps } from "@/validations/mutual/dashboard/props";
|
|||
import LanguageSelectionComponent from "@/components/mutual/languageSelection/component";
|
||||
import { langGetKey } from "@/lib/langGet";
|
||||
|
||||
const HeaderComponent: FC<HeaderProps> = ({ translations, lang, activePageUrl }) => {
|
||||
const HeaderComponent: FC<HeaderProps> = ({ translations, lang, activePageUrl, prefix }) => {
|
||||
|
||||
return (
|
||||
<div className="flex justify-between h-24 items-center p-4 border-emerald-150 border-b-2 shadow-sm backdrop-blur-sm sticky top-0 z-50 bg-emerald-50">
|
||||
|
|
@ -12,7 +12,7 @@ const HeaderComponent: FC<HeaderProps> = ({ translations, lang, activePageUrl })
|
|||
<p className="text-2xl font-bold mx-3">{langGetKey(translations, 'selectedPage')} :</p>
|
||||
<p className="text-lg font-bold mx-3"> {langGetKey(translations, 'page')}</p>
|
||||
</div>
|
||||
<LanguageSelectionComponent lang={lang} activePage={activePageUrl} />
|
||||
<LanguageSelectionComponent lang={lang} activePage={activePageUrl} prefix={prefix} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -6,18 +6,20 @@ import { MenuSingleProps, SingleLayerItemProps } from "@/validations/mutual/dash
|
|||
import { langGetKey } from "@/lib/langGet";
|
||||
|
||||
const SingleLayerItem: FC<SingleLayerItemProps> = ({ isActive, innerText, url }) => {
|
||||
console.log({ isActive, innerText, url })
|
||||
let className = "py-3 px-4 text-sm rounded-xl cursor-pointer transition-colors duration-200 flex justify-between items-center w-full";
|
||||
if (isActive) { className += " bg-emerald-700 text-white font-medium" }
|
||||
if (isActive) { className += " bg-black text-white font-medium" }
|
||||
else { className += " bg-emerald-800 text-white hover:bg-emerald-700" }
|
||||
return <Link href={url} replace className={className}><span>{innerText}</span></Link>
|
||||
if (isActive) { return <div className={className}><span>{innerText}</span></div> }
|
||||
else { return <Link href={url} replace className={className}><span>{innerText}</span></Link> }
|
||||
};
|
||||
|
||||
const MenuComponent: FC<MenuSingleProps> = ({ lang, activePageUrl, translations, menuItems }) => {
|
||||
const MenuComponent: FC<MenuSingleProps> = ({ lang, activePageUrl, translations, menuItems, prefix }) => {
|
||||
|
||||
const renderMenuItems = () => {
|
||||
return menuItems.map((key) => {
|
||||
const url = `/${lang}/${key}`;
|
||||
const isActive = activePageUrl === key;
|
||||
return Object.keys(menuItems).map((key) => {
|
||||
const url = `${prefix}/${lang}${menuItems[key]}`;
|
||||
const isActive = `${activePageUrl}` === `${key}`;
|
||||
return <div key={`${key}-item`} className="mb-2"><SingleLayerItem isActive={isActive} innerText={langGetKey(translations, key)} url={url} /></div>
|
||||
});
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,9 +7,9 @@ import { LanguageTypes } from "@/validations/mutual/language/validations";
|
|||
|
||||
import LanguageSelectionItem from "./languageItem";
|
||||
|
||||
const LanguageSelectionComponent: React.FC<{ lang: LanguageTypes, activePage: string }> = ({ lang, activePage }) => {
|
||||
const LanguageSelectionComponent: React.FC<{ lang: LanguageTypes, activePage: string, prefix: string }> = ({ lang, activePage, prefix }) => {
|
||||
const translations = langGet(lang, languageSelectionTranslation);
|
||||
const getPageWithLocale = (locale: LanguageTypes): string => { return `/${locale}/${activePage}` }
|
||||
const getPageWithLocale = (locale: LanguageTypes): string => { return `${prefix}/${locale}/${activePage}` }
|
||||
|
||||
const englishButtonProps = {
|
||||
activeLang: lang,
|
||||
|
|
@ -30,8 +30,7 @@ const LanguageSelectionComponent: React.FC<{ lang: LanguageTypes, activePage: st
|
|||
<DropdownMenuTrigger asChild>
|
||||
<Button className="w-48 h-12 text-center text-md">{langGetKey(translations, "title")}</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<LanguageSelectionItem {...englishButtonProps} />
|
||||
<LanguageSelectionItem {...turkishButtonProps} />
|
||||
<LanguageSelectionItem {...englishButtonProps} /><LanguageSelectionItem {...turkishButtonProps} />
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { managementAccountTenantMain } from "./management/account/tenantSomethin
|
|||
import { managementAccountTenantMainSecond } from "./management/account/tenantSomethingSecond/index";
|
||||
|
||||
const dynamicPagesIndex: Record<string, Record<LanguageTypes, DynamicPage>> = {
|
||||
dashboard: managementAccountTenantMain,
|
||||
application: managementAccountTenantMain,
|
||||
services: managementAccountTenantMainSecond,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
'use server';
|
||||
import { FC, Suspense } from "react";
|
||||
import { AuthLayoutProps } from "@/validations/mutual/auth/props";
|
||||
import LanguageSelectionComponent from "@/components/mutual/languageSelection/component";
|
||||
|
||||
const AuthLayout: FC<AuthLayoutProps> = async ({ lang, page, activePageUrl }) => {
|
||||
return (
|
||||
<div className="min-h-screen min-w-screen flex h-screen w-screen overflow-hidden">
|
||||
<div className="w-1/4">
|
||||
<div className="flex flex-col items-center justify-center h-screen bg-purple-600">
|
||||
<div className="text-2xl font-bold">WAG Frontend</div>
|
||||
<div className="text-sm text-gray-500 mt-4">Welcome to the WAG Frontend Application</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-3/4 text-black">
|
||||
<LanguageSelectionComponent lang={lang} activePage={activePageUrl} prefix={"/auth"} />
|
||||
<Suspense fallback={<div>Loading...</div>}>{page}</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { AuthLayout };
|
||||
|
|
@ -10,12 +10,31 @@ import ContentComponent from "@/components/custom/content/component";
|
|||
import FooterComponent from "@/components/custom/footer/component";
|
||||
import { menuTranslation } from "@/languages/mutual/menu";
|
||||
|
||||
const menuTranslations = {
|
||||
en: {
|
||||
"dashboard": "Dashboard",
|
||||
"application": "Application",
|
||||
"services": "Services",
|
||||
},
|
||||
tr: {
|
||||
"dashboard": "Panel",
|
||||
"application": "Uygulama",
|
||||
"services": "Servisler",
|
||||
},
|
||||
}
|
||||
|
||||
const menuUrlIndex = {
|
||||
dashboard: "/dashboard",
|
||||
application: "/application",
|
||||
services: "/services",
|
||||
}
|
||||
|
||||
const DashboardLayout: FC<DashboardLayoutProps> = async ({ params, searchParams, lang }) => {
|
||||
const activePageUrl = `/${lang}/${params?.page?.join("/")}`;
|
||||
const activePageUrl = `${params?.page?.join("/")}`;
|
||||
const mode = (searchParams?.mode as ModeTypes) || 'shortList';
|
||||
const translations = langGet(lang, langDynamicPagesGet(activePageUrl, dynamicPagesIndex));
|
||||
const headerProps = { translations: translations.header, lang, activePageUrl }
|
||||
const menuProps = { lang, activePageUrl, translations: menuTranslation[lang], menuItems: Object.keys(translations.menu) }
|
||||
const headerProps = { translations: translations.header, lang, activePageUrl, prefix: "/panel" }
|
||||
const menuProps = { lang, activePageUrl, translations: menuTranslations[lang], menuItems: menuUrlIndex, prefix: "/panel" }
|
||||
const contentProps = { translations: translations.content, lang, activePageUrl, mode, isMulti: false }
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -5,12 +5,12 @@ import { ContentProps } from "@/validations/mutual/dashboard/props";
|
|||
|
||||
import pageIndexMulti from "@/pages/multi/index";
|
||||
import pageIndexSingle from "@/pages/single/index";
|
||||
import ContentToRenderNoPage from "@/pages/mutual/noContent/page";
|
||||
|
||||
function resolveWhichPageToRenderSingle({
|
||||
activePageUrl,
|
||||
}: ResolverProps): React.FC<ContentProps> {
|
||||
const ApplicationToRender = pageIndexSingle[activePageUrl]
|
||||
return ApplicationToRender
|
||||
return activePageUrl in pageIndexSingle ? pageIndexSingle[activePageUrl] : ContentToRenderNoPage
|
||||
}
|
||||
|
||||
async function resolveWhichPageToRenderMulti({
|
||||
|
|
@ -23,7 +23,7 @@ async function resolveWhichPageToRenderMulti({
|
|||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
return null
|
||||
return ContentToRenderNoPage
|
||||
}
|
||||
|
||||
export { resolveWhichPageToRenderSingle, resolveWhichPageToRenderMulti };
|
||||
|
|
|
|||
|
|
@ -4,9 +4,9 @@ import superUserTenantSomethingSecond from "./management/account/tenantSomething
|
|||
import superUserBuildingPartsTenantSomething from "./building/parts/tenantSomething/page";
|
||||
|
||||
const pageIndexSingle: Record<string, React.FC<ContentProps>> = {
|
||||
"management/account/tenant/something": superUserTenantSomething,
|
||||
"management/account/tenant/somethingSecond": superUserTenantSomethingSecond,
|
||||
"building/parts/tenant/something": superUserBuildingPartsTenantSomething,
|
||||
dashboard: superUserTenantSomething,
|
||||
application: superUserTenantSomethingSecond,
|
||||
service: superUserBuildingPartsTenantSomething,
|
||||
};
|
||||
|
||||
export default pageIndexSingle;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,13 @@
|
|||
import { LanguageTypes } from "../language/validations";
|
||||
|
||||
// <AuthLayout params={params} searchParams={searchParams} lang={lang} page={page} />
|
||||
interface AuthLayoutProps {
|
||||
page: React.ReactNode;
|
||||
lang: LanguageTypes;
|
||||
activePageUrl: string;
|
||||
}
|
||||
interface AuthPageProps {
|
||||
query?: { [key: string]: string | string[] | undefined };
|
||||
language: LanguageTypes;
|
||||
}
|
||||
export type { AuthLayoutProps, AuthPageProps };
|
||||
|
|
@ -35,7 +35,8 @@ interface MenuSingleProps {
|
|||
lang: LanguageTypes;
|
||||
activePageUrl: string;
|
||||
translations: Record<string, any>;
|
||||
menuItems: string[];
|
||||
menuItems: Record<string, string>;
|
||||
prefix: string;
|
||||
}
|
||||
|
||||
interface FooterProps {
|
||||
|
|
@ -46,6 +47,7 @@ interface HeaderProps {
|
|||
translations: Record<string, string>;
|
||||
lang: LanguageTypes;
|
||||
activePageUrl: string;
|
||||
prefix: string;
|
||||
}
|
||||
|
||||
interface SingleLayerItemProps {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,7 @@
|
|||
type ParamsType = { page: string[] | undefined };
|
||||
interface AuthServerProps {
|
||||
params: Promise<{ page: string[] | undefined }>;
|
||||
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
|
||||
}
|
||||
|
||||
export type { ParamsType, AuthServerProps };
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import { LanguageTypes } from "@/validations/mutual/language/validations";
|
||||
|
||||
export function loginHook(
|
||||
startTransition: any,
|
||||
data: any,
|
||||
setError: any,
|
||||
setJsonText: any,
|
||||
Router: any,
|
||||
lang: LanguageTypes
|
||||
) {
|
||||
try {
|
||||
const sendData = { ...data };
|
||||
startTransition(() => {
|
||||
fetch("/api/login/email", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(sendData),
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.status === 200) {
|
||||
response.json().then((data) => {
|
||||
console.log("data", data); // setJsonText(JSON.stringify(data));
|
||||
setTimeout(() => {
|
||||
const userType =
|
||||
data?.data?.user_type.toLowerCase() === "employee"
|
||||
? "employee"
|
||||
: "occupant";
|
||||
const rediretUrl = `/auth/${lang}/select?type=${userType}`;
|
||||
console.log("rediretUrl", rediretUrl);
|
||||
Router.push(rediretUrl);
|
||||
}, 100);
|
||||
});
|
||||
} else {
|
||||
response.json().then((data) => {
|
||||
setError(data?.message);
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
} catch (error) {
|
||||
setError("An error occurred during login");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
export const loginTranslation = {
|
||||
tr: {
|
||||
email: "E-Posta",
|
||||
password: "Şifre",
|
||||
rememberMe: "Beni Hatırla",
|
||||
login: "Giriş Yap",
|
||||
successMessage: "Giriş Yapıldı",
|
||||
errorMessage: "Giriş Yapılmadı",
|
||||
pendingMessage: "Giriş Yapılıyor...",
|
||||
responseData: "Giriş Verileri",
|
||||
},
|
||||
en: {
|
||||
email: "Email",
|
||||
password: "Password",
|
||||
rememberMe: "Remember Me",
|
||||
login: "Login",
|
||||
successMessage: "Login completed successfully",
|
||||
errorMessage: "Login failed",
|
||||
pendingMessage: "Logging in...",
|
||||
responseData: "Response Data",
|
||||
},
|
||||
};
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
"use client";
|
||||
import { useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { LoginFormData } from "./types";
|
||||
import { loginSchemaEmail } from "./schemas";
|
||||
import { loginTranslation } from "./language";
|
||||
import { loginHook } from "./hook";
|
||||
import { AuthPageProps } from "@/validations/mutual/auth/props";
|
||||
|
||||
function Login({ language }: AuthPageProps) {
|
||||
const Router = useRouter();
|
||||
const translation = loginTranslation[language];
|
||||
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [jsonText, setJsonText] = useState<string | null>(null);
|
||||
|
||||
const { register, formState: { errors }, handleSubmit, } = useForm<LoginFormData>({ resolver: zodResolver(loginSchemaEmail) });
|
||||
const onSubmit = async (data: LoginFormData) => { loginHook(startTransition, data, setError, setJsonText, Router, language) };
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-full min-h-[inherit] flex-col items-center justify-center gap-4">
|
||||
<div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
|
||||
<h2 className="mb-6 text-center text-2xl font-bold text-gray-900">{translation.login}</h2>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700">{translation.email}</label>
|
||||
<input {...register("email")} type="email" id="email" className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-indigo-500" />
|
||||
{errors.email && (<p className="mt-1 text-sm text-red-600">{errors.email.message}</p>)}
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700">{translation.password}</label>
|
||||
<input {...register("password")} type="password" id="password" className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-indigo-500" />
|
||||
{errors.password && (<p className="mt-1 text-sm text-red-600">{errors.password.message}</p>)}
|
||||
</div>
|
||||
{error && (<div className="rounded-md bg-red-50 p-4"><p className="text-sm text-red-700">{error}</p></div>)}
|
||||
<button type="submit" disabled={isPending} className="w-full rounded-md bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50">
|
||||
{isPending ? translation.pendingMessage : translation.login}</button>
|
||||
</form>
|
||||
</div>
|
||||
{jsonText && (
|
||||
<div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
|
||||
<h2 className="mb-4 text-center text-xl font-bold text-gray-900">{translation.responseData}</h2>
|
||||
<div className="space-y-2">
|
||||
{Object.entries(JSON.parse(jsonText)).map(([key, value]) => (
|
||||
<div key={key} className="flex items-start gap-2">
|
||||
<strong className="text-gray-700">{key}:</strong>
|
||||
<span className="text-gray-600">{typeof value === "object" ? JSON.stringify(value) : value?.toString() || "N/A"}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default Login;
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { z } from "zod";
|
||||
|
||||
const loginSchemaEmail = z.object({
|
||||
email: z.string().email("Invalid email address"),
|
||||
password: z.string().min(5, "Password must be at least 5 characters"),
|
||||
rememberMe: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
const loginSchemaPhone = z.object({
|
||||
phone: z.string().regex(/^[0-9]{10}$/, "Invalid phone number"),
|
||||
password: z.string().min(5, "Password must be at least 5 characters"),
|
||||
rememberMe: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
export { loginSchemaEmail, loginSchemaPhone };
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
'use server';
|
||||
import Login from "./page";
|
||||
import { FC } from "react";
|
||||
import { AuthPageProps } from "@/validations/mutual/auth/props";
|
||||
|
||||
const LoginPage: FC<AuthPageProps> = async ({ query, language }) => { return <Login language={language} query={query} /> };
|
||||
|
||||
export default LoginPage;
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
type LoginFormData = {
|
||||
email: string;
|
||||
password: string;
|
||||
rememberMe?: boolean;
|
||||
};
|
||||
|
||||
type LoginFormDataPhone = {
|
||||
phone: string;
|
||||
password: string;
|
||||
rememberMe?: boolean;
|
||||
};
|
||||
|
||||
export type { LoginFormData, LoginFormDataPhone };
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
"use client";
|
||||
import React, { useTransition, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Company } from "./types";
|
||||
import { LoginEmployeeProps } from "./types";
|
||||
import { selectEmployeeHook } from "./hook";
|
||||
|
||||
function LoginEmployee({
|
||||
selectionList,
|
||||
translation,
|
||||
lang
|
||||
}: LoginEmployeeProps) {
|
||||
const isArrayLengthOne = Array.isArray(selectionList) && selectionList.length === 1;
|
||||
const isArrayLengthZero = Array.isArray(selectionList) && selectionList.length === 0;
|
||||
const isArrayMoreThanOne = Array.isArray(selectionList) && selectionList.length > 1;
|
||||
const Router = useRouter();
|
||||
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [jsonText, setJsonText] = useState<string | null>(null);
|
||||
|
||||
const onSubmitEmployee = async (uu_id: string) => {
|
||||
selectEmployeeHook(startTransition, { company_uu_id: uu_id }, setError, setJsonText, Router, lang)
|
||||
};
|
||||
|
||||
// Render a company card with consistent styling
|
||||
const CompanyCard = ({ company, showButton = false }: { company: Company, showButton?: boolean }) => (
|
||||
<div className="w-full p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-all">
|
||||
<div className="flex flex-col" onClick={() => onSubmitEmployee(company.uu_id)}>
|
||||
{/* Company name and type */}
|
||||
<div className="flex items-center mb-2">
|
||||
<h3 className="text-xl font-semibold text-gray-800">{company.public_name}</h3>
|
||||
{company.company_type && (
|
||||
<span className="ml-2 px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded-full">
|
||||
{company.company_type}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Duty information */}
|
||||
{company.duty && (
|
||||
<div className="mb-2 text-sm text-gray-600">
|
||||
<span className="font-medium">{translation.duty}:</span> {company.duty}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ID information */}
|
||||
<div className="text-xs text-gray-500 mb-3">
|
||||
<span className="font-medium">{translation.id}:</span> {company.uu_id}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-md mx-auto">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-2">{translation.companySelection}</h1>
|
||||
<p className="text-sm text-gray-500 mb-6">{translation.loggedInAs}</p>
|
||||
|
||||
{/* No companies available */}
|
||||
{isArrayLengthZero && (
|
||||
<div className="text-center p-6 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<p className="text-gray-600">{translation.noSelections}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Single company */}
|
||||
{isArrayLengthOne && <CompanyCard company={selectionList[0]} showButton={true} />}
|
||||
|
||||
{/* Multiple companies */}
|
||||
{isArrayMoreThanOne && (
|
||||
<div className="space-y-3">
|
||||
{selectionList.map((company, index) => (
|
||||
<div
|
||||
key={company.uu_id || index}
|
||||
onClick={() => onSubmitEmployee(company.uu_id)}
|
||||
className="cursor-pointer hover:translate-x-1 transition-transform"
|
||||
>
|
||||
<CompanyCard company={company} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Show error if any */}
|
||||
{error && <p className="mt-4 text-sm text-red-600">{error}</p>}
|
||||
|
||||
{/* Loading indicator */}
|
||||
{isPending && (
|
||||
<div className="mt-4 flex justify-center">
|
||||
<div className="animate-spin h-5 w-5 border-2 border-blue-600 rounded-full border-t-transparent"></div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LoginEmployee;
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
"use client";
|
||||
import React, { useState, useTransition, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { LoginOccupantProps } from "./types";
|
||||
import { selectOccupantHook } from "./hook";
|
||||
|
||||
function LoginOccupant({
|
||||
selectionList,
|
||||
translation,
|
||||
lang
|
||||
}: LoginOccupantProps) {
|
||||
|
||||
const Router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [jsonText, setJsonText] = useState<string | null>(null);
|
||||
|
||||
const onSubmitOccupant = async (data: any) => {
|
||||
selectOccupantHook(startTransition, data, setError, setJsonText, Router, lang)
|
||||
};
|
||||
const isArrayLengthZero = Array.isArray(selectionList) && selectionList.length === 0;
|
||||
|
||||
// Render an occupant card with consistent styling
|
||||
const OccupantCard = ({ occupant, buildKey, idx }: { occupant: any, buildKey: string, idx: number }) => (
|
||||
<div
|
||||
key={`${buildKey}-${idx}`}
|
||||
className="w-full p-4 mb-3 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-all cursor-pointer hover:translate-x-1"
|
||||
onClick={() => onSubmitOccupant({ build_living_space_uu_id: occupant.build_living_space_uu_id })}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
{/* Occupant description and code */}
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-lg font-semibold text-gray-800">{occupant.description}</h3>
|
||||
<span className="px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded-full">
|
||||
{occupant.code}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Part name */}
|
||||
<div className="mb-1 text-sm text-gray-700 font-medium">
|
||||
{occupant.part_name}
|
||||
</div>
|
||||
|
||||
{/* Level information */}
|
||||
<div className="text-xs text-gray-500">
|
||||
<span className="font-medium">{translation.level}:</span> {occupant.part_level}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Render a building section with its occupants
|
||||
const BuildingSection = ({ building, buildKey }: { building: any, buildKey: string }) => (
|
||||
<div key={buildKey} className="mb-6">
|
||||
<div className="p-3 bg-gray-50 border border-gray-200 rounded-lg mb-3">
|
||||
<h2 className="text-lg font-semibold text-gray-800 flex items-center">
|
||||
<svg className="w-5 h-5 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
|
||||
</svg>
|
||||
<span>{building.build_name}</span>
|
||||
<span className="ml-2 px-2 py-0.5 text-xs bg-blue-100 text-blue-800 rounded-full">No: {building.build_no}</span>
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{building.occupants.map((occupant: any, idx: number) => (
|
||||
<OccupantCard key={idx} occupant={occupant} buildKey={buildKey} idx={idx} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-md mx-auto">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-2">{translation.occupantSelection}</h1>
|
||||
<p className="text-sm text-gray-500 mb-6">{translation.loggedInAs}</p>
|
||||
|
||||
{/* No occupants available */}
|
||||
{!isArrayLengthZero ? (
|
||||
<div className="text-center p-6 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<p className="text-gray-600">{translation.noSelections}</p>
|
||||
</div>
|
||||
) : (
|
||||
/* Building sections with occupants */
|
||||
<div>
|
||||
{Object.keys(selectionList).map((buildKey: string) => (
|
||||
<BuildingSection
|
||||
key={buildKey}
|
||||
building={selectionList[buildKey]}
|
||||
buildKey={buildKey}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Show error if any */}
|
||||
{error && <p className="mt-4 text-sm text-red-600">{error}</p>}
|
||||
|
||||
{/* Loading indicator */}
|
||||
{isPending && (
|
||||
<div className="mt-4 flex justify-center">
|
||||
<div className="animate-spin h-5 w-5 border-2 border-blue-600 rounded-full border-t-transparent"></div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LoginOccupant;
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
import { apiPostFetcher } from "@/lib/fetcher";
|
||||
import { LanguageTypes } from "@/validations/mutual/language/validations";
|
||||
|
||||
function selectEmployeeHook(
|
||||
startTransition: any,
|
||||
data: any,
|
||||
setError: any,
|
||||
setJsonText: any,
|
||||
Router: any,
|
||||
lang: LanguageTypes
|
||||
) {
|
||||
try {
|
||||
const sendData = { ...data };
|
||||
const urlToDirect = `/panel/${lang}/dashboard`;
|
||||
startTransition(() => {
|
||||
apiPostFetcher({
|
||||
url: "/api/selection/employee",
|
||||
isNoCache: true,
|
||||
body: sendData,
|
||||
})
|
||||
.then((response) => {
|
||||
const data = response.data;
|
||||
if (response.success) {
|
||||
setTimeout(() => {
|
||||
Router.push(urlToDirect);
|
||||
}, 100);
|
||||
} else {
|
||||
setError(data?.message);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
} catch (error) {
|
||||
setError("An error occurred during login");
|
||||
}
|
||||
}
|
||||
|
||||
function selectOccupantHook(
|
||||
startTransition: any,
|
||||
data: any,
|
||||
setError: any,
|
||||
setJsonText: any,
|
||||
Router: any,
|
||||
lang: LanguageTypes
|
||||
) {
|
||||
try {
|
||||
const sendData = { ...data };
|
||||
const urlToDirect = `/auth/${lang}/panel/dashboard`;
|
||||
startTransition(() => {
|
||||
apiPostFetcher({
|
||||
url: "/api/selection/occupant",
|
||||
isNoCache: true,
|
||||
body: sendData,
|
||||
})
|
||||
.then((response) => {
|
||||
const data = response.data;
|
||||
if (response.success) {
|
||||
setTimeout(() => {
|
||||
Router.push(urlToDirect);
|
||||
}, 100);
|
||||
} else {
|
||||
setError(data?.message);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
} catch (error) {
|
||||
setError("An error occurred during login");
|
||||
}
|
||||
}
|
||||
|
||||
export { selectEmployeeHook, selectOccupantHook };
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
export const selectEmployeeTranslation = {
|
||||
tr: {
|
||||
companySelection: "Şirket Seçimi",
|
||||
loggedInAs: "Çalışan olarak giriş yaptınız",
|
||||
duty: "Görev",
|
||||
id: "Kimlik",
|
||||
noSelections: "Seçenek bulunamadı",
|
||||
continue: "Devam et",
|
||||
select: "Konut Seçimi",
|
||||
|
||||
},
|
||||
en: {
|
||||
companySelection: "Select your company",
|
||||
loggedInAs: "You are logged in as an employee",
|
||||
duty: "Duty",
|
||||
id: "ID",
|
||||
noSelections: "No selections available",
|
||||
continue: "Continue",
|
||||
select: "Select Occupant",
|
||||
|
||||
},
|
||||
};
|
||||
|
||||
export const selectOccupantTranslation = {
|
||||
tr: {
|
||||
occupantSelection: "Daire Seçimi",
|
||||
loggedInAs: "Kiracı olarak giriş yaptınız",
|
||||
buildingInfo: "Bina Bilgisi",
|
||||
level: "Kat",
|
||||
noSelections: "Seçenek bulunamadı",
|
||||
continue: "Devam et",
|
||||
select: "Şirket Seçimi",
|
||||
|
||||
},
|
||||
en: {
|
||||
occupantSelection: "Select your occupant type",
|
||||
loggedInAs: "You are logged in as an occupant",
|
||||
buildingInfo: "Building Info",
|
||||
level: "Level",
|
||||
continue: "Continue",
|
||||
noSelections: "No selections available",
|
||||
select: "Select Company",
|
||||
},
|
||||
};
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
"use client";
|
||||
import { useState, useEffect } from "react";
|
||||
import LoginOccupant from "./LoginOccupant";
|
||||
import LoginEmployee from "./LoginEmployee";
|
||||
|
||||
import { Company, SelectListProps, BuildingMap } from "./types";
|
||||
import { selectEmployeeTranslation, selectOccupantTranslation } from "./language";
|
||||
|
||||
const Select: React.FC<SelectListProps> = ({ selectionList, isEmployee, isOccupant, language, query }) => {
|
||||
const isEmployeee = query?.isEmployee == "true";
|
||||
const isOccupante = query?.isOccupant == "true";
|
||||
const userType = isEmployeee || isOccupante ? isEmployeee ? "employee" : "occupant" : "employee";
|
||||
|
||||
const isEmployeeTrue = userType == "employee" && Array.isArray(selectionList)
|
||||
const isOccupantTrue = userType == "occupant" && !Array.isArray(selectionList)
|
||||
const initTranslation = userType == "employee" ? selectEmployeeTranslation[language] : selectOccupantTranslation[language]
|
||||
|
||||
const [translation, setTranslation] = useState(initTranslation);
|
||||
const [listEmployeeSelection, setListEmployeeSelection] = useState<Company[]>(selectionList as Company[]);
|
||||
const [listOccupantSelection, setListOccupantSelection] = useState<BuildingMap>(selectionList as BuildingMap);
|
||||
|
||||
useEffect(() => {
|
||||
if (isEmployee) { setListEmployeeSelection(selectionList as Company[]) }
|
||||
else if (isOccupant) { setListOccupantSelection(selectionList as BuildingMap) }
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setTranslation(isEmployee ? selectEmployeeTranslation[language] : selectOccupantTranslation[language]);
|
||||
}, [language]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-full min-h-[inherit] flex-col items-center justify-center gap-4">
|
||||
<div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
|
||||
{isEmployeeTrue && <LoginEmployee translation={translation} selectionList={listEmployeeSelection} lang={language} />}
|
||||
{isOccupantTrue && <LoginOccupant translation={translation} selectionList={listOccupantSelection} lang={language} />}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default Select;
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
"use server";
|
||||
import React, { FC } from "react";
|
||||
import Select from "./page";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { checkAccessTokenIsValid, retrieveUserType } from "@/apicalls/mutual/cookies/token";
|
||||
import { AuthPageProps } from "@/validations/mutual/auth/props";
|
||||
|
||||
const SelectPage: FC<AuthPageProps> = async ({ query, language }) => {
|
||||
const token_is_valid = await checkAccessTokenIsValid();
|
||||
const selection = await retrieveUserType();
|
||||
const isEmployee = selection?.userType == "employee";
|
||||
const isOccupant = selection?.userType == "occupant";
|
||||
const selectionList = selection?.selectionList;
|
||||
|
||||
if (!selectionList || !token_is_valid) { redirect("/auth/en/login") }
|
||||
return <Select selectionList={selectionList} isEmployee={isEmployee} isOccupant={isOccupant} language={language} query={query} />
|
||||
}
|
||||
|
||||
export default SelectPage;
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
import { LanguageTypes } from "@/validations/mutual/language/validations";
|
||||
|
||||
interface Company {
|
||||
uu_id: string;
|
||||
public_name: string;
|
||||
company_type?: string;
|
||||
company_address?: any;
|
||||
duty?: string;
|
||||
}
|
||||
|
||||
interface Occupant {
|
||||
build_living_space_uu_id: string;
|
||||
part_uu_id: string;
|
||||
part_name: string;
|
||||
part_level: number;
|
||||
occupant_uu_id: string;
|
||||
description: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
interface Building {
|
||||
build_uu_id: string;
|
||||
build_name: string;
|
||||
build_no: string;
|
||||
occupants: Occupant[];
|
||||
}
|
||||
|
||||
interface BuildingMap {
|
||||
[key: string]: Building;
|
||||
}
|
||||
|
||||
interface SelectListProps {
|
||||
selectionList: Company[] | BuildingMap;
|
||||
isEmployee: boolean;
|
||||
isOccupant: boolean;
|
||||
language: LanguageTypes;
|
||||
query?: { [key: string]: string | string[] | undefined };
|
||||
}
|
||||
|
||||
interface LoginOccupantProps {
|
||||
selectionList: BuildingMap;
|
||||
translation: any;
|
||||
lang: LanguageTypes;
|
||||
}
|
||||
|
||||
interface LoginEmployeeProps {
|
||||
selectionList: Company[];
|
||||
translation: any;
|
||||
lang: LanguageTypes;
|
||||
}
|
||||
|
||||
export type {
|
||||
Company,
|
||||
Occupant,
|
||||
Building,
|
||||
BuildingMap,
|
||||
SelectListProps,
|
||||
LoginOccupantProps,
|
||||
LoginEmployeeProps,
|
||||
};
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import LoginPage from "./auth/login/serverPage";
|
||||
import SelectPage from "./auth/select/serverPage";
|
||||
|
||||
export default function getPage(pageName: string, props: any) {
|
||||
switch (pageName) {
|
||||
case "/login":
|
||||
return <LoginPage {...props} />;
|
||||
case "/select":
|
||||
return <SelectPage {...props} />;
|
||||
default:
|
||||
return <LoginPage {...props} />;
|
||||
}
|
||||
return <></>
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue