Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

BIN
apps/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EMA Backoffice</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,13 @@
{
"name": "@ema-platform/backoffice",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/backoffice/src",
"projectType": "application",
"targets": {
"serve": {
"executor": "@nx/vite:dev-server",
"options": { "buildTarget": "@ema-platform/backoffice:build" }
}
},
"tags": []
}

View File

@@ -0,0 +1,10 @@
import { AppProviders } from './providers/AppProviders';
import { AppRouter } from './router';
export function App() {
return (
<AppProviders>
<AppRouter />
</AppProviders>
);
}

View File

@@ -0,0 +1,28 @@
import { baseApi } from '@ema-platform/api';
import type { LoginPayload } from '../types/auth.types';
interface LoginArgs {
email: string;
password: string;
}
interface RefreshArgs {
refreshToken: string;
}
const authApi = baseApi.injectEndpoints({
endpoints: (builder) => ({
login: builder.mutation<LoginPayload, LoginArgs>({
query: (body) => ({ url: '/auth/login', method: 'POST', body }),
}),
refresh: builder.mutation<{ token: string }, RefreshArgs>({
query: (body) => ({ url: '/auth/refresh', method: 'POST', body }),
}),
logout: builder.mutation<{ message: string }, void>({
query: () => ({ url: '/auth/logout', method: 'POST' }),
}),
}),
overrideExisting: false,
});
export const { useLoginMutation, useRefreshMutation, useLogoutMutation } = authApi;

View File

@@ -0,0 +1,79 @@
import {
TextInput,
PasswordInput,
Button,
Stack,
Title,
Paper,
Text,
} from '@mantine/core';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useNavigate } from 'react-router-dom';
import { useLoginMutation } from '../api/auth-api';
import { useAuth } from '../hooks/useAuth';
import { notify } from '@ema-platform/ui';
const schema = z.object({
email: z.string().email('Enter a valid email'),
password: z.string().min(6, 'Password must be at least 6 characters'),
});
type FormValues = z.infer<typeof schema>;
export function LoginForm() {
const navigate = useNavigate();
const { login } = useAuth();
const [loginMutate, { isLoading }] = useLoginMutation();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(schema),
});
const onSubmit = async (values: FormValues) => {
try {
const result = await loginMutate(values).unwrap();
login(result);
navigate('/dashboard');
} catch {
notify.error('Invalid email or password');
}
};
return (
<Paper p="xl" shadow="md" radius="md">
<Stack gap="lg">
<Stack gap={4}>
<Title order={2}>Sign in</Title>
<Text c="dimmed" size="sm">
Enter your credentials to access the backoffice
</Text>
</Stack>
<form onSubmit={handleSubmit(onSubmit)}>
<Stack gap="md">
<TextInput
label="Email"
placeholder="you@example.com"
error={errors.email?.message}
{...register('email')}
/>
<PasswordInput
label="Password"
placeholder="Your password"
error={errors.password?.message}
{...register('password')}
/>
<Button type="submit" loading={isLoading} fullWidth mt="sm">
Sign in
</Button>
</Stack>
</form>
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,17 @@
import { useAppDispatch, useAppSelector } from '../../../store/hooks';
import { loginSuccess, logout as logoutAction, hydrateAuth } from '../store/auth.slice';
import type { LoginPayload } from '../types/auth.types';
export function useAuth() {
const dispatch = useAppDispatch();
const { user, token, isAuthenticated } = useAppSelector((s) => s.auth);
return {
user,
token,
isAuthenticated,
login: (payload: LoginPayload) => dispatch(loginSuccess(payload)),
logout: () => dispatch(logoutAction()),
hydrate: () => dispatch(hydrateAuth()),
};
}

View File

@@ -0,0 +1,5 @@
import { LoginForm } from '../components/LoginForm';
export function LoginPage() {
return <LoginForm />;
}

View File

@@ -0,0 +1,42 @@
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
import type { AuthState, LoginPayload } from '../types/auth.types';
import { authStorage } from '../utils/auth-storage';
const initialState: AuthState = {
user: null,
token: null,
isAuthenticated: false,
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
loginSuccess(state, action: PayloadAction<LoginPayload>) {
state.user = action.payload.user;
state.token = action.payload.token;
state.isAuthenticated = true;
authStorage.setToken(action.payload.token);
authStorage.setRefreshToken(action.payload.refreshToken);
authStorage.setUser(action.payload.user);
},
logout(state) {
state.user = null;
state.token = null;
state.isAuthenticated = false;
authStorage.clear();
},
hydrateAuth(state) {
const token = authStorage.getToken();
const user = authStorage.getUser();
if (token && user) {
state.token = token;
state.user = user;
state.isAuthenticated = true;
}
},
},
});
export const { loginSuccess, logout, hydrateAuth } = authSlice.actions;
export const authReducer = authSlice.reducer;

View File

@@ -0,0 +1,19 @@
export interface AuthUser {
id: string;
email: string;
username: string;
roles: string[];
permissions: string[];
}
export interface AuthState {
user: AuthUser | null;
token: string | null;
isAuthenticated: boolean;
}
export interface LoginPayload {
user: AuthUser;
token: string;
refreshToken: string;
}

View File

@@ -0,0 +1,28 @@
import type { AuthUser } from '../types/auth.types';
const KEYS = {
token: 'ema-backoffice-auth-token',
refreshToken: 'ema-backoffice-refresh-token',
user: 'ema-backoffice-auth-user',
} as const;
export const authStorage = {
getToken: () => localStorage.getItem(KEYS.token) ?? undefined,
setToken: (token: string) => localStorage.setItem(KEYS.token, token),
removeToken: () => localStorage.removeItem(KEYS.token),
getRefreshToken: () => localStorage.getItem(KEYS.refreshToken) ?? undefined,
setRefreshToken: (token: string) => localStorage.setItem(KEYS.refreshToken, token),
getUser: (): AuthUser | null => {
const raw = localStorage.getItem(KEYS.user);
try {
return raw ? (JSON.parse(raw) as AuthUser) : null;
} catch {
return null;
}
},
setUser: (user: AuthUser) => localStorage.setItem(KEYS.user, JSON.stringify(user)),
clear: () => Object.values(KEYS).forEach((k) => localStorage.removeItem(k)),
};

View File

@@ -0,0 +1,44 @@
import { Grid, Paper, Text, Title, Stack, Group } from '@mantine/core';
import { IconBox, IconUsers, IconActivity } from '@tabler/icons-react';
interface StatCardProps {
label: string;
value: string;
icon: React.ElementType;
color: string;
}
function StatCard({ label, value, icon: Icon, color }: StatCardProps) {
return (
<Paper p="md" shadow="sm" radius="md" withBorder>
<Group justify="space-between">
<Stack gap={4}>
<Text size="sm" c="dimmed">
{label}
</Text>
<Title order={3}>{value}</Title>
</Stack>
<Icon size={32} color={color} />
</Group>
</Paper>
);
}
export function DashboardPage() {
return (
<Stack gap="lg">
<Title order={2}>Dashboard</Title>
<Grid>
<Grid.Col span={{ base: 12, sm: 4 }}>
<StatCard label="Total Items" value="—" icon={IconBox} color="#2563eb" />
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 4 }}>
<StatCard label="Total Users" value="—" icon={IconUsers} color="#16a34a" />
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 4 }}>
<StatCard label="Activity" value="—" icon={IconActivity} color="#d97706" />
</Grid.Col>
</Grid>
</Stack>
);
}

View File

@@ -0,0 +1,39 @@
import { baseApi } from '@ema-platform/api';
export interface Item {
id: string;
name: string;
description: string | null;
status: 'DRAFT' | 'ACTIVE' | 'ARCHIVED';
createdAt: string;
}
export interface PaginatedResponse<T> {
data: T[];
total: number;
page: number;
limit: number;
}
const itemApi = baseApi.injectEndpoints({
endpoints: (builder) => ({
getItems: builder.query<PaginatedResponse<Item>, { page?: number; limit?: number }>({
query: ({ page = 1, limit = 20 } = {}) => ({
url: '/items',
params: { page, limit },
}),
providesTags: ['Api'],
}),
createItem: builder.mutation<Item, { name: string; description?: string }>({
query: (body) => ({ url: '/items', method: 'POST', body }),
invalidatesTags: ['Api'],
}),
deleteItem: builder.mutation<void, string>({
query: (id) => ({ url: `/items/${id}`, method: 'DELETE' }),
invalidatesTags: ['Api'],
}),
}),
overrideExisting: false,
});
export const { useGetItemsQuery, useCreateItemMutation, useDeleteItemMutation } = itemApi;

View File

@@ -0,0 +1,60 @@
import { Table, Badge, ActionIcon, Text } from '@mantine/core';
import { IconTrash } from '@tabler/icons-react';
import { useGetItemsQuery, useDeleteItemMutation, type Item } from '../api/item-api';
import { notify } from '@ema-platform/ui';
const STATUS_COLORS: Record<Item['status'], string> = {
DRAFT: 'gray',
ACTIVE: 'green',
ARCHIVED: 'orange',
};
export function ItemTable() {
const { data, isLoading } = useGetItemsQuery({});
const [deleteItem] = useDeleteItemMutation();
const handleDelete = async (id: string) => {
try {
await deleteItem(id).unwrap();
notify.success('Item deleted');
} catch {
notify.error('Failed to delete item');
}
};
if (isLoading) return <Text>Loading...</Text>;
if (!data?.data.length) return <Text c="dimmed">No items found.</Text>;
return (
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>Name</Table.Th>
<Table.Th>Status</Table.Th>
<Table.Th>Created</Table.Th>
<Table.Th />
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data.data.map((item) => (
<Table.Tr key={item.id}>
<Table.Td>{item.name}</Table.Td>
<Table.Td>
<Badge color={STATUS_COLORS[item.status]}>{item.status}</Badge>
</Table.Td>
<Table.Td>{new Date(item.createdAt).toLocaleDateString()}</Table.Td>
<Table.Td>
<ActionIcon
color="red"
variant="subtle"
onClick={() => handleDelete(item.id)}
>
<IconTrash size={16} />
</ActionIcon>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
);
}

View File

@@ -0,0 +1,13 @@
import { Stack, Title, Paper } from '@mantine/core';
import { ItemTable } from '../components/ItemTable';
export function ItemPage() {
return (
<Stack gap="lg">
<Title order={2}>Items</Title>
<Paper p="md" shadow="sm" radius="md" withBorder>
<ItemTable />
</Paper>
</Stack>
);
}

View File

@@ -0,0 +1,12 @@
import { Center, Box } from '@mantine/core';
import { Outlet } from 'react-router-dom';
export function AuthLayout() {
return (
<Center h="100vh" bg="gray.0">
<Box w={420}>
<Outlet />
</Box>
</Center>
);
}

View File

@@ -0,0 +1,27 @@
import { AppShell } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { Outlet } from 'react-router-dom';
import { AppHeader } from './components/AppHeader';
import { AppSidebar } from './components/AppSidebar';
export function BackofficeLayout() {
const [opened, { toggle }] = useDisclosure();
return (
<AppShell
header={{ height: 60 }}
navbar={{ width: 240, breakpoint: 'sm', collapsed: { mobile: !opened } }}
padding="md"
>
<AppShell.Header>
<AppHeader onToggle={toggle} />
</AppShell.Header>
<AppShell.Navbar>
<AppSidebar />
</AppShell.Navbar>
<AppShell.Main>
<Outlet />
</AppShell.Main>
</AppShell>
);
}

View File

@@ -0,0 +1,32 @@
import { Group, Text, ActionIcon, Burger } from '@mantine/core';
import { IconLogout } from '@tabler/icons-react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../features/auth/hooks/useAuth';
interface AppHeaderProps {
onToggle: () => void;
}
export function AppHeader({ onToggle }: AppHeaderProps) {
const { logout } = useAuth();
const navigate = useNavigate();
const handleLogout = () => {
logout();
navigate('/login');
};
return (
<Group h="100%" px="md" justify="space-between">
<Group>
<Burger onClick={onToggle} size="sm" hiddenFrom="sm" />
<Text fw={700} size="lg">
EMA Backoffice
</Text>
</Group>
<ActionIcon variant="subtle" onClick={handleLogout} title="Logout">
<IconLogout size={18} />
</ActionIcon>
</Group>
);
}

View File

@@ -0,0 +1,27 @@
import { NavLink, Stack } from '@mantine/core';
import { IconDashboard, IconBox } from '@tabler/icons-react';
import { useNavigate, useLocation } from 'react-router-dom';
const NAV_ITEMS = [
{ label: 'Dashboard', icon: IconDashboard, path: '/dashboard' },
{ label: 'Items', icon: IconBox, path: '/items' },
];
export function AppSidebar() {
const navigate = useNavigate();
const { pathname } = useLocation();
return (
<Stack p="xs" gap={4}>
{NAV_ITEMS.map(({ label, icon: Icon, path }) => (
<NavLink
key={path}
label={label}
leftSection={<Icon size={18} />}
active={pathname.startsWith(path)}
onClick={() => navigate(path)}
/>
))}
</Stack>
);
}

View File

@@ -0,0 +1,21 @@
import { Provider } from 'react-redux';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react';
import { store } from '../store';
import { MantineThemeProvider } from './MantineThemeProvider';
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: 1, staleTime: 1000 * 60 * 5 },
},
});
export function AppProviders({ children }: { children: ReactNode }) {
return (
<Provider store={store}>
<QueryClientProvider client={queryClient}>
<MantineThemeProvider>{children}</MantineThemeProvider>
</QueryClientProvider>
</Provider>
);
}

View File

@@ -0,0 +1,13 @@
import { MantineProvider } from '@mantine/core';
import { Notifications } from '@mantine/notifications';
import { emaTheme } from '@ema-platform/shared';
import type { ReactNode } from 'react';
export function MantineThemeProvider({ children }: { children: ReactNode }) {
return (
<MantineProvider theme={emaTheme}>
<Notifications position="top-right" />
{children}
</MantineProvider>
);
}

View File

@@ -0,0 +1,13 @@
import { Navigate, Outlet } from 'react-router-dom';
function getTokenFromCookie(): string | undefined {
const match = document.cookie.match(/(?:^|;\s*)auth-token=([^;]*)/);
return match ? decodeURIComponent(match[1]) : undefined;
}
export function ProtectedRoute() {
const token =
localStorage.getItem('ema-backoffice-auth-token') ?? getTokenFromCookie();
if (!token) return <Navigate to="/login" replace />;
return <Outlet />;
}

View File

@@ -0,0 +1,33 @@
import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom';
import { ProtectedRoute } from './ProtectedRoute';
import { BackofficeLayout } from '../layouts/BackofficeLayout';
import { AuthLayout } from '../layouts/AuthLayout';
import { LoginPage } from '../features/auth/pages/LoginPage';
import { DashboardPage } from '../features/dashboard/pages/DashboardPage';
import { ItemPage } from '../features/item/pages/ItemPage';
const router = createBrowserRouter([
{
element: <ProtectedRoute />,
children: [
{
element: <BackofficeLayout />,
children: [
{ path: '/', element: <Navigate to="/dashboard" replace /> },
{ path: '/dashboard', element: <DashboardPage /> },
{ path: '/items', element: <ItemPage /> },
],
},
],
},
{
element: <AuthLayout />,
children: [{ path: '/login', element: <LoginPage /> }],
},
{ path: '/404', element: <div>Page not found</div> },
{ path: '*', element: <Navigate to="/404" replace /> },
]);
export function AppRouter() {
return <RouterProvider router={router} />;
}

View File

@@ -0,0 +1,6 @@
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './index';
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector = <T>(selector: (state: RootState) => T) =>
useSelector(selector);

View File

@@ -0,0 +1,15 @@
import { configureStore } from '@reduxjs/toolkit';
import { baseApi } from '@ema-platform/api';
import { authReducer } from '../features/auth/store/auth.slice';
export const store = configureStore({
reducer: {
auth: authReducer,
[baseApi.reducerPath]: baseApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(baseApi.middleware),
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

View File

@@ -0,0 +1,16 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import '@mantine/core/styles.css';
import '@mantine/notifications/styles.css';
import '@mantine/dates/styles.css';
import './styles.css';
import { App } from './app/app';
const root = document.getElementById('root');
if (!root) throw new Error('Root element not found');
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);

View File

@@ -0,0 +1,6 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
*, *::before, *::after { box-sizing: border-box; }

View File

@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc/apps/backoffice",
"types": ["vite/client", "node"]
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.d.ts"]
}

View File

@@ -0,0 +1,22 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
export default defineConfig({
root: __dirname,
cacheDir: '../../node_modules/.vite/apps/backoffice',
server: {
port: 4201,
host: 'localhost',
},
preview: { port: 4201, host: 'localhost' },
plugins: [react(), nxViteTsPaths()],
resolve: {
dedupe: ['react', 'react-dom', 'react-router-dom', '@tanstack/react-query'],
},
build: {
outDir: '../../dist/apps/backoffice',
emptyOutDir: true,
reportCompressedSize: true,
},
});

12
apps/portal/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EMA Portal</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

13
apps/portal/project.json Normal file
View File

@@ -0,0 +1,13 @@
{
"name": "@ema-platform/portal",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/portal/src",
"projectType": "application",
"targets": {
"serve": {
"executor": "@nx/vite:dev-server",
"options": { "buildTarget": "@ema-platform/portal:build" }
}
},
"tags": []
}

View File

@@ -0,0 +1,10 @@
import { AppProviders } from './providers/AppProviders';
import { AppRouter } from './router';
export function App() {
return (
<AppProviders>
<AppRouter />
</AppProviders>
);
}

View File

@@ -0,0 +1,17 @@
import { useAppDispatch, useAppSelector } from '../../../store/hooks';
import { loginSuccess, logout as logoutAction, hydrateAuth } from '../store/auth.slice';
import type { LoginPayload } from '../types/auth.types';
export function useAuth() {
const dispatch = useAppDispatch();
const { user, token, isAuthenticated } = useAppSelector((s) => s.auth);
return {
user,
token,
isAuthenticated,
login: (p: LoginPayload) => dispatch(loginSuccess(p)),
logout: () => dispatch(logoutAction()),
hydrate: () => dispatch(hydrateAuth()),
};
}

View File

@@ -0,0 +1,89 @@
import { useState } from 'react';
import {
Paper,
TextInput,
PasswordInput,
Button,
Stack,
Title,
Center,
} from '@mantine/core';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import { notify } from '@ema-platform/ui';
const BASE_API_URL =
(import.meta as { env?: Record<string, string> }).env?.['VITE_BASE_API_URL'] ??
'http://localhost:3000';
const schema = z.object({
email: z.string().email('Enter a valid email'),
password: z.string().min(6, 'Password must be at least 6 characters'),
});
type FormValues = z.infer<typeof schema>;
export function LoginPage() {
const navigate = useNavigate();
const { login } = useAuth();
const [isLoading, setIsLoading] = useState(false);
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(schema),
});
const onSubmit = async (values: FormValues) => {
setIsLoading(true);
try {
const res = await fetch(`${BASE_API_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values),
});
if (!res.ok) throw new Error('Login failed');
const data = (await res.json()) as Parameters<typeof login>[0];
login(data);
navigate('/dashboard');
} catch {
notify.error('Invalid email or password');
} finally {
setIsLoading(false);
}
};
return (
<Center h="100vh">
<Paper p="xl" shadow="md" radius="md" w={400}>
<Stack gap="md">
<Title order={3}>Sign in to Portal</Title>
<form onSubmit={handleSubmit(onSubmit)}>
<Stack gap="sm">
<TextInput
label="Email"
placeholder="you@example.com"
error={errors.email?.message}
{...register('email')}
/>
<PasswordInput
label="Password"
placeholder="Your password"
error={errors.password?.message}
{...register('password')}
/>
<Button type="submit" loading={isLoading} fullWidth mt="sm">
Sign in
</Button>
</Stack>
</form>
</Stack>
</Paper>
</Center>
);
}

View File

@@ -0,0 +1,42 @@
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
import type { AuthState, LoginPayload } from '../types/auth.types';
import { authStorage } from '../utils/auth-storage';
const initialState: AuthState = {
user: null,
token: null,
isAuthenticated: false,
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
loginSuccess(state, action: PayloadAction<LoginPayload>) {
state.user = action.payload.user;
state.token = action.payload.token;
state.isAuthenticated = true;
authStorage.setToken(action.payload.token);
authStorage.setRefreshToken(action.payload.refreshToken);
authStorage.setUser(action.payload.user);
},
logout(state) {
state.user = null;
state.token = null;
state.isAuthenticated = false;
authStorage.clear();
},
hydrateAuth(state) {
const token = authStorage.getToken();
const user = authStorage.getUser();
if (token && user) {
state.token = token;
state.user = user;
state.isAuthenticated = true;
}
},
},
});
export const { loginSuccess, logout, hydrateAuth } = authSlice.actions;
export const authReducer = authSlice.reducer;

View File

@@ -0,0 +1,19 @@
export interface AuthUser {
id: string;
email: string;
username: string;
roles: string[];
permissions: string[];
}
export interface AuthState {
user: AuthUser | null;
token: string | null;
isAuthenticated: boolean;
}
export interface LoginPayload {
user: AuthUser;
token: string;
refreshToken: string;
}

View File

@@ -0,0 +1,23 @@
import type { AuthUser } from '../types/auth.types';
const KEYS = {
token: 'ema-portal-auth-token',
refreshToken: 'ema-portal-refresh-token',
user: 'ema-portal-auth-user',
} as const;
export const authStorage = {
getToken: () => localStorage.getItem(KEYS.token) ?? undefined,
setToken: (token: string) => localStorage.setItem(KEYS.token, token),
getRefreshToken: () => localStorage.getItem(KEYS.refreshToken) ?? undefined,
setRefreshToken: (t: string) => localStorage.setItem(KEYS.refreshToken, t),
getUser: (): AuthUser | null => {
try {
return JSON.parse(localStorage.getItem(KEYS.user) ?? 'null') as AuthUser | null;
} catch {
return null;
}
},
setUser: (u: AuthUser) => localStorage.setItem(KEYS.user, JSON.stringify(u)),
clear: () => Object.values(KEYS).forEach((k) => localStorage.removeItem(k)),
};

View File

@@ -0,0 +1,14 @@
import { Stack, Title, Text, Paper } from '@mantine/core';
export function DashboardPage() {
return (
<Stack gap="lg">
<Title order={2}>My Dashboard</Title>
<Paper p="md" shadow="sm" radius="md" withBorder>
<Text c="dimmed">
Welcome to the EMA Portal. Your content will appear here.
</Text>
</Paper>
</Stack>
);
}

View File

@@ -0,0 +1,36 @@
import { AppShell, Group, Text, Button } from '@mantine/core';
import { Outlet, useNavigate } from 'react-router-dom';
export function PortalLayout() {
const navigate = useNavigate();
const isLoggedIn = !!localStorage.getItem('ema-portal-auth-token');
return (
<AppShell header={{ height: 56 }} padding="md">
<AppShell.Header>
<Group h="100%" px="md" justify="space-between">
<Text fw={700}>EMA Portal</Text>
{isLoggedIn ? (
<Button
variant="subtle"
size="sm"
onClick={() => {
localStorage.removeItem('ema-portal-auth-token');
navigate('/login');
}}
>
Logout
</Button>
) : (
<Button variant="subtle" size="sm" onClick={() => navigate('/login')}>
Login
</Button>
)}
</Group>
</AppShell.Header>
<AppShell.Main>
<Outlet />
</AppShell.Main>
</AppShell>
);
}

View File

@@ -0,0 +1,19 @@
import { Provider } from 'react-redux';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react';
import { store } from '../store';
import { MantineThemeProvider } from './MantineThemeProvider';
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 1, staleTime: 1000 * 60 * 5 } },
});
export function AppProviders({ children }: { children: ReactNode }) {
return (
<Provider store={store}>
<QueryClientProvider client={queryClient}>
<MantineThemeProvider>{children}</MantineThemeProvider>
</QueryClientProvider>
</Provider>
);
}

View File

@@ -0,0 +1,13 @@
import { MantineProvider } from '@mantine/core';
import { Notifications } from '@mantine/notifications';
import { emaTheme } from '@ema-platform/shared';
import type { ReactNode } from 'react';
export function MantineThemeProvider({ children }: { children: ReactNode }) {
return (
<MantineProvider theme={emaTheme}>
<Notifications position="top-right" />
{children}
</MantineProvider>
);
}

View File

@@ -0,0 +1,37 @@
import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom';
import type { ReactNode } from 'react';
import { PortalLayout } from './layouts/PortalLayout';
import { LoginPage } from './features/auth/pages/LoginPage';
import { DashboardPage } from './features/dashboard/pages/DashboardPage';
function getToken(): string | null {
return localStorage.getItem('ema-portal-auth-token');
}
function ProtectedRoute({ children }: { children: ReactNode }) {
if (!getToken()) return <Navigate to="/login" replace />;
return <>{children}</>;
}
const router = createBrowserRouter([
{ path: '/login', element: <LoginPage /> },
{
element: <PortalLayout />,
children: [
{ path: '/', element: <Navigate to="/dashboard" replace /> },
{
path: '/dashboard',
element: (
<ProtectedRoute>
<DashboardPage />
</ProtectedRoute>
),
},
],
},
{ path: '*', element: <Navigate to="/" replace /> },
]);
export function AppRouter() {
return <RouterProvider router={router} />;
}

View File

@@ -0,0 +1,6 @@
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './index';
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector = <T>(selector: (state: RootState) => T) =>
useSelector(selector);

View File

@@ -0,0 +1,15 @@
import { configureStore } from '@reduxjs/toolkit';
import { baseApi } from '@ema-platform/api';
import { authReducer } from '../features/auth/store/auth.slice';
export const store = configureStore({
reducer: {
auth: authReducer,
[baseApi.reducerPath]: baseApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(baseApi.middleware),
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

15
apps/portal/src/main.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import '@mantine/core/styles.css';
import '@mantine/notifications/styles.css';
import './styles.css';
import { App } from './app/app';
const root = document.getElementById('root');
if (!root) throw new Error('Root element not found');
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);

View File

@@ -0,0 +1,4 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;

View File

@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc/apps/portal",
"types": ["vite/client", "node"]
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.d.ts"]
}

View File

@@ -0,0 +1,19 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
export default defineConfig({
root: __dirname,
cacheDir: '../../node_modules/.vite/apps/portal',
server: { port: 4200, host: 'localhost' },
preview: { port: 4200, host: 'localhost' },
plugins: [react(), nxViteTsPaths()],
resolve: {
dedupe: ['react', 'react-dom', 'react-router-dom', '@tanstack/react-query'],
},
build: {
outDir: '../../dist/apps/portal',
emptyOutDir: true,
reportCompressedSize: true,
},
});