mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2026-10-23 10:47:56 +00:00
Compare commits
91
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54ce5b022d | ||
|
|
dae9cb6323 | ||
|
|
270753cfd7 | ||
|
|
6b1cb3a84e | ||
|
|
ebd4b293e9 | ||
|
|
87bb1a2709 | ||
|
|
663e8972c4 | ||
|
|
8ff9f921e8 | ||
|
|
6d2d2b558a | ||
|
|
5aa3d3774d | ||
|
|
221f3bae4f | ||
|
|
62621c1a15 | ||
|
|
756e947c8a | ||
|
|
db02a28b4d | ||
|
|
afc087ff08 | ||
|
|
ee433a5c8c | ||
|
|
3ab0f179d8 | ||
|
|
25ef549417 | ||
|
|
084d39096c | ||
|
|
eca84b4e75 | ||
|
|
aefa866ae7 | ||
|
|
557ef4cd33 | ||
|
|
eea6302dda | ||
|
|
c0fafd3f7c | ||
|
|
f7290419d2 | ||
|
|
0fd2066c4a | ||
|
|
cb54311a7b | ||
|
|
ca71632755 | ||
|
|
ebf335eabd | ||
|
|
f383f6d14d | ||
|
|
5663a287f9 | ||
|
|
a7028fa64c | ||
|
|
0750509a85 | ||
|
|
4d9ebe729e | ||
|
|
bb8cc33d53 | ||
|
|
e933cacdcf | ||
|
|
3719498c2f | ||
|
|
c7470302bd | ||
|
|
5e9e83cb74 | ||
|
|
4cef58580e | ||
|
|
0ba09cbf8b | ||
|
|
28a2cb5d75 | ||
|
|
4961a192ea | ||
|
|
8ab47f3835 | ||
|
|
8112fb81a2 | ||
|
|
2c3c862c4a | ||
|
|
93f5d83825 | ||
|
|
ea60ac3d7b | ||
|
|
0748695f23 | ||
|
|
a201692c0c | ||
|
|
fd6c1d1442 | ||
|
|
ed57ce6e91 | ||
|
|
33453b193f | ||
|
|
b0972f1a0a | ||
|
|
7437403756 | ||
|
|
4d2f6f57f4 | ||
|
|
24d990592d | ||
|
|
5b7b7ff689 | ||
|
|
6fccacd085 | ||
|
|
51fa61dbc6 | ||
|
|
4867a5f858 | ||
|
|
687b6a5c6d | ||
|
|
e6ed1772f7 | ||
|
|
1f0a14fee4 | ||
|
|
eb70828ae0 | ||
|
|
220a03cc46 | ||
|
|
39b1e76bb5 | ||
|
|
83fc634d25 | ||
|
|
35b434bc3d | ||
|
|
749ee5457f | ||
|
|
d539073f29 | ||
|
|
66e1bb0f28 | ||
|
|
577f91b796 | ||
|
|
7ed37c30e1 | ||
|
|
c2f63ccc72 | ||
|
|
970a41c895 | ||
|
|
3fd29b3905 | ||
|
|
7f7fef3f89 | ||
|
|
90ee8023e6 | ||
|
|
c486d558ad | ||
|
|
85569af770 | ||
|
|
f97bb08c5c | ||
|
|
6f6e3f7e7b | ||
|
|
26b2d153fd | ||
|
|
2577f2dcac | ||
|
|
e4b69a406f | ||
|
|
2fdce34ffc | ||
|
|
2bf9dea771 | ||
|
|
847c078735 | ||
|
|
14e70a63b8 | ||
|
|
05872b5170 |
@@ -0,0 +1,40 @@
|
|||||||
|
NODE_ENV=dev
|
||||||
|
PORT=5000
|
||||||
|
DB_HOST=
|
||||||
|
DB_PASS=
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_NAME=
|
||||||
|
MIGRATIONS_RUN=true
|
||||||
|
SWAGGER_API_DOCS_PATH="/api-docs"
|
||||||
|
|
||||||
|
JWT_ACCESS_TOKEN_SECRET=your_access_token_secret
|
||||||
|
JWT_ACCESS_TOKEN_EXPIRY=1d
|
||||||
|
JWT_REFRESH_TOKEN_SECRET=your_refresh_token_secret
|
||||||
|
JWT_REFRESH_TOKEN_EXPIRY=1d
|
||||||
|
USE_MOCK=true
|
||||||
|
|
||||||
|
|
||||||
|
OCI_TENANCY_ID=
|
||||||
|
OCI_USER_ID=
|
||||||
|
OCI_FINGERPRINT=
|
||||||
|
OCI_PRIVATE_KEY=
|
||||||
|
OCI_PASSPHRASE=""
|
||||||
|
OCI_NAMESPACE=
|
||||||
|
OCI_REGION=
|
||||||
|
|
||||||
|
|
||||||
|
MAIL_HOST=smtp.gmail.com
|
||||||
|
MAIL_USER=[email protected]
|
||||||
|
MAIL_PASSWORD=
|
||||||
|
MAIL_PORT=587
|
||||||
|
MAIL_FROM=UBA
|
||||||
|
|
||||||
|
|
||||||
|
BRANCH_IO_URL=https://api2.branch.io/v1/url
|
||||||
|
BRANCH_IO_KEY=
|
||||||
|
ZOD_BASE_URL=http://localhost:5001
|
||||||
|
ANDROID_PACKAGE_NAME=com.zod
|
||||||
|
IOS_PACKAGE_NAME=com.zod
|
||||||
|
ANDRIOD_JUNIOR_DEEPLINK_PATH=zodbank://juniors/qr-code/validate
|
||||||
|
IOS_JUNIOR_DEEPLINK_PATH=zodbank://juniors/qr-code/validate
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/** @type {import('eslint').Linter.Config} */
|
||||||
|
module.exports = {
|
||||||
|
parser: '@typescript-eslint/parser',
|
||||||
|
parserOptions: {
|
||||||
|
project: 'tsconfig.json',
|
||||||
|
tsconfigRootDir: __dirname,
|
||||||
|
sourceType: 'module',
|
||||||
|
},
|
||||||
|
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||||
|
extends: ['plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', 'plugin:security/recommended'],
|
||||||
|
root: true,
|
||||||
|
env: {
|
||||||
|
node: true,
|
||||||
|
jest: true,
|
||||||
|
},
|
||||||
|
ignorePatterns: ['.eslintrc.js', 'node_modules', 'dist', 'coverage', 'jest*\\.ts', 'typeorm*\\.ts'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/interface-name-prefix': 'off',
|
||||||
|
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||||
|
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-unused-vars': [
|
||||||
|
'warn',
|
||||||
|
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' },
|
||||||
|
],
|
||||||
|
'@typescript-eslint/no-inferrable-types': 'off',
|
||||||
|
'func-names': ['error', 'as-needed'],
|
||||||
|
'no-underscore-dangle': ['error'],
|
||||||
|
'require-await': ['error'],
|
||||||
|
'no-console': ['error'],
|
||||||
|
'no-multi-assign': ['error'],
|
||||||
|
'no-magic-numbers': ['error', { ignoreArrayIndexes: true}],
|
||||||
|
'no-multiple-empty-lines': ['error', { max: 1, maxEOF: 1, maxBOF: 0 }],
|
||||||
|
'max-len': [
|
||||||
|
'error',
|
||||||
|
{ code: 120, tabWidth: 2, ignoreUrls: true, ignoreStrings: true, ignoreTemplateLiterals: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
overrides: [
|
||||||
|
{
|
||||||
|
files: ['*spec.ts'],
|
||||||
|
rules: {
|
||||||
|
'no-magic-numbers': ['off'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
name: CI Zod
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- '*'
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- dev
|
||||||
|
- main
|
||||||
|
|
||||||
|
env:
|
||||||
|
NODE_ENV: development
|
||||||
|
TAG: dev
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
install_dependencies:
|
||||||
|
name: Install Dependencies
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 22.4.1
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: npm install
|
||||||
|
|
||||||
|
- name: Cache Node Modules
|
||||||
|
uses: actions/cache@v3
|
||||||
|
with:
|
||||||
|
path: node_modules
|
||||||
|
key: ${{ runner.os }}-node_modules-${{ hashFiles('**/package-lock.json') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-node_modules-
|
||||||
|
|
||||||
|
run_tests:
|
||||||
|
name: Run Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: install_dependencies
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 22.4.1
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: npm install
|
||||||
|
|
||||||
|
- name: Run Lint
|
||||||
|
run: npm run lint
|
||||||
|
|
||||||
|
- name: Run Tests with Coverage
|
||||||
|
run: npm run test:cov
|
||||||
|
|
||||||
|
build_app:
|
||||||
|
name: Build Application
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: run_tests
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version: 22.4.1
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: npm install
|
||||||
|
|
||||||
|
- name: Build Application
|
||||||
|
run: npm run build
|
||||||
|
|
||||||
|
- name: Upload Build Artifacts
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: dist
|
||||||
|
path: dist/
|
||||||
+52
-21
@@ -1,24 +1,55 @@
|
|||||||
/static
|
# compiled output
|
||||||
/media
|
/dist
|
||||||
.idea/
|
/node_modules
|
||||||
*.pyc
|
/build
|
||||||
media/
|
|
||||||
*.name
|
# Logs
|
||||||
*.iml
|
logs
|
||||||
*.log
|
*.log
|
||||||
*.xml
|
npm-debug.log*
|
||||||
*.pyo
|
pnpm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.idea
|
|
||||||
venv/*
|
# Tests
|
||||||
static/*
|
/coverage
|
||||||
*.pem
|
/.nyc_output
|
||||||
*.sqlite3
|
|
||||||
/migrations/__pycache__/
|
# IDEs and editors
|
||||||
/__pycache__/
|
/.idea
|
||||||
/*.pyc
|
.project
|
||||||
*/__pycache__/*.pyc
|
.classpath
|
||||||
__pycache__/
|
.c9/
|
||||||
*.env
|
*.launch
|
||||||
ve/*
|
.settings/
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# IDE - VSCode
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
|
||||||
|
|
||||||
|
# dotenv environment variable files
|
||||||
|
.env
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# temp directory
|
||||||
|
.temp
|
||||||
|
.tmp
|
||||||
|
|
||||||
|
# Runtime data
|
||||||
|
pids
|
||||||
|
*.pid
|
||||||
|
*.seed
|
||||||
|
*.pid.lock
|
||||||
|
|
||||||
|
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||||
|
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"tabWidth": 2,
|
||||||
|
"printWidth": 120
|
||||||
|
}
|
||||||
Vendored
+6
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"editor.formatOnSave": true,
|
||||||
|
"editor.codeActionsOnSave": {
|
||||||
|
"source.organizeImports": "explicit"
|
||||||
|
}
|
||||||
|
}
|
||||||
-11
@@ -1,11 +0,0 @@
|
|||||||
FROM python:3.9
|
|
||||||
ENV PYTHONUNBUFFERED 1
|
|
||||||
RUN mkdir /usr/src/app
|
|
||||||
WORKDIR /usr/src/app
|
|
||||||
COPY . .
|
|
||||||
RUN apt-get update
|
|
||||||
RUN apt-get install wkhtmltopdf -y
|
|
||||||
RUN apt install -y gdal-bin python3-gdal
|
|
||||||
RUN pip install -r requirements.txt
|
|
||||||
WORKDIR /usr/src/app
|
|
||||||
|
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Base image
|
||||||
|
FROM node:22.4.1-alpine
|
||||||
|
RUN apk update && \
|
||||||
|
apk upgrade && \
|
||||||
|
apk add ca-certificates curl && \
|
||||||
|
update-ca-certificates
|
||||||
|
|
||||||
|
#saudi timezone
|
||||||
|
ENV TZ=Asia/Riyadh
|
||||||
|
|
||||||
|
# Create app directory
|
||||||
|
RUN mkdir /app && chown node:node /app
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# finally switch user to node
|
||||||
|
USER node
|
||||||
|
|
||||||
|
|
||||||
|
# A wildcard is used to ensure both package.json, package-lock.json and package-lock.json are copied
|
||||||
|
COPY --chown=node:node package*.json ./
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Install app dependencies
|
||||||
|
RUN npm install --frozen-lockfile
|
||||||
|
# Bundle app source
|
||||||
|
COPY --chown=node:node . .
|
||||||
|
|
||||||
|
# Creates a "dist" folder with the production build
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Start the server using the production build
|
||||||
|
CMD [ "node", "dist/main" ]
|
||||||
@@ -1 +1,99 @@
|
|||||||
# ZODBank-Backend
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||||
|
</p>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compile and run the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ npm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ npm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ npm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ npm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ npm run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||||
|
|
||||||
|
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install -g mau
|
||||||
|
$ mau deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
Check out a few resources that may come in handy when working with NestJS:
|
||||||
|
|
||||||
|
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||||
|
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||||
|
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||||
|
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||||
|
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||||
|
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||||
|
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||||
|
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||||
|
|
||||||
|
## Stay in touch
|
||||||
|
|
||||||
|
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||||
|
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||||
|
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
"""Account admin"""
|
|
||||||
from django.contrib import admin
|
|
||||||
|
|
||||||
"""Import django app"""
|
|
||||||
from .models import UserProfile, UserEmailOtp, UserPhoneOtp
|
|
||||||
# Register your models here.
|
|
||||||
@admin.register(UserProfile)
|
|
||||||
class UserProfileAdmin(admin.ModelAdmin):
|
|
||||||
"""User profile admin"""
|
|
||||||
list_display = ['user']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.user__email
|
|
||||||
|
|
||||||
@admin.register(UserEmailOtp)
|
|
||||||
class UserEmailOtpAdmin(admin.ModelAdmin):
|
|
||||||
"""User Email otp admin"""
|
|
||||||
list_display = ['email']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return object in email and otp format"""
|
|
||||||
return self.email + '-' + self.otp
|
|
||||||
|
|
||||||
@admin.register(UserPhoneOtp)
|
|
||||||
class UserPhoneOtpAdmin(admin.ModelAdmin):
|
|
||||||
"""User Phone otp admin"""
|
|
||||||
list_display = ['phone']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return object in phone number and otp format"""
|
|
||||||
return self.phone + '-' + self.otp
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
from django.apps import AppConfig
|
|
||||||
|
|
||||||
|
|
||||||
class AccountConfig(AppConfig):
|
|
||||||
default_auto_field = 'django.db.models.BigAutoField'
|
|
||||||
name = 'account'
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db import migrations, models
|
|
||||||
import django.db.models.deletion
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
initial = True
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='UserEmailOtp',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('email', models.EmailField(max_length=254)),
|
|
||||||
('otp', models.CharField(max_length=10)),
|
|
||||||
('is_verified', models.BooleanField(default=False)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('expired_at', models.DateTimeField(blank=True, null=True)),
|
|
||||||
('is_active', models.BooleanField(default=True)),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'db_table': 'user_email_otp',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='UserPhoneOtp',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('country_code', models.IntegerField()),
|
|
||||||
('phone', models.CharField(max_length=17)),
|
|
||||||
('otp', models.CharField(max_length=10)),
|
|
||||||
('is_verified', models.BooleanField(default=False)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('expired_at', models.DateTimeField(blank=True, null=True)),
|
|
||||||
('is_active', models.BooleanField(default=True)),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'db_table': 'user_phone_otp',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='UserProfile',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('user_type', models.CharField(blank=True, choices=[('1', 'junior'), ('2', 'guardian'), ('3', 'superuser')], default=None, max_length=15, null=True)),
|
|
||||||
('is_verified', models.BooleanField(default=False)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('is_active', models.BooleanField(default=False)),
|
|
||||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_profile', to=settings.AUTH_USER_MODEL)),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'db_table': 'user_profile',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
from django.db import models
|
|
||||||
import random
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
from base.constants import USER_TYPE
|
|
||||||
# Create your models here.
|
|
||||||
|
|
||||||
class UserProfile(models.Model):
|
|
||||||
"""
|
|
||||||
User details
|
|
||||||
"""
|
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile')
|
|
||||||
user_type = models.CharField(max_length=15, choices=USER_TYPE, null=True, blank=True, default=None)
|
|
||||||
is_verified = models.BooleanField(default=False)
|
|
||||||
|
|
||||||
# OTP validity
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
is_active = models.BooleanField(default=False)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta information """
|
|
||||||
db_table = 'user_profile'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""return phone as an object"""
|
|
||||||
return f'{self.user}'
|
|
||||||
|
|
||||||
class UserPhoneOtp(models.Model):
|
|
||||||
"""
|
|
||||||
This class is used to verify user email and their contact no.
|
|
||||||
"""
|
|
||||||
"""user details"""
|
|
||||||
country_code = models.IntegerField()
|
|
||||||
phone = models.CharField(max_length=17)
|
|
||||||
"""otp details"""
|
|
||||||
otp = models.CharField(max_length=10)
|
|
||||||
is_verified = models.BooleanField(default=False)
|
|
||||||
|
|
||||||
# OTP validity
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
expired_at = models.DateTimeField(blank=True, null=True)
|
|
||||||
is_active = models.BooleanField(default=True)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta information """
|
|
||||||
db_table = 'user_phone_otp'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""return phone as an object"""
|
|
||||||
return self.phone
|
|
||||||
|
|
||||||
class UserEmailOtp(models.Model):
|
|
||||||
"""
|
|
||||||
This class is used to verify user email and their contact no.
|
|
||||||
"""
|
|
||||||
"""user details"""
|
|
||||||
email = models.EmailField()
|
|
||||||
"""otp details"""
|
|
||||||
otp = models.CharField(max_length=10)
|
|
||||||
is_verified = models.BooleanField(default=False)
|
|
||||||
|
|
||||||
# OTP validity
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
expired_at = models.DateTimeField(blank=True, null=True)
|
|
||||||
is_active = models.BooleanField(default=True)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta information """
|
|
||||||
db_table = 'user_email_otp'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""return phone as an object"""
|
|
||||||
return self.email
|
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
from rest_framework import serializers
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
from guardian.models import Guardian
|
|
||||||
from junior.models import Junior
|
|
||||||
from account.models import UserProfile, UserEmailOtp, UserPhoneOtp
|
|
||||||
from base.constants import GUARDIAN, JUNIOR, SUPERUSER
|
|
||||||
from django.db import transaction
|
|
||||||
from base.messages import ERROR_CODE_REQUIRED, ERROR_CODE, SUCCESS_CODE, STATUS_CODE_ERROR
|
|
||||||
from django.core.exceptions import ObjectDoesNotExist
|
|
||||||
from django.contrib.auth import authenticate
|
|
||||||
from rest_framework import viewsets, status
|
|
||||||
from rest_framework.decorators import action
|
|
||||||
from django.contrib.auth import authenticate, login
|
|
||||||
from rest_framework_simplejwt.tokens import RefreshToken
|
|
||||||
|
|
||||||
|
|
||||||
class ResetPasswordSerializer(serializers.Serializer):
|
|
||||||
"""Reset Password after verification"""
|
|
||||||
verification_code = serializers.CharField(max_length=10)
|
|
||||||
password = serializers.CharField(required=True)
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = User
|
|
||||||
|
|
||||||
def create(self, validated_data):
|
|
||||||
verification_code = validated_data.pop('verification_code')
|
|
||||||
password = validated_data.pop('password')
|
|
||||||
print("verification_code===>",verification_code)
|
|
||||||
print("password===>", password)
|
|
||||||
user_opt_details = UserEmailOtp.objects.filter(otp=verification_code, is_verified=True).last()
|
|
||||||
print("user_opt_details===>",user_opt_details)
|
|
||||||
if user_opt_details:
|
|
||||||
print("qqqqqqqqqq")
|
|
||||||
user_details = User.objects.filter(email=user_opt_details.email).last()
|
|
||||||
if user_details:
|
|
||||||
print("333333333==>",user_details.password)
|
|
||||||
user_details.set_password(password)
|
|
||||||
user_details.save()
|
|
||||||
return {'password':password}
|
|
||||||
return user_opt_details
|
|
||||||
return ''
|
|
||||||
|
|
||||||
class ChangePasswordSerializer(serializers.Serializer):
|
|
||||||
"""Update Password after verification"""
|
|
||||||
current_password = serializers.CharField(max_length=100)
|
|
||||||
new_password = serializers.CharField(required=True)
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = User
|
|
||||||
|
|
||||||
def validate_current_password(self, value):
|
|
||||||
user = self.context
|
|
||||||
if self.context.password not in ('', None):
|
|
||||||
if user.check_password(value):
|
|
||||||
return value
|
|
||||||
raise serializers.ValidationError({"error":"Invalid Current password"})
|
|
||||||
def create(self, validated_data):
|
|
||||||
new_password = validated_data.pop('new_password')
|
|
||||||
user_details = User.objects.filter(email=self.context).last()
|
|
||||||
print("user_details==>", user_details)
|
|
||||||
if user_details:
|
|
||||||
print("333333333==>",user_details.password)
|
|
||||||
user_details.set_password(new_password)
|
|
||||||
user_details.save()
|
|
||||||
return {'password':new_password}
|
|
||||||
return ''
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class ForgotPasswordSerializer(serializers.Serializer):
|
|
||||||
"""Forget password serializer"""
|
|
||||||
email = serializers.EmailField()
|
|
||||||
|
|
||||||
class SuperUserSerializer(serializers.ModelSerializer):
|
|
||||||
user_type = serializers.SerializerMethodField('get_user_type')
|
|
||||||
|
|
||||||
def get_user_type(self, obj):
|
|
||||||
"""user type"""
|
|
||||||
return SUPERUSER
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = User
|
|
||||||
fields = ['id', 'username', 'email', 'first_name', 'last_name', 'is_active', 'user_type']
|
|
||||||
|
|
||||||
|
|
||||||
class GuardianSerializer(serializers.ModelSerializer):
|
|
||||||
"""guardian serializer"""
|
|
||||||
user_type = serializers.SerializerMethodField('get_user_type')
|
|
||||||
email = serializers.SerializerMethodField('get_auth')
|
|
||||||
first_name = serializers.SerializerMethodField('get_first_name')
|
|
||||||
last_name = serializers.SerializerMethodField('get_last_name')
|
|
||||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
|
||||||
|
|
||||||
def get_auth_token(self, obj):
|
|
||||||
refresh = RefreshToken.for_user(obj.user)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
return access_token
|
|
||||||
|
|
||||||
def get_user_type(self, obj):
|
|
||||||
"""user type"""
|
|
||||||
return GUARDIAN
|
|
||||||
|
|
||||||
def get_auth(self, obj):
|
|
||||||
"""user email address"""
|
|
||||||
return obj.user.username
|
|
||||||
|
|
||||||
def get_first_name(self, obj):
|
|
||||||
"""user first name"""
|
|
||||||
return obj.user.first_name
|
|
||||||
|
|
||||||
def get_last_name(self, obj):
|
|
||||||
"""user last name"""
|
|
||||||
return obj.user.last_name
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Guardian
|
|
||||||
fields = ['auth_token', 'email', 'first_name', 'last_name', 'country_code', 'phone', 'family_name', 'gender', 'dob',
|
|
||||||
'referral_code', 'is_active', 'is_complete_profile', 'passcode',
|
|
||||||
'created_at', 'updated_at', 'user_type']
|
|
||||||
|
|
||||||
|
|
||||||
class JuniorSerializer(serializers.ModelSerializer):
|
|
||||||
"""junior serializer"""
|
|
||||||
user_type = serializers.SerializerMethodField('get_user_type')
|
|
||||||
email = serializers.SerializerMethodField('get_auth')
|
|
||||||
first_name = serializers.SerializerMethodField('get_first_name')
|
|
||||||
last_name = serializers.SerializerMethodField('get_last_name')
|
|
||||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
|
||||||
|
|
||||||
def get_auth_token(self, obj):
|
|
||||||
refresh = RefreshToken.for_user(obj.auth)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
return access_token
|
|
||||||
|
|
||||||
def get_user_type(self, obj):
|
|
||||||
return JUNIOR
|
|
||||||
|
|
||||||
def get_auth(self, obj):
|
|
||||||
return obj.auth.username
|
|
||||||
|
|
||||||
def get_first_name(self, obj):
|
|
||||||
return obj.auth.first_name
|
|
||||||
|
|
||||||
def get_last_name(self, obj):
|
|
||||||
return obj.auth.last_name
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Junior
|
|
||||||
fields = ['auth_token', 'email', 'first_name', 'last_name', 'country_code', 'phone', 'gender', 'dob',
|
|
||||||
'guardian_code', 'referral_code','is_active', 'is_complete_profile', 'created_at',
|
|
||||||
'updated_at', 'user_type']
|
|
||||||
|
|
||||||
class EmailVerificationSerializer(serializers.ModelSerializer):
|
|
||||||
"""Email verification serializer"""
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = UserEmailOtp
|
|
||||||
fields = '__all__'
|
|
||||||
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
<!DOCTYPE HTML>
|
|
||||||
{% block subject %}DinDin{% endblock %}
|
|
||||||
{% load static %}
|
|
||||||
|
|
||||||
{% block html %}
|
|
||||||
<html lang="en" style="height: 100%;">
|
|
||||||
<head>
|
|
||||||
<meta http-equiv="Content-Type"
|
|
||||||
content="text/html; charset=UTF-8">
|
|
||||||
<meta name="viewport"
|
|
||||||
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
|
|
||||||
<title>Zod Bank | OTP</title>
|
|
||||||
<style type="text/css">
|
|
||||||
@media all and (max-width: 599px) {
|
|
||||||
.block {
|
|
||||||
display: block !important;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
.top-space {
|
|
||||||
padding: 15px 0 0 !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body style="margin: 0; padding: 0; background: #f7f8f9; height: 100%;">
|
|
||||||
<!-- begin template body -->
|
|
||||||
<table style="background:#f7f8f9; border: 0; border-collapse: separate; border-spacing: 0px; margin: auto; width: 100%; font-family: Arial, Helvetica, sans-serif; height: 100%;" aria-describedby="email-data-wrapper">
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0;">
|
|
||||||
<table style="background-color: white; border-collapse: separate; border-spacing: 0px; border: 1px solid #e4e8eb; width: 100%; max-width: 600px; margin-right:auto; margin-left: auto;
|
|
||||||
font-family: Arial, Helvetica, sans-serif;" aria-describedby="email-data-wrapper">
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 41px 30px 40px; height: 39px; background: url({% static 'images/backgrounds/email_template.png' %}) left center no-repeat; background-size: cover;">
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% block plain %}
|
|
||||||
{% endblock %}
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px;">
|
|
||||||
<p style="margin: 0; font-size: 14px; line-height: 20px; color: #505050; font-weight: 400;">-</p>
|
|
||||||
<p style="margin: 0; font-size: 14px; line-height: 20px; color: #505050; font-weight: 400;">Cheers!</p>
|
|
||||||
<p style="margin: 0 0 30px; font-size: 14px; line-height: 20px; color: #505050; font-weight: 700;">Zod Bank Team</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<!-- end template body -->
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
{% extends "templated_email/email_base.email" %}
|
|
||||||
|
|
||||||
{% block subject %}
|
|
||||||
OTP Verification
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block plain %}
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px 15px;">
|
|
||||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
|
||||||
Hi User,
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px 22px;">
|
|
||||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
|
||||||
You are receiving this email for email verification. Please use <b>{{ otp }} </b>as the verification code for your email address & username.
|
|
||||||
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
{% extends "templated_email/email_base.email" %}
|
|
||||||
|
|
||||||
{% block subject %}
|
|
||||||
Password Reset Verification Code
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block plain %}
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px 15px;">
|
|
||||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
|
||||||
Hi User,
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td style="padding: 0 27px 22px;">
|
|
||||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
|
||||||
You are receiving this email for reset password verification. Please use <b>{{ verification_code }} </b>as the verification code.
|
|
||||||
|
|
||||||
</p>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% endblock %}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
# Create your tests here.
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
""" Urls files"""
|
|
||||||
"""Django import"""
|
|
||||||
from django.urls import path, include
|
|
||||||
from rest_framework.decorators import api_view
|
|
||||||
"""Third party import"""
|
|
||||||
from rest_framework import routers
|
|
||||||
from .views import (UserLogin, SendPhoneOtp, UserPhoneVerification, UserEmailVerification, ReSendEmailOtp,
|
|
||||||
ForgotPasswordAPIView, ResetPasswordAPIView, ChangePasswordAPIView)
|
|
||||||
"""Router"""
|
|
||||||
router = routers.SimpleRouter()
|
|
||||||
|
|
||||||
"""API End points with router"""
|
|
||||||
router.register('user', UserLogin, basename='user')
|
|
||||||
router.register('admin', UserLogin, basename='admin')
|
|
||||||
router.register('send-phone-otp', SendPhoneOtp, basename='send-phone-otp')
|
|
||||||
router.register('user-phone-verification', UserPhoneVerification, basename='user-phone-verification')
|
|
||||||
router.register('user-email-verification', UserEmailVerification, basename='user-email-verification')
|
|
||||||
router.register('resend-email-otp', ReSendEmailOtp, basename='resend-email-otp')
|
|
||||||
|
|
||||||
urlpatterns = [
|
|
||||||
path('api/v1/', include(router.urls)),
|
|
||||||
path('api/v1/forgot-password/', ForgotPasswordAPIView.as_view()),
|
|
||||||
path('api/v1/reset-password/', ResetPasswordAPIView.as_view()),
|
|
||||||
path('api/v1/change-password/', ChangePasswordAPIView.as_view())
|
|
||||||
]
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
"""Account utils"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.conf import settings
|
|
||||||
from rest_framework import viewsets, status
|
|
||||||
from rest_framework.response import Response
|
|
||||||
|
|
||||||
from templated_email import send_templated_mail
|
|
||||||
def send_otp_email(recipient_email, otp):
|
|
||||||
from_email = settings.EMAIL_HOST_USER
|
|
||||||
recipient_list = [recipient_email]
|
|
||||||
send_templated_mail(
|
|
||||||
template_name='email_otp_verification.email',
|
|
||||||
from_email=from_email,
|
|
||||||
recipient_list=recipient_list,
|
|
||||||
context={
|
|
||||||
'otp': otp
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return otp
|
|
||||||
|
|
||||||
def custom_response(detail, data=None, response_status=status.HTTP_200_OK):
|
|
||||||
"""Custom response code"""
|
|
||||||
if not data:
|
|
||||||
data = None
|
|
||||||
|
|
||||||
return Response({"data": data, "message": detail, "status": "success", "code": response_status})
|
|
||||||
|
|
||||||
|
|
||||||
def custom_error_response(detail, response_status):
|
|
||||||
"""
|
|
||||||
function is used for getting same global error response for all
|
|
||||||
:param detail: error message .
|
|
||||||
:param response_status: http status.
|
|
||||||
:return: Json response
|
|
||||||
"""
|
|
||||||
if not detail:
|
|
||||||
detail = {}
|
|
||||||
return Response({"error": detail, "status": "failed", "code": response_status})
|
|
||||||
@@ -1,196 +0,0 @@
|
|||||||
from rest_framework import viewsets, status, views
|
|
||||||
from rest_framework.decorators import action
|
|
||||||
import random
|
|
||||||
import logging
|
|
||||||
from django.contrib.auth import authenticate, login
|
|
||||||
from guardian.models import Guardian
|
|
||||||
from junior.models import Junior
|
|
||||||
from account.models import UserProfile, UserPhoneOtp, UserEmailOtp
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
from .serializers import (SuperUserSerializer, GuardianSerializer, JuniorSerializer, EmailVerificationSerializer,
|
|
||||||
ForgotPasswordSerializer, ResetPasswordSerializer, ChangePasswordSerializer)
|
|
||||||
from rest_framework_simplejwt.tokens import RefreshToken
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
from guardian.tasks import generate_otp
|
|
||||||
from django.conf import settings
|
|
||||||
from account.utils import send_otp_email
|
|
||||||
from account.utils import custom_response, custom_error_response
|
|
||||||
from django.core.mail import EmailMessage
|
|
||||||
from django.core.mail import send_mail
|
|
||||||
from rest_framework.response import Response
|
|
||||||
from rest_framework.permissions import IsAuthenticated
|
|
||||||
from templated_email import send_templated_mail
|
|
||||||
|
|
||||||
|
|
||||||
class ChangePasswordAPIView(views.APIView):
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
def post(self, request):
|
|
||||||
serializer = ChangePasswordSerializer(context=request.user, data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3007'], response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ResetPasswordAPIView(views.APIView):
|
|
||||||
def post(self, request):
|
|
||||||
serializer = ResetPasswordSerializer(data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3006'], response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ForgotPasswordAPIView(views.APIView):
|
|
||||||
def post(self, request):
|
|
||||||
serializer = ForgotPasswordSerializer(data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
email = serializer.validated_data['email']
|
|
||||||
try:
|
|
||||||
User.objects.get(email=email)
|
|
||||||
except User.DoesNotExist:
|
|
||||||
return custom_error_response(ERROR_CODE['2004'], response_status=status.HTTP_404_NOT_FOUND)
|
|
||||||
verification_code = ''.join([str(random.randrange(9)) for _ in range(6)])
|
|
||||||
# Send the verification code to the user's email
|
|
||||||
from_email = settings.EMAIL_HOST_USER
|
|
||||||
recipient_list = [email]
|
|
||||||
send_templated_mail(
|
|
||||||
template_name='email_reset_verification.email',
|
|
||||||
from_email=from_email,
|
|
||||||
recipient_list=recipient_list,
|
|
||||||
context={
|
|
||||||
'verification_code': verification_code
|
|
||||||
}
|
|
||||||
)
|
|
||||||
user_data, created = UserEmailOtp.objects.get_or_create(email=email)
|
|
||||||
if user_data:
|
|
||||||
user_data.otp = verification_code
|
|
||||||
user_data.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3015'],
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class SendPhoneOtp(viewsets.ModelViewSet):
|
|
||||||
"""Send otp on phone"""
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
otp = generate_otp()
|
|
||||||
phone_number = self.request.data['phone']
|
|
||||||
if phone_number.isdigit() and len(phone_number) == 10:
|
|
||||||
phone_otp, created = UserPhoneOtp.objects.get_or_create(country_code=self.request.data['country_code'],
|
|
||||||
phone=self.request.data['phone'])
|
|
||||||
if phone_otp:
|
|
||||||
phone_otp.otp = otp
|
|
||||||
phone_otp.save()
|
|
||||||
return custom_response(None, {'phone_otp':otp}, response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(ERROR_CODE['2020'], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
|
|
||||||
class UserPhoneVerification(viewsets.ModelViewSet):
|
|
||||||
"""Send otp on phone"""
|
|
||||||
def list(self, request, *args, **kwargs):
|
|
||||||
try:
|
|
||||||
phone_data = UserPhoneOtp.objects.filter(phone=self.request.GET.get('phone'),
|
|
||||||
otp=self.request.GET.get('otp')).last()
|
|
||||||
if phone_data:
|
|
||||||
phone_data.is_verified = True
|
|
||||||
phone_data.save()
|
|
||||||
return custom_response(SUCCESS_CODE['3012'], response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
except Exception:
|
|
||||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class UserLogin(viewsets.ViewSet):
|
|
||||||
@action(methods=['post'], detail=False)
|
|
||||||
def login(self, request):
|
|
||||||
username = request.data.get('username')
|
|
||||||
password = request.data.get('password')
|
|
||||||
user = authenticate(request, username=username, password=password)
|
|
||||||
try:
|
|
||||||
if user is not None:
|
|
||||||
login(request, user)
|
|
||||||
guardian_data = Guardian.objects.filter(user__username=username, is_complete_profile=True).last()
|
|
||||||
if guardian_data:
|
|
||||||
serializer = GuardianSerializer(guardian_data)
|
|
||||||
junior_data = Junior.objects.filter(auth__username=username, is_complete_profile=True).last()
|
|
||||||
if junior_data:
|
|
||||||
serializer = JuniorSerializer(junior_data)
|
|
||||||
return custom_response(SUCCESS_CODE['3003'], serializer.data, response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2002"], response_status=status.HTTP_401_UNAUTHORIZED)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
user_profile_data = UserProfile.objects.filter(user__username=username).last()
|
|
||||||
email_verified = UserEmailOtp.objects.filter(email=username).last()
|
|
||||||
refresh = RefreshToken.for_user(user)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
data = {"auth_token":access_token, "is_profile_complete": False,
|
|
||||||
"user_role": user_profile_data.user_type,
|
|
||||||
}
|
|
||||||
is_verified = False
|
|
||||||
if email_verified:
|
|
||||||
is_verified = email_verified.is_verified
|
|
||||||
if not is_verified:
|
|
||||||
otp = generate_otp()
|
|
||||||
email_verified.otp = otp
|
|
||||||
email_verified.save()
|
|
||||||
data.update({"email_otp":otp})
|
|
||||||
return custom_response(ERROR_CODE['2024'], {"email_otp": otp, "is_email_verified": is_verified},
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
data.update({"is_email_verified": is_verified})
|
|
||||||
return custom_response(None, data, response_status=status.HTTP_200_OK)
|
|
||||||
|
|
||||||
@action(methods=['post'], detail=False)
|
|
||||||
def admin_login(self, request):
|
|
||||||
username = request.data.get('username')
|
|
||||||
password = request.data.get('password')
|
|
||||||
user = authenticate(request, username=username, password=password)
|
|
||||||
try:
|
|
||||||
if user is not None:
|
|
||||||
login(request, user)
|
|
||||||
if user.is_superuser:
|
|
||||||
serializer = SuperUserSerializer(user)
|
|
||||||
return custom_response(SUCCESS_CODE['3003'], serializer.data, response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2002"], response_status=status.HTTP_401_UNAUTHORIZED)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
refresh = RefreshToken.for_user(user)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
data = {"auth_token": access_token, "user_role": '3'}
|
|
||||||
return custom_response(None, data, response_status=status.HTTP_200_OK)
|
|
||||||
|
|
||||||
class UserEmailVerification(viewsets.ModelViewSet):
|
|
||||||
"""User Email verification"""
|
|
||||||
serializer_class = EmailVerificationSerializer
|
|
||||||
|
|
||||||
def list(self, request, *args, **kwargs):
|
|
||||||
try:
|
|
||||||
user_obj = User.objects.filter(username=self.request.GET.get('email')).last()
|
|
||||||
email_data = UserEmailOtp.objects.filter(email=self.request.GET.get('email'),
|
|
||||||
otp=self.request.GET.get('otp')).last()
|
|
||||||
if email_data:
|
|
||||||
email_data.is_verified = True
|
|
||||||
email_data.save()
|
|
||||||
refresh = RefreshToken.for_user(user_obj)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
return custom_response(SUCCESS_CODE['3011'], {"auth_token":access_token}, response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ReSendEmailOtp(viewsets.ModelViewSet):
|
|
||||||
"""Send otp on phone"""
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
otp = generate_otp()
|
|
||||||
if User.objects.filter(email=request.data['email']):
|
|
||||||
email_data, created = UserEmailOtp.objects.get_or_create(email=request.data['email'])
|
|
||||||
if email_data:
|
|
||||||
email_data.otp = otp
|
|
||||||
email_data.save()
|
|
||||||
send_otp_email(request.data['email'], otp)
|
|
||||||
return custom_response(SUCCESS_CODE['3016'], response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2023"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
"""
|
|
||||||
This is init module of the Project Zod Bank
|
|
||||||
"""
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
"""
|
|
||||||
Common send_mail function
|
|
||||||
"""
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from django.core.mail import EmailMultiAlternatives
|
|
||||||
|
|
||||||
|
|
||||||
def send_mail(subject, message, from_email, recipient_list, html_message=None, cc=None,
|
|
||||||
fail_silently=False):
|
|
||||||
"""
|
|
||||||
Send Email
|
|
||||||
:param subject:
|
|
||||||
:param message:
|
|
||||||
:param from_email:
|
|
||||||
:param recipient_list:
|
|
||||||
:param html_message:
|
|
||||||
:param cc:
|
|
||||||
:param fail_silently:
|
|
||||||
:return:
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, cc)
|
|
||||||
if html_message:
|
|
||||||
mail.attach_alternative(html_message, 'text/html')
|
|
||||||
|
|
||||||
return mail.send(fail_silently)
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
return False
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains constants used throughout the project
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
|
|
||||||
# GOOGLE_URL used for interact with google server to verify user existence.
|
|
||||||
#GOOGLE_URL = "https://www.googleapis.com/plus/v1/"
|
|
||||||
|
|
||||||
|
|
||||||
# Super Admin string constant for 'role'
|
|
||||||
SUPER_ADMIN = "Super Admin"
|
|
||||||
|
|
||||||
# Define jwt_token_expiration time in minutes for now token will expire after 3 days
|
|
||||||
JWT_TOKEN_EXPIRATION = 3 * 24 * 60
|
|
||||||
|
|
||||||
# Define common file extention
|
|
||||||
FILE_EXTENSION = ("gif", "jpeg", "jpg", "png", "svg")
|
|
||||||
|
|
||||||
# Define file size in bytes(5MB = 5 * 1024 * 1024)
|
|
||||||
FILE_SIZE = 5 * 1024 * 1024
|
|
||||||
|
|
||||||
# String constant for configurable date for allocation lock period
|
|
||||||
ALLOCATION_LOCK_DATE = 1
|
|
||||||
|
|
||||||
sort_dict = {
|
|
||||||
'1': 'name',
|
|
||||||
'2': '-name'
|
|
||||||
}
|
|
||||||
USER_TYPE = (
|
|
||||||
('1', 'junior'),
|
|
||||||
('2', 'guardian'),
|
|
||||||
('3', 'superuser')
|
|
||||||
)
|
|
||||||
GENDERS = (
|
|
||||||
('1', 'Male'),
|
|
||||||
('2', 'Female')
|
|
||||||
)
|
|
||||||
# duplicate name used defined in constant PROJECT_NAME
|
|
||||||
PROJECT_NAME = 'Zod Bank'
|
|
||||||
GUARDIAN = 'guardian'
|
|
||||||
JUNIOR = 'junior'
|
|
||||||
SUPERUSER = 'superuser'
|
|
||||||
# numbers used as a constant
|
|
||||||
|
|
||||||
# Define the byte into kb
|
|
||||||
BYTE_IMAGE_SIZE = 1024
|
|
||||||
|
|
||||||
# validate file size
|
|
||||||
MAX_FILE_SIZE = 1024 * 1024 * 5
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains constants used throughout the project
|
|
||||||
"""
|
|
||||||
from zod_bank.settings import BUCKET_NAME
|
|
||||||
|
|
||||||
# Define S3 folder url
|
|
||||||
S3_FOLDER_DIR = {
|
|
||||||
'user_image': 'user_image/',
|
|
||||||
}
|
|
||||||
|
|
||||||
# S3 bucket url
|
|
||||||
S3_URL = "https://"+BUCKET_NAME+".s3.amazonaws.com/"
|
|
||||||
|
|
||||||
S3_FOLDER_URL = {
|
|
||||||
'user_image_file': S3_URL+S3_FOLDER_DIR['user_image'],
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
"""
|
|
||||||
This module contains all the messages used all across the project
|
|
||||||
"""
|
|
||||||
|
|
||||||
ERROR_CODE_REQUIRED = {
|
|
||||||
# Error code for email address
|
|
||||||
"1000": ["Required email address not found."],
|
|
||||||
# Error code for password
|
|
||||||
"1001": ["Required password not found."],
|
|
||||||
# Error code for Required Post parameters
|
|
||||||
"1002": ["Required POST parameters not found."],
|
|
||||||
# Error code for Required Get parameters
|
|
||||||
"1003": ["Required GET parameters not found."],
|
|
||||||
# Error code for Required Headers
|
|
||||||
"1004": ["Required headers were not found."],
|
|
||||||
# Error code for Required Put parameters
|
|
||||||
"1005": ["Required PUT parameters not found."],
|
|
||||||
# Error code for Required query parameters
|
|
||||||
"1006": ["Required query parameters is not valid."],
|
|
||||||
# Error code for Required Head parameters
|
|
||||||
"1008": ["Required HEAD parameters not found."]
|
|
||||||
}
|
|
||||||
|
|
||||||
# Error code
|
|
||||||
ERROR_CODE = {
|
|
||||||
"2000": "Email not found.",
|
|
||||||
"2001": "Your account has not been verified. Please check your email and verify it.",
|
|
||||||
"2002": "Invalid login credentials.",
|
|
||||||
"2003": "An account already exists with this email address.",
|
|
||||||
"2004": "User not found.",
|
|
||||||
"2005": "Your account has been activated.",
|
|
||||||
"2006": "Your account is not activated.",
|
|
||||||
"2007": "Your account already activated.",
|
|
||||||
"2008": "Invalid OTP.",
|
|
||||||
"2009": "The user provided cannot be found or the reset password token has become invalid/timed out.",
|
|
||||||
"2010": "Invalid Link.",
|
|
||||||
"2011": "Your profile has not been completed yet.",
|
|
||||||
"2012": "Password and Confirm password should be same.",
|
|
||||||
"2013": "Invalid token.",
|
|
||||||
"2014": "Your old password doesn't match.",
|
|
||||||
"2015": "Invalid old password.",
|
|
||||||
"2016": "Invalid search.",
|
|
||||||
"2017": "{model} object with {pk} does not exist",
|
|
||||||
"2018": "Attached File not found",
|
|
||||||
"2019": "Either File extension or File size doesn't meet the requirements",
|
|
||||||
"2020": "Enter valid mobile number",
|
|
||||||
"2021": "Already register",
|
|
||||||
"2022":"Invalid Guardian code",
|
|
||||||
"2023":"Invalid user",
|
|
||||||
"2024":"Email not verified"
|
|
||||||
}
|
|
||||||
SUCCESS_CODE = {
|
|
||||||
# Success code for password
|
|
||||||
"3001": "Sign up successfully",
|
|
||||||
# Success code for Thank you
|
|
||||||
"3002": "Thank you for contacting us! Our Consumer Experience Team will reach out to you shortly.",
|
|
||||||
# Success code for account activation
|
|
||||||
"3003": "Log in successfully",
|
|
||||||
# Success code for password reset
|
|
||||||
"3004": "Password reset link has been sent to your email address",
|
|
||||||
# Success code for link verified
|
|
||||||
"3005": "Your link has been verified, it's valid",
|
|
||||||
# Success code for password reset
|
|
||||||
"3006": "Your password has been reset successfully.",
|
|
||||||
# Success code for password update
|
|
||||||
"3007": "Your password has been changed successfully.",
|
|
||||||
# Success code for valid link
|
|
||||||
"3008": "You have a valid link.",
|
|
||||||
# Success code for logged out
|
|
||||||
"3009": "You have successfully logged out!",
|
|
||||||
# Success code for check all fields
|
|
||||||
"3010": "All fields are valid",
|
|
||||||
"3011": "Email OTP Verified successfully",
|
|
||||||
"3012": "Phone OTP Verified successfully",
|
|
||||||
"3013": "Valid Guardian code",
|
|
||||||
"3014": "Password has been updated successfully.",
|
|
||||||
"3015": "Verification code sent on your email.",
|
|
||||||
"3016": "Send otp on your Email successfully"
|
|
||||||
}
|
|
||||||
|
|
||||||
STATUS_CODE_ERROR = {
|
|
||||||
# Status code for Invalid Input
|
|
||||||
"4001": ["Invalid input."],
|
|
||||||
# Status code for Authentication credentials
|
|
||||||
"4002": ["Authentication credentials were not provided."],
|
|
||||||
# Status code for Permission
|
|
||||||
"4003": ["You do not have permission to perform this action."],
|
|
||||||
# Status code for not found
|
|
||||||
"4004": ["Not found."],
|
|
||||||
# Status code for method not allowed
|
|
||||||
"4005": ["Method not allowed."]
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
"""
|
|
||||||
Custom routers for job sourcing .
|
|
||||||
"""
|
|
||||||
# third party imports
|
|
||||||
from rest_framework.routers import DefaultRouter
|
|
||||||
|
|
||||||
|
|
||||||
class OptionalSlashRouter(DefaultRouter):
|
|
||||||
"""
|
|
||||||
optional slash router class
|
|
||||||
"""
|
|
||||||
def __init__(self):
|
|
||||||
"""
|
|
||||||
explicitly appending '/' in urls if '/' doesn't exists for making common url patterns .
|
|
||||||
"""
|
|
||||||
super(OptionalSlashRouter, self).__init__()
|
|
||||||
self.trailing_slash = '/?'
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
"""
|
|
||||||
This file used for file uploaded
|
|
||||||
"""
|
|
||||||
import datetime
|
|
||||||
# python imports
|
|
||||||
import logging
|
|
||||||
import mimetypes
|
|
||||||
import os
|
|
||||||
|
|
||||||
import boto3
|
|
||||||
from django.core.files.storage import FileSystemStorage
|
|
||||||
# django imports
|
|
||||||
from django.utils.crypto import get_random_string
|
|
||||||
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK
|
|
||||||
|
|
||||||
from base import constants
|
|
||||||
from base.constants import NUMBER
|
|
||||||
# local import
|
|
||||||
from zod_bank.settings import base_settings as settings
|
|
||||||
from zod_bank.settings.base_settings import BASE_DIR
|
|
||||||
|
|
||||||
|
|
||||||
def image_upload(folder, file_name, data):
|
|
||||||
"""
|
|
||||||
Function to upload files
|
|
||||||
:param folder:folder location string
|
|
||||||
:param file_name:file_name without ext string
|
|
||||||
:param data:data file obj
|
|
||||||
:return:Dictionary
|
|
||||||
"""
|
|
||||||
status = HTTP_400_BAD_REQUEST
|
|
||||||
img_name = None
|
|
||||||
error = None
|
|
||||||
try:
|
|
||||||
s3_client = boto3.client('s3',
|
|
||||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
|
||||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
|
||||||
region_name=settings.AWS_DEFAULT_REGION
|
|
||||||
)
|
|
||||||
|
|
||||||
bucket_name = settings.BUCKET_NAME
|
|
||||||
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/tmp')
|
|
||||||
fss = FileSystemStorage()
|
|
||||||
file = fss.save('tmp/' + str(file_name), data)
|
|
||||||
fss.url(file)
|
|
||||||
tmp_file = os.path.join(MEDIA_ROOT, str(file_name))
|
|
||||||
s3_client.upload_file(
|
|
||||||
tmp_file, bucket_name, folder + str(file_name),
|
|
||||||
ExtraArgs={'ACL': 'public-read', 'ContentType': data.content_type}
|
|
||||||
)
|
|
||||||
os.unlink(tmp_file)
|
|
||||||
img_name = file_name
|
|
||||||
status = HTTP_200_OK
|
|
||||||
except Exception as e:
|
|
||||||
error = e
|
|
||||||
logging.error(e)
|
|
||||||
return status, error, img_name
|
|
||||||
|
|
||||||
|
|
||||||
def file_delete(folder, file_name):
|
|
||||||
"""
|
|
||||||
To delete common file
|
|
||||||
:param folder: folder name str
|
|
||||||
:param file_name: file_name string type
|
|
||||||
"""
|
|
||||||
status = HTTP_400_BAD_REQUEST
|
|
||||||
error = None
|
|
||||||
try:
|
|
||||||
s3_client = boto3.client('s3',
|
|
||||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
|
||||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
|
||||||
region_name=settings.AWS_DEFAULT_REGION
|
|
||||||
)
|
|
||||||
|
|
||||||
s3_client.delete_object(Bucket=settings.BUCKET_NAME, Key=str(folder) + str(file_name))
|
|
||||||
status = HTTP_200_OK
|
|
||||||
except Exception as e:
|
|
||||||
error = e
|
|
||||||
return status, error
|
|
||||||
|
|
||||||
|
|
||||||
def get_aws_obj(folder, file_name):
|
|
||||||
"""
|
|
||||||
To get aws file obj
|
|
||||||
:param folder: folder string type
|
|
||||||
:param file_name: file_name string type
|
|
||||||
"""
|
|
||||||
status = HTTP_400_BAD_REQUEST
|
|
||||||
obj = None
|
|
||||||
try:
|
|
||||||
s3_client = boto3.client('s3',
|
|
||||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
|
||||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
|
||||||
region_name=settings.AWS_DEFAULT_REGION
|
|
||||||
)
|
|
||||||
file_name = folder + file_name
|
|
||||||
obj = s3_client.get_object(Bucket=settings.BUCKET_NAME, Key=file_name)
|
|
||||||
status = HTTP_200_OK
|
|
||||||
except Exception as e:
|
|
||||||
logging.error(e)
|
|
||||||
return status, obj
|
|
||||||
|
|
||||||
|
|
||||||
def upload_image(post_data, folder):
|
|
||||||
"""
|
|
||||||
:param post_data:
|
|
||||||
:param folder: string type
|
|
||||||
:return:
|
|
||||||
"""
|
|
||||||
upload_obj = None
|
|
||||||
# Check Post data
|
|
||||||
if post_data:
|
|
||||||
date_now = datetime.datetime.now()
|
|
||||||
file_extension = os.path.splitext(str(post_data.name))
|
|
||||||
file_extension = file_extension[constants.NUMBER['one']].split(".")[constants.NUMBER['one']].lower()
|
|
||||||
rand = get_random_string(NUMBER['twelve'])
|
|
||||||
image_name = str(rand) + date_now.strftime("%s") + "." + file_extension
|
|
||||||
upload_obj = image_upload(folder, image_name, post_data)
|
|
||||||
return upload_obj
|
|
||||||
|
|
||||||
|
|
||||||
def upload_voice_kit_image(post_data, folder, image_dir):
|
|
||||||
"""
|
|
||||||
:param post_data:
|
|
||||||
:param folder: string type
|
|
||||||
:param image_dir: image_dir
|
|
||||||
:return:
|
|
||||||
"""
|
|
||||||
upload_obj = None
|
|
||||||
# Check Post data
|
|
||||||
if post_data:
|
|
||||||
date_now = datetime.datetime.now()
|
|
||||||
file_extension = os.path.splitext(str(post_data))
|
|
||||||
file_extension = file_extension[constants.NUMBER['one']].split(".")[constants.NUMBER['one']].lower()
|
|
||||||
rand = get_random_string(NUMBER['twelve'])
|
|
||||||
image_name = str(rand) + date_now.strftime("%s") + "." + file_extension
|
|
||||||
upload_obj = voice_kit_image_upload(folder, image_name, post_data, image_dir)
|
|
||||||
return upload_obj
|
|
||||||
|
|
||||||
|
|
||||||
def voice_kit_image_upload(folder, file_name, data, image_dir):
|
|
||||||
"""
|
|
||||||
Function to upload files
|
|
||||||
:param folder:folder location string
|
|
||||||
:param file_name:file_name without ext string
|
|
||||||
:param data:data file obj
|
|
||||||
:return:Dictionary
|
|
||||||
"""
|
|
||||||
status = HTTP_400_BAD_REQUEST
|
|
||||||
img_name = None
|
|
||||||
error = None
|
|
||||||
try:
|
|
||||||
s3_client = boto3.client('s3',
|
|
||||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
|
||||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
|
||||||
region_name=settings.AWS_DEFAULT_REGION
|
|
||||||
)
|
|
||||||
|
|
||||||
bucket_name = settings.BUCKET_NAME
|
|
||||||
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/tmp')
|
|
||||||
fss = FileSystemStorage()
|
|
||||||
with open(image_dir+data, 'rb') as f:
|
|
||||||
file = fss.save('tmp/' + str(file_name), f)
|
|
||||||
fss.url(file)
|
|
||||||
tmp_file = os.path.join(MEDIA_ROOT, str(file_name))
|
|
||||||
s3_client.upload_file(
|
|
||||||
tmp_file, bucket_name, folder + str(file_name),
|
|
||||||
ExtraArgs={'ACL': 'public-read', 'ContentType': mimetypes.guess_type(file_name)[0]}
|
|
||||||
)
|
|
||||||
os.unlink(tmp_file)
|
|
||||||
img_name = file_name
|
|
||||||
status = HTTP_200_OK
|
|
||||||
except Exception as e:
|
|
||||||
error = e
|
|
||||||
logging.error(e)
|
|
||||||
return status, error, img_name
|
|
||||||
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# 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?
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# 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,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
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 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!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>
|
||||||
Generated
+4115
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<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>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,42 @@
|
|||||||
|
#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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
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;
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
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`),
|
||||||
|
};
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<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>
|
||||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,69 @@
|
|||||||
|
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 */
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
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>;
|
||||||
|
};
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export enum GrantType {
|
||||||
|
PASSWORD = 'PASSWORD',
|
||||||
|
APPLE = 'APPLE',
|
||||||
|
GOOGLE = 'GOOGLE',
|
||||||
|
BIOMETRIC = 'BIOMETRIC',
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from './grantType.enum';
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
@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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
interface ApiErrorField {
|
||||||
|
field: string;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiError {
|
||||||
|
statusCode: number;
|
||||||
|
message: string | ApiErrorField[];
|
||||||
|
error: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiResponse<T> {
|
||||||
|
data: T;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
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'
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
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;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
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';
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"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"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"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"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
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,18 +0,0 @@
|
|||||||
version: '3'
|
|
||||||
services:
|
|
||||||
nginx:
|
|
||||||
image: nginx:latest
|
|
||||||
container_name: nginx
|
|
||||||
ports:
|
|
||||||
- "8000:8000"
|
|
||||||
volumes:
|
|
||||||
- ./nginx:/etc/nginx/conf.d
|
|
||||||
- .:/usr/src/app
|
|
||||||
depends_on:
|
|
||||||
- web
|
|
||||||
web:
|
|
||||||
build: .
|
|
||||||
container_name: django
|
|
||||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
|
||||||
volumes:
|
|
||||||
- .:/usr/src/app
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
"""Guardian admin"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.contrib import admin
|
|
||||||
"""Import Django app"""
|
|
||||||
from .models import Guardian
|
|
||||||
# Register your models here.
|
|
||||||
@admin.register(Guardian)
|
|
||||||
class GuardianAdmin(admin.ModelAdmin):
|
|
||||||
"""Junior Admin"""
|
|
||||||
list_display = ['user', 'family_name']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return email id"""
|
|
||||||
return self.user__email
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
"""Guardian app file"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.apps import AppConfig
|
|
||||||
|
|
||||||
|
|
||||||
class CustodianConfig(AppConfig):
|
|
||||||
"""Guardian config"""
|
|
||||||
default_auto_field = 'django.db.models.BigAutoField'
|
|
||||||
name = 'guardian'
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
import django.contrib.postgres.fields
|
|
||||||
from django.db import migrations, models
|
|
||||||
import django.db.models.deletion
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
initial = True
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='Guardian',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('country_code', models.IntegerField(blank=True, null=True)),
|
|
||||||
('phone', models.CharField(blank=True, default=None, max_length=31, null=True)),
|
|
||||||
('family_name', models.CharField(blank=True, default=None, max_length=50, null=True)),
|
|
||||||
('gender', models.CharField(blank=True, choices=[('1', 'Male'), ('2', 'Female')], default=None, max_length=15, null=True)),
|
|
||||||
('dob', models.DateField(blank=True, default=None, max_length=15, null=True)),
|
|
||||||
('guardian_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('junior_code', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, default=None, max_length=10, null=True), null=True, size=None)),
|
|
||||||
('referral_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('referral_code_used', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('is_active', models.BooleanField(default=True)),
|
|
||||||
('is_complete_profile', models.BooleanField(default=False)),
|
|
||||||
('passcode', models.IntegerField(blank=True, default=None, null=True)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='guardian_profile', to=settings.AUTH_USER_MODEL, verbose_name='Email')),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'verbose_name': 'Guardian',
|
|
||||||
'db_table': 'guardians',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-27 06:15
|
|
||||||
|
|
||||||
from django.db import migrations
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('guardian', '0001_initial'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.RemoveField(
|
|
||||||
model_name='guardian',
|
|
||||||
name='junior_code',
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
"""Guardian model file"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.auth import get_user_model
|
|
||||||
"""Import Django app"""
|
|
||||||
from base.constants import GENDERS
|
|
||||||
User = get_user_model()
|
|
||||||
# Create your models here.
|
|
||||||
|
|
||||||
class Guardian(models.Model):
|
|
||||||
"""Guardian model"""
|
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='guardian_profile', verbose_name='Email')
|
|
||||||
"""Contact details"""
|
|
||||||
country_code = models.IntegerField(blank=True, null=True)
|
|
||||||
phone = models.CharField(max_length=31, null=True, blank=True, default=None)
|
|
||||||
"""Personal info"""
|
|
||||||
family_name = models.CharField(max_length=50, null=True, blank=True, default=None)
|
|
||||||
gender = models.CharField(choices=GENDERS, max_length=15, null=True, blank=True, default=None)
|
|
||||||
dob = models.DateField(max_length=15, null=True, blank=True, default=None)
|
|
||||||
"""Codes"""
|
|
||||||
guardian_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
referral_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
referral_code_used = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
"""Profile activity"""
|
|
||||||
is_active = models.BooleanField(default=True)
|
|
||||||
is_complete_profile = models.BooleanField(default=False)
|
|
||||||
passcode = models.IntegerField(null=True, blank=True, default=None)
|
|
||||||
"""Profile created and updated time"""
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta class """
|
|
||||||
db_table = 'guardians'
|
|
||||||
verbose_name = 'Guardian'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return email id"""
|
|
||||||
return f'{self.user}'
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
"""Serializer of Guardian"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
import logging
|
|
||||||
import random
|
|
||||||
from rest_framework import serializers
|
|
||||||
from rest_framework_simplejwt.tokens import RefreshToken
|
|
||||||
from django.db import transaction
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
"""Import Django app"""
|
|
||||||
from .models import Guardian
|
|
||||||
from account.models import UserProfile
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
class UserSerializer(serializers.ModelSerializer):
|
|
||||||
"""User serializer"""
|
|
||||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = User
|
|
||||||
fields = ['email', 'password', 'auth_token']
|
|
||||||
|
|
||||||
def get_auth_token(self, obj):
|
|
||||||
"""generate auth token"""
|
|
||||||
refresh = RefreshToken.for_user(obj)
|
|
||||||
access_token = str(refresh.access_token)
|
|
||||||
return access_token
|
|
||||||
def create(self, validated_data):
|
|
||||||
"""fetch data"""
|
|
||||||
email = validated_data.get('email')
|
|
||||||
user_type = self.context
|
|
||||||
password = validated_data.get('password')
|
|
||||||
try:
|
|
||||||
"""Create user profile"""
|
|
||||||
user = User.objects.create_user(username=email, email=email, password=password)
|
|
||||||
UserProfile.objects.create(user=user, user_type=user_type)
|
|
||||||
return user
|
|
||||||
except Exception as e:
|
|
||||||
"""Error handling"""
|
|
||||||
logging.error(e)
|
|
||||||
raise serializers.ValidationError({"details":ERROR_CODE['2021']})
|
|
||||||
|
|
||||||
def save(self, **kwargs):
|
|
||||||
"""save the data"""
|
|
||||||
with transaction.atomic():
|
|
||||||
instance = super().save(**kwargs)
|
|
||||||
return instance
|
|
||||||
|
|
||||||
class CreateGuardianSerializer(serializers.ModelSerializer):
|
|
||||||
"""Create guardian serializer"""
|
|
||||||
"""Basic info"""
|
|
||||||
first_name = serializers.SerializerMethodField('get_first_name')
|
|
||||||
last_name = serializers.SerializerMethodField('get_last_name')
|
|
||||||
email = serializers.SerializerMethodField('get_email')
|
|
||||||
"""Contact details"""
|
|
||||||
phone = serializers.CharField(max_length=20, required=False)
|
|
||||||
country_code = serializers.IntegerField(required=False)
|
|
||||||
family_name = serializers.CharField(max_length=100, required=False)
|
|
||||||
dob = serializers.DateField(required=False)
|
|
||||||
referral_code = serializers.CharField(max_length=100, required=False)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Guardian
|
|
||||||
fields = ['first_name', 'last_name', 'email', 'phone', 'family_name', 'gender', 'country_code',
|
|
||||||
'dob', 'referral_code', 'passcode', 'is_complete_profile']
|
|
||||||
|
|
||||||
def get_first_name(self,obj):
|
|
||||||
"""first name of guardian"""
|
|
||||||
return obj.user.first_name
|
|
||||||
|
|
||||||
def get_last_name(self,obj):
|
|
||||||
"""last name of guardian"""
|
|
||||||
return obj.user.last_name
|
|
||||||
|
|
||||||
def get_email(self,obj):
|
|
||||||
"""emailof guardian"""
|
|
||||||
return obj.user.email
|
|
||||||
|
|
||||||
def create(self, validated_data):
|
|
||||||
"""Create guardian profile"""
|
|
||||||
user = User.objects.filter(username=self.context['user']).last()
|
|
||||||
if user:
|
|
||||||
"""Save first and last name of guardian"""
|
|
||||||
user.first_name = self.context.get('first_name', user.first_name)
|
|
||||||
user.last_name = self.context.get('last_name', user.last_name)
|
|
||||||
user.save()
|
|
||||||
"""Create guardian data"""
|
|
||||||
guardian, created = Guardian.objects.get_or_create(user=self.context['user'])
|
|
||||||
if created:
|
|
||||||
"""Create referral code and guardian code"""
|
|
||||||
guardian.referral_code = ''.join([str(random.randrange(9)) for _ in range(4)])
|
|
||||||
guardian.guardian_code = ''.join([str(random.randrange(9)) for _ in range(4)])
|
|
||||||
if guardian:
|
|
||||||
"""update details according to the data get from request"""
|
|
||||||
guardian.gender = validated_data.get('gender',guardian.gender)
|
|
||||||
guardian.family_name = validated_data.get('family_name', guardian.family_name)
|
|
||||||
guardian.dob = validated_data.get('dob',guardian.dob)
|
|
||||||
"""Update country code and phone number"""
|
|
||||||
guardian.phone = validated_data.get('phone', guardian.phone)
|
|
||||||
guardian.country_code = validated_data.get('country_code', guardian.country_code)
|
|
||||||
guardian.passcode = validated_data.get('passcode', guardian.passcode)
|
|
||||||
guardian.referral_code_used = validated_data.get('referral_code_used', guardian.referral_code_used)
|
|
||||||
"""Complete profile of the junior if below all data are filled"""
|
|
||||||
complete_profile_field = all([guardian.phone, guardian.gender, guardian.family_name,
|
|
||||||
guardian.dob, guardian.country_code, user.first_name, user.last_name])
|
|
||||||
guardian.is_complete_profile = False
|
|
||||||
if complete_profile_field:
|
|
||||||
guardian.is_complete_profile = True
|
|
||||||
guardian.save()
|
|
||||||
return guardian
|
|
||||||
|
|
||||||
def save(self, **kwargs):
|
|
||||||
"""Save the data into junior table"""
|
|
||||||
with transaction.atomic():
|
|
||||||
instance = super().save(**kwargs)
|
|
||||||
return instance
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
"""task files"""
|
|
||||||
"""Django import"""
|
|
||||||
import random
|
|
||||||
def generate_otp():
|
|
||||||
"""generate random otp"""
|
|
||||||
return ''.join([str(random.randrange(9)) for _ in range(6)])
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
"""Test file of Guardian"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
# Create your tests here.
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
""" Urls files"""
|
|
||||||
"""Django import"""
|
|
||||||
from django.urls import path, include
|
|
||||||
from .views import SignupViewset, UpdateGuardianProfile
|
|
||||||
"""Third party import"""
|
|
||||||
from rest_framework import routers
|
|
||||||
|
|
||||||
"""Define Router"""
|
|
||||||
router = routers.SimpleRouter()
|
|
||||||
|
|
||||||
"""API End points with router"""
|
|
||||||
"""Sign up API"""
|
|
||||||
router.register('sign-up', SignupViewset, basename='sign-up')
|
|
||||||
"""Create guardian profile API"""
|
|
||||||
router.register('create-guardian-profile', UpdateGuardianProfile, basename='update-guardian-profile')
|
|
||||||
"""Define Url pattern"""
|
|
||||||
urlpatterns = [
|
|
||||||
path('api/v1/', include(router.urls)),
|
|
||||||
]
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
"""Views of Guardian"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from rest_framework.permissions import IsAuthenticated
|
|
||||||
from rest_framework import viewsets, status
|
|
||||||
"""Import Django app"""
|
|
||||||
from .serializers import UserSerializer
|
|
||||||
from .serializers import CreateGuardianSerializer
|
|
||||||
from account.models import UserEmailOtp
|
|
||||||
from .tasks import generate_otp
|
|
||||||
from account.utils import send_otp_email
|
|
||||||
from account.utils import custom_response, custom_error_response
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
# Create your views here.
|
|
||||||
class SignupViewset(viewsets.ModelViewSet):
|
|
||||||
"""Signup view set"""
|
|
||||||
serializer_class = UserSerializer
|
|
||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
"""Create user profile"""
|
|
||||||
serializer = UserSerializer(context=request.data['user_type'], data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
serializer.save()
|
|
||||||
"""Generate otp"""
|
|
||||||
otp = generate_otp()
|
|
||||||
UserEmailOtp.objects.create(email=request.data['email'], otp=otp)
|
|
||||||
"""Send email to the register user"""
|
|
||||||
send_otp_email(request.data['email'], otp)
|
|
||||||
return custom_response(SUCCESS_CODE['3001'], {"email_otp": otp},
|
|
||||||
response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class UpdateGuardianProfile(viewsets.ViewSet):
|
|
||||||
"""Update guardian profile"""
|
|
||||||
serializer_class = CreateGuardianSerializer
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
"""Create guardian profile"""
|
|
||||||
serializer = CreateGuardianSerializer(context={"user":request.user,
|
|
||||||
"first_name":request.data.get('first_name', ''),
|
|
||||||
"last_name": request.data.get('last_name',' ')},
|
|
||||||
data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
"""save serializer"""
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(None, serializer.data,response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import type { Config as JestConfig } from 'jest';
|
||||||
|
import { pathsToModuleNameMapper } from 'ts-jest';
|
||||||
|
import { compilerOptions as tsConfigCompilerOptions } from './tsconfig.json';
|
||||||
|
|
||||||
|
type ArrayElement<A> = A extends readonly (infer T)[] ? T : never;
|
||||||
|
type JestProjectConfig = Exclude<ArrayElement<JestConfig['projects']>, string>;
|
||||||
|
|
||||||
|
const baseJestConfig: JestConfig = {
|
||||||
|
// ...
|
||||||
|
};
|
||||||
|
const baseJestProjectConfig: JestProjectConfig = {
|
||||||
|
testEnvironment: 'node',
|
||||||
|
transform: {
|
||||||
|
'^.+\\.(t|j)s$': 'ts-jest',
|
||||||
|
},
|
||||||
|
moduleNameMapper: pathsToModuleNameMapper(tsConfigCompilerOptions.paths, { prefix: '<rootDir>' }),
|
||||||
|
globalSetup: '<rootDir>/test/global-setup.ts',
|
||||||
|
};
|
||||||
|
const projects: { name?: string; rootDir: string }[] = [{ rootDir: '.' }];
|
||||||
|
|
||||||
|
export function buildJestConfig(config?: {
|
||||||
|
jestConfigs?: JestConfig;
|
||||||
|
jestProjectConfigs?: JestProjectConfig;
|
||||||
|
}): JestConfig {
|
||||||
|
return {
|
||||||
|
...baseJestConfig,
|
||||||
|
...config?.jestConfigs,
|
||||||
|
projects: projects.map(({ name, rootDir }) => ({
|
||||||
|
...baseJestProjectConfig,
|
||||||
|
...config?.jestProjectConfigs,
|
||||||
|
...(name && { displayName: name }),
|
||||||
|
rootDir,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import type { Config } from 'jest';
|
||||||
|
import { buildJestConfig } from './jest.base.config';
|
||||||
|
|
||||||
|
const config: Config = buildJestConfig({
|
||||||
|
jestProjectConfigs: {
|
||||||
|
testRegex: '.*\\.spec\\.ts$',
|
||||||
|
coveragePathIgnorePatterns: ['__testing__', 'entities', '<rootDir>/src/db', 'index.ts'],
|
||||||
|
},
|
||||||
|
jestConfigs: {
|
||||||
|
coverageDirectory: 'coverage',
|
||||||
|
collectCoverageFrom: ['<rootDir>/src/**/*.(t|j)s'],
|
||||||
|
coverageReporters: ['clover', 'json', 'lcov', 'text', 'text-summary', 'cobertura'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default config;
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
"""Junior admin"""
|
|
||||||
"""Third party Django app"""
|
|
||||||
from django.contrib import admin
|
|
||||||
"""Import Django app"""
|
|
||||||
from .models import Junior
|
|
||||||
# Register your models here.
|
|
||||||
@admin.register(Junior)
|
|
||||||
class JuniorAdmin(admin.ModelAdmin):
|
|
||||||
"""Junior Admin"""
|
|
||||||
list_display = ['auth']
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return email id"""
|
|
||||||
return self.auth__email
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
"""App file"""
|
|
||||||
"""Import AppConfig"""
|
|
||||||
from django.apps import AppConfig
|
|
||||||
|
|
||||||
class JuniorConfig(AppConfig):
|
|
||||||
"""Junior config"""
|
|
||||||
default_auto_field = 'django.db.models.BigAutoField'
|
|
||||||
name = 'junior'
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
import django.contrib.postgres.fields
|
|
||||||
from django.db import migrations, models
|
|
||||||
import django.db.models.deletion
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
initial = True
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='Junior',
|
|
||||||
fields=[
|
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
||||||
('phone', models.CharField(blank=True, default=None, max_length=31, null=True)),
|
|
||||||
('country_code', models.IntegerField(blank=True, null=True)),
|
|
||||||
('gender', models.CharField(blank=True, choices=[('1', 'Male'), ('2', 'Female')], default=None, max_length=10, null=True)),
|
|
||||||
('dob', models.DateField(blank=True, default=None, max_length=15, null=True)),
|
|
||||||
('junior_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('guardian_code', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, default=None, max_length=10, null=True), null=True, size=None)),
|
|
||||||
('referral_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('referral_code_used', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
|
||||||
('is_active', models.BooleanField(default=True)),
|
|
||||||
('is_complete_profile', models.BooleanField(default=False)),
|
|
||||||
('passcode', models.IntegerField(blank=True, default=None, null=True)),
|
|
||||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
||||||
('updated_at', models.DateTimeField(auto_now=True)),
|
|
||||||
('auth', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='junior_profile', to=settings.AUTH_USER_MODEL, verbose_name='Email')),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'verbose_name': 'Junior',
|
|
||||||
'db_table': 'junior',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
"""Junior model """
|
|
||||||
"""Import django"""
|
|
||||||
from django.db import models
|
|
||||||
from django.contrib.auth import get_user_model
|
|
||||||
from django.contrib.postgres.fields import ArrayField
|
|
||||||
"""Import django app"""
|
|
||||||
from base.constants import GENDERS
|
|
||||||
User = get_user_model()
|
|
||||||
# Create your models here.
|
|
||||||
|
|
||||||
class Junior(models.Model):
|
|
||||||
"""Junior model"""
|
|
||||||
auth = models.ForeignKey(User, on_delete=models.CASCADE, related_name='junior_profile', verbose_name='Email')
|
|
||||||
"""Contact details"""
|
|
||||||
phone = models.CharField(max_length=31, null=True, blank=True, default=None)
|
|
||||||
country_code = models.IntegerField(blank=True, null=True)
|
|
||||||
"""Personal info"""
|
|
||||||
gender = models.CharField(max_length=10, choices=GENDERS, null=True, blank=True, default=None)
|
|
||||||
dob = models.DateField(max_length=15, null=True, blank=True, default=None)
|
|
||||||
# image = models.ImageField(upload_to='images/')
|
|
||||||
"""Codes"""
|
|
||||||
junior_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
guardian_code = ArrayField(models.CharField(max_length=10, null=True, blank=True, default=None),null=True)
|
|
||||||
referral_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
referral_code_used = models.CharField(max_length=10, null=True, blank=True, default=None)
|
|
||||||
"""Profile activity"""
|
|
||||||
is_active = models.BooleanField(default=True)
|
|
||||||
is_complete_profile = models.BooleanField(default=False)
|
|
||||||
passcode = models.IntegerField(null=True, blank=True, default=None)
|
|
||||||
"""Profile created and updated time"""
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
""" Meta class """
|
|
||||||
db_table = 'junior'
|
|
||||||
verbose_name = 'Junior'
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
"""Return email id"""
|
|
||||||
return f'{self.auth}'
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
"""Serializer file for junior"""
|
|
||||||
"""Import Django 3rd party app"""
|
|
||||||
from rest_framework import serializers
|
|
||||||
from django.contrib.auth.models import User
|
|
||||||
from django.db import transaction
|
|
||||||
import random
|
|
||||||
"""Import django app"""
|
|
||||||
from junior.models import Junior
|
|
||||||
|
|
||||||
class ListCharField(serializers.ListField):
|
|
||||||
"""Serializer for Array field"""
|
|
||||||
child = serializers.CharField()
|
|
||||||
|
|
||||||
def to_representation(self, data):
|
|
||||||
"""to represent the data"""
|
|
||||||
return data
|
|
||||||
|
|
||||||
def to_internal_value(self, data):
|
|
||||||
"""internal value"""
|
|
||||||
if isinstance(data, list):
|
|
||||||
return data
|
|
||||||
raise serializers.ValidationError({"details":"Invalid input. Expected a list of strings."})
|
|
||||||
|
|
||||||
|
|
||||||
class CreateJuniorSerializer(serializers.ModelSerializer):
|
|
||||||
"""Create junior serializer"""
|
|
||||||
first_name = serializers.SerializerMethodField('get_first_name')
|
|
||||||
last_name = serializers.SerializerMethodField('get_last_name')
|
|
||||||
email = serializers.SerializerMethodField('get_email')
|
|
||||||
phone = serializers.CharField(max_length=20, required=False)
|
|
||||||
country_code = serializers.IntegerField(required=False)
|
|
||||||
dob = serializers.DateField(required=False)
|
|
||||||
referral_code = serializers.CharField(max_length=100, required=False)
|
|
||||||
guardian_code = ListCharField(required=False)
|
|
||||||
|
|
||||||
class Meta(object):
|
|
||||||
"""Meta info"""
|
|
||||||
model = Junior
|
|
||||||
fields = ['first_name', 'last_name', 'email', 'phone', 'gender', 'country_code', 'dob', 'referral_code',
|
|
||||||
'passcode', 'is_complete_profile', 'guardian_code']
|
|
||||||
|
|
||||||
def get_first_name(self,obj):
|
|
||||||
"""first name of junior"""
|
|
||||||
return obj.auth.first_name
|
|
||||||
|
|
||||||
def get_last_name(self,obj):
|
|
||||||
"""last name of junior"""
|
|
||||||
return obj.auth.last_name
|
|
||||||
|
|
||||||
def get_email(self,obj):
|
|
||||||
"""email of junior"""
|
|
||||||
return obj.auth.email
|
|
||||||
|
|
||||||
def create(self, validated_data):
|
|
||||||
"""Create junior profile"""
|
|
||||||
user = User.objects.filter(username=self.context['user']).last()
|
|
||||||
if user:
|
|
||||||
"""Save first and last name of junior"""
|
|
||||||
user.first_name = self.context.get('first_name', user.first_name)
|
|
||||||
user.last_name = self.context.get('last_name', user.last_name)
|
|
||||||
user.save()
|
|
||||||
"""Create junior data"""
|
|
||||||
junior, created = Junior.objects.get_or_create(auth=self.context['user'])
|
|
||||||
if created:
|
|
||||||
"""Create referral code and junior code"""
|
|
||||||
junior.referral_code = ''.join([str(random.randrange(9)) for _ in range(4)])
|
|
||||||
junior.junior_code = ''.join([str(random.randrange(9)) for _ in range(4)])
|
|
||||||
if junior:
|
|
||||||
"""update details according to the data get from request"""
|
|
||||||
junior.gender = validated_data.get('gender',junior.gender)
|
|
||||||
"""Update guardian code"""
|
|
||||||
junior.guardian_code = validated_data.get('guardian_code', junior.guardian_code)
|
|
||||||
junior.dob = validated_data.get('dob',junior.dob)
|
|
||||||
junior.passcode = validated_data.get('passcode', junior.passcode)
|
|
||||||
"""Update country code and phone number"""
|
|
||||||
junior.phone = validated_data.get('phone', junior.phone)
|
|
||||||
junior.country_code = validated_data.get('country_code', junior.country_code)
|
|
||||||
junior.referral_code_used = validated_data.get('referral_code_used', junior.referral_code_used)
|
|
||||||
"""Complete profile of the junior if below all data are filled"""
|
|
||||||
complete_profile_field = all([junior.phone, junior.gender, junior.family_name,
|
|
||||||
junior.dob, junior.country_code, user.first_name, user.last_name])
|
|
||||||
junior.is_complete_profile = False
|
|
||||||
if complete_profile_field:
|
|
||||||
junior.is_complete_profile = True
|
|
||||||
junior.save()
|
|
||||||
return junior
|
|
||||||
|
|
||||||
def save(self, **kwargs):
|
|
||||||
"""Save the data into junior table"""
|
|
||||||
with transaction.atomic():
|
|
||||||
instance = super().save(**kwargs)
|
|
||||||
return instance
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
"""Junior test file"""
|
|
||||||
"""Import TestCase"""
|
|
||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
# Create your tests here.
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
""" Urls files"""
|
|
||||||
"""Django import"""
|
|
||||||
from django.urls import path, include
|
|
||||||
from .views import UpdateJuniorProfile, ValidateGuardianCode
|
|
||||||
"""Third party import"""
|
|
||||||
from rest_framework import routers
|
|
||||||
|
|
||||||
"""Router"""
|
|
||||||
router = routers.SimpleRouter()
|
|
||||||
|
|
||||||
"""API End points with router"""
|
|
||||||
"""Create junior profile API"""
|
|
||||||
router.register('create-junior-profile', UpdateJuniorProfile, basename='profile-update')
|
|
||||||
"""validate guardian code API"""
|
|
||||||
router.register('validate-guardian-code', ValidateGuardianCode, basename='validate-guardian-code')
|
|
||||||
"""Define url pattern"""
|
|
||||||
urlpatterns = [
|
|
||||||
path('api/v1/', include(router.urls)),
|
|
||||||
]
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
"""Junior view file"""
|
|
||||||
from rest_framework import viewsets, status
|
|
||||||
from rest_framework.permissions import IsAuthenticated
|
|
||||||
"""Django app import"""
|
|
||||||
from junior.models import Junior
|
|
||||||
from .serializers import CreateJuniorSerializer
|
|
||||||
from guardian.models import Guardian
|
|
||||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
|
||||||
from account.utils import custom_response, custom_error_response
|
|
||||||
# Create your views here.
|
|
||||||
class UpdateJuniorProfile(viewsets.ViewSet):
|
|
||||||
"""Update junior profile"""
|
|
||||||
serializer_class = CreateJuniorSerializer
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
|
|
||||||
def create(self, request, *args, **kwargs):
|
|
||||||
"""Use CreateJuniorSerializer"""
|
|
||||||
serializer = CreateJuniorSerializer(context={"user":request.user,
|
|
||||||
"first_name":request.data.get('first_name', ''),
|
|
||||||
"last_name": request.data.get('last_name',' ')},
|
|
||||||
data=request.data)
|
|
||||||
if serializer.is_valid():
|
|
||||||
"""save serializer"""
|
|
||||||
serializer.save()
|
|
||||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
|
||||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
class ValidateGuardianCode(viewsets.ViewSet):
|
|
||||||
"""Check guardian code exist or not"""
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
|
|
||||||
def list(self, request, *args, **kwargs):
|
|
||||||
"""check guardian code"""
|
|
||||||
guardian_code = self.request.GET.get('guardian_code').split(',')
|
|
||||||
for code in guardian_code:
|
|
||||||
guardian_data = Guardian.objects.filter(guardian_code=code).exists()
|
|
||||||
if guardian_data:
|
|
||||||
return custom_response(SUCCESS_CODE['3013'], response_status=status.HTTP_200_OK)
|
|
||||||
else:
|
|
||||||
return custom_error_response(ERROR_CODE["2022"], response_status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
"""Django's command-line utility for administrative tasks."""
|
|
||||||
"""Django import"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
"""Main function"""
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zod_bank.settings')
|
|
||||||
try:
|
|
||||||
"""Import execute from command line function"""
|
|
||||||
from django.core.management import execute_from_command_line
|
|
||||||
except ImportError as exc:
|
|
||||||
"""Show Exception error"""
|
|
||||||
raise ImportError(
|
|
||||||
"Couldn't import Django. Are you sure it's installed and "
|
|
||||||
"available on your PYTHONPATH environment variable? Did you "
|
|
||||||
"forget to activate a virtual environment?"
|
|
||||||
) from exc
|
|
||||||
execute_from_command_line(sys.argv)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true,
|
||||||
|
"watchAssets": true,
|
||||||
|
"assets": [
|
||||||
|
{
|
||||||
|
"include": "config",
|
||||||
|
"exclude": "**/*.md"
|
||||||
|
},
|
||||||
|
{ "include": "common/modules/**/templates/*", "watchAssets": true }
|
||||||
|
,
|
||||||
|
"i18n",
|
||||||
|
"files"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
upstream web {
|
|
||||||
ip_hash;
|
|
||||||
server web:8000;
|
|
||||||
}
|
|
||||||
|
|
||||||
# portal
|
|
||||||
server {
|
|
||||||
location / {
|
|
||||||
proxy_pass http://web/;
|
|
||||||
proxy_set_header Host $http_host;
|
|
||||||
}
|
|
||||||
listen 8000;
|
|
||||||
client_max_body_size 512M;
|
|
||||||
server_name localhost;
|
|
||||||
proxy_read_timeout 900;
|
|
||||||
proxy_connect_timeout 900;
|
|
||||||
proxy_send_timeout 900;
|
|
||||||
#proxy_set_header Host $http_host;
|
|
||||||
|
|
||||||
location /static {
|
|
||||||
autoindex on;
|
|
||||||
alias /usr/src/app/zod_bank/static/;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Generated
+18084
File diff suppressed because it is too large
Load Diff
+123
@@ -0,0 +1,123 @@
|
|||||||
|
{
|
||||||
|
"name": "test",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"author": "",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:cov": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||||
|
"typeorm:cli": "./node_modules/.bin/ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
|
||||||
|
"typeorm:cli-d": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm -d typeorm.cli.ts",
|
||||||
|
"migration:generate": "npm run typeorm:cli-d migration:generate",
|
||||||
|
"migration:create": "npm run typeorm:cli migration:create",
|
||||||
|
"migration:up": "npm run typeorm:cli-d migration:run",
|
||||||
|
"migration:down": "npm run typeorm:cli-d migration:revert",
|
||||||
|
"seed": "TS_NODE_PROJECT=tsconfig.json ts-node -r tsconfig-paths/register src/scripts/seed.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@abdalhamid/hello": "^2.0.0",
|
||||||
|
"@hamid/hello": "file:../libraries/test-package",
|
||||||
|
"@keyv/redis": "^4.0.2",
|
||||||
|
"@nestjs-modules/mailer": "^2.0.2",
|
||||||
|
"@nestjs/axios": "^3.1.2",
|
||||||
|
"@nestjs/common": "^10.0.0",
|
||||||
|
"@nestjs/config": "^3.3.0",
|
||||||
|
"@nestjs/core": "^10.0.0",
|
||||||
|
"@nestjs/event-emitter": "^2.1.1",
|
||||||
|
"@nestjs/jwt": "^10.2.0",
|
||||||
|
"@nestjs/microservices": "^10.4.7",
|
||||||
|
"@nestjs/passport": "^10.0.3",
|
||||||
|
"@nestjs/platform-express": "^10.4.8",
|
||||||
|
"@nestjs/schedule": "^4.1.2",
|
||||||
|
"@nestjs/swagger": "^8.0.5",
|
||||||
|
"@nestjs/terminus": "^10.2.3",
|
||||||
|
"@nestjs/throttler": "^6.2.1",
|
||||||
|
"@nestjs/typeorm": "^10.0.2",
|
||||||
|
"amqp-connection-manager": "^4.1.14",
|
||||||
|
"amqplib": "^0.10.4",
|
||||||
|
"bcrypt": "^5.1.1",
|
||||||
|
"cacheable": "^1.8.5",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.1",
|
||||||
|
"firebase-admin": "^13.0.2",
|
||||||
|
"google-libphonenumber": "^3.2.39",
|
||||||
|
"handlebars": "^4.7.8",
|
||||||
|
"ioredis": "^5.4.1",
|
||||||
|
"jwk-to-pem": "^2.0.7",
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"moment": "^2.30.1",
|
||||||
|
"nestjs-i18n": "^10.4.9",
|
||||||
|
"nestjs-pino": "^4.1.0",
|
||||||
|
"nestjs-twilio": "^4.4.0",
|
||||||
|
"nodemailer": "^6.9.16",
|
||||||
|
"oci-common": "^2.99.0",
|
||||||
|
"oci-sdk": "^2.99.0",
|
||||||
|
"passport": "^0.7.0",
|
||||||
|
"passport-jwt": "^4.0.1",
|
||||||
|
"pg": "^8.13.1",
|
||||||
|
"pino-http": "^10.3.0",
|
||||||
|
"pino-pretty": "^13.0.0",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"typeorm": "^0.3.20",
|
||||||
|
"typeorm-transactional": "^0.5.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@golevelup/ts-jest": "^0.6.0",
|
||||||
|
"@nestjs/cli": "^10.0.0",
|
||||||
|
"@nestjs/schematics": "^10.0.0",
|
||||||
|
"@nestjs/testing": "^10.0.0",
|
||||||
|
"@types/bcrypt": "^5.0.2",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/google-libphonenumber": "^7.4.30",
|
||||||
|
"@types/jest": "^29.5.2",
|
||||||
|
"@types/jwk-to-pem": "^2.0.3",
|
||||||
|
"@types/lodash": "^4.17.13",
|
||||||
|
"@types/multer": "^1.4.12",
|
||||||
|
"@types/node": "^20.3.1",
|
||||||
|
"@types/nodemailer": "^6.4.16",
|
||||||
|
"@types/passport-jwt": "^4.0.1",
|
||||||
|
"@types/qrcode": "^1.5.5",
|
||||||
|
"@types/supertest": "^6.0.0",
|
||||||
|
"@types/uuid": "^10.0.0",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^5.59.2",
|
||||||
|
"@typescript-eslint/parser": "^5.59.2",
|
||||||
|
"eslint": "^8.39.0",
|
||||||
|
"eslint-config-prettier": "^8.8.0",
|
||||||
|
"eslint-plugin-prettier": "^4.0.0",
|
||||||
|
"eslint-plugin-security": "^1.7.1",
|
||||||
|
"i": "^0.3.7",
|
||||||
|
"jest": "^29.5.0",
|
||||||
|
"lint-staged": "^13.2.2",
|
||||||
|
"npm": "^10.9.2",
|
||||||
|
"prettier": "^2.8.8",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.1.0",
|
||||||
|
"ts-loader": "^9.4.3",
|
||||||
|
"ts-node": "^10.9.1",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.1.3"
|
||||||
|
},
|
||||||
|
"lint-staged": {
|
||||||
|
"*.{js,ts}": [
|
||||||
|
"eslint --fix"
|
||||||
|
],
|
||||||
|
"*.{js,ts,json,md}": [
|
||||||
|
"prettier --write"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
aliyun-python-sdk-core==2.13.36
|
|
||||||
aliyun-python-sdk-dysmsapi==2.1.2
|
|
||||||
amqp==5.1.1
|
|
||||||
asgiref==3.7.2
|
|
||||||
async-timeout==4.0.2
|
|
||||||
billiard==4.1.0
|
|
||||||
boto3==1.26.157
|
|
||||||
botocore==1.29.157
|
|
||||||
celery==5.3.1
|
|
||||||
cffi==1.15.1
|
|
||||||
channels==4.0.0
|
|
||||||
channels-redis==4.1.0
|
|
||||||
click==8.1.3
|
|
||||||
click-didyoumean==0.3.0
|
|
||||||
click-plugins==1.1.1
|
|
||||||
click-repl==0.3.0
|
|
||||||
cron-descriptor==1.4.0
|
|
||||||
cryptography==41.0.1
|
|
||||||
decouple==0.0.7
|
|
||||||
Django==4.2.2
|
|
||||||
django-celery-beat==2.5.0
|
|
||||||
django-celery-results==2.5.1
|
|
||||||
django-cors-headers==4.1.0
|
|
||||||
django-dotenv==1.4.2
|
|
||||||
django-extensions==3.2.3
|
|
||||||
django-phonenumber-field==7.1.0
|
|
||||||
django-render-block==0.9.2
|
|
||||||
django-ses==3.5.0
|
|
||||||
django-smtp-ssl==1.0
|
|
||||||
django-storages==1.13.2
|
|
||||||
django-templated-email==3.0.1
|
|
||||||
django-timezone-field==5.1
|
|
||||||
djangorestframework==3.14.0
|
|
||||||
djangorestframework-simplejwt==5.2.2
|
|
||||||
drf-yasg==1.21.6
|
|
||||||
gunicorn==20.1.0
|
|
||||||
inflection==0.5.1
|
|
||||||
jmespath==0.10.0
|
|
||||||
kombu==5.3.1
|
|
||||||
msgpack==1.0.5
|
|
||||||
packaging==23.1
|
|
||||||
phonenumbers==8.13.15
|
|
||||||
prompt-toolkit==3.0.38
|
|
||||||
psycopg==3.1.9
|
|
||||||
pycparser==2.21
|
|
||||||
PyJWT==2.7.0
|
|
||||||
python-crontab==2.7.1
|
|
||||||
python-dateutil==2.8.2
|
|
||||||
python-dotenv==1.0.0
|
|
||||||
pytz==2023.3
|
|
||||||
PyYAML==6.0
|
|
||||||
redis==4.5.5
|
|
||||||
s3transfer==0.6.1
|
|
||||||
six==1.16.0
|
|
||||||
sqlparse==0.4.4
|
|
||||||
typing_extensions==4.6.3
|
|
||||||
tzdata==2023.3
|
|
||||||
uritemplate==4.1.1
|
|
||||||
urllib3==1.26.16
|
|
||||||
vine==5.0.0
|
|
||||||
wcwidth==0.2.6
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
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 {}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user