mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-08-25 05:42:27 +00:00
refactor: remove unsed code
This commit is contained in:
24
client/.gitignore
vendored
24
client/.gitignore
vendored
@ -1,24 +0,0 @@
|
|||||||
# Logs
|
|
||||||
logs
|
|
||||||
*.log
|
|
||||||
npm-debug.log*
|
|
||||||
yarn-debug.log*
|
|
||||||
yarn-error.log*
|
|
||||||
pnpm-debug.log*
|
|
||||||
lerna-debug.log*
|
|
||||||
|
|
||||||
node_modules
|
|
||||||
dist
|
|
||||||
dist-ssr
|
|
||||||
*.local
|
|
||||||
|
|
||||||
# Editor directories and files
|
|
||||||
.vscode/*
|
|
||||||
!.vscode/extensions.json
|
|
||||||
.idea
|
|
||||||
.DS_Store
|
|
||||||
*.suo
|
|
||||||
*.ntvs*
|
|
||||||
*.njsproj
|
|
||||||
*.sln
|
|
||||||
*.sw?
|
|
@ -1,50 +0,0 @@
|
|||||||
# React + TypeScript + Vite
|
|
||||||
|
|
||||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
|
||||||
|
|
||||||
Currently, two official plugins are available:
|
|
||||||
|
|
||||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
|
|
||||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
|
||||||
|
|
||||||
## Expanding the ESLint configuration
|
|
||||||
|
|
||||||
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
|
|
||||||
|
|
||||||
- Configure the top-level `parserOptions` property like this:
|
|
||||||
|
|
||||||
```js
|
|
||||||
export default tseslint.config({
|
|
||||||
languageOptions: {
|
|
||||||
// other options...
|
|
||||||
parserOptions: {
|
|
||||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
|
||||||
tsconfigRootDir: import.meta.dirname,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked`
|
|
||||||
- Optionally add `...tseslint.configs.stylisticTypeChecked`
|
|
||||||
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config:
|
|
||||||
|
|
||||||
```js
|
|
||||||
// eslint.config.js
|
|
||||||
import react from 'eslint-plugin-react'
|
|
||||||
|
|
||||||
export default tseslint.config({
|
|
||||||
// Set the react version
|
|
||||||
settings: { react: { version: '18.3' } },
|
|
||||||
plugins: {
|
|
||||||
// Add the react plugin
|
|
||||||
react,
|
|
||||||
},
|
|
||||||
rules: {
|
|
||||||
// other rules...
|
|
||||||
// Enable its recommended rules
|
|
||||||
...react.configs.recommended.rules,
|
|
||||||
...react.configs['jsx-runtime'].rules,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
```
|
|
@ -1,28 +0,0 @@
|
|||||||
import js from '@eslint/js'
|
|
||||||
import globals from 'globals'
|
|
||||||
import reactHooks from 'eslint-plugin-react-hooks'
|
|
||||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
|
||||||
import tseslint from 'typescript-eslint'
|
|
||||||
|
|
||||||
export default tseslint.config(
|
|
||||||
{ ignores: ['dist'] },
|
|
||||||
{
|
|
||||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
|
||||||
files: ['**/*.{ts,tsx}'],
|
|
||||||
languageOptions: {
|
|
||||||
ecmaVersion: 2020,
|
|
||||||
globals: globals.browser,
|
|
||||||
},
|
|
||||||
plugins: {
|
|
||||||
'react-hooks': reactHooks,
|
|
||||||
'react-refresh': reactRefresh,
|
|
||||||
},
|
|
||||||
rules: {
|
|
||||||
...reactHooks.configs.recommended.rules,
|
|
||||||
'react-refresh/only-export-components': [
|
|
||||||
'warn',
|
|
||||||
{ allowConstantExport: true },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
@ -1,13 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>Vite + React + TS</title>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div id="root"></div>
|
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
4115
client/package-lock.json
generated
4115
client/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -1,38 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "client",
|
|
||||||
"private": true,
|
|
||||||
"version": "0.0.0",
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"dev": "vite",
|
|
||||||
"build": "tsc -b && vite build",
|
|
||||||
"lint": "eslint .",
|
|
||||||
"preview": "vite preview"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@emotion/react": "^11.14.0",
|
|
||||||
"@emotion/styled": "^11.14.0",
|
|
||||||
"@fontsource/roboto": "^5.1.1",
|
|
||||||
"@mui/icons-material": "^6.3.1",
|
|
||||||
"@mui/material": "^6.3.1",
|
|
||||||
"@react-oauth/google": "^0.12.1",
|
|
||||||
"axios": "^1.7.9",
|
|
||||||
"react": "^18.3.1",
|
|
||||||
"react-apple-signin-auth": "^1.1.0",
|
|
||||||
"react-dom": "^18.3.1",
|
|
||||||
"react-router-dom": "^7.1.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@eslint/js": "^9.17.0",
|
|
||||||
"@types/react": "^18.3.18",
|
|
||||||
"@types/react-dom": "^18.3.5",
|
|
||||||
"@vitejs/plugin-react": "^4.3.4",
|
|
||||||
"eslint": "^9.17.0",
|
|
||||||
"eslint-plugin-react-hooks": "^5.0.0",
|
|
||||||
"eslint-plugin-react-refresh": "^0.4.16",
|
|
||||||
"globals": "^15.14.0",
|
|
||||||
"typescript": "~5.6.2",
|
|
||||||
"typescript-eslint": "^8.18.2",
|
|
||||||
"vite": "^6.0.5"
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
|
Before Width: | Height: | Size: 1.5 KiB |
@ -1,42 +0,0 @@
|
|||||||
#root {
|
|
||||||
max-width: 1280px;
|
|
||||||
margin: 0 auto;
|
|
||||||
padding: 2rem;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.logo {
|
|
||||||
height: 6em;
|
|
||||||
padding: 1.5em;
|
|
||||||
will-change: filter;
|
|
||||||
transition: filter 300ms;
|
|
||||||
}
|
|
||||||
.logo:hover {
|
|
||||||
filter: drop-shadow(0 0 2em #646cffaa);
|
|
||||||
}
|
|
||||||
.logo.react:hover {
|
|
||||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes logo-spin {
|
|
||||||
from {
|
|
||||||
transform: rotate(0deg);
|
|
||||||
}
|
|
||||||
to {
|
|
||||||
transform: rotate(360deg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: no-preference) {
|
|
||||||
a:nth-of-type(2) .logo {
|
|
||||||
animation: logo-spin infinite 20s linear;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.card {
|
|
||||||
padding: 2em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.read-the-docs {
|
|
||||||
color: #888;
|
|
||||||
}
|
|
@ -1,127 +0,0 @@
|
|||||||
import { CssBaseline, ThemeProvider, createTheme } from '@mui/material';
|
|
||||||
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
|
|
||||||
import { LoginForm } from './components/auth/LoginForm';
|
|
||||||
import { RegisterForm } from './components/auth/RegisterForm';
|
|
||||||
import { Dashboard } from './components/dashboard/Dashboard';
|
|
||||||
import { AddJuniorForm } from './components/juniors/AddJuniorForm';
|
|
||||||
import { JuniorsList } from './components/juniors/JuniorsList';
|
|
||||||
import { AuthLayout } from './components/layout/AuthLayout';
|
|
||||||
import { AddTaskForm } from './components/tasks/AddTask';
|
|
||||||
import { TaskDetails } from './components/tasks/TaskDetails';
|
|
||||||
import { TasksList } from './components/tasks/TasksList';
|
|
||||||
import { AuthProvider } from './contexts/AuthContext';
|
|
||||||
|
|
||||||
// Create theme
|
|
||||||
const theme = createTheme({
|
|
||||||
palette: {
|
|
||||||
primary: {
|
|
||||||
main: '#00A7E1', // Bright blue like Zod Wallet
|
|
||||||
light: '#33B7E7',
|
|
||||||
dark: '#0074B2',
|
|
||||||
},
|
|
||||||
secondary: {
|
|
||||||
main: '#FF6B6B', // Coral red for accents
|
|
||||||
light: '#FF8E8E',
|
|
||||||
dark: '#FF4848',
|
|
||||||
},
|
|
||||||
background: {
|
|
||||||
default: '#F8F9FA',
|
|
||||||
paper: '#FFFFFF',
|
|
||||||
},
|
|
||||||
text: {
|
|
||||||
primary: '#2D3748', // Dark gray for main text
|
|
||||||
secondary: '#718096', // Medium gray for secondary text
|
|
||||||
},
|
|
||||||
},
|
|
||||||
typography: {
|
|
||||||
fontFamily: '"Inter", "Helvetica", "Arial", sans-serif',
|
|
||||||
h1: {
|
|
||||||
fontWeight: 700,
|
|
||||||
fontSize: '2.5rem',
|
|
||||||
},
|
|
||||||
h2: {
|
|
||||||
fontWeight: 600,
|
|
||||||
fontSize: '2rem',
|
|
||||||
},
|
|
||||||
h3: {
|
|
||||||
fontWeight: 600,
|
|
||||||
fontSize: '1.75rem',
|
|
||||||
},
|
|
||||||
h4: {
|
|
||||||
fontWeight: 600,
|
|
||||||
fontSize: '1.5rem',
|
|
||||||
},
|
|
||||||
h5: {
|
|
||||||
fontWeight: 600,
|
|
||||||
fontSize: '1.25rem',
|
|
||||||
},
|
|
||||||
h6: {
|
|
||||||
fontWeight: 600,
|
|
||||||
fontSize: '1rem',
|
|
||||||
},
|
|
||||||
button: {
|
|
||||||
textTransform: 'none',
|
|
||||||
fontWeight: 500,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
shape: {
|
|
||||||
borderRadius: 12,
|
|
||||||
},
|
|
||||||
components: {
|
|
||||||
MuiButton: {
|
|
||||||
styleOverrides: {
|
|
||||||
root: {
|
|
||||||
borderRadius: '8px',
|
|
||||||
padding: '8px 16px',
|
|
||||||
fontWeight: 500,
|
|
||||||
},
|
|
||||||
contained: {
|
|
||||||
boxShadow: 'none',
|
|
||||||
'&:hover': {
|
|
||||||
boxShadow: 'none',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
MuiCard: {
|
|
||||||
styleOverrides: {
|
|
||||||
root: {
|
|
||||||
borderRadius: '16px',
|
|
||||||
boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
function App() {
|
|
||||||
return (
|
|
||||||
<ThemeProvider theme={theme}>
|
|
||||||
<CssBaseline />
|
|
||||||
<AuthProvider>
|
|
||||||
<BrowserRouter>
|
|
||||||
<Routes>
|
|
||||||
{/* Public routes */}
|
|
||||||
<Route path="/login" element={<LoginForm />} />
|
|
||||||
<Route path="/register" element={<RegisterForm />} />
|
|
||||||
|
|
||||||
{/* Protected routes */}
|
|
||||||
<Route element={<AuthLayout />}>
|
|
||||||
<Route path="/dashboard" element={<Dashboard />} />
|
|
||||||
<Route path="/juniors" element={<JuniorsList />} />
|
|
||||||
<Route path="/juniors/new" element={<AddJuniorForm />} />
|
|
||||||
<Route path="/tasks" element={<TasksList />} />
|
|
||||||
<Route path="/tasks/new" element={<AddTaskForm />} />
|
|
||||||
<Route path="/tasks/:taskId" element={<TaskDetails />} />
|
|
||||||
</Route>
|
|
||||||
|
|
||||||
{/* Redirect root to dashboard or login */}
|
|
||||||
<Route path="/" element={<Navigate to="/dashboard" replace />} />
|
|
||||||
</Routes>
|
|
||||||
</BrowserRouter>
|
|
||||||
</AuthProvider>
|
|
||||||
</ThemeProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default App;
|
|
@ -1,140 +0,0 @@
|
|||||||
import axios from 'axios';
|
|
||||||
import { LoginRequest } from '../types/auth';
|
|
||||||
import { CreateJuniorRequest, JuniorTheme } from '../types/junior';
|
|
||||||
import { CreateTaskRequest, TaskStatus, TaskSubmission } from '../types/task';
|
|
||||||
|
|
||||||
const API_BASE_URL = 'https://zod.life';
|
|
||||||
const AUTH_TOKEN = btoa('zod-digital:Zod2025'); // Base64 encode credentials
|
|
||||||
|
|
||||||
// Helper function to get auth header
|
|
||||||
const getAuthHeader = () => {
|
|
||||||
const token = localStorage.getItem('accessToken');
|
|
||||||
return token ? `Bearer ${token}` : `Basic ${AUTH_TOKEN}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const apiClient = axios.create({
|
|
||||||
baseURL: API_BASE_URL,
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'x-client-id': 'web-client',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add request interceptor to include current auth header
|
|
||||||
apiClient.interceptors.request.use((config) => {
|
|
||||||
config.headers.Authorization = getAuthHeader();
|
|
||||||
return config;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add response interceptor to handle errors
|
|
||||||
apiClient.interceptors.response.use(
|
|
||||||
(response) => response,
|
|
||||||
(error) => {
|
|
||||||
const errorMessage =
|
|
||||||
error.response?.data?.message || error.response?.data?.error || error.message || 'An unexpected error occurred';
|
|
||||||
|
|
||||||
console.error('API Error:', {
|
|
||||||
status: error.response?.status,
|
|
||||||
message: errorMessage,
|
|
||||||
data: error.response?.data,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Throw error with meaningful message
|
|
||||||
throw new Error(errorMessage);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
// Auth API
|
|
||||||
export const authApi = {
|
|
||||||
register: (countryCode: string, phoneNumber: string) => {
|
|
||||||
// Ensure phone number is in the correct format (remove any non-digit characters)
|
|
||||||
const cleanPhoneNumber = phoneNumber.replace(/\D/g, '');
|
|
||||||
return apiClient.post('/api/auth/register/otp', {
|
|
||||||
countryCode: countryCode.startsWith('+') ? countryCode : `+${countryCode}`,
|
|
||||||
phoneNumber: cleanPhoneNumber,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
verifyOtp: (countryCode: string, phoneNumber: string, otp: string) =>
|
|
||||||
apiClient.post('/api/auth/register/verify', { countryCode, phoneNumber, otp }),
|
|
||||||
|
|
||||||
setEmail: (email: string) => {
|
|
||||||
// Use the stored token from localStorage
|
|
||||||
const storedToken = localStorage.getItem('accessToken');
|
|
||||||
if (!storedToken) {
|
|
||||||
throw new Error('No access token found');
|
|
||||||
}
|
|
||||||
return apiClient.post('/api/auth/register/set-email', { email });
|
|
||||||
},
|
|
||||||
|
|
||||||
setPasscode: (passcode: string) => {
|
|
||||||
// Use the stored token from localStorage
|
|
||||||
const storedToken = localStorage.getItem('accessToken');
|
|
||||||
if (!storedToken) {
|
|
||||||
throw new Error('No access token found');
|
|
||||||
}
|
|
||||||
return apiClient.post('/api/auth/register/set-passcode', { passcode });
|
|
||||||
},
|
|
||||||
|
|
||||||
login: ({ grantType, email, password, appleToken, googleToken }: LoginRequest) =>
|
|
||||||
apiClient.post('/api/auth/login', {
|
|
||||||
grantType,
|
|
||||||
email,
|
|
||||||
password,
|
|
||||||
appleToken,
|
|
||||||
googleToken,
|
|
||||||
fcmToken: 'web-client-token', // Required by API
|
|
||||||
signature: 'web-login', // Required by API
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Juniors API
|
|
||||||
export const juniorsApi = {
|
|
||||||
createJunior: (data: CreateJuniorRequest) => apiClient.post('/api/juniors', data),
|
|
||||||
|
|
||||||
getJuniors: (page = 1, size = 10) => apiClient.get(`/api/juniors?page=${page}&size=${size}`),
|
|
||||||
|
|
||||||
getJunior: (juniorId: string) => apiClient.get(`/api/juniors/${juniorId}`),
|
|
||||||
|
|
||||||
setTheme: (data: JuniorTheme) => apiClient.post('/api/juniors/set-theme', data),
|
|
||||||
|
|
||||||
getQrCode: (juniorId: string) => apiClient.get(`/api/juniors/${juniorId}/qr-code`),
|
|
||||||
|
|
||||||
validateQrCode: (token: string) => apiClient.get(`/api/juniors/qr-code/${token}/validate`),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Document API
|
|
||||||
export const documentApi = {
|
|
||||||
upload: (file: File, documentType: string) => {
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('document', file);
|
|
||||||
formData.append('documentType', documentType);
|
|
||||||
return apiClient.post('/api/document', formData, {
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'multipart/form-data',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// Tasks API
|
|
||||||
export const tasksApi = {
|
|
||||||
createTask: (data: CreateTaskRequest) => apiClient.post('/api/tasks', data),
|
|
||||||
|
|
||||||
getTasks: (status: TaskStatus, page = 1, size = 10, juniorId?: string) => {
|
|
||||||
const url = new URL('/api/tasks', API_BASE_URL);
|
|
||||||
url.searchParams.append('status', status);
|
|
||||||
url.searchParams.append('page', page.toString());
|
|
||||||
url.searchParams.append('size', size.toString());
|
|
||||||
if (juniorId) url.searchParams.append('juniorId', juniorId);
|
|
||||||
return apiClient.get(url.pathname + url.search);
|
|
||||||
},
|
|
||||||
|
|
||||||
getTaskById: (taskId: string) => apiClient.get(`/api/tasks/${taskId}`),
|
|
||||||
|
|
||||||
submitTask: (taskId: string, data: TaskSubmission) => apiClient.patch(`/api/tasks/${taskId}/submit`, data),
|
|
||||||
|
|
||||||
approveTask: (taskId: string) => apiClient.patch(`/api/tasks/${taskId}/approve`),
|
|
||||||
|
|
||||||
rejectTask: (taskId: string) => apiClient.patch(`/api/tasks/${taskId}/reject`),
|
|
||||||
};
|
|
@ -1 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
|
Before Width: | Height: | Size: 4.0 KiB |
@ -1,69 +0,0 @@
|
|||||||
import AppleSignInButton from 'react-apple-signin-auth';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { useAuth } from '../../contexts/AuthContext';
|
|
||||||
import { GrantType } from '../../enums';
|
|
||||||
|
|
||||||
interface LoginProps {
|
|
||||||
setError: (error: string) => void;
|
|
||||||
setLoading: (loading: boolean) => void;
|
|
||||||
}
|
|
||||||
export const AppleLogin = ({ setError, setLoading }: LoginProps) => {
|
|
||||||
const { login } = useAuth();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const onError = (err: any) => {
|
|
||||||
setError(err instanceof Error ? err.message : 'Login failed. Please check your credentials.');
|
|
||||||
};
|
|
||||||
|
|
||||||
const onSuccess = async (response: any) => {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
await login({ grantType: GrantType.APPLE, appleToken: response.authorization.id_token });
|
|
||||||
navigate('/dashboard');
|
|
||||||
} catch (error) {
|
|
||||||
setError(error instanceof Error ? error.message : 'Login failed. Please check your credentials.');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AppleSignInButton
|
|
||||||
/** Auth options passed to AppleID.auth.init() */
|
|
||||||
authOptions={{
|
|
||||||
/** Client ID - eg: 'com.example.com' */
|
|
||||||
clientId: process?.env.REACT_APP_APPLE_CLIENT_ID!,
|
|
||||||
|
|
||||||
scope: 'email name',
|
|
||||||
/** Requested scopes, seperated by spaces - eg: 'email name' */
|
|
||||||
/** Apple's redirectURI - must be one of the URIs you added to the serviceID - the undocumented trick in apple docs is that you should call auth from a page that is listed as a redirectURI, localhost fails */
|
|
||||||
redirectURI: process?.env.REACT_APP_APPLE_REDIRECT_URI!,
|
|
||||||
|
|
||||||
state: 'default',
|
|
||||||
|
|
||||||
/** Uses popup auth instead of redirection */
|
|
||||||
usePopup: true,
|
|
||||||
}} // REQUIRED
|
|
||||||
/** General props */
|
|
||||||
uiType="dark"
|
|
||||||
/** className */
|
|
||||||
className="apple-auth-btn"
|
|
||||||
/** Removes default style tag */
|
|
||||||
noDefaultStyle={false}
|
|
||||||
/** Allows to change the button's children, eg: for changing the button text */
|
|
||||||
buttonExtraChildren="Continue with Apple"
|
|
||||||
/** Extra controlling props */
|
|
||||||
/** Called upon signin success in case authOptions.usePopup = true -- which means auth is handled client side */
|
|
||||||
onSuccess={(response: any) => {
|
|
||||||
onSuccess(response);
|
|
||||||
}} // default = undefined
|
|
||||||
/** Called upon signin error */
|
|
||||||
onError={(error: any) => onError(error)} // default = undefined
|
|
||||||
/** Skips loading the apple script if true */
|
|
||||||
skipScript={false} // default = undefined
|
|
||||||
/** Apple image props */
|
|
||||||
|
|
||||||
/** render function - called with all props - can be used to fully customize the UI by rendering your own component */
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,40 +0,0 @@
|
|||||||
import { GoogleLogin as GoogleApiLogin, GoogleOAuthProvider } from '@react-oauth/google';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { useAuth } from '../../contexts/AuthContext';
|
|
||||||
import { GrantType } from '../../enums';
|
|
||||||
interface LoginProps {
|
|
||||||
setError: (error: string) => void;
|
|
||||||
setLoading: (loading: boolean) => void;
|
|
||||||
}
|
|
||||||
export const GoogleLogin = ({ setError, setLoading }: LoginProps) => {
|
|
||||||
const { login } = useAuth();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const onError = (err: any) => {
|
|
||||||
setError(err instanceof Error ? err.message : 'Login failed. Please check your credentials.');
|
|
||||||
};
|
|
||||||
|
|
||||||
const onSuccess = async (response: any) => {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
await login({ grantType: GrantType.GOOGLE, googleToken: response.credential });
|
|
||||||
navigate('/dashboard');
|
|
||||||
} catch (error) {
|
|
||||||
setError(error instanceof Error ? error.message : 'Login failed. Please check your credentials.');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return (
|
|
||||||
<GoogleOAuthProvider clientId={process.env.GOOGLE_WEB_CLIENT_ID!}>
|
|
||||||
<GoogleApiLogin
|
|
||||||
onSuccess={(credentialResponse) => {
|
|
||||||
onSuccess(credentialResponse);
|
|
||||||
}}
|
|
||||||
onError={() => {
|
|
||||||
onError('Login failed. Please check your credentials.');
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</GoogleOAuthProvider>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,149 +0,0 @@
|
|||||||
import { Alert, Box, Button, Container, Paper, TextField, Typography } from '@mui/material';
|
|
||||||
import React, { useState } from 'react';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { useAuth } from '../../contexts/AuthContext';
|
|
||||||
import { GrantType } from '../../enums';
|
|
||||||
import { AppleLogin } from './AppleLogin';
|
|
||||||
import { GoogleLogin } from './GoogleLogin';
|
|
||||||
export const LoginForm = () => {
|
|
||||||
const { login } = useAuth();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const [formData, setFormData] = useState({
|
|
||||||
email: '',
|
|
||||||
password: '',
|
|
||||||
});
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError('');
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await login({ email: formData.email, password: formData.password, grantType: GrantType.PASSWORD });
|
|
||||||
navigate('/dashboard');
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'Login failed. Please check your credentials.');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
[name]: value,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
minHeight: '100vh',
|
|
||||||
display: 'flex',
|
|
||||||
flexDirection: 'column',
|
|
||||||
backgroundColor: 'background.default',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Container maxWidth="sm" sx={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
|
|
||||||
<Box sx={{ mb: 4, textAlign: 'center' }}>
|
|
||||||
<Typography variant="h3" component="h1" gutterBottom sx={{ fontWeight: 700, color: 'primary.main' }}>
|
|
||||||
Zod Alkhair | API TEST
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="h6" sx={{ color: 'text.secondary', mb: 4 }}>
|
|
||||||
login to your account.
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Paper
|
|
||||||
elevation={0}
|
|
||||||
sx={{
|
|
||||||
p: 4,
|
|
||||||
borderRadius: 3,
|
|
||||||
border: '1px solid',
|
|
||||||
borderColor: 'divider',
|
|
||||||
backgroundColor: 'background.paper',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{error && (
|
|
||||||
<Alert severity="error" sx={{ mb: 3 }}>
|
|
||||||
{error}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box component="form" onSubmit={handleSubmit}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
label="Email"
|
|
||||||
name="email"
|
|
||||||
type="email"
|
|
||||||
value={formData.email}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
autoFocus
|
|
||||||
sx={{
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
borderRadius: 2,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
label="Password"
|
|
||||||
name="password"
|
|
||||||
type="password"
|
|
||||||
value={formData.password}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
sx={{
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
borderRadius: 2,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
fullWidth
|
|
||||||
variant="contained"
|
|
||||||
size="large"
|
|
||||||
sx={{
|
|
||||||
mt: 3,
|
|
||||||
mb: 2,
|
|
||||||
height: 48,
|
|
||||||
borderRadius: 2,
|
|
||||||
textTransform: 'none',
|
|
||||||
fontSize: '1rem',
|
|
||||||
}}
|
|
||||||
disabled={loading}
|
|
||||||
>
|
|
||||||
{loading ? 'Signing in...' : 'Sign in'}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
variant="text"
|
|
||||||
sx={{
|
|
||||||
textTransform: 'none',
|
|
||||||
fontSize: '1rem',
|
|
||||||
color: 'text.secondary',
|
|
||||||
'&:hover': {
|
|
||||||
color: 'primary.main',
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
onClick={() => navigate('/register')}
|
|
||||||
>
|
|
||||||
signup
|
|
||||||
</Button>
|
|
||||||
<AppleLogin setError={setError} setLoading={setLoading} />
|
|
||||||
<GoogleLogin setError={setError} setLoading={setLoading} />
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
</Container>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,254 +0,0 @@
|
|||||||
import { Alert, Box, Button, Container, Paper, Step, StepLabel, Stepper, TextField, Typography } from '@mui/material';
|
|
||||||
import React, { useState } from 'react';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { useAuth } from '../../contexts/AuthContext';
|
|
||||||
|
|
||||||
const steps = ['Phone Verification', 'Email', 'Set Passcode'];
|
|
||||||
|
|
||||||
export const RegisterForm = () => {
|
|
||||||
const { register, verifyOtp, setEmail, setPasscode } = useAuth();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const [activeStep, setActiveStep] = useState(0);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [formData, setFormData] = useState({
|
|
||||||
countryCode: '+962',
|
|
||||||
phoneNumber: '',
|
|
||||||
otp: '',
|
|
||||||
email: '',
|
|
||||||
passcode: '',
|
|
||||||
confirmPasscode: '',
|
|
||||||
otpRequested: false
|
|
||||||
});
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError('');
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
switch (activeStep) {
|
|
||||||
case 0:
|
|
||||||
if (!formData.otpRequested) {
|
|
||||||
// Request OTP
|
|
||||||
await register(formData.countryCode, formData.phoneNumber);
|
|
||||||
setFormData(prev => ({ ...prev, otpRequested: true }));
|
|
||||||
} else {
|
|
||||||
// Verify OTP
|
|
||||||
await verifyOtp(formData.countryCode, formData.phoneNumber, formData.otp);
|
|
||||||
setActiveStep(1);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 1:
|
|
||||||
await setEmail(formData.email);
|
|
||||||
setActiveStep(2);
|
|
||||||
break;
|
|
||||||
case 2:
|
|
||||||
if (formData.passcode !== formData.confirmPasscode) {
|
|
||||||
throw new Error('Passcodes do not match');
|
|
||||||
}
|
|
||||||
await setPasscode(formData.passcode);
|
|
||||||
navigate('/dashboard');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'Registration failed');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
[name]: value,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
const renderStepContent = () => {
|
|
||||||
switch (activeStep) {
|
|
||||||
case 0:
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
label="Phone Number"
|
|
||||||
name="phoneNumber"
|
|
||||||
value={formData.phoneNumber}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
placeholder="7XXXXXXXX"
|
|
||||||
required
|
|
||||||
disabled={formData.otpRequested}
|
|
||||||
sx={{
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
borderRadius: 2,
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{formData.otpRequested && (
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
label="OTP"
|
|
||||||
name="otp"
|
|
||||||
value={formData.otp}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
placeholder="Enter OTP"
|
|
||||||
required
|
|
||||||
autoFocus
|
|
||||||
sx={{
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
borderRadius: 2,
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
case 1:
|
|
||||||
return (
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
label="Email"
|
|
||||||
name="email"
|
|
||||||
type="email"
|
|
||||||
value={formData.email}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
autoFocus
|
|
||||||
sx={{
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
borderRadius: 2,
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
case 2:
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
label="Passcode"
|
|
||||||
name="passcode"
|
|
||||||
type="password"
|
|
||||||
value={formData.passcode}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
autoFocus
|
|
||||||
sx={{
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
borderRadius: 2,
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
label="Confirm Passcode"
|
|
||||||
name="confirmPasscode"
|
|
||||||
type="password"
|
|
||||||
value={formData.confirmPasscode}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
sx={{
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
borderRadius: 2,
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
minHeight: '100vh',
|
|
||||||
display: 'flex',
|
|
||||||
flexDirection: 'column',
|
|
||||||
backgroundColor: 'background.default',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Container maxWidth="sm" sx={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
|
|
||||||
<Box sx={{ mb: 4, textAlign: 'center' }}>
|
|
||||||
<Typography variant="h3" component="h1" gutterBottom sx={{ fontWeight: 700, color: 'primary.main' }}>
|
|
||||||
Zod Alkhair | API TEST
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="h6" sx={{ color: 'text.secondary', mb: 4 }}>
|
|
||||||
signup
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Paper
|
|
||||||
elevation={0}
|
|
||||||
sx={{
|
|
||||||
p: 4,
|
|
||||||
borderRadius: 3,
|
|
||||||
border: '1px solid',
|
|
||||||
borderColor: 'divider',
|
|
||||||
backgroundColor: 'background.paper'
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Stepper activeStep={activeStep} sx={{ mb: 4 }}>
|
|
||||||
{steps.map((label) => (
|
|
||||||
<Step key={label}>
|
|
||||||
<StepLabel>{label}</StepLabel>
|
|
||||||
</Step>
|
|
||||||
))}
|
|
||||||
</Stepper>
|
|
||||||
|
|
||||||
{error && (
|
|
||||||
<Alert severity="error" sx={{ mb: 3 }}>
|
|
||||||
{error}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box component="form" onSubmit={handleSubmit}>
|
|
||||||
{renderStepContent()}
|
|
||||||
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
fullWidth
|
|
||||||
variant="contained"
|
|
||||||
size="large"
|
|
||||||
sx={{
|
|
||||||
mt: 3,
|
|
||||||
mb: 2,
|
|
||||||
height: 48,
|
|
||||||
borderRadius: 2,
|
|
||||||
textTransform: 'none',
|
|
||||||
fontSize: '1rem'
|
|
||||||
}}
|
|
||||||
disabled={loading}
|
|
||||||
>
|
|
||||||
{loading ? 'Processing...' : activeStep === 0 && !formData.otpRequested ? 'Send OTP' : 'Continue'}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
variant="text"
|
|
||||||
sx={{
|
|
||||||
textTransform: 'none',
|
|
||||||
fontSize: '1rem',
|
|
||||||
color: 'text.secondary',
|
|
||||||
'&:hover': {
|
|
||||||
color: 'primary.main'
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClick={() => navigate('/login')}
|
|
||||||
>
|
|
||||||
sign in
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
</Container>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,151 +0,0 @@
|
|||||||
import {
|
|
||||||
People as PeopleIcon,
|
|
||||||
Assignment as TaskIcon,
|
|
||||||
TrendingUp as TrendingUpIcon,
|
|
||||||
AccountBalance as WalletIcon
|
|
||||||
} from '@mui/icons-material';
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Button,
|
|
||||||
Card,
|
|
||||||
CardContent,
|
|
||||||
Grid,
|
|
||||||
Paper,
|
|
||||||
Typography,
|
|
||||||
useTheme
|
|
||||||
} from '@mui/material';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
|
|
||||||
export const Dashboard = () => {
|
|
||||||
const theme = useTheme();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const stats = [
|
|
||||||
{
|
|
||||||
title: 'Total Juniors',
|
|
||||||
value: '3',
|
|
||||||
icon: <PeopleIcon sx={{ fontSize: 40, color: 'primary.main' }} />,
|
|
||||||
action: () => navigate('/juniors')
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: 'Active Tasks',
|
|
||||||
value: '5',
|
|
||||||
icon: <TaskIcon sx={{ fontSize: 40, color: 'secondary.main' }} />,
|
|
||||||
action: () => navigate('/tasks')
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: 'Total Balance',
|
|
||||||
value: 'SAR 500',
|
|
||||||
icon: <WalletIcon sx={{ fontSize: 40, color: 'success.main' }} />,
|
|
||||||
action: () => { }
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: 'Monthly Growth',
|
|
||||||
value: '+15%',
|
|
||||||
icon: <TrendingUpIcon sx={{ fontSize: 40, color: 'info.main' }} />,
|
|
||||||
action: () => { }
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Box sx={{ mb: 4 }}>
|
|
||||||
<Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
|
|
||||||
Welcome to Zod Alkhair,
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body1" sx={{ color: 'text.secondary' }}>
|
|
||||||
This is the API Testing client
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Grid container spacing={3} sx={{ mb: 4 }}>
|
|
||||||
{stats.map((stat, index) => (
|
|
||||||
<Grid item xs={12} sm={6} md={3} key={index}>
|
|
||||||
<Card
|
|
||||||
sx={{
|
|
||||||
height: '100%',
|
|
||||||
cursor: 'pointer',
|
|
||||||
transition: 'transform 0.2s',
|
|
||||||
'&:hover': {
|
|
||||||
transform: 'translateY(-4px)'
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClick={stat.action}
|
|
||||||
>
|
|
||||||
<CardContent>
|
|
||||||
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
|
|
||||||
{stat.icon}
|
|
||||||
</Box>
|
|
||||||
<Typography variant="h5" sx={{ fontWeight: 600, mb: 1 }}>
|
|
||||||
{stat.value}
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
|
||||||
{stat.title}
|
|
||||||
</Typography>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</Grid>
|
|
||||||
))}
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid container spacing={3}>
|
|
||||||
<Grid item xs={12} md={8}>
|
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
p: 3,
|
|
||||||
height: '100%',
|
|
||||||
backgroundColor: theme.palette.primary.main,
|
|
||||||
color: 'white'
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
|
|
||||||
Quick Actions
|
|
||||||
</Typography>
|
|
||||||
<Grid container spacing={2}>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
variant="contained"
|
|
||||||
sx={{
|
|
||||||
backgroundColor: 'rgba(255, 255, 255, 0.1)',
|
|
||||||
'&:hover': {
|
|
||||||
backgroundColor: 'rgba(255, 255, 255, 0.2)'
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClick={() => navigate('/juniors/new')}
|
|
||||||
>
|
|
||||||
Add New Junior
|
|
||||||
</Button>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
variant="contained"
|
|
||||||
sx={{
|
|
||||||
backgroundColor: 'rgba(255, 255, 255, 0.1)',
|
|
||||||
'&:hover': {
|
|
||||||
backgroundColor: 'rgba(255, 255, 255, 0.2)'
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClick={() => navigate('/tasks/new')}
|
|
||||||
>
|
|
||||||
Create New Task
|
|
||||||
</Button>
|
|
||||||
</Grid>
|
|
||||||
</Grid>
|
|
||||||
</Paper>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} md={4}>
|
|
||||||
<Paper sx={{ p: 3, height: '100%' }}>
|
|
||||||
<Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
|
|
||||||
Recent Activity
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center', mt: 4 }}>
|
|
||||||
No recent activity
|
|
||||||
</Typography>
|
|
||||||
</Paper>
|
|
||||||
</Grid>
|
|
||||||
</Grid>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,86 +0,0 @@
|
|||||||
import { CloudUpload as CloudUploadIcon } from '@mui/icons-material';
|
|
||||||
import { Alert, Box, Button, CircularProgress } from '@mui/material';
|
|
||||||
import { AxiosError } from 'axios';
|
|
||||||
import React, { useState } from 'react';
|
|
||||||
import { documentApi } from '../../api/client';
|
|
||||||
import { ApiError } from '../../types/api';
|
|
||||||
import { DocumentType } from '../../types/document';
|
|
||||||
|
|
||||||
interface DocumentUploadProps {
|
|
||||||
onUploadSuccess: (documentId: string) => void;
|
|
||||||
documentType: DocumentType;
|
|
||||||
label: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DocumentUpload = ({ onUploadSuccess, documentType, label }: DocumentUploadProps) => {
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [success, setSuccess] = useState(false);
|
|
||||||
|
|
||||||
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = event.target.files?.[0];
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
setLoading(true);
|
|
||||||
setError('');
|
|
||||||
setSuccess(false);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await documentApi.upload(file, documentType);
|
|
||||||
console.log('Document upload response:', response.data);
|
|
||||||
const documentId = response.data.data.id;
|
|
||||||
console.log('Extracted document ID:', documentId);
|
|
||||||
onUploadSuccess(documentId);
|
|
||||||
setSuccess(true);
|
|
||||||
} catch (err) {
|
|
||||||
if (err instanceof AxiosError && err.response?.data) {
|
|
||||||
const apiError = err.response.data as ApiError;
|
|
||||||
const messages = Array.isArray(apiError.message)
|
|
||||||
? apiError.message.map((m) => `${m.field}: ${m.message}`).join('\n')
|
|
||||||
: apiError.message;
|
|
||||||
setError(messages);
|
|
||||||
} else {
|
|
||||||
setError(err instanceof Error ? err.message : 'Failed to upload document');
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const now = new Date();
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<input
|
|
||||||
accept="image/*,.pdf"
|
|
||||||
style={{ display: 'none' }}
|
|
||||||
id={`upload-${documentType}-${now.getTime()}`}
|
|
||||||
type="file"
|
|
||||||
onChange={handleFileChange}
|
|
||||||
disabled={loading}
|
|
||||||
/>
|
|
||||||
<label htmlFor={`upload-${documentType}-${now.getTime()}`}>
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
component="span"
|
|
||||||
startIcon={loading ? <CircularProgress size={20} /> : <CloudUploadIcon />}
|
|
||||||
disabled={loading}
|
|
||||||
fullWidth
|
|
||||||
>
|
|
||||||
{loading ? 'Uploading...' : label}
|
|
||||||
</Button>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
{error && (
|
|
||||||
<Alert severity="error" sx={{ mt: 1, whiteSpace: 'pre-line' }}>
|
|
||||||
{error}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{success && (
|
|
||||||
<Alert severity="success" sx={{ mt: 1 }}>
|
|
||||||
Document uploaded successfully
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,266 +0,0 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
TextField,
|
|
||||||
Button,
|
|
||||||
Typography,
|
|
||||||
Paper,
|
|
||||||
FormControl,
|
|
||||||
InputLabel,
|
|
||||||
Select,
|
|
||||||
MenuItem,
|
|
||||||
Grid,
|
|
||||||
Alert,
|
|
||||||
SelectChangeEvent,
|
|
||||||
Divider
|
|
||||||
} from '@mui/material';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { juniorsApi } from '../../api/client';
|
|
||||||
import { CreateJuniorRequest } from '../../types/junior';
|
|
||||||
import { DocumentUpload } from '../document/DocumentUpload';
|
|
||||||
import { DocumentType } from '../../types/document';
|
|
||||||
import { ApiError } from '../../types/api';
|
|
||||||
import { AxiosError } from 'axios';
|
|
||||||
|
|
||||||
export const AddJuniorForm = () => {
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [formData, setFormData] = useState<CreateJuniorRequest>({
|
|
||||||
countryCode: '+962',
|
|
||||||
phoneNumber: '',
|
|
||||||
firstName: '',
|
|
||||||
lastName: '',
|
|
||||||
dateOfBirth: '',
|
|
||||||
email: '',
|
|
||||||
relationship: 'PARENT',
|
|
||||||
civilIdFrontId: '',
|
|
||||||
civilIdBackId: ''
|
|
||||||
});
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
console.log('Form data:', formData);
|
|
||||||
|
|
||||||
setError('');
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (!formData.civilIdFrontId || !formData.civilIdBackId) {
|
|
||||||
console.log('Missing documents - Front:', formData.civilIdFrontId, 'Back:', formData.civilIdBackId);
|
|
||||||
throw new Error('Please upload both front and back civil ID documents');
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Submitting data:', formData);
|
|
||||||
const dataToSubmit = {
|
|
||||||
...formData,
|
|
||||||
civilIdFrontId: formData.civilIdFrontId.trim(),
|
|
||||||
civilIdBackId: formData.civilIdBackId.trim()
|
|
||||||
};
|
|
||||||
await juniorsApi.createJunior(dataToSubmit);
|
|
||||||
navigate('/juniors');
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Create junior error:', err);
|
|
||||||
if (err instanceof AxiosError && err.response?.data) {
|
|
||||||
const apiError = err.response.data as ApiError;
|
|
||||||
const messages = Array.isArray(apiError.message)
|
|
||||||
? apiError.message.map(m => `${m.field}: ${m.message}`).join('\n')
|
|
||||||
: apiError.message;
|
|
||||||
setError(messages);
|
|
||||||
} else {
|
|
||||||
setError(err instanceof Error ? err.message : 'Failed to create junior');
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
setFormData(prev => ({
|
|
||||||
...prev,
|
|
||||||
[name]: value
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSelectChange = (e: SelectChangeEvent) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
setFormData(prev => ({
|
|
||||||
...prev,
|
|
||||||
[name as string]: value
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
console.log('Form data updated:', formData);
|
|
||||||
}, [formData]);
|
|
||||||
|
|
||||||
const handleCivilIdFrontUpload = (documentId: string) => {
|
|
||||||
console.log('Front ID uploaded:', documentId);
|
|
||||||
setFormData(prev => ({
|
|
||||||
...prev,
|
|
||||||
civilIdFrontId: documentId
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCivilIdBackUpload = (documentId: string) => {
|
|
||||||
console.log('Back ID uploaded:', documentId);
|
|
||||||
setFormData(prev => ({
|
|
||||||
...prev,
|
|
||||||
civilIdBackId: documentId
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Typography variant="h4" gutterBottom>
|
|
||||||
Add New Junior
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Paper sx={{ p: 3, maxWidth: 600, mx: 'auto' }}>
|
|
||||||
{error && (
|
|
||||||
<Alert severity="error" sx={{ mb: 3, whiteSpace: 'pre-line' }}>
|
|
||||||
{error}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box component="form" onSubmit={handleSubmit}>
|
|
||||||
<Grid container spacing={3}>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<FormControl fullWidth>
|
|
||||||
<InputLabel>Country Code</InputLabel>
|
|
||||||
<Select
|
|
||||||
name="countryCode"
|
|
||||||
value={formData.countryCode}
|
|
||||||
label="Country Code"
|
|
||||||
onChange={handleSelectChange}
|
|
||||||
>
|
|
||||||
<MenuItem value="+962">Jordan (+962)</MenuItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Phone Number"
|
|
||||||
name="phoneNumber"
|
|
||||||
value={formData.phoneNumber}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
placeholder="7XXXXXXXX"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="First Name"
|
|
||||||
name="firstName"
|
|
||||||
value={formData.firstName}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Last Name"
|
|
||||||
name="lastName"
|
|
||||||
value={formData.lastName}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Email"
|
|
||||||
name="email"
|
|
||||||
type="email"
|
|
||||||
value={formData.email}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Date of Birth"
|
|
||||||
name="dateOfBirth"
|
|
||||||
type="date"
|
|
||||||
value={formData.dateOfBirth}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
InputLabelProps={{
|
|
||||||
shrink: true,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12}>
|
|
||||||
<FormControl fullWidth>
|
|
||||||
<InputLabel>Relationship</InputLabel>
|
|
||||||
<Select
|
|
||||||
name="relationship"
|
|
||||||
value={formData.relationship}
|
|
||||||
label="Relationship"
|
|
||||||
onChange={handleSelectChange}
|
|
||||||
>
|
|
||||||
<MenuItem value="PARENT">Parent</MenuItem>
|
|
||||||
<MenuItem value="GUARDIAN">Guardian</MenuItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid item xs={12}>
|
|
||||||
<Divider sx={{ my: 2 }}>
|
|
||||||
<Typography variant="body2" color="textSecondary">
|
|
||||||
Civil ID Documents
|
|
||||||
</Typography>
|
|
||||||
</Divider>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<DocumentUpload
|
|
||||||
documentType={DocumentType.PASSPORT}
|
|
||||||
label="Upload Civil ID Front"
|
|
||||||
onUploadSuccess={handleCivilIdFrontUpload}
|
|
||||||
/>
|
|
||||||
{formData.civilIdFrontId && (
|
|
||||||
<Typography variant="caption" color="success.main" sx={{ mt: 1, display: 'block' }}>
|
|
||||||
Civil ID Front uploaded (ID: {formData.civilIdFrontId})
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={6}>
|
|
||||||
<DocumentUpload
|
|
||||||
documentType={DocumentType.PASSPORT}
|
|
||||||
label="Upload Civil ID Back"
|
|
||||||
onUploadSuccess={handleCivilIdBackUpload}
|
|
||||||
/>
|
|
||||||
{formData.civilIdBackId && (
|
|
||||||
<Typography variant="caption" color="success.main" sx={{ mt: 1, display: 'block' }}>
|
|
||||||
Civil ID Back uploaded (ID: {formData.civilIdBackId})
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</Grid>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Box sx={{ mt: 3, display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
onClick={() => navigate('/juniors')}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
variant="contained"
|
|
||||||
disabled={loading}
|
|
||||||
>
|
|
||||||
{loading ? 'Adding...' : 'Add Junior'}
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,121 +0,0 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Typography,
|
|
||||||
Grid,
|
|
||||||
Card,
|
|
||||||
CardContent,
|
|
||||||
CardMedia,
|
|
||||||
Button,
|
|
||||||
CircularProgress,
|
|
||||||
Pagination
|
|
||||||
} from '@mui/material';
|
|
||||||
import { juniorsApi } from '../../api/client';
|
|
||||||
import { Junior, PaginatedResponse } from '../../types/junior';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
|
|
||||||
export const JuniorsList = () => {
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [juniors, setJuniors] = useState<Junior[]>([]);
|
|
||||||
const [page, setPage] = useState(1);
|
|
||||||
const [totalPages, setTotalPages] = useState(1);
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const fetchJuniors = async (pageNum: number) => {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
const response = await juniorsApi.getJuniors(pageNum);
|
|
||||||
const data = response.data as PaginatedResponse<Junior>;
|
|
||||||
setJuniors(data.data);
|
|
||||||
setTotalPages(data.meta.pageCount);
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'Failed to load juniors');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchJuniors(page);
|
|
||||||
}, [page]);
|
|
||||||
|
|
||||||
const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
|
|
||||||
setPage(value);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
|
|
||||||
<CircularProgress />
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Typography color="error">{error}</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
|
|
||||||
<Typography variant="h4">Juniors</Typography>
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
color="primary"
|
|
||||||
onClick={() => navigate('/juniors/new')}
|
|
||||||
>
|
|
||||||
Add Junior
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Grid container spacing={3}>
|
|
||||||
{juniors.map((junior) => (
|
|
||||||
<Grid item xs={12} sm={6} md={4} key={junior.id}>
|
|
||||||
<Card>
|
|
||||||
<CardMedia
|
|
||||||
component="img"
|
|
||||||
height="140"
|
|
||||||
image={junior.profilePicture?.url || '/default-avatar.png'}
|
|
||||||
alt={junior.fullName}
|
|
||||||
sx={{ objectFit: 'contain', bgcolor: 'grey.100' }}
|
|
||||||
/>
|
|
||||||
<CardContent>
|
|
||||||
<Typography variant="h6" gutterBottom>
|
|
||||||
{junior.fullName}
|
|
||||||
</Typography>
|
|
||||||
<Typography color="textSecondary">
|
|
||||||
{junior.relationship}
|
|
||||||
</Typography>
|
|
||||||
<Box mt={2}>
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
fullWidth
|
|
||||||
onClick={() => navigate(`/juniors/${junior.id}`)}
|
|
||||||
>
|
|
||||||
View Details
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</Grid>
|
|
||||||
))}
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<Box display="flex" justifyContent="center" mt={4}>
|
|
||||||
<Pagination
|
|
||||||
count={totalPages}
|
|
||||||
page={page}
|
|
||||||
onChange={handlePageChange}
|
|
||||||
color="primary"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,175 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
import { Navigate, Outlet, useNavigate } from 'react-router-dom';
|
|
||||||
import {
|
|
||||||
AppBar,
|
|
||||||
Toolbar,
|
|
||||||
Typography,
|
|
||||||
Button,
|
|
||||||
Box,
|
|
||||||
Container,
|
|
||||||
List,
|
|
||||||
ListItem,
|
|
||||||
Drawer,
|
|
||||||
Divider
|
|
||||||
} from '@mui/material';
|
|
||||||
import {
|
|
||||||
Dashboard as DashboardIcon,
|
|
||||||
People as PeopleIcon,
|
|
||||||
Assignment as TasksIcon,
|
|
||||||
Person as ProfileIcon
|
|
||||||
} from '@mui/icons-material';
|
|
||||||
import { useAuth } from '../../contexts/AuthContext';
|
|
||||||
|
|
||||||
export const AuthLayout = () => {
|
|
||||||
const { isAuthenticated, user, logout } = useAuth();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
if (!isAuthenticated) {
|
|
||||||
return <Navigate to="/login" />;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
|
|
||||||
<AppBar
|
|
||||||
position="fixed"
|
|
||||||
sx={{
|
|
||||||
zIndex: (theme) => theme.zIndex.drawer + 1,
|
|
||||||
backgroundColor: 'background.paper',
|
|
||||||
boxShadow: 'none',
|
|
||||||
borderBottom: '1px solid',
|
|
||||||
borderColor: 'divider'
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Toolbar>
|
|
||||||
<Typography variant="h5" component="div" sx={{ flexGrow: 1, color: 'text.primary', fontWeight: 600 }}>
|
|
||||||
Zod Alkhair | API Testting client
|
|
||||||
</Typography>
|
|
||||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
|
|
||||||
{user && (
|
|
||||||
<Typography variant="body1" sx={{ color: 'text.primary' }}>
|
|
||||||
{user.firstName} {user.lastName}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
color="primary"
|
|
||||||
onClick={logout}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
Logout
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</Toolbar>
|
|
||||||
</AppBar>
|
|
||||||
|
|
||||||
<Drawer
|
|
||||||
variant="permanent"
|
|
||||||
sx={{
|
|
||||||
width: 280,
|
|
||||||
flexShrink: 0,
|
|
||||||
'& .MuiDrawer-paper': {
|
|
||||||
width: 280,
|
|
||||||
boxSizing: 'border-box',
|
|
||||||
marginTop: '64px',
|
|
||||||
backgroundColor: 'background.paper',
|
|
||||||
borderRight: '1px solid',
|
|
||||||
borderColor: 'divider',
|
|
||||||
padding: 2
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box sx={{ overflow: 'auto' }}>
|
|
||||||
<List>
|
|
||||||
<ListItem component="div">
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
sx={{
|
|
||||||
justifyContent: 'flex-start',
|
|
||||||
pl: 2,
|
|
||||||
py: 1.5,
|
|
||||||
borderRadius: 2,
|
|
||||||
color: 'text.primary',
|
|
||||||
'&:hover': {
|
|
||||||
backgroundColor: 'primary.light',
|
|
||||||
color: 'primary.contrastText'
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClick={() => navigate('/dashboard')}
|
|
||||||
startIcon={<DashboardIcon />}
|
|
||||||
>
|
|
||||||
Dashboard
|
|
||||||
</Button>
|
|
||||||
</ListItem>
|
|
||||||
<ListItem component="div">
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
sx={{
|
|
||||||
justifyContent: 'flex-start',
|
|
||||||
pl: 2,
|
|
||||||
py: 1.5,
|
|
||||||
borderRadius: 2,
|
|
||||||
color: 'text.primary',
|
|
||||||
'&:hover': {
|
|
||||||
backgroundColor: 'primary.light',
|
|
||||||
color: 'primary.contrastText'
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClick={() => navigate('/juniors')}
|
|
||||||
startIcon={<PeopleIcon />}
|
|
||||||
>
|
|
||||||
Juniors
|
|
||||||
</Button>
|
|
||||||
</ListItem>
|
|
||||||
<ListItem component="div">
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
sx={{
|
|
||||||
justifyContent: 'flex-start',
|
|
||||||
pl: 2,
|
|
||||||
py: 1.5,
|
|
||||||
borderRadius: 2,
|
|
||||||
color: 'text.primary',
|
|
||||||
'&:hover': {
|
|
||||||
backgroundColor: 'primary.light',
|
|
||||||
color: 'primary.contrastText'
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClick={() => navigate('/tasks')}
|
|
||||||
startIcon={<TasksIcon />}
|
|
||||||
>
|
|
||||||
Tasks
|
|
||||||
</Button>
|
|
||||||
</ListItem>
|
|
||||||
</List>
|
|
||||||
<Divider />
|
|
||||||
<List>
|
|
||||||
<ListItem component="div">
|
|
||||||
<Button
|
|
||||||
fullWidth
|
|
||||||
sx={{
|
|
||||||
justifyContent: 'flex-start',
|
|
||||||
pl: 2,
|
|
||||||
py: 1.5,
|
|
||||||
borderRadius: 2,
|
|
||||||
color: 'text.primary',
|
|
||||||
'&:hover': {
|
|
||||||
backgroundColor: 'primary.light',
|
|
||||||
color: 'primary.contrastText'
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onClick={() => navigate('/profile')}
|
|
||||||
startIcon={<ProfileIcon />}
|
|
||||||
>
|
|
||||||
Profile
|
|
||||||
</Button>
|
|
||||||
</ListItem>
|
|
||||||
</List>
|
|
||||||
</Box>
|
|
||||||
</Drawer>
|
|
||||||
|
|
||||||
<Container component="main" sx={{ flexGrow: 1, p: 4, marginLeft: '280px', marginTop: '64px' }}>
|
|
||||||
<Outlet />
|
|
||||||
</Container>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,245 +0,0 @@
|
|||||||
import {
|
|
||||||
Alert,
|
|
||||||
Box,
|
|
||||||
Button,
|
|
||||||
Checkbox,
|
|
||||||
FormControl,
|
|
||||||
FormControlLabel,
|
|
||||||
Grid,
|
|
||||||
InputLabel,
|
|
||||||
MenuItem,
|
|
||||||
Paper,
|
|
||||||
Select,
|
|
||||||
SelectChangeEvent,
|
|
||||||
TextField,
|
|
||||||
Typography,
|
|
||||||
} from '@mui/material';
|
|
||||||
import { AxiosError } from 'axios';
|
|
||||||
import React, { useEffect, useState } from 'react';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { juniorsApi, tasksApi } from '../../api/client';
|
|
||||||
import { ApiError } from '../../types/api';
|
|
||||||
import { DocumentType } from '../../types/document';
|
|
||||||
import { Junior, PaginatedResponse } from '../../types/junior';
|
|
||||||
import { CreateTaskRequest } from '../../types/task';
|
|
||||||
import { DocumentUpload } from '../document/DocumentUpload';
|
|
||||||
|
|
||||||
export const AddTaskForm = () => {
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [formData, setFormData] = useState<CreateTaskRequest>({
|
|
||||||
title: '',
|
|
||||||
description: '',
|
|
||||||
dueDate: '',
|
|
||||||
rewardAmount: 0,
|
|
||||||
isProofRequired: false,
|
|
||||||
juniorId: '',
|
|
||||||
imageId: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
const [juniors, setJuniors] = useState<Junior[]>([]);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
console.log('Form data:', formData);
|
|
||||||
|
|
||||||
setError('');
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (!formData.imageId) {
|
|
||||||
console.log('Proof is required but no image uploaded');
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Submitting data:', formData);
|
|
||||||
const dataToSubmit = {
|
|
||||||
...formData,
|
|
||||||
rewardAmount: Number(formData.rewardAmount),
|
|
||||||
imageId: formData.imageId,
|
|
||||||
};
|
|
||||||
await tasksApi.createTask(dataToSubmit);
|
|
||||||
navigate('/tasks');
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Create junior error:', err);
|
|
||||||
if (err instanceof AxiosError && err.response?.data) {
|
|
||||||
const apiError = err.response.data as ApiError;
|
|
||||||
const messages = Array.isArray(apiError.message)
|
|
||||||
? apiError.message.map((m) => `${m.field}: ${m.message}`).join('\n')
|
|
||||||
: apiError.message;
|
|
||||||
setError(messages);
|
|
||||||
} else {
|
|
||||||
setError(err instanceof Error ? err.message : 'Failed to create Task');
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
console.log(name, value);
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
[name]: value,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchJuniors = async () => {
|
|
||||||
try {
|
|
||||||
const response = await juniorsApi.getJuniors(1, 50);
|
|
||||||
const data = response.data as PaginatedResponse<Junior>;
|
|
||||||
setJuniors(data.data);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to load juniors:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSelectChange = (e: SelectChangeEvent) => {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
[name as string]: value,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
console.log('Form data updated:', formData);
|
|
||||||
}, [formData]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchJuniors();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleTaskImageUpload = (documentId: string) => {
|
|
||||||
console.log('task image ID uploaded:', documentId);
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
imageId: documentId,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCheckedInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
isProofRequired: e.target.checked,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Typography variant="h4" gutterBottom>
|
|
||||||
Add New Task
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Paper sx={{ p: 3, maxWidth: 600, mx: 'auto' }}>
|
|
||||||
{error && (
|
|
||||||
<Alert severity="error" sx={{ mb: 3, whiteSpace: 'pre-line' }}>
|
|
||||||
{error}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box component="form" onSubmit={handleSubmit}>
|
|
||||||
<Grid container spacing={3}>
|
|
||||||
<Grid item xs={12} sm={12}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Title"
|
|
||||||
name="title"
|
|
||||||
value={formData.title}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
placeholder="Task Title"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
<Grid item xs={12} sm={12}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Description"
|
|
||||||
name="description"
|
|
||||||
value={formData.description}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
placeholder="Task Description"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid item xs={12} sm={12}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Due Date"
|
|
||||||
name="dueDate"
|
|
||||||
type="date"
|
|
||||||
value={formData.dueDate}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
InputLabelProps={{
|
|
||||||
shrink: true,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid item xs={12} sm={12}>
|
|
||||||
<TextField
|
|
||||||
fullWidth
|
|
||||||
label="Reward Amount"
|
|
||||||
name="rewardAmount"
|
|
||||||
type="number"
|
|
||||||
value={formData.rewardAmount}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid item xs={12}>
|
|
||||||
<FormControl fullWidth>
|
|
||||||
<InputLabel>Junior</InputLabel>
|
|
||||||
<Select name="juniorId" value={formData.juniorId} label="Junior" onChange={handleSelectChange}>
|
|
||||||
<MenuItem value="">Select Junior</MenuItem>
|
|
||||||
{juniors.map((junior) => (
|
|
||||||
<MenuItem key={junior.id} value={junior.id}>
|
|
||||||
{junior.fullName}
|
|
||||||
</MenuItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid item xs={12} sm={12}>
|
|
||||||
<DocumentUpload
|
|
||||||
documentType={DocumentType.PASSPORT}
|
|
||||||
label="Upload Task Image"
|
|
||||||
onUploadSuccess={handleTaskImageUpload}
|
|
||||||
/>
|
|
||||||
{formData.imageId && (
|
|
||||||
<Typography variant="caption" color="success.main" sx={{ mt: 1, display: 'block' }}>
|
|
||||||
Task Image uploaded (ID: {formData.imageId})
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid item xs={12}>
|
|
||||||
<FormControl fullWidth>
|
|
||||||
<FormControlLabel
|
|
||||||
control={
|
|
||||||
<Checkbox checked={formData.isProofRequired} onChange={handleCheckedInputChange} color="primary" />
|
|
||||||
}
|
|
||||||
label="Proof Required"
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
</Grid>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Box sx={{ mt: 3, display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
|
|
||||||
<Button variant="outlined" onClick={() => navigate('/juniors')}>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button type="submit" variant="contained" disabled={loading}>
|
|
||||||
{loading ? 'Adding...' : 'Add Task'}
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,87 +0,0 @@
|
|||||||
import { Box, Card, CardContent, Chip, CircularProgress, Typography } from '@mui/material';
|
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
import { useNavigate, useParams } from 'react-router-dom';
|
|
||||||
import { tasksApi } from '../../api/client';
|
|
||||||
import { Task } from '../../types/task';
|
|
||||||
|
|
||||||
export const TaskDetails = () => {
|
|
||||||
useNavigate();
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const statusColors = {
|
|
||||||
PENDING: 'warning',
|
|
||||||
IN_PROGRESS: 'info',
|
|
||||||
COMPLETED: 'success',
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const { taskId } = useParams();
|
|
||||||
if (!taskId) {
|
|
||||||
throw new Error('Task ID is required');
|
|
||||||
}
|
|
||||||
const [task, setTask] = useState<Task>();
|
|
||||||
const fetchTask = async () => {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
const response = await tasksApi.getTaskById(taskId);
|
|
||||||
setTask(response.data.data);
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'Failed to load task');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchTask();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
|
|
||||||
<CircularProgress />
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Typography color="error">{error}</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!task) {
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Typography color="error">Task not found</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
console.log(task);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card>
|
|
||||||
<CardContent>
|
|
||||||
<Box display="flex" justifyContent="space-between" alignItems="flex-start">
|
|
||||||
<Typography variant="h6" gutterBottom>
|
|
||||||
{task.title}
|
|
||||||
</Typography>
|
|
||||||
<Chip label={task.status} color={statusColors[task.status]} size="small" />
|
|
||||||
</Box>
|
|
||||||
<Typography color="textSecondary" gutterBottom>
|
|
||||||
Due: {new Date(task.dueDate).toLocaleDateString()}
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" gutterBottom>
|
|
||||||
{task.description}
|
|
||||||
</Typography>
|
|
||||||
<Typography color="primary" gutterBottom>
|
|
||||||
Reward: ${task.rewardAmount}
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" color="textSecondary">
|
|
||||||
Assigned to: {task.junior.fullName}
|
|
||||||
</Typography>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,200 +0,0 @@
|
|||||||
import {
|
|
||||||
Box,
|
|
||||||
Button,
|
|
||||||
Card,
|
|
||||||
CardContent,
|
|
||||||
Chip,
|
|
||||||
CircularProgress,
|
|
||||||
FormControl,
|
|
||||||
Grid,
|
|
||||||
InputLabel,
|
|
||||||
MenuItem,
|
|
||||||
Pagination,
|
|
||||||
Select,
|
|
||||||
SelectChangeEvent,
|
|
||||||
Typography
|
|
||||||
} from '@mui/material';
|
|
||||||
import React, { useEffect, useState } from 'react';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { juniorsApi, tasksApi } from '../../api/client';
|
|
||||||
import { Junior, PaginatedResponse } from '../../types/junior';
|
|
||||||
import { Task, TaskStatus } from '../../types/task';
|
|
||||||
|
|
||||||
const statusColors = {
|
|
||||||
PENDING: 'warning',
|
|
||||||
IN_PROGRESS: 'info',
|
|
||||||
COMPLETED: 'success'
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export const TasksList = () => {
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [tasks, setTasks] = useState<Task[]>([]);
|
|
||||||
const [juniors, setJuniors] = useState<Junior[]>([]);
|
|
||||||
const [page, setPage] = useState(1);
|
|
||||||
const [totalPages, setTotalPages] = useState(1);
|
|
||||||
const [status, setStatus] = useState<TaskStatus>('PENDING');
|
|
||||||
const [selectedJuniorId, setSelectedJuniorId] = useState<string>('');
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
const fetchJuniors = async () => {
|
|
||||||
try {
|
|
||||||
const response = await juniorsApi.getJuniors(1, 50);
|
|
||||||
const data = response.data as PaginatedResponse<Junior>;
|
|
||||||
setJuniors(data.data);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to load juniors:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchTasks = async (pageNum: number) => {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
const response = await tasksApi.getTasks(status, pageNum, 10, selectedJuniorId || undefined);
|
|
||||||
const data = response.data as PaginatedResponse<Task>;
|
|
||||||
setTasks(data.data);
|
|
||||||
setTotalPages(data.meta.pageCount);
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : 'Failed to load tasks');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchJuniors();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchTasks(page);
|
|
||||||
}, [page, status, selectedJuniorId]);
|
|
||||||
|
|
||||||
const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
|
|
||||||
setPage(value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleStatusChange = (event: SelectChangeEvent) => {
|
|
||||||
setStatus(event.target.value as TaskStatus);
|
|
||||||
setPage(1);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleJuniorChange = (event: SelectChangeEvent) => {
|
|
||||||
setSelectedJuniorId(event.target.value);
|
|
||||||
setPage(1);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading && page === 1) {
|
|
||||||
return (
|
|
||||||
<Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
|
|
||||||
<CircularProgress />
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Typography color="error">{error}</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
|
|
||||||
<Typography variant="h4">Tasks</Typography>
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
color="primary"
|
|
||||||
onClick={() => navigate('/tasks/new')}
|
|
||||||
>
|
|
||||||
Create Task
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box display="flex" gap={2} mb={3}>
|
|
||||||
<FormControl sx={{ minWidth: 200 }}>
|
|
||||||
<InputLabel>Status</InputLabel>
|
|
||||||
<Select
|
|
||||||
value={status}
|
|
||||||
label="Status"
|
|
||||||
onChange={handleStatusChange}
|
|
||||||
>
|
|
||||||
<MenuItem value="PENDING">Pending</MenuItem>
|
|
||||||
<MenuItem value="IN_PROGRESS">In Progress</MenuItem>
|
|
||||||
<MenuItem value="COMPLETED">Completed</MenuItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
|
|
||||||
<FormControl sx={{ minWidth: 200 }}>
|
|
||||||
<InputLabel>Junior</InputLabel>
|
|
||||||
<Select
|
|
||||||
value={selectedJuniorId}
|
|
||||||
label="Junior"
|
|
||||||
onChange={handleJuniorChange}
|
|
||||||
>
|
|
||||||
<MenuItem value="">All Juniors</MenuItem>
|
|
||||||
{juniors.map(junior => (
|
|
||||||
<MenuItem key={junior.id} value={junior.id}>
|
|
||||||
{junior.fullName}
|
|
||||||
</MenuItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Grid container spacing={3}>
|
|
||||||
{tasks.map((task) => (
|
|
||||||
<Grid item xs={12} sm={6} md={4} key={task.id}>
|
|
||||||
<Card>
|
|
||||||
<CardContent>
|
|
||||||
<Box display="flex" justifyContent="space-between" alignItems="flex-start">
|
|
||||||
<Typography variant="h6" gutterBottom>
|
|
||||||
{task.title}
|
|
||||||
</Typography>
|
|
||||||
<Chip
|
|
||||||
label={task.status}
|
|
||||||
color={statusColors[task.status]}
|
|
||||||
size="small"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
<Typography color="textSecondary" gutterBottom>
|
|
||||||
Due: {new Date(task.dueDate).toLocaleDateString()}
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" gutterBottom>
|
|
||||||
{task.description}
|
|
||||||
</Typography>
|
|
||||||
<Typography color="primary" gutterBottom>
|
|
||||||
Reward: ${task.rewardAmount}
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" color="textSecondary">
|
|
||||||
Assigned to: {task.junior.fullName}
|
|
||||||
</Typography>
|
|
||||||
<Box mt={2}>
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
fullWidth
|
|
||||||
onClick={() => navigate(`/tasks/${task.id}`)}
|
|
||||||
>
|
|
||||||
View Details
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</Grid>
|
|
||||||
))}
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<Box display="flex" justifyContent="center" mt={4}>
|
|
||||||
<Pagination
|
|
||||||
count={totalPages}
|
|
||||||
page={page}
|
|
||||||
onChange={handlePageChange}
|
|
||||||
color="primary"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,119 +0,0 @@
|
|||||||
import React, { createContext, useCallback, useContext, useState } from 'react';
|
|
||||||
import { authApi } from '../api/client';
|
|
||||||
import { LoginRequest, LoginResponse, User } from '../types/auth';
|
|
||||||
|
|
||||||
interface AuthContextType {
|
|
||||||
isAuthenticated: boolean;
|
|
||||||
user: User | null;
|
|
||||||
login: (loginRequest: LoginRequest) => Promise<void>;
|
|
||||||
logout: () => void;
|
|
||||||
register: (countryCode: string, phoneNumber: string) => Promise<void>;
|
|
||||||
verifyOtp: (countryCode: string, phoneNumber: string, otp: string) => Promise<string>;
|
|
||||||
setEmail: (email: string) => Promise<void>;
|
|
||||||
setPasscode: (passcode: string) => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextType | null>(null);
|
|
||||||
|
|
||||||
export const useAuth = () => {
|
|
||||||
const context = useContext(AuthContext);
|
|
||||||
if (!context) {
|
|
||||||
throw new Error('useAuth must be used within an AuthProvider');
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|
||||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
|
||||||
const [user, setUser] = useState<User | null>(null);
|
|
||||||
|
|
||||||
const login = useCallback(async (loginRequest: LoginRequest) => {
|
|
||||||
try {
|
|
||||||
const response = await authApi.login(loginRequest);
|
|
||||||
const loginData = response.data.data as LoginResponse;
|
|
||||||
setUser(loginData.user);
|
|
||||||
// Store tokens
|
|
||||||
localStorage.setItem('accessToken', loginData.accessToken);
|
|
||||||
localStorage.setItem('refreshToken', loginData.refreshToken);
|
|
||||||
setIsAuthenticated(true);
|
|
||||||
// Store tokens or other auth data in localStorage if needed
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Login failed:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const logout = useCallback(() => {
|
|
||||||
setUser(null);
|
|
||||||
setIsAuthenticated(false);
|
|
||||||
// Clear any stored auth data
|
|
||||||
localStorage.clear();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Registration state
|
|
||||||
const [registrationData, setRegistrationData] = useState<{
|
|
||||||
countryCode?: string;
|
|
||||||
phoneNumber?: string;
|
|
||||||
email?: string;
|
|
||||||
token?: string;
|
|
||||||
}>({});
|
|
||||||
|
|
||||||
const register = useCallback(async (countryCode: string, phoneNumber: string) => {
|
|
||||||
try {
|
|
||||||
await authApi.register(countryCode, phoneNumber);
|
|
||||||
setRegistrationData({ countryCode, phoneNumber });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Registration failed:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const verifyOtp = useCallback(async (countryCode: string, phoneNumber: string, otp: string) => {
|
|
||||||
try {
|
|
||||||
const response = await authApi.verifyOtp(countryCode, phoneNumber, otp);
|
|
||||||
console.log('OTP verification response:', response.data);
|
|
||||||
const { accessToken } = response.data.data;
|
|
||||||
console.log('Access token:', accessToken);
|
|
||||||
// Store token in localStorage immediately
|
|
||||||
localStorage.setItem('accessToken', accessToken);
|
|
||||||
setRegistrationData((prev) => ({ ...prev, token: accessToken }));
|
|
||||||
return accessToken;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('OTP verification failed:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const setEmail = useCallback(async (email: string) => {
|
|
||||||
try {
|
|
||||||
await authApi.setEmail(email);
|
|
||||||
setRegistrationData((prev) => ({ ...prev, email }));
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Setting email failed:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const setPasscode = useCallback(async (passcode: string) => {
|
|
||||||
try {
|
|
||||||
await authApi.setPasscode(passcode);
|
|
||||||
setIsAuthenticated(true);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Setting passcode failed:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const value = {
|
|
||||||
isAuthenticated,
|
|
||||||
user,
|
|
||||||
login,
|
|
||||||
logout,
|
|
||||||
register,
|
|
||||||
verifyOtp,
|
|
||||||
setEmail,
|
|
||||||
setPasscode,
|
|
||||||
};
|
|
||||||
|
|
||||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
||||||
};
|
|
@ -1,6 +0,0 @@
|
|||||||
export enum GrantType {
|
|
||||||
PASSWORD = 'PASSWORD',
|
|
||||||
APPLE = 'APPLE',
|
|
||||||
GOOGLE = 'GOOGLE',
|
|
||||||
BIOMETRIC = 'BIOMETRIC',
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './grantType.enum';
|
|
@ -1,52 +0,0 @@
|
|||||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
|
||||||
|
|
||||||
* {
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
|
|
||||||
body {
|
|
||||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
|
||||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
|
||||||
sans-serif;
|
|
||||||
-webkit-font-smoothing: antialiased;
|
|
||||||
-moz-osx-font-smoothing: grayscale;
|
|
||||||
background-color: #F8F9FA;
|
|
||||||
color: #2D3748;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Custom scrollbar */
|
|
||||||
::-webkit-scrollbar {
|
|
||||||
width: 8px;
|
|
||||||
height: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
::-webkit-scrollbar-track {
|
|
||||||
background: #F8F9FA;
|
|
||||||
}
|
|
||||||
|
|
||||||
::-webkit-scrollbar-thumb {
|
|
||||||
background: #CBD5E0;
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
::-webkit-scrollbar-thumb:hover {
|
|
||||||
background: #A0AEC0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Smooth transitions */
|
|
||||||
a, button {
|
|
||||||
transition: all 0.2s ease-in-out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Remove focus outline for mouse users, keep for keyboard users */
|
|
||||||
:focus:not(:focus-visible) {
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Keep focus outline for keyboard users */
|
|
||||||
:focus-visible {
|
|
||||||
outline: 2px solid #00A7E1;
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
import ReactDOM from 'react-dom/client';
|
|
||||||
import App from './App';
|
|
||||||
import '@fontsource/roboto/300.css';
|
|
||||||
import '@fontsource/roboto/400.css';
|
|
||||||
import '@fontsource/roboto/500.css';
|
|
||||||
import '@fontsource/roboto/700.css';
|
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
|
||||||
<React.StrictMode>
|
|
||||||
<App />
|
|
||||||
</React.StrictMode>
|
|
||||||
);
|
|
@ -1,14 +0,0 @@
|
|||||||
interface ApiErrorField {
|
|
||||||
field: string;
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ApiError {
|
|
||||||
statusCode: number;
|
|
||||||
message: string | ApiErrorField[];
|
|
||||||
error: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ApiResponse<T> {
|
|
||||||
data: T;
|
|
||||||
}
|
|
@ -1,27 +0,0 @@
|
|||||||
import { GrantType } from '../enums';
|
|
||||||
|
|
||||||
export interface User {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
customerStatus?: string;
|
|
||||||
firstName?: string;
|
|
||||||
lastName?: string;
|
|
||||||
dateOfBirth?: string;
|
|
||||||
countryOfResidence?: string;
|
|
||||||
isJunior?: boolean;
|
|
||||||
isGuardian?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LoginResponse {
|
|
||||||
accessToken: string;
|
|
||||||
refreshToken: string;
|
|
||||||
user: User;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LoginRequest {
|
|
||||||
email?: string;
|
|
||||||
password?: string;
|
|
||||||
grantType: GrantType;
|
|
||||||
googleToken?: string;
|
|
||||||
appleToken?: string;
|
|
||||||
}
|
|
@ -1,9 +0,0 @@
|
|||||||
export enum DocumentType {
|
|
||||||
PROFILE_PICTURE = 'PROFILE_PICTURE',
|
|
||||||
PASSPORT = 'PASSPORT',
|
|
||||||
DEFAULT_AVATAR = 'DEFAULT_AVATAR',
|
|
||||||
DEFAULT_TASKS_LOGO = 'DEFAULT_TASKS_LOGO',
|
|
||||||
CUSTOM_AVATAR = 'CUSTOM_AVATAR',
|
|
||||||
CUSTOM_TASKS_LOGO = 'CUSTOM_TASKS_LOGO',
|
|
||||||
GOALS = 'GOALS'
|
|
||||||
}
|
|
@ -1,41 +0,0 @@
|
|||||||
export interface Junior {
|
|
||||||
id: string;
|
|
||||||
fullName: string;
|
|
||||||
relationship: string;
|
|
||||||
profilePicture?: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
extension: string;
|
|
||||||
documentType: string;
|
|
||||||
url: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CreateJuniorRequest {
|
|
||||||
countryCode: string;
|
|
||||||
phoneNumber: string;
|
|
||||||
firstName: string;
|
|
||||||
lastName: string;
|
|
||||||
dateOfBirth: string;
|
|
||||||
email: string;
|
|
||||||
relationship: string;
|
|
||||||
civilIdFrontId: string;
|
|
||||||
civilIdBackId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface JuniorTheme {
|
|
||||||
color: string;
|
|
||||||
avatarId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PaginatedResponse<T> {
|
|
||||||
data: T[];
|
|
||||||
meta: {
|
|
||||||
page: number;
|
|
||||||
size: number;
|
|
||||||
itemCount: number;
|
|
||||||
pageCount: number;
|
|
||||||
hasPreviousPage: boolean;
|
|
||||||
hasNextPage: boolean;
|
|
||||||
};
|
|
||||||
}
|
|
@ -1,42 +0,0 @@
|
|||||||
import { Junior } from './junior';
|
|
||||||
|
|
||||||
export interface Task {
|
|
||||||
id: string;
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED';
|
|
||||||
dueDate: string;
|
|
||||||
rewardAmount: number;
|
|
||||||
isProofRequired: boolean;
|
|
||||||
submission?: {
|
|
||||||
imageId?: string;
|
|
||||||
submittedAt?: string;
|
|
||||||
status?: 'PENDING' | 'APPROVED' | 'REJECTED';
|
|
||||||
};
|
|
||||||
junior: Junior;
|
|
||||||
image?: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
extension: string;
|
|
||||||
documentType: string;
|
|
||||||
url: string;
|
|
||||||
};
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CreateTaskRequest {
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
dueDate: string;
|
|
||||||
rewardAmount: number;
|
|
||||||
isProofRequired: boolean;
|
|
||||||
imageId?: string;
|
|
||||||
juniorId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TaskSubmission {
|
|
||||||
imageId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type TaskStatus = 'PENDING' | 'IN_PROGRESS' | 'COMPLETED';
|
|
1
client/src/vite-env.d.ts
vendored
1
client/src/vite-env.d.ts
vendored
@ -1 +0,0 @@
|
|||||||
/// <reference types="vite/client" />
|
|
@ -1,26 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
|
||||||
"target": "ES2020",
|
|
||||||
"useDefineForClassFields": true,
|
|
||||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
|
||||||
"module": "ESNext",
|
|
||||||
"skipLibCheck": true,
|
|
||||||
|
|
||||||
/* Bundler mode */
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"allowImportingTsExtensions": true,
|
|
||||||
"isolatedModules": true,
|
|
||||||
"moduleDetection": "force",
|
|
||||||
"noEmit": true,
|
|
||||||
"jsx": "react-jsx",
|
|
||||||
|
|
||||||
/* Linting */
|
|
||||||
"strict": true,
|
|
||||||
"noUnusedLocals": false,
|
|
||||||
"noUnusedParameters": false,
|
|
||||||
"noFallthroughCasesInSwitch": true,
|
|
||||||
"noUncheckedSideEffectImports": true
|
|
||||||
},
|
|
||||||
"include": ["src"]
|
|
||||||
}
|
|
@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"files": [],
|
|
||||||
"references": [
|
|
||||||
{ "path": "./tsconfig.app.json" },
|
|
||||||
{ "path": "./tsconfig.node.json" }
|
|
||||||
]
|
|
||||||
}
|
|
@ -1,24 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
|
||||||
"target": "ES2022",
|
|
||||||
"lib": ["ES2023"],
|
|
||||||
"module": "ESNext",
|
|
||||||
"skipLibCheck": true,
|
|
||||||
|
|
||||||
/* Bundler mode */
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"allowImportingTsExtensions": true,
|
|
||||||
"isolatedModules": true,
|
|
||||||
"moduleDetection": "force",
|
|
||||||
"noEmit": true,
|
|
||||||
|
|
||||||
/* Linting */
|
|
||||||
"strict": true,
|
|
||||||
"noUnusedLocals": true,
|
|
||||||
"noUnusedParameters": true,
|
|
||||||
"noFallthroughCasesInSwitch": true,
|
|
||||||
"noUncheckedSideEffectImports": true
|
|
||||||
},
|
|
||||||
"include": ["vite.config.ts"]
|
|
||||||
}
|
|
@ -1,16 +0,0 @@
|
|||||||
import react from '@vitejs/plugin-react';
|
|
||||||
import path from 'path';
|
|
||||||
import { defineConfig, loadEnv } from 'vite';
|
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
|
||||||
export default defineConfig(({ mode }) => {
|
|
||||||
const env = loadEnv(mode, path.join(process.cwd(), '..'), '');
|
|
||||||
return {
|
|
||||||
define: {
|
|
||||||
'process.env.REACT_APP_APPLE_CLIENT_ID': JSON.stringify(env.REACT_APP_APPLE_CLIENT_ID),
|
|
||||||
'process.env.REACT_APP_APPLE_REDIRECT_URI': JSON.stringify(env.REACT_APP_APPLE_REDIRECT_URI),
|
|
||||||
'process.env.GOOGLE_WEB_CLIENT_ID': JSON.stringify(env.GOOGLE_WEB_CLIENT_ID),
|
|
||||||
},
|
|
||||||
plugins: [react()],
|
|
||||||
};
|
|
||||||
});
|
|
@ -1,20 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { JuniorModule } from '~/junior/junior.module';
|
|
||||||
import { AllowanceChangeRequestController, AllowancesController } from './controllers';
|
|
||||||
import { Allowance, AllowanceChangeRequest } from './entities';
|
|
||||||
import { AllowanceChangeRequestsRepository, AllowancesRepository } from './repositories';
|
|
||||||
import { AllowanceChangeRequestsService, AllowancesService } from './services';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
controllers: [AllowancesController, AllowanceChangeRequestController],
|
|
||||||
imports: [TypeOrmModule.forFeature([Allowance, AllowanceChangeRequest]), JuniorModule],
|
|
||||||
providers: [
|
|
||||||
AllowancesService,
|
|
||||||
AllowancesRepository,
|
|
||||||
AllowanceChangeRequestsService,
|
|
||||||
AllowanceChangeRequestsRepository,
|
|
||||||
],
|
|
||||||
exports: [AllowancesService],
|
|
||||||
})
|
|
||||||
export class AllowanceModule {}
|
|
@ -1,81 +0,0 @@
|
|||||||
import { Body, Controller, Get, HttpCode, HttpStatus, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
|
||||||
import { Roles } from '~/auth/enums';
|
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
|
||||||
import { AllowedRoles, AuthenticatedUser } from '~/common/decorators';
|
|
||||||
import { RolesGuard } from '~/common/guards';
|
|
||||||
import { ApiDataPageResponse, ApiDataResponse, ApiLangRequestHeader } from '~/core/decorators';
|
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
|
||||||
import { CustomParseUUIDPipe } from '~/core/pipes';
|
|
||||||
import { ResponseFactory } from '~/core/utils';
|
|
||||||
import { CreateAllowanceChangeRequestDto } from '../dtos/request';
|
|
||||||
import { AllowanceChangeRequestResponseDto } from '../dtos/response';
|
|
||||||
import { AllowanceChangeRequestsService } from '../services';
|
|
||||||
|
|
||||||
@Controller('allowance-change-requests')
|
|
||||||
@ApiTags('Allowance Change Requests')
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@ApiLangRequestHeader()
|
|
||||||
export class AllowanceChangeRequestController {
|
|
||||||
constructor(private readonly allowanceChangeRequestsService: AllowanceChangeRequestsService) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.JUNIOR)
|
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
|
||||||
requestAllowanceChange(@AuthenticatedUser() { sub }: IJwtPayload, @Body() body: CreateAllowanceChangeRequestDto) {
|
|
||||||
return this.allowanceChangeRequestsService.createAllowanceChangeRequest(sub, body);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@ApiDataPageResponse(AllowanceChangeRequestResponseDto)
|
|
||||||
async findAllowanceChangeRequests(@AuthenticatedUser() { sub }: IJwtPayload, @Query() query: PageOptionsRequestDto) {
|
|
||||||
const [requests, itemCount] = await this.allowanceChangeRequestsService.findAllowanceChangeRequests(sub, query);
|
|
||||||
|
|
||||||
return ResponseFactory.dataPage(
|
|
||||||
requests.map((request) => new AllowanceChangeRequestResponseDto(request)),
|
|
||||||
{
|
|
||||||
itemCount,
|
|
||||||
page: query.page,
|
|
||||||
size: query.size,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get('/:changeRequestId')
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@ApiDataResponse(AllowanceChangeRequestResponseDto)
|
|
||||||
async findAllowanceChangeRequestById(
|
|
||||||
@AuthenticatedUser() { sub }: IJwtPayload,
|
|
||||||
@Param('changeRequestId', CustomParseUUIDPipe) changeRequestId: string,
|
|
||||||
) {
|
|
||||||
const request = await this.allowanceChangeRequestsService.findAllowanceChangeRequestById(sub, changeRequestId);
|
|
||||||
|
|
||||||
return ResponseFactory.data(new AllowanceChangeRequestResponseDto(request));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':changeRequestId/approve')
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
|
||||||
approveAllowanceChangeRequest(
|
|
||||||
@AuthenticatedUser() { sub }: IJwtPayload,
|
|
||||||
@Param('changeRequestId', CustomParseUUIDPipe) changeRequestId: string,
|
|
||||||
) {
|
|
||||||
return this.allowanceChangeRequestsService.approveAllowanceChangeRequest(sub, changeRequestId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':changeRequestId/reject')
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
|
||||||
rejectAllowanceChangeRequest(
|
|
||||||
@AuthenticatedUser() { sub }: IJwtPayload,
|
|
||||||
@Param('changeRequestId', CustomParseUUIDPipe) changeRequestId: string,
|
|
||||||
) {
|
|
||||||
return this.allowanceChangeRequestsService.rejectAllowanceChangeRequest(sub, changeRequestId);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,73 +0,0 @@
|
|||||||
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Query, UseGuards } from '@nestjs/common';
|
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
|
||||||
import { Roles } from '~/auth/enums';
|
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
|
||||||
import { AllowedRoles, AuthenticatedUser } from '~/common/decorators';
|
|
||||||
import { RolesGuard } from '~/common/guards';
|
|
||||||
import { ApiDataPageResponse, ApiDataResponse, ApiLangRequestHeader } from '~/core/decorators';
|
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
|
||||||
import { CustomParseUUIDPipe } from '~/core/pipes';
|
|
||||||
import { ResponseFactory } from '~/core/utils';
|
|
||||||
import { CreateAllowanceRequestDto } from '../dtos/request';
|
|
||||||
import { AllowanceResponseDto } from '../dtos/response';
|
|
||||||
import { AllowancesService } from '../services';
|
|
||||||
|
|
||||||
@Controller('allowances')
|
|
||||||
@ApiTags('Allowances')
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@ApiLangRequestHeader()
|
|
||||||
export class AllowancesController {
|
|
||||||
constructor(private readonly allowancesService: AllowancesService) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@ApiDataResponse(AllowanceResponseDto)
|
|
||||||
async createAllowance(@AuthenticatedUser() { sub }: IJwtPayload, @Body() body: CreateAllowanceRequestDto) {
|
|
||||||
const allowance = await this.allowancesService.createAllowance(sub, body);
|
|
||||||
|
|
||||||
return ResponseFactory.data(new AllowanceResponseDto(allowance));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@ApiDataPageResponse(AllowanceResponseDto)
|
|
||||||
async findAllowances(@AuthenticatedUser() { sub }: IJwtPayload, @Query() query: PageOptionsRequestDto) {
|
|
||||||
const [allowances, itemCount] = await this.allowancesService.findAllowances(sub, query);
|
|
||||||
|
|
||||||
return ResponseFactory.dataPage(
|
|
||||||
allowances.map((allowance) => new AllowanceResponseDto(allowance)),
|
|
||||||
{
|
|
||||||
itemCount,
|
|
||||||
page: query.page,
|
|
||||||
size: query.size,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get(':allowanceId')
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@ApiDataResponse(AllowanceResponseDto)
|
|
||||||
async findAllowanceById(
|
|
||||||
@AuthenticatedUser() { sub }: IJwtPayload,
|
|
||||||
@Param('allowanceId', CustomParseUUIDPipe) allowanceId: string,
|
|
||||||
) {
|
|
||||||
const allowance = await this.allowancesService.findAllowanceById(allowanceId, sub);
|
|
||||||
|
|
||||||
return ResponseFactory.data(new AllowanceResponseDto(allowance));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Delete(':allowanceId')
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@ApiDataResponse(AllowanceResponseDto)
|
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
|
||||||
deleteAllowance(
|
|
||||||
@AuthenticatedUser() { sub }: IJwtPayload,
|
|
||||||
@Param('allowanceId', CustomParseUUIDPipe) allowanceId: string,
|
|
||||||
) {
|
|
||||||
return this.allowancesService.deleteAllowance(sub, allowanceId);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
export * from './allowance-change-request.controller';
|
|
||||||
export * from './allowances.controller';
|
|
@ -1,28 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { IsNotEmpty, IsNumber, IsPositive, IsString, IsUUID } from 'class-validator';
|
|
||||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
|
||||||
|
|
||||||
export class CreateAllowanceChangeRequestDto {
|
|
||||||
@ApiProperty({ example: 'I want to change the amount of the allowance' })
|
|
||||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'allowanceChangeRequest.reason' }) })
|
|
||||||
@IsNotEmpty({
|
|
||||||
message: i18n('validation.IsNotEmpty', { path: 'general', property: 'allowanceChangeRequest.reason' }),
|
|
||||||
})
|
|
||||||
reason!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 100 })
|
|
||||||
@IsNumber(
|
|
||||||
{},
|
|
||||||
{ message: i18n('validation.IsNumber', { path: 'general', property: 'allowanceChangeRequest.amount' }) },
|
|
||||||
)
|
|
||||||
@IsPositive({
|
|
||||||
message: i18n('validation.IsPositive', { path: 'general', property: 'allowanceChangeRequest.amount' }),
|
|
||||||
})
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'd641bb71-2e7c-4e62-96fa-2785f0a651c6' })
|
|
||||||
@IsUUID('4', {
|
|
||||||
message: i18n('validation.IsUUID', { path: 'general', property: 'allowanceChangeRequest.allowanceId' }),
|
|
||||||
})
|
|
||||||
allowanceId!: string;
|
|
||||||
}
|
|
@ -1,52 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { Transform } from 'class-transformer';
|
|
||||||
import { IsDate, IsEnum, IsInt, IsNotEmpty, IsNumber, IsPositive, IsString, IsUUID, ValidateIf } from 'class-validator';
|
|
||||||
import moment from 'moment';
|
|
||||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
|
||||||
import { AllowanceFrequency, AllowanceType } from '~/allowance/enums';
|
|
||||||
export class CreateAllowanceRequestDto {
|
|
||||||
@ApiProperty({ example: 'Allowance name' })
|
|
||||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'allowance.name' }) })
|
|
||||||
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'allowance.name' }) })
|
|
||||||
name!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 100 })
|
|
||||||
@IsNumber({}, { message: i18n('validation.IsNumber', { path: 'general', property: 'allowance.amount' }) })
|
|
||||||
@IsPositive({ message: i18n('validation.IsPositive', { path: 'general', property: 'allowance.amount' }) })
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: AllowanceFrequency.WEEKLY })
|
|
||||||
@IsEnum(AllowanceFrequency, {
|
|
||||||
message: i18n('validation.IsEnum', { path: 'general', property: 'allowance.frequency' }),
|
|
||||||
})
|
|
||||||
frequency!: AllowanceFrequency;
|
|
||||||
|
|
||||||
@ApiProperty({ example: AllowanceType.BY_END_DATE })
|
|
||||||
@IsEnum(AllowanceType, { message: i18n('validation.IsEnum', { path: 'general', property: 'allowance.type' }) })
|
|
||||||
type!: AllowanceType;
|
|
||||||
|
|
||||||
@ApiProperty({ example: new Date() })
|
|
||||||
@IsDate({ message: i18n('validation.IsDate', { path: 'general', property: 'allowance.startDate' }) })
|
|
||||||
@Transform(({ value }) => moment(value).startOf('day').toDate())
|
|
||||||
startDate!: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ example: new Date() })
|
|
||||||
@IsDate({ message: i18n('validation.IsDate', { path: 'general', property: 'allowance.endDate' }) })
|
|
||||||
@Transform(({ value }) => moment(value).endOf('day').toDate())
|
|
||||||
@ValidateIf((o) => o.type === AllowanceType.BY_END_DATE)
|
|
||||||
endDate?: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 10 })
|
|
||||||
@IsNumber(
|
|
||||||
{},
|
|
||||||
{ message: i18n('validation.IsNumber', { path: 'general', property: 'allowance.numberOfTransactions' }) },
|
|
||||||
)
|
|
||||||
@IsInt({ message: i18n('validation.IsInt', { path: 'general', property: 'allowance.amount' }) })
|
|
||||||
@IsPositive({ message: i18n('validation.IsPositive', { path: 'general', property: 'allowance.amount' }) })
|
|
||||||
@ValidateIf((o) => o.type === AllowanceType.BY_COUNT)
|
|
||||||
numberOfTransactions?: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'e7b1b3b4-4b3b-4b3b-4b3b-4b3b4b3b4b3b' })
|
|
||||||
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'allowance.juniorId' }) })
|
|
||||||
juniorId!: string;
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
export * from './create-allowance-change.request.dto';
|
|
||||||
export * from './create-allowance.request.dto';
|
|
@ -1,45 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { AllowanceChangeRequest } from '~/allowance/entities';
|
|
||||||
import { AllowanceChangeRequestStatus } from '~/allowance/enums';
|
|
||||||
import { JuniorResponseDto } from '~/junior/dtos/response';
|
|
||||||
|
|
||||||
export class AllowanceChangeRequestResponseDto {
|
|
||||||
@ApiProperty({ example: 'd641bb71-2e7c-4e62-96fa-2785f0a651c6' })
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: AllowanceChangeRequestStatus.APPROVED })
|
|
||||||
status!: AllowanceChangeRequestStatus;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Allowance name' })
|
|
||||||
name!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '100' })
|
|
||||||
oldAmount!: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '200' })
|
|
||||||
newAmount!: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Some reason' })
|
|
||||||
reason!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'd641bb71-2e7c-4e62-96fa-2785f0a651c6' })
|
|
||||||
allowanceId!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ type: JuniorResponseDto })
|
|
||||||
junior!: JuniorResponseDto;
|
|
||||||
|
|
||||||
@ApiProperty({ example: new Date() })
|
|
||||||
createdAt!: Date;
|
|
||||||
|
|
||||||
constructor(allowanceChangeRequest: AllowanceChangeRequest) {
|
|
||||||
this.id = allowanceChangeRequest.id;
|
|
||||||
this.status = allowanceChangeRequest.status;
|
|
||||||
this.name = allowanceChangeRequest.allowance.name;
|
|
||||||
this.oldAmount = allowanceChangeRequest.allowance.amount;
|
|
||||||
this.newAmount = allowanceChangeRequest.amount;
|
|
||||||
this.reason = allowanceChangeRequest.reason;
|
|
||||||
this.allowanceId = allowanceChangeRequest.allowanceId;
|
|
||||||
this.junior = new JuniorResponseDto(allowanceChangeRequest.allowance.junior);
|
|
||||||
this.createdAt = allowanceChangeRequest.createdAt;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,53 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { Allowance } from '~/allowance/entities';
|
|
||||||
import { AllowanceFrequency, AllowanceType } from '~/allowance/enums';
|
|
||||||
import { JuniorResponseDto } from '~/junior/dtos/response';
|
|
||||||
|
|
||||||
export class AllowanceResponseDto {
|
|
||||||
@ApiProperty({ example: 'd641bb71-2e7c-4e62-96fa-2785f0a651c6' })
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Allowance name' })
|
|
||||||
name!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 100 })
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: AllowanceFrequency.WEEKLY })
|
|
||||||
frequency!: AllowanceFrequency;
|
|
||||||
|
|
||||||
@ApiProperty({ example: AllowanceType.BY_END_DATE })
|
|
||||||
type!: AllowanceType;
|
|
||||||
|
|
||||||
@ApiProperty({ example: new Date() })
|
|
||||||
startDate!: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ example: new Date() })
|
|
||||||
endDate?: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 10 })
|
|
||||||
numberOfTransactions?: number;
|
|
||||||
|
|
||||||
@ApiProperty({ type: JuniorResponseDto })
|
|
||||||
junior!: JuniorResponseDto;
|
|
||||||
|
|
||||||
@ApiProperty({ example: new Date() })
|
|
||||||
createdAt!: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ example: new Date() })
|
|
||||||
updatedAt!: Date;
|
|
||||||
|
|
||||||
constructor(allowance: Allowance) {
|
|
||||||
this.id = allowance.id;
|
|
||||||
this.name = allowance.name;
|
|
||||||
this.amount = allowance.amount;
|
|
||||||
this.frequency = allowance.frequency;
|
|
||||||
this.type = allowance.type;
|
|
||||||
this.startDate = allowance.startDate;
|
|
||||||
this.endDate = allowance.endDate;
|
|
||||||
this.numberOfTransactions = allowance.numberOfTransactions;
|
|
||||||
this.junior = new JuniorResponseDto(allowance.junior);
|
|
||||||
this.createdAt = allowance.createdAt;
|
|
||||||
this.updatedAt = allowance.updatedAt;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
export * from './allowance-change-request.response.dto';
|
|
||||||
export * from './allowance.response.dto';
|
|
@ -1,45 +0,0 @@
|
|||||||
import {
|
|
||||||
Column,
|
|
||||||
CreateDateColumn,
|
|
||||||
Entity,
|
|
||||||
JoinColumn,
|
|
||||||
ManyToOne,
|
|
||||||
PrimaryGeneratedColumn,
|
|
||||||
UpdateDateColumn,
|
|
||||||
} from 'typeorm';
|
|
||||||
import { AllowanceChangeRequestStatus } from '../enums';
|
|
||||||
import { Allowance } from './allowance.entity';
|
|
||||||
|
|
||||||
@Entity('allowance_change_requests')
|
|
||||||
export class AllowanceChangeRequest {
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'text', name: 'reason' })
|
|
||||||
reason!: string;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'decimal',
|
|
||||||
precision: 10,
|
|
||||||
scale: 2,
|
|
||||||
name: 'amount',
|
|
||||||
transformer: { to: (value: number) => value, from: (value: string) => parseFloat(value) },
|
|
||||||
})
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', length: 255, name: 'status', default: AllowanceChangeRequestStatus.PENDING })
|
|
||||||
status!: AllowanceChangeRequestStatus;
|
|
||||||
|
|
||||||
@Column({ type: 'uuid', name: 'allowance_id' })
|
|
||||||
allowanceId!: string;
|
|
||||||
|
|
||||||
@ManyToOne(() => Allowance, (allowance) => allowance.changeRequests)
|
|
||||||
@JoinColumn({ name: 'allowance_id' })
|
|
||||||
allowance!: Allowance;
|
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
createdAt!: Date;
|
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
updatedAt!: Date;
|
|
||||||
}
|
|
@ -1,107 +0,0 @@
|
|||||||
import moment from 'moment';
|
|
||||||
import {
|
|
||||||
Column,
|
|
||||||
CreateDateColumn,
|
|
||||||
DeleteDateColumn,
|
|
||||||
Entity,
|
|
||||||
JoinColumn,
|
|
||||||
ManyToOne,
|
|
||||||
OneToMany,
|
|
||||||
PrimaryGeneratedColumn,
|
|
||||||
UpdateDateColumn,
|
|
||||||
} from 'typeorm';
|
|
||||||
import { Guardian } from '~/guardian/entities/guradian.entity';
|
|
||||||
import { Junior } from '~/junior/entities';
|
|
||||||
import { AllowanceFrequency, AllowanceType } from '../enums';
|
|
||||||
import { AllowanceChangeRequest } from './allowance-change-request.entity';
|
|
||||||
@Entity('allowances')
|
|
||||||
export class Allowance {
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', length: 255, name: 'name' })
|
|
||||||
name!: string;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'decimal',
|
|
||||||
precision: 10,
|
|
||||||
scale: 2,
|
|
||||||
name: 'amount',
|
|
||||||
transformer: { to: (value: number) => value, from: (value: string) => parseFloat(value) },
|
|
||||||
})
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', length: 255, name: 'frequency' })
|
|
||||||
frequency!: AllowanceFrequency;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', length: 255, name: 'type' })
|
|
||||||
type!: AllowanceType;
|
|
||||||
|
|
||||||
@Column({ type: 'timestamp with time zone', name: 'start_date' })
|
|
||||||
startDate!: Date;
|
|
||||||
|
|
||||||
@Column({ type: 'timestamp with time zone', name: 'end_date', nullable: true })
|
|
||||||
endDate?: Date;
|
|
||||||
|
|
||||||
@Column({ type: 'int', name: 'number_of_transactions', nullable: true })
|
|
||||||
numberOfTransactions?: number;
|
|
||||||
|
|
||||||
@Column({ type: 'uuid', name: 'guardian_id' })
|
|
||||||
guardianId!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'uuid', name: 'junior_id' })
|
|
||||||
juniorId!: string;
|
|
||||||
|
|
||||||
@ManyToOne(() => Guardian, (guardian) => guardian.allowances)
|
|
||||||
@JoinColumn({ name: 'guardian_id' })
|
|
||||||
guardian!: Guardian;
|
|
||||||
|
|
||||||
@ManyToOne(() => Junior, (junior) => junior.allowances)
|
|
||||||
@JoinColumn({ name: 'junior_id' })
|
|
||||||
junior!: Junior;
|
|
||||||
|
|
||||||
@OneToMany(() => AllowanceChangeRequest, (changeRequest) => changeRequest.allowance)
|
|
||||||
changeRequests!: AllowanceChangeRequest[];
|
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
createdAt!: Date;
|
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
updatedAt!: Date;
|
|
||||||
|
|
||||||
@DeleteDateColumn({ name: 'deleted_at', type: 'timestamp with time zone', nullable: true })
|
|
||||||
deletedAt?: Date;
|
|
||||||
|
|
||||||
get nextPaymentDate(): Date | null {
|
|
||||||
const startDate = moment(this.startDate).clone().startOf('day');
|
|
||||||
const endDate = this.endDate ? moment(this.endDate).endOf('day') : null;
|
|
||||||
const now = moment().startOf('day');
|
|
||||||
|
|
||||||
if (endDate && moment().isAfter(endDate)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const calculateNextDate = (unit: moment.unitOfTime.Diff) => {
|
|
||||||
const diff = now.diff(startDate, unit);
|
|
||||||
const nextDate = startDate.clone().add(diff, unit);
|
|
||||||
const adjustedDate = nextDate.isSameOrAfter(now) ? nextDate : nextDate.add('1', unit);
|
|
||||||
|
|
||||||
if (endDate && adjustedDate.isAfter(endDate)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return adjustedDate.toDate();
|
|
||||||
};
|
|
||||||
|
|
||||||
switch (this.frequency) {
|
|
||||||
case AllowanceFrequency.DAILY:
|
|
||||||
return calculateNextDate('days');
|
|
||||||
case AllowanceFrequency.WEEKLY:
|
|
||||||
return calculateNextDate('weeks');
|
|
||||||
case AllowanceFrequency.MONTHLY:
|
|
||||||
return calculateNextDate('months');
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
export * from './allowance-change-request.entity';
|
|
||||||
export * from './allowance.entity';
|
|
@ -1,5 +0,0 @@
|
|||||||
export enum AllowanceChangeRequestStatus {
|
|
||||||
PENDING = 'PENDING',
|
|
||||||
APPROVED = 'APPROVED',
|
|
||||||
REJECTED = 'REJECTED',
|
|
||||||
}
|
|
@ -1,5 +0,0 @@
|
|||||||
export enum AllowanceFrequency {
|
|
||||||
DAILY = 'DAILY',
|
|
||||||
WEEKLY = 'WEEKLY',
|
|
||||||
MONTHLY = 'MONTHLY',
|
|
||||||
}
|
|
@ -1,4 +0,0 @@
|
|||||||
export enum AllowanceType {
|
|
||||||
BY_END_DATE = 'BY_END_DATE',
|
|
||||||
BY_COUNT = 'BY_COUNT',
|
|
||||||
}
|
|
@ -1,3 +0,0 @@
|
|||||||
export * from './allowance-change-request-status.enum';
|
|
||||||
export * from './allowance-frequency.enum';
|
|
||||||
export * from './allowance-type.enum';
|
|
@ -1,50 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { FindOptionsWhere, Repository } from 'typeorm';
|
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
|
||||||
import { CreateAllowanceChangeRequestDto } from '../dtos/request';
|
|
||||||
import { AllowanceChangeRequest } from '../entities';
|
|
||||||
import { AllowanceChangeRequestStatus } from '../enums';
|
|
||||||
const ONE = 1;
|
|
||||||
@Injectable()
|
|
||||||
export class AllowanceChangeRequestsRepository {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(AllowanceChangeRequest)
|
|
||||||
private readonly allowanceChangeRequestsRepository: Repository<AllowanceChangeRequest>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
createAllowanceChangeRequest(allowanceId: string, body: CreateAllowanceChangeRequestDto) {
|
|
||||||
return this.allowanceChangeRequestsRepository.save(
|
|
||||||
this.allowanceChangeRequestsRepository.create({
|
|
||||||
allowanceId,
|
|
||||||
amount: body.amount,
|
|
||||||
reason: body.reason,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
findAllowanceChangeRequestBy(where: FindOptionsWhere<AllowanceChangeRequest>, withRelations = false) {
|
|
||||||
const relations = withRelations
|
|
||||||
? ['allowance', 'allowance.junior', 'allowance.junior.customer', 'allowance.junior.customer.profilePicture']
|
|
||||||
: [];
|
|
||||||
return this.allowanceChangeRequestsRepository.findOne({ where, relations });
|
|
||||||
}
|
|
||||||
|
|
||||||
updateAllowanceChangeRequestStatus(requestId: string, status: AllowanceChangeRequestStatus) {
|
|
||||||
return this.allowanceChangeRequestsRepository.update({ id: requestId }, { status });
|
|
||||||
}
|
|
||||||
|
|
||||||
findAllowanceChangeRequests(guardianId: string, query: PageOptionsRequestDto) {
|
|
||||||
return this.allowanceChangeRequestsRepository.findAndCount({
|
|
||||||
where: { allowance: { guardianId } },
|
|
||||||
take: query.size,
|
|
||||||
skip: query.size * (query.page - ONE),
|
|
||||||
relations: [
|
|
||||||
'allowance',
|
|
||||||
'allowance.junior',
|
|
||||||
'allowance.junior.customer',
|
|
||||||
'allowance.junior.customer.profilePicture',
|
|
||||||
],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,64 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
|
||||||
import { CreateAllowanceRequestDto } from '../dtos/request';
|
|
||||||
import { Allowance } from '../entities';
|
|
||||||
const ONE = 1;
|
|
||||||
@Injectable()
|
|
||||||
export class AllowancesRepository {
|
|
||||||
constructor(@InjectRepository(Allowance) private readonly allowancesRepository: Repository<Allowance>) {}
|
|
||||||
|
|
||||||
createAllowance(guardianId: string, body: CreateAllowanceRequestDto) {
|
|
||||||
return this.allowancesRepository.save(
|
|
||||||
this.allowancesRepository.create({
|
|
||||||
guardianId,
|
|
||||||
name: body.name,
|
|
||||||
amount: body.amount,
|
|
||||||
frequency: body.frequency,
|
|
||||||
type: body.type,
|
|
||||||
startDate: body.startDate,
|
|
||||||
endDate: body.endDate,
|
|
||||||
numberOfTransactions: body.numberOfTransactions,
|
|
||||||
juniorId: body.juniorId,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
findAllowanceById(allowanceId: string, guardianId?: string) {
|
|
||||||
return this.allowancesRepository.findOne({
|
|
||||||
where: { id: allowanceId, guardianId },
|
|
||||||
relations: ['junior', 'junior.customer', 'junior.customer.profilePicture'],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
findAllowances(guardianId: string, query: PageOptionsRequestDto) {
|
|
||||||
return this.allowancesRepository.findAndCount({
|
|
||||||
where: { guardianId },
|
|
||||||
relations: ['junior', 'junior.customer', 'junior.customer.profilePicture'],
|
|
||||||
take: query.size,
|
|
||||||
skip: query.size * (query.page - ONE),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
deleteAllowance(guardianId: string, allowanceId: string) {
|
|
||||||
return this.allowancesRepository.softDelete({ id: allowanceId, guardianId });
|
|
||||||
}
|
|
||||||
|
|
||||||
async *findAllowancesChunks(chunkSize: number) {
|
|
||||||
let offset = 0;
|
|
||||||
while (true) {
|
|
||||||
const allowances = await this.allowancesRepository.find({
|
|
||||||
take: chunkSize,
|
|
||||||
skip: offset,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!allowances.length) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
yield allowances;
|
|
||||||
offset += chunkSize;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
export * from './allowance-change-request.repository';
|
|
||||||
export * from './allowances.repository';
|
|
@ -1,132 +0,0 @@
|
|||||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
|
||||||
import { FindOptionsWhere } from 'typeorm';
|
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
|
||||||
import { OciService } from '~/document/services';
|
|
||||||
import { CreateAllowanceChangeRequestDto } from '../dtos/request';
|
|
||||||
import { AllowanceChangeRequest } from '../entities';
|
|
||||||
import { AllowanceChangeRequestStatus } from '../enums';
|
|
||||||
import { AllowanceChangeRequestsRepository } from '../repositories';
|
|
||||||
import { AllowancesService } from './allowances.service';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AllowanceChangeRequestsService {
|
|
||||||
private readonly logger = new Logger(AllowanceChangeRequestsService.name);
|
|
||||||
constructor(
|
|
||||||
private readonly allowanceChangeRequestsRepository: AllowanceChangeRequestsRepository,
|
|
||||||
private readonly ociService: OciService,
|
|
||||||
private readonly allowanceService: AllowancesService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async createAllowanceChangeRequest(juniorId: string, body: CreateAllowanceChangeRequestDto) {
|
|
||||||
this.logger.log(`Creating allowance change request for junior ${juniorId}`);
|
|
||||||
const allowance = await this.allowanceService.validateAllowanceForJunior(juniorId, body.allowanceId);
|
|
||||||
|
|
||||||
if (allowance.amount === body.amount) {
|
|
||||||
this.logger.error(`Amount is the same as the current allowance amount`);
|
|
||||||
throw new BadRequestException('ALLOWANCE_CHANGE_REQUEST.SAME_AMOUNT');
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestWithTheSameAmount = await this.findAllowanceChangeRequestBy({
|
|
||||||
allowanceId: body.allowanceId,
|
|
||||||
amount: body.amount,
|
|
||||||
status: AllowanceChangeRequestStatus.PENDING,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (requestWithTheSameAmount) {
|
|
||||||
this.logger.error(`There is a pending request with the same amount`);
|
|
||||||
throw new BadRequestException('ALLOWANCE_CHANGE_REQUEST.SAME_AMOUNT_PENDING');
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.allowanceChangeRequestsRepository.createAllowanceChangeRequest(body.allowanceId, body);
|
|
||||||
}
|
|
||||||
|
|
||||||
findAllowanceChangeRequestBy(where: FindOptionsWhere<AllowanceChangeRequest>) {
|
|
||||||
this.logger.log(`Finding allowance change request by ${JSON.stringify(where)}`);
|
|
||||||
return this.allowanceChangeRequestsRepository.findAllowanceChangeRequestBy(where);
|
|
||||||
}
|
|
||||||
|
|
||||||
async approveAllowanceChangeRequest(guardianId: string, requestId: string) {
|
|
||||||
this.logger.log(`Approving allowance change request ${requestId} by guardian ${guardianId}`);
|
|
||||||
const request = await this.findAllowanceChangeRequestBy({ id: requestId, allowance: { guardianId } });
|
|
||||||
|
|
||||||
if (!request) {
|
|
||||||
this.logger.error(`Allowance change request ${requestId} not found for guardian ${guardianId}`);
|
|
||||||
throw new BadRequestException('ALLOWANCE_CHANGE_REQUEST.NOT_FOUND');
|
|
||||||
}
|
|
||||||
if (request.status === AllowanceChangeRequestStatus.APPROVED) {
|
|
||||||
this.logger.error(`Allowance change request ${requestId} already approved`);
|
|
||||||
throw new BadRequestException('ALLOWANCE_CHANGE_REQUEST.ALREADY_APPROVED');
|
|
||||||
}
|
|
||||||
return this.allowanceChangeRequestsRepository.updateAllowanceChangeRequestStatus(
|
|
||||||
requestId,
|
|
||||||
AllowanceChangeRequestStatus.APPROVED,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async rejectAllowanceChangeRequest(guardianId: string, requestId: string) {
|
|
||||||
this.logger.log(`Rejecting allowance change request ${requestId} by guardian ${guardianId}`);
|
|
||||||
const request = await this.findAllowanceChangeRequestBy({ id: requestId, allowance: { guardianId } });
|
|
||||||
|
|
||||||
if (!request) {
|
|
||||||
this.logger.error(`Allowance change request ${requestId} not found for guardian ${guardianId}`);
|
|
||||||
throw new BadRequestException('ALLOWANCE_CHANGE_REQUEST.NOT_FOUND');
|
|
||||||
}
|
|
||||||
if (request.status === AllowanceChangeRequestStatus.REJECTED) {
|
|
||||||
this.logger.error(`Allowance change request ${requestId} already rejected`);
|
|
||||||
throw new BadRequestException('ALLOWANCE_CHANGE_REQUEST.ALREADY_REJECTED');
|
|
||||||
}
|
|
||||||
return this.allowanceChangeRequestsRepository.updateAllowanceChangeRequestStatus(
|
|
||||||
requestId,
|
|
||||||
AllowanceChangeRequestStatus.REJECTED,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async findAllowanceChangeRequests(
|
|
||||||
guardianId: string,
|
|
||||||
query: PageOptionsRequestDto,
|
|
||||||
): Promise<[AllowanceChangeRequest[], number]> {
|
|
||||||
this.logger.log(`Finding allowance change requests for guardian ${guardianId}`);
|
|
||||||
const [requests, itemCount] = await this.allowanceChangeRequestsRepository.findAllowanceChangeRequests(
|
|
||||||
guardianId,
|
|
||||||
query,
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.prepareAllowanceChangeRequestsImages(requests);
|
|
||||||
|
|
||||||
this.logger.log(`Returning allowance change requests for guardian ${guardianId}`);
|
|
||||||
return [requests, itemCount];
|
|
||||||
}
|
|
||||||
|
|
||||||
async findAllowanceChangeRequestById(guardianId: string, requestId: string) {
|
|
||||||
this.logger.log(`Finding allowance change request ${requestId} for guardian ${guardianId}`);
|
|
||||||
const request = await this.allowanceChangeRequestsRepository.findAllowanceChangeRequestBy(
|
|
||||||
{
|
|
||||||
id: requestId,
|
|
||||||
allowance: { guardianId },
|
|
||||||
},
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!request) {
|
|
||||||
this.logger.error(`Allowance change request ${requestId} not found for guardian ${guardianId}`);
|
|
||||||
throw new BadRequestException('ALLOWANCE_CHANGE_REQUEST.NOT_FOUND');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.prepareAllowanceChangeRequestsImages([request]);
|
|
||||||
|
|
||||||
this.logger.log(`Allowance change request ${requestId} found successfully`);
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|
||||||
private prepareAllowanceChangeRequestsImages(requests: AllowanceChangeRequest[]) {
|
|
||||||
this.logger.log(`Preparing allowance change requests images`);
|
|
||||||
return Promise.all(
|
|
||||||
requests.map(async (request) => {
|
|
||||||
const profilePicture = request.allowance.junior.customer.profilePicture;
|
|
||||||
if (profilePicture) {
|
|
||||||
profilePicture.url = await this.ociService.generatePreSignedUrl(profilePicture);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,110 +0,0 @@
|
|||||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
|
||||||
import moment from 'moment';
|
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
|
||||||
import { OciService } from '~/document/services';
|
|
||||||
import { JuniorService } from '~/junior/services';
|
|
||||||
import { CreateAllowanceRequestDto } from '../dtos/request';
|
|
||||||
import { Allowance } from '../entities';
|
|
||||||
import { AllowancesRepository } from '../repositories';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AllowancesService {
|
|
||||||
private readonly logger = new Logger(AllowancesService.name);
|
|
||||||
constructor(
|
|
||||||
private readonly allowancesRepository: AllowancesRepository,
|
|
||||||
private readonly juniorService: JuniorService,
|
|
||||||
private readonly ociService: OciService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async createAllowance(guardianId: string, body: CreateAllowanceRequestDto) {
|
|
||||||
this.logger.log(`Creating allowance for junior ${body.juniorId} by guardian ${guardianId}`);
|
|
||||||
if (moment(body.startDate).isBefore(moment().startOf('day'))) {
|
|
||||||
this.logger.error(`Start date ${body.startDate} is before today`);
|
|
||||||
throw new BadRequestException('ALLOWANCE.START_DATE_BEFORE_TODAY');
|
|
||||||
}
|
|
||||||
if (moment(body.startDate).isAfter(body.endDate)) {
|
|
||||||
this.logger.error(`Start date ${body.startDate} is after end date ${body.endDate}`);
|
|
||||||
throw new BadRequestException('ALLOWANCE.START_DATE_AFTER_END_DATE');
|
|
||||||
}
|
|
||||||
|
|
||||||
const doesJuniorBelongToGuardian = await this.juniorService.doesJuniorBelongToGuardian(guardianId, body.juniorId);
|
|
||||||
|
|
||||||
if (!doesJuniorBelongToGuardian) {
|
|
||||||
this.logger.error(`Junior ${body.juniorId} does not belong to guardian ${guardianId}`);
|
|
||||||
throw new BadRequestException('JUNIOR.DOES_NOT_BELONG_TO_GUARDIAN');
|
|
||||||
}
|
|
||||||
|
|
||||||
const allowance = await this.allowancesRepository.createAllowance(guardianId, body);
|
|
||||||
|
|
||||||
this.logger.log(`Allowance ${allowance.id} created successfully`);
|
|
||||||
return this.findAllowanceById(allowance.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
async findAllowanceById(allowanceId: string, guardianId?: string) {
|
|
||||||
this.logger.log(`Finding allowance ${allowanceId} ${guardianId ? `by guardian ${guardianId}` : ''}`);
|
|
||||||
const allowance = await this.allowancesRepository.findAllowanceById(allowanceId, guardianId);
|
|
||||||
|
|
||||||
if (!allowance) {
|
|
||||||
this.logger.error(`Allowance ${allowanceId} not found ${guardianId ? `for guardian ${guardianId}` : ''}`);
|
|
||||||
throw new BadRequestException('ALLOWANCE.NOT_FOUND');
|
|
||||||
}
|
|
||||||
await this.prepareAllowanceDocuments([allowance]);
|
|
||||||
this.logger.log(`Allowance ${allowanceId} found successfully`);
|
|
||||||
return allowance;
|
|
||||||
}
|
|
||||||
|
|
||||||
async findAllowances(guardianId: string, query: PageOptionsRequestDto): Promise<[Allowance[], number]> {
|
|
||||||
this.logger.log(`Finding allowances for guardian ${guardianId}`);
|
|
||||||
const [allowances, itemCount] = await this.allowancesRepository.findAllowances(guardianId, query);
|
|
||||||
await this.prepareAllowanceDocuments(allowances);
|
|
||||||
this.logger.log(`Returning allowances for guardian ${guardianId}`);
|
|
||||||
return [allowances, itemCount];
|
|
||||||
}
|
|
||||||
|
|
||||||
async deleteAllowance(guardianId: string, allowanceId: string) {
|
|
||||||
this.logger.log(`Deleting allowance ${allowanceId} for guardian ${guardianId}`);
|
|
||||||
const { affected } = await this.allowancesRepository.deleteAllowance(guardianId, allowanceId);
|
|
||||||
|
|
||||||
if (!affected) {
|
|
||||||
this.logger.error(`Allowance ${allowanceId} not found`);
|
|
||||||
throw new BadRequestException('ALLOWANCE.NOT_FOUND');
|
|
||||||
}
|
|
||||||
this.logger.log(`Allowance ${allowanceId} deleted successfully`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateAllowanceForJunior(juniorId: string, allowanceId: string) {
|
|
||||||
this.logger.log(`Validating allowance ${allowanceId} for junior ${juniorId}`);
|
|
||||||
const allowance = await this.allowancesRepository.findAllowanceById(allowanceId);
|
|
||||||
|
|
||||||
if (!allowance) {
|
|
||||||
this.logger.error(`Allowance ${allowanceId} not found`);
|
|
||||||
throw new BadRequestException('ALLOWANCE.NOT_FOUND');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allowance.juniorId !== juniorId) {
|
|
||||||
this.logger.error(`Allowance ${allowanceId} does not belong to junior ${juniorId}`);
|
|
||||||
throw new BadRequestException('ALLOWANCE.DOES_NOT_BELONG_TO_JUNIOR');
|
|
||||||
}
|
|
||||||
|
|
||||||
return allowance;
|
|
||||||
}
|
|
||||||
|
|
||||||
async findAllowancesChunks(chunkSize: number) {
|
|
||||||
this.logger.log(`Finding allowances chunks`);
|
|
||||||
const allowances = await this.allowancesRepository.findAllowancesChunks(chunkSize);
|
|
||||||
this.logger.log(`Returning allowances chunks`);
|
|
||||||
return allowances;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async prepareAllowanceDocuments(allowance: Allowance[]) {
|
|
||||||
this.logger.log(`Preparing document for allowances`);
|
|
||||||
await Promise.all(
|
|
||||||
allowance.map(async (allowance) => {
|
|
||||||
const profilePicture = allowance.junior.customer.profilePicture;
|
|
||||||
if (profilePicture) {
|
|
||||||
profilePicture.url = await this.ociService.generatePreSignedUrl(profilePicture);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
export * from './allowance-change-requests.service';
|
|
||||||
export * from './allowances.service';
|
|
@ -8,7 +8,6 @@ import { I18nMiddleware, I18nModule } from 'nestjs-i18n';
|
|||||||
import { LoggerModule } from 'nestjs-pino';
|
import { LoggerModule } from 'nestjs-pino';
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { addTransactionalDataSource } from 'typeorm-transactional';
|
import { addTransactionalDataSource } from 'typeorm-transactional';
|
||||||
import { AllowanceModule } from './allowance/allowance.module';
|
|
||||||
import { AuthModule } from './auth/auth.module';
|
import { AuthModule } from './auth/auth.module';
|
||||||
import { CacheModule } from './common/modules/cache/cache.module';
|
import { CacheModule } from './common/modules/cache/cache.module';
|
||||||
import { LookupModule } from './common/modules/lookup/lookup.module';
|
import { LookupModule } from './common/modules/lookup/lookup.module';
|
||||||
@ -22,13 +21,9 @@ import { CronModule } from './cron/cron.module';
|
|||||||
import { CustomerModule } from './customer/customer.module';
|
import { CustomerModule } from './customer/customer.module';
|
||||||
import { migrations } from './db';
|
import { migrations } from './db';
|
||||||
import { DocumentModule } from './document/document.module';
|
import { DocumentModule } from './document/document.module';
|
||||||
import { GiftModule } from './gift/gift.module';
|
|
||||||
import { GuardianModule } from './guardian/guardian.module';
|
import { GuardianModule } from './guardian/guardian.module';
|
||||||
import { HealthModule } from './health/health.module';
|
import { HealthModule } from './health/health.module';
|
||||||
import { JuniorModule } from './junior/junior.module';
|
import { JuniorModule } from './junior/junior.module';
|
||||||
import { MoneyRequestModule } from './money-request/money-request.module';
|
|
||||||
import { SavingGoalsModule } from './saving-goals/saving-goals.module';
|
|
||||||
import { TaskModule } from './task/task.module';
|
|
||||||
import { UserModule } from './user/user.module';
|
import { UserModule } from './user/user.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
@ -41,7 +36,6 @@ import { UserModule } from './user/user.module';
|
|||||||
useFactory: (config: ConfigService) => {
|
useFactory: (config: ConfigService) => {
|
||||||
return buildTypeormOptions(config, migrations);
|
return buildTypeormOptions(config, migrations);
|
||||||
},
|
},
|
||||||
/* eslint-disable require-await */
|
|
||||||
async dataSourceFactory(options) {
|
async dataSourceFactory(options) {
|
||||||
if (!options) {
|
if (!options) {
|
||||||
throw new Error('Invalid options passed');
|
throw new Error('Invalid options passed');
|
||||||
@ -49,7 +43,6 @@ import { UserModule } from './user/user.module';
|
|||||||
|
|
||||||
return addTransactionalDataSource(new DataSource(options));
|
return addTransactionalDataSource(new DataSource(options));
|
||||||
},
|
},
|
||||||
/* eslint-enable require-await */
|
|
||||||
}),
|
}),
|
||||||
LoggerModule.forRootAsync({
|
LoggerModule.forRootAsync({
|
||||||
useFactory: (config: ConfigService) => buildLoggerOptions(config),
|
useFactory: (config: ConfigService) => buildLoggerOptions(config),
|
||||||
@ -61,15 +54,12 @@ import { UserModule } from './user/user.module';
|
|||||||
ScheduleModule.forRoot(),
|
ScheduleModule.forRoot(),
|
||||||
// App modules
|
// App modules
|
||||||
AuthModule,
|
AuthModule,
|
||||||
|
UserModule,
|
||||||
|
|
||||||
CustomerModule,
|
CustomerModule,
|
||||||
JuniorModule,
|
JuniorModule,
|
||||||
|
|
||||||
TaskModule,
|
|
||||||
GuardianModule,
|
GuardianModule,
|
||||||
SavingGoalsModule,
|
|
||||||
AllowanceModule,
|
|
||||||
MoneyRequestModule,
|
|
||||||
GiftModule,
|
|
||||||
NotificationModule,
|
NotificationModule,
|
||||||
OtpModule,
|
OtpModule,
|
||||||
DocumentModule,
|
DocumentModule,
|
||||||
@ -77,8 +67,6 @@ import { UserModule } from './user/user.module';
|
|||||||
|
|
||||||
HealthModule,
|
HealthModule,
|
||||||
|
|
||||||
UserModule,
|
|
||||||
|
|
||||||
CronModule,
|
CronModule,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
|
@ -1,11 +1,8 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { AllowanceModule } from '~/allowance/allowance.module';
|
|
||||||
import { MoneyRequestModule } from '~/money-request/money-request.module';
|
|
||||||
import { BaseCronService } from './services';
|
import { BaseCronService } from './services';
|
||||||
import { AllowanceTask, MoneyRequestTask } from './tasks';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [AllowanceModule, MoneyRequestModule],
|
imports: [],
|
||||||
providers: [AllowanceTask, MoneyRequestTask, BaseCronService],
|
providers: [BaseCronService],
|
||||||
})
|
})
|
||||||
export class CronModule {}
|
export class CronModule {}
|
||||||
|
@ -1,54 +0,0 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
|
||||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
|
||||||
import moment from 'moment';
|
|
||||||
import { AllowancesService } from '~/allowance/services';
|
|
||||||
import { CacheService } from '~/common/modules/cache/services';
|
|
||||||
import { BaseCronService } from '../services/base-cron.service';
|
|
||||||
const TEN = 10;
|
|
||||||
const SIXTY = 60;
|
|
||||||
const THOUSAND = 1000;
|
|
||||||
const TEN_MINUTES = TEN * SIXTY * THOUSAND;
|
|
||||||
const CHUNK_SIZE = 50;
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AllowanceTask extends BaseCronService {
|
|
||||||
private readonly logger = new Logger(AllowanceTask.name);
|
|
||||||
private readonly cronLockKey = `${AllowanceTask.name}-lock`;
|
|
||||||
private readonly cronLockTtl = TEN_MINUTES;
|
|
||||||
constructor(cacheService: CacheService, private readonly allowanceService: AllowancesService) {
|
|
||||||
super(cacheService);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Cron(CronExpression.EVERY_DAY_AT_3AM)
|
|
||||||
async handleCron() {
|
|
||||||
try {
|
|
||||||
const isLockAcquired = await this.acquireLock(this.cronLockKey, this.cronLockTtl);
|
|
||||||
if (!isLockAcquired) {
|
|
||||||
this.logger.log('Lock already acquired. Skipping cron job.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.logger.log('Processing cron job');
|
|
||||||
await this.processJob();
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.error('Error processing cron job', error);
|
|
||||||
} finally {
|
|
||||||
this.logger.log('Releasing lock');
|
|
||||||
await this.releaseLock(this.cronLockKey);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async processJob() {
|
|
||||||
const today = moment().startOf('day');
|
|
||||||
const allowancesChunks = await this.allowanceService.findAllowancesChunks(CHUNK_SIZE);
|
|
||||||
for await (const allowances of allowancesChunks) {
|
|
||||||
for (const allowance of allowances) {
|
|
||||||
this.logger.log(`Processing allowance ${allowance.id} with next payment date ${allowance.nextPaymentDate}`);
|
|
||||||
// if today is the same as allowance payment date
|
|
||||||
if (moment(allowance.nextPaymentDate).startOf('day').isSame(today)) {
|
|
||||||
this.logger.log(`Today is the payment date for allowance ${allowance.id}`);
|
|
||||||
//@TODO: Implement payment logic
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
export * from './allowance.task';
|
|
||||||
export * from './money-request.task';
|
|
||||||
|
@ -1,54 +0,0 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
|
||||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
|
||||||
import moment from 'moment';
|
|
||||||
import { CacheService } from '~/common/modules/cache/services';
|
|
||||||
import { MoneyRequestsService } from '~/money-request/services';
|
|
||||||
import { BaseCronService } from '../services';
|
|
||||||
const TEN = 10;
|
|
||||||
const SIXTY = 60;
|
|
||||||
const THOUSAND = 1000;
|
|
||||||
const TEN_MINUTES = TEN * SIXTY * THOUSAND;
|
|
||||||
const CHUNK_SIZE = 50;
|
|
||||||
@Injectable()
|
|
||||||
export class MoneyRequestTask extends BaseCronService {
|
|
||||||
private readonly cronLockKey = `${MoneyRequestTask.name}-lock`;
|
|
||||||
private readonly cronLockTtl = TEN_MINUTES;
|
|
||||||
private readonly logger = new Logger(MoneyRequestTask.name);
|
|
||||||
constructor(cacheService: CacheService, private readonly moneyRequestService: MoneyRequestsService) {
|
|
||||||
super(cacheService);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Cron(CronExpression.EVERY_DAY_AT_3AM)
|
|
||||||
async handleCron() {
|
|
||||||
try {
|
|
||||||
const isLockAcquired = await this.acquireLock(this.cronLockKey, this.cronLockTtl);
|
|
||||||
if (!isLockAcquired) {
|
|
||||||
this.logger.log('Lock already acquired. Skipping cron job for MoneyRequestTask.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.logger.log('Processing cron job for MoneyRequestTask');
|
|
||||||
await this.processJob();
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.error('Error processing MoneyRequestTask cron job', error);
|
|
||||||
} finally {
|
|
||||||
this.logger.log('Releasing lock for MoneyRequestTask');
|
|
||||||
await this.releaseLock(this.cronLockKey);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async processJob() {
|
|
||||||
const today = moment().startOf('day');
|
|
||||||
const moneyRequestsChunks = await this.moneyRequestService.findMoneyRequestsChunks(CHUNK_SIZE);
|
|
||||||
for await (const moneyRequests of moneyRequestsChunks) {
|
|
||||||
for (const moneyRequest of moneyRequests) {
|
|
||||||
this.logger.log(
|
|
||||||
`Processing money request ${moneyRequest.id} with next payment date ${moneyRequest.nextPaymentDate}`,
|
|
||||||
);
|
|
||||||
// if today is the same as money request payment date
|
|
||||||
if (moment(moneyRequest.nextPaymentDate).startOf('day').isSame(today)) {
|
|
||||||
this.logger.log(`Today is the payment date for money request ${moneyRequest.id}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -82,8 +82,6 @@ export class InternalCustomerDetailsResponseDto {
|
|||||||
this.gender = customer.gender;
|
this.gender = customer.gender;
|
||||||
this.isJunior = customer.isJunior;
|
this.isJunior = customer.isJunior;
|
||||||
this.isGuardian = customer.isGuardian;
|
this.isGuardian = customer.isGuardian;
|
||||||
this.civilIdFront = new DocumentMetaResponseDto(customer.civilIdFront);
|
|
||||||
this.civilIdBack = new DocumentMetaResponseDto(customer.civilIdBack);
|
|
||||||
this.profilePicture = customer.profilePicture ? new DocumentMetaResponseDto(customer.profilePicture) : null;
|
this.profilePicture = customer.profilePicture ? new DocumentMetaResponseDto(customer.profilePicture) : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -92,20 +92,6 @@ export class Customer extends BaseEntity {
|
|||||||
@OneToOne(() => Guardian, (guardian) => guardian.customer, { cascade: true })
|
@OneToOne(() => Guardian, (guardian) => guardian.customer, { cascade: true })
|
||||||
guardian!: Guardian;
|
guardian!: Guardian;
|
||||||
|
|
||||||
@Column('uuid', { name: 'civil_id_front_id', nullable: true })
|
|
||||||
civilIdFrontId!: string;
|
|
||||||
|
|
||||||
@Column('uuid', { name: 'civil_id_back_id', nullable: true })
|
|
||||||
civilIdBackId!: string;
|
|
||||||
|
|
||||||
@OneToOne(() => Document, (document) => document.customerCivilIdFront, { nullable: true })
|
|
||||||
@JoinColumn({ name: 'civil_id_front_id' })
|
|
||||||
civilIdFront!: Document;
|
|
||||||
|
|
||||||
@OneToOne(() => Document, (document) => document.customerCivilIdBack, { nullable: true })
|
|
||||||
@JoinColumn({ name: 'civil_id_back_id' })
|
|
||||||
civilIdBack!: Document;
|
|
||||||
|
|
||||||
@CreateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP', name: 'created_at' })
|
@CreateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP', name: 'created_at' })
|
||||||
createdAt!: Date;
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@ -61,10 +61,4 @@ export class CustomerRepository {
|
|||||||
|
|
||||||
return query.getManyAndCount();
|
return query.getManyAndCount();
|
||||||
}
|
}
|
||||||
|
|
||||||
findCustomerByCivilId(civilIdFrontId: string, civilIdBackId: string) {
|
|
||||||
return this.customerRepository.findOne({
|
|
||||||
where: [{ civilIdFrontId, civilIdBackId }, { civilIdFrontId }, { civilIdBackId }],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -35,8 +35,6 @@ export class CustomerService {
|
|||||||
async createJuniorCustomer(guardianId: string, juniorId: string, body: CreateJuniorRequestDto) {
|
async createJuniorCustomer(guardianId: string, juniorId: string, body: CreateJuniorRequestDto) {
|
||||||
this.logger.log(`Creating junior customer for user ${juniorId}`);
|
this.logger.log(`Creating junior customer for user ${juniorId}`);
|
||||||
|
|
||||||
await this.validateCivilIdForCustomer(guardianId, body.civilIdFrontId, body.civilIdBackId);
|
|
||||||
|
|
||||||
return this.customerRepository.createCustomer(juniorId, body, false);
|
return this.customerRepository.createCustomer(juniorId, body, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -143,48 +141,9 @@ export class CustomerService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async validateCivilIdForCustomer(userId: string, civilIdFrontId: string, civilIdBackId: string) {
|
|
||||||
this.logger.log(`Validating customer documents`);
|
|
||||||
|
|
||||||
if (!civilIdFrontId || !civilIdBackId) {
|
|
||||||
this.logger.error('Civil id front and back are required');
|
|
||||||
throw new BadRequestException('CUSTOMER.CIVIL_ID_REQUIRED');
|
|
||||||
}
|
|
||||||
|
|
||||||
const [civilIdFront, civilIdBack] = await Promise.all([
|
|
||||||
this.documentService.findDocumentById(civilIdFrontId),
|
|
||||||
this.documentService.findDocumentById(civilIdBackId),
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (!civilIdFront || !civilIdBack) {
|
|
||||||
this.logger.error('Civil id front or back not found');
|
|
||||||
throw new BadRequestException('CUSTOMER.CIVIL_ID_REQUIRED');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (civilIdFront.createdById !== userId || civilIdBack.createdById !== userId) {
|
|
||||||
this.logger.error(`Civil id front or back not created by user with id ${userId}`);
|
|
||||||
throw new BadRequestException('CUSTOMER.CIVIL_ID_NOT_CREATED_BY_USER');
|
|
||||||
}
|
|
||||||
|
|
||||||
const customerWithTheSameCivilId = await this.customerRepository.findCustomerByCivilId(
|
|
||||||
civilIdFrontId,
|
|
||||||
civilIdBackId,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (customerWithTheSameCivilId) {
|
|
||||||
this.logger.error(
|
|
||||||
`Customer with civil id front ${civilIdFrontId} and civil id back ${civilIdBackId} already exists`,
|
|
||||||
);
|
|
||||||
throw new BadRequestException('CUSTOMER.CIVIL_ID_ALREADY_EXISTS');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async prepareCustomerDocuments(customer: Customer) {
|
private async prepareCustomerDocuments(customer: Customer) {
|
||||||
const promises = [];
|
const promises = [];
|
||||||
|
|
||||||
promises.push(this.ociService.generatePreSignedUrl(customer.civilIdFront));
|
|
||||||
promises.push(this.ociService.generatePreSignedUrl(customer.civilIdBack));
|
|
||||||
|
|
||||||
if (customer.profilePicture) {
|
if (customer.profilePicture) {
|
||||||
promises.push(this.ociService.generatePreSignedUrl(customer.profilePicture));
|
promises.push(this.ociService.generatePreSignedUrl(customer.profilePicture));
|
||||||
}
|
}
|
||||||
@ -194,8 +153,6 @@ export class CustomerService {
|
|||||||
customer.profilePicture.url = profilePictureUrl;
|
customer.profilePicture.url = profilePictureUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
customer.civilIdFront.url = civilIdFrontUrl;
|
|
||||||
customer.civilIdBack.url = civilIdBackUrl;
|
|
||||||
return customer;
|
return customer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,249 +0,0 @@
|
|||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
|
|
||||||
export class InitialMigration1733750228289 implements MigrationInterface {
|
|
||||||
name = 'InitialMigration1733750228289';
|
|
||||||
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "gift_replies" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "status" character varying NOT NULL DEFAULT 'PENDING', "color" character varying NOT NULL, "gift_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "REL_8292da97f1ceb9a806b8bc812f" UNIQUE ("gift_id"), CONSTRAINT "PK_ec6567bb5ab318bb292fa6599a2" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "gift" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "description" text NOT NULL, "color" character varying NOT NULL, "amount" numeric(10,3) NOT NULL, "status" character varying NOT NULL DEFAULT 'AVAILABLE', "redeemed_at" TIMESTAMP WITH TIME ZONE, "giver_id" uuid NOT NULL, "image_id" uuid NOT NULL, "recipient_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_f91217caddc01a085837ebe0606" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "gift_redemptions" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "gift_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_6ad7ac76169c3a224ce4a3afff4" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "saving_goals" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "description" character varying(255), "due_date" TIMESTAMP WITH TIME ZONE NOT NULL, "target_amount" numeric(12,3) NOT NULL, "current_amount" numeric(12,3) NOT NULL DEFAULT '0', "image_id" uuid, "junior_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_5193f14c1c3a38e6657a159795e" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "categories" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "type" character varying(255) NOT NULL, "junior_id" uuid, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_24dbc6126a28ff948da33e97d3b" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "task_submissions" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "status" character varying NOT NULL, "submitted_at" TIMESTAMP WITH TIME ZONE NOT NULL, "task_id" uuid NOT NULL, "proof_of_completion_id" uuid, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "REL_d6cfaee118a0300d652e28ee16" UNIQUE ("task_id"), CONSTRAINT "PK_8d19d6b5dd776e373113de50018" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "tasks" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "title" character varying(255) NOT NULL, "description" character varying(255) NOT NULL, "reward_amount" numeric(12,3) NOT NULL, "image_id" uuid NOT NULL, "task_frequency" character varying NOT NULL, "start_date" TIMESTAMP WITH TIME ZONE NOT NULL, "due_date" TIMESTAMP WITH TIME ZONE NOT NULL, "is_proof_required" boolean NOT NULL, "assigned_to_id" uuid NOT NULL, "assigned_by_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_8d12ff38fcc62aaba2cab748772" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "notifications" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "title" character varying NOT NULL, "message" character varying NOT NULL, "recipient" character varying, "scope" character varying NOT NULL, "status" character varying, "channel" character varying NOT NULL, "user_id" uuid, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_6a72c3c0f683f6462415e653c3a" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "otp" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "value" character varying(255) NOT NULL, "scope" character varying(255) NOT NULL, "otp_type" character varying(255) NOT NULL, "expires_at" TIMESTAMP WITH TIME ZONE NOT NULL, "user_id" uuid NOT NULL, "is_used" boolean NOT NULL DEFAULT false, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_32556d9d7b22031d7d0e1fd6723" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(`CREATE INDEX "IDX_6427c192ef35355ebac18fb683" ON "otp" ("scope") `);
|
|
||||||
await queryRunner.query(`CREATE INDEX "IDX_258d028d322ea3b856bf9f12f2" ON "otp" ("user_id") `);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "user_registration_tokens" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "token" character varying(255) NOT NULL, "user_type" character varying(255) NOT NULL, "is_used" boolean NOT NULL DEFAULT false, "expiry_date" TIMESTAMP NOT NULL, "user_id" uuid, "junior_id" uuid, "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "created_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "UQ_5881556d05b46fc7bd9e3bba935" UNIQUE ("token"), CONSTRAINT "PK_135a2d86443071ff0ba1c14135c" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(`CREATE INDEX "IDX_5881556d05b46fc7bd9e3bba93" ON "user_registration_tokens" ("token") `);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "users" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "email" character varying(255), "phone_number" character varying(255), "country_code" character varying(10), "password" character varying(255), "salt" character varying(255), "google_id" character varying(255), "apple_id" character varying(255), "is_phone_verified" boolean NOT NULL DEFAULT false, "is_email_verified" boolean NOT NULL DEFAULT false, "is_profile_completed" boolean NOT NULL DEFAULT false, "is_email_enabled" boolean NOT NULL DEFAULT false, "is_push_enabled" boolean NOT NULL DEFAULT false, "is_sms_enabled" boolean NOT NULL DEFAULT false, "roles" text array, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "devices" ("deviceId" character varying(255) NOT NULL, "user_id" uuid NOT NULL, "device_name" character varying, "public_key" character varying, "fcm_token" character varying, "last_access_on" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_666c9b59efda8ca85b29157152c" PRIMARY KEY ("deviceId"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "documents" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "extension" character varying(255) NOT NULL, "document_type" character varying(255) NOT NULL, "created_by_id" uuid, "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "created_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_ac51aa5181ee2036f5ca482857c" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "customers" ("id" uuid NOT NULL, "customer_status" character varying(255) NOT NULL DEFAULT 'PENDING', "kyc_status" character varying(255) NOT NULL DEFAULT 'PENDING', "rejection_reason" text, "first_name" character varying(255), "last_name" character varying(255), "date_of_birth" date, "national_id" character varying(255), "national_id_expiry" date, "country_of_residence" character varying(255), "source_of_income" character varying(255), "profession" character varying(255), "profession_type" character varying(255), "is_pep" boolean NOT NULL DEFAULT false, "gender" character varying(255), "is_junior" boolean NOT NULL DEFAULT false, "is_guardian" boolean NOT NULL DEFAULT false, "application_number" SERIAL NOT NULL, "user_id" uuid NOT NULL, "profile_picture_id" uuid, "civil_id_front_id" uuid, "civil_id_back_id" uuid, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "REL_e7574892da11dd01de5cfc4649" UNIQUE ("profile_picture_id"), CONSTRAINT "REL_11d81cd7be87b6f8865b0cf766" UNIQUE ("user_id"), CONSTRAINT "REL_d5f99c497892ce31598ba19a72" UNIQUE ("civil_id_front_id"), CONSTRAINT "REL_2191662d124c56dd968ba01bf1" UNIQUE ("civil_id_back_id"), CONSTRAINT "PK_133ec679a801fab5e070f73d3ea" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "money_requests" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "requested_amount" numeric(10,3) NOT NULL, "message" character varying NOT NULL, "frequency" character varying NOT NULL DEFAULT 'ONE_TIME', "status" character varying NOT NULL DEFAULT 'PENDING', "reviewed_at" TIMESTAMP WITH TIME ZONE, "start_date" TIMESTAMP WITH TIME ZONE, "end_date" TIMESTAMP WITH TIME ZONE, "requester_id" uuid NOT NULL, "reviewer_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_28cff23e9fb06cd5dbf73cd53e7" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "themes" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "color" character varying(255) NOT NULL, "avatar_id" uuid, "junior_id" uuid NOT NULL, CONSTRAINT "REL_73fcb76399a308cdd2d431a8f2" UNIQUE ("junior_id"), CONSTRAINT "PK_ddbeaab913c18682e5c88155592" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "juniors" ("id" uuid NOT NULL, "relationship" character varying(255) NOT NULL, "customer_id" uuid NOT NULL, "guardian_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "REL_dfbf64ede1ff823a489902448a" UNIQUE ("customer_id"), CONSTRAINT "PK_2d273092322c1f8bf26296fa608" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "allowances" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "amount" numeric(10,2) NOT NULL, "frequency" character varying(255) NOT NULL, "type" character varying(255) NOT NULL, "start_date" TIMESTAMP WITH TIME ZONE NOT NULL, "end_date" TIMESTAMP WITH TIME ZONE, "number_of_transactions" integer, "guardian_id" uuid NOT NULL, "junior_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "deleted_at" TIMESTAMP WITH TIME ZONE, CONSTRAINT "PK_3731e781e7c4e932ba4d4213ac1" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "allowance_change_requests" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "reason" text NOT NULL, "amount" numeric(10,2) NOT NULL, "status" character varying(255) NOT NULL DEFAULT 'PENDING', "allowance_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_664715670e1e72c64ce65a078de" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "guardians" ("id" uuid NOT NULL, "customer_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "REL_6c46a1b6af00e6457cb1b70f7e" UNIQUE ("customer_id"), CONSTRAINT "PK_3dcf02f3dc96a2c017106f280be" PRIMARY KEY ("id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE TABLE "saving_goals_categories" ("saving_goal_id" uuid NOT NULL, "category_id" uuid NOT NULL, CONSTRAINT "PK_a49d4f57d06d0a36a8385b6c28f" PRIMARY KEY ("saving_goal_id", "category_id"))`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE INDEX "IDX_d421de423f21c01672ea7c2e98" ON "saving_goals_categories" ("saving_goal_id") `,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`CREATE INDEX "IDX_b0a721a8f7f5b6fe93f3603ebc" ON "saving_goals_categories" ("category_id") `,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "gift_replies" ADD CONSTRAINT "FK_8292da97f1ceb9a806b8bc812f2" FOREIGN KEY ("gift_id") REFERENCES "gift"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "gift" ADD CONSTRAINT "FK_0d317b68508819308455db9b9be" FOREIGN KEY ("giver_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "gift" ADD CONSTRAINT "FK_4a46b5734fb573dc956904c18d0" FOREIGN KEY ("recipient_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "gift" ADD CONSTRAINT "FK_83bb54c127d0e6ee487b90e2996" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "gift_redemptions" ADD CONSTRAINT "FK_243c4349f0c45ce5385ac316aaa" FOREIGN KEY ("gift_id") REFERENCES "gift"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "saving_goals" ADD CONSTRAINT "FK_dad35932272342c1a247a2cee1c" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "saving_goals" ADD CONSTRAINT "FK_f494ba0a361b2f9cbe5f6e56e38" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "categories" ADD CONSTRAINT "FK_4f98e0b010d5e90cae0a2007748" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "task_submissions" ADD CONSTRAINT "FK_d6cfaee118a0300d652e28ee166" FOREIGN KEY ("task_id") REFERENCES "tasks"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "task_submissions" ADD CONSTRAINT "FK_87876dfe440de7aafce216e9f58" FOREIGN KEY ("proof_of_completion_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_f1f00d41b1e95d0bbda2710a62b" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_9430f12c5a1604833f64595a57f" FOREIGN KEY ("assigned_to_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_3e08a7ca125a175cf899b09f71a" FOREIGN KEY ("assigned_by_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "notifications" ADD CONSTRAINT "FK_9a8a82462cab47c73d25f49261f" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "otp" ADD CONSTRAINT "FK_258d028d322ea3b856bf9f12f25" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "user_registration_tokens" ADD CONSTRAINT "FK_57cbbe079a7945d6ed1df114825" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "user_registration_tokens" ADD CONSTRAINT "FK_e41bec3ed6e549cbf90f57cc344" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "devices" ADD CONSTRAINT "FK_5e9bee993b4ce35c3606cda194c" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "documents" ADD CONSTRAINT "FK_7f46f4f77acde1dcedba64cb220" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "customers" ADD CONSTRAINT "FK_e7574892da11dd01de5cfc46499" FOREIGN KEY ("profile_picture_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "customers" ADD CONSTRAINT "FK_11d81cd7be87b6f8865b0cf7661" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "customers" ADD CONSTRAINT "FK_d5f99c497892ce31598ba19a72c" FOREIGN KEY ("civil_id_front_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "customers" ADD CONSTRAINT "FK_2191662d124c56dd968ba01bf18" FOREIGN KEY ("civil_id_back_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "money_requests" ADD CONSTRAINT "FK_5cce02836c6033b6e2412995e34" FOREIGN KEY ("requester_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "money_requests" ADD CONSTRAINT "FK_75ba0766db9a7bf03126facf31c" FOREIGN KEY ("reviewer_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "themes" ADD CONSTRAINT "FK_169b672cc28cc757e1f4464864d" FOREIGN KEY ("avatar_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "themes" ADD CONSTRAINT "FK_73fcb76399a308cdd2d431a8f2e" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_dfbf64ede1ff823a489902448a2" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_0b11aa56264184690e2220da4a0" FOREIGN KEY ("guardian_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "allowances" ADD CONSTRAINT "FK_80b144a74e630ed63311e97427b" FOREIGN KEY ("guardian_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "allowances" ADD CONSTRAINT "FK_61e6e612f6d4644f8910d453cc9" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "allowance_change_requests" ADD CONSTRAINT "FK_4ea6382927f50cb93873fae16d2" FOREIGN KEY ("allowance_id") REFERENCES "allowances"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "guardians" ADD CONSTRAINT "FK_6c46a1b6af00e6457cb1b70f7e7" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "saving_goals_categories" ADD CONSTRAINT "FK_d421de423f21c01672ea7c2e98f" FOREIGN KEY ("saving_goal_id") REFERENCES "saving_goals"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
|
|
||||||
);
|
|
||||||
await queryRunner.query(
|
|
||||||
`ALTER TABLE "saving_goals_categories" ADD CONSTRAINT "FK_b0a721a8f7f5b6fe93f3603ebc8" FOREIGN KEY ("category_id") REFERENCES "categories"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(`ALTER TABLE "saving_goals_categories" DROP CONSTRAINT "FK_b0a721a8f7f5b6fe93f3603ebc8"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "saving_goals_categories" DROP CONSTRAINT "FK_d421de423f21c01672ea7c2e98f"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "guardians" DROP CONSTRAINT "FK_6c46a1b6af00e6457cb1b70f7e7"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "allowance_change_requests" DROP CONSTRAINT "FK_4ea6382927f50cb93873fae16d2"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "allowances" DROP CONSTRAINT "FK_61e6e612f6d4644f8910d453cc9"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "allowances" DROP CONSTRAINT "FK_80b144a74e630ed63311e97427b"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_0b11aa56264184690e2220da4a0"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_dfbf64ede1ff823a489902448a2"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "themes" DROP CONSTRAINT "FK_73fcb76399a308cdd2d431a8f2e"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "themes" DROP CONSTRAINT "FK_169b672cc28cc757e1f4464864d"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "money_requests" DROP CONSTRAINT "FK_75ba0766db9a7bf03126facf31c"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "money_requests" DROP CONSTRAINT "FK_5cce02836c6033b6e2412995e34"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_2191662d124c56dd968ba01bf18"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_d5f99c497892ce31598ba19a72c"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_11d81cd7be87b6f8865b0cf7661"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_e7574892da11dd01de5cfc46499"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "documents" DROP CONSTRAINT "FK_7f46f4f77acde1dcedba64cb220"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "devices" DROP CONSTRAINT "FK_5e9bee993b4ce35c3606cda194c"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "user_registration_tokens" DROP CONSTRAINT "FK_e41bec3ed6e549cbf90f57cc344"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "user_registration_tokens" DROP CONSTRAINT "FK_57cbbe079a7945d6ed1df114825"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "otp" DROP CONSTRAINT "FK_258d028d322ea3b856bf9f12f25"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "notifications" DROP CONSTRAINT "FK_9a8a82462cab47c73d25f49261f"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_3e08a7ca125a175cf899b09f71a"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_9430f12c5a1604833f64595a57f"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_f1f00d41b1e95d0bbda2710a62b"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "task_submissions" DROP CONSTRAINT "FK_87876dfe440de7aafce216e9f58"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "task_submissions" DROP CONSTRAINT "FK_d6cfaee118a0300d652e28ee166"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "categories" DROP CONSTRAINT "FK_4f98e0b010d5e90cae0a2007748"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "saving_goals" DROP CONSTRAINT "FK_f494ba0a361b2f9cbe5f6e56e38"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "saving_goals" DROP CONSTRAINT "FK_dad35932272342c1a247a2cee1c"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "gift_redemptions" DROP CONSTRAINT "FK_243c4349f0c45ce5385ac316aaa"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_83bb54c127d0e6ee487b90e2996"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_4a46b5734fb573dc956904c18d0"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_0d317b68508819308455db9b9be"`);
|
|
||||||
await queryRunner.query(`ALTER TABLE "gift_replies" DROP CONSTRAINT "FK_8292da97f1ceb9a806b8bc812f2"`);
|
|
||||||
await queryRunner.query(`DROP INDEX "public"."IDX_b0a721a8f7f5b6fe93f3603ebc"`);
|
|
||||||
await queryRunner.query(`DROP INDEX "public"."IDX_d421de423f21c01672ea7c2e98"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "saving_goals_categories"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "guardians"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "allowance_change_requests"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "allowances"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "juniors"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "themes"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "money_requests"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "customers"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "documents"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "devices"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "users"`);
|
|
||||||
await queryRunner.query(`DROP INDEX "public"."IDX_5881556d05b46fc7bd9e3bba93"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "user_registration_tokens"`);
|
|
||||||
await queryRunner.query(`DROP INDEX "public"."IDX_258d028d322ea3b856bf9f12f2"`);
|
|
||||||
await queryRunner.query(`DROP INDEX "public"."IDX_6427c192ef35355ebac18fb683"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "otp"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "notifications"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "tasks"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "task_submissions"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "categories"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "saving_goals"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "gift_redemptions"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "gift"`);
|
|
||||||
await queryRunner.query(`DROP TABLE "gift_replies"`);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,41 +0,0 @@
|
|||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
import { v4 as uuid } from 'uuid';
|
|
||||||
import { Document } from '~/document/entities';
|
|
||||||
import { DocumentType } from '~/document/enums';
|
|
||||||
const DEFAULT_TASK_LOGOS = [
|
|
||||||
{
|
|
||||||
id: uuid(),
|
|
||||||
name: 'bed-furniture',
|
|
||||||
extension: '.jpg',
|
|
||||||
documentType: DocumentType.DEFAULT_TASKS_LOGO,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: uuid(),
|
|
||||||
name: 'dog',
|
|
||||||
extension: '.jpg',
|
|
||||||
documentType: DocumentType.DEFAULT_TASKS_LOGO,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: uuid(),
|
|
||||||
name: 'dish-washing',
|
|
||||||
extension: '.jpg',
|
|
||||||
documentType: DocumentType.DEFAULT_TASKS_LOGO,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: uuid(),
|
|
||||||
name: 'walking-the-dog',
|
|
||||||
extension: '.jpg',
|
|
||||||
documentType: DocumentType.DEFAULT_TASKS_LOGO,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
export class SeedsDefaultTasksLogo1733990253208 implements MigrationInterface {
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.manager.getRepository(Document).save(DEFAULT_TASK_LOGOS);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await DEFAULT_TASK_LOGOS.forEach(async (logo) => {
|
|
||||||
await queryRunner.manager.getRepository(Document).delete({ name: logo.name, documentType: logo.documentType });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,57 +0,0 @@
|
|||||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
|
||||||
import { CategoryType } from '~/saving-goals/enums';
|
|
||||||
const DEFAULT_CATEGORIES = [
|
|
||||||
{
|
|
||||||
name: 'School',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Toys',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Games',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Clothes',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Hobbies',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Party',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Sport',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'University',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Travel',
|
|
||||||
type: CategoryType.GLOBAL,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
export class SeedsGoalsCategories1734247702310 implements MigrationInterface {
|
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`INSERT INTO categories (name, type) VALUES ${DEFAULT_CATEGORIES.map(
|
|
||||||
(category) => `('${category.name}', '${category.type}')`,
|
|
||||||
)}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
|
||||||
await queryRunner.query(
|
|
||||||
`DELETE FROM categories WHERE name IN (${DEFAULT_CATEGORIES.map(
|
|
||||||
(category) => `'${category.name}'`,
|
|
||||||
)}) AND type = '${CategoryType.GLOBAL}'`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
105
src/db/migrations/1754913378460-initial-migration.ts
Normal file
105
src/db/migrations/1754913378460-initial-migration.ts
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class InitialMigration1754913378460 implements MigrationInterface {
|
||||||
|
name = 'InitialMigration1754913378460';
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "themes" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "color" character varying(255) NOT NULL, "avatar_id" uuid, "junior_id" uuid NOT NULL, CONSTRAINT "REL_73fcb76399a308cdd2d431a8f2" UNIQUE ("junior_id"), CONSTRAINT "PK_ddbeaab913c18682e5c88155592" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "juniors" ("id" uuid NOT NULL, "relationship" character varying(255) NOT NULL, "customer_id" uuid NOT NULL, "guardian_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "REL_dfbf64ede1ff823a489902448a" UNIQUE ("customer_id"), CONSTRAINT "PK_2d273092322c1f8bf26296fa608" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "notifications" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "title" character varying NOT NULL, "message" character varying NOT NULL, "recipient" character varying, "scope" character varying NOT NULL, "status" character varying, "channel" character varying NOT NULL, "user_id" uuid, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_6a72c3c0f683f6462415e653c3a" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "otp" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "value" character varying(255) NOT NULL, "scope" character varying(255) NOT NULL, "otp_type" character varying(255) NOT NULL, "expires_at" TIMESTAMP WITH TIME ZONE NOT NULL, "user_id" uuid NOT NULL, "is_used" boolean NOT NULL DEFAULT false, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_32556d9d7b22031d7d0e1fd6723" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`CREATE INDEX "IDX_6427c192ef35355ebac18fb683" ON "otp" ("scope") `);
|
||||||
|
await queryRunner.query(`CREATE INDEX "IDX_258d028d322ea3b856bf9f12f2" ON "otp" ("user_id") `);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "user_auth_tokens" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "token" character varying(255) NOT NULL, "is_used" boolean NOT NULL DEFAULT false, "expiry_date" TIMESTAMP WITH TIME ZONE NOT NULL, "user_id" uuid NOT NULL, "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "UQ_579eaaadf51ae3542caf3491062" UNIQUE ("token"), CONSTRAINT "PK_e15c7c76bf967080b272104d828" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(`CREATE INDEX "IDX_579eaaadf51ae3542caf349106" ON "user_auth_tokens" ("token") `);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "users" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "email" character varying(255), "phone_number" character varying(255), "country_code" character varying(10), "password" character varying(255), "salt" character varying(255), "google_id" character varying(255), "apple_id" character varying(255), "is_phone_verified" boolean NOT NULL DEFAULT false, "is_email_verified" boolean NOT NULL DEFAULT false, "is_profile_completed" boolean NOT NULL DEFAULT false, "is_email_enabled" boolean NOT NULL DEFAULT false, "is_push_enabled" boolean NOT NULL DEFAULT false, "is_sms_enabled" boolean NOT NULL DEFAULT false, "roles" text array, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "devices" ("deviceId" character varying(255) NOT NULL, "user_id" uuid NOT NULL, "device_name" character varying, "public_key" character varying, "fcm_token" character varying, "last_access_on" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_666c9b59efda8ca85b29157152c" PRIMARY KEY ("deviceId"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "documents" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "extension" character varying(255) NOT NULL, "document_type" character varying(255) NOT NULL, "created_by_id" uuid, "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_ac51aa5181ee2036f5ca482857c" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "customers" ("id" uuid NOT NULL, "customer_status" character varying(255) NOT NULL DEFAULT 'PENDING', "kyc_status" character varying(255) NOT NULL DEFAULT 'PENDING', "rejection_reason" text, "first_name" character varying(255), "last_name" character varying(255), "date_of_birth" date, "national_id" character varying(255), "national_id_expiry" date, "country_of_residence" character varying(255), "source_of_income" character varying(255), "profession" character varying(255), "profession_type" character varying(255), "is_pep" boolean NOT NULL DEFAULT false, "gender" character varying(255), "is_junior" boolean NOT NULL DEFAULT false, "is_guardian" boolean NOT NULL DEFAULT false, "application_number" SERIAL NOT NULL, "user_id" uuid NOT NULL, "profile_picture_id" uuid, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "REL_e7574892da11dd01de5cfc4649" UNIQUE ("profile_picture_id"), CONSTRAINT "REL_11d81cd7be87b6f8865b0cf766" UNIQUE ("user_id"), CONSTRAINT "PK_133ec679a801fab5e070f73d3ea" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "guardians" ("id" uuid NOT NULL, "customer_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "REL_6c46a1b6af00e6457cb1b70f7e" UNIQUE ("customer_id"), CONSTRAINT "PK_3dcf02f3dc96a2c017106f280be" PRIMARY KEY ("id"))`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "themes" ADD CONSTRAINT "FK_169b672cc28cc757e1f4464864d" FOREIGN KEY ("avatar_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "themes" ADD CONSTRAINT "FK_73fcb76399a308cdd2d431a8f2e" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_dfbf64ede1ff823a489902448a2" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_0b11aa56264184690e2220da4a0" FOREIGN KEY ("guardian_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "notifications" ADD CONSTRAINT "FK_9a8a82462cab47c73d25f49261f" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "otp" ADD CONSTRAINT "FK_258d028d322ea3b856bf9f12f25" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "user_auth_tokens" ADD CONSTRAINT "FK_bab7def1955bd13dcc47c036c03" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "devices" ADD CONSTRAINT "FK_5e9bee993b4ce35c3606cda194c" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "documents" ADD CONSTRAINT "FK_7f46f4f77acde1dcedba64cb220" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "customers" ADD CONSTRAINT "FK_e7574892da11dd01de5cfc46499" FOREIGN KEY ("profile_picture_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "customers" ADD CONSTRAINT "FK_11d81cd7be87b6f8865b0cf7661" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
await queryRunner.query(
|
||||||
|
`ALTER TABLE "guardians" ADD CONSTRAINT "FK_6c46a1b6af00e6457cb1b70f7e7" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "guardians" DROP CONSTRAINT "FK_6c46a1b6af00e6457cb1b70f7e7"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_11d81cd7be87b6f8865b0cf7661"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_e7574892da11dd01de5cfc46499"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "documents" DROP CONSTRAINT "FK_7f46f4f77acde1dcedba64cb220"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "devices" DROP CONSTRAINT "FK_5e9bee993b4ce35c3606cda194c"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "user_auth_tokens" DROP CONSTRAINT "FK_bab7def1955bd13dcc47c036c03"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "otp" DROP CONSTRAINT "FK_258d028d322ea3b856bf9f12f25"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "notifications" DROP CONSTRAINT "FK_9a8a82462cab47c73d25f49261f"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_0b11aa56264184690e2220da4a0"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_dfbf64ede1ff823a489902448a2"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "themes" DROP CONSTRAINT "FK_73fcb76399a308cdd2d431a8f2e"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "themes" DROP CONSTRAINT "FK_169b672cc28cc757e1f4464864d"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "guardians"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "customers"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "documents"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "devices"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "users"`);
|
||||||
|
await queryRunner.query(`DROP INDEX "public"."IDX_579eaaadf51ae3542caf349106"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "user_auth_tokens"`);
|
||||||
|
await queryRunner.query(`DROP INDEX "public"."IDX_258d028d322ea3b856bf9f12f2"`);
|
||||||
|
await queryRunner.query(`DROP INDEX "public"."IDX_6427c192ef35355ebac18fb683"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "otp"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "notifications"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "juniors"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "themes"`);
|
||||||
|
}
|
||||||
|
}
|
@ -58,7 +58,7 @@ const DEFAULT_AVATARS = [
|
|||||||
documentType: DocumentType.DEFAULT_AVATAR,
|
documentType: DocumentType.DEFAULT_AVATAR,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
export class SeedDefaultAvatar1753869637732 implements MigrationInterface {
|
export class SeedDefaultAvatar1754913378460 implements MigrationInterface {
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
await queryRunner.manager.getRepository(Document).save(DEFAULT_AVATARS);
|
await queryRunner.manager.getRepository(Document).save(DEFAULT_AVATARS);
|
||||||
}
|
}
|
@ -1,4 +1,2 @@
|
|||||||
export * from './1753869637732-seed-default-avatar';
|
export * from './1754913378460-initial-migration';
|
||||||
export * from './1733990253208-seeds-default-tasks-logo';
|
export * from './1754913378461-seed-default-avatar';
|
||||||
export * from './1734247702310-seeds-goals-categories';
|
|
||||||
export * from './1733750228289-initial-migration';
|
|
||||||
|
@ -9,11 +9,7 @@ import {
|
|||||||
UpdateDateColumn,
|
UpdateDateColumn,
|
||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
import { Customer } from '~/customer/entities';
|
import { Customer } from '~/customer/entities';
|
||||||
import { Gift } from '~/gift/entities';
|
|
||||||
import { Theme } from '~/junior/entities';
|
import { Theme } from '~/junior/entities';
|
||||||
import { SavingGoal } from '~/saving-goals/entities';
|
|
||||||
import { Task } from '~/task/entities';
|
|
||||||
import { TaskSubmission } from '~/task/entities/task-submissions.entity';
|
|
||||||
import { User } from '~/user/entities';
|
import { User } from '~/user/entities';
|
||||||
import { DocumentType } from '../enums';
|
import { DocumentType } from '../enums';
|
||||||
|
|
||||||
@ -37,35 +33,17 @@ export class Document {
|
|||||||
@OneToOne(() => Customer, (customer) => customer.profilePicture, { onDelete: 'SET NULL' })
|
@OneToOne(() => Customer, (customer) => customer.profilePicture, { onDelete: 'SET NULL' })
|
||||||
customerPicture?: Customer;
|
customerPicture?: Customer;
|
||||||
|
|
||||||
@OneToOne(() => Customer, (customer) => customer.civilIdFront, { onDelete: 'SET NULL' })
|
|
||||||
customerCivilIdFront?: User;
|
|
||||||
|
|
||||||
@OneToOne(() => Customer, (customer) => customer.civilIdBack, { onDelete: 'SET NULL' })
|
|
||||||
customerCivilIdBack?: User;
|
|
||||||
|
|
||||||
@OneToMany(() => Theme, (theme) => theme.avatar)
|
@OneToMany(() => Theme, (theme) => theme.avatar)
|
||||||
themes?: Theme[];
|
themes?: Theme[];
|
||||||
|
|
||||||
@OneToMany(() => Task, (task) => task.image)
|
|
||||||
tasks?: Task[];
|
|
||||||
|
|
||||||
@OneToMany(() => TaskSubmission, (taskSubmission) => taskSubmission.proofOfCompletion)
|
|
||||||
submissions?: TaskSubmission[];
|
|
||||||
|
|
||||||
@OneToMany(() => SavingGoal, (savingGoal) => savingGoal.image)
|
|
||||||
goals?: SavingGoal[];
|
|
||||||
|
|
||||||
@OneToMany(() => Gift, (gift) => gift.image)
|
|
||||||
gifts?: Gift[];
|
|
||||||
|
|
||||||
@ManyToOne(() => User, (user) => user.createdDocuments, { nullable: true, onDelete: 'SET NULL' })
|
@ManyToOne(() => User, (user) => user.createdDocuments, { nullable: true, onDelete: 'SET NULL' })
|
||||||
@JoinColumn({ name: 'created_by_id' })
|
@JoinColumn({ name: 'created_by_id' })
|
||||||
createdBy?: User;
|
createdBy?: User;
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
updatedAt!: Date;
|
updatedAt!: Date;
|
||||||
|
|
||||||
@Column({ name: 'created_at', type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
|
@Column({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
createdAt!: Date;
|
createdAt!: Date;
|
||||||
|
|
||||||
// virtual field
|
// virtual field
|
||||||
|
@ -1,82 +0,0 @@
|
|||||||
import { Body, Controller, Get, HttpCode, HttpStatus, Param, Post, Query, UseGuards } from '@nestjs/common';
|
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
|
||||||
import { Roles } from '~/auth/enums';
|
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
|
||||||
import { AllowedRoles, AuthenticatedUser } from '~/common/decorators';
|
|
||||||
import { AccessTokenGuard, RolesGuard } from '~/common/guards';
|
|
||||||
import { ApiDataPageResponse, ApiDataResponse, ApiLangRequestHeader } from '~/core/decorators';
|
|
||||||
import { ResponseFactory } from '~/core/utils';
|
|
||||||
import { CreateGiftRequestDto, GiftFiltersRequestDto, GiftReplyRequestDto } from '../dtos/request';
|
|
||||||
import { GiftDetailsResponseDto, GiftListResponseDto } from '../dtos/response';
|
|
||||||
import { GiftsService } from '../services';
|
|
||||||
|
|
||||||
@Controller('gift')
|
|
||||||
@ApiTags('Gifts')
|
|
||||||
@ApiBearerAuth()
|
|
||||||
@ApiLangRequestHeader()
|
|
||||||
export class GiftsController {
|
|
||||||
constructor(private readonly giftsService: GiftsService) {}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
|
||||||
@ApiDataResponse(GiftDetailsResponseDto)
|
|
||||||
async createGift(@AuthenticatedUser() { sub }: IJwtPayload, @Body() body: CreateGiftRequestDto) {
|
|
||||||
const gift = await this.giftsService.createGift(sub, body);
|
|
||||||
|
|
||||||
return ResponseFactory.data(new GiftDetailsResponseDto(gift));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
@UseGuards(AccessTokenGuard)
|
|
||||||
@ApiDataPageResponse(GiftListResponseDto)
|
|
||||||
async findGifts(@AuthenticatedUser() user: IJwtPayload, @Query() filters: GiftFiltersRequestDto) {
|
|
||||||
const [gifts, itemCount] = await this.giftsService.findGifts(user, filters);
|
|
||||||
|
|
||||||
return ResponseFactory.dataPage(
|
|
||||||
gifts.map((gift) => new GiftListResponseDto(gift)),
|
|
||||||
{
|
|
||||||
size: filters.size,
|
|
||||||
page: filters.page,
|
|
||||||
itemCount,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get(':giftId')
|
|
||||||
@UseGuards(AccessTokenGuard)
|
|
||||||
@ApiDataResponse(GiftDetailsResponseDto)
|
|
||||||
async findGiftById(@AuthenticatedUser() user: IJwtPayload, @Param('giftId') giftId: string) {
|
|
||||||
const gift = await this.giftsService.findUserGiftById(user, giftId);
|
|
||||||
|
|
||||||
return ResponseFactory.data(new GiftDetailsResponseDto(gift));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post(':giftId/redeem')
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.JUNIOR)
|
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
|
||||||
redeemGift(@AuthenticatedUser() { sub }: IJwtPayload, @Param('giftId') giftId: string) {
|
|
||||||
return this.giftsService.redeemGift(sub, giftId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post(':giftId/undo-redeem')
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.JUNIOR)
|
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
|
||||||
UndoGiftRedemption(@AuthenticatedUser() { sub }: IJwtPayload, @Param('giftId') giftId: string) {
|
|
||||||
return this.giftsService.UndoGiftRedemption(sub, giftId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post(':giftId/reply')
|
|
||||||
@UseGuards(RolesGuard)
|
|
||||||
@AllowedRoles(Roles.JUNIOR)
|
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
|
||||||
replyToGift(
|
|
||||||
@AuthenticatedUser() { sub }: IJwtPayload,
|
|
||||||
@Param('giftId') giftId: string,
|
|
||||||
@Body() body: GiftReplyRequestDto,
|
|
||||||
) {
|
|
||||||
return this.giftsService.replyToGift(sub, giftId, body);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './gifts.controller';
|
|
@ -1,32 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { IsEnum, IsNotEmpty, IsNumber, IsPositive, IsString, IsUUID } from 'class-validator';
|
|
||||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
|
||||||
import { GiftColor } from '~/gift/enums';
|
|
||||||
export class CreateGiftRequestDto {
|
|
||||||
@ApiProperty({ example: 'Happy Birthday' })
|
|
||||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'gift.name' }) })
|
|
||||||
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'gift.name' }) })
|
|
||||||
name!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Description of the gift' })
|
|
||||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'gift.description' }) })
|
|
||||||
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'gift.description' }) })
|
|
||||||
description!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: GiftColor.VIOLET })
|
|
||||||
@IsEnum(GiftColor, { message: i18n('validation.IsEnum', { path: 'general', property: 'gift.color' }) })
|
|
||||||
color!: GiftColor;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 100 })
|
|
||||||
@IsNumber({}, { message: i18n('validation.IsNumber', { path: 'general', property: 'gift.amount' }) })
|
|
||||||
@IsPositive({ message: i18n('validation.IsPositive', { path: 'general', property: 'gift.amount' }) })
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'f7b9b1b0-0b3b-4b3b-8b3b-0b3b4b3b8b3b' })
|
|
||||||
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'gift.imageId' }) })
|
|
||||||
imageId!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'f7b9b1b0-0b3b-4b3b-8b3b-0b3b4b3b8b3b' })
|
|
||||||
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'gift.recipientId' }) })
|
|
||||||
recipientId!: string;
|
|
||||||
}
|
|
@ -1,10 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { IsEnum } from 'class-validator';
|
|
||||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
|
||||||
import { GiftStatus } from '~/gift/enums';
|
|
||||||
export class GiftFiltersRequestDto extends PageOptionsRequestDto {
|
|
||||||
@ApiProperty({ enum: GiftStatus })
|
|
||||||
@IsEnum(GiftStatus, { message: i18n('validation.IsEnum', { path: 'general', property: 'gift.status' }) })
|
|
||||||
status!: GiftStatus;
|
|
||||||
}
|
|
@ -1,9 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { IsEnum } from 'class-validator';
|
|
||||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
|
||||||
import { GiftColor } from '~/gift/enums';
|
|
||||||
export class GiftReplyRequestDto {
|
|
||||||
@ApiProperty()
|
|
||||||
@IsEnum(GiftColor, { message: i18n('validation.IsEnum', { path: 'general', property: 'gift.color' }) })
|
|
||||||
color!: GiftColor;
|
|
||||||
}
|
|
@ -1,3 +0,0 @@
|
|||||||
export * from './create-gift.request.dto';
|
|
||||||
export * from './gift-filters.request.dto';
|
|
||||||
export * from './gift-reply.request.dto';
|
|
@ -1,54 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { DocumentMetaResponseDto } from '~/document/dtos/response';
|
|
||||||
import { Gift } from '~/gift/entities';
|
|
||||||
import { GiftColor, GiftStatus } from '~/gift/enums';
|
|
||||||
import { JuniorResponseDto } from '~/junior/dtos/response';
|
|
||||||
|
|
||||||
export class GiftDetailsResponseDto {
|
|
||||||
@ApiProperty({ example: 'f7b9b1b0-0b3b-4b3b-8b3b-0b3b4b3b8b3b' })
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Happy Birthday' })
|
|
||||||
name!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Description of the gift' })
|
|
||||||
description!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '200' })
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: GiftStatus.AVAILABLE })
|
|
||||||
status!: GiftStatus;
|
|
||||||
|
|
||||||
@ApiProperty({ example: GiftColor.GREEN })
|
|
||||||
color!: GiftColor;
|
|
||||||
|
|
||||||
@ApiProperty({ type: JuniorResponseDto })
|
|
||||||
recipient!: JuniorResponseDto;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Ahmad Khalid' })
|
|
||||||
giverName!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ type: DocumentMetaResponseDto })
|
|
||||||
image!: DocumentMetaResponseDto;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '2022-01-01T00:00:00.000Z' })
|
|
||||||
createdAt!: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '2022-01-01T00:00:00.000Z' })
|
|
||||||
updatedAt!: Date;
|
|
||||||
|
|
||||||
constructor(gift: Gift) {
|
|
||||||
this.id = gift.id;
|
|
||||||
this.name = gift.name;
|
|
||||||
this.description = gift.description;
|
|
||||||
this.amount = gift.amount;
|
|
||||||
this.status = gift.status;
|
|
||||||
this.color = gift.color;
|
|
||||||
this.giverName = gift.giver.customer.firstName + ' ' + gift.giver.customer.lastName;
|
|
||||||
this.recipient = new JuniorResponseDto(gift.recipient);
|
|
||||||
this.image = new DocumentMetaResponseDto(gift.image);
|
|
||||||
this.createdAt = gift.createdAt;
|
|
||||||
this.updatedAt = gift.updatedAt;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,32 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { Gift } from '~/gift/entities';
|
|
||||||
import { GiftColor, GiftStatus } from '~/gift/enums';
|
|
||||||
|
|
||||||
export class GiftListResponseDto {
|
|
||||||
@ApiProperty({ example: 'f7b9b1b0-0b3b-4b3b-8b3b-0b3b4b3b8b3b' })
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Happy Birthday' })
|
|
||||||
name!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '242' })
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@ApiProperty({ example: GiftStatus.AVAILABLE })
|
|
||||||
status!: GiftStatus;
|
|
||||||
|
|
||||||
@ApiProperty({ example: GiftColor.GREEN })
|
|
||||||
color!: GiftColor;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '2022-01-01T00:00:00.000Z' })
|
|
||||||
createdAt!: Date;
|
|
||||||
|
|
||||||
constructor(gift: Gift) {
|
|
||||||
this.id = gift.id;
|
|
||||||
this.name = gift.name;
|
|
||||||
this.amount = gift.amount;
|
|
||||||
this.status = gift.status;
|
|
||||||
this.color = gift.color;
|
|
||||||
this.createdAt = gift.createdAt;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
export * from './gift-details.response.dto';
|
|
||||||
export * from './gift-list.response.dto';
|
|
@ -1,30 +0,0 @@
|
|||||||
import {
|
|
||||||
BaseEntity,
|
|
||||||
Column,
|
|
||||||
CreateDateColumn,
|
|
||||||
Entity,
|
|
||||||
JoinColumn,
|
|
||||||
ManyToOne,
|
|
||||||
PrimaryGeneratedColumn,
|
|
||||||
UpdateDateColumn,
|
|
||||||
} from 'typeorm';
|
|
||||||
import { Gift } from './gift.entity';
|
|
||||||
|
|
||||||
@Entity('gift_redemptions')
|
|
||||||
export class GiftRedemption extends BaseEntity {
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'uuid', name: 'gift_id' })
|
|
||||||
giftId!: string;
|
|
||||||
|
|
||||||
@ManyToOne(() => Gift, (gift) => gift.redemptions, { onDelete: 'CASCADE' })
|
|
||||||
@JoinColumn({ name: 'gift_id' })
|
|
||||||
gift!: Gift;
|
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
createdAt!: Date;
|
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
updatedAt!: Date;
|
|
||||||
}
|
|
@ -1,25 +0,0 @@
|
|||||||
import { BaseEntity, Column, CreateDateColumn, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn } from 'typeorm';
|
|
||||||
import { GiftColor, GiftReplyStatus } from '../enums';
|
|
||||||
import { Gift } from './gift.entity';
|
|
||||||
|
|
||||||
@Entity('gift_replies')
|
|
||||||
export class GiftReply extends BaseEntity {
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', name: 'status', default: GiftReplyStatus.PENDING })
|
|
||||||
status!: GiftReplyStatus;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', name: 'color' })
|
|
||||||
color!: GiftColor;
|
|
||||||
|
|
||||||
@Column({ type: 'uuid', name: 'gift_id' })
|
|
||||||
giftId!: string;
|
|
||||||
|
|
||||||
@OneToOne(() => Gift, (gift) => gift.reply, { onDelete: 'CASCADE' })
|
|
||||||
@JoinColumn({ name: 'gift_id' })
|
|
||||||
gift!: Gift;
|
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
createdAt!: Date;
|
|
||||||
}
|
|
@ -1,83 +0,0 @@
|
|||||||
import {
|
|
||||||
Column,
|
|
||||||
CreateDateColumn,
|
|
||||||
Entity,
|
|
||||||
JoinColumn,
|
|
||||||
ManyToOne,
|
|
||||||
OneToMany,
|
|
||||||
OneToOne,
|
|
||||||
PrimaryGeneratedColumn,
|
|
||||||
UpdateDateColumn,
|
|
||||||
} from 'typeorm';
|
|
||||||
import { Document } from '~/document/entities';
|
|
||||||
import { Guardian } from '~/guardian/entities/guradian.entity';
|
|
||||||
import { Junior } from '~/junior/entities';
|
|
||||||
import { GiftColor, GiftStatus } from '../enums';
|
|
||||||
import { GiftRedemption } from './gift-redemption.entity';
|
|
||||||
import { GiftReply } from './gift-reply.entity';
|
|
||||||
|
|
||||||
@Entity('gift')
|
|
||||||
export class Gift {
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', length: 255, name: 'name' })
|
|
||||||
name!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'text', name: 'description' })
|
|
||||||
description!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', name: 'color' })
|
|
||||||
color!: GiftColor;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'decimal',
|
|
||||||
name: 'amount',
|
|
||||||
precision: 10,
|
|
||||||
scale: 3,
|
|
||||||
transformer: {
|
|
||||||
to: (value: number) => value,
|
|
||||||
from: (value: string) => parseFloat(value),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
amount!: number;
|
|
||||||
|
|
||||||
@Column({ type: 'varchar', name: 'status', default: GiftStatus.AVAILABLE })
|
|
||||||
status!: GiftStatus;
|
|
||||||
|
|
||||||
@Column({ type: 'timestamp with time zone', name: 'redeemed_at', nullable: true })
|
|
||||||
redeemedAt!: Date | null;
|
|
||||||
|
|
||||||
@Column({ type: 'uuid', name: 'giver_id' })
|
|
||||||
giverId!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'uuid', name: 'image_id' })
|
|
||||||
imageId!: string;
|
|
||||||
|
|
||||||
@Column({ type: 'uuid', name: 'recipient_id' })
|
|
||||||
recipientId!: string;
|
|
||||||
|
|
||||||
@ManyToOne(() => Guardian, (guardian) => guardian.gifts)
|
|
||||||
@JoinColumn({ name: 'giver_id' })
|
|
||||||
giver!: Guardian;
|
|
||||||
|
|
||||||
@ManyToOne(() => Junior, (junior) => junior.gifts)
|
|
||||||
@JoinColumn({ name: 'recipient_id' })
|
|
||||||
recipient!: Junior;
|
|
||||||
|
|
||||||
@ManyToOne(() => Document, (document) => document.gifts)
|
|
||||||
@JoinColumn({ name: 'image_id' })
|
|
||||||
image!: Document;
|
|
||||||
|
|
||||||
@OneToMany(() => GiftRedemption, (giftRedemption) => giftRedemption.gift, { cascade: true })
|
|
||||||
redemptions!: GiftRedemption[];
|
|
||||||
|
|
||||||
@OneToOne(() => GiftReply, (giftReply) => giftReply.gift, { cascade: true })
|
|
||||||
reply?: GiftReply;
|
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
createdAt!: Date;
|
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
updatedAt!: Date;
|
|
||||||
}
|
|
@ -1,3 +0,0 @@
|
|||||||
export * from './gift-redemption.entity';
|
|
||||||
export * from './gift-reply.entity';
|
|
||||||
export * from './gift.entity';
|
|
@ -1,6 +0,0 @@
|
|||||||
export enum GiftColor {
|
|
||||||
VIOLET = 'VIOLET',
|
|
||||||
PINK = 'PINK',
|
|
||||||
BLUE = 'BLUE',
|
|
||||||
GREEN = 'GREEN',
|
|
||||||
}
|
|
@ -1,4 +0,0 @@
|
|||||||
export enum GiftReplyStatus {
|
|
||||||
PENDING = 'PENDING',
|
|
||||||
OPENED = 'OPENED',
|
|
||||||
}
|
|
@ -1,4 +0,0 @@
|
|||||||
export enum GiftStatus {
|
|
||||||
AVAILABLE = 'AVAILABLE',
|
|
||||||
REDEEMED = 'REDEEMED',
|
|
||||||
}
|
|
@ -1,3 +0,0 @@
|
|||||||
export * from './gift-color.enum';
|
|
||||||
export * from './gift-reply-status.enum';
|
|
||||||
export * from './gift-status.enum';
|
|
@ -1,14 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { JuniorModule } from '~/junior/junior.module';
|
|
||||||
import { GiftsController } from './controllers';
|
|
||||||
import { Gift, GiftRedemption, GiftReply } from './entities';
|
|
||||||
import { GiftsRepository } from './repositories';
|
|
||||||
import { GiftsService } from './services';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [TypeOrmModule.forFeature([Gift, GiftReply, GiftRedemption]), JuniorModule],
|
|
||||||
controllers: [GiftsController],
|
|
||||||
providers: [GiftsService, GiftsRepository],
|
|
||||||
})
|
|
||||||
export class GiftModule {}
|
|
@ -1,76 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { Repository } from 'typeorm';
|
|
||||||
import { Roles } from '~/auth/enums';
|
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
|
||||||
import { CreateGiftRequestDto, GiftFiltersRequestDto, GiftReplyRequestDto } from '../dtos/request';
|
|
||||||
import { Gift, GiftRedemption, GiftReply } from '../entities';
|
|
||||||
import { GiftStatus } from '../enums';
|
|
||||||
const ONE = 1;
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GiftsRepository {
|
|
||||||
constructor(@InjectRepository(Gift) private readonly giftsRepository: Repository<Gift>) {}
|
|
||||||
|
|
||||||
create(guardianId: string, gift: CreateGiftRequestDto): Promise<Gift> {
|
|
||||||
return this.giftsRepository.save(
|
|
||||||
this.giftsRepository.create({
|
|
||||||
name: gift.name,
|
|
||||||
description: gift.description,
|
|
||||||
amount: gift.amount,
|
|
||||||
recipientId: gift.recipientId,
|
|
||||||
imageId: gift.imageId,
|
|
||||||
color: gift.color,
|
|
||||||
giverId: guardianId,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
findJuniorGiftById(juniorId: string, giftId: string): Promise<Gift | null> {
|
|
||||||
return this.giftsRepository.findOne({
|
|
||||||
where: { recipientId: juniorId, id: giftId },
|
|
||||||
relations: ['recipient', 'recipient.customer', 'image', 'giver', 'giver.customer', 'reply'],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
findGuardianGiftById(guardianId: string, giftId: string): Promise<Gift | null> {
|
|
||||||
return this.giftsRepository.findOne({
|
|
||||||
where: { giverId: guardianId, id: giftId },
|
|
||||||
relations: ['recipient', 'recipient.customer', 'image', 'giver', 'giver.customer', 'reply'],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
findGifts(user: IJwtPayload, filters: GiftFiltersRequestDto) {
|
|
||||||
const query = this.giftsRepository.createQueryBuilder('gift');
|
|
||||||
if (user.roles.includes(Roles.GUARDIAN)) {
|
|
||||||
query.where('gift.giverId = :giverId', { giverId: user.sub });
|
|
||||||
} else {
|
|
||||||
query.where('gift.recipientId = :recipientId', { recipientId: user.sub });
|
|
||||||
}
|
|
||||||
query.andWhere('gift.status = :status', { status: filters.status });
|
|
||||||
query.skip((filters.page - ONE) * filters.size);
|
|
||||||
query.take(filters.size);
|
|
||||||
query.orderBy('gift.createdAt', 'DESC');
|
|
||||||
return query.getManyAndCount();
|
|
||||||
}
|
|
||||||
|
|
||||||
redeemGift(gift: Gift) {
|
|
||||||
const redemptions = gift.redemptions || [];
|
|
||||||
gift.status = GiftStatus.REDEEMED;
|
|
||||||
gift.redeemedAt = new Date();
|
|
||||||
gift.redemptions = [...redemptions, new GiftRedemption()];
|
|
||||||
return this.giftsRepository.save(gift);
|
|
||||||
}
|
|
||||||
|
|
||||||
UndoGiftRedemption(gift: Gift) {
|
|
||||||
gift.status = GiftStatus.AVAILABLE;
|
|
||||||
gift.redeemedAt = null;
|
|
||||||
return this.giftsRepository.save(gift);
|
|
||||||
}
|
|
||||||
|
|
||||||
replyToGift(gift: Gift, reply: GiftReplyRequestDto) {
|
|
||||||
gift.reply = GiftReply.create({ ...reply });
|
|
||||||
|
|
||||||
return this.giftsRepository.save(gift);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './gifts.repository';
|
|
@ -1,139 +0,0 @@
|
|||||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
|
||||||
import { Roles } from '~/auth/enums';
|
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
|
||||||
import { DocumentService, OciService } from '~/document/services';
|
|
||||||
import { JuniorService } from '~/junior/services';
|
|
||||||
import { CreateGiftRequestDto, GiftFiltersRequestDto, GiftReplyRequestDto } from '../dtos/request';
|
|
||||||
import { Gift } from '../entities';
|
|
||||||
import { GiftStatus } from '../enums';
|
|
||||||
import { GiftsRepository } from '../repositories';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class GiftsService {
|
|
||||||
private readonly logger = new Logger(GiftsService.name);
|
|
||||||
constructor(
|
|
||||||
private readonly juniorService: JuniorService,
|
|
||||||
private readonly giftsRepository: GiftsRepository,
|
|
||||||
private readonly ociService: OciService,
|
|
||||||
private readonly documentService: DocumentService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async createGift(guardianId: string, body: CreateGiftRequestDto) {
|
|
||||||
this.logger.log(`Creating gift for junior ${body.recipientId} by guardian ${guardianId}`);
|
|
||||||
|
|
||||||
await this.validateGiftImage(guardianId, body.imageId);
|
|
||||||
const doesJuniorBelongToGuardian = await this.juniorService.doesJuniorBelongToGuardian(
|
|
||||||
guardianId,
|
|
||||||
body.recipientId,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!doesJuniorBelongToGuardian) {
|
|
||||||
this.logger.error(`Junior ${body.recipientId} does not belong to guardian ${guardianId}`);
|
|
||||||
throw new BadRequestException('JUNIOR.DOES_NOT_BELONG_TO_GUARDIAN');
|
|
||||||
}
|
|
||||||
|
|
||||||
const gift = await this.giftsRepository.create(guardianId, body);
|
|
||||||
this.logger.log(`Gift ${gift.id} created successfully`);
|
|
||||||
return this.findUserGiftById({ sub: guardianId, roles: [Roles.GUARDIAN] }, gift.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
async findUserGiftById(user: IJwtPayload, giftId: string) {
|
|
||||||
this.logger.log(`Finding gift ${giftId} for user ${user.sub} with roles ${user.roles}`);
|
|
||||||
const gift = user.roles.includes(Roles.GUARDIAN)
|
|
||||||
? await this.giftsRepository.findGuardianGiftById(user.sub, giftId)
|
|
||||||
: await this.giftsRepository.findJuniorGiftById(user.sub, giftId);
|
|
||||||
|
|
||||||
if (!gift) {
|
|
||||||
this.logger.error(`Gift ${giftId} not found`);
|
|
||||||
throw new BadRequestException('GIFT.NOT_FOUND');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.prepareGiftImages([gift]);
|
|
||||||
|
|
||||||
this.logger.log(`Gift ${giftId} found successfully`);
|
|
||||||
|
|
||||||
return gift;
|
|
||||||
}
|
|
||||||
|
|
||||||
async redeemGift(juniorId: string, giftId: string) {
|
|
||||||
this.logger.log(`Redeeming gift ${giftId} for junior ${juniorId}`);
|
|
||||||
const gift = await this.giftsRepository.findJuniorGiftById(juniorId, giftId);
|
|
||||||
|
|
||||||
if (!gift) {
|
|
||||||
this.logger.error(`Gift ${giftId} not found`);
|
|
||||||
throw new BadRequestException('GIFT.NOT_FOUND');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (gift.status === GiftStatus.REDEEMED) {
|
|
||||||
this.logger.error(`Gift ${giftId} already redeemed`);
|
|
||||||
throw new BadRequestException('GIFT.ALREADY_REDEEMED');
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.giftsRepository.redeemGift(gift);
|
|
||||||
}
|
|
||||||
|
|
||||||
async UndoGiftRedemption(juniorId: string, giftId: string) {
|
|
||||||
this.logger.log(`Undoing gift redemption for junior ${juniorId} and gift ${giftId}`);
|
|
||||||
const gift = await this.giftsRepository.findJuniorGiftById(juniorId, giftId);
|
|
||||||
|
|
||||||
if (!gift) {
|
|
||||||
this.logger.error(`Gift ${giftId} not found`);
|
|
||||||
throw new BadRequestException('GIFT.NOT_FOUND');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (gift.status === GiftStatus.AVAILABLE) {
|
|
||||||
this.logger.error(`Gift ${giftId} is not redeemed yet`);
|
|
||||||
throw new BadRequestException('GIFT.NOT_REDEEMED');
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.giftsRepository.UndoGiftRedemption(gift);
|
|
||||||
}
|
|
||||||
|
|
||||||
async replyToGift(juniorId: string, giftId: string, body: GiftReplyRequestDto) {
|
|
||||||
this.logger.log(`Replying to gift ${giftId} for junior ${juniorId}`);
|
|
||||||
const gift = await this.giftsRepository.findJuniorGiftById(juniorId, giftId);
|
|
||||||
|
|
||||||
if (!gift) {
|
|
||||||
this.logger.error(`Gift ${giftId} not found`);
|
|
||||||
throw new BadRequestException('GIFT.NOT_FOUND');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (gift.reply) {
|
|
||||||
this.logger.error(`Gift ${giftId} already replied`);
|
|
||||||
throw new BadRequestException('GIFT.ALREADY_REPLIED');
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.giftsRepository.replyToGift(gift, body);
|
|
||||||
}
|
|
||||||
|
|
||||||
findGifts(user: IJwtPayload, filters: GiftFiltersRequestDto) {
|
|
||||||
this.logger.log(`Finding gifts for user ${user.sub} with roles ${user.roles}`);
|
|
||||||
return this.giftsRepository.findGifts(user, filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async prepareGiftImages(gifts: Gift[]) {
|
|
||||||
this.logger.log('Preparing gifts image');
|
|
||||||
await Promise.all(
|
|
||||||
gifts.map(async (gift) => {
|
|
||||||
gift.image.url = await this.ociService.generatePreSignedUrl(gift.image);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async validateGiftImage(userId: string, imageId?: string) {
|
|
||||||
if (!imageId) return;
|
|
||||||
|
|
||||||
this.logger.log(`Validating gift image ${imageId}`);
|
|
||||||
const image = await this.documentService.findDocumentById(imageId);
|
|
||||||
|
|
||||||
if (!image) {
|
|
||||||
this.logger.error(`Gift image ${imageId} not found`);
|
|
||||||
throw new BadRequestException('DOCUMENT.NOT_FOUND');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (image.createdById && image.createdById !== userId) {
|
|
||||||
this.logger.error(`Gift image ${imageId} does not belong to user ${userId}`);
|
|
||||||
throw new BadRequestException('DOCUMENT.NOT_CREATED_BY_USER');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
export * from './gifts.service';
|
|
@ -9,12 +9,8 @@ import {
|
|||||||
PrimaryColumn,
|
PrimaryColumn,
|
||||||
UpdateDateColumn,
|
UpdateDateColumn,
|
||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
import { Allowance } from '~/allowance/entities';
|
|
||||||
import { Customer } from '~/customer/entities';
|
import { Customer } from '~/customer/entities';
|
||||||
import { Gift } from '~/gift/entities';
|
|
||||||
import { Junior } from '~/junior/entities';
|
import { Junior } from '~/junior/entities';
|
||||||
import { MoneyRequest } from '~/money-request/entities';
|
|
||||||
import { Task } from '~/task/entities';
|
|
||||||
|
|
||||||
@Entity('guardians')
|
@Entity('guardians')
|
||||||
export class Guardian extends BaseEntity {
|
export class Guardian extends BaseEntity {
|
||||||
@ -31,21 +27,9 @@ export class Guardian extends BaseEntity {
|
|||||||
@OneToMany(() => Junior, (junior) => junior.guardian)
|
@OneToMany(() => Junior, (junior) => junior.guardian)
|
||||||
juniors!: Junior[];
|
juniors!: Junior[];
|
||||||
|
|
||||||
@OneToMany(() => Task, (task) => task.assignedBy)
|
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
tasks?: Task[];
|
|
||||||
|
|
||||||
@OneToMany(() => MoneyRequest, (moneyRequest) => moneyRequest.reviewer)
|
|
||||||
moneyRequests?: MoneyRequest[];
|
|
||||||
|
|
||||||
@OneToMany(() => Allowance, (allowance) => allowance.guardian)
|
|
||||||
allowances?: Allowance[];
|
|
||||||
|
|
||||||
@OneToMany(() => Gift, (gift) => gift.giver)
|
|
||||||
gifts?: Gift[];
|
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'created_at', type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
|
|
||||||
createdAt!: Date;
|
createdAt!: Date;
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
updatedAt!: Date;
|
updatedAt!: Date;
|
||||||
}
|
}
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user