Compare commits
216
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b429b3a9c7 | ||
|
|
6fe495eed1 | ||
|
|
97c2fce7be | ||
|
|
98c46611fb | ||
|
|
fbfe3dcd51 | ||
|
|
5cc5a3dfe1 | ||
|
|
95ae55c9df | ||
|
|
f7ca67d720 | ||
|
|
02421e9bc2 | ||
|
|
5e2b0d3caf | ||
|
|
b9a51ce6cc | ||
|
|
d4a6c4c9ea | ||
|
|
ece6499e2b | ||
|
|
1caaa8404b | ||
|
|
cb6eef2054 | ||
|
|
e77797d7bb | ||
|
|
d5ccf4cf75 | ||
|
|
1a36698962 | ||
|
|
15a2ee1950 | ||
|
|
bef8482402 | ||
|
|
768e583f81 | ||
|
|
1ca6d8f47c | ||
|
|
3fcfb3709e | ||
|
|
6915a97d79 | ||
|
|
6f596efadd | ||
|
|
b6b5f48055 | ||
|
|
789b20c278 | ||
|
|
884b679ba8 | ||
|
|
6ef624c169 | ||
|
|
c10443f881 | ||
|
|
466ba3391a | ||
|
|
8c2527d61e | ||
|
|
018124f7b3 | ||
|
|
7749f6fdec | ||
|
|
b27e4a4404 | ||
|
|
3dde67a4ac | ||
|
|
49abcf28c3 | ||
|
|
9cecc8fa05 | ||
|
|
a32f54873b | ||
|
|
af41a98111 | ||
|
|
4c435708c0 | ||
|
|
ac462ea771 | ||
|
|
3e52223730 | ||
|
|
01e479350b | ||
|
|
b0cf9817d7 | ||
|
|
e530eba60d | ||
|
|
ef1d63e893 | ||
|
|
5859af5294 | ||
|
|
c12da948aa | ||
|
|
3cde18360c | ||
|
|
14b22328de | ||
|
|
96debc210a | ||
|
|
b80662188f | ||
|
|
7b9ce6cda1 | ||
|
|
1bb2d6a419 | ||
|
|
14690a378f | ||
|
|
17cc4ccdba | ||
|
|
1b7368a4b7 | ||
|
|
ff2e14d5f9 | ||
|
|
012aff60ef | ||
|
|
f3d88e2ac9 | ||
|
|
0e48b6755f | ||
|
|
7056f8c8a6 | ||
|
|
4ecdcd12d2 | ||
|
|
dd4a73e360 | ||
|
|
49e0a89ad1 | ||
|
|
82b85abe8f | ||
|
|
df11aa5eb8 | ||
|
|
ac44867ec1 | ||
|
|
7205afe43b | ||
|
|
b1c678c72b | ||
|
|
fa3687c6be | ||
|
|
ba46a19a5a | ||
|
|
8cdbca24ba | ||
|
|
8f981572cd | ||
|
|
39b75f410f | ||
|
|
6da1b2a7e7 | ||
|
|
acccae9f7c | ||
|
|
e7c17784cc | ||
|
|
042e0b4eff | ||
|
|
0b51a56dee | ||
|
|
cb98440b65 | ||
|
|
3c19d262f3 | ||
|
|
bdffe85544 | ||
|
|
9ed619e3fd | ||
|
|
00fd7e1907 | ||
|
|
b70126734e | ||
|
|
6af9461079 | ||
|
|
57b3662951 | ||
|
|
c0c08f2821 | ||
|
|
8402415649 | ||
|
|
01e20baa45 | ||
|
|
10dc869eaf | ||
|
|
199d0c885e | ||
|
|
89ef48a57e | ||
|
|
da1826ebba | ||
|
|
874986f1d6 | ||
|
|
bbff555a06 | ||
|
|
d3eb687a58 | ||
|
|
c5516d4006 | ||
|
|
5f51dd281d | ||
|
|
f6232832af | ||
|
|
277cf0770d | ||
|
|
650728a385 | ||
|
|
3cc3e2a7d8 | ||
|
|
39fc2f86ad | ||
|
|
7bd0ef2274 | ||
|
|
b40a430c49 | ||
|
|
44b1e09551 | ||
|
|
1b9251b2dd | ||
|
|
34b6cdabfb | ||
|
|
a25e896fa2 | ||
|
|
adf3ef8e28 | ||
|
|
ad46687f07 | ||
|
|
0ba04abee9 | ||
|
|
1e25a5b496 | ||
|
|
d7178c792d | ||
|
|
d2754de9ef | ||
|
|
cda950ed7e | ||
|
|
c6a95c1231 | ||
|
|
86116b8157 | ||
|
|
ac06224ed1 | ||
|
|
83e765f358 | ||
|
|
558e0ce568 | ||
|
|
148cf3a5cd | ||
|
|
ee9d23e01b | ||
|
|
1a2e0c58b6 | ||
|
|
e66f1f1634 | ||
|
|
6f45cf80c8 | ||
|
|
02be09506a | ||
|
|
b88ecd1361 | ||
|
|
fa435994f2 | ||
|
|
16c613d699 | ||
|
|
f598dedb3b | ||
|
|
cfa251337f | ||
|
|
cca9aa6318 | ||
|
|
f1e4e02697 | ||
|
|
a3c2715a85 | ||
|
|
89cc631fb0 | ||
|
|
36c12110c2 | ||
|
|
070060365a | ||
|
|
68e816f956 | ||
|
|
48db5f07ef | ||
|
|
a4b5d91906 | ||
|
|
9878279660 | ||
|
|
465cbee2c3 | ||
|
|
33a2ae86c6 | ||
|
|
d906fc4747 | ||
|
|
055ef6ac8e | ||
|
|
e63658c082 | ||
|
|
f4b0ed0a4a | ||
|
|
1e5ed26f76 | ||
|
|
d97095a38d | ||
|
|
e48507901e | ||
|
|
a43ef8ec04 | ||
|
|
874f25aa80 | ||
|
|
12a730a394 | ||
|
|
bdcd41f54d | ||
|
|
96fb8eb7d3 | ||
|
|
d2c333dbd6 | ||
|
|
054f0f63ff | ||
|
|
eb05ea5994 | ||
|
|
4f870ec4c9 | ||
|
|
31f9b6cfea | ||
|
|
07a93ff0b7 | ||
|
|
d2b098ed92 | ||
|
|
09a7f4371a | ||
|
|
b4bf78f0d6 | ||
|
|
de9c5a6dc1 | ||
|
|
8a661df059 | ||
|
|
c7c16d4197 | ||
|
|
3aec0346a9 | ||
|
|
8d2f720de1 | ||
|
|
4b8da68df4 | ||
|
|
6460979bab | ||
|
|
3ae9dbd717 | ||
|
|
0816566d03 | ||
|
|
a97044edfc | ||
|
|
9d92a9a136 | ||
|
|
8e12c79ea6 | ||
|
|
5777268441 | ||
|
|
34eaa418d5 | ||
|
|
77f12610dd | ||
|
|
5be737ad70 | ||
|
|
0ae1e26ba8 | ||
|
|
79721b7af6 | ||
|
|
093e290221 | ||
|
|
1e6957720e | ||
|
|
a0f263bb4f | ||
|
|
413a28c089 | ||
|
|
a90e8662e1 | ||
|
|
955d384f96 | ||
|
|
ea5ece9ab2 | ||
|
|
8ff532bb67 | ||
|
|
eb6cfd51ae | ||
|
|
11d6249007 | ||
|
|
497c250e6d | ||
|
|
2872c1827a | ||
|
|
f9c49d44b5 | ||
|
|
12043f027c | ||
|
|
0c28d34d57 | ||
|
|
271b00c2c4 | ||
|
|
b096f4129a | ||
|
|
7ab036f5f7 | ||
|
|
9ffe808797 | ||
|
|
acfb8259bc | ||
|
|
298144bd36 | ||
|
|
ff9d8cba69 | ||
|
|
8b2769706e | ||
|
|
b8606ef0bb | ||
|
|
44de53a49d | ||
|
|
9abab01b9c | ||
|
|
53414687ff | ||
|
|
d2ec21c7b1 | ||
|
|
4deee3a9cb | ||
|
|
b50ce2b060 |
@@ -0,0 +1,2 @@
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
linker = "rust-lld.exe"
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
target
|
||||
.dockerignore
|
||||
Dockerfile
|
||||
.git
|
||||
.gitignore
|
||||
target
|
||||
.dockerignore
|
||||
Dockerfile
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
+59
-4
@@ -1,4 +1,59 @@
|
||||
PORT=
|
||||
DATABASE_URL=
|
||||
ACCESS_TOKEN_SECRET=
|
||||
REFRESH_TOKEN_SECRET=
|
||||
# RUST_ENV : Mode environment aplikasi (misal: development, production)
|
||||
# RUST_LOG : Level logging aplikasi Rust (misal: debug, info, warn, error)
|
||||
# PORT : Port yang digunakan backend service
|
||||
# SURREALDB_URL : URL koneksi ke SurrealDB (gunakan ws:// untuk WebSocket)
|
||||
# SURREALDB_USERNAME : Username untuk SurrealDB
|
||||
# SURREALDB_PASSWORD : Password untuk SurrealDB
|
||||
# SURREALDB_NAMESPACE : Namespace SurrealDB yang digunakan
|
||||
# SURREALDB_DBNAME : Nama database SurrealDB
|
||||
# ACCESS_TOKEN_SECRET : Secret key untuk JWT access token (ganti dengan nilai rahasia)
|
||||
# REFRESH_TOKEN_SECRET : Secret key untuk JWT refresh token (ganti dengan nilai rahasia)
|
||||
# SMTP_EMAIL : Email yang digunakan untuk mengirim email (SMTP)
|
||||
# SMTP_PASSWORD : Password email SMTP
|
||||
# SMTP_NAME : Nama pengirim email (misal: nama aplikasi)
|
||||
# SMTP_HOST : Host SMTP server (misal: smtp.gmail.com)
|
||||
# REDISDB_URL : URL/host Redis database
|
||||
# FE_URL : URL frontend aplikasi (misal: http://localhost)
|
||||
# MINIO_ENDPOINT : Endpoint MinIO object storage
|
||||
# MINIO_BUCKET_NAME : Nama bucket default MinIO
|
||||
# MINIO_ACCESS_KEY : Access key MinIO atau MINIO_ROOT_USER
|
||||
# MINIO_SECRET_KEY : Secret key MinIO atau MINIO_ROOT_PASSWORD
|
||||
# MINIO_ROOT_USER : Username root MinIO (default: minioadmin)
|
||||
# MINIO_ROOT_PASSWORD : Password root MinIO (default: minioadmin)
|
||||
# GOOGLE_CLIENT_ID : Client ID OAuth Google (untuk login Google)
|
||||
# GOOGLE_CLIENT_SECRET : Client Secret OAuth Google
|
||||
|
||||
RUST_ENV=development
|
||||
RUST_LOG=debug
|
||||
PORT=4099
|
||||
SURREALDB_URL=ws://localhost:8000/rpc
|
||||
SURREALDB_USERNAME=root
|
||||
SURREALDB_PASSWORD=root
|
||||
SURREALDB_NAMESPACE=test
|
||||
SURREALDB_DBNAME=test
|
||||
ACCESS_TOKEN_SECRET=your-access-token-secret-key-here
|
||||
REFRESH_TOKEN_SECRET=your-refresh-token-secret-key-here
|
||||
SMTP_EMAIL=your-email@example.com
|
||||
SMTP_PASSWORD=your-smtp-password
|
||||
SMTP_NAME="Your App Name"
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
REDISDB_URL=localhost
|
||||
FE_URL=http://localhost
|
||||
MINIO_ENDPOINT=http://localhost:9000
|
||||
MINIO_BUCKET_NAME=default_bucket
|
||||
MINIO_ACCESS_KEY=minioadmin
|
||||
MINIO_SECRET_KEY=minioadmin
|
||||
MINIO_SECURE=false
|
||||
|
||||
GOOGLE_CLIENT_ID="your_google_client_id"
|
||||
GOOGLE_CLIENT_SECRET="your_google_client_secret"
|
||||
POOL_SIZE=10
|
||||
CONNECT_TIMEOUT=30
|
||||
IDLE_TIMEOUT=60
|
||||
MAX_LIFETIME=1800
|
||||
STATEMENT_TIMEOUT=30000
|
||||
IDLE_IN_TRANSACTION_SESSION_TIMEOUT=60000
|
||||
SSLMODE=require
|
||||
RETRY_ATTEMPTS=3
|
||||
RETRY_DELAY=1
|
||||
GOOGLE_REDIRECT_URL=http://localhost:8000/api/v1/auth/google/callback
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
use flake --impure
|
||||
use flake --impure
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
name: Deploy to Ancikri
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- develop
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
|
||||
- name: Build the project
|
||||
run: cargo build --release
|
||||
|
||||
- name: Stop service on VPS before upload
|
||||
uses: appleboy/ssh-action@v0.1.7
|
||||
with:
|
||||
host: ${{ secrets.VPS_ANCIKRI_IP }}
|
||||
username: ${{ secrets.VPS_ANCIKRI_USER }}
|
||||
key: ${{ secrets.VPS_ANCIKRI_SSH_KEY }}
|
||||
port: ${{ secrets.VPS_ANCIKRI_PORT }}
|
||||
script: |
|
||||
set -e
|
||||
echo "Stopping the service before uploading the binary"
|
||||
sudo systemctl stop imphnen-backend-service
|
||||
|
||||
- name: Upload artifact to VPS
|
||||
uses: appleboy/scp-action@v0.1.7
|
||||
with:
|
||||
host: ${{ secrets.VPS_ANCIKRI_IP }}
|
||||
username: ${{ secrets.VPS_ANCIKRI_USER }}
|
||||
key: ${{ secrets.VPS_ANCIKRI_SSH_KEY }}
|
||||
port: ${{ secrets.VPS_ANCIKRI_PORT }}
|
||||
source: ./target/release/*
|
||||
target: /opt/imphnen-backend-service/imphnen-backend-service
|
||||
rm: true
|
||||
overwrite: true
|
||||
|
||||
- name: Deploy to server
|
||||
uses: appleboy/ssh-action@v0.1.7
|
||||
with:
|
||||
host: ${{ secrets.VPS_ANCIKRI_IP }}
|
||||
username: ${{ secrets.VPS_ANCIKRI_USER }}
|
||||
key: ${{ secrets.VPS_ANCIKRI_SSH_KEY }}
|
||||
port: ${{ secrets.VPS_ANCIKRI_PORT }}
|
||||
script: |
|
||||
set -e
|
||||
|
||||
echo "Restarting the service"
|
||||
|
||||
sudo systemctl daemon-reload
|
||||
|
||||
sudo systemctl restart imphnen-backend-service
|
||||
|
||||
echo "Deployment completed successfully"
|
||||
@@ -0,0 +1,19 @@
|
||||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["develop"]
|
||||
pull_request:
|
||||
branches: ["develop"]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build
|
||||
run: cargo build --verbose
|
||||
+16
-14
@@ -1,14 +1,16 @@
|
||||
# Build
|
||||
/target
|
||||
/resutl
|
||||
|
||||
# Nix
|
||||
/.direnv
|
||||
|
||||
# Environment
|
||||
.envrc
|
||||
.env
|
||||
.env.local
|
||||
.env.development
|
||||
.env.staging
|
||||
.env.production
|
||||
# Build
|
||||
/target
|
||||
/resutl
|
||||
|
||||
# Nix
|
||||
/.direnv
|
||||
/Cargo.nix
|
||||
|
||||
# Environment
|
||||
.envrc
|
||||
.env
|
||||
.env.local
|
||||
.env.development
|
||||
.env.staging
|
||||
.env.production
|
||||
**/**.log
|
||||
@@ -0,0 +1 @@
|
||||
/cache
|
||||
@@ -0,0 +1,71 @@
|
||||
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
||||
# * For C, use cpp
|
||||
# * For JavaScript, use typescript
|
||||
# Special requirements:
|
||||
# * csharp: Requires the presence of a .sln file in the project folder.
|
||||
language: rust
|
||||
|
||||
# the encoding used by text files in the project
|
||||
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
|
||||
encoding: "utf-8"
|
||||
|
||||
# whether to use the project's gitignore file to ignore files
|
||||
# Added on 2025-04-07
|
||||
ignore_all_files_in_gitignore: true
|
||||
# list of additional paths to ignore
|
||||
# same syntax as gitignore, so you can use * and **
|
||||
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
||||
# Added (renamed) on 2025-04-07
|
||||
ignored_paths: []
|
||||
|
||||
# whether the project is in read-only mode
|
||||
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||
# Added on 2025-04-18
|
||||
read_only: false
|
||||
|
||||
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
||||
# Below is the complete list of tools for convenience.
|
||||
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||
# execute `uv run scripts/print_tool_overview.py`.
|
||||
#
|
||||
# * `activate_project`: Activates a project by name.
|
||||
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||
# * `delete_lines`: Deletes a range of lines within a file.
|
||||
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
||||
# * `execute_shell_command`: Executes a shell command.
|
||||
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
||||
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
||||
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
||||
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||
# * `initial_instructions`: Gets the initial instructions for the current project.
|
||||
# Should only be used in settings where the system prompt cannot be set,
|
||||
# e.g. in clients you have no control over, like Claude Desktop.
|
||||
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||
# * `insert_at_line`: Inserts content at a given line in a file.
|
||||
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
||||
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
||||
# * `read_file`: Reads a file within the project directory.
|
||||
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
||||
# * `remove_project`: Removes a project from the Serena configuration.
|
||||
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
||||
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
||||
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
||||
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
||||
# * `switch_modes`: Activates modes by providing a list of their names
|
||||
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
||||
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
||||
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
||||
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
||||
excluded_tools: []
|
||||
|
||||
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||
# (contrary to the memories, which are loaded on demand).
|
||||
initial_prompt: ""
|
||||
|
||||
project_name: "imphnen-backend-service"
|
||||
Generated
+2171
-587
File diff suppressed because it is too large
Load Diff
+83
-15
@@ -1,24 +1,92 @@
|
||||
[package]
|
||||
name = "imphnen-cms-be"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"tests",
|
||||
"imphnen-entities", # Most basic - core data structures
|
||||
"imphnen-macros", # Macros
|
||||
"imphnen-libs", # Depends on entities
|
||||
"imphnen-utils", # Depends on libs and entities
|
||||
"imphnen-middleware",# Utility for permissions
|
||||
"imphnen-iam", # Core auth service, depends on libs, utils, entities
|
||||
"imphnen-cms", # Content management, depends on core services
|
||||
"imphnen-gacha", # Game mechanics, depends on core services
|
||||
"imphnen-dimentorin",# Learning platform, depends on core services
|
||||
"imphnen-gateway", # API gateway, depends on all services
|
||||
"imphnen-backend", # Main application, depends on all services
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.8.1", features = ["multipart"] }
|
||||
log = "0.4.25"
|
||||
sea-orm = { version = "1.1.4", features = ["sqlx-postgres", "macros", "with-json", "with-uuid", "runtime-tokio", "runtime-tokio-native-tls"] }
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
serde_json = "1.0.138"
|
||||
tokio = { version = "1.43.0", features = ["full"] }
|
||||
|
||||
[workspace.dependencies]
|
||||
async-trait = "0.1.83"
|
||||
oauth2 = "5.0.0"
|
||||
reqwest = { version = "0.12.23", features = ["json"] }
|
||||
serde_json = "1.0.142"
|
||||
axum = { version = "0.8.4", features = ["multipart", "macros"] }
|
||||
log = "0.4.27"
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
tokio = { version = "1.47.1", features = ["full"] }
|
||||
argon2 = { version = "0.5.3", features = ["password-hash"] }
|
||||
jsonwebtoken = "9.3.1"
|
||||
chrono = "0.4.39"
|
||||
utoipa = { version = "5.3.1", features = ["axum_extras"] }
|
||||
utoipa-swagger-ui = { version = "9.0.0", features = ["axum"] }
|
||||
redis = "0.28.2"
|
||||
chrono = "0.4.41"
|
||||
utoipa = { version = "5.4.0", features = ["axum_extras"] }
|
||||
utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] }
|
||||
lettre = { version = "0.11.18", features = ["tokio1-native-tls"] }
|
||||
thiserror = "2.0.14"
|
||||
anyhow = "1.0.99"
|
||||
rand = { version = "0.9.2", features = ["std", "alloc"] }
|
||||
rand_distr = "0.5.1"
|
||||
tower-http = { version = "0.6.6", features = ["cors", "trace"] }
|
||||
http-body-util = "0.1.3"
|
||||
validator = { version = "0.20.0", features = ["derive"] }
|
||||
lazy_static = "1.5.0"
|
||||
regex = "1.11.1"
|
||||
axum-test = "17.3.0"
|
||||
axum-extra = { version = "0.10.1", features = ["typed-header"] }
|
||||
fancy-regex = "0.16.1"
|
||||
futures = "0.3.31"
|
||||
tower = "0.5.2"
|
||||
env_logger = "0.11.8"
|
||||
tracing = "0.1.41"
|
||||
uuid = { version = "1.18.0", features = ["v4", "fast-rng", "serde"] }
|
||||
strum = { version = "0.27.2", features = ["derive"] }
|
||||
strum_macros = "0.27.2"
|
||||
base64 = "0.22.1"
|
||||
sha2 = "0.10.9"
|
||||
hmac = "0.12"
|
||||
hex = "0.4"
|
||||
urlencoding = "2.1"
|
||||
hyper = "1.6.0"
|
||||
hyper-util = "0.1.16"
|
||||
minio = "0.3.0"
|
||||
sea-orm = { version = "1.1", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros", "with-chrono", "uuid"] }
|
||||
num_cpus = "1.16.0"
|
||||
|
||||
|
||||
tokio-test = "0.4.4"
|
||||
mockall = "0.13.1"
|
||||
once_cell = "1.21.3"
|
||||
dotenvy = "0.15.7"
|
||||
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
|
||||
tokio-tungstenite = "0.27"
|
||||
url = "2.5"
|
||||
futures-util = "0.3"
|
||||
http = "1.3"
|
||||
tests = { path = "./tests" }
|
||||
imphnen-iam = { path = "./imphnen-iam" }
|
||||
imphnen-cms = { path = "./imphnen-cms" }
|
||||
imphnen-libs = { path = "./imphnen-libs" }
|
||||
imphnen-utils = { path = "./imphnen-utils" }
|
||||
imphnen-gacha = { path = "./imphnen-gacha" }
|
||||
imphnen-gateway = { path = "./imphnen-gateway" }
|
||||
imphnen-backend = { path = "./imphnen-backend" }
|
||||
imphnen-entities = { path = "./imphnen-entities" }
|
||||
imphnen-dimentorin = { path = "./imphnen-dimentorin" }
|
||||
imphnen-middleware = { path = "./imphnen-middleware" }
|
||||
imphnen-macros = { path = "./imphnen-macros" }
|
||||
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
opt-level = "z"
|
||||
|
||||
|
||||
+47
-22
@@ -1,22 +1,47 @@
|
||||
FROM rust:1.83-slim-bullseye AS builder
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
libssl-dev \
|
||||
pkg-config \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY ./src ./src
|
||||
|
||||
RUN cargo build --release && strip /app/target/release/imphnen-cms-api
|
||||
|
||||
FROM gcr.io/distroless/cc AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /app/target/release/imphnen-cms-api .
|
||||
|
||||
CMD ["/app/imphnen-cms-api"]
|
||||
FROM rust:1.86-alpine AS builder
|
||||
|
||||
RUN apk add --no-cache \
|
||||
curl \
|
||||
musl-dev \
|
||||
openssl-dev \
|
||||
openssl-libs-static \
|
||||
pkgconfig
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
|
||||
RUN mkdir -p imphnen-backend/src imphnen-cms/src imphnen-dimentorin/src \
|
||||
imphnen-entities/src imphnen-gacha/src imphnen-gateway/src \
|
||||
imphnen-iam/src imphnen-libs/src imphnen-middleware/src \
|
||||
imphnen-utils/src tests/src && \
|
||||
echo "fn main() {}" > imphnen-backend/src/main.rs && \
|
||||
find . -name "src" -type d -exec sh -c 'echo "// dummy" > "$1/lib.rs"' _ {} \;
|
||||
|
||||
RUN echo '[package]\nname = "tests"\nversion = "0.1.0"\nedition = "2021"' > tests/Cargo.toml
|
||||
|
||||
|
||||
RUN echo -e '[package]\nname = "tests"\nversion = "0.1.0"\nedition = "2021"' > tests/Cargo.toml
|
||||
|
||||
|
||||
COPY imphnen-backend ./imphnen-backend
|
||||
COPY imphnen-cms ./imphnen-cms
|
||||
COPY imphnen-dimentorin ./imphnen-dimentorin
|
||||
COPY imphnen-entities ./imphnen-entities
|
||||
COPY imphnen-gacha ./imphnen-gacha
|
||||
COPY imphnen-gateway ./imphnen-gateway
|
||||
COPY imphnen-iam ./imphnen-iam
|
||||
COPY imphnen-libs ./imphnen-libs
|
||||
COPY imphnen-middleware ./imphnen-middleware
|
||||
COPY imphnen-utils ./imphnen-utils
|
||||
COPY tests ./tests
|
||||
|
||||
RUN RUSTFLAGS="-C target-cpu=generic -C opt-level=s -C panic=abort -C codegen-units=1 -C strip=symbols" \
|
||||
cargo build -p imphnen-backend --release && \
|
||||
strip target/release/api && \
|
||||
upx --best --lzma target/release/api 2>/dev/null || true
|
||||
|
||||
FROM scratch AS runner
|
||||
COPY --from=builder /app/target/release/api /api
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||
ENTRYPOINT ["/api"]
|
||||
@@ -0,0 +1,130 @@
|
||||
# IMPHNEN Backend Service
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/logo.svg" alt="IMPHNEN">
|
||||
</p>
|
||||
|
||||
This repository serves as the **monorepo** for all backend services of IMPHNEN. It encompasses several main services:
|
||||
|
||||
1. **IMPHNEN-Backend** - Provides fundamental functionalities and shared resources for other services.
|
||||
2. **IMPHNEN-IAM** - Handles identity and access management across IMPHNEN applications.
|
||||
3. **IMPHNEN-CMS** - Supports the cms services by IMPHNEN [Landing Page website](https://imphnen.dev/).
|
||||
4. **IMPHNEN-Gacha** - Supports the gacha services by IMPHNEN [Gacha website](https://gacha.imphnen.dev/).
|
||||
5. **IMPHNEN-Dimentorin** - Supports the mentoring services by IMPHNEN [Dimentorin website](https://dimentorin.imphnen.dev/).
|
||||
6. **IMPHNEN-Gateway** - Acts as the API gateway, routing requests to appropriate services.
|
||||
7. **IMPHNEN-Middleware** - Acts as the middleware for the API Gateway, providing authentication and authorization.
|
||||
|
||||
## How to Install
|
||||
|
||||
1. **Clone the repository**:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/IMPHNEN/imphnen-backend-service.git
|
||||
cd imphnen-backend-service
|
||||
```
|
||||
|
||||
2. **Set up the environment**:
|
||||
|
||||
- Copy the example environment files:
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
if you use windows based system
|
||||
|
||||
```sh
|
||||
./apply-env.ps1
|
||||
```
|
||||
|
||||
if you use unix based system
|
||||
|
||||
```sh
|
||||
source ./apply-env.sh
|
||||
```
|
||||
|
||||
- Modify the `.env` files with your specific configuration settings.
|
||||
|
||||
3. **Install dependencies**:
|
||||
|
||||
Ensure you have [Rust](https://www.rust-lang.org/) installed. Then, run:
|
||||
|
||||
```sh
|
||||
cargo fetch
|
||||
```
|
||||
|
||||
4. **Run the seeders**:
|
||||
|
||||
to run the seeders, run:
|
||||
|
||||
```sh
|
||||
cargo run --bin seeder
|
||||
```
|
||||
|
||||
## How to Run
|
||||
|
||||
### Development
|
||||
|
||||
To run the services in development mode:
|
||||
|
||||
1. **Start the database and other dependencies** using Docker Compose:
|
||||
|
||||
```sh
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
2. **Run using cargo run**. For example, to run the Core Service:
|
||||
|
||||
```sh
|
||||
cargo run --bin api
|
||||
```
|
||||
|
||||
3. **Run using cargo watch**. For example, to run the Core Service:
|
||||
|
||||
```sh
|
||||
cargo watch -x "run --bin api"
|
||||
```
|
||||
|
||||
### Production
|
||||
|
||||
For production deployment:
|
||||
|
||||
1. **Build the Docker image**:
|
||||
|
||||
```sh
|
||||
docker build -t imphnen-backend .
|
||||
```
|
||||
|
||||
2. **Run the Docker container**:
|
||||
|
||||
```sh
|
||||
docker run --name imphnen-backend -d --env-file .env -p 3000:3000 imphnen-backend
|
||||
```
|
||||
|
||||
Adjust the port and environment variables as needed.
|
||||
|
||||
## How to Run the Tests
|
||||
|
||||
1. **Run the tests**:
|
||||
|
||||
```sh
|
||||
cargo test -p tests
|
||||
```
|
||||
|
||||
## How to Contribute
|
||||
|
||||
1. **Fork the repository** and clone it locally.
|
||||
2. **Create a new branch** for your feature or fix:
|
||||
|
||||
```sh
|
||||
git checkout -b feat/your-feature-name
|
||||
```
|
||||
|
||||
3. **Make your changes**, commit them, and push to your forked repository.
|
||||
4. **Create a pull request** to the `develop` branch of this repository.
|
||||
|
||||
If you encounter any issues or have questions, feel free to create a new issue in the repository.
|
||||
|
||||
---
|
||||
|
||||
_Note: For detailed API documentation, please refer to our [API Docs](https://api.imphnen.dev/docs)._
|
||||
@@ -0,0 +1,35 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
:: Cek apakah file .env ada
|
||||
if not exist ".env" (
|
||||
echo File .env tidak ditemukan di direktori saat ini.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo Memuat variabel dari .env...
|
||||
|
||||
:: Baca file .env baris per baris
|
||||
for /f "tokens=*" %%a in ('type ".env" ^| findstr /v "^$" ^| findstr /v "^#"') do (
|
||||
echo.%%a | findstr "=" >nul && (
|
||||
for /f "tokens=1,2 delims==" %%b in ("%%a") do (
|
||||
set "key=%%b"
|
||||
set "value=%%c"
|
||||
:: Trim whitespace
|
||||
call :trimValue key value
|
||||
echo Set variabel: %%b=%%c
|
||||
setx %%b %%c >nul
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Semua variabel telah dimuat.
|
||||
endlocal
|
||||
goto :eof
|
||||
|
||||
:: Fungsi trim (sederhana)
|
||||
:trimValue
|
||||
set "%1=%[%1]%"
|
||||
set "%2=%[%2]%"
|
||||
goto :eof
|
||||
@@ -0,0 +1,30 @@
|
||||
function Set-TempEnvFromDotEnv {
|
||||
param (
|
||||
[string]$envFilePath
|
||||
)
|
||||
|
||||
if (-Not (Test-Path $envFilePath)) {
|
||||
Write-Error "The .env file at path '$envFilePath' does not exist."
|
||||
return
|
||||
}
|
||||
|
||||
$envContent = Get-Content $envFilePath
|
||||
|
||||
foreach ($line in $envContent) {
|
||||
$trimmedLine = $line.Trim()
|
||||
|
||||
if (-Not [string]::IsNullOrWhiteSpace($trimmedLine) -and -Not $trimmedLine.StartsWith("#")) {
|
||||
$keyValue = $trimmedLine -split "=", 2
|
||||
if ($keyValue.Length -eq 2) {
|
||||
$key = $keyValue[0].Trim()
|
||||
$value = $keyValue[1].Trim()
|
||||
[System.Environment]::SetEnvironmentVariable($key, $value, [System.EnvironmentVariableTarget]::Process)
|
||||
Write-Host "Set temporary environment variable: $key=$value"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "All environment variables from '$envFilePath' have been set temporarily."
|
||||
}
|
||||
|
||||
Set-TempEnvFromDotEnv -envFilePath ".env"
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
|
||||
set_temp_env_from_dotenv() {
|
||||
local env_file_path="$1"
|
||||
|
||||
if [[ ! -f "$env_file_path" ]]; then
|
||||
echo "Error: The .env file at path '$env_file_path' does not exist."
|
||||
return 1
|
||||
fi
|
||||
|
||||
while IFS= read -r line || [[ -n "$line" ]]; do
|
||||
trimmed_line=$(echo "$line" | xargs)
|
||||
|
||||
if [[ -n "$trimmed_line" && ! "$trimmed_line" =~ ^# ]]; then
|
||||
key=$(echo "$trimmed_line" | cut -d '=' -f 1 | xargs)
|
||||
value=$(echo "$trimmed_line" | cut -d '=' -f 2- | xargs)
|
||||
export "$key=$value"
|
||||
echo "Set temporary environment variable: $key=$value"
|
||||
fi
|
||||
done < "$env_file_path"
|
||||
|
||||
echo "All environment variables from '$env_file_path' have been set temporarily."
|
||||
}
|
||||
|
||||
set_temp_env_from_dotenv ".env"
|
||||
+15
-15
@@ -1,15 +1,15 @@
|
||||
{pkgs ? import <nixpkgs> {}}: let
|
||||
manifest = (pkgs.lib.importTOML ./Cargo.toml).package;
|
||||
rustDeps = pkgs.callPackage ./Cargo.nix {};
|
||||
packageEntry = rustDeps.workspaceMembers.${manifest.name};
|
||||
deps = packageEntry.build.cargoDeps or null;
|
||||
in
|
||||
pkgs.rustPlatform.buildRustPackage {
|
||||
pname = manifest.name;
|
||||
version = manifest.version;
|
||||
cargoDeps = deps;
|
||||
src = pkgs.lib.cleanSource ./.;
|
||||
cargoLock.lockFile = ./Cargo.lock;
|
||||
nativeBuildInputs = [pkgs.openssl pkgs.pkg-config];
|
||||
buildInputs = [pkgs.openssl];
|
||||
}
|
||||
{pkgs ? import <nixpkgs> {}}: let
|
||||
manifest = (pkgs.lib.importTOML ./Cargo.toml).package;
|
||||
rustDeps = pkgs.callPackage ./Cargo.nix {};
|
||||
packageEntry = rustDeps.workspaceMembers.${manifest.name};
|
||||
deps = packageEntry.build.cargoDeps or null;
|
||||
in
|
||||
pkgs.rustPlatform.buildRustPackage {
|
||||
pname = manifest.name;
|
||||
version = manifest.version;
|
||||
cargoDeps = deps;
|
||||
src = pkgs.lib.cleanSource ./.;
|
||||
cargoLock.lockFile = ./Cargo.lock;
|
||||
nativeBuildInputs = [pkgs.openssl pkgs.pkg-config];
|
||||
buildInputs = [pkgs.openssl];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/bin/bash
|
||||
# Script deploy semua binary hasil build Rust (untuk Linux)
|
||||
|
||||
set -e
|
||||
|
||||
REMOTE_USER="asephs"
|
||||
REMOTE_HOST="70.153.9.42"
|
||||
REMOTE_PATH="/home/asephs/imphnen-backend-service"
|
||||
|
||||
# Build release binary
|
||||
echo "🔧 Building Rust project..."
|
||||
cargo build --release
|
||||
|
||||
# Filter hanya file executable tanpa ekstensi .exe, .rlib, atau .d
|
||||
BINARIES=$(find target/release -maxdepth 1 -type f ! -name "*.exe" ! -name "*.rlib" ! -name "*.d")
|
||||
|
||||
if [ -z "$BINARIES" ]; then
|
||||
echo "❌ Tidak ada binary Linux (.exe/.rlib/.d diabaikan)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Upload semua binary yang valid ke server
|
||||
echo "🚀 Mengirim binary ke server..."
|
||||
rsync -avz --compress-level=9 --progress \
|
||||
$BINARIES \
|
||||
$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/target/release/
|
||||
|
||||
# Jalankan ulang service utama di VPS
|
||||
echo "♻️ Restart service utama di server..."
|
||||
ssh $REMOTE_USER@$REMOTE_HOST << 'EOF'
|
||||
set -e
|
||||
cd /home/asephs/imphnen-backend-service
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
if [ -f ~/.bashrc ]; then
|
||||
source ~/.bashrc
|
||||
fi
|
||||
|
||||
# Pastikan semua binary bisa dieksekusi
|
||||
chmod +x target/release/*
|
||||
|
||||
# Restart service utama (misalnya api.d)
|
||||
if pm2 list | grep -q api; then
|
||||
pm2 restart api --update-env
|
||||
else
|
||||
pm2 start target/release/api.d --name api
|
||||
fi
|
||||
EOF
|
||||
|
||||
echo "✅ Deploy semua binary Linux selesai ke $REMOTE_HOST:$REMOTE_PATH"
|
||||
+46
-8
@@ -1,8 +1,46 @@
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "${PORT}:${PORT}"
|
||||
env_file: ".env"
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "${PORT}:${PORT}"
|
||||
env_file: ".env"
|
||||
depends_on:
|
||||
- postgres
|
||||
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: imphnen_postgres
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-imphnen}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
||||
ports:
|
||||
- "${POSTGRES_PORT:-5432}:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-imphnen}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
minio:
|
||||
image: minio/minio:latest
|
||||
container_name: minio
|
||||
ports:
|
||||
- "9000:9000"
|
||||
- "9001:9001"
|
||||
environment:
|
||||
MINIO_ROOT_USER: minioadmin
|
||||
MINIO_ROOT_PASSWORD: minioadmin
|
||||
command: server /data --console-address ":9001"
|
||||
volumes:
|
||||
- minio_data:/data
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
minio_data:
|
||||
|
||||
+42
-42
@@ -1,42 +1,42 @@
|
||||
{pkgs, ...}: let
|
||||
baseImage = pkgs.ociTools.pullImage {
|
||||
imageName = "ubuntu";
|
||||
tag = "latest";
|
||||
};
|
||||
in
|
||||
pkgs.dockerTools.buildImage {
|
||||
name = "imphnen-cms-api";
|
||||
|
||||
fromImage = baseImage;
|
||||
|
||||
copyToRoot = pkgs.buildEnv {
|
||||
name = "imphnen-cms-api";
|
||||
paths = [
|
||||
(pkgs.stdenv.mkDerivation {
|
||||
name = "imphnen-cms-api";
|
||||
src = ./src;
|
||||
|
||||
buildInputs = [
|
||||
pkgs.rustc
|
||||
pkgs.cargo
|
||||
pkgs.openssl
|
||||
pkgs.pkg-config
|
||||
];
|
||||
|
||||
buildPhase = ''
|
||||
cargo build --release
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
cp target/release/najm-course-api $out/bin/
|
||||
'';
|
||||
})
|
||||
];
|
||||
};
|
||||
|
||||
config = {
|
||||
Cmd = ["/bin/imphnen-cms-api"];
|
||||
WorkingDir = "/bin";
|
||||
};
|
||||
}
|
||||
{pkgs, ...}: let
|
||||
baseImage = pkgs.ociTools.pullImage {
|
||||
imageName = "ubuntu";
|
||||
tag = "latest";
|
||||
};
|
||||
in
|
||||
pkgs.dockerTools.buildImage {
|
||||
name = "imphnen-cms-api";
|
||||
|
||||
fromImage = baseImage;
|
||||
|
||||
copyToRoot = pkgs.buildEnv {
|
||||
name = "imphnen-cms-api";
|
||||
paths = [
|
||||
(pkgs.stdenv.mkDerivation {
|
||||
name = "imphnen-cms-api";
|
||||
src = ./src;
|
||||
|
||||
buildInputs = [
|
||||
pkgs.rustc
|
||||
pkgs.cargo
|
||||
pkgs.openssl
|
||||
pkgs.pkg-config
|
||||
];
|
||||
|
||||
buildPhase = ''
|
||||
cargo build --release
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
cp target/release/najm-course-api $out/bin/
|
||||
'';
|
||||
})
|
||||
];
|
||||
};
|
||||
|
||||
config = {
|
||||
Cmd = ["/bin/imphnen-cms-api"];
|
||||
WorkingDir = "/bin";
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 351 KiB |
Generated
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1739020877,
|
||||
"narHash": "sha256-mIvECo/NNdJJ/bXjNqIh8yeoSjVLAuDuTUzAo7dzs8Y=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "a79cfe0ebd24952b580b1cf08cd906354996d547",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nixos",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -1,24 +1,32 @@
|
||||
{
|
||||
description = "IMPHNEN CMS API Nix Flake";
|
||||
inputs = {
|
||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||
};
|
||||
outputs = {
|
||||
self,
|
||||
nixpkgs,
|
||||
}: let
|
||||
supportedSystems = ["x86_64-linux" "x86_64-darwin" "aarch64-darwin" "aarch64-linux"];
|
||||
forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
|
||||
pkgsFor = nixpkgs.legacyPackages;
|
||||
in {
|
||||
packages = forAllSystems (system: {
|
||||
default = pkgsFor.${system}.callPackage ./default.nix {};
|
||||
});
|
||||
devShells = forAllSystems (system: {
|
||||
default = pkgsFor.${system}.callPackage ./shell.nix {};
|
||||
});
|
||||
dockerImages = forAllSystems (system: {
|
||||
tryOutApi = pkgsFor.${system}.callPackage ./docker.nix {};
|
||||
});
|
||||
};
|
||||
}
|
||||
{
|
||||
description = "IMPHNEN Backend Service Nix Flake";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||
};
|
||||
|
||||
outputs = {
|
||||
self,
|
||||
nixpkgs,
|
||||
}: let
|
||||
supportedSystems = ["x86_64-linux" "x86_64-darwin" "aarch64-darwin" "aarch64-linux"];
|
||||
pkgsFor = system:
|
||||
import nixpkgs {
|
||||
inherit system;
|
||||
config = {
|
||||
allowUnfree = true;
|
||||
};
|
||||
};
|
||||
forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
|
||||
in {
|
||||
packages = forAllSystems (system: {
|
||||
default = (pkgsFor system).callPackage ./default.nix {};
|
||||
});
|
||||
devShells = forAllSystems (system: {
|
||||
default = (pkgsFor system).callPackage ./shell.nix {};
|
||||
});
|
||||
dockerImages = forAllSystems (system: {
|
||||
tryOutApi = (pkgsFor system).callPackage ./docker.nix {};
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
[package]
|
||||
name = "imphnen-backend"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[[bin]]
|
||||
name = "api"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "create_schema"
|
||||
path = "src/bin/create_schema.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seeder"
|
||||
path = "src/bin/seeder.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_events"
|
||||
path = "src/bin/seed_events.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_gacha_rolls"
|
||||
path = "src/bin/seed_gacha_rolls.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_mentor_user"
|
||||
path = "src/bin/seed_mentor_user.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_permissions"
|
||||
path = "src/bin/seed_permissions.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_roles"
|
||||
path = "src/bin/seed_roles.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_roles_permissions"
|
||||
path = "src/bin/seed_roles_permissions.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_test_data"
|
||||
path = "src/bin/seed_test_data.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "test_postgres"
|
||||
path = "src/bin/test_postgres.rs"
|
||||
|
||||
[dependencies]
|
||||
sea-orm.workspace = true
|
||||
imphnen-libs.workspace = true
|
||||
imphnen-utils.workspace = true
|
||||
imphnen-gateway.workspace = true
|
||||
imphnen-entities.workspace = true
|
||||
imphnen-iam.workspace = true
|
||||
imphnen-cms.workspace = true
|
||||
imphnen-gacha.workspace = true
|
||||
imphnen-dimentorin.workspace = true
|
||||
axum.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
utoipa.workspace = true
|
||||
lazy_static.workspace = true
|
||||
regex.workspace = true
|
||||
validator.workspace = true
|
||||
axum-test.workspace = true
|
||||
rand.workspace = true
|
||||
tokio.workspace = true
|
||||
chrono.workspace = true
|
||||
anyhow.workspace = true
|
||||
tower-http.workspace = true
|
||||
utoipa-swagger-ui.workspace = true
|
||||
env_logger.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace=true
|
||||
@@ -0,0 +1,14 @@
|
||||
// API entry point using PostgreSQL (SurrealDB migration complete)
|
||||
// This file has been updated to use SeaORM with PostgreSQL instead of SurrealDB
|
||||
use imphnen_gateway::gateway_service;
|
||||
use imphnen_libs::axum_init;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
axum_init(|postgres_db| async {
|
||||
// Gateway service now uses PostgreSQL exclusively (SeaORM)
|
||||
// SurrealDB dependencies have been completely removed
|
||||
gateway_service(postgres_db).await
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use sea_orm::{Statement, ConnectionTrait};
|
||||
use std::error::Error;
|
||||
use std::env;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
// New default behavior: execute by default; use --dry-run to preview only.
|
||||
let dry_run = args.iter().any(|s| s == "--dry-run" || s == "--no-exec" || s == "--dry");
|
||||
let force = args.iter().any(|s| s == "--force" || s == "-f");
|
||||
|
||||
println!("🔎 Clear DB script - WARNING: This will remove data from tables\n");
|
||||
println!("Note: script now runs by default (no --yes required). To preview without executing, use --dry-run.\n");
|
||||
|
||||
// List of tables to truncate (order doesn't matter with CASCADE)
|
||||
let tables = vec![
|
||||
"gacha_claims",
|
||||
"gacha_rolls",
|
||||
"gacha_items",
|
||||
"gacha_credits",
|
||||
"audit_logs",
|
||||
"rate_limits",
|
||||
"testimonials",
|
||||
"events",
|
||||
"app_mentors",
|
||||
"app_sessions",
|
||||
"app_roles_permissions",
|
||||
"app_permissions",
|
||||
"app_roles",
|
||||
"app_users",
|
||||
];
|
||||
|
||||
let postgres_config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(postgres_config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
// Filter tables that actually exist in the database
|
||||
let mut existing_tables: Vec<&str> = vec![];
|
||||
for t in tables.iter() {
|
||||
let check_sql = format!(
|
||||
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '{}') as exists;",
|
||||
t
|
||||
);
|
||||
let stmt = Statement::from_string(db.get_database_backend(), check_sql);
|
||||
if let Ok(Some(row)) = pg_conn.query_one(stmt).await {
|
||||
let exists_val: Option<bool> = row.try_get("", "exists").ok();
|
||||
if exists_val.unwrap_or(false) {
|
||||
existing_tables.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if existing_tables.is_empty() {
|
||||
println!("No configured tables found to clear - nothing to do.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let truncate_sql = format!(
|
||||
"TRUNCATE TABLE {} RESTART IDENTITY CASCADE;",
|
||||
existing_tables.join(", ")
|
||||
);
|
||||
|
||||
println!("The script will run the following SQL (on the DB configured by env vars):\n\n{}", truncate_sql);
|
||||
|
||||
// Prevent accidental execution in production without explicit force flag
|
||||
let env_name = std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string());
|
||||
if env_name == "production" && !force {
|
||||
println!("Security: RUST_ENV=production; the script will NOT run without --force. Use --force to override.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if dry_run {
|
||||
println!("Dry run enabled. No changes applied. To execute, re-run without --dry-run or use --force (in production).");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("Executing truncate...\n");
|
||||
|
||||
let postgres_config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(postgres_config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
let stmt = Statement::from_string(db.get_database_backend(), truncate_sql);
|
||||
match pg_conn.execute(stmt).await {
|
||||
Ok(_) => println!("✅ Successfully cleared DB tables"),
|
||||
Err(e) => println!("❌ Failed to clear DB tables: {}", e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use sea_orm::{ConnectionTrait, Database, Schema, DbBackend, EntityTrait};
|
||||
use imphnen_libs::postgres::PostgresConfig;
|
||||
use imphnen_entities::seaorm::{auth, common, gacha};
|
||||
use sea_orm::sea_query::Table;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("🛠️ Creating database schema...");
|
||||
|
||||
let config = PostgresConfig::from_env()?;
|
||||
let db = Database::connect(&config.database_url).await?;
|
||||
let builder = db.get_database_backend();
|
||||
|
||||
println!(" Database connected. Creating/updating tables...");
|
||||
|
||||
// Dropping and recreating tables to ensure schema is up-to-date
|
||||
// This is safer for development/testing environments to prevent schema drift.
|
||||
drop_and_create_table(&db, builder, "app_roles", auth::roles::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "app_permissions", auth::permissions::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "app_users", auth::users::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "app_roles_permissions", auth::roles_permissions::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "app_mentors", auth::mentors::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "app_sessions", auth::sessions::Entity).await?;
|
||||
|
||||
drop_and_create_table(&db, builder, "events", common::events::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "testimonials", common::testimonials::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "audit_logs", common::audit_log::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "rate_limits", common::rate_limit::Entity).await?;
|
||||
|
||||
drop_and_create_table(&db, builder, "gacha_credits", gacha::gacha_credits::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "gacha_items", gacha::gacha_items::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "gacha_rolls", gacha::gacha_rolls::Entity).await?;
|
||||
drop_and_create_table(&db, builder, "gacha_claims", gacha::gacha_claims::Entity).await?;
|
||||
|
||||
println!("✅ Schema creation completed.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn drop_and_create_table<E>(
|
||||
db: &sea_orm::DatabaseConnection,
|
||||
builder: DbBackend,
|
||||
name: &str,
|
||||
entity: E,
|
||||
) -> Result<(), Box<dyn std::error::Error>> // Return Result
|
||||
where
|
||||
E: EntityTrait,
|
||||
{
|
||||
let schema = Schema::new(builder);
|
||||
|
||||
// Drop table if it exists
|
||||
let drop_stmt = Table::drop().table(entity).if_exists().cascade().to_owned(); // Added .cascade()
|
||||
db.execute(builder.build(&drop_stmt)).await?; // Propagate error
|
||||
println!(" Dropped table if exists: {}", name);
|
||||
|
||||
// Create table
|
||||
let mut create_stmt = schema.create_table_from_entity(entity);
|
||||
create_stmt.if_not_exists();
|
||||
|
||||
db.execute(builder.build(&create_stmt)).await?; // Propagate error
|
||||
println!(" ✅ Created table: {}", name);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use imphnen_libs::jsonwebtoken::encode_access_token;
|
||||
use std::env;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() < 2 {
|
||||
eprintln!("Usage: mk_token <email_or_sub>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let sub = args[1].clone();
|
||||
// Use sub as both sub and user_id
|
||||
match encode_access_token(sub.clone(), sub.clone()) {
|
||||
Ok(token) => println!("{}", token),
|
||||
Err(e) => {
|
||||
eprintln!("Failed to generate token: {:?}", e);
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use std::error::Error;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use imphnen_entities::seaorm::common::events::{ActiveModel as EventsActiveModel, Entity as EventEntity};
|
||||
use sea_orm::{ActiveValue::Set, ActiveModelTrait, EntityTrait, ColumnTrait, QueryFilter};
|
||||
use uuid::Uuid;
|
||||
use chrono::Utc; // Removed NaiveDateTime as it was unused
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let postgres_config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(postgres_config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
let events = vec![
|
||||
(
|
||||
"Tech Conference 2025",
|
||||
"Annual technology conference featuring the latest innovations in software development, AI, and cloud computing.",
|
||||
"https://techconf2025.example.com",
|
||||
150.0,
|
||||
Some("Jakarta Convention Center".to_string()),
|
||||
false,
|
||||
"2025-06-15T09:00:00Z",
|
||||
"2025-06-17T18:00:00Z",
|
||||
),
|
||||
(
|
||||
"Online Web Development Workshop",
|
||||
"Comprehensive workshop covering modern web development frameworks including React, Vue, and Angular.",
|
||||
"https://webdev-workshop.example.com",
|
||||
75.0,
|
||||
None,
|
||||
true,
|
||||
"2025-07-10T14:00:00Z",
|
||||
"2025-07-10T17:00:00Z",
|
||||
),
|
||||
(
|
||||
"Startup Pitch Competition",
|
||||
"Exciting competition where emerging startups present their innovative ideas to a panel of expert judges and investors.",
|
||||
"https://startup-pitch.example.com",
|
||||
25.0,
|
||||
Some("Innovation Hub Surabaya".to_string()),
|
||||
false,
|
||||
"2025-08-05T10:00:00Z",
|
||||
"2025-08-05T16:00:00Z",
|
||||
),
|
||||
(
|
||||
"Digital Marketing Masterclass",
|
||||
"Learn advanced digital marketing strategies, social media optimization, and data-driven marketing techniques.",
|
||||
"https://digital-marketing.example.com",
|
||||
100.0,
|
||||
None,
|
||||
true,
|
||||
"2025-09-20T13:00:00Z",
|
||||
"2025-09-22T15:00:00Z",
|
||||
),
|
||||
// Additional Events
|
||||
(
|
||||
"Rust Programming Bootcamp",
|
||||
"Intensive 3-day bootcamp to master Rust fundamentals and advanced concepts.",
|
||||
"https://rust-bootcamp.example.com",
|
||||
200.0,
|
||||
Some("Bandung Digital Valley".to_string()),
|
||||
false,
|
||||
"2025-10-01T09:00:00Z",
|
||||
"2025-10-03T17:00:00Z",
|
||||
),
|
||||
(
|
||||
"AI & Machine Learning Summit",
|
||||
"Global summit discussing the future of AI and its impact on industries.",
|
||||
"https://ai-summit.example.com",
|
||||
300.0,
|
||||
Some("Bali Nusa Dua Convention Center".to_string()),
|
||||
false,
|
||||
"2025-11-15T08:00:00Z",
|
||||
"2025-11-17T18:00:00Z",
|
||||
),
|
||||
(
|
||||
"Cybersecurity Awareness Webinar",
|
||||
"Free webinar on best practices for personal and corporate cybersecurity.",
|
||||
"https://cybersecurity-webinar.example.com",
|
||||
0.0,
|
||||
None,
|
||||
true,
|
||||
"2025-12-05T14:00:00Z",
|
||||
"2025-12-05T16:00:00Z",
|
||||
),
|
||||
(
|
||||
"Cloud Computing Workshop",
|
||||
"Hands-on workshop on deploying scalable applications using AWS and Azure.",
|
||||
"https://cloud-workshop.example.com",
|
||||
120.0,
|
||||
None,
|
||||
true,
|
||||
"2026-01-20T10:00:00Z",
|
||||
"2026-01-22T15:00:00Z",
|
||||
),
|
||||
(
|
||||
"Blockchain for Finance",
|
||||
"Exploring the applications of blockchain technology in the financial sector.",
|
||||
"https://blockchain-finance.example.com",
|
||||
180.0,
|
||||
Some("Jakarta Ritz-Carlton".to_string()),
|
||||
false,
|
||||
"2026-02-10T09:00:00Z",
|
||||
"2026-02-11T17:00:00Z",
|
||||
),
|
||||
(
|
||||
"Game Development Jam",
|
||||
"48-hour game development marathon for indie developers.",
|
||||
"https://game-jam.example.com",
|
||||
50.0,
|
||||
Some("Yogyakarta Creative Hub".to_string()),
|
||||
false,
|
||||
"2026-03-15T18:00:00Z",
|
||||
"2026-03-17T18:00:00Z",
|
||||
),
|
||||
(
|
||||
"UX/UI Design Principles",
|
||||
"Masterclass on creating intuitive and user-friendly interfaces.",
|
||||
"https://uxui-design.example.com",
|
||||
90.0,
|
||||
None,
|
||||
true,
|
||||
"2026-04-05T13:00:00Z",
|
||||
"2026-04-07T16:00:00Z",
|
||||
),
|
||||
(
|
||||
"Data Science Fundamentals",
|
||||
"Introduction to data analysis, visualization, and statistical modeling.",
|
||||
"https://data-science.example.com",
|
||||
110.0,
|
||||
None,
|
||||
true,
|
||||
"2026-05-12T10:00:00Z",
|
||||
"2026-05-14T15:00:00Z",
|
||||
),
|
||||
(
|
||||
"IoT Innovation Expo",
|
||||
"Showcase of the latest Internet of Things devices and solutions.",
|
||||
"https://iot-expo.example.com",
|
||||
50.0,
|
||||
Some("Surabaya Expo Center".to_string()),
|
||||
false,
|
||||
"2026-06-20T09:00:00Z",
|
||||
"2026-06-22T18:00:00Z",
|
||||
),
|
||||
];
|
||||
|
||||
for (
|
||||
name,
|
||||
description,
|
||||
detail_link,
|
||||
price,
|
||||
location,
|
||||
is_online,
|
||||
start_date_str, // Renamed to avoid conflict
|
||||
end_date_str, // Renamed to avoid conflict
|
||||
) in events
|
||||
{
|
||||
// Check if event already exists by name
|
||||
let existing = EventEntity::find().filter(<EventEntity as EntityTrait>::Column::Name.eq(name)).one(db).await?;
|
||||
if existing.is_some() {
|
||||
println!("ℹ️ Skipping (already exists): {name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
let uuid = Uuid::new_v4(); // Generate a Uuid
|
||||
let mut event_model: EventsActiveModel = Default::default();
|
||||
event_model.id = Set(uuid);
|
||||
event_model.name = Set(name.to_string());
|
||||
event_model.description = Set(description.to_string());
|
||||
event_model.detail_link = Set(detail_link.to_string());
|
||||
event_model.price = Set(price);
|
||||
event_model.is_online = Set(is_online);
|
||||
event_model.location = Set(location.clone());
|
||||
event_model.start_date = Set(chrono::DateTime::parse_from_rfc3339(start_date_str)?.with_timezone(&chrono::Utc));
|
||||
event_model.end_date = Set(chrono::DateTime::parse_from_rfc3339(end_date_str)?.with_timezone(&chrono::Utc));
|
||||
event_model.is_deleted = Set(false); // Explicitly set is_deleted
|
||||
event_model.created_at = Set(Utc::now()); // Explicitly set created_at
|
||||
event_model.updated_at = Set(Utc::now()); // Explicitly set updated_at
|
||||
|
||||
|
||||
event_model.insert(db).await?;
|
||||
|
||||
println!(
|
||||
"✅ Inserted event: {} ({})",
|
||||
name,
|
||||
if is_online { "Online" } else { "In-person" }
|
||||
);
|
||||
}
|
||||
|
||||
println!("✅ All Events seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use std::error::Error;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use imphnen_entities::seaorm::gacha::gacha_items::ActiveModel as GachaItemActiveModel;
|
||||
use imphnen_entities::seaorm::gacha::gacha_rolls::ActiveModel as GachaRollActiveModel;
|
||||
use sea_orm::ActiveModelTrait;
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use uuid::Uuid;
|
||||
use sea_orm::ConnectionTrait;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
// Check if gacha item already exists
|
||||
let check_item_sql = "SELECT id FROM app_gacha_items WHERE item_code = 'ITEM_TEST_1' LIMIT 1";
|
||||
let item_result = pg_conn.query_one(sea_orm::Statement::from_string(db.get_database_backend(), check_item_sql)).await?;
|
||||
let gacha_item_uuid = if let Some(ref row) = item_result {
|
||||
// Item exists, get its ID
|
||||
row.try_get("", "id")?
|
||||
} else {
|
||||
// Item doesn't exist, create it
|
||||
// Note: We can't easily delete by a fixed ID since it's a UUID, but the insert will fail if there's a conflict
|
||||
let _ = pg_conn.execute(sea_orm::Statement::from_string(db.get_database_backend(), "DELETE FROM app_gacha_items WHERE item_code = 'ITEM_TEST_1'".to_string())).await.ok();
|
||||
|
||||
// Create gacha item via SeaORM
|
||||
let new_uuid = Uuid::new_v4();
|
||||
let mut item_model: GachaItemActiveModel = Default::default();
|
||||
item_model.id = Set(new_uuid);
|
||||
item_model.item_code = Set("ITEM_TEST_1".to_string());
|
||||
item_model.name = Set("Test Gacha Item".to_string());
|
||||
item_model.description = Set("Test item for gacha".to_string());
|
||||
item_model.rarity = Set("common".to_string());
|
||||
item_model.type_ = Set("item".to_string());
|
||||
item_model.category = Set("test".to_string());
|
||||
item_model.value = Set(1);
|
||||
item_model.weight = Set(1.0);
|
||||
item_model.stock = Set(10);
|
||||
item_model.is_limited = Set(false);
|
||||
item_model.created_at = Set(chrono::Utc::now());
|
||||
item_model.updated_at = Set(chrono::Utc::now());
|
||||
item_model.insert(db).await?;
|
||||
println!("Gacha Item seeded successfully!");
|
||||
new_uuid
|
||||
};
|
||||
|
||||
// Always try to insert the roll, relying on the database constraints to prevent duplicates if needed
|
||||
let gacha_roll_id = Uuid::new_v4();
|
||||
let mut roll_model: GachaRollActiveModel = Default::default();
|
||||
roll_model.id = Set(gacha_roll_id);
|
||||
roll_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
|
||||
roll_model.gacha_id = Set(Uuid::new_v4().to_string());
|
||||
roll_model.item_id = Set(gacha_item_uuid);
|
||||
roll_model.weight = Set(1.0);
|
||||
roll_model.quantity = Set(10);
|
||||
roll_model.is_deleted = Set(false);
|
||||
roll_model.created_at = Set(Some(chrono::Utc::now().naive_utc()));
|
||||
roll_model.updated_at = Set(Some(chrono::Utc::now().naive_utc()));
|
||||
roll_model.insert(db).await?;
|
||||
println!("Gacha Roll seeded successfully!");
|
||||
let gacha_roll_id = Uuid::new_v4();
|
||||
let mut roll_model: GachaRollActiveModel = Default::default();
|
||||
roll_model.id = Set(gacha_roll_id);
|
||||
roll_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
|
||||
roll_model.gacha_id = Set(Uuid::new_v4().to_string());
|
||||
roll_model.item_id = Set(gacha_item_uuid);
|
||||
roll_model.weight = Set(1.0);
|
||||
roll_model.quantity = Set(10);
|
||||
roll_model.is_deleted = Set(false);
|
||||
roll_model.created_at = Set(Some(chrono::Utc::now().naive_utc()));
|
||||
roll_model.updated_at = Set(Some(chrono::Utc::now().naive_utc()));
|
||||
roll_model.insert(db).await?;
|
||||
println!("✅ Gacha items and rolls seeded.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use imphnen_libs::hash_password;
|
||||
use serde_json::json;
|
||||
use std::error::Error;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use imphnen_entities::seaorm::auth::users::ActiveModel as UsersActiveModel;
|
||||
use imphnen_entities::seaorm::auth::mentors::ActiveModel as MentorsActiveModel;
|
||||
use imphnen_entities::seaorm::auth::roles::{Entity as RoleEntity, Column as RoleColumn};
|
||||
use sea_orm::{ActiveModelTrait, ConnectionTrait, ActiveValue::Set, EntityTrait, QueryFilter, ColumnTrait};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
let _ = pg_conn.execute(sea_orm::Statement::from_string(db.get_database_backend(), "DELETE FROM app_mentors WHERE id = 'e6f78d23-83bf-5c2b-bcd4-001345678901'".to_string())).await.ok();
|
||||
let _ = pg_conn.execute(sea_orm::Statement::from_string(db.get_database_backend(), "DELETE FROM app_users WHERE email = 'mentor@example.com'".to_string())).await.ok();
|
||||
|
||||
// Find Mentor role
|
||||
let role = RoleEntity::find()
|
||||
.filter(RoleColumn::Name.eq("Mentor"))
|
||||
.one(db)
|
||||
.await?
|
||||
.ok_or("Role 'Mentor' not found")?;
|
||||
|
||||
// Insert user with Mentor role
|
||||
let user_id = Uuid::new_v4();
|
||||
let mut user_model: UsersActiveModel = Default::default();
|
||||
user_model.id = Set(user_id);
|
||||
user_model.email = Set("mentor@example.com".to_string());
|
||||
user_model.password_hash = Set(hash_password("password").unwrap());
|
||||
user_model.username = Set("mentor@example.com".to_string());
|
||||
user_model.first_name = Set(Some("Mentor".to_string()));
|
||||
user_model.last_name = Set(Some("User".to_string()));
|
||||
user_model.avatar_url = Set(Some("https://example.com/avatar.jpg".to_string()));
|
||||
user_model.is_active = Set(true);
|
||||
user_model.is_verified = Set(true);
|
||||
user_model.role_id = Set(Some(role.id));
|
||||
user_model.created_at = Set(chrono::Utc::now());
|
||||
user_model.updated_at = Set(chrono::Utc::now());
|
||||
user_model.insert(db).await?;
|
||||
|
||||
// Insert mentor
|
||||
let mentor_id = Uuid::new_v4();
|
||||
let mut mentor_model: MentorsActiveModel = Default::default();
|
||||
mentor_model.id = Set(mentor_id);
|
||||
mentor_model.user_id = Set(user_id);
|
||||
mentor_model.industries = Set(Some(json!( ["Software", "Education"] )));
|
||||
mentor_model.expertise = Set(Some(json!( ["Rust", "Microservices"] )));
|
||||
mentor_model.languages = Set(Some(json!( ["Indonesian", "English"] )));
|
||||
mentor_model.current_company = Set(Some("PT Contoh".to_string()));
|
||||
mentor_model.current_role = Set(Some("Senior Backend Engineer".to_string()));
|
||||
mentor_model.years_of_experience = Set(Some(5));
|
||||
mentor_model.topics_of_interest = Set(Some(json!( ["Rust Programming", "Backend Development"] )));
|
||||
mentor_model.preferred_mentee_level = Set(Some("beginner".to_string()));
|
||||
mentor_model.preferred_mentoring_formats = Set(Some(json!( ["online", "offline"] )));
|
||||
mentor_model.availability_commitment = Set(Some("2 jam per minggu untuk mentoring online dan offline".to_string()));
|
||||
mentor_model.mentoring_rate = Set(Some(100000.0));
|
||||
mentor_model.status = Set(Some("verified".to_string()));
|
||||
mentor_model.is_deleted = Set(false);
|
||||
mentor_model.created_at = Set(chrono::Utc::now());
|
||||
mentor_model.updated_at = Set(chrono::Utc::now());
|
||||
mentor_model.insert(db).await?;
|
||||
println!("Mentor created successfully!");
|
||||
|
||||
println!("✅ Inserted mentor user: mentor@example.com");
|
||||
println!("✅ Mentor user seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use imphnen_iam::PermissionsEnum;
|
||||
use std::error::Error;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use imphnen_entities::seaorm::auth::permissions::ActiveModel as PermissionActiveModel;
|
||||
use imphnen_entities::seaorm::auth::permissions::Entity as PermissionEntity;
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use sea_orm::{ActiveModelTrait};
|
||||
use uuid::Uuid;
|
||||
use chrono::Utc;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
for permission in [
|
||||
PermissionsEnum::ReadListUsers,
|
||||
PermissionsEnum::ReadDetailUsers,
|
||||
PermissionsEnum::CreateUsers,
|
||||
PermissionsEnum::DeleteUsers,
|
||||
PermissionsEnum::UpdateUsers,
|
||||
PermissionsEnum::ActivateUsers,
|
||||
PermissionsEnum::ReadListRoles,
|
||||
PermissionsEnum::ReadDetailRoles,
|
||||
PermissionsEnum::CreateRoles,
|
||||
PermissionsEnum::DeleteRoles,
|
||||
PermissionsEnum::UpdateRoles,
|
||||
PermissionsEnum::ReadListPermissions,
|
||||
PermissionsEnum::ReadDetailPermissions,
|
||||
PermissionsEnum::CreatePermissions,
|
||||
PermissionsEnum::DeletePermissions,
|
||||
PermissionsEnum::UpdatePermissions,
|
||||
PermissionsEnum::CreateGachaClaims,
|
||||
PermissionsEnum::ReadDetailGachaClaims,
|
||||
PermissionsEnum::ReadListGachaItems,
|
||||
PermissionsEnum::ReadDetailGachaItems,
|
||||
PermissionsEnum::CreateGachaItems,
|
||||
PermissionsEnum::DeleteGachaItems,
|
||||
PermissionsEnum::UpdateGachaItems,
|
||||
PermissionsEnum::ReadDetailGachaRolls,
|
||||
PermissionsEnum::CreateGachaRolls,
|
||||
PermissionsEnum::ExecuteGachaRolls,
|
||||
PermissionsEnum::ReadListMentors,
|
||||
PermissionsEnum::ReadDetailMentors,
|
||||
PermissionsEnum::RegisterMentors,
|
||||
PermissionsEnum::ReadOwnMentorProfile,
|
||||
PermissionsEnum::UpdateOwnMentorProfile,
|
||||
PermissionsEnum::ReadOwnMentorStatus,
|
||||
PermissionsEnum::UpdateMentors,
|
||||
PermissionsEnum::VerifyMentors,
|
||||
PermissionsEnum::DeleteMentors,
|
||||
PermissionsEnum::Administrator,
|
||||
] {
|
||||
// permission.id() returns a string, try parse to uuid
|
||||
let parsed_id = Uuid::parse_str(&permission.id()).unwrap_or_else(|_| Uuid::new_v4());
|
||||
|
||||
// Check if permission already exists
|
||||
let existing = PermissionEntity::find_by_id(parsed_id).one(db).await?;
|
||||
if existing.is_some() {
|
||||
println!("ℹ️ Skipping (already exists): {permission}");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Insert permission using active model
|
||||
let mut perm_model: PermissionActiveModel = Default::default();
|
||||
perm_model.id = Set(parsed_id);
|
||||
perm_model.name = Set(permission.to_string());
|
||||
perm_model.is_deleted = Set(false);
|
||||
perm_model.created_at = Set(Utc::now());
|
||||
perm_model.updated_at = Set(Utc::now());
|
||||
perm_model.insert(db).await?;
|
||||
println!("✅ Inserted: {permission}");
|
||||
}
|
||||
|
||||
println!("✅ All Permissions seeded");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use std::error::Error;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use imphnen_entities::seaorm::auth::roles::{RoleBuilder, Entity as RoleEntity};
|
||||
use sea_orm::{ActiveModelTrait, ActiveValue::Set, EntityTrait};
|
||||
use uuid::Uuid;
|
||||
use chrono::Utc; // Added chrono
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
let roles = vec![
|
||||
(
|
||||
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
|
||||
"Staf",
|
||||
Some("2025-02-24T16:52:27.630453+00"),
|
||||
Some("2025-02-24T16:52:27.630461+00"),
|
||||
),
|
||||
(
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
"User",
|
||||
Some("2025-02-28T14:53:58.576688+00"),
|
||||
Some("2025-02-28T14:53:58.576688+00"),
|
||||
),
|
||||
(
|
||||
"60f1aeb7-dad2-4e06-bcb5-be1ba510c906",
|
||||
"Staff Aktivasi User",
|
||||
Some("2025-02-20T02:47:09.660640+00"),
|
||||
Some("2025-02-20T02:48:30.083283+00"),
|
||||
),
|
||||
(
|
||||
"6d4fea5d-4a08-4b8a-9782-f2ab2183dcf0",
|
||||
"Admin Pembayaran",
|
||||
Some("2025-01-29T05:39:28.562667+00"),
|
||||
Some("2025-03-12T22:56:29.597416+00"),
|
||||
),
|
||||
(
|
||||
"f6b03f25-e416-4893-ac88-caaa690afb07",
|
||||
"Admin",
|
||||
Some("2025-02-22T15:38:39.868306+00"),
|
||||
Some("2025-02-22T15:38:39.868306+00"),
|
||||
),
|
||||
(
|
||||
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a",
|
||||
"Mentor",
|
||||
Some("2025-07-06T10:00:00.000000+00"),
|
||||
Some("2025-07-06T10:00:00.000000+00"),
|
||||
),
|
||||
];
|
||||
|
||||
for (id, name, _created_at_str, _updated_at_str) in roles { // Renamed to avoid conflict
|
||||
let uuid = Uuid::parse_str(id).unwrap_or_else(|_| Uuid::new_v4());
|
||||
|
||||
// Check if role already exists
|
||||
let existing = RoleEntity::find_by_id(uuid).one(db).await?;
|
||||
if existing.is_some() {
|
||||
println!("ℹ️ Skipping (already exists): {name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Delete existing by id to avoid duplicates (original logic, replaced by existence check)
|
||||
// let _ = pg_conn.execute(sea_orm::Statement::from_string(db.get_database_backend(), format!("DELETE FROM app_roles WHERE id = '{}'", uuid))).await.ok();
|
||||
|
||||
let role_model = RoleBuilder::new()
|
||||
.name(name.to_string())
|
||||
.description("System generated role".to_string())
|
||||
.permissions(vec![])
|
||||
.is_default(false)
|
||||
.build()?;
|
||||
let mut role_model = role_model;
|
||||
role_model.id = Set(uuid);
|
||||
role_model.is_system_role = Set(true); // Set the missing field
|
||||
role_model.created_at = Set(Utc::now()); // Set created_at
|
||||
role_model.updated_at = Set(Utc::now()); // Set updated_at
|
||||
|
||||
role_model.insert(db).await?;
|
||||
println!("✅ Inserted role: {name}");
|
||||
}
|
||||
println!("✅ All Roles seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use imphnen_iam::PermissionsEnum;
|
||||
use std::error::Error;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use imphnen_entities::seaorm::auth::roles::Entity as RolesEntity;
|
||||
use imphnen_entities::seaorm::auth::roles::ActiveModel as RoleActiveModel;
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use sea_orm::EntityTrait;
|
||||
use sea_orm::ActiveModelTrait;
|
||||
use uuid::Uuid;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
// Ensure indexes are present if needed (placeholders) - we don't modify schema here
|
||||
|
||||
println!("✅ Index 'user_email_index' defined on table 'users' for column 'email'.");
|
||||
|
||||
let roles_permissions = vec![
|
||||
(
|
||||
"f6b03f25-e416-4893-ac88-caaa690afb07",
|
||||
vec![
|
||||
// Only Administrator permission - grants access to everything
|
||||
PermissionsEnum::Administrator,
|
||||
],
|
||||
),
|
||||
(
|
||||
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a",
|
||||
vec![
|
||||
PermissionsEnum::ReadListUsers, // Added ReadListUsers permission
|
||||
PermissionsEnum::ReadOwnMentorProfile,
|
||||
PermissionsEnum::UpdateOwnMentorProfile,
|
||||
PermissionsEnum::ReadOwnMentorStatus,
|
||||
PermissionsEnum::ReadListMentors,
|
||||
PermissionsEnum::ReadDetailMentors,
|
||||
PermissionsEnum::ReadListGachaItems,
|
||||
PermissionsEnum::ReadDetailGachaItems,
|
||||
PermissionsEnum::ReadDetailGachaRolls,
|
||||
PermissionsEnum::CreateGachaRolls,
|
||||
PermissionsEnum::ExecuteGachaRolls,
|
||||
],
|
||||
),
|
||||
(
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
vec![
|
||||
PermissionsEnum::ReadListGachaItems,
|
||||
PermissionsEnum::ReadDetailGachaItems,
|
||||
PermissionsEnum::ReadListUsers,
|
||||
PermissionsEnum::ReadDetailUsers,
|
||||
PermissionsEnum::CreateGachaClaims,
|
||||
PermissionsEnum::ReadDetailGachaClaims,
|
||||
PermissionsEnum::ReadDetailGachaRolls,
|
||||
PermissionsEnum::CreateGachaRolls,
|
||||
PermissionsEnum::ExecuteGachaRolls,
|
||||
PermissionsEnum::RegisterMentors,
|
||||
PermissionsEnum::ReadListMentors,
|
||||
PermissionsEnum::ReadDetailMentors,
|
||||
PermissionsEnum::ReadOwnMentorProfile,
|
||||
PermissionsEnum::ReadOwnMentorStatus,
|
||||
],
|
||||
),
|
||||
(
|
||||
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
|
||||
vec![
|
||||
// Staff should be able to list roles and permissions in tests
|
||||
PermissionsEnum::ReadListRoles,
|
||||
PermissionsEnum::ReadListPermissions,
|
||||
PermissionsEnum::ReadListUsers,
|
||||
PermissionsEnum::ReadListMentors,
|
||||
PermissionsEnum::ReadDetailUsers,
|
||||
PermissionsEnum::ActivateUsers,
|
||||
PermissionsEnum::ReadDetailRoles,
|
||||
PermissionsEnum::ReadDetailPermissions,
|
||||
PermissionsEnum::ReadListGachaItems,
|
||||
PermissionsEnum::ReadDetailGachaItems,
|
||||
PermissionsEnum::ReadListMentors,
|
||||
PermissionsEnum::ReadDetailMentors,
|
||||
PermissionsEnum::ReadDetailGachaRolls,
|
||||
PermissionsEnum::CreateGachaRolls,
|
||||
PermissionsEnum::ExecuteGachaRolls,
|
||||
],
|
||||
),
|
||||
(
|
||||
"60f1aeb7-dad2-4e06-bcb5-be1ba510c906",
|
||||
vec![PermissionsEnum::ActivateUsers],
|
||||
),
|
||||
("6d4fea5d-4a08-4b8a-9782-f2ab2183dcf0", vec![]),
|
||||
];
|
||||
|
||||
for (role_id, permissions) in roles_permissions {
|
||||
let role_uuid = Uuid::parse_str(role_id).unwrap_or_else(|_| Uuid::new_v4());
|
||||
// Map permissions enum to JSON array of permission ids
|
||||
let json_permissions = JsonValue::Array(
|
||||
permissions.iter().map(|p| JsonValue::String(p.id())).collect()
|
||||
);
|
||||
|
||||
// Find role and update permissions
|
||||
if let Some(role_model) = RolesEntity::find_by_id(role_uuid).one(db).await? {
|
||||
let mut am: RoleActiveModel = role_model.into();
|
||||
am.permissions = Set(Some(json_permissions));
|
||||
am.update(db).await?;
|
||||
println!("✅ Permissions updated for role: {role_id}");
|
||||
} else {
|
||||
println!("⚠️ Role with id {role_id} not found, skipping permissions update");
|
||||
}
|
||||
}
|
||||
|
||||
println!("✅ All roles permissions updated!");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use std::error::Error;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use imphnen_entities::seaorm::common::events::ActiveModel as EventsActiveModel;
|
||||
use imphnen_entities::seaorm::common::testimonials::ActiveModel as TestimonialsActiveModel;
|
||||
use imphnen_entities::seaorm::auth::mentors::ActiveModel as MentorsActiveModel;
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use sea_orm::ActiveModelTrait;
|
||||
use uuid::Uuid;
|
||||
use serde_json::json;
|
||||
use chrono::Utc;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
// Seed Events - handle existing data
|
||||
let uuid = Uuid::new_v4().to_string();
|
||||
let mut event_model: EventsActiveModel = Default::default();
|
||||
event_model.id = Set(Uuid::parse_str(&uuid)?);
|
||||
event_model.name = Set("Test Event".to_string());
|
||||
event_model.description = Set("Test event description".to_string());
|
||||
event_model.detail_link = Set("https://example.com/event".to_string());
|
||||
event_model.price = Set(50.0);
|
||||
event_model.is_online = Set(true);
|
||||
event_model.start_date = Set(Utc::now());
|
||||
event_model.end_date = Set(Utc::now() + chrono::Duration::days(1));
|
||||
event_model.location = Set(None);
|
||||
event_model.is_deleted = Set(false);
|
||||
match event_model.insert(db).await {
|
||||
Ok(_) => println!("✅ Inserted test event"),
|
||||
Err(_) => println!("⚠️ Test event already exists or could not be inserted, skipping"),
|
||||
};
|
||||
|
||||
// Seed Testimonials - handle existing data
|
||||
let mut testimonial_model: TestimonialsActiveModel = Default::default();
|
||||
testimonial_model.id = Set(Uuid::parse_str("00000000-0000-0000-0000-000000000001")?);
|
||||
testimonial_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
|
||||
testimonial_model.role = Set("Student".to_string());
|
||||
testimonial_model.content = Set("This is a great platform!".to_string());
|
||||
testimonial_model.is_deleted = Set(false);
|
||||
match testimonial_model.insert(db).await {
|
||||
Ok(_) => println!("✅ Inserted test testimonial"),
|
||||
Err(_) => println!("⚠️ Test testimonial already exists or could not be inserted, skipping"),
|
||||
};
|
||||
|
||||
// Seed Mentor - handle existing data
|
||||
let mentor_id = Uuid::new_v4();
|
||||
let mut mentor_model: MentorsActiveModel = Default::default();
|
||||
mentor_model.id = Set(mentor_id);
|
||||
// Use the admin user ID instead of a random one
|
||||
mentor_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
|
||||
mentor_model.industries = Set(Some(json!( ["Technology", "Education"] )));
|
||||
mentor_model.expertise = Set(Some(json!( ["Software Development"] )));
|
||||
mentor_model.languages = Set(Some(json!( ["English", "Indonesian"] )));
|
||||
mentor_model.current_company = Set(Some("Tech Corp".to_string()));
|
||||
mentor_model.current_role = Set(Some("Senior Engineer".to_string()));
|
||||
mentor_model.years_of_experience = Set(Some(5));
|
||||
mentor_model.topics_of_interest = Set(Some(json!( ["Rust", "Web Development"] )));
|
||||
mentor_model.preferred_mentee_level = Set(Some("Beginner".to_string()));
|
||||
mentor_model.preferred_mentoring_formats = Set(Some(json!( ["1:1", "Group"] )));
|
||||
mentor_model.availability_commitment = Set(Some("Weekly".to_string()));
|
||||
mentor_model.mentoring_rate = Set(Some(100.0));
|
||||
mentor_model.status = Set(Some("active".to_string()));
|
||||
mentor_model.is_deleted = Set(false);
|
||||
mentor_model.created_at = Set(chrono::Utc::now());
|
||||
mentor_model.updated_at = Set(chrono::Utc::now());
|
||||
// Create mentor record via SeaORM active model
|
||||
mentor_model.insert(db).await?;
|
||||
println!("✅ Inserted test mentor via SeaORM");
|
||||
|
||||
println!("✅ All test data seeded successfully");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use imphnen_libs::hash_password;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||
use imphnen_entities::seaorm::auth::users::Entity as UserEntity; // Added for dynamic role lookup
|
||||
use imphnen_entities::seaorm::auth::users::ActiveModel as UsersActiveModel;
|
||||
|
||||
use sea_orm::{ActiveModelTrait, ActiveValue::Set, EntityTrait, IntoActiveModel};
|
||||
use uuid::Uuid;
|
||||
use std::error::Error;
|
||||
use chrono::Utc;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let postgres_config = PostgresConfig::from_env()?;
|
||||
let pg_conn = PostgresConnection::new(postgres_config).await?;
|
||||
let db = &pg_conn.conn;
|
||||
|
||||
let users = vec![
|
||||
(
|
||||
"c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2",
|
||||
"admin@example.com",
|
||||
"Admin",
|
||||
"f6b03f25-e416-4893-ac88-caaa690afb07",
|
||||
),
|
||||
(
|
||||
"a4d23fb5-9e31-423c-9842-fbd6e75a5298",
|
||||
"staff@example.com",
|
||||
"Staff",
|
||||
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
|
||||
),
|
||||
(
|
||||
"d5e89c12-72af-4b1a-abc3-ff1234567890",
|
||||
"user@example.com",
|
||||
"User",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"665a3cfc-ea5f-4bcd-8769-4a6d8d1451d4",
|
||||
"testuser1@example.com",
|
||||
"Test User 1",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059", // Fixed UUID
|
||||
),
|
||||
(
|
||||
"3972c139-a450-416c-93b0-c42539dc780f",
|
||||
"testuser2@example.com",
|
||||
"Test User 2",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"b426c0a9-0efb-4e26-b078-4f18767255f3",
|
||||
"testuser3@example.com",
|
||||
"Test User 3",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059", // Fixed UUID
|
||||
),
|
||||
// Additional Users for Volume and Variety
|
||||
(
|
||||
"11111111-1111-1111-1111-111111111111",
|
||||
"user4@example.com",
|
||||
"User Four",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"22222222-2222-2222-2222-222222222222",
|
||||
"user5@example.com",
|
||||
"User Five",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"33333333-3333-3333-3333-333333333333",
|
||||
"mentor2@example.com",
|
||||
"Mentor Two",
|
||||
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a", // Mentor Role
|
||||
),
|
||||
(
|
||||
"44444444-4444-4444-4444-444444444444",
|
||||
"staff2@example.com",
|
||||
"Staff Two",
|
||||
"50133429-f4b1-4249-9f97-7b86e6ee9d86", // Staff Role
|
||||
),
|
||||
(
|
||||
"55555555-5555-5555-5555-555555555555",
|
||||
"user6@example.com",
|
||||
"User Six",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"66666666-6666-6666-6666-666666666666",
|
||||
"user7@example.com",
|
||||
"User Seven",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"77777777-7777-7777-7777-777777777777",
|
||||
"user8@example.com",
|
||||
"User Eight",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"88888888-8888-8888-8888-888888888888",
|
||||
"user9@example.com",
|
||||
"User Nine",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"99999999-9999-9999-9999-999999999999",
|
||||
"user10@example.com",
|
||||
"User Ten",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
];
|
||||
|
||||
for (id, email, fullname, role_id_str) in users { // role_id_str directly contains UUID
|
||||
let role_uuid = Some(Uuid::parse_str(role_id_str)
|
||||
.map_err(|e| format!("Invalid UUID for role: {role_id_str} - {e}"))?);
|
||||
|
||||
// Build SeaORM ActiveModel for users
|
||||
let uid = Uuid::parse_str(id)?; // Should always be valid UUID strings from test data
|
||||
|
||||
let names: Vec<&str> = fullname.split_whitespace().collect();
|
||||
let first_name = names.first().map(|s| s.to_string());
|
||||
let last_name = if names.len() > 1 { Some(names[1..].join(" ")) } else { None };
|
||||
|
||||
let password = "password";
|
||||
let hashed = hash_password(password).unwrap();
|
||||
|
||||
// Explicit Upsert Logic
|
||||
let existing_user = UserEntity::find_by_id(uid).one(db).await?;
|
||||
let is_update = existing_user.is_some();
|
||||
|
||||
let mut user_model: UsersActiveModel = if let Some(existing) = existing_user {
|
||||
println!("🔄 Updating user: {fullname} ({email})");
|
||||
existing.into_active_model()
|
||||
} else {
|
||||
println!("✅ Inserting user: {fullname} ({email})");
|
||||
let mut active: UsersActiveModel = Default::default();
|
||||
active.id = Set(uid);
|
||||
active.created_at = Set(Utc::now());
|
||||
active
|
||||
};
|
||||
|
||||
user_model.email = Set(email.to_string());
|
||||
user_model.password_hash = Set(hashed);
|
||||
user_model.username = Set(email.to_string());
|
||||
user_model.first_name = Set(first_name);
|
||||
user_model.last_name = Set(last_name);
|
||||
user_model.avatar_url = Set(Some("https://example.com/avatar.jpg".to_string()));
|
||||
user_model.is_verified = Set(true);
|
||||
user_model.is_active = Set(true);
|
||||
user_model.role_id = Set(role_uuid);
|
||||
user_model.updated_at = Set(Utc::now());
|
||||
|
||||
if is_update {
|
||||
user_model.update(db).await?;
|
||||
} else {
|
||||
user_model.insert(db).await?;
|
||||
}
|
||||
}
|
||||
println!("✅ All Users seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use std::error::Error;
|
||||
use std::process::Command;
|
||||
|
||||
fn run_seed(bin: &str) -> Result<(), Box<dyn Error>> {
|
||||
println!("🔧 Seeding: {bin}");
|
||||
#[cfg(target_os = "windows")]
|
||||
let status = Command::new(format!("./target/release/{}.exe", bin)).status()?;
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let status = Command::new(format!("./target/release/{}", bin)).status()?;
|
||||
|
||||
if !status.success() {
|
||||
Err(format!("❌ Failed to run seed: {bin}").into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("🚀 Running all seeders...\n");
|
||||
|
||||
run_seed("seed_permissions")?;
|
||||
run_seed("seed_roles")?;
|
||||
run_seed("seed_roles_permissions")?;
|
||||
run_seed("seed_users")?;
|
||||
run_seed("seed_events")?;
|
||||
run_seed("seed_gacha_rolls")?;
|
||||
run_seed("seed_mentor_user")?;
|
||||
run_seed("seed_test_data")?;
|
||||
println!("\n✅ All seeding completed successfully.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
//! PostgreSQL Connection Test Program
|
||||
//! This program tests the PostgreSQL integration with SeaORM
|
||||
|
||||
use std::sync::Arc;
|
||||
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection, PostgresError};
|
||||
use imphnen_entities::seaorm::auth::users::{Entity as UsersEntity, Model as UserModel};
|
||||
use imphnen_entities::seaorm::auth::roles::{Entity as RolesEntity, Model as RoleModel};
|
||||
use sea_orm::{EntityTrait, ActiveModelTrait, Set, TransactionTrait, DbErr, PaginatorTrait};
|
||||
use uuid::Uuid;
|
||||
use chrono::Utc;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("🚀 Starting PostgreSQL Connection Test");
|
||||
println!("=====================================");
|
||||
|
||||
// Load configuration from environment
|
||||
let config = PostgresConfig::from_env()?;
|
||||
println!("✅ Configuration loaded successfully");
|
||||
println!(" Database URL: {}", config.database_url.replace("postgres://", "postgres://****:****@"));
|
||||
println!(" Pool size: {}", config.pool_size);
|
||||
println!(" Connect timeout: {}s", config.connect_timeout);
|
||||
println!(" Retry attempts: {}", config.retry_attempts);
|
||||
|
||||
// Test connection
|
||||
println!("\n🔌 Testing PostgreSQL connection...");
|
||||
match test_connection(config).await {
|
||||
Ok(()) => {
|
||||
println!("✅ All PostgreSQL tests passed successfully!");
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
println!("❌ PostgreSQL test failed: {}", e);
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn test_connection(config: PostgresConfig) -> Result<(), PostgresError> {
|
||||
// Create connection
|
||||
println!(" Creating PostgreSQL connection...");
|
||||
let postgres_conn = PostgresConnection::new(config).await?;
|
||||
let connection = Arc::new(postgres_conn);
|
||||
println!(" ✅ Connection established successfully");
|
||||
|
||||
// Test basic connectivity
|
||||
println!(" Testing basic connectivity...");
|
||||
test_basic_connectivity(&connection).await?;
|
||||
println!(" ✅ Basic connectivity test passed");
|
||||
|
||||
// Test table existence
|
||||
println!(" Testing table existence...");
|
||||
test_table_existence(&connection).await?;
|
||||
println!(" ✅ Table existence test passed");
|
||||
|
||||
// Test CRUD operations
|
||||
println!(" Testing CRUD operations...");
|
||||
test_crud_operations(&connection).await?;
|
||||
println!(" ✅ CRUD operations test passed");
|
||||
|
||||
// Test transaction support
|
||||
println!(" Testing transaction support...");
|
||||
test_transactions(&connection).await?;
|
||||
println!(" ✅ Transaction support test passed");
|
||||
|
||||
// Test error handling
|
||||
println!(" Testing error handling...");
|
||||
test_error_handling(&connection).await?;
|
||||
println!(" ✅ Error handling test passed");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn test_basic_connectivity(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||
// Execute a simple query
|
||||
let statement = sea_orm::Statement::from_string(
|
||||
connection.get_database_backend(),
|
||||
"SELECT 1 as test_value, current_timestamp as current_time".to_string()
|
||||
);
|
||||
|
||||
let result = connection.query_one(statement).await?
|
||||
.ok_or_else(|| PostgresError::ConnectionError(sea_orm::DbErr::Custom("No results returned".to_string())))?;
|
||||
|
||||
// Verify we got expected results
|
||||
let test_value: Option<i32> = result.try_get("", "test_value").ok();
|
||||
let current_time: Option<String> = result.try_get("", "current_time").ok();
|
||||
|
||||
if test_value != Some(1) {
|
||||
return Err(PostgresError::ConnectionError(sea_orm::DbErr::Custom(
|
||||
format!("Expected test_value=1, got {:?}", test_value)
|
||||
)));
|
||||
}
|
||||
|
||||
if current_time.is_none() {
|
||||
return Err(PostgresError::ConnectionError(sea_orm::DbErr::Custom(
|
||||
"Expected current_time to be set".to_string()
|
||||
)));
|
||||
}
|
||||
|
||||
println!(" 📝 Query result: test_value={:?}, current_time={:?}", test_value, current_time);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn test_table_existence(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||
// Test if our tables exist
|
||||
use sea_orm::EntityTrait;
|
||||
|
||||
println!(" 📋 Checking users table...");
|
||||
let user_count = UsersEntity::find()
|
||||
.count(&connection.conn)
|
||||
.await
|
||||
.map_err(PostgresError::ConnectionError)?;
|
||||
println!(" 📊 Users table accessible, current count: {}", user_count);
|
||||
|
||||
println!(" 📋 Checking roles table...");
|
||||
let role_count = RolesEntity::find()
|
||||
.count(&connection.conn)
|
||||
.await
|
||||
.map_err(PostgresError::ConnectionError)?;
|
||||
println!(" 📊 Roles table accessible, current count: {}", role_count);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn test_crud_operations(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||
use sea_orm::{ActiveModelTrait, Set};
|
||||
|
||||
// Create test user
|
||||
println!(" ➕ Creating test user...");
|
||||
let test_user_id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
|
||||
let user_model = imphnen_entities::seaorm::auth::users::ActiveModel {
|
||||
id: Set(test_user_id),
|
||||
email: Set(format!("test_user_{}@example.com", test_user_id)),
|
||||
password_hash: Set("test_password_hash".to_string()),
|
||||
username: Set(format!("testuser_{}", test_user_id)),
|
||||
first_name: Set(Some("Test".to_string())),
|
||||
last_name: Set(Some("User".to_string())),
|
||||
avatar_url: Set(None),
|
||||
is_verified: Set(false),
|
||||
is_active: Set(true),
|
||||
metadata: Set(None),
|
||||
role_id: Set(None),
|
||||
created_at: Set(now),
|
||||
updated_at: Set(now),
|
||||
deleted_at: Set(None),
|
||||
};
|
||||
|
||||
let created_user = user_model.insert(&connection.conn)
|
||||
.await
|
||||
.map_err(PostgresError::ConnectionError)?;
|
||||
|
||||
println!(" ✅ Created user with ID: {}", created_user.id);
|
||||
|
||||
// Read user
|
||||
println!(" 🔍 Reading test user...");
|
||||
let found_user = UsersEntity::find_by_id(test_user_id)
|
||||
.one(&connection.conn)
|
||||
.await
|
||||
.map_err(PostgresError::ConnectionError)?
|
||||
.ok_or_else(|| PostgresError::ConnectionError(sea_orm::DbErr::Custom("User not found after creation".to_string())))?;
|
||||
|
||||
println!(" ✅ Found user: {} ({})", found_user.username, found_user.email);
|
||||
|
||||
// Update user
|
||||
println!(" ✏️ Updating test user...");
|
||||
let mut update_model: imphnen_entities::seaorm::auth::users::ActiveModel = found_user.into();
|
||||
update_model.first_name = Set(Some("Updated".to_string()));
|
||||
update_model.updated_at = Set(Utc::now());
|
||||
|
||||
let updated_user = update_model.update(&connection.conn)
|
||||
.await
|
||||
.map_err(PostgresError::ConnectionError)?;
|
||||
|
||||
println!(" ✅ Updated user first name to: {:?}", updated_user.first_name);
|
||||
|
||||
// Delete user
|
||||
println!(" 🗑️ Deleting test user...");
|
||||
UsersEntity::delete_by_id(updated_user.id)
|
||||
.exec(&connection.conn)
|
||||
.await
|
||||
.map_err(PostgresError::ConnectionError)?;
|
||||
|
||||
println!(" ✅ Test user deleted successfully");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn test_transactions(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||
println!(" 💰 Testing transaction support...");
|
||||
|
||||
// Test transaction with rollback
|
||||
let transaction_result = connection.conn.transaction(|txn| {
|
||||
Box::pin(async move {
|
||||
// Create a test user within transaction
|
||||
let test_user_id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
|
||||
let user_model = imphnen_entities::seaorm::auth::users::ActiveModel {
|
||||
id: Set(test_user_id),
|
||||
email: Set(format!("transaction_test_{}@example.com", test_user_id)),
|
||||
password_hash: Set("transaction_password_hash".to_string()),
|
||||
username: Set(format!("transaction_user_{}", test_user_id)),
|
||||
first_name: Set(Some("Transaction".to_string())),
|
||||
last_name: Set(Some("Test".to_string())),
|
||||
avatar_url: Set(None),
|
||||
is_verified: Set(false),
|
||||
is_active: Set(true),
|
||||
metadata: Set(None),
|
||||
role_id: Set(None),
|
||||
created_at: Set(now),
|
||||
updated_at: Set(now),
|
||||
deleted_at: Set(None),
|
||||
};
|
||||
|
||||
let _created_user = user_model.insert(txn)
|
||||
.await?;
|
||||
|
||||
// Simulate an error to trigger rollback (return a sea_orm::DbErr so the TransactionError matches)
|
||||
Err::<(), DbErr>(DbErr::Custom("Simulated transaction failure".to_string()))
|
||||
})
|
||||
}).await;
|
||||
|
||||
// Transaction should fail and rollback
|
||||
match transaction_result {
|
||||
Err(e) => {
|
||||
let e_text = format!("{:?}", e);
|
||||
if e_text.contains("Simulated transaction failure") {
|
||||
println!(" ✅ Transaction failed as expected, rollback successful");
|
||||
} else {
|
||||
return Err(PostgresError::OperationFailed(format!("Unexpected transaction result: {}", e_text)));
|
||||
}
|
||||
}
|
||||
Ok(_) => {
|
||||
return Err(PostgresError::OperationFailed("Unexpected transaction result: transaction unexpectedly succeeded".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// Verify user was not created (due to rollback)
|
||||
let user_exists = UsersEntity::find_by_id(Uuid::nil()) // Use nil UUID as we don't know the actual ID
|
||||
.one(&connection.conn)
|
||||
.await
|
||||
.map_err(PostgresError::ConnectionError)?
|
||||
.is_some();
|
||||
|
||||
if user_exists {
|
||||
println!(" ⚠️ User found despite rollback - this might indicate an issue");
|
||||
} else {
|
||||
println!(" ✅ Transaction rollback verified - user not found");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn test_error_handling(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||
println!(" ⚠️ Testing error handling...");
|
||||
|
||||
// Test invalid UUID
|
||||
println!(" 🔍 Testing invalid UUID handling...");
|
||||
let invalid_uuid = Uuid::nil(); // This should exist or be handled gracefully
|
||||
|
||||
match UsersEntity::find_by_id(invalid_uuid)
|
||||
.one(&connection.conn)
|
||||
.await
|
||||
.map_err(PostgresError::ConnectionError)?
|
||||
{
|
||||
Some(_) => println!(" ✅ Found user with nil UUID (expected in some cases)"),
|
||||
None => println!(" ✅ No user found with nil UUID (expected)"),
|
||||
}
|
||||
|
||||
// Test invalid query
|
||||
println!(" 🔍 Testing invalid query handling...");
|
||||
let invalid_statement = sea_orm::Statement::from_string(
|
||||
connection.get_database_backend(),
|
||||
"SELECT * FROM non_existent_table".to_string()
|
||||
);
|
||||
|
||||
match connection.execute(invalid_statement).await {
|
||||
Err(_) => println!(" ✅ Invalid query properly handled with error"),
|
||||
Ok(_) => println!(" ⚠️ Invalid query unexpectedly succeeded"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Additional utility functions for comprehensive testing
|
||||
pub mod test_utils {
|
||||
use super::*;
|
||||
|
||||
/// Create a test PostgreSQL configuration
|
||||
pub fn create_test_config() -> PostgresConfig {
|
||||
PostgresConfig {
|
||||
database_url: "postgres://postgres:postgres@localhost:5432/imphnen_test".to_string(),
|
||||
pool_size: 5,
|
||||
connect_timeout: 10,
|
||||
idle_timeout: 30,
|
||||
max_lifetime: Some(600),
|
||||
retry_attempts: 2,
|
||||
retry_delay: 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a test user model
|
||||
pub fn create_test_user_model() -> UserModel {
|
||||
UserModel {
|
||||
id: Uuid::new_v4(),
|
||||
email: format!("test_{}@example.com", Uuid::new_v4()),
|
||||
password_hash: "test_password_hash".to_string(),
|
||||
username: format!("testuser_{}", Uuid::new_v4()),
|
||||
first_name: Some("Test".to_string()),
|
||||
last_name: Some("User".to_string()),
|
||||
avatar_url: None,
|
||||
is_verified: false,
|
||||
is_active: true,
|
||||
metadata: None,
|
||||
role_id: None,
|
||||
created_at: Utc::now(),
|
||||
updated_at: Utc::now(),
|
||||
deleted_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a test role model
|
||||
pub fn create_test_role_model() -> RoleModel {
|
||||
RoleModel {
|
||||
id: Uuid::new_v4(),
|
||||
name: format!("test_role_{}", Uuid::new_v4()),
|
||||
description: "Test role description".to_string(),
|
||||
permissions: Some(serde_json::json!(["test.permission"])),
|
||||
is_system_role: false,
|
||||
is_default: false,
|
||||
created_at: Utc::now(),
|
||||
updated_at: Utc::now(),
|
||||
deleted_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_create_test_config() {
|
||||
let config = test_utils::create_test_config();
|
||||
assert_eq!(config.pool_size, 5);
|
||||
assert_eq!(config.connect_timeout, 10);
|
||||
assert!(config.database_url.contains("imphnen_test"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_test_user_model() {
|
||||
let user = test_utils::create_test_user_model();
|
||||
assert!(!user.email.is_empty());
|
||||
assert!(!user.username.is_empty());
|
||||
assert!(user.is_active);
|
||||
// is_admin field removed; instead, check role-based permission or is_active
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_test_role_model() {
|
||||
let role = test_utils::create_test_role_model();
|
||||
assert!(!role.name.is_empty());
|
||||
assert!(role.permissions.is_some());
|
||||
assert!(!role.is_system_role);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use imphnen_gateway::gateway_service;
|
||||
use imphnen_libs::axum_init;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let _ = axum_init(|postgres_conn| async {
|
||||
// PostgreSQL is now the primary database - SurrealDB has been completely removed
|
||||
gateway_service(postgres_conn).await
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "imphnen-cms"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
imphnen-iam.workspace = true
|
||||
imphnen-libs.workspace = true
|
||||
imphnen-utils.workspace = true
|
||||
imphnen-entities.workspace = true
|
||||
axum.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
utoipa.workspace = true
|
||||
lazy_static.workspace = true
|
||||
regex.workspace = true
|
||||
validator.workspace = true
|
||||
axum-test.workspace = true
|
||||
rand.workspace = true
|
||||
tokio.workspace = true
|
||||
chrono.workspace = true
|
||||
anyhow.workspace = true
|
||||
tower-http.workspace = true
|
||||
utoipa-swagger-ui.workspace = true
|
||||
log.workspace = true
|
||||
tracing.workspace = true
|
||||
sea-orm.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[package.metadata.validator.regex]
|
||||
VALID_URL_REGEX = "^https?://"
|
||||
@@ -0,0 +1,9 @@
|
||||
pub mod v1;
|
||||
|
||||
pub use v1::landing;
|
||||
pub use v1::landing::events;
|
||||
pub use v1::landing::testimonials;
|
||||
pub use v1::landing::events::events_public_routes;
|
||||
pub use v1::landing::events::events_protected_routes;
|
||||
pub use v1::landing::testimonials::testimonials_public_routes;
|
||||
pub use v1::landing::testimonials::testimonials_protected_routes;
|
||||
@@ -0,0 +1,139 @@
|
||||
use super::{
|
||||
events_dto::{
|
||||
EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto,
|
||||
EventsUpdateRequestDto,
|
||||
},
|
||||
events_service::EventsService,
|
||||
};
|
||||
use axum::extract::{Path, Query};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Extension, http::HeaderMap, http::StatusCode};
|
||||
use imphnen_libs::{
|
||||
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
|
||||
ResponseSuccessDto, ValidatedJson,
|
||||
};
|
||||
use imphnen_iam::{PermissionsEnum, require_permissions};
|
||||
use imphnen_utils::common_response;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/cms/landing/events",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Get event list", body = ResponseListSuccessDto<Vec<EventsListItemDto>>)
|
||||
),
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn get_event_list(
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
EventsService::get_event_list(&state, meta).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/cms/landing/events/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Event ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Get event by ID", body = ResponseSuccessDto<EventsDetailItemDto>)
|
||||
),
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn get_event_by_id(
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let parsed_id = match Uuid::parse_str(&id) {
|
||||
Ok(uuid) => uuid,
|
||||
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
|
||||
};
|
||||
EventsService::get_event_by_id(&state, parsed_id).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/cms/landing/events/create",
|
||||
request_body = EventsCreateRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "[ADMIN] Create new event", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn post_create_event(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
ValidatedJson(payload): ValidatedJson<EventsCreateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
EventsService::create_event(&state, payload).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/cms/landing/events/update/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Event ID")
|
||||
),
|
||||
request_body = EventsUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Update event", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn patch_update_event(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(payload): ValidatedJson<EventsUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
EventsService::update_event(&state, id, payload).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/cms/landing/events/delete/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Event ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Soft delete event", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn delete_event(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
let parsed_id = match Uuid::parse_str(&id) {
|
||||
Ok(uuid) => uuid,
|
||||
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
|
||||
};
|
||||
EventsService::delete_event(&state, parsed_id).await
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::LazyLock;
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
// Custom URL validator that ensures valid HTTP/HTTPS URLs
|
||||
static VALID_URL_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^https?://[^\s$.?#].[^\s]*$").unwrap());
|
||||
|
||||
pub fn validate_url(url: &str) -> Result<(), ValidationError> {
|
||||
if VALID_URL_REGEX.is_match(url) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("invalid_url"))
|
||||
}
|
||||
}
|
||||
|
||||
// Custom validator for future dates
|
||||
pub fn validate_future_date(end_date: &DateTime<Utc>) -> Result<(), ValidationError> {
|
||||
let now = Utc::now();
|
||||
if end_date > &now {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("future_date"))
|
||||
}
|
||||
}
|
||||
|
||||
// Custom validator for event date ranges (for combined validation)
|
||||
pub fn validate_date_range(start_date: &DateTime<Utc>, end_date: &DateTime<Utc>) -> Result<(), ValidationError> {
|
||||
if start_date <= end_date {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("date_range"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct EventsCreateRequestDto {
|
||||
#[validate(length(min = 1, max = 100, message = "Name must be between 1 and 100 characters"))]
|
||||
pub name: String,
|
||||
|
||||
#[validate(length(min = 1, max = 1000, message = "Description must be between 1 and 1000 characters"))]
|
||||
pub description: String,
|
||||
|
||||
#[validate(custom(
|
||||
function = "validate_url",
|
||||
message = "Detail link must be a valid HTTP/HTTPS URL"
|
||||
))]
|
||||
pub detail_link: String,
|
||||
|
||||
#[validate(range(min = 0.0, max = 1_000_000.0, message = "Price must be between 0 and 1,000,000"))]
|
||||
pub price: f64,
|
||||
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
#[validate(custom(
|
||||
function = "validate_future_date",
|
||||
message = "End date must be in the future"
|
||||
))]
|
||||
pub end_date: DateTime<Utc>,
|
||||
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub start_date: DateTime<Utc>,
|
||||
|
||||
#[validate(length(max = 200, message = "Location name cannot exceed 200 characters"))]
|
||||
pub location: Option<String>,
|
||||
pub is_online: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct EventsUpdateRequestDto {
|
||||
#[validate(length(min = 1, message = "Name is required"))]
|
||||
pub name: String,
|
||||
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub end_date: DateTime<Utc>,
|
||||
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub start_date: DateTime<Utc>,
|
||||
|
||||
#[validate(range(min = 0.0, message = "Price cannot be negative"))]
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub description: String,
|
||||
#[validate(url(message = "Detail link must be a valid URL"))]
|
||||
pub detail_link: String,
|
||||
pub location: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct EventsListItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub created_at: String,
|
||||
pub location: Option<String>,
|
||||
pub is_deleted: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct EventsDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub location: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct EventsQueryDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub is_deleted: bool,
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub location: Option<String>,
|
||||
}
|
||||
|
||||
impl EventsQueryDto {
|
||||
pub fn from(self) -> EventsListItemDto {
|
||||
EventsListItemDto {
|
||||
id: self.id,
|
||||
name: self.name,
|
||||
description: self.description,
|
||||
detail_link: self.detail_link,
|
||||
price: self.price,
|
||||
location: self.location,
|
||||
is_online: self.is_online,
|
||||
start_date: self.start_date,
|
||||
end_date: self.end_date,
|
||||
created_at: self.created_at,
|
||||
is_deleted: self.is_deleted,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
use sea_orm::prelude::*;
|
||||
use sea_orm::{ActiveValue, QueryOrder};
|
||||
use std::time::Instant;
|
||||
use tracing::instrument;
|
||||
use uuid::Uuid; // Added Uuid import
|
||||
use imphnen_entities::seaorm::common::events::{Entity as EventsEntity, Column as EventsColumn, Model as EventsModel};
|
||||
use imphnen_libs::{AppState, MetaRequestDto, ResponseListSuccessDto, AppStatePostgresExt};
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_utils::Result;
|
||||
use crate::events::events_dto::EventsQueryDto;
|
||||
use crate::events::events_schema::EventsSchema;
|
||||
|
||||
pub struct EventsRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> EventsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, meta), err)]
|
||||
pub async fn query_event_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<EventsQueryDto>>> {
|
||||
let now = Instant::now();
|
||||
let page = meta.page.unwrap_or(1);
|
||||
let page_size = 10u64;
|
||||
let _offset = (page - 1) * page_size;
|
||||
|
||||
let mut query = EventsEntity::find()
|
||||
.filter(EventsColumn::IsDeleted.eq(false)); // Add sorting
|
||||
if let Some(sort_by) = &meta.sort_by {
|
||||
match sort_by.as_str() {
|
||||
"created_at" => {
|
||||
if meta.order.as_deref() == Some("desc") {
|
||||
query = query.order_by_desc(EventsColumn::CreatedAt);
|
||||
} else {
|
||||
query = query.order_by_asc(EventsColumn::CreatedAt);
|
||||
}
|
||||
}
|
||||
"name" => {
|
||||
if meta.order.as_deref() == Some("desc") {
|
||||
query = query.order_by_desc(EventsColumn::Name);
|
||||
} else {
|
||||
query = query.order_by_asc(EventsColumn::Name);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
query = query.order_by_desc(EventsColumn::CreatedAt);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
query = query.order_by_desc(EventsColumn::CreatedAt);
|
||||
}
|
||||
|
||||
let paginator = query.paginate(self.state.postgres_db(), page_size);
|
||||
let events: Vec<EventsModel> = paginator.fetch_page(page - 1).await?;
|
||||
|
||||
let res: Vec<EventsQueryDto> = events.into_iter().map(|model| EventsQueryDto {
|
||||
id: model.id.to_string(),
|
||||
name: model.name,
|
||||
description: model.description,
|
||||
detail_link: model.detail_link,
|
||||
price: model.price,
|
||||
is_online: model.is_online,
|
||||
is_deleted: model.is_deleted,
|
||||
start_date: model.start_date.to_rfc3339(),
|
||||
end_date: model.end_date.to_rfc3339(),
|
||||
created_at: model.created_at.to_rfc3339(),
|
||||
updated_at: model.updated_at.to_rfc3339(),
|
||||
location: model.location,
|
||||
}).collect();
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_event_list' took: {elapsed:.2?}");
|
||||
}
|
||||
let data = ResponseListSuccessDto {
|
||||
data: res,
|
||||
meta: None,
|
||||
};
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_event_by_id(&self, id: Uuid) -> Result<EventsQueryDto> {
|
||||
let now = Instant::now();
|
||||
|
||||
let event = EventsEntity::find_by_id(id)
|
||||
.filter(EventsColumn::IsDeleted.eq(false))
|
||||
.one(self.state.postgres_db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Event not found"))?;
|
||||
|
||||
let result = EventsQueryDto {
|
||||
id: event.id.to_string(),
|
||||
name: event.name,
|
||||
description: event.description,
|
||||
detail_link: event.detail_link,
|
||||
price: event.price,
|
||||
is_online: event.is_online,
|
||||
is_deleted: event.is_deleted,
|
||||
start_date: event.start_date.to_rfc3339(),
|
||||
end_date: event.end_date.to_rfc3339(),
|
||||
created_at: event.created_at.to_rfc3339(),
|
||||
updated_at: event.updated_at.to_rfc3339(),
|
||||
location: event.location,
|
||||
};
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_event_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_create_event(&self, data: EventsSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let active_model = imphnen_entities::seaorm::common::events::ActiveModel {
|
||||
id: ActiveValue::Set(Uuid::parse_str(&data.id)?),
|
||||
name: ActiveValue::Set(data.name),
|
||||
description: ActiveValue::Set(data.description),
|
||||
detail_link: ActiveValue::Set(data.detail_link),
|
||||
price: ActiveValue::Set(data.price),
|
||||
is_online: ActiveValue::Set(data.is_online),
|
||||
is_deleted: ActiveValue::Set(data.is_deleted),
|
||||
location: ActiveValue::Set(data.location),
|
||||
start_date: ActiveValue::Set(chrono::DateTime::parse_from_rfc3339(&data.start_date)?.with_timezone(&chrono::Utc)),
|
||||
end_date: ActiveValue::Set(chrono::DateTime::parse_from_rfc3339(&data.end_date)?.with_timezone(&chrono::Utc)),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
};
|
||||
|
||||
let _result = EventsEntity::insert(active_model).exec(self.state.postgres_db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_event' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success create event".into())
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_update_event(&self, data: EventsSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let existing = self.query_event_by_id(Uuid::parse_str(&data.id)?).await?;
|
||||
if existing.is_deleted {
|
||||
return Err(AppError::BadRequestError("Event already deleted".to_string()));
|
||||
}
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::common::events::ActiveModel = EventsEntity::find_by_id(Uuid::parse_str(&data.id)?)
|
||||
.one(self.state.postgres_db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Event not found"))?
|
||||
.into();
|
||||
|
||||
active_model.name = ActiveValue::Set(data.name);
|
||||
active_model.description = ActiveValue::Set(data.description);
|
||||
active_model.detail_link = ActiveValue::Set(data.detail_link);
|
||||
active_model.price = ActiveValue::Set(data.price);
|
||||
active_model.is_online = ActiveValue::Set(data.is_online);
|
||||
active_model.location = ActiveValue::Set(data.location);
|
||||
active_model.start_date = ActiveValue::Set(chrono::DateTime::parse_from_rfc3339(&data.start_date)?.with_timezone(&chrono::Utc));
|
||||
active_model.end_date = ActiveValue::Set(chrono::DateTime::parse_from_rfc3339(&data.end_date)?.with_timezone(&chrono::Utc));
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
active_model.update(self.state.postgres_db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_event' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success update event".into())
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_event(&self, id: Uuid) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let event = self.query_event_by_id(id).await?;
|
||||
if event.is_deleted {
|
||||
return Err(AppError::NotFoundError("Event not found".to_string()));
|
||||
}
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::common::events::ActiveModel = EventsEntity::find_by_id(id)
|
||||
.one(self.state.postgres_db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Event not found"))?
|
||||
.into();
|
||||
|
||||
active_model.is_deleted = ActiveValue::Set(true);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
active_model.update(self.state.postgres_db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_delete_event' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success delete event".into())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use imphnen_utils::get_iso_date;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::events_dto::{
|
||||
EventsCreateRequestDto, EventsQueryDto, EventsUpdateRequestDto,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct EventsSchema {
|
||||
pub id: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub is_deleted: bool,
|
||||
pub name: String,
|
||||
pub end_date: String,
|
||||
pub start_date: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub location: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for EventsSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
name: String::new(),
|
||||
description: String::new(),
|
||||
detail_link: String::new(),
|
||||
price: 0.0,
|
||||
location: None,
|
||||
is_online: false,
|
||||
is_deleted: false,
|
||||
start_date: String::new(),
|
||||
end_date: String::new(),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EventsSchema {
|
||||
pub fn from(dto: EventsQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id,
|
||||
name: dto.name,
|
||||
description: dto.description,
|
||||
detail_link: dto.detail_link,
|
||||
price: dto.price,
|
||||
location: dto.location,
|
||||
is_online: dto.is_online,
|
||||
is_deleted: false,
|
||||
start_date: dto.start_date,
|
||||
end_date: dto.end_date,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create(payload: EventsCreateRequestDto) -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
detail_link: payload.detail_link,
|
||||
price: payload.price,
|
||||
location: payload.location,
|
||||
is_online: payload.is_online,
|
||||
is_deleted: false,
|
||||
end_date: payload.end_date.to_string(),
|
||||
start_date: payload.start_date.to_string(),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(payload: EventsUpdateRequestDto, id: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
name: payload.name,
|
||||
price: payload.price,
|
||||
location: payload.location,
|
||||
is_online: payload.is_online,
|
||||
description: payload.description,
|
||||
detail_link: payload.detail_link,
|
||||
end_date: payload.end_date.to_string(),
|
||||
start_date: payload.start_date.to_string(),
|
||||
updated_at: get_iso_date(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use super::{
|
||||
events_dto::{
|
||||
EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto, EventsQueryDto,
|
||||
EventsUpdateRequestDto,
|
||||
},
|
||||
events_repository::EventsRepository,
|
||||
events_schema::EventsSchema,
|
||||
};
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use imphnen_libs::{
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
use imphnen_utils::{
|
||||
common_response, success_list_response, success_response, validate_request,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct EventsService;
|
||||
|
||||
impl EventsService {
|
||||
pub async fn get_event_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||
let repo = EventsRepository::new(state);
|
||||
match repo.query_event_list(meta).await {
|
||||
Ok(data) => {
|
||||
let items: Vec<EventsListItemDto> = data
|
||||
.data
|
||||
.into_iter()
|
||||
.filter(|e| !e.is_deleted)
|
||||
.map(EventsQueryDto::from)
|
||||
.collect();
|
||||
let response = ResponseListSuccessDto {
|
||||
data: items,
|
||||
meta: data.meta,
|
||||
};
|
||||
success_list_response(response)
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_event_by_id(state: &AppState, id: Uuid) -> Response {
|
||||
let repo = EventsRepository::new(state);
|
||||
match repo.query_event_by_id(id).await {
|
||||
Ok(event) if !event.is_deleted => success_response(ResponseSuccessDto {
|
||||
data: EventsDetailItemDto {
|
||||
id: event.id,
|
||||
name: event.name,
|
||||
description: event.description,
|
||||
detail_link: event.detail_link,
|
||||
price: event.price,
|
||||
is_online: event.is_online,
|
||||
start_date: event.start_date,
|
||||
end_date: event.end_date,
|
||||
created_at: event.created_at,
|
||||
updated_at: event.updated_at,
|
||||
location: event.location,
|
||||
},
|
||||
}),
|
||||
Ok(_) => common_response(StatusCode::NOT_FOUND, "Event not found"),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_event(
|
||||
state: &AppState,
|
||||
payload: EventsCreateRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = EventsRepository::new(state);
|
||||
let schema = EventsSchema::create(payload);
|
||||
match repo.query_create_event(schema).await {
|
||||
Ok(msg) => common_response(StatusCode::CREATED, msg.as_str()),
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_event(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
payload: EventsUpdateRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = EventsRepository::new(state);
|
||||
let schema = EventsSchema::update(payload, id);
|
||||
match repo.query_update_event(schema).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, msg.as_str()),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_event(state: &AppState, id: Uuid) -> Response {
|
||||
let repo = EventsRepository::new(state);
|
||||
match repo.query_delete_event(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, msg.as_str()),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, patch, post},
|
||||
};
|
||||
|
||||
pub mod events_controller;
|
||||
pub mod events_dto;
|
||||
pub mod events_repository;
|
||||
pub mod events_schema;
|
||||
pub mod events_service;
|
||||
|
||||
// Export only the necessary public items
|
||||
pub use events_dto::{
|
||||
EventsCreateRequestDto,
|
||||
EventsUpdateRequestDto,
|
||||
EventsListItemDto,
|
||||
EventsDetailItemDto,
|
||||
};
|
||||
pub use events_controller::{
|
||||
get_event_list,
|
||||
get_event_by_id,
|
||||
post_create_event,
|
||||
patch_update_event,
|
||||
delete_event,
|
||||
};
|
||||
|
||||
pub fn events_public_routes() -> Router {
|
||||
Router::new()
|
||||
.route("/cms/landing/events", get(get_event_list))
|
||||
.route("/cms/landing/events/detail/{id}", get(get_event_by_id))
|
||||
}
|
||||
|
||||
pub fn events_protected_routes() -> Router {
|
||||
Router::new()
|
||||
.route("/cms/landing/events/create", post(post_create_event))
|
||||
.route("/cms/landing/events/update/{id}", patch(patch_update_event))
|
||||
.route("/cms/landing/events/delete/{id}", delete(delete_event))
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod events;
|
||||
pub mod testimonials;
|
||||
|
||||
pub use events::events_public_routes;
|
||||
pub use events::events_protected_routes;
|
||||
pub use testimonials::testimonials_public_routes;
|
||||
pub use testimonials::testimonials_protected_routes;
|
||||
@@ -0,0 +1,38 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, patch, post},
|
||||
};
|
||||
|
||||
pub mod testimonials_controller;
|
||||
pub mod testimonials_dto;
|
||||
pub mod testimonials_repository;
|
||||
pub mod testimonials_schema;
|
||||
pub mod testimonials_service;
|
||||
|
||||
// Export only the necessary public items
|
||||
pub use testimonials_dto::{
|
||||
TestimonialsCreateRequestDto,
|
||||
TestimonialsUpdateRequestDto,
|
||||
TestimonialsListItemDto,
|
||||
TestimonialsDetailItemDto,
|
||||
};
|
||||
pub use testimonials_controller::{
|
||||
get_testimonial_list,
|
||||
get_testimonial_by_id,
|
||||
post_create_testimonial,
|
||||
patch_update_testimonial,
|
||||
delete_testimonial,
|
||||
};
|
||||
|
||||
pub fn testimonials_public_routes() -> Router {
|
||||
Router::new()
|
||||
.route("/cms/landing/testimonials", get(get_testimonial_list))
|
||||
.route("/cms/landing/testimonials/detail/{id}", get(get_testimonial_by_id))
|
||||
}
|
||||
|
||||
pub fn testimonials_protected_routes() -> Router {
|
||||
Router::new()
|
||||
.route("/cms/landing/testimonials/create", post(post_create_testimonial))
|
||||
.route("/cms/landing/testimonials/update/{id}", patch(patch_update_testimonial))
|
||||
.route("/cms/landing/testimonials/delete/{id}", delete(delete_testimonial))
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
use super::{
|
||||
testimonials_dto::{
|
||||
TestimonialsCreateRequestDto, TestimonialsDetailItemDto,
|
||||
TestimonialsListItemDto, TestimonialsUpdateRequestDto,
|
||||
},
|
||||
testimonials_service::TestimonialsService,
|
||||
};
|
||||
use axum::extract::{Path, Query};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Extension, http::HeaderMap};
|
||||
use imphnen_iam::{UsersDetailQueryDto, require_auth};
|
||||
use imphnen_libs::{
|
||||
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
|
||||
ResponseSuccessDto, ValidatedJson,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::common_response;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/cms/landing/testimonials",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Get testimonial list", body = ResponseListSuccessDto<Vec<TestimonialsListItemDto>>)
|
||||
),
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn get_testimonial_list(
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
TestimonialsService::get_testimonial_list(&state, meta).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/cms/landing/testimonials/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Testimonial ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Get testimonial by ID", body = ResponseSuccessDto<TestimonialsDetailItemDto>)
|
||||
),
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn get_testimonial_by_id(
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let parsed_id = match Uuid::parse_str(&id) {
|
||||
Ok(uuid) => uuid,
|
||||
Err(e) => return common_response(axum::http::StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
|
||||
};
|
||||
TestimonialsService::get_testimonial_by_id(&state, parsed_id).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/cms/landing/testimonials/create",
|
||||
request_body = TestimonialsCreateRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "[USER] Create new testimonial", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn post_create_testimonial(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
|
||||
ValidatedJson(payload): ValidatedJson<TestimonialsCreateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
require_auth!(headers, state, {
|
||||
TestimonialsService::create_testimonial(&state, payload, &authenticated_user).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
patch,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/cms/landing/testimonials/update/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Testimonial ID")
|
||||
),
|
||||
request_body = TestimonialsUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[USER] Update testimonial", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn patch_update_testimonial(
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<String>,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
|
||||
ValidatedJson(payload): ValidatedJson<TestimonialsUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
require_auth!(headers, state, {
|
||||
TestimonialsService::update_testimonial(&state, id, payload, &authenticated_user).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/cms/landing/testimonials/delete/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Testimonial ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Soft delete testimonial", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn delete_testimonial(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
require_auth!(headers, state, {
|
||||
let parsed_id = match Uuid::parse_str(&id) {
|
||||
Ok(uuid) => uuid,
|
||||
Err(e) => return common_response(axum::http::StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
|
||||
};
|
||||
TestimonialsService::delete_testimonial(&state, parsed_id, &authenticated_user).await
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
// Custom validator for content length and format
|
||||
pub fn validate_testimonial_content(content: &str) -> Result<(), ValidationError> {
|
||||
lazy_static! {
|
||||
static ref CONTENT_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9\s.,!?'-]+$").unwrap();
|
||||
}
|
||||
if CONTENT_REGEX.is_match(content) && content.len() <= 1000 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("invalid_content"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct TestimonialsCreateRequestDto {
|
||||
#[validate(length(min = 1, max = 100, message = "Role must be between 1 and 100 characters"))]
|
||||
pub role: String,
|
||||
|
||||
#[validate(length(
|
||||
min = 1,
|
||||
max = 1000,
|
||||
message = "Content must be between 1 and 1000 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_testimonial_content",
|
||||
message = "Content contains invalid characters or is too long"
|
||||
))]
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct TestimonialsUpdateRequestDto {
|
||||
#[validate(length(min = 1, max = 100, message = "Role must be between 1 and 100 characters"))]
|
||||
pub role: String,
|
||||
|
||||
#[validate(length(
|
||||
min = 1,
|
||||
max = 1000,
|
||||
message = "Content must be between 1 and 1000 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_testimonial_content",
|
||||
message = "Content contains invalid characters or is too long"
|
||||
))]
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TestimonialsListItemDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub created_at: String,
|
||||
pub is_deleted: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TestimonialsDetailItemDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TestimonialsQueryDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl TestimonialsQueryDto {
|
||||
pub fn from(self) -> TestimonialsListItemDto {
|
||||
TestimonialsListItemDto {
|
||||
id: self.id,
|
||||
user_id: self.user_id,
|
||||
user_fullname: self.user_fullname,
|
||||
role: self.role,
|
||||
content: self.content,
|
||||
created_at: self.created_at,
|
||||
is_deleted: self.is_deleted,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
use sea_orm::prelude::*;
|
||||
use sea_orm::{ActiveValue, ActiveModelTrait, QueryOrder};
|
||||
use std::time::Instant;
|
||||
use tracing::instrument;
|
||||
use uuid::Uuid; // Added Uuid import
|
||||
use imphnen_entities::seaorm::common::testimonials::{Entity as TestimonialsEntity, Column as TestimonialsColumn};
|
||||
use imphnen_entities::seaorm::auth::users::Entity as UsersEntity;
|
||||
use imphnen_libs::{AppState, MetaRequestDto, ResponseListSuccessDto, AppStatePostgresExt};
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_utils::Result;
|
||||
use crate::testimonials::testimonials_schema::TestimonialsSchema;
|
||||
use crate::testimonials::testimonials_dto::TestimonialsQueryDto;
|
||||
|
||||
pub struct TestimonialsRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> TestimonialsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
fn get_db(&self) -> &DatabaseConnection {
|
||||
self.state.postgres_db()
|
||||
}
|
||||
|
||||
#[instrument(skip(self, meta), err)]
|
||||
pub async fn query_testimonial_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<TestimonialsQueryDto>>> {
|
||||
let now = Instant::now();
|
||||
let db = self.get_db();
|
||||
|
||||
let page = meta.page.unwrap_or(1);
|
||||
let per_page = meta.per_page.unwrap_or(10);
|
||||
|
||||
let mut query = TestimonialsEntity::find()
|
||||
.filter(TestimonialsColumn::IsDeleted.eq(false))
|
||||
.find_also_related(UsersEntity); // Apply sorting
|
||||
if let Some(sort_by) = &meta.sort_by {
|
||||
let order = meta.order.as_deref().unwrap_or("asc");
|
||||
match sort_by.as_str() {
|
||||
"created_at" => {
|
||||
if order == "desc" {
|
||||
query = query.order_by_desc(TestimonialsColumn::CreatedAt);
|
||||
} else {
|
||||
query = query.order_by_asc(TestimonialsColumn::CreatedAt);
|
||||
}
|
||||
}
|
||||
"updated_at" => {
|
||||
if order == "desc" {
|
||||
query = query.order_by_desc(TestimonialsColumn::UpdatedAt);
|
||||
} else {
|
||||
query = query.order_by_asc(TestimonialsColumn::UpdatedAt);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
query = query.order_by_desc(TestimonialsColumn::CreatedAt);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
query = query.order_by_desc(TestimonialsColumn::CreatedAt);
|
||||
}
|
||||
|
||||
let paginator = query.paginate(db, per_page);
|
||||
let total_pages = paginator.num_pages().await?;
|
||||
let testimonials = paginator.fetch_page(page - 1).await?;
|
||||
|
||||
let data: Vec<TestimonialsQueryDto> = testimonials
|
||||
.into_iter()
|
||||
.filter_map(|(testimonial, user)| {
|
||||
user.map(|u| TestimonialsQueryDto {
|
||||
id: testimonial.id.to_string(),
|
||||
user_id: testimonial.user_id.to_string(),
|
||||
user_fullname: format!("{} {}", u.first_name.as_deref().unwrap_or(""), u.last_name.as_deref().unwrap_or("")).trim().to_string(),
|
||||
role: testimonial.role,
|
||||
content: testimonial.content,
|
||||
is_deleted: testimonial.is_deleted,
|
||||
created_at: testimonial.created_at.to_rfc3339(),
|
||||
updated_at: testimonial.updated_at.to_rfc3339(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_testimonial_list' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let response = ResponseListSuccessDto {
|
||||
data,
|
||||
meta: Some(imphnen_entities::MetaResponseDto {
|
||||
page: Some(page),
|
||||
per_page: Some(per_page),
|
||||
total: Some(total_pages),
|
||||
}),
|
||||
};
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_testimonial_by_id(
|
||||
&self,
|
||||
id: Uuid,
|
||||
) -> Result<TestimonialsQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = self.get_db();
|
||||
|
||||
let (testimonial, user) = TestimonialsEntity::find_by_id(id)
|
||||
.filter(TestimonialsColumn::IsDeleted.eq(false))
|
||||
.find_also_related(UsersEntity)
|
||||
.one(db)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Testimonial not found"))?;
|
||||
|
||||
let user = user.ok_or_else(|| anyhow::anyhow!("User not found for testimonial"))?;
|
||||
|
||||
let result = TestimonialsQueryDto {
|
||||
id: testimonial.id.to_string(),
|
||||
user_id: testimonial.user_id.to_string(),
|
||||
user_fullname: format!("{} {}", user.first_name.as_deref().unwrap_or(""), user.last_name.as_deref().unwrap_or("")).trim().to_string(),
|
||||
role: testimonial.role,
|
||||
content: testimonial.content,
|
||||
is_deleted: testimonial.is_deleted,
|
||||
created_at: testimonial.created_at.to_rfc3339(),
|
||||
updated_at: testimonial.updated_at.to_rfc3339(),
|
||||
};
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_testimonial_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_create_testimonial(
|
||||
&self,
|
||||
data: TestimonialsSchema,
|
||||
) -> Result<TestimonialsSchema> {
|
||||
let now = Instant::now();
|
||||
let db = self.get_db();
|
||||
|
||||
let active_model = imphnen_entities::seaorm::common::testimonials::ActiveModel {
|
||||
id: ActiveValue::Set(Uuid::parse_str(&data.id)?),
|
||||
user_id: ActiveValue::Set(Uuid::parse_str(&data.user_id)?),
|
||||
role: ActiveValue::Set(data.role.clone()),
|
||||
content: ActiveValue::Set(data.content.clone()),
|
||||
is_deleted: ActiveValue::Set(data.is_deleted),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
};
|
||||
|
||||
let inserted = active_model.insert(db).await?;
|
||||
let created_testimonial = TestimonialsSchema {
|
||||
id: inserted.id.to_string(),
|
||||
user_id: inserted.user_id.to_string(),
|
||||
role: inserted.role,
|
||||
content: inserted.content,
|
||||
is_deleted: inserted.is_deleted,
|
||||
created_at: inserted.created_at.to_rfc3339(),
|
||||
updated_at: inserted.updated_at.to_rfc3339(),
|
||||
};
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_testimonial' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(created_testimonial)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_update_testimonial(
|
||||
&self,
|
||||
data: TestimonialsSchema,
|
||||
) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = self.get_db();
|
||||
|
||||
let existing = self.query_testimonial_by_id(Uuid::parse_str(&data.id)?).await?;
|
||||
if existing.is_deleted {
|
||||
return Err(AppError::BadRequestError("Testimonial already deleted".to_string()));
|
||||
}
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::common::testimonials::ActiveModel = TestimonialsEntity::find_by_id(Uuid::parse_str(&data.id)?)
|
||||
.one(db)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Testimonial not found"))?
|
||||
.into();
|
||||
|
||||
active_model.role = ActiveValue::Set(data.role.clone());
|
||||
active_model.content = ActiveValue::Set(data.content.clone());
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
active_model.update(db).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_testimonial' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success update testimonial".into())
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_testimonial(&self, id: Uuid) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = self.get_db();
|
||||
|
||||
let testimonial = self.query_testimonial_by_id(id).await?;
|
||||
if testimonial.is_deleted {
|
||||
return Err(AppError::NotFoundError("Testimonial not found".to_string()));
|
||||
}
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::common::testimonials::ActiveModel = TestimonialsEntity::find_by_id(id)
|
||||
.one(db)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?
|
||||
.into();
|
||||
|
||||
active_model.is_deleted = ActiveValue::Set(true);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
active_model.update(db).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_delete_testimonial' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success delete testimonial".into())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use imphnen_utils::get_iso_date;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::testimonials_dto::{
|
||||
TestimonialsCreateRequestDto, TestimonialsQueryDto, TestimonialsUpdateRequestDto,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TestimonialsSchema {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl Default for TestimonialsSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
user_id: Uuid::new_v4().to_string(),
|
||||
role: String::new(),
|
||||
content: String::new(),
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TestimonialsSchema {
|
||||
pub fn from(dto: TestimonialsQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id,
|
||||
user_id: dto.user_id,
|
||||
role: dto.role,
|
||||
content: dto.content,
|
||||
is_deleted: dto.is_deleted,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create(payload: TestimonialsCreateRequestDto, user_id: &str) -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
user_id: user_id.to_string(),
|
||||
role: payload.role,
|
||||
content: payload.content,
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(
|
||||
payload: TestimonialsUpdateRequestDto,
|
||||
id: String,
|
||||
user_id: &str,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
role: payload.role,
|
||||
content: payload.content,
|
||||
updated_at: get_iso_date(),
|
||||
user_id: user_id.to_string(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use super::{
|
||||
testimonials_dto::{
|
||||
TestimonialsCreateRequestDto, TestimonialsDetailItemDto,
|
||||
TestimonialsListItemDto, TestimonialsUpdateRequestDto,
|
||||
},
|
||||
testimonials_repository::TestimonialsRepository,
|
||||
testimonials_schema::TestimonialsSchema,
|
||||
};
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use imphnen_libs::{
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
use imphnen_utils::{
|
||||
common_response, success_list_response, success_response, success_created_response, validate_request,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct TestimonialsService;
|
||||
|
||||
impl TestimonialsService {
|
||||
pub async fn get_testimonial_list(
|
||||
state: &AppState,
|
||||
meta: MetaRequestDto,
|
||||
) -> Response {
|
||||
let repo = TestimonialsRepository::new(state);
|
||||
match repo.query_testimonial_list(meta).await {
|
||||
Ok(data) => {
|
||||
let items: Vec<TestimonialsListItemDto> = data
|
||||
.data
|
||||
.into_iter()
|
||||
.filter(|e| !e.is_deleted)
|
||||
.map(|e| e.from())
|
||||
.collect();
|
||||
let response = ResponseListSuccessDto {
|
||||
data: items,
|
||||
meta: data.meta,
|
||||
};
|
||||
success_list_response(response)
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_testimonial_by_id(state: &AppState, id: Uuid) -> Response {
|
||||
let repo = TestimonialsRepository::new(state);
|
||||
match repo.query_testimonial_by_id(id).await {
|
||||
Ok(testimonial) if !testimonial.is_deleted => {
|
||||
success_response(ResponseSuccessDto {
|
||||
data: TestimonialsDetailItemDto {
|
||||
id: testimonial.id,
|
||||
user_id: testimonial.user_id,
|
||||
user_fullname: testimonial.user_fullname,
|
||||
role: testimonial.role,
|
||||
content: testimonial.content,
|
||||
created_at: testimonial.created_at,
|
||||
updated_at: testimonial.updated_at,
|
||||
},
|
||||
})
|
||||
}
|
||||
Ok(_) => common_response(StatusCode::NOT_FOUND, "Testimonial not found"),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_testimonial(
|
||||
state: &AppState,
|
||||
payload: TestimonialsCreateRequestDto,
|
||||
authenticated_user: &imphnen_iam::UsersDetailQueryDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = TestimonialsRepository::new(state);
|
||||
let schema = TestimonialsSchema::create(payload, &authenticated_user.id);
|
||||
match repo.query_create_testimonial(schema).await {
|
||||
Ok(created_testimonial) => {
|
||||
success_created_response(ResponseSuccessDto {
|
||||
data: TestimonialsDetailItemDto {
|
||||
id: created_testimonial.id,
|
||||
user_id: created_testimonial.user_id,
|
||||
user_fullname: authenticated_user.fullname.clone(),
|
||||
role: created_testimonial.role,
|
||||
content: created_testimonial.content,
|
||||
created_at: created_testimonial.created_at,
|
||||
updated_at: created_testimonial.updated_at,
|
||||
},
|
||||
})
|
||||
}
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_testimonial(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
payload: TestimonialsUpdateRequestDto,
|
||||
authenticated_user: &imphnen_iam::UsersDetailQueryDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = TestimonialsRepository::new(state);
|
||||
let schema = TestimonialsSchema::update(payload, id, &authenticated_user.id);
|
||||
match repo.query_update_testimonial(schema).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, msg.as_str()),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_testimonial(
|
||||
state: &AppState,
|
||||
id: Uuid,
|
||||
_authenticated_user: &imphnen_iam::UsersDetailQueryDto,
|
||||
) -> Response {
|
||||
let repo = TestimonialsRepository::new(state);
|
||||
match repo.query_delete_testimonial(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, msg.as_str()),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
pub mod landing;
|
||||
|
||||
pub use landing::events;
|
||||
pub use landing::testimonials;
|
||||
pub use landing::events::events_public_routes;
|
||||
pub use landing::events::events_protected_routes;
|
||||
pub use landing::testimonials::testimonials_public_routes;
|
||||
pub use landing::testimonials::testimonials_protected_routes;
|
||||
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "imphnen-dimentorin"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
imphnen-libs.workspace = true
|
||||
imphnen-utils.workspace = true
|
||||
imphnen-entities.workspace = true
|
||||
imphnen-iam.workspace = true
|
||||
imphnen-middleware.workspace = true
|
||||
axum.workspace = true
|
||||
async-trait.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
utoipa.workspace = true
|
||||
lazy_static.workspace = true
|
||||
regex.workspace = true
|
||||
validator.workspace = true
|
||||
axum-test.workspace = true
|
||||
rand.workspace = true
|
||||
tokio.workspace = true
|
||||
chrono.workspace = true
|
||||
anyhow.workspace = true
|
||||
tower-http.workspace = true
|
||||
utoipa-swagger-ui.workspace = true
|
||||
tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
sea-orm.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dotenvy.workspace = true
|
||||
http-body-util.workspace = true
|
||||
@@ -0,0 +1,12 @@
|
||||
pub mod v1;
|
||||
|
||||
// Explicitly export only what's needed from v1
|
||||
pub use v1::dimentorin_router;
|
||||
pub use v1::mentors::mentors_router;
|
||||
pub use v1::sessions::{
|
||||
sessions_router, BookSessionRequestDto, BookSessionResponseDto, MentorAvailabilityDto,
|
||||
SessionFeedbackRequestDto, SessionFeedbackResponseDto, SessionListItemDto,
|
||||
SessionListResponseDto, UpdateSessionStatusRequestDto, UpdateSessionStatusResponseDto,
|
||||
AvailabilitySlotDto,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
use super::{
|
||||
MentorDetailResponseDto, MentorListResponseDto, MentorUpdateRequestDto,
|
||||
MentorUserRegisterRequestDto, MentorVerifyRequestDto, MentorsService,
|
||||
};
|
||||
use crate::v1::mentors::mentors_dto::MentorRegisterResponseDto;
|
||||
use ::axum::{
|
||||
extract::{Extension, Path, Query},
|
||||
http::HeaderMap,
|
||||
response::Response,
|
||||
};
|
||||
use imphnen_entities::MetaRequestDto;
|
||||
use uuid::Uuid;
|
||||
use axum::http::StatusCode;
|
||||
use imphnen_utils::common_response;
|
||||
use imphnen_libs::{AppState, ValidatedJson};
|
||||
use imphnen_iam::{PermissionsEnum, require_permissions};
|
||||
use imphnen_utils::extract_email;
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/mentors/create",
|
||||
request_body = MentorUserRegisterRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Mentor registered successfully", body = MentorRegisterResponseDto),
|
||||
(status = 400, description = "[PUBLIC] Bad request - validation error"),
|
||||
(status = 409, description = "[PUBLIC] Conflict - user already has mentor profile"),
|
||||
(status = 500, description = "[PUBLIC] Internal server error")
|
||||
),
|
||||
tag = "Mentors"
|
||||
)]
|
||||
pub async fn post_register_mentor(
|
||||
Extension(app_state): Extension<AppState>,
|
||||
ValidatedJson(dto): ValidatedJson<MentorUserRegisterRequestDto>,
|
||||
) -> Response {
|
||||
MentorsService::register_mentor(&app_state, dto).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors",
|
||||
params(
|
||||
("page" = Option<u64>, Query, description = "Page number"),
|
||||
("per_page" = Option<u64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search query"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Sort order (ASC/DESC)"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get list of mentors", body = Vec<MentorListResponseDto>),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
)
|
||||
)]
|
||||
pub async fn get_mentor_list(
|
||||
headers: HeaderMap,
|
||||
Extension(app_state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> Response {
|
||||
require_permissions!(headers, app_state, [PermissionsEnum::ReadListMentors], {
|
||||
MentorsService::get_mentor_list(&app_state, meta).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get mentor by ID", body = MentorDetailResponseDto),
|
||||
(status = 404, description = "[ADMIN] Mentor not found"),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
)
|
||||
)]
|
||||
pub async fn get_mentor_by_id(
|
||||
headers: HeaderMap,
|
||||
Extension(app_state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
// Validate UUID format
|
||||
let _mentor_uuid = match Uuid::parse_str(&id) {
|
||||
Ok(uuid) => uuid,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid mentor ID format. Must be a valid UUID."
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
require_permissions!(headers, app_state, [PermissionsEnum::ReadDetailMentors], {
|
||||
MentorsService::get_mentor_by_id(&app_state, &id).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/mentors/update/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID")
|
||||
),
|
||||
request_body = MentorUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Mentor updated successfully", body = MentorDetailResponseDto),
|
||||
(status = 400, description = "[ADMIN] Bad request - validation error"),
|
||||
(status = 404, description = "[ADMIN] Mentor not found"),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors - Admin",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
)
|
||||
)]
|
||||
pub async fn put_update_mentor(
|
||||
headers: HeaderMap,
|
||||
Extension(app_state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(dto): ValidatedJson<MentorUpdateRequestDto>,
|
||||
) -> Response {
|
||||
// Validate UUID format
|
||||
let _mentor_uuid = match Uuid::parse_str(&id) {
|
||||
Ok(uuid) => uuid,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid mentor ID format. Must be a valid UUID."
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
require_permissions!(headers, app_state, [PermissionsEnum::UpdateMentors], {
|
||||
MentorsService::update_mentor(&app_state, &id, dto).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/v1/mentors/delete/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Mentor deleted successfully"),
|
||||
(status = 404, description = "[ADMIN] Mentor not found"),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors - Admin",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
)
|
||||
)]
|
||||
pub async fn delete_mentor(
|
||||
headers: HeaderMap,
|
||||
Extension(app_state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
// Validate UUID format
|
||||
let _mentor_uuid = match Uuid::parse_str(&id) {
|
||||
Ok(uuid) => uuid,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid mentor ID format. Must be a valid UUID."
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
require_permissions!(headers, app_state, [PermissionsEnum::DeleteMentors], {
|
||||
MentorsService::delete_mentor(&app_state, &id).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/mentors/verify/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID")
|
||||
),
|
||||
request_body = MentorVerifyRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Mentor verified successfully", body = MentorDetailResponseDto),
|
||||
(status = 400, description = "[ADMIN] Bad request - validation error"),
|
||||
(status = 404, description = "[ADMIN] Mentor not found"),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors - Admin",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
)
|
||||
)]
|
||||
pub async fn put_verify_mentor(
|
||||
headers: HeaderMap,
|
||||
Extension(app_state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(dto): ValidatedJson<MentorVerifyRequestDto>,
|
||||
) -> Response {
|
||||
// Validate UUID format
|
||||
let _mentor_uuid = match Uuid::parse_str(&id) {
|
||||
Ok(uuid) => uuid,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid mentor ID format. Must be a valid UUID."
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
require_permissions!(headers, app_state, [PermissionsEnum::VerifyMentors], {
|
||||
MentorsService::verify_mentor(&app_state, &id, dto).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors/me",
|
||||
responses(
|
||||
(status = 200, description = "[MENTOR] Current user's mentor profile", body = MentorDetailResponseDto),
|
||||
(status = 401, description = "[MENTOR] Unauthorized - invalid token"),
|
||||
(status = 403, description = "[MENTOR] Mentor profile not found for current user"),
|
||||
(status = 500, description = "[MENTOR] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
)
|
||||
)]
|
||||
pub async fn get_mentor_me(
|
||||
headers: HeaderMap,
|
||||
Extension(app_state): Extension<AppState>,
|
||||
) -> Response {
|
||||
require_permissions!(headers.clone(), app_state, [PermissionsEnum::ReadOwnMentorProfile], {
|
||||
let email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return imphnen_utils::common_response(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"Token tidak valid",
|
||||
);
|
||||
}
|
||||
};
|
||||
MentorsService::get_mentor_me(&app_state, &email).await
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/mentors/me/update",
|
||||
request_body = MentorUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[MENTOR] Mentor profile updated successfully", body = MentorDetailResponseDto),
|
||||
(status = 400, description = "[MENTOR] Bad request - validation error"),
|
||||
(status = 401, description = "[MENTOR] Unauthorized - invalid token"),
|
||||
(status = 404, description = "[MENTOR] Mentor profile not found"),
|
||||
(status = 500, description = "[MENTOR] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
)
|
||||
)]
|
||||
pub async fn put_update_mentor_me(
|
||||
headers: HeaderMap,
|
||||
Extension(app_state): Extension<AppState>,
|
||||
ValidatedJson(dto): ValidatedJson<MentorUpdateRequestDto>,
|
||||
) -> Response {
|
||||
require_permissions!(headers.clone(), app_state, [PermissionsEnum::UpdateOwnMentorProfile], {
|
||||
let email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return imphnen_utils::common_response(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"Token tidak valid",
|
||||
);
|
||||
}
|
||||
};
|
||||
MentorsService::update_mentor_me(&app_state, &email, dto).await
|
||||
})
|
||||
}
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/mentors/update",
|
||||
request_body = MentorUpdateRequestDto,
|
||||
responses(
|
||||
(status = 400, description = "[PUBLIC] Bad request - Mentor ID is required for update"),
|
||||
),
|
||||
tag = "Mentors - Admin"
|
||||
)]
|
||||
pub async fn put_update_mentor_no_id() -> Response {
|
||||
imphnen_utils::common_response(
|
||||
axum::http::StatusCode::BAD_REQUEST,
|
||||
"Mentor ID is required for update",
|
||||
)
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors/me/status",
|
||||
responses(
|
||||
(status = 200, description = "[MENTOR] Mentor application status", body = String),
|
||||
(status = 401, description = "[MENTOR] Unauthorized - invalid token"),
|
||||
(status = 403, description = "[MENTOR] No mentor application found for current user"),
|
||||
(status = 500, description = "[MENTOR] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
)
|
||||
)]
|
||||
pub async fn get_mentor_status(
|
||||
headers: HeaderMap,
|
||||
Extension(app_state): Extension<AppState>,
|
||||
) -> Response {
|
||||
require_permissions!(headers.clone(), app_state, [PermissionsEnum::ReadOwnMentorStatus], {
|
||||
let email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return imphnen_utils::common_response(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"Token tidak valid",
|
||||
);
|
||||
}
|
||||
};
|
||||
MentorsService::get_mentor_status(&app_state, &email).await
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
use crate::v1::mentors::MentorSchema;
|
||||
use crate::v1::sessions::sessions_schema::Thing;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MentorListResponseDto {
|
||||
pub id: String,
|
||||
pub fullname: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub status: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct MentorDetailWithUserDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
// Personal data is now in UsersSchema, access via user_id
|
||||
// Removed: fullname, email, legal_name, identity_document_url,
|
||||
// phone_for_verification, bio, linkedin_url, github_url, cv_url
|
||||
pub industries: Vec<String>,
|
||||
pub expertise: Vec<String>,
|
||||
pub languages: Vec<String>,
|
||||
pub current_company: String,
|
||||
pub current_role: String,
|
||||
pub years_of_experience: i32,
|
||||
pub topics_of_interest: Vec<String>,
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
pub availability_commitment: String,
|
||||
pub mentoring_rate: f64,
|
||||
pub status: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MentorDetailResponseDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
// Personal data fields from UsersSchema
|
||||
pub fullname: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub legal_name: Option<String>,
|
||||
pub gender: Option<String>,
|
||||
pub domicile: Option<String>,
|
||||
pub phone_for_verification: Option<String>,
|
||||
pub bio: Option<String>,
|
||||
pub last_education: Option<String>,
|
||||
pub linkedin_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub cv_url: Option<String>,
|
||||
pub portfolio_url: Option<String>,
|
||||
// Professional data from MentorSchema
|
||||
pub industries: Vec<String>,
|
||||
pub expertise: Vec<String>,
|
||||
pub languages: Vec<String>,
|
||||
pub current_company: String,
|
||||
pub current_role: String,
|
||||
pub years_of_experience: i32,
|
||||
pub topics_of_interest: Vec<String>,
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
pub availability_commitment: String,
|
||||
pub mentoring_rate: f64,
|
||||
pub status: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct MentorRegisterResponseDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub email: Option<String>,
|
||||
pub status: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct MentorUpdateRequestDto {
|
||||
#[validate(length(
|
||||
min = 3,
|
||||
message = "Legal name must be at least 3 characters"
|
||||
))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legal_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gender: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub domicile: Option<String>,
|
||||
#[validate(length(
|
||||
min = 10,
|
||||
max = 15,
|
||||
message = "Phone must be 10-15 characters"
|
||||
))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_for_verification: Option<String>,
|
||||
#[validate(length(min = 50, message = "Bio must be at least 50 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bio: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub last_education: Option<String>,
|
||||
#[validate(url(message = "Invalid LinkedIn URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linkedin_url: Option<String>,
|
||||
#[validate(url(message = "Invalid GitHub URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub github_url: Option<String>,
|
||||
#[validate(url(message = "Invalid CV URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cv_url: Option<String>,
|
||||
#[validate(url(message = "Invalid portfolio URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub portfolio_url: Option<String>,
|
||||
#[validate(length(min = 1, message = "At least 1 industry required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub industries: Option<Vec<String>>,
|
||||
#[validate(length(min = 1, message = "At least 1 expertise required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub expertise: Option<Vec<String>>,
|
||||
#[validate(length(min = 1, message = "At least 1 language required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub languages: Option<Vec<String>>,
|
||||
#[validate(length(min = 1, message = "Current company required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub current_company: Option<String>,
|
||||
#[validate(length(min = 1, message = "Current role required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub current_role: Option<String>,
|
||||
#[validate(range(min = 2, message = "At least 2 years of experience required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub years_of_experience: Option<i32>,
|
||||
#[validate(length(min = 1, message = "At least 1 topic required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub topics_of_interest: Option<Vec<String>>,
|
||||
#[validate(length(min = 1, message = "At least 1 mentee level required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub preferred_mentee_level: Option<Vec<String>>,
|
||||
#[validate(length(min = 1, message = "At least 1 mentoring format required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub preferred_mentoring_formats: Option<Vec<String>>,
|
||||
#[validate(length(
|
||||
min = 5,
|
||||
message = "Availability commitment must be at least 5 characters"
|
||||
))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub availability_commitment: Option<String>,
|
||||
#[validate(range(min = 1, message = "Amount must be at least 1"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub mentoring_rate_amount: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct MentorUserRegisterRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "imphnen_iam::v1::auth::auth_dto::validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
pub fullname: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_number: Option<String>,
|
||||
#[validate(nested)]
|
||||
pub identity_and_verification: IdentityAndVerification,
|
||||
#[validate(nested)]
|
||||
pub professional_profile: ProfessionalProfile,
|
||||
#[validate(nested)]
|
||||
pub mentoring_logistics: MentoringLogistics,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct MentorRegisterFromTokenRequestDto {
|
||||
#[validate(nested)]
|
||||
pub identity_and_verification: IdentityAndVerification,
|
||||
#[validate(nested)]
|
||||
pub professional_profile: ProfessionalProfile,
|
||||
#[validate(nested)]
|
||||
pub mentoring_logistics: MentoringLogistics,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct IdentityAndVerification {
|
||||
#[validate(length(
|
||||
min = 3,
|
||||
message = "Legal name must be at least 3 characters"
|
||||
))]
|
||||
pub legal_name: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gender: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub domicile: Option<String>,
|
||||
#[validate(url(message = "Invalid identity document URL"))]
|
||||
pub identity_document_url: String,
|
||||
#[validate(length(
|
||||
min = 10,
|
||||
max = 15,
|
||||
message = "Phone must be 10-15 characters"
|
||||
))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_for_verification: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct ProfessionalProfile {
|
||||
#[validate(length(min = 50, message = "Bio must be at least 50 characters"))]
|
||||
pub bio: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub last_education: Option<String>,
|
||||
#[validate(url(message = "Invalid LinkedIn URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linkedin_url: Option<String>,
|
||||
#[validate(url(message = "Invalid GitHub URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub github_url: Option<String>,
|
||||
#[validate(url(message = "Invalid CV URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cv_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub portfolio_url: Option<String>,
|
||||
#[validate(length(min = 1, message = "At least 1 industry required"))]
|
||||
pub industries: Vec<String>,
|
||||
#[validate(length(min = 1, message = "At least 1 expertise required"))]
|
||||
pub expertise: Vec<String>,
|
||||
#[validate(length(min = 1, message = "At least 1 language required"))]
|
||||
pub languages: Vec<String>,
|
||||
#[validate(length(min = 1, message = "Current company required"))]
|
||||
pub current_company: String,
|
||||
#[validate(length(min = 1, message = "Current role required"))]
|
||||
pub current_role: String,
|
||||
#[validate(range(min = 2, message = "At least 2 years of experience required"))]
|
||||
pub years_of_experience: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct MentoringLogistics {
|
||||
#[validate(length(min = 1, message = "At least 1 topic required"))]
|
||||
pub topics_of_interest: Vec<String>,
|
||||
#[validate(length(min = 1, message = "At least 1 mentee level required"))]
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
#[validate(length(min = 1, message = "At least 1 mentoring format required"))]
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
#[validate(length(
|
||||
min = 5,
|
||||
message = "Availability commitment must be at least 5 characters"
|
||||
))]
|
||||
pub availability_commitment: String,
|
||||
#[validate(range(min = 1, message = "Amount must be at least 1"))]
|
||||
pub mentoring_rate_amount: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate, Default)]
|
||||
pub struct MentoringRate {
|
||||
#[validate(range(min = 1, message = "Amount must be at least 1"))]
|
||||
pub amount: u64,
|
||||
#[validate(length(min = 1, message = "Currency is required"))]
|
||||
pub currency: String,
|
||||
#[validate(length(min = 1, message = "Per duration is required"))]
|
||||
pub per_duration: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct MentorInsertDto {
|
||||
pub id: Thing,
|
||||
pub user_id: Option<Thing>,
|
||||
// Personal data removed - now stored in UsersSchema
|
||||
pub industries: Vec<String>,
|
||||
pub expertise: Vec<String>,
|
||||
pub languages: Vec<String>,
|
||||
pub current_company: String,
|
||||
pub current_role: String,
|
||||
pub years_of_experience: i32,
|
||||
pub topics_of_interest: Vec<String>,
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
pub availability_commitment: String,
|
||||
pub mentoring_rate: f64,
|
||||
pub status: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl From<MentorSchema> for MentorInsertDto {
|
||||
fn from(schema: MentorSchema) -> Self {
|
||||
MentorInsertDto {
|
||||
id: schema.id,
|
||||
user_id: schema.user_id,
|
||||
// Personal data removed from MentorSchema
|
||||
industries: schema.industries,
|
||||
expertise: schema.expertise,
|
||||
languages: schema.languages,
|
||||
current_company: schema.current_company,
|
||||
current_role: schema.current_role,
|
||||
years_of_experience: schema.years_of_experience,
|
||||
topics_of_interest: schema.topics_of_interest,
|
||||
preferred_mentee_level: schema.preferred_mentee_level,
|
||||
preferred_mentoring_formats: schema.preferred_mentoring_formats,
|
||||
availability_commitment: schema.availability_commitment,
|
||||
mentoring_rate: schema.mentoring_rate,
|
||||
status: schema.status,
|
||||
is_deleted: schema.is_deleted,
|
||||
created_at: schema.created_at,
|
||||
updated_at: schema.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct MentorVerifyRequestDto {
|
||||
#[validate(length(min = 1, message = "Status is required"))]
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct MentorDetailQueryDto {
|
||||
pub id: Thing,
|
||||
pub user_id: Thing,
|
||||
// Personal data has been moved to UsersSchema
|
||||
// Use user_id to get: fullname, email, legal_name, gender, domicile,
|
||||
// identity_document_url, phone_for_verification, bio, last_education,
|
||||
// linkedin_url, github_url, cv_url, portfolio_url
|
||||
pub industries: Vec<String>,
|
||||
pub expertise: Vec<String>,
|
||||
pub languages: Vec<String>,
|
||||
pub current_company: String,
|
||||
pub current_role: String,
|
||||
pub years_of_experience: i32,
|
||||
pub topics_of_interest: Vec<String>,
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
pub availability_commitment: String,
|
||||
pub mentoring_rate: f64,
|
||||
pub status: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl From<MentorDetailQueryDto> for MentorListResponseDto {
|
||||
fn from(dto: MentorDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.clone(),
|
||||
fullname: None, // now in user table, must be populated from service layer
|
||||
email: None, // now in user table, must be populated from service layer
|
||||
status: dto.status,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MentorDetailQueryDto> for MentorDetailResponseDto {
|
||||
fn from(dto: MentorDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.clone(),
|
||||
user_id: dto.user_id.clone(),
|
||||
// Personal data fields are populated in service layer from UsersSchema
|
||||
fullname: None, // populated from user table in service layer
|
||||
email: None, // populated from user table in service layer
|
||||
legal_name: None, // populated from user table in service layer
|
||||
gender: None, // populated from user table in service layer
|
||||
domicile: None, // populated from user table in service layer
|
||||
phone_for_verification: None, // populated from user table in service layer
|
||||
bio: None, // populated from user table in service layer
|
||||
last_education: None, // populated from user table in service layer
|
||||
linkedin_url: None, // populated from user table in service layer
|
||||
github_url: None, // populated from user table in service layer
|
||||
cv_url: None, // populated from user table in service layer
|
||||
portfolio_url: None, // populated from user table in service layer
|
||||
// Professional data from mentor
|
||||
industries: dto.industries,
|
||||
expertise: dto.expertise,
|
||||
languages: dto.languages,
|
||||
current_company: dto.current_company,
|
||||
current_role: dto.current_role,
|
||||
years_of_experience: dto.years_of_experience,
|
||||
topics_of_interest: dto.topics_of_interest,
|
||||
preferred_mentee_level: dto.preferred_mentee_level,
|
||||
preferred_mentoring_formats: dto.preferred_mentoring_formats,
|
||||
availability_commitment: dto.availability_commitment,
|
||||
mentoring_rate: dto.mentoring_rate,
|
||||
status: dto.status,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<MentorSchema> for MentorRegisterResponseDto {
|
||||
fn from(schema: MentorSchema) -> Self {
|
||||
Self {
|
||||
id: schema.id.to_string(),
|
||||
user_id: schema.user_id.unwrap_or_default(),
|
||||
email: None, // schema.email - now in user table
|
||||
status: schema.status,
|
||||
created_at: schema.created_at,
|
||||
updated_at: schema.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MentorDetailWithUserDto> for MentorDetailQueryDto {
|
||||
fn from(dto: MentorDetailWithUserDto) -> Self {
|
||||
MentorDetailQueryDto {
|
||||
id: dto.id,
|
||||
user_id: dto.user_id,
|
||||
// Personal data removed from MentorDetailWithUserDto - now in UsersSchema
|
||||
industries: dto.industries,
|
||||
expertise: dto.expertise,
|
||||
languages: dto.languages,
|
||||
current_company: dto.current_company,
|
||||
current_role: dto.current_role,
|
||||
years_of_experience: dto.years_of_experience,
|
||||
topics_of_interest: dto.topics_of_interest,
|
||||
preferred_mentee_level: dto.preferred_mentee_level,
|
||||
preferred_mentoring_formats: dto.preferred_mentoring_formats,
|
||||
availability_commitment: dto.availability_commitment,
|
||||
mentoring_rate: dto.mentoring_rate,
|
||||
status: dto.status,
|
||||
is_deleted: dto.is_deleted,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
use crate::v1::mentors::mentors_schema::MentorSchema;
|
||||
use imphnen_libs::AppState;
|
||||
use imphnen_libs::AppStatePostgresExt;
|
||||
use imphnen_entities::seaorm::auth::mentors::{Entity as Mentors, ActiveModel as MentorActiveModel, Column as MentorColumn};
|
||||
use imphnen_entities::seaorm::auth::users::Entity as Users;
|
||||
use anyhow::{Result, bail};
|
||||
use sea_orm::*;
|
||||
use sea_orm::EntityTrait;
|
||||
use uuid::Uuid;
|
||||
use sea_orm::ActiveModelTrait as ActiveModelTraitSpecific;
|
||||
use anyhow::anyhow;
|
||||
use imphnen_entities::{MetaRequestDto, ResponseListSuccessDto};
|
||||
use imphnen_utils::Result as UtilsResult;
|
||||
use crate::v1::mentors::mentors_dto::MentorDetailQueryDto;
|
||||
use std::time::Instant;
|
||||
use tracing::{instrument, info};
|
||||
use serde_json;
|
||||
use chrono::Utc;
|
||||
|
||||
pub struct MentorsRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> MentorsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
fn get_db(&self) -> &DatabaseConnection {
|
||||
self.state.postgres_db()
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_create_mentor(&self, data: MentorSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let mentor_active_model = MentorActiveModel {
|
||||
user_id: ActiveValue::Set(Uuid::parse_str(&data.user_id.unwrap_or_default())?),
|
||||
industries: ActiveValue::Set(Some(data.industries.into())),
|
||||
expertise: ActiveValue::Set(Some(data.expertise.into())),
|
||||
languages: ActiveValue::Set(Some(data.languages.into())),
|
||||
current_company: ActiveValue::Set(Some(data.current_company)),
|
||||
current_role: ActiveValue::Set(Some(data.current_role)),
|
||||
years_of_experience: ActiveValue::Set(Some(data.years_of_experience)),
|
||||
topics_of_interest: ActiveValue::Set(Some(data.topics_of_interest.into())),
|
||||
preferred_mentee_level: ActiveValue::Set(Some(serde_json::to_string(&data.preferred_mentee_level).unwrap())),
|
||||
preferred_mentoring_formats: ActiveValue::Set(Some(data.preferred_mentoring_formats.into())),
|
||||
availability_commitment: ActiveValue::Set(Some(data.availability_commitment)),
|
||||
mentoring_rate: ActiveValue::Set(Some(data.mentoring_rate)),
|
||||
status: ActiveValue::Set(Some(data.status)),
|
||||
created_at: ActiveValue::Set(Utc::now()),
|
||||
updated_at: ActiveValue::Set(Utc::now()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
info!("Executing PostgreSQL create in query_create_mentor");
|
||||
let result = <MentorActiveModel as sea_orm::ActiveModelTrait>::insert(mentor_active_model, self.get_db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_create_mentor' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(result.id.to_string())
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_update_mentor(&self, data: MentorSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let mentor_id = Uuid::parse_str(&data.id)?;
|
||||
let existing_mentor = Mentors::find_by_id(mentor_id)
|
||||
.one(self.get_db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow!("Mentor not found"))?;
|
||||
|
||||
let mut mentor_active_model: MentorActiveModel = existing_mentor.into();
|
||||
|
||||
if !data.industries.is_empty() { mentor_active_model.industries = ActiveValue::Set(Some(serde_json::to_value(data.industries).unwrap())); }
|
||||
if !data.expertise.is_empty() { mentor_active_model.expertise = ActiveValue::Set(Some(serde_json::to_value(data.expertise).unwrap())); }
|
||||
if !data.languages.is_empty() { mentor_active_model.languages = ActiveValue::Set(Some(serde_json::to_value(data.languages).unwrap())); }
|
||||
if !data.current_company.is_empty() { mentor_active_model.current_company = ActiveValue::Set(Some(data.current_company)); }
|
||||
if !data.current_role.is_empty() { mentor_active_model.current_role = ActiveValue::Set(Some(data.current_role)); }
|
||||
mentor_active_model.years_of_experience = ActiveValue::Set(Some(data.years_of_experience));
|
||||
if !data.topics_of_interest.is_empty() { mentor_active_model.topics_of_interest = ActiveValue::Set(Some(serde_json::to_value(data.topics_of_interest).unwrap())); }
|
||||
if !data.preferred_mentee_level.is_empty() { mentor_active_model.preferred_mentee_level = ActiveValue::Set(Some(serde_json::to_string(&data.preferred_mentee_level).unwrap())); }
|
||||
if !data.preferred_mentoring_formats.is_empty() { mentor_active_model.preferred_mentoring_formats = ActiveValue::Set(Some(serde_json::to_value(data.preferred_mentoring_formats).unwrap())); }
|
||||
if !data.availability_commitment.is_empty() { mentor_active_model.availability_commitment = ActiveValue::Set(Some(data.availability_commitment)); }
|
||||
mentor_active_model.mentoring_rate = ActiveValue::Set(Some(data.mentoring_rate));
|
||||
if !data.status.is_empty() { mentor_active_model.status = ActiveValue::Set(Some(data.status)); }
|
||||
mentor_active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
info!("Executing PostgreSQL update in query_update_mentor");
|
||||
let result = mentor_active_model.update(self.get_db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_update_mentor' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(format!("Success update mentor: {}", result.id))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_mentor(&self, id: &str) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let mentor = Mentors::find_by_id(Uuid::parse_str(id)?)
|
||||
.one(self.get_db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow!("Mentor not found"))?;
|
||||
|
||||
if mentor.is_deleted {
|
||||
bail!("Mentor is already soft deleted");
|
||||
}
|
||||
|
||||
let mut mentor_active_model: MentorActiveModel = mentor.into();
|
||||
mentor_active_model.is_deleted = ActiveValue::Set(true);
|
||||
mentor_active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
info!("Executing PostgreSQL soft delete in query_delete_mentor");
|
||||
let result = mentor_active_model.update(self.get_db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_delete_mentor' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(format!("Success soft delete mentor: {}", result.id))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email, include_deleted), err)]
|
||||
pub async fn query_mentor_by_email(
|
||||
&self,
|
||||
email: String,
|
||||
include_deleted: bool,
|
||||
) -> UtilsResult<MentorDetailQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = self.get_db();
|
||||
|
||||
let mut query = Mentors::find()
|
||||
.find_also_related(Users);
|
||||
|
||||
if !include_deleted {
|
||||
query = query.filter(MentorColumn::IsDeleted.eq(false));
|
||||
}
|
||||
|
||||
let (mentor, user) = query
|
||||
.filter(imphnen_entities::seaorm::auth::users::Column::Email.eq(email))
|
||||
.one(db)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Mentor not found"))?;
|
||||
|
||||
let _user = user.ok_or_else(|| anyhow::anyhow!("User not found for mentor"))?;
|
||||
|
||||
let result = MentorDetailQueryDto {
|
||||
id: mentor.id.to_string(),
|
||||
user_id: mentor.user_id.to_string(),
|
||||
industries: serde_json::from_value(mentor.industries.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
expertise: serde_json::from_value(mentor.expertise.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
languages: serde_json::from_value(mentor.languages.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
current_company: mentor.current_company.unwrap_or_default(),
|
||||
current_role: mentor.current_role.unwrap_or_default(),
|
||||
years_of_experience: mentor.years_of_experience.unwrap_or(0),
|
||||
topics_of_interest: serde_json::from_value(mentor.topics_of_interest.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
preferred_mentee_level: serde_json::from_str(&mentor.preferred_mentee_level.unwrap_or_default()).unwrap_or_default(),
|
||||
preferred_mentoring_formats: serde_json::from_value(mentor.preferred_mentoring_formats.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
availability_commitment: mentor.availability_commitment.unwrap_or_default(),
|
||||
mentoring_rate: mentor.mentoring_rate.unwrap_or(0.0),
|
||||
status: mentor.status.unwrap_or_default(),
|
||||
is_deleted: mentor.is_deleted,
|
||||
created_at: mentor.created_at.to_rfc3339(),
|
||||
updated_at: mentor.updated_at.to_rfc3339(),
|
||||
};
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_mentor_by_email' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, meta), err)]
|
||||
pub async fn query_mentor_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> UtilsResult<ResponseListSuccessDto<Vec<MentorDetailQueryDto>>> {
|
||||
let now = Instant::now();
|
||||
let db = self.get_db();
|
||||
|
||||
let page = meta.page.unwrap_or(1);
|
||||
let per_page = meta.per_page.unwrap_or(10);
|
||||
|
||||
let mut query = Mentors::find()
|
||||
.filter(MentorColumn::IsDeleted.eq(false))
|
||||
.find_also_related(Users);
|
||||
|
||||
// Apply sorting
|
||||
if let Some(sort_by) = &meta.sort_by {
|
||||
let order = meta.order.as_deref().unwrap_or("asc");
|
||||
match sort_by.as_str() {
|
||||
"created_at" => {
|
||||
if order == "desc" {
|
||||
query = query.order_by_desc(MentorColumn::CreatedAt);
|
||||
} else {
|
||||
query = query.order_by_asc(MentorColumn::CreatedAt);
|
||||
}
|
||||
}
|
||||
"updated_at" => {
|
||||
if order == "desc" {
|
||||
query = query.order_by_desc(MentorColumn::UpdatedAt);
|
||||
} else {
|
||||
query = query.order_by_asc(MentorColumn::UpdatedAt);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
query = query.order_by_desc(MentorColumn::CreatedAt);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
query = query.order_by_desc(MentorColumn::CreatedAt);
|
||||
}
|
||||
|
||||
let paginator = query.paginate(db, per_page);
|
||||
let total_pages = paginator.num_pages().await?;
|
||||
let mentors = paginator.fetch_page(page - 1).await?;
|
||||
|
||||
let data: Vec<MentorDetailQueryDto> = mentors
|
||||
.into_iter()
|
||||
.filter_map(|(mentor, user)| {
|
||||
user.map(|_u| MentorDetailQueryDto {
|
||||
id: mentor.id.to_string(),
|
||||
user_id: mentor.user_id.to_string(),
|
||||
industries: serde_json::from_value(mentor.industries.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
expertise: serde_json::from_value(mentor.expertise.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
languages: serde_json::from_value(mentor.languages.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
current_company: mentor.current_company.unwrap_or_default(),
|
||||
current_role: mentor.current_role.unwrap_or_default(),
|
||||
years_of_experience: mentor.years_of_experience.unwrap_or(0),
|
||||
topics_of_interest: serde_json::from_value(mentor.topics_of_interest.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
preferred_mentee_level: serde_json::from_str(&mentor.preferred_mentee_level.unwrap_or_default()).unwrap_or_default(),
|
||||
preferred_mentoring_formats: serde_json::from_value(mentor.preferred_mentoring_formats.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
availability_commitment: mentor.availability_commitment.unwrap_or_default(),
|
||||
mentoring_rate: mentor.mentoring_rate.unwrap_or(0.0),
|
||||
status: mentor.status.unwrap_or_default(),
|
||||
is_deleted: mentor.is_deleted,
|
||||
created_at: mentor.created_at.to_rfc3339(),
|
||||
updated_at: mentor.updated_at.to_rfc3339(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_mentor_list' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let response = ResponseListSuccessDto {
|
||||
data,
|
||||
meta: Some(imphnen_entities::MetaResponseDto {
|
||||
page: Some(page),
|
||||
per_page: Some(per_page),
|
||||
total: Some(total_pages),
|
||||
}),
|
||||
};
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id, include_deleted), err)]
|
||||
pub async fn query_mentor_by_id(
|
||||
&self,
|
||||
id: &str,
|
||||
include_deleted: bool,
|
||||
) -> UtilsResult<MentorDetailQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = self.get_db();
|
||||
|
||||
let mentor_id = Uuid::parse_str(id).map_err(|e| anyhow!("Invalid mentor ID: {}", e))?;
|
||||
|
||||
let mut query = Mentors::find_by_id(mentor_id)
|
||||
.find_also_related(Users);
|
||||
|
||||
if !include_deleted {
|
||||
query = query.filter(MentorColumn::IsDeleted.eq(false));
|
||||
}
|
||||
|
||||
let (mentor, user) = query
|
||||
.one(db)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Mentor not found"))?;
|
||||
|
||||
let _user = user.ok_or_else(|| anyhow::anyhow!("User not found for mentor"))?;
|
||||
|
||||
let result = MentorDetailQueryDto {
|
||||
id: mentor.id.to_string(),
|
||||
user_id: mentor.user_id.to_string(),
|
||||
industries: serde_json::from_value(mentor.industries.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
expertise: serde_json::from_value(mentor.expertise.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
languages: serde_json::from_value(mentor.languages.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
current_company: mentor.current_company.unwrap_or_default(),
|
||||
current_role: mentor.current_role.unwrap_or_default(),
|
||||
years_of_experience: mentor.years_of_experience.unwrap_or(0),
|
||||
topics_of_interest: serde_json::from_value(mentor.topics_of_interest.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
preferred_mentee_level: serde_json::from_str(&mentor.preferred_mentee_level.unwrap_or_default()).unwrap_or_default(),
|
||||
preferred_mentoring_formats: serde_json::from_value(mentor.preferred_mentoring_formats.clone().unwrap_or(serde_json::Value::Null)).unwrap_or_default(),
|
||||
availability_commitment: mentor.availability_commitment.unwrap_or_default(),
|
||||
mentoring_rate: mentor.mentoring_rate.unwrap_or(0.0),
|
||||
status: mentor.status.unwrap_or_default(),
|
||||
is_deleted: mentor.is_deleted,
|
||||
created_at: mentor.created_at.to_rfc3339(),
|
||||
updated_at: mentor.updated_at.to_rfc3339(),
|
||||
};
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_mentor_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
use super::{
|
||||
MentorDetailQueryDto, MentorUpdateRequestDto,
|
||||
MentoringLogistics, ProfessionalProfile,
|
||||
};
|
||||
use crate::v1::sessions::sessions_schema::Thing;
|
||||
use imphnen_entities::ResourceEnum;
|
||||
use imphnen_utils::{get_iso_date, make_thing};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct MentorSchema {
|
||||
pub id: Thing,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub user_id: Option<Thing>,
|
||||
// Personal data has been moved to UsersSchema - use user_id to reference
|
||||
// phone_for_verification, bio, last_education, linkedin_url, github_url,
|
||||
// cv_url, portfolio_url
|
||||
pub industries: Vec<String>,
|
||||
pub expertise: Vec<String>,
|
||||
pub languages: Vec<String>,
|
||||
pub current_company: String,
|
||||
pub current_role: String,
|
||||
pub years_of_experience: i32,
|
||||
pub topics_of_interest: Vec<String>,
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
pub availability_commitment: String,
|
||||
pub mentoring_rate: f64,
|
||||
pub status: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl Default for MentorSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: make_thing(
|
||||
ResourceEnum::Mentors.to_string().as_str(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user_id: Some(make_thing(
|
||||
ResourceEnum::Users.to_string().as_str(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
)),
|
||||
industries: Vec::new(),
|
||||
expertise: Vec::new(),
|
||||
languages: Vec::new(),
|
||||
current_company: String::new(),
|
||||
current_role: String::new(),
|
||||
years_of_experience: 0,
|
||||
topics_of_interest: Vec::new(),
|
||||
preferred_mentee_level: Vec::new(),
|
||||
preferred_mentoring_formats: Vec::new(),
|
||||
availability_commitment: String::new(),
|
||||
mentoring_rate: 0.0,
|
||||
status: "pending".to_string(),
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MentorSchema {
|
||||
pub fn create(
|
||||
professional_profile: ProfessionalProfile,
|
||||
mentoring_logistics: MentoringLogistics,
|
||||
user_id_raw: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: make_thing(
|
||||
&ResourceEnum::Mentors.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user_id: Some(make_thing(&ResourceEnum::Users.to_string(), &user_id_raw)),
|
||||
// Personal data now stored in UsersSchema, not here
|
||||
industries: professional_profile.industries,
|
||||
expertise: professional_profile.expertise,
|
||||
languages: professional_profile.languages,
|
||||
current_company: professional_profile.current_company,
|
||||
current_role: professional_profile.current_role,
|
||||
years_of_experience: professional_profile.years_of_experience,
|
||||
topics_of_interest: mentoring_logistics.topics_of_interest,
|
||||
preferred_mentee_level: mentoring_logistics.preferred_mentee_level,
|
||||
preferred_mentoring_formats: mentoring_logistics.preferred_mentoring_formats,
|
||||
availability_commitment: mentoring_logistics.availability_commitment,
|
||||
mentoring_rate: mentoring_logistics.mentoring_rate_amount as f64,
|
||||
status: "pending".to_string(),
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from(dto: MentorDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id,
|
||||
user_id: Some(dto.user_id),
|
||||
// Personal data now comes from UsersSchema via user_id
|
||||
industries: dto.industries,
|
||||
expertise: dto.expertise,
|
||||
languages: dto.languages,
|
||||
current_company: dto.current_company,
|
||||
current_role: dto.current_role,
|
||||
years_of_experience: dto.years_of_experience,
|
||||
topics_of_interest: dto.topics_of_interest,
|
||||
preferred_mentee_level: dto.preferred_mentee_level,
|
||||
preferred_mentoring_formats: dto.preferred_mentoring_formats,
|
||||
availability_commitment: dto.availability_commitment,
|
||||
mentoring_rate: dto.mentoring_rate,
|
||||
status: dto.status,
|
||||
is_deleted: dto.is_deleted,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(mut self, dto: MentorUpdateRequestDto) -> Self {
|
||||
// phone_for_verification, bio, last_education, linkedin_url, github_url,
|
||||
// cv_url, portfolio_url) are now updated in UsersSchema, not here
|
||||
|
||||
// Only update professional fields that are still in MentorSchema
|
||||
if let Some(val) = dto.industries {
|
||||
self.industries = val;
|
||||
}
|
||||
if let Some(val) = dto.expertise {
|
||||
self.expertise = val;
|
||||
}
|
||||
if let Some(val) = dto.languages {
|
||||
self.languages = val;
|
||||
}
|
||||
if let Some(val) = dto.current_company {
|
||||
self.current_company = val;
|
||||
}
|
||||
if let Some(val) = dto.current_role {
|
||||
self.current_role = val;
|
||||
}
|
||||
if let Some(val) = dto.years_of_experience {
|
||||
self.years_of_experience = val;
|
||||
}
|
||||
if let Some(val) = dto.topics_of_interest {
|
||||
self.topics_of_interest = val;
|
||||
}
|
||||
if let Some(val) = dto.preferred_mentee_level {
|
||||
self.preferred_mentee_level = val;
|
||||
}
|
||||
if let Some(val) = dto.preferred_mentoring_formats {
|
||||
self.preferred_mentoring_formats = val;
|
||||
}
|
||||
if let Some(val) = dto.availability_commitment {
|
||||
self.availability_commitment = val;
|
||||
}
|
||||
if let Some(val) = dto.mentoring_rate_amount {
|
||||
self.mentoring_rate = val as f64;
|
||||
}
|
||||
|
||||
self.updated_at = get_iso_date();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn update_status(mut self, status: String) -> Self {
|
||||
self.status = status;
|
||||
self.updated_at = get_iso_date();
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
use crate::v1::mentors::{
|
||||
MentorDetailResponseDto, MentorListResponseDto,
|
||||
MentorRegisterResponseDto, MentorSchema, MentorUpdateRequestDto,
|
||||
MentorUserRegisterRequestDto, MentorVerifyRequestDto, MentorsRepository,
|
||||
};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Response;
|
||||
use imphnen_entities::{
|
||||
MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
use imphnen_libs::AppState;
|
||||
use imphnen_iam::{
|
||||
v1::auth::AuthRepository,
|
||||
RolesEnum, RolesRepository, UsersRepository, UsersSchema,
|
||||
};
|
||||
use imphnen_libs::argon::hash_password;
|
||||
use imphnen_utils::{
|
||||
common_response, success_list_response, success_response, validator::validate_request,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
use tracing::error;
|
||||
|
||||
pub struct MentorsService;
|
||||
|
||||
impl MentorsService {
|
||||
pub async fn register_mentor(
|
||||
state: &AppState,
|
||||
dto: MentorUserRegisterRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&dto) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
|
||||
let user_repo = UsersRepository::new(state);
|
||||
let mentor_repo = MentorsRepository::new(state);
|
||||
let role_repo = RolesRepository::new(state);
|
||||
let _auth_repo = AuthRepository::new(state);
|
||||
|
||||
let user_email = &dto.email;
|
||||
let mut _user_to_update: Option<UsersSchema> = None;
|
||||
|
||||
let existing_user_result =
|
||||
user_repo.query_user_by_email(user_email.clone()).await;
|
||||
|
||||
let user_id;
|
||||
let final_user_email = user_email.clone();
|
||||
|
||||
if let Ok(user_detail_query_dto) = existing_user_result {
|
||||
if mentor_repo
|
||||
.query_mentor_by_email(user_email.clone(), false)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
return common_response(
|
||||
StatusCode::CONFLICT,
|
||||
"Mentor profile already exists for this user",
|
||||
);
|
||||
}
|
||||
|
||||
let mut user_schema = UsersSchema::from(user_detail_query_dto);
|
||||
|
||||
user_schema.fullname = Some(dto.fullname.clone());
|
||||
// Update profile_extension fields
|
||||
let mut profile_ext = user_schema.profile_extension.clone().unwrap_or_default();
|
||||
profile_ext.phone_number = dto.phone_number.clone();
|
||||
profile_ext.phone_for_verification = dto.identity_and_verification.phone_for_verification.clone();
|
||||
profile_ext.gender = dto.identity_and_verification.gender.clone();
|
||||
profile_ext.domicile = dto.identity_and_verification.domicile.clone();
|
||||
profile_ext.bio = Some(dto.professional_profile.bio.clone());
|
||||
profile_ext.last_education = dto.professional_profile.last_education.clone();
|
||||
profile_ext.linkedin_url = dto.professional_profile.linkedin_url.clone();
|
||||
profile_ext.github_url = dto.professional_profile.github_url.clone();
|
||||
profile_ext.cv_url = dto.professional_profile.cv_url.clone();
|
||||
profile_ext.portfolio_url = dto.professional_profile.portfolio_url.clone();
|
||||
user_schema.profile_extension = Some(profile_ext);
|
||||
user_schema.updated_at = imphnen_utils::get_iso_date();
|
||||
|
||||
let hashed_password = match hash_password(&dto.password) {
|
||||
Ok(hash) => hash,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to hash password during update for {}: {}",
|
||||
final_user_email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to hash password",
|
||||
);
|
||||
}
|
||||
};
|
||||
user_schema.password = Some(hashed_password);
|
||||
|
||||
let mentor_role = match role_repo
|
||||
.query_role_by_name(RolesEnum::Mentor.to_string())
|
||||
.await
|
||||
{
|
||||
Ok(role) => role,
|
||||
Err(_e) => {
|
||||
return common_response(StatusCode::BAD_REQUEST, "Mentor Role Not Found");
|
||||
}
|
||||
};
|
||||
user_schema.mentor_id = Some(imphnen_utils::make_thing_from_enum("Roles", &mentor_role.id));
|
||||
user_schema.is_active = false;
|
||||
|
||||
if let Err(_err) = user_repo.query_update_user(user_schema.clone()).await {
|
||||
error!(
|
||||
"Failed to update existing user {} to mentor role: {}",
|
||||
final_user_email, _err
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&_err.to_string(),
|
||||
);
|
||||
}
|
||||
user_id = user_schema.id.clone();
|
||||
} else {
|
||||
let mentor_role = match role_repo
|
||||
.query_role_by_name(RolesEnum::Mentor.to_string())
|
||||
.await
|
||||
{
|
||||
Ok(role) => role,
|
||||
Err(_e) => {
|
||||
return common_response(StatusCode::BAD_REQUEST, "Mentor Role Not Found");
|
||||
}
|
||||
};
|
||||
|
||||
let hashed_password = match hash_password(&dto.password) {
|
||||
Ok(hash) => hash,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to hash password for new user {}: {}",
|
||||
final_user_email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to hash password",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let mut new_user_schema = UsersSchema {
|
||||
id: imphnen_utils::make_thing_from_enum(
|
||||
"Users",
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
email: Some(dto.email),
|
||||
fullname: Some(dto.fullname),
|
||||
password: Some(hashed_password),
|
||||
// Set phone number in profile extension instead
|
||||
// Store personal data from identity_and_verification in user
|
||||
legal_name: Some(dto.identity_and_verification.legal_name.clone()),
|
||||
// Use profile_extension for these fields
|
||||
// Store personal data from professional_profile in user
|
||||
created_at: imphnen_utils::get_iso_date(),
|
||||
updated_at: imphnen_utils::get_iso_date(),
|
||||
mentor_id: Some(imphnen_utils::make_thing_from_enum(
|
||||
"Roles",
|
||||
&mentor_role.id,
|
||||
)),
|
||||
is_active: false,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// populate profile_extension
|
||||
let mut profile_ext = new_user_schema.profile_extension.clone().unwrap_or_default();
|
||||
profile_ext.phone_number = dto.phone_number.clone();
|
||||
profile_ext.phone_for_verification = dto.identity_and_verification.phone_for_verification.clone();
|
||||
profile_ext.gender = dto.identity_and_verification.gender.clone();
|
||||
profile_ext.domicile = dto.identity_and_verification.domicile.clone();
|
||||
profile_ext.bio = Some(dto.professional_profile.bio.clone());
|
||||
profile_ext.last_education = dto.professional_profile.last_education.clone();
|
||||
profile_ext.linkedin_url = dto.professional_profile.linkedin_url.clone();
|
||||
profile_ext.github_url = dto.professional_profile.github_url.clone();
|
||||
profile_ext.cv_url = dto.professional_profile.cv_url.clone();
|
||||
profile_ext.portfolio_url = dto.professional_profile.portfolio_url.clone();
|
||||
new_user_schema.profile_extension = Some(profile_ext);
|
||||
user_id = new_user_schema.id.clone();
|
||||
|
||||
match user_repo.query_create_user(new_user_schema).await {
|
||||
Ok(_) => {}
|
||||
Err(_err) => {
|
||||
error!("Failed to create new user {}: {}", final_user_email, _err);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&_err.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Skip OTP for now - implement later if needed
|
||||
|
||||
let mentor_schema = MentorSchema::create(
|
||||
dto.professional_profile,
|
||||
dto.mentoring_logistics,
|
||||
user_id.clone(),
|
||||
);
|
||||
|
||||
match mentor_repo.query_create_mentor(mentor_schema.clone()).await {
|
||||
Ok(mentor_profile_id) => {
|
||||
let user_after_mentor_creation_dto = user_repo
|
||||
.query_user_by_email(final_user_email.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut user_after_mentor_creation_schema =
|
||||
UsersSchema::from(user_after_mentor_creation_dto);
|
||||
user_after_mentor_creation_schema = user_after_mentor_creation_schema
|
||||
.update_mentor_id(Some(mentor_profile_id));
|
||||
if let Err(_e) = user_repo
|
||||
.query_update_user(user_after_mentor_creation_schema)
|
||||
.await
|
||||
{
|
||||
error!(
|
||||
"Failed to update user's mentor_id for {}: {}",
|
||||
final_user_email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&_e.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let response_dto = MentorRegisterResponseDto::from(mentor_schema);
|
||||
success_response(ResponseSuccessDto { data: response_dto })
|
||||
}
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to create mentor profile for {}: {}",
|
||||
final_user_email, _e
|
||||
);
|
||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, &_e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_mentor_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||
let repo = MentorsRepository::new(state);
|
||||
let user_repo = UsersRepository::new(state);
|
||||
|
||||
match repo.query_mentor_list(meta).await {
|
||||
Ok(result) => {
|
||||
let mut mentor_list_data: Vec<MentorListResponseDto> = Vec::new();
|
||||
|
||||
for mentor_with_user in result.data {
|
||||
let mentor_dto = mentor_with_user;
|
||||
let mut list_item = MentorListResponseDto::from(mentor_dto.clone());
|
||||
|
||||
// Get user data to populate personal fields
|
||||
if let Ok(user) = user_repo.query_user_by_id(&mentor_dto.user_id).await {
|
||||
list_item.fullname = Some(user.fullname);
|
||||
list_item.email = Some(user.email);
|
||||
}
|
||||
|
||||
mentor_list_data.push(list_item);
|
||||
}
|
||||
|
||||
success_list_response(ResponseListSuccessDto {
|
||||
data: mentor_list_data,
|
||||
meta: result.meta,
|
||||
})
|
||||
}
|
||||
Err(_e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &_e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_mentor_by_id(state: &AppState, id: &str) -> Response {
|
||||
let mentor_repo = MentorsRepository::new(state);
|
||||
let user_repo = UsersRepository::new(state);
|
||||
let thing_id = imphnen_utils::make_thing_from_enum("Mentors", id); match mentor_repo.query_mentor_by_id(&thing_id, false).await {
|
||||
Ok(mentor) => {
|
||||
// Get user data separately
|
||||
let user_result = user_repo.query_user_by_id(&mentor.user_id).await;
|
||||
match user_result {
|
||||
Ok(user) => {
|
||||
// Combine mentor and user data
|
||||
let dto = MentorDetailResponseDto {
|
||||
id: mentor.id.clone(),
|
||||
user_id: mentor.user_id.clone(),
|
||||
// Personal data from user
|
||||
fullname: Some(user.fullname),
|
||||
email: Some(user.email),
|
||||
legal_name: user.legal_name,
|
||||
gender: user.profile_extension.as_ref().and_then(|ext| ext.gender.clone()),
|
||||
domicile: user.profile_extension.as_ref().and_then(|ext| ext.domicile.clone()),
|
||||
phone_for_verification: user.profile_extension.as_ref().and_then(|ext| ext.phone_for_verification.clone()),
|
||||
bio: user.profile_extension.as_ref().and_then(|ext| ext.bio.clone()),
|
||||
last_education: user.profile_extension.as_ref().and_then(|ext| ext.last_education.clone()),
|
||||
linkedin_url: user.profile_extension.as_ref().and_then(|ext| ext.linkedin_url.clone()),
|
||||
github_url: user.profile_extension.as_ref().and_then(|ext| ext.github_url.clone()),
|
||||
cv_url: user.profile_extension.as_ref().and_then(|ext| ext.cv_url.clone()),
|
||||
portfolio_url: user.profile_extension.as_ref().and_then(|ext| ext.portfolio_url.clone()),
|
||||
// Professional data from mentor
|
||||
industries: mentor.industries,
|
||||
expertise: mentor.expertise,
|
||||
languages: mentor.languages,
|
||||
current_company: mentor.current_company,
|
||||
current_role: mentor.current_role,
|
||||
years_of_experience: mentor.years_of_experience,
|
||||
topics_of_interest: mentor.topics_of_interest,
|
||||
preferred_mentee_level: mentor.preferred_mentee_level,
|
||||
preferred_mentoring_formats: mentor.preferred_mentoring_formats,
|
||||
availability_commitment: mentor.availability_commitment,
|
||||
mentoring_rate: mentor.mentoring_rate,
|
||||
status: mentor.status,
|
||||
created_at: mentor.created_at,
|
||||
updated_at: mentor.updated_at,
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: dto })
|
||||
}
|
||||
Err(_e) => {
|
||||
error!("Failed to get user data for mentor {}: {}", id, _e);
|
||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, "Failed to get mentor user data")
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_e) => common_response(StatusCode::NOT_FOUND, &_e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_mentor(
|
||||
state: &AppState,
|
||||
id: &str,
|
||||
dto: MentorUpdateRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&dto) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = MentorsRepository::new(state);
|
||||
let mentor_uuid = Uuid::parse_str(id).map_err(|_| {
|
||||
common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid mentor ID format"
|
||||
)
|
||||
}).unwrap();
|
||||
let existing_mentor = match repo.query_mentor_by_id(&mentor_uuid.to_string(), false).await {
|
||||
Ok(mentor) => mentor,
|
||||
Err(_e) => return common_response(StatusCode::NOT_FOUND, &_e.to_string()),
|
||||
};
|
||||
|
||||
let mut schema = MentorSchema::from(existing_mentor);
|
||||
schema = schema.update(dto);
|
||||
|
||||
match repo.query_update_mentor(schema).await {
|
||||
Ok(_) => {
|
||||
let updated_mentor =
|
||||
repo.query_mentor_by_id(id, false).await.unwrap();
|
||||
let response_dto =
|
||||
MentorDetailResponseDto::from(updated_mentor);
|
||||
success_response(ResponseSuccessDto { data: response_dto })
|
||||
}
|
||||
Err(_e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &_e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_mentor(state: &AppState, id: &str) -> Response {
|
||||
let repo = MentorsRepository::new(state);
|
||||
match repo.query_delete_mentor(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(_e) => common_response(StatusCode::NOT_FOUND, &_e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_mentor_me(state: &AppState, email: &str) -> Response {
|
||||
let repo = MentorsRepository::new(state);
|
||||
match repo.query_mentor_by_email(email.to_string(), false).await {
|
||||
Ok(mentor) => {
|
||||
let dto = MentorDetailResponseDto::from(mentor);
|
||||
success_response(ResponseSuccessDto { data: dto })
|
||||
}
|
||||
Err(_e) => common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"Mentor profile not found for current user",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_mentor_me(
|
||||
state: &AppState,
|
||||
email: &str,
|
||||
dto: MentorUpdateRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&dto) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = MentorsRepository::new(state);
|
||||
let existing_mentor =
|
||||
match repo.query_mentor_by_email(email.to_string(), false).await {
|
||||
Ok(mentor) => mentor,
|
||||
Err(_e) => return common_response(StatusCode::FORBIDDEN, &_e.to_string()),
|
||||
};
|
||||
|
||||
let mut schema = MentorSchema::from(existing_mentor);
|
||||
schema = schema.update(dto);
|
||||
|
||||
match repo.query_update_mentor(schema).await {
|
||||
Ok(_) => {
|
||||
let updated_mentor = repo
|
||||
.query_mentor_by_email(email.to_string(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
let response_dto =
|
||||
MentorDetailResponseDto::from(updated_mentor);
|
||||
success_response(ResponseSuccessDto { data: response_dto })
|
||||
}
|
||||
Err(_e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &_e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_mentor_status(state: &AppState, email: &str) -> Response {
|
||||
let repo = MentorsRepository::new(state);
|
||||
match repo.query_mentor_by_email(email.to_string(), false).await {
|
||||
Ok(mentor) => common_response(StatusCode::OK, &mentor.status),
|
||||
Err(_e) => common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"No mentor application found for current user",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn verify_mentor(
|
||||
state: &AppState,
|
||||
id: &str,
|
||||
dto: MentorVerifyRequestDto,
|
||||
) -> Response {
|
||||
let repo = MentorsRepository::new(state);
|
||||
let mentor_uuid = Uuid::parse_str(id).map_err(|_| {
|
||||
common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid mentor ID format"
|
||||
)
|
||||
}).unwrap();
|
||||
let existing_mentor = match repo.query_mentor_by_id(&mentor_uuid.to_string(), false).await {
|
||||
Ok(mentor) => mentor,
|
||||
Err(_e) => return common_response(StatusCode::NOT_FOUND, &_e.to_string()),
|
||||
};
|
||||
|
||||
let mut schema = MentorSchema::from(existing_mentor);
|
||||
schema = schema.update_status(dto.status);
|
||||
|
||||
match repo.query_update_mentor(schema).await {
|
||||
Ok(_) => {
|
||||
let updated_mentor =
|
||||
repo.query_mentor_by_id(&mentor_uuid.to_string(), false).await.unwrap();
|
||||
let response_dto =
|
||||
MentorDetailResponseDto::from(updated_mentor);
|
||||
success_response(ResponseSuccessDto { data: response_dto })
|
||||
}
|
||||
Err(_e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &_e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
|
||||
pub mod mentors_controller;
|
||||
pub mod mentors_dto;
|
||||
pub mod mentors_repository;
|
||||
pub mod mentors_schema;
|
||||
pub mod mentors_service;
|
||||
|
||||
// Explicitly export only public controller functions and key types
|
||||
pub use mentors_controller::{
|
||||
post_register_mentor,
|
||||
get_mentor_list,
|
||||
get_mentor_by_id,
|
||||
put_update_mentor,
|
||||
delete_mentor,
|
||||
put_verify_mentor,
|
||||
get_mentor_me,
|
||||
put_update_mentor_me,
|
||||
put_update_mentor_no_id,
|
||||
get_mentor_status,
|
||||
};
|
||||
|
||||
// Export key DTO types used across the API
|
||||
pub use mentors_dto::{
|
||||
MentorListResponseDto,
|
||||
MentorDetailResponseDto,
|
||||
MentorRegisterResponseDto,
|
||||
MentorUpdateRequestDto,
|
||||
MentorUserRegisterRequestDto,
|
||||
MentorVerifyRequestDto,
|
||||
MentorDetailQueryDto,
|
||||
ProfessionalProfile,
|
||||
MentoringLogistics,
|
||||
MentoringRate,
|
||||
IdentityAndVerification,
|
||||
MentorInsertDto,
|
||||
};
|
||||
|
||||
// Export service and repository for internal use
|
||||
pub use mentors_service::MentorsService;
|
||||
pub use mentors_repository::MentorsRepository;
|
||||
|
||||
// Export schema types for database interactions
|
||||
pub use mentors_schema::MentorSchema;
|
||||
|
||||
pub fn mentors_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(get_mentor_list))
|
||||
.route("/create", post(post_register_mentor))
|
||||
.route("/me", get(get_mentor_me))
|
||||
.route("/me/update", put(put_update_mentor_me))
|
||||
.route("/me/status", get(get_mentor_status))
|
||||
.route("/detail/{id}", get(get_mentor_by_id))
|
||||
.route("/update/{id}", put(put_update_mentor))
|
||||
.route("/update", put(put_update_mentor_no_id))
|
||||
.route("/delete/{id}", delete(delete_mentor))
|
||||
.route("/verify/{id}", put(put_verify_mentor))
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use axum::Router;
|
||||
|
||||
pub mod mentors;
|
||||
pub mod sessions;
|
||||
|
||||
/// Creates the main Dimentorin router with all version 1 endpoints
|
||||
/// Routes:
|
||||
/// - /mentors -> mentors::mentors_router()
|
||||
/// - /sessions -> sessions::sessions_router()
|
||||
/// - /users/me/sessions -> sessions::get_my_sessions()
|
||||
pub fn dimentorin_router() -> Router {
|
||||
Router::new()
|
||||
.nest("/mentors", mentors::mentors_router())
|
||||
.merge(sessions::sessions_router())
|
||||
}
|
||||
|
||||
// Explicitly re-export key items for easier consumption
|
||||
pub use mentors::mentors_router;
|
||||
pub use mentors::MentorsService;
|
||||
pub use mentors::MentorsRepository;
|
||||
pub use mentors::MentorSchema;
|
||||
|
||||
pub use sessions::sessions_router;
|
||||
pub use sessions::SessionsService;
|
||||
pub use sessions::SessionsRepository;
|
||||
pub use sessions::SessionSchema;
|
||||
@@ -0,0 +1,11 @@
|
||||
pub mod sessions_controller;
|
||||
pub mod sessions_dto;
|
||||
pub mod sessions_repository;
|
||||
pub mod sessions_schema;
|
||||
pub mod sessions_service;
|
||||
|
||||
pub use sessions_controller::*;
|
||||
pub use sessions_dto::*;
|
||||
pub use sessions_repository::*;
|
||||
pub use sessions_schema::*;
|
||||
pub use sessions_service::*;
|
||||
@@ -0,0 +1,297 @@
|
||||
use super::{
|
||||
BookSessionRequestDto, BookSessionResponseDto, MentorAvailabilityDto,
|
||||
SessionFeedbackRequestDto, SessionFeedbackResponseDto, SessionListResponseDto,
|
||||
SessionsService, UpdateSessionStatusRequestDto, UpdateSessionStatusResponseDto,
|
||||
};
|
||||
use axum::{
|
||||
extract::{Extension, Path, Query},
|
||||
http::HeaderMap,
|
||||
response::Response,
|
||||
routing::{get, post, put},
|
||||
Json, Router,
|
||||
};
|
||||
use imphnen_libs::AppState;
|
||||
use imphnen_utils::extract_email;
|
||||
use serde::Deserialize;
|
||||
use utoipa::OpenApi;
|
||||
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(
|
||||
paths(
|
||||
post_book_session,
|
||||
get_mentor_sessions,
|
||||
get_mentor_availability,
|
||||
put_update_session_status,
|
||||
post_submit_feedback,
|
||||
get_my_sessions,
|
||||
),
|
||||
components(schemas(
|
||||
BookSessionRequestDto,
|
||||
BookSessionResponseDto,
|
||||
SessionListResponseDto,
|
||||
super::SessionListItemDto,
|
||||
MentorAvailabilityDto,
|
||||
super::AvailabilitySlotDto,
|
||||
UpdateSessionStatusRequestDto,
|
||||
UpdateSessionStatusResponseDto,
|
||||
SessionFeedbackRequestDto,
|
||||
SessionFeedbackResponseDto,
|
||||
)),
|
||||
tags(
|
||||
(name = "sessions", description = "Mentoring Sessions Management API")
|
||||
)
|
||||
)]
|
||||
pub struct SessionsApiDoc;
|
||||
|
||||
// ============================================
|
||||
// Book Session
|
||||
// ============================================
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/mentors/{id}/sessions/create",
|
||||
tag = "sessions",
|
||||
summary = "Book a mentoring session",
|
||||
description = "Book a mentoring session with a specific mentor. Requires authentication.",
|
||||
security(("Bearer" = [])),
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID"),
|
||||
),
|
||||
request_body = BookSessionRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "Session booked successfully", body = BookSessionResponseDto),
|
||||
(status = 400, description = "Invalid request"),
|
||||
(status = 401, description = "Unauthorized"),
|
||||
(status = 404, description = "Mentor not found"),
|
||||
)
|
||||
)]
|
||||
pub async fn post_book_session(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(mentor_id): Path<String>,
|
||||
Json(dto): Json<BookSessionRequestDto>,
|
||||
) -> Response {
|
||||
let user_email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return imphnen_utils::common_response(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"Token tidak valid",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
SessionsService::book_session(&state, mentor_id, user_email, dto).await
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Mentor's Sessions
|
||||
// ============================================
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SessionStatusFilter {
|
||||
status: Option<String>,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors/{id}/sessions",
|
||||
tag = "sessions",
|
||||
summary = "List mentor's sessions",
|
||||
description = "Get all sessions for a specific mentor. Only accessible by the mentor themselves or admin.",
|
||||
security(("Bearer" = [])),
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID"),
|
||||
("status" = Option<String>, Query, description = "Filter by status (pending, confirmed, completed, cancelled, no_show)"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Sessions retrieved successfully", body = SessionListResponseDto),
|
||||
(status = 401, description = "Unauthorized"),
|
||||
(status = 403, description = "Forbidden"),
|
||||
(status = 404, description = "Mentor not found"),
|
||||
)
|
||||
)]
|
||||
pub async fn get_mentor_sessions(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(mentor_id): Path<String>,
|
||||
Query(filter): Query<SessionStatusFilter>,
|
||||
) -> Response {
|
||||
let user_email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return imphnen_utils::common_response(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"Token tidak valid",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
SessionsService::get_mentor_sessions(&state, mentor_id, user_email, filter.status).await
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Mentor Availability
|
||||
// ============================================
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors/{id}/availability",
|
||||
tag = "sessions",
|
||||
summary = "Get mentor availability",
|
||||
description = "Get available time slots for booking with a mentor. Public endpoint.",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Availability retrieved successfully", body = MentorAvailabilityDto),
|
||||
(status = 404, description = "Mentor not found"),
|
||||
)
|
||||
)]
|
||||
pub async fn get_mentor_availability(
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(mentor_id): Path<String>,
|
||||
) -> Response {
|
||||
SessionsService::get_mentor_availability(&state, mentor_id).await
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Update Session Status
|
||||
// ============================================
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/sessions/update/{id}/status",
|
||||
tag = "sessions",
|
||||
summary = "Update session status",
|
||||
description = "Update the status of a session (confirm, complete, cancel). Only accessible by the mentor.",
|
||||
security(("Bearer" = [])),
|
||||
params(
|
||||
("id" = String, Path, description = "Session ID"),
|
||||
),
|
||||
request_body = UpdateSessionStatusRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Status updated successfully", body = UpdateSessionStatusResponseDto),
|
||||
(status = 400, description = "Invalid request"),
|
||||
(status = 401, description = "Unauthorized"),
|
||||
(status = 403, description = "Forbidden"),
|
||||
(status = 404, description = "Session not found"),
|
||||
)
|
||||
)]
|
||||
pub async fn put_update_session_status(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(session_id): Path<String>,
|
||||
Json(dto): Json<UpdateSessionStatusRequestDto>,
|
||||
) -> Response {
|
||||
let user_email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return imphnen_utils::common_response(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"Token tidak valid",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
SessionsService::update_session_status(&state, session_id, user_email, dto).await
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Submit Feedback
|
||||
// ============================================
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/sessions/{id}/feedback/create",
|
||||
tag = "sessions",
|
||||
summary = "Submit session feedback",
|
||||
description = "Submit feedback and rating for a completed session. Only accessible by the mentee.",
|
||||
security(("Bearer" = [])),
|
||||
params(
|
||||
("id" = String, Path, description = "Session ID"),
|
||||
),
|
||||
request_body = SessionFeedbackRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Feedback submitted successfully", body = SessionFeedbackResponseDto),
|
||||
(status = 400, description = "Invalid request or session not completed"),
|
||||
(status = 401, description = "Unauthorized"),
|
||||
(status = 403, description = "Forbidden"),
|
||||
(status = 404, description = "Session not found"),
|
||||
)
|
||||
)]
|
||||
pub async fn post_submit_feedback(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(session_id): Path<String>,
|
||||
Json(dto): Json<SessionFeedbackRequestDto>,
|
||||
) -> Response {
|
||||
let user_email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return imphnen_utils::common_response(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"Token tidak valid",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
SessionsService::submit_feedback(&state, session_id, user_email, dto).await
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get User's Sessions
|
||||
// ============================================
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/users/me/sessions",
|
||||
tag = "sessions",
|
||||
summary = "Get my sessions",
|
||||
description = "Get all sessions for the authenticated user (as mentee). Requires authentication.",
|
||||
security(("Bearer" = [])),
|
||||
params(
|
||||
("status" = Option<String>, Query, description = "Filter by status (pending, confirmed, completed, cancelled, no_show)"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Sessions retrieved successfully", body = SessionListResponseDto),
|
||||
(status = 401, description = "Unauthorized"),
|
||||
)
|
||||
)]
|
||||
pub async fn get_my_sessions(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(filter): Query<SessionStatusFilter>,
|
||||
) -> Response {
|
||||
let user_email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return imphnen_utils::common_response(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"Token tidak valid",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
SessionsService::get_user_sessions(&state, user_email, filter.status).await
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Router
|
||||
// ============================================
|
||||
|
||||
pub fn sessions_router() -> Router {
|
||||
Router::new()
|
||||
// Book session (under mentors path)
|
||||
.route("/mentors/{id}/sessions/create", post(post_book_session))
|
||||
// Get mentor's sessions
|
||||
.route("/mentors/{id}/sessions", get(get_mentor_sessions))
|
||||
// Get mentor availability (public - no auth)
|
||||
.route("/mentors/{id}/availability", get(get_mentor_availability))
|
||||
// Update session status
|
||||
.route("/sessions/update/{id}/status", put(put_update_session_status))
|
||||
// Submit feedback
|
||||
.route("/sessions/{id}/feedback/create", post(post_submit_feedback))
|
||||
// Get my sessions
|
||||
.route("/users/me/sessions", get(get_my_sessions))
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
// ============================================
|
||||
// Book Session (POST /v1/mentors/{id}/sessions/book)
|
||||
// ============================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct BookSessionRequestDto {
|
||||
#[validate(length(min = 3, max = 200, message = "Topic must be 3-200 characters"))]
|
||||
pub topic: String,
|
||||
|
||||
#[validate(length(max = 1000, message = "Description must be max 1000 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
|
||||
#[validate(length(min = 1, message = "Scheduled time is required"))]
|
||||
pub scheduled_at: String, // ISO 8601 datetime
|
||||
|
||||
#[validate(range(min = 15, max = 240, message = "Duration must be 15-240 minutes"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub duration_minutes: Option<i32>,
|
||||
|
||||
#[validate(length(max = 50, message = "Session type must be max 50 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub session_type: Option<String>, // "video_call", "phone_call", "chat"
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct BookSessionResponseDto {
|
||||
pub id: String,
|
||||
pub mentor_id: String,
|
||||
pub mentee_id: String,
|
||||
pub topic: String,
|
||||
pub description: Option<String>,
|
||||
pub scheduled_at: String,
|
||||
pub duration_minutes: i32,
|
||||
pub session_type: String,
|
||||
pub status: String,
|
||||
pub created_at: String,
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// List Sessions (GET /v1/mentors/{id}/sessions & /v1/users/me/sessions)
|
||||
// ============================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct SessionListItemDto {
|
||||
pub id: String,
|
||||
pub mentor_id: String,
|
||||
pub mentee_id: String,
|
||||
pub mentee_fullname: Option<String>,
|
||||
pub mentee_email: Option<String>,
|
||||
pub topic: String,
|
||||
pub scheduled_at: String,
|
||||
pub duration_minutes: i32,
|
||||
pub session_type: String,
|
||||
pub status: String,
|
||||
pub rating: Option<i32>,
|
||||
pub created_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct SessionListResponseDto {
|
||||
pub sessions: Vec<SessionListItemDto>,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Session Detail
|
||||
// ============================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct SessionDetailDto {
|
||||
pub id: String,
|
||||
pub mentor_id: String,
|
||||
pub mentor_fullname: Option<String>,
|
||||
pub mentee_id: String,
|
||||
pub mentee_fullname: Option<String>,
|
||||
pub topic: String,
|
||||
pub description: Option<String>,
|
||||
pub scheduled_at: String,
|
||||
pub duration_minutes: i32,
|
||||
pub meeting_link: Option<String>,
|
||||
pub session_type: String,
|
||||
pub status: String,
|
||||
pub feedback: Option<String>,
|
||||
pub rating: Option<i32>,
|
||||
pub feedback_submitted_at: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Mentor Availability (GET /v1/mentors/{id}/availability)
|
||||
// ============================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AvailabilitySlotDto {
|
||||
pub date: String, // YYYY-MM-DD
|
||||
pub time: String, // HH:MM
|
||||
pub available: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MentorAvailabilityDto {
|
||||
pub mentor_id: String,
|
||||
pub availability_commitment: String,
|
||||
pub preferred_formats: Vec<String>,
|
||||
pub slots: Vec<AvailabilitySlotDto>,
|
||||
pub booked_dates: Vec<String>, // Dates with existing sessions
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Update Session Status (PUT /v1/sessions/{id}/status)
|
||||
// ============================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct UpdateSessionStatusRequestDto {
|
||||
#[validate(length(min = 1, max = 50, message = "Status must be 1-50 characters"))]
|
||||
pub status: String, // "confirmed", "completed", "cancelled", "no_show"
|
||||
|
||||
#[validate(url(message = "Meeting link must be a valid URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub meeting_link: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UpdateSessionStatusResponseDto {
|
||||
pub id: String,
|
||||
pub status: String,
|
||||
pub meeting_link: Option<String>,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Submit Feedback (POST /v1/sessions/{id}/feedback)
|
||||
// ============================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct SessionFeedbackRequestDto {
|
||||
#[validate(length(min = 10, max = 2000, message = "Feedback must be 10-2000 characters"))]
|
||||
pub feedback: String,
|
||||
|
||||
#[validate(range(min = 1, max = 5, message = "Rating must be 1-5"))]
|
||||
pub rating: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct SessionFeedbackResponseDto {
|
||||
pub id: String,
|
||||
pub feedback: String,
|
||||
pub rating: i32,
|
||||
pub submitted_at: String,
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Query DTOs (internal use)
|
||||
// ============================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct SessionDetailQueryDto {
|
||||
pub id: String,
|
||||
pub mentor_id: String,
|
||||
pub mentee_id: String,
|
||||
pub topic: String,
|
||||
pub description: Option<String>,
|
||||
pub scheduled_at: String,
|
||||
pub duration_minutes: i32,
|
||||
pub meeting_link: Option<String>,
|
||||
pub session_type: String,
|
||||
pub status: String,
|
||||
pub feedback: Option<String>,
|
||||
pub rating: Option<i32>,
|
||||
pub feedback_submitted_at: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub mentor_fullname: Option<String>,
|
||||
pub mentee_fullname: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct SessionListQueryDto {
|
||||
pub id: String,
|
||||
pub mentor_id: String,
|
||||
pub mentee_id: String,
|
||||
pub topic: String,
|
||||
pub scheduled_at: String,
|
||||
pub duration_minutes: i32,
|
||||
pub session_type: String,
|
||||
pub status: String,
|
||||
pub rating: Option<i32>,
|
||||
pub created_at: String,
|
||||
pub mentee_fullname: Option<String>,
|
||||
pub mentee_email: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
use super::{SessionDetailQueryDto, SessionListQueryDto, SessionSchema};
|
||||
use anyhow::{anyhow, Result};
|
||||
use imphnen_libs::{AppState, AppStatePostgresExt};
|
||||
use sea_orm::*;
|
||||
use uuid::Uuid;
|
||||
|
||||
use imphnen_entities::seaorm::auth::sessions::{
|
||||
Entity as Sessions, Model as SessionModel, ActiveModel as SessionActiveModel, Column as SessionColumn,
|
||||
};
|
||||
use imphnen_entities::seaorm::auth::users::Entity as Users;
|
||||
|
||||
pub struct SessionsRepository<'a> {
|
||||
pub db: &'a DatabaseConnection,
|
||||
}
|
||||
|
||||
impl<'a> SessionsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { db: state.postgres_db() }
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Create Session
|
||||
// ============================================
|
||||
pub async fn create_session(&self, schema: SessionSchema) -> Result<SessionSchema> {
|
||||
let mut result = schema.clone();
|
||||
|
||||
let session_active_model = SessionActiveModel {
|
||||
id: Set(schema.id),
|
||||
mentor_id: Set(schema.mentor_id),
|
||||
mentee_id: Set(schema.mentee_id),
|
||||
topic: Set(schema.topic),
|
||||
description: Set(schema.description),
|
||||
scheduled_at: Set(schema.scheduled_at),
|
||||
duration_minutes: Set(schema.duration_minutes),
|
||||
meeting_link: Set(schema.meeting_link),
|
||||
session_type: Set(schema.session_type),
|
||||
status: Set(schema.status),
|
||||
feedback: Set(schema.feedback),
|
||||
rating: Set(schema.rating),
|
||||
feedback_submitted_at: Set(schema.feedback_submitted_at),
|
||||
created_at: Set(schema.created_at),
|
||||
updated_at: Set(schema.updated_at),
|
||||
};
|
||||
|
||||
let session_model: SessionModel = session_active_model.insert(self.db).await?;
|
||||
|
||||
result.id = session_model.id;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Session by ID
|
||||
// ============================================
|
||||
pub async fn query_session_by_id(&self, id: &str) -> Result<Option<SessionSchema>> {
|
||||
let session_model: Option<SessionModel> = Sessions::find_by_id(Uuid::parse_str(id).map_err(|e| anyhow!("Invalid session ID: {}", e))?)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to fetch session: {}", e))?;
|
||||
|
||||
if let Some(session) = session_model {
|
||||
let schema = SessionSchema {
|
||||
id: session.id,
|
||||
mentor_id: session.mentor_id,
|
||||
mentee_id: session.mentee_id,
|
||||
topic: session.topic,
|
||||
description: session.description,
|
||||
scheduled_at: session.scheduled_at,
|
||||
duration_minutes: session.duration_minutes,
|
||||
meeting_link: session.meeting_link,
|
||||
session_type: session.session_type,
|
||||
status: session.status,
|
||||
feedback: session.feedback,
|
||||
rating: session.rating,
|
||||
feedback_submitted_at: session.feedback_submitted_at,
|
||||
created_at: session.created_at,
|
||||
updated_at: session.updated_at,
|
||||
};
|
||||
|
||||
Ok(Some(schema))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Session Detail with User Info
|
||||
// ============================================
|
||||
pub async fn query_session_detail(&self, id: &str) -> Result<Option<SessionDetailQueryDto>> {
|
||||
let session_id = Uuid::parse_str(id).map_err(|e| anyhow!("Invalid session ID: {}", e))?;
|
||||
|
||||
let session = Sessions::find_by_id(session_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to fetch session: {}", e))?
|
||||
.ok_or_else(|| anyhow!("Session not found"))?;
|
||||
|
||||
let mentor = Users::find_by_id(session.mentor_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to fetch mentor: {}", e))?
|
||||
.ok_or_else(|| anyhow!("Mentor not found"))?;
|
||||
|
||||
let mentee = Users::find_by_id(session.mentee_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to fetch mentee: {}", e))?
|
||||
.ok_or_else(|| anyhow!("Mentee not found"))?;
|
||||
|
||||
let session_detail = SessionDetailQueryDto {
|
||||
id: session.id.to_string(),
|
||||
mentor_id: session.mentor_id.to_string(),
|
||||
mentee_id: session.mentee_id.to_string(),
|
||||
topic: session.topic,
|
||||
description: session.description,
|
||||
scheduled_at: session.scheduled_at.to_rfc3339(),
|
||||
duration_minutes: session.duration_minutes,
|
||||
meeting_link: session.meeting_link,
|
||||
session_type: session.session_type,
|
||||
status: session.status,
|
||||
feedback: session.feedback,
|
||||
rating: session.rating,
|
||||
feedback_submitted_at: session.feedback_submitted_at.map(|dt| dt.to_rfc3339()),
|
||||
created_at: session.created_at.to_rfc3339(),
|
||||
updated_at: session.updated_at.to_rfc3339(),
|
||||
mentor_fullname: Some(format!("{} {}", mentor.first_name.unwrap_or_default(), mentor.last_name.unwrap_or_default())),
|
||||
mentee_fullname: Some(format!("{} {}", mentee.first_name.unwrap_or_default(), mentee.last_name.unwrap_or_default())),
|
||||
};
|
||||
|
||||
Ok(Some(session_detail))
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// List Mentor's Sessions
|
||||
// ============================================
|
||||
pub async fn query_mentor_sessions(
|
||||
&self,
|
||||
mentor_id: &str,
|
||||
status_filter: Option<String>,
|
||||
) -> Result<Vec<SessionListQueryDto>> {
|
||||
let mentor_uuid = Uuid::parse_str(mentor_id).map_err(|e| anyhow!("Invalid mentor ID: {}", e))?;
|
||||
|
||||
let query = Sessions::find()
|
||||
.filter(SessionColumn::MentorId.eq(mentor_uuid))
|
||||
.order_by_desc(SessionColumn::ScheduledAt);
|
||||
|
||||
let query = if let Some(status) = status_filter {
|
||||
query.filter(SessionColumn::Status.eq(status))
|
||||
} else {
|
||||
query
|
||||
};
|
||||
|
||||
let sessions = query.all(self.db).await.map_err(|e| anyhow!("Failed to query mentor sessions: {}", e))?;
|
||||
|
||||
let mut session_list = Vec::with_capacity(sessions.len());
|
||||
|
||||
for session in sessions {
|
||||
// Join with users table to get mentee details
|
||||
let mentee = Users::find_by_id(session.mentee_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to fetch mentee: {}", e))?;
|
||||
|
||||
let session_dto = SessionListQueryDto {
|
||||
id: session.id.to_string(),
|
||||
mentor_id: session.mentor_id.to_string(),
|
||||
mentee_id: session.mentee_id.to_string(),
|
||||
topic: session.topic,
|
||||
scheduled_at: session.scheduled_at.to_rfc3339(),
|
||||
duration_minutes: session.duration_minutes,
|
||||
session_type: session.session_type,
|
||||
status: session.status,
|
||||
rating: session.rating,
|
||||
created_at: session.created_at.to_rfc3339(),
|
||||
mentee_fullname: mentee.as_ref().map(|m| format!("{} {}", m.first_name.clone().unwrap_or_default(), m.last_name.clone().unwrap_or_default())),
|
||||
mentee_email: mentee.as_ref().map(|u| u.email.clone()), // Assuming Users model has an email field
|
||||
};
|
||||
|
||||
session_list.push(session_dto);
|
||||
}
|
||||
|
||||
Ok(session_list)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// List User's Sessions (as mentee)
|
||||
// ============================================
|
||||
pub async fn query_user_sessions(
|
||||
&self,
|
||||
user_id: &str,
|
||||
status_filter: Option<String>,
|
||||
) -> Result<Vec<SessionListQueryDto>> {
|
||||
let user_uuid = Uuid::parse_str(user_id).map_err(|e| anyhow!("Invalid user ID: {}", e))?;
|
||||
|
||||
let query = Sessions::find()
|
||||
.filter(SessionColumn::MenteeId.eq(user_uuid))
|
||||
.order_by_desc(SessionColumn::ScheduledAt);
|
||||
|
||||
let query = if let Some(status) = status_filter {
|
||||
query.filter(SessionColumn::Status.eq(status))
|
||||
} else {
|
||||
query
|
||||
};
|
||||
|
||||
let sessions = query.all(self.db).await.map_err(|e| anyhow!("Failed to query user sessions: {}", e))?;
|
||||
|
||||
let mut session_list = Vec::with_capacity(sessions.len());
|
||||
|
||||
for session in sessions {
|
||||
// Join with users table to get mentor details
|
||||
let _mentor = Users::find_by_id(session.mentor_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to fetch mentor: {}", e))?;
|
||||
|
||||
let session_dto = SessionListQueryDto {
|
||||
id: session.id.to_string(),
|
||||
mentor_id: session.mentor_id.to_string(),
|
||||
mentee_id: session.mentee_id.to_string(),
|
||||
topic: session.topic,
|
||||
scheduled_at: session.scheduled_at.to_rfc3339(),
|
||||
duration_minutes: session.duration_minutes,
|
||||
session_type: session.session_type,
|
||||
status: session.status,
|
||||
rating: session.rating,
|
||||
created_at: session.created_at.to_rfc3339(),
|
||||
mentee_fullname: Some(session.mentee_id.to_string()), // Simplified - should get from user table
|
||||
mentee_email: Some("user@example.com".to_string()), // Simplified - should get from user table
|
||||
};
|
||||
|
||||
session_list.push(session_dto);
|
||||
}
|
||||
|
||||
Ok(session_list)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Booked Dates for Mentor
|
||||
// ============================================
|
||||
pub async fn query_booked_dates(&self, mentor_id: &str) -> Result<Vec<String>> {
|
||||
let mentor_uuid = Uuid::parse_str(mentor_id).map_err(|e| anyhow!("Invalid mentor ID: {}", e))?;
|
||||
|
||||
let sessions = Sessions::find()
|
||||
.filter(SessionColumn::MentorId.eq(mentor_uuid))
|
||||
.filter(SessionColumn::Status.is_in(["pending", "confirmed"]))
|
||||
.order_by_asc(SessionColumn::ScheduledAt)
|
||||
.all(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to query booked dates: {}", e))?;
|
||||
|
||||
Ok(sessions.into_iter()
|
||||
.map(|s| s.scheduled_at.to_rfc3339())
|
||||
.collect())
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Update Session
|
||||
// ============================================
|
||||
pub async fn update_session(&self, id: &str, schema: SessionSchema) -> Result<SessionSchema> {
|
||||
let session_id = Uuid::parse_str(id).map_err(|e| anyhow!("Invalid session ID: {}", e))?;
|
||||
|
||||
let mut result = schema.clone();
|
||||
|
||||
// Fetch existing session
|
||||
let session_model = Sessions::find_by_id(session_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to fetch session for update: {}", e))?
|
||||
.ok_or_else(|| anyhow!("Session not found"))?;
|
||||
|
||||
// Convert to ActiveModel for update
|
||||
let mut session_active_model = session_model.into_active_model();
|
||||
|
||||
// Update fields
|
||||
session_active_model.topic = Set(schema.topic);
|
||||
session_active_model.description = Set(schema.description);
|
||||
session_active_model.scheduled_at = Set(schema.scheduled_at);
|
||||
session_active_model.duration_minutes = Set(schema.duration_minutes);
|
||||
session_active_model.meeting_link = Set(schema.meeting_link);
|
||||
session_active_model.session_type = Set(schema.session_type);
|
||||
session_active_model.status = Set(schema.status);
|
||||
session_active_model.feedback = Set(schema.feedback.clone());
|
||||
session_active_model.rating = Set(schema.rating);
|
||||
session_active_model.feedback_submitted_at = Set(schema.feedback_submitted_at);
|
||||
session_active_model.updated_at = Set(schema.updated_at);
|
||||
|
||||
// Save updated session
|
||||
let updated_session = session_active_model.update(self.db).await.map_err(|e| anyhow!("Failed to update session: {}", e))?;
|
||||
|
||||
// Convert back to SessionSchema for response
|
||||
result.id = updated_session.id;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Count Mentor Sessions
|
||||
// ============================================
|
||||
pub async fn count_mentor_sessions(
|
||||
&self,
|
||||
mentor_id: &str,
|
||||
status_filter: Option<String>,
|
||||
) -> Result<usize> {
|
||||
let mentor_uuid = Uuid::parse_str(mentor_id).map_err(|e| anyhow!("Invalid mentor ID: {}", e))?;
|
||||
|
||||
let query = Sessions::find()
|
||||
.filter(SessionColumn::MentorId.eq(mentor_uuid));
|
||||
|
||||
let query = if let Some(status) = status_filter {
|
||||
query.filter(SessionColumn::Status.eq(status))
|
||||
} else {
|
||||
query
|
||||
};
|
||||
|
||||
let count = query.count(self.db).await.map_err(|e| anyhow!("Failed to count mentor sessions: {}", e))?;
|
||||
|
||||
Ok(count as usize)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Count User Sessions
|
||||
// ============================================
|
||||
pub async fn count_user_sessions(
|
||||
&self,
|
||||
user_id: &str,
|
||||
status_filter: Option<String>,
|
||||
) -> Result<usize> {
|
||||
let user_uuid = Uuid::parse_str(user_id).map_err(|e| anyhow!("Invalid user ID: {}", e))?;
|
||||
|
||||
let query = Sessions::find()
|
||||
.filter(SessionColumn::MenteeId.eq(user_uuid));
|
||||
|
||||
let query = if let Some(status) = status_filter {
|
||||
query.filter(SessionColumn::Status.eq(status))
|
||||
} else {
|
||||
query
|
||||
};
|
||||
|
||||
let count = query.count(self.db).await.map_err(|e| anyhow!("Failed to count user sessions: {}", e))?;
|
||||
|
||||
Ok(count as usize)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Delete Session (soft delete)
|
||||
// ============================================
|
||||
pub async fn delete_session(&self, id: &str) -> Result<()> {
|
||||
let session_id = Uuid::parse_str(id).map_err(|e| anyhow!("Invalid session ID: {}", e))?;
|
||||
|
||||
// Fetch the session first
|
||||
let session_model = Sessions::find_by_id(session_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to fetch session for deletion: {}", e))?
|
||||
.ok_or_else(|| anyhow!("Session not found"))?;
|
||||
|
||||
// Convert to ActiveModel for deletion
|
||||
let session_active_model = session_model.into_active_model();
|
||||
|
||||
// For soft delete, we would typically set an `is_deleted` flag
|
||||
// Since the original implementation didn't have this, we'll just delete the record
|
||||
// If you want to implement soft delete, add an `is_deleted` field to the SessionModel
|
||||
|
||||
let _ = session_active_model.delete(self.db).await.map_err(|e| anyhow!("Failed to delete session: {}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
use super::{BookSessionRequestDto, SessionFeedbackRequestDto, UpdateSessionStatusRequestDto};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
|
||||
// Type alias for Thing
|
||||
pub type Thing = String;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct SessionSchema {
|
||||
pub id: Uuid,
|
||||
pub mentor_id: Uuid,
|
||||
pub mentee_id: Uuid,
|
||||
pub topic: String,
|
||||
pub description: Option<String>,
|
||||
pub scheduled_at: DateTime<Utc>,
|
||||
pub duration_minutes: i32,
|
||||
pub meeting_link: Option<String>,
|
||||
pub session_type: String, // "video_call", "phone_call", "chat"
|
||||
pub status: String, // "pending", "confirmed", "completed", "cancelled", "no_show"
|
||||
pub feedback: Option<String>,
|
||||
pub rating: Option<i32>, // 1-5
|
||||
pub feedback_submitted_at: Option<DateTime<Utc>>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl Default for SessionSchema {
|
||||
fn default() -> Self {
|
||||
let now = Utc::now();
|
||||
Self {
|
||||
id: Uuid::new_v4(),
|
||||
mentor_id: Uuid::new_v4(),
|
||||
mentee_id: Uuid::new_v4(),
|
||||
topic: String::new(),
|
||||
description: None,
|
||||
scheduled_at: now,
|
||||
duration_minutes: 60,
|
||||
meeting_link: None,
|
||||
session_type: "video_call".to_string(),
|
||||
status: "pending".to_string(),
|
||||
feedback: None,
|
||||
rating: None,
|
||||
feedback_submitted_at: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionSchema {
|
||||
pub fn from_book_request(
|
||||
mentor_id: Thing,
|
||||
mentee_id: Thing,
|
||||
request: BookSessionRequestDto,
|
||||
) -> Result<Self, Error> {
|
||||
let scheduled_at = DateTime::parse_from_rfc3339(&request.scheduled_at)
|
||||
.map_err(|e| Error::Validation(format!("Invalid scheduled_at format: {}", e)))?
|
||||
.with_timezone(&Utc);
|
||||
|
||||
let mentor_id = Uuid::parse_str(&mentor_id)
|
||||
.map_err(|e| Error::Validation(format!("Invalid mentor_id: {}", e)))?;
|
||||
let mentee_id = Uuid::parse_str(&mentee_id)
|
||||
.map_err(|e| Error::Validation(format!("Invalid mentee_id: {}", e)))?;
|
||||
|
||||
Ok(Self {
|
||||
mentor_id,
|
||||
mentee_id,
|
||||
topic: request.topic,
|
||||
description: request.description,
|
||||
scheduled_at,
|
||||
duration_minutes: request.duration_minutes.unwrap_or(60),
|
||||
session_type: request.session_type.unwrap_or_else(|| "video_call".to_string()),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update_status(&mut self, request: UpdateSessionStatusRequestDto) {
|
||||
self.status = request.status;
|
||||
if let Some(link) = request.meeting_link {
|
||||
self.meeting_link = Some(link);
|
||||
}
|
||||
self.updated_at = Utc::now();
|
||||
}
|
||||
|
||||
pub fn add_feedback(&mut self, request: SessionFeedbackRequestDto) {
|
||||
self.feedback = Some(request.feedback);
|
||||
self.rating = Some(request.rating);
|
||||
self.feedback_submitted_at = Some(Utc::now());
|
||||
self.updated_at = Utc::now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
use super::{
|
||||
AvailabilitySlotDto, BookSessionRequestDto, BookSessionResponseDto, MentorAvailabilityDto,
|
||||
SessionFeedbackRequestDto, SessionFeedbackResponseDto, SessionListItemDto,
|
||||
SessionListResponseDto, SessionSchema, SessionsRepository, UpdateSessionStatusRequestDto,
|
||||
UpdateSessionStatusResponseDto,
|
||||
};
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use imphnen_entities::ResponseSuccessDto;
|
||||
use imphnen_libs::AppState;
|
||||
use imphnen_utils::{common_response, success_response, validator::validate_request};
|
||||
use uuid;
|
||||
|
||||
pub struct SessionsService;
|
||||
|
||||
impl SessionsService {
|
||||
// ============================================
|
||||
// Book Session
|
||||
// ============================================
|
||||
pub async fn book_session(
|
||||
state: &AppState,
|
||||
mentor_id: String,
|
||||
user_id: String,
|
||||
dto: BookSessionRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&dto) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
|
||||
let scheduled_at = match DateTime::parse_from_rfc3339(&dto.scheduled_at) {
|
||||
Ok(dt) => dt.with_timezone(&Utc),
|
||||
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid scheduled_at format: {}", e)),
|
||||
};
|
||||
|
||||
let schema = SessionSchema {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
mentor_id: match uuid::Uuid::parse_str(&mentor_id) {
|
||||
Ok(id) => id,
|
||||
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid mentor ID: {}", e)),
|
||||
},
|
||||
mentee_id: match uuid::Uuid::parse_str(&user_id) {
|
||||
Ok(id) => id,
|
||||
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid user ID: {}", e)),
|
||||
},
|
||||
topic: dto.topic,
|
||||
description: dto.description,
|
||||
scheduled_at,
|
||||
duration_minutes: dto.duration_minutes.unwrap_or(60),
|
||||
meeting_link: None,
|
||||
session_type: dto.session_type.unwrap_or_else(|| "video_call".to_string()),
|
||||
status: "pending".to_string(),
|
||||
feedback: None,
|
||||
rating: None,
|
||||
feedback_submitted_at: None,
|
||||
created_at: Utc::now(),
|
||||
updated_at: Utc::now(),
|
||||
};
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
match repo.create_session(schema).await {
|
||||
Ok(created) => {
|
||||
let response = BookSessionResponseDto {
|
||||
id: created.id.to_string(),
|
||||
mentor_id: created.mentor_id.to_string(),
|
||||
mentee_id: created.mentee_id.to_string(),
|
||||
topic: created.topic,
|
||||
description: created.description,
|
||||
scheduled_at: created.scheduled_at.to_rfc3339(),
|
||||
duration_minutes: created.duration_minutes,
|
||||
session_type: created.session_type,
|
||||
status: created.status,
|
||||
created_at: created.created_at.to_rfc3339(),
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Mentor's Sessions
|
||||
// ============================================
|
||||
pub async fn get_mentor_sessions(
|
||||
state: &AppState,
|
||||
mentor_id: String,
|
||||
_user_email: String,
|
||||
status_filter: Option<String>,
|
||||
) -> Response {
|
||||
let repo = SessionsRepository::new(state);
|
||||
|
||||
// Get count and sessions
|
||||
let count = match repo.count_mentor_sessions(&mentor_id, status_filter.clone()).await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return common_response(StatusCode::INTERNAL_SERVER_ERROR, &format!("Failed to count sessions: {}", e)),
|
||||
};
|
||||
|
||||
match repo.query_mentor_sessions(&mentor_id, status_filter).await {
|
||||
Ok(sessions) => {
|
||||
let session_items: Vec<SessionListItemDto> = sessions
|
||||
.into_iter()
|
||||
.map(|s| SessionListItemDto {
|
||||
id: s.id,
|
||||
mentor_id: s.mentor_id,
|
||||
mentee_id: s.mentee_id,
|
||||
mentee_fullname: s.mentee_fullname,
|
||||
mentee_email: s.mentee_email,
|
||||
topic: s.topic,
|
||||
scheduled_at: s.scheduled_at,
|
||||
duration_minutes: s.duration_minutes,
|
||||
session_type: s.session_type,
|
||||
status: s.status,
|
||||
rating: s.rating,
|
||||
created_at: s.created_at,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let response = SessionListResponseDto {
|
||||
sessions: session_items,
|
||||
total: count,
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get User's Sessions (as mentee)
|
||||
// ============================================
|
||||
pub async fn get_user_sessions(
|
||||
state: &AppState,
|
||||
user_id: String,
|
||||
status_filter: Option<String>,
|
||||
) -> Response {
|
||||
let repo = SessionsRepository::new(state);
|
||||
|
||||
// Get count and sessions
|
||||
let count = match repo.count_user_sessions(&user_id, status_filter.clone()).await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return common_response(StatusCode::INTERNAL_SERVER_ERROR, &format!("Failed to count sessions: {}", e)),
|
||||
};
|
||||
|
||||
match repo.query_user_sessions(&user_id, status_filter).await {
|
||||
Ok(sessions) => {
|
||||
let session_items: Vec<SessionListItemDto> = sessions
|
||||
.into_iter()
|
||||
.map(|s| SessionListItemDto {
|
||||
id: s.id,
|
||||
mentor_id: s.mentor_id,
|
||||
mentee_id: s.mentee_id,
|
||||
mentee_fullname: s.mentee_fullname,
|
||||
mentee_email: s.mentee_email,
|
||||
topic: s.topic,
|
||||
scheduled_at: s.scheduled_at,
|
||||
duration_minutes: s.duration_minutes,
|
||||
session_type: s.session_type,
|
||||
status: s.status,
|
||||
rating: s.rating,
|
||||
created_at: s.created_at,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let response = SessionListResponseDto {
|
||||
sessions: session_items,
|
||||
total: count,
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Mentor Availability
|
||||
// ============================================
|
||||
pub async fn get_mentor_availability(state: &AppState, mentor_id: String) -> Response {
|
||||
let repo = SessionsRepository::new(state);
|
||||
match repo.query_booked_dates(&mentor_id).await {
|
||||
Ok(booked_dates) => {
|
||||
// Generate sample availability slots (next 7 days)
|
||||
let mut slots = Vec::new();
|
||||
let today = Utc::now().date_naive();
|
||||
|
||||
for i in 0..7 {
|
||||
let date = today + Duration::days(i);
|
||||
let date_str = date.format("%Y-%m-%d").to_string();
|
||||
|
||||
// Generate time slots (9 AM to 5 PM, every hour)
|
||||
for hour in 9..17 {
|
||||
let time_str = format!("{:02}:00", hour);
|
||||
let datetime_str = format!("{}T{}:00Z", date_str, time_str);
|
||||
|
||||
// Check if this slot is booked
|
||||
let is_booked = booked_dates.iter().any(|d| d.starts_with(&datetime_str[..13]));
|
||||
|
||||
slots.push(AvailabilitySlotDto {
|
||||
date: date_str.clone(),
|
||||
time: time_str,
|
||||
available: !is_booked,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let response = MentorAvailabilityDto {
|
||||
mentor_id,
|
||||
availability_commitment: "Available weekdays 9 AM - 5 PM".to_string(),
|
||||
preferred_formats: vec!["video_call".to_string(), "phone_call".to_string()],
|
||||
slots,
|
||||
booked_dates,
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Update Session Status
|
||||
// ============================================
|
||||
pub async fn update_session_status(
|
||||
state: &AppState,
|
||||
session_id: String,
|
||||
_user_id: String,
|
||||
dto: UpdateSessionStatusRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&dto) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
match repo.query_session_by_id(&session_id).await {
|
||||
Ok(Some(mut session)) => {
|
||||
session.status = dto.status.clone();
|
||||
if let Some(link) = &dto.meeting_link {
|
||||
session.meeting_link = Some(link.clone());
|
||||
}
|
||||
session.updated_at = Utc::now();
|
||||
|
||||
match repo.update_session(&session_id, session).await {
|
||||
Ok(updated) => {
|
||||
let response = UpdateSessionStatusResponseDto {
|
||||
id: updated.id.to_string(),
|
||||
status: updated.status,
|
||||
meeting_link: updated.meeting_link,
|
||||
updated_at: updated.updated_at.to_rfc3339(),
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
Ok(None) => common_response(StatusCode::NOT_FOUND, "Session not found"),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Submit Feedback
|
||||
// ============================================
|
||||
pub async fn submit_feedback(
|
||||
state: &AppState,
|
||||
session_id: String,
|
||||
user_id: String,
|
||||
dto: SessionFeedbackRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&dto) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
match repo.query_session_by_id(&session_id).await {
|
||||
Ok(Some(mut session)) => {
|
||||
// Authorization: Only mentee can submit feedback
|
||||
let mentee_id = session.mentee_id.to_string();
|
||||
if mentee_id != user_id {
|
||||
return common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"Unauthorized: Only the mentee can submit feedback",
|
||||
);
|
||||
}
|
||||
|
||||
// Validate session is completed
|
||||
if session.status != "completed" {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Feedback can only be submitted for completed sessions",
|
||||
);
|
||||
}
|
||||
|
||||
session.feedback = Some(dto.feedback.clone());
|
||||
session.rating = Some(dto.rating);
|
||||
session.feedback_submitted_at = Some(Utc::now());
|
||||
session.updated_at = Utc::now();
|
||||
|
||||
match repo.update_session(&session_id, session).await {
|
||||
Ok(updated) => {
|
||||
let response = SessionFeedbackResponseDto {
|
||||
id: updated.id.to_string(),
|
||||
feedback: dto.feedback,
|
||||
rating: dto.rating,
|
||||
submitted_at: updated.feedback_submitted_at.unwrap_or(Utc::now()).to_rfc3339(),
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
Ok(None) => common_response(StatusCode::NOT_FOUND, "Session not found"),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/// Version 2 of the Dimentorin API - currently under development
|
||||
/// This module will contain all version 2 endpoints following API versioning best practices
|
||||
|
||||
use axum::Router;
|
||||
|
||||
/// Placeholder for version 2 router
|
||||
/// To be implemented when version 2 endpoints are ready
|
||||
pub fn dimentorin_v2_router() -> Router {
|
||||
Router::new()
|
||||
// Version 2 endpoints will be added here following the same pattern as v1
|
||||
}
|
||||
|
||||
// Re-export the v1 router for backward compatibility
|
||||
pub use crate::v1::dimentorin_router;
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "imphnen-entities"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
utoipa.workspace = true
|
||||
anyhow.workspace = true
|
||||
thiserror.workspace = true
|
||||
uuid.workspace = true
|
||||
chrono.workspace = true
|
||||
sea-orm.workspace = true
|
||||
strum.workspace = true
|
||||
imphnen-macros.workspace = true
|
||||
sqlx = { version = "0.8", features = ["postgres", "runtime-tokio-native-tls", "uuid", "chrono", "json"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
use crate::seaorm::common::audit_log;
|
||||
|
||||
pub type AuditLogSchema = audit_log::Model;
|
||||
@@ -0,0 +1,64 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::{IntoParams, ToSchema};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MessageResponseDto {
|
||||
pub message: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, IntoParams)]
|
||||
pub struct MetaRequestDto {
|
||||
pub page: Option<u64>,
|
||||
pub per_page: Option<u64>,
|
||||
pub search: Option<String>,
|
||||
pub sort_by: Option<String>,
|
||||
pub order: Option<String>,
|
||||
pub filter: Option<String>,
|
||||
pub filter_by: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for MetaRequestDto {
|
||||
fn default() -> Self {
|
||||
MetaRequestDto {
|
||||
page: Some(1),
|
||||
per_page: Some(10),
|
||||
search: None,
|
||||
sort_by: None,
|
||||
order: None,
|
||||
filter: None,
|
||||
filter_by: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, IntoParams)]
|
||||
pub struct MetaResponseDto {
|
||||
pub page: Option<u64>,
|
||||
pub per_page: Option<u64>,
|
||||
pub total: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct ResponseSuccessDto<T: Serialize> {
|
||||
pub data: T,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct ResponseListSuccessDto<T: Serialize> {
|
||||
pub data: T,
|
||||
pub meta: Option<MetaResponseDto>,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct ErrorDto {
|
||||
pub status: u16,
|
||||
pub message: String,
|
||||
pub details: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct CountResult {
|
||||
pub count: u64,
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
pub mod error {
|
||||
use axum::Json;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::response::Response;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("database error: {0}")]
|
||||
Db(String),
|
||||
#[error("anyhow error: {0}")]
|
||||
Anyhow(#[from] anyhow::Error),
|
||||
#[error("HTTP status code error: {0}")]
|
||||
StatusCode(StatusCode),
|
||||
#[error("authentication error: {0}")]
|
||||
Auth(String),
|
||||
#[error("validation error: {0}")]
|
||||
Validation(String),
|
||||
}
|
||||
|
||||
impl IntoResponse for Error {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, error_message) = match self {
|
||||
Error::Db(detail) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database error: {detail}"),
|
||||
),
|
||||
Error::Anyhow(detail) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Internal server error: {detail}"),
|
||||
),
|
||||
Error::StatusCode(s) => (s, format!("HTTP error: {s}")),
|
||||
Error::Auth(detail) => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
format!("Authentication error: {detail}"),
|
||||
),
|
||||
Error::Validation(detail) => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("Validation error: {detail}"),
|
||||
),
|
||||
};
|
||||
(status, Json(error_message)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StatusCode> for Error {
|
||||
fn from(status: StatusCode) -> Self {
|
||||
Self::StatusCode(status)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
pub mod common_dto;
|
||||
pub mod error_dto;
|
||||
pub mod users;
|
||||
pub mod permissions;
|
||||
pub mod audit_log;
|
||||
pub mod seaorm;
|
||||
|
||||
// Re-export error type at root level for convenience
|
||||
pub use error_dto::error::Error;
|
||||
|
||||
// Explicit common_dto exports
|
||||
pub use common_dto::CountResult;
|
||||
pub use common_dto::ErrorDto;
|
||||
pub use common_dto::MessageResponseDto;
|
||||
pub use common_dto::MetaRequestDto;
|
||||
pub use common_dto::MetaResponseDto;
|
||||
pub use common_dto::ResponseListSuccessDto;
|
||||
pub use common_dto::ResponseSuccessDto;
|
||||
|
||||
// Explicit users exports
|
||||
pub use users::EducationDto;
|
||||
pub use users::ExperienceDto;
|
||||
pub use users::RolesDetailItemDto;
|
||||
pub use users::RolesDetailQueryDto;
|
||||
pub use users::UsersDetailQueryDto;
|
||||
|
||||
// Explicit permissions exports
|
||||
pub use permissions::PermissionsEnum;
|
||||
pub use permissions::PermissionsItemDto;
|
||||
pub use permissions::PermissionsQueryDto;
|
||||
pub use seaorm::common::enums::ResourceEnum;
|
||||
|
||||
// Explicit audit_log exports
|
||||
pub use audit_log::AuditLogSchema;
|
||||
|
||||
// SeaORM entity exports
|
||||
pub use seaorm::*;
|
||||
@@ -0,0 +1,273 @@
|
||||
use std::fmt;
|
||||
use uuid::Uuid;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, strum::EnumIter)]
|
||||
pub enum PermissionsEnum {
|
||||
// User permissions
|
||||
ReadListUsers,
|
||||
ReadDetailUsers,
|
||||
CreateUsers,
|
||||
DeleteUsers,
|
||||
UpdateUsers,
|
||||
ActivateUsers,
|
||||
|
||||
// Role permissions
|
||||
ReadListRoles,
|
||||
ReadDetailRoles,
|
||||
CreateRoles,
|
||||
DeleteRoles,
|
||||
UpdateRoles,
|
||||
|
||||
// Permission permissions
|
||||
ReadListPermissions,
|
||||
ReadDetailPermissions,
|
||||
CreatePermissions,
|
||||
DeletePermissions,
|
||||
UpdatePermissions,
|
||||
|
||||
// Administrator permissions
|
||||
ManageAllUsers,
|
||||
ManageAllRoles,
|
||||
ManageAllPermissions,
|
||||
ViewAllSensitiveData,
|
||||
AccessAdminDashboard,
|
||||
Administrator,
|
||||
|
||||
// Gacha permissions
|
||||
CreateGachaClaims,
|
||||
ReadDetailGachaClaims,
|
||||
ReadListGachaItems,
|
||||
ReadDetailGachaItems,
|
||||
CreateGachaItems,
|
||||
DeleteGachaItems,
|
||||
UpdateGachaItems,
|
||||
ReadDetailGachaRolls,
|
||||
CreateGachaRolls,
|
||||
ExecuteGachaRolls,
|
||||
DeleteGachaRolls,
|
||||
|
||||
// Mentor permissions
|
||||
ReadListMentors,
|
||||
ReadDetailMentors,
|
||||
RegisterMentors,
|
||||
ReadOwnMentorProfile,
|
||||
UpdateOwnMentorProfile,
|
||||
ReadOwnMentorStatus,
|
||||
UpdateMentors,
|
||||
VerifyMentors,
|
||||
DeleteMentors,
|
||||
}
|
||||
|
||||
impl fmt::Display for PermissionsEnum {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let permission_str = match self {
|
||||
// User permissions
|
||||
PermissionsEnum::ReadListUsers => "Read List Users",
|
||||
PermissionsEnum::ReadDetailUsers => "Read Detail Users",
|
||||
PermissionsEnum::CreateUsers => "Create Users",
|
||||
PermissionsEnum::DeleteUsers => "Delete Users",
|
||||
PermissionsEnum::UpdateUsers => "Update Users",
|
||||
PermissionsEnum::ActivateUsers => "Activate Users",
|
||||
|
||||
// Role permissions
|
||||
PermissionsEnum::ReadListRoles => "Read List Roles",
|
||||
PermissionsEnum::ReadDetailRoles => "Read Detail Roles",
|
||||
PermissionsEnum::CreateRoles => "Create Roles",
|
||||
PermissionsEnum::DeleteRoles => "Delete Roles",
|
||||
PermissionsEnum::UpdateRoles => "Update Roles",
|
||||
|
||||
// Permission permissions
|
||||
PermissionsEnum::ReadListPermissions => "Read List Permissions",
|
||||
PermissionsEnum::ReadDetailPermissions => "Read Detail Permissions",
|
||||
PermissionsEnum::CreatePermissions => "Create Permissions",
|
||||
PermissionsEnum::DeletePermissions => "Delete Permissions",
|
||||
PermissionsEnum::UpdatePermissions => "Update Permissions",
|
||||
|
||||
// Gacha permissions
|
||||
PermissionsEnum::CreateGachaClaims => "Create Gacha Claims",
|
||||
PermissionsEnum::ReadDetailGachaClaims => "Read Detail Gacha Claims",
|
||||
PermissionsEnum::ReadListGachaItems => "Read List Gacha Items",
|
||||
PermissionsEnum::ReadDetailGachaItems => "Read Detail Gacha Items",
|
||||
PermissionsEnum::CreateGachaItems => "Create Gacha Items",
|
||||
PermissionsEnum::DeleteGachaItems => "Delete Gacha Items",
|
||||
PermissionsEnum::UpdateGachaItems => "Update Gacha Items",
|
||||
PermissionsEnum::ReadDetailGachaRolls => "Read Detail Gacha Rolls",
|
||||
PermissionsEnum::CreateGachaRolls => "Create Gacha Rolls",
|
||||
PermissionsEnum::ExecuteGachaRolls => "Execute Gacha Rolls",
|
||||
PermissionsEnum::DeleteGachaRolls => "Delete Gacha Rolls",
|
||||
|
||||
// Mentor permissions
|
||||
PermissionsEnum::ReadListMentors => "Read List Mentors",
|
||||
PermissionsEnum::ReadDetailMentors => "Read Detail Mentors",
|
||||
PermissionsEnum::RegisterMentors => "Register Mentors",
|
||||
PermissionsEnum::ReadOwnMentorProfile => "Read Own Mentor Profile",
|
||||
PermissionsEnum::UpdateOwnMentorProfile => "Update Own Mentor Profile",
|
||||
PermissionsEnum::ReadOwnMentorStatus => "Read Own Mentor Status",
|
||||
PermissionsEnum::UpdateMentors => "Update Mentors",
|
||||
PermissionsEnum::VerifyMentors => "Verify Mentors",
|
||||
PermissionsEnum::DeleteMentors => "Delete Mentors",
|
||||
|
||||
// Administrator permissions
|
||||
PermissionsEnum::ManageAllUsers => "Manage All Users",
|
||||
PermissionsEnum::ManageAllRoles => "Manage All Roles",
|
||||
PermissionsEnum::ManageAllPermissions => "Manage All Permissions",
|
||||
PermissionsEnum::ViewAllSensitiveData => "View All Sensitive Data",
|
||||
PermissionsEnum::AccessAdminDashboard => "Access Admin Dashboard",
|
||||
PermissionsEnum::Administrator => "Administrator",
|
||||
};
|
||||
write!(f, "{permission_str}")
|
||||
}
|
||||
}
|
||||
|
||||
impl PermissionsEnum {
|
||||
pub fn id(&self) -> String {
|
||||
match self {
|
||||
// User permissions
|
||||
PermissionsEnum::ReadListUsers => "7c15e31d-36e2-49f9-97db-138c03fb0cf6".to_string(),
|
||||
PermissionsEnum::ReadDetailUsers => "319ee593-ff0a-4f29-bbaf-9feb3174a3a6".to_string(),
|
||||
PermissionsEnum::CreateUsers => "023e2dfe-93c3-4008-94a8-b5dff403f73b".to_string(),
|
||||
PermissionsEnum::DeleteUsers => "96df0689-2ae9-4894-bf00-837c19415e5c".to_string(),
|
||||
PermissionsEnum::UpdateUsers => "98b3dc4c-0124-461f-afcd-166637c5e6e8".to_string(),
|
||||
PermissionsEnum::ActivateUsers => "4da8b434-89f9-4d91-85ae-eebd63cdbeda".to_string(),
|
||||
|
||||
// Role permissions
|
||||
PermissionsEnum::ReadListRoles => "9164ca6e-c7e3-4238-a15f-f36ab9577e7e".to_string(),
|
||||
PermissionsEnum::ReadDetailRoles => "73888d18-b3e9-4f62-95a5-ba2c0d69fccb".to_string(),
|
||||
PermissionsEnum::CreateRoles => "319ee593-ff0a-4f29-bbaf-9feb3174a3a2".to_string(),
|
||||
PermissionsEnum::DeleteRoles => "35b0d992-65c8-4b62-b030-e6e0320e4048".to_string(),
|
||||
PermissionsEnum::UpdateRoles => "a00d5608-4c48-4542-845c-dfe004687022".to_string(),
|
||||
|
||||
// Permission permissions
|
||||
PermissionsEnum::ReadListPermissions => "8195eeb8-e64f-4172-aa57-596492c84a72".to_string(),
|
||||
PermissionsEnum::ReadDetailPermissions => "dad435cf-042c-41bd-a946-cea61ed2ffbc".to_string(),
|
||||
PermissionsEnum::CreatePermissions => "0269ed71-0ae0-4c43-ad29-e3d861d8f9a0".to_string(),
|
||||
PermissionsEnum::DeletePermissions => "b2dc3928-86ba-4c59-a03d-0b57d5183ebc".to_string(),
|
||||
PermissionsEnum::UpdatePermissions => "299cb4d5-6556-4cc9-b6c1-32e6d31e0f9b".to_string(),
|
||||
|
||||
// Gacha permissions
|
||||
PermissionsEnum::CreateGachaClaims => "f41d53ce-4f88-4bb6-b9b4-5e3a8c38d962".to_string(),
|
||||
PermissionsEnum::ReadDetailGachaClaims => "c1c3d6c2-19fb-4b70-b58c-c19f2e8cfc79".to_string(),
|
||||
PermissionsEnum::ReadListGachaItems => "fa6eb842-0a61-40c2-9c24-b226ad975037".to_string(),
|
||||
PermissionsEnum::ReadDetailGachaItems => "9c7857d7-b5ae-4688-923d-ef5572e9bc8b".to_string(),
|
||||
PermissionsEnum::CreateGachaItems => "cf063be1-4d71-489e-b9fb-1c08c65f396c".to_string(),
|
||||
PermissionsEnum::DeleteGachaItems => "46f8c6cf-ea0c-4c90-860c-69e2e65f7eb1".to_string(),
|
||||
PermissionsEnum::UpdateGachaItems => "2d0cf4ae-56ae-4714-a12e-655cfc3d9eb2".to_string(),
|
||||
PermissionsEnum::ReadDetailGachaRolls => "53d6483a-04cd-4667-8792-2d0cc8e2d343".to_string(),
|
||||
PermissionsEnum::CreateGachaRolls => "18e36c63-fcb7-4877-b911-c5aa611e878f".to_string(),
|
||||
PermissionsEnum::ExecuteGachaRolls => "14c6a1cd-5c63-4643-89b5-b1a5f9920cc0".to_string(),
|
||||
PermissionsEnum::DeleteGachaRolls => "12345678-ABCD-EFAB-CDEF-0123456789AB".to_string(),
|
||||
|
||||
// Mentor permissions
|
||||
PermissionsEnum::ReadListMentors => "a1b2c3d4-5e6f-7890-abcd-ef1234567890".to_string(),
|
||||
PermissionsEnum::ReadDetailMentors => "b2c3d4e5-6f78-9012-bcde-f23456789012".to_string(),
|
||||
PermissionsEnum::RegisterMentors => "c3d4e5f6-7890-1234-cdef-345678901234".to_string(),
|
||||
PermissionsEnum::ReadOwnMentorProfile => "d4e5f6a7-8901-2345-def0-456789012345".to_string(),
|
||||
PermissionsEnum::UpdateOwnMentorProfile => "e5f6a7b8-9012-3456-ef01-567890123456".to_string(),
|
||||
PermissionsEnum::ReadOwnMentorStatus => "f6a7b8c9-0123-4567-f012-678901234567".to_string(),
|
||||
PermissionsEnum::UpdateMentors => "a7b8c9d0-1234-5678-0123-789012345678".to_string(),
|
||||
PermissionsEnum::VerifyMentors => "b8c9d0e1-2345-6789-1234-890123456789".to_string(),
|
||||
PermissionsEnum::DeleteMentors => "c9d0e1f2-3456-7890-2345-901234567890".to_string(),
|
||||
|
||||
// Administrator permissions
|
||||
PermissionsEnum::ManageAllUsers => "d0e1f2a3-4567-8901-2345-0123456789ab".to_string(),
|
||||
PermissionsEnum::ManageAllRoles => "e1f2a3b4-5678-9012-3456-1234567890ab".to_string(),
|
||||
PermissionsEnum::ManageAllPermissions => "f2a3b4c5-6789-0123-4567-2345678901ab".to_string(),
|
||||
PermissionsEnum::ViewAllSensitiveData => "b4c5d6e7-8901-2345-6789-4567890123ab".to_string(),
|
||||
PermissionsEnum::AccessAdminDashboard => "c5d6e7f8-9012-3456-7890-5678901234ab".to_string(),
|
||||
PermissionsEnum::Administrator => "d6e7f8a9-0123-4567-8901-6789012345ab".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a new unique ID for a permission
|
||||
pub fn generate_id() -> String {
|
||||
Uuid::new_v4().to_string()
|
||||
}
|
||||
|
||||
/// Get all permissions as a vector
|
||||
pub fn all() -> Vec<PermissionsEnum> {
|
||||
vec![
|
||||
// User permissions
|
||||
PermissionsEnum::ReadListUsers,
|
||||
PermissionsEnum::ReadDetailUsers,
|
||||
PermissionsEnum::CreateUsers,
|
||||
PermissionsEnum::DeleteUsers,
|
||||
PermissionsEnum::UpdateUsers,
|
||||
PermissionsEnum::ActivateUsers,
|
||||
|
||||
// Role permissions
|
||||
PermissionsEnum::ReadListRoles,
|
||||
PermissionsEnum::ReadDetailRoles,
|
||||
PermissionsEnum::CreateRoles,
|
||||
PermissionsEnum::DeleteRoles,
|
||||
PermissionsEnum::UpdateRoles,
|
||||
|
||||
// Permission permissions
|
||||
PermissionsEnum::ReadListPermissions,
|
||||
PermissionsEnum::ReadDetailPermissions,
|
||||
PermissionsEnum::CreatePermissions,
|
||||
PermissionsEnum::DeletePermissions,
|
||||
PermissionsEnum::UpdatePermissions,
|
||||
|
||||
// Gacha permissions
|
||||
PermissionsEnum::CreateGachaClaims,
|
||||
PermissionsEnum::ReadDetailGachaClaims,
|
||||
PermissionsEnum::ReadListGachaItems,
|
||||
PermissionsEnum::ReadDetailGachaItems,
|
||||
PermissionsEnum::CreateGachaItems,
|
||||
PermissionsEnum::DeleteGachaItems,
|
||||
PermissionsEnum::UpdateGachaItems,
|
||||
PermissionsEnum::ReadDetailGachaRolls,
|
||||
PermissionsEnum::CreateGachaRolls,
|
||||
PermissionsEnum::ExecuteGachaRolls,
|
||||
PermissionsEnum::DeleteGachaRolls,
|
||||
|
||||
// Mentor permissions
|
||||
PermissionsEnum::ReadListMentors,
|
||||
PermissionsEnum::ReadDetailMentors,
|
||||
PermissionsEnum::RegisterMentors,
|
||||
PermissionsEnum::ReadOwnMentorProfile,
|
||||
PermissionsEnum::UpdateOwnMentorProfile,
|
||||
PermissionsEnum::ReadOwnMentorStatus,
|
||||
PermissionsEnum::UpdateMentors,
|
||||
PermissionsEnum::VerifyMentors,
|
||||
PermissionsEnum::DeleteMentors,
|
||||
|
||||
// Administrator permissions
|
||||
PermissionsEnum::ManageAllUsers,
|
||||
PermissionsEnum::ManageAllRoles,
|
||||
PermissionsEnum::ManageAllPermissions,
|
||||
PermissionsEnum::ViewAllSensitiveData,
|
||||
PermissionsEnum::AccessAdminDashboard,
|
||||
PermissionsEnum::Administrator,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct PermissionsItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl PermissionsItemDto {
|
||||
pub fn from(dto: &PermissionsQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.clone().unwrap_or_default(),
|
||||
name: dto.name.clone().unwrap_or_default(),
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct PermissionsQueryDto {
|
||||
pub id: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! SeaORM entity for Mentors table
|
||||
//! Corresponding to ResourceEnum::Mentors
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use sea_orm::entity::prelude::*;
|
||||
use sea_orm::{ActiveModelBehavior, DeriveEntityModel, DeriveRelation};
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize, imphnen_macros::Builder)]
|
||||
#[sea_orm(table_name = "app_mentors")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, default = "gen_random_uuid()", auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
|
||||
#[sea_orm(unique, not_null)]
|
||||
pub user_id: Uuid,
|
||||
|
||||
#[sea_orm(type = "jsonb", nullable)]
|
||||
pub industries: Option<serde_json::Value>,
|
||||
|
||||
#[sea_orm(type = "jsonb", nullable)]
|
||||
pub expertise: Option<serde_json::Value>,
|
||||
|
||||
#[sea_orm(type = "jsonb", nullable)]
|
||||
pub languages: Option<serde_json::Value>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub current_company: Option<String>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub current_role: Option<String>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub years_of_experience: Option<i32>,
|
||||
|
||||
#[sea_orm(type = "jsonb", nullable)]
|
||||
pub topics_of_interest: Option<serde_json::Value>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub preferred_mentee_level: Option<String>,
|
||||
|
||||
#[sea_orm(type = "jsonb", nullable)]
|
||||
pub preferred_mentoring_formats: Option<serde_json::Value>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub availability_commitment: Option<String>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub mentoring_rate: Option<f64>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub status: Option<String>,
|
||||
|
||||
#[sea_orm(default = "false")]
|
||||
pub is_deleted: bool,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, sea_orm::EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(belongs_to = "super::users::Entity", from = "Column::UserId", to = "super::users::Column::Id")]
|
||||
User,
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::User.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
// Default implementation - SeaORM will handle timestamps automatically
|
||||
}
|
||||
|
||||
// Builder pattern for Mentor creation
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct MentorBuilder {
|
||||
user_id: Option<Uuid>,
|
||||
industries: Option<Vec<String>>,
|
||||
expertise: Option<Vec<String>>,
|
||||
languages: Option<Vec<String>>,
|
||||
current_company: Option<String>,
|
||||
current_role: Option<String>,
|
||||
years_of_experience: Option<i32>,
|
||||
topics_of_interest: Option<Vec<String>>,
|
||||
preferred_mentee_level: Option<String>,
|
||||
preferred_mentoring_formats: Option<Vec<String>>,
|
||||
availability_commitment: Option<String>,
|
||||
mentoring_rate: Option<f64>,
|
||||
status: Option<String>,
|
||||
is_deleted: Option<bool>,
|
||||
}
|
||||
|
||||
impl MentorBuilder {
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn user_id(mut self, user_id: Uuid) -> Self {
|
||||
self.user_id = Some(user_id);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn industries(mut self, industries: Vec<String>) -> Self {
|
||||
self.industries = Some(industries);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn expertise(mut self, expertise: Vec<String>) -> Self {
|
||||
self.expertise = Some(expertise);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn languages(mut self, languages: Vec<String>) -> Self {
|
||||
self.languages = Some(languages);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn current_company(mut self, current_company: String) -> Self {
|
||||
self.current_company = Some(current_company);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn current_role(mut self, current_role: String) -> Self {
|
||||
self.current_role = Some(current_role);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn years_of_experience(mut self, years_of_experience: i32) -> Self {
|
||||
self.years_of_experience = Some(years_of_experience);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn topics_of_interest(mut self, topics_of_interest: Vec<String>) -> Self {
|
||||
self.topics_of_interest = Some(topics_of_interest);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn preferred_mentee_level(mut self, preferred_mentee_level: String) -> Self {
|
||||
self.preferred_mentee_level = Some(preferred_mentee_level);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn preferred_mentoring_formats(mut self, preferred_mentoring_formats: Vec<String>) -> Self {
|
||||
self.preferred_mentoring_formats = Some(preferred_mentoring_formats);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn availability_commitment(mut self, availability_commitment: String) -> Self {
|
||||
self.availability_commitment = Some(availability_commitment);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn mentoring_rate(mut self, mentoring_rate: f64) -> Self {
|
||||
self.mentoring_rate = Some(mentoring_rate);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn status(mut self, status: String) -> Self {
|
||||
self.status = Some(status);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_deleted(mut self, is_deleted: bool) -> Self {
|
||||
self.is_deleted = Some(is_deleted);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(self) -> Result<ActiveModel, String> {
|
||||
let mut active_model = <ActiveModel as std::default::Default>::default();
|
||||
|
||||
if let Some(user_id) = self.user_id {
|
||||
active_model.user_id = Set(user_id);
|
||||
} else {
|
||||
return Err("User ID is required".to_string());
|
||||
}
|
||||
|
||||
if let Some(industries) = self.industries {
|
||||
active_model.industries = Set(Some(serde_json::to_value(industries).map_err(|e| format!("Failed to serialize industries: {}", e))?));
|
||||
}
|
||||
|
||||
if let Some(expertise) = self.expertise {
|
||||
active_model.expertise = Set(Some(serde_json::to_value(expertise).map_err(|e| format!("Failed to serialize expertise: {}", e))?));
|
||||
}
|
||||
|
||||
if let Some(languages) = self.languages {
|
||||
active_model.languages = Set(Some(serde_json::to_value(languages).map_err(|e| format!("Failed to serialize languages: {}", e))?));
|
||||
}
|
||||
|
||||
if let Some(current_company) = self.current_company {
|
||||
active_model.current_company = Set(Some(current_company));
|
||||
}
|
||||
|
||||
if let Some(current_role) = self.current_role {
|
||||
active_model.current_role = Set(Some(current_role));
|
||||
}
|
||||
|
||||
if let Some(years_of_experience) = self.years_of_experience {
|
||||
active_model.years_of_experience = Set(Some(years_of_experience));
|
||||
}
|
||||
|
||||
if let Some(topics_of_interest) = self.topics_of_interest {
|
||||
active_model.topics_of_interest = Set(Some(serde_json::to_value(topics_of_interest).map_err(|e| format!("Failed to serialize topics_of_interest: {}", e))?));
|
||||
}
|
||||
|
||||
if let Some(preferred_mentee_level) = self.preferred_mentee_level {
|
||||
active_model.preferred_mentee_level = Set(Some(preferred_mentee_level));
|
||||
}
|
||||
|
||||
if let Some(preferred_mentoring_formats) = self.preferred_mentoring_formats {
|
||||
active_model.preferred_mentoring_formats = Set(Some(serde_json::to_value(preferred_mentoring_formats).map_err(|e| format!("Failed to serialize preferred_mentoring_formats: {}", e))?));
|
||||
}
|
||||
|
||||
if let Some(availability_commitment) = self.availability_commitment {
|
||||
active_model.availability_commitment = Set(Some(availability_commitment));
|
||||
}
|
||||
|
||||
if let Some(mentoring_rate) = self.mentoring_rate {
|
||||
active_model.mentoring_rate = Set(Some(mentoring_rate));
|
||||
}
|
||||
|
||||
if let Some(status) = self.status {
|
||||
active_model.status = Set(Some(status));
|
||||
}
|
||||
|
||||
if let Some(is_deleted) = self.is_deleted {
|
||||
active_model.is_deleted = Set(is_deleted);
|
||||
}
|
||||
|
||||
Ok(active_model)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::seaorm::common::utils::generate_uuid;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn test_mentor_model_creation() {
|
||||
let uid = generate_uuid();
|
||||
let mentor = MentorBuilder::new()
|
||||
.user_id(uid)
|
||||
.industries(vec!["Technology".to_string(), "Finance".to_string()])
|
||||
.expertise(vec!["Blockchain".to_string(), "AI".to_string()])
|
||||
.languages(vec!["English".to_string(), "Spanish".to_string()])
|
||||
.current_company("Tech Corp".to_string())
|
||||
.current_role("Senior Engineer".to_string())
|
||||
.years_of_experience(10)
|
||||
.topics_of_interest(vec!["Web3".to_string(), "Machine Learning".to_string()])
|
||||
.preferred_mentee_level("Intermediate".to_string())
|
||||
.preferred_mentoring_formats(vec!["1:1".to_string(), "Group".to_string()])
|
||||
.availability_commitment("Weekly".to_string())
|
||||
.mentoring_rate(150.0)
|
||||
.status("active".to_string())
|
||||
.build();
|
||||
|
||||
assert!(mentor.is_ok());
|
||||
let mentor_model = mentor.unwrap();
|
||||
assert_eq!(mentor_model.user_id, Set(uid));
|
||||
assert_eq!(mentor_model.industries, Set(Some(json!(["Technology", "Finance"]))));
|
||||
assert_eq!(mentor_model.expertise, Set(Some(json!(["Blockchain", "AI"]))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mentor_model_missing_required_fields() {
|
||||
let mentor = MentorBuilder::new()
|
||||
// Missing user_id
|
||||
.industries(vec!["Technology".to_string()])
|
||||
.build();
|
||||
|
||||
assert!(mentor.is_err());
|
||||
assert_eq!(mentor.unwrap_err(), "User ID is required");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod users;
|
||||
pub mod roles;
|
||||
pub mod permissions;
|
||||
pub mod roles_permissions;
|
||||
pub mod mentors;
|
||||
pub mod sessions;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! SeaORM entity for Permissions table
|
||||
//! Corresponding to ResourceEnum::Permissions
|
||||
//! Represents system permissions
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use sea_orm::entity::prelude::*;
|
||||
use sea_orm::{ActiveModelBehavior, DeriveEntityModel, DeriveRelation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "app_permissions")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, default = "gen_random_uuid()", auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
|
||||
#[sea_orm(not_null)]
|
||||
pub name: String,
|
||||
|
||||
#[sea_orm(not_null, default = "false")]
|
||||
pub is_deleted: bool,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub updated_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub deleted_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, sea_orm::EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::roles_permissions::Entity")]
|
||||
RolesPermissions,
|
||||
}
|
||||
|
||||
impl Related<super::roles_permissions::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::RolesPermissions.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
impl Entity {
|
||||
pub fn find_by_id(id: Uuid) -> Select<Entity> {
|
||||
Self::find().filter(Column::Id.eq(id))
|
||||
}
|
||||
|
||||
pub fn find_by_name(name: &str) -> Select<Entity> {
|
||||
Self::find().filter(Column::Name.eq(name))
|
||||
}
|
||||
|
||||
pub fn find_active() -> Select<Entity> {
|
||||
Self::find().filter(Column::IsDeleted.eq(false))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! SeaORM entity for Roles table
|
||||
//! Corresponding to ResourceEnum::Roles
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use sea_orm::entity::prelude::*;
|
||||
use sea_orm::{ActiveModelBehavior, DeriveEntityModel, DeriveRelation};
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "app_roles")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, default = "gen_random_uuid()", auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
|
||||
#[sea_orm(unique, not_null)]
|
||||
pub name: String,
|
||||
|
||||
#[sea_orm(not_null)]
|
||||
pub description: String,
|
||||
|
||||
#[sea_orm(default = "false")]
|
||||
pub is_system_role: bool,
|
||||
|
||||
#[sea_orm(default = "false")]
|
||||
pub is_default: bool,
|
||||
|
||||
#[sea_orm(type = "jsonb", nullable)]
|
||||
pub permissions: Option<serde_json::Value>,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub updated_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub deleted_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, sea_orm::EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
// Default implementation - SeaORM will handle timestamps automatically
|
||||
}
|
||||
|
||||
// Builder pattern for Role creation
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct RoleBuilder {
|
||||
name: Option<String>,
|
||||
description: Option<String>,
|
||||
is_system_role: Option<bool>,
|
||||
is_default: Option<bool>,
|
||||
permissions: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl RoleBuilder {
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn name(mut self, name: String) -> Self {
|
||||
self.name = Some(name);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn description(mut self, description: String) -> Self {
|
||||
self.description = Some(description);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_system_role(mut self, is_system_role: bool) -> Self {
|
||||
self.is_system_role = Some(is_system_role);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_default(mut self, is_default: bool) -> Self {
|
||||
self.is_default = Some(is_default);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn permissions(mut self, permissions: Vec<String>) -> Self {
|
||||
self.permissions = Some(permissions);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(self) -> Result<ActiveModel, String> {
|
||||
let mut active_model = <ActiveModel as std::default::Default>::default();
|
||||
|
||||
if let Some(name) = self.name {
|
||||
active_model.name = Set(name);
|
||||
} else {
|
||||
return Err("Role name is required".to_string());
|
||||
}
|
||||
|
||||
if let Some(description) = self.description {
|
||||
active_model.description = Set(description);
|
||||
} else {
|
||||
return Err("Role description is required".to_string());
|
||||
}
|
||||
|
||||
if let Some(is_system_role) = self.is_system_role {
|
||||
active_model.is_system_role = Set(is_system_role);
|
||||
}
|
||||
|
||||
if let Some(is_default) = self.is_default {
|
||||
active_model.is_default = Set(is_default);
|
||||
}
|
||||
|
||||
if let Some(permissions) = self.permissions {
|
||||
active_model.permissions = Set(Some(serde_json::Value::Array(
|
||||
permissions.into_iter().map(serde_json::Value::String).collect()
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(active_model)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_role_model_creation() {
|
||||
let role = RoleBuilder::new()
|
||||
.name("admin".to_string())
|
||||
.description("Administrator role".to_string())
|
||||
.is_system_role(true)
|
||||
.is_default(false)
|
||||
.build();
|
||||
|
||||
assert!(role.is_ok());
|
||||
let role_model = role.unwrap();
|
||||
assert_eq!(role_model.name, Set("admin".to_string()));
|
||||
assert_eq!(role_model.description, Set("Administrator role".to_string()));
|
||||
assert_eq!(role_model.is_system_role, Set(true));
|
||||
assert_eq!(role_model.is_default, Set(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! SeaORM entity for RolesPermissions table
|
||||
//! Corresponding to ResourceEnum::RolesPermissions
|
||||
//! Represents the many-to-many relationship between Users and Roles
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use sea_orm::entity::prelude::*;
|
||||
use sea_orm::{ActiveModelBehavior, DeriveEntityModel, DeriveRelation};
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "app_roles_permissions")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, default = "gen_random_uuid()", auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
|
||||
#[sea_orm(not_null)]
|
||||
pub user_id: Uuid,
|
||||
|
||||
#[sea_orm(not_null)]
|
||||
pub role_id: Uuid,
|
||||
|
||||
#[sea_orm(not_null)]
|
||||
pub permission_id: Uuid,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub assigned_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(not_null, default = "false")]
|
||||
pub is_active: bool,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub updated_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub deleted_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, sea_orm::EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(belongs_to = "super::users::Entity", from = "Column::UserId", to = "super::users::Column::Id")]
|
||||
User,
|
||||
#[sea_orm(belongs_to = "super::roles::Entity", from = "Column::RoleId", to = "super::roles::Column::Id")]
|
||||
Role,
|
||||
#[sea_orm(belongs_to = "super::permissions::Entity", from = "Column::PermissionId", to = "super::permissions::Column::Id")]
|
||||
Permission,
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::User.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::roles::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Role.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::permissions::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Permission.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
// Default implementation - SeaORM will handle timestamps automatically
|
||||
}
|
||||
|
||||
// Builder pattern for RolePermission creation
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct RolePermissionBuilder {
|
||||
user_id: Option<Uuid>,
|
||||
role_id: Option<Uuid>,
|
||||
permission_id: Option<Uuid>,
|
||||
is_active: Option<bool>,
|
||||
}
|
||||
|
||||
impl RolePermissionBuilder {
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn user_id(mut self, user_id: Uuid) -> Self {
|
||||
self.user_id = Some(user_id);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn role_id(mut self, role_id: Uuid) -> Self {
|
||||
self.role_id = Some(role_id);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn permission_id(mut self, permission_id: Uuid) -> Self {
|
||||
self.permission_id = Some(permission_id);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_active(mut self, is_active: bool) -> Self {
|
||||
self.is_active = Some(is_active);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(self) -> Result<ActiveModel, String> {
|
||||
let mut active_model = <ActiveModel as std::default::Default>::default();
|
||||
|
||||
if let (Some(user_id), Some(role_id), Some(permission_id)) = (self.user_id, self.role_id, self.permission_id) {
|
||||
active_model.user_id = Set(user_id);
|
||||
active_model.role_id = Set(role_id);
|
||||
active_model.permission_id = Set(permission_id);
|
||||
} else {
|
||||
return Err("User ID, Role ID, and Permission ID are required".to_string());
|
||||
}
|
||||
|
||||
if let Some(is_active) = self.is_active {
|
||||
active_model.is_active = Set(is_active);
|
||||
}
|
||||
|
||||
Ok(active_model)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::seaorm::common::utils::generate_uuid;
|
||||
|
||||
#[test]
|
||||
fn test_role_permission_model_creation() {
|
||||
let user_id = generate_uuid();
|
||||
let role_id = generate_uuid();
|
||||
let permission_id = generate_uuid();
|
||||
|
||||
let role_permission = RolePermissionBuilder::new()
|
||||
.user_id(user_id)
|
||||
.role_id(role_id)
|
||||
.permission_id(permission_id)
|
||||
.is_active(true)
|
||||
.build();
|
||||
|
||||
assert!(role_permission.is_ok());
|
||||
let role_permission_model = role_permission.unwrap();
|
||||
assert_eq!(role_permission_model.user_id, Set(user_id));
|
||||
assert_eq!(role_permission_model.role_id, Set(role_id));
|
||||
assert_eq!(role_permission_model.permission_id, Set(permission_id));
|
||||
assert_eq!(role_permission_model.is_active, Set(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use chrono::{DateTime, Utc};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
#[sea_orm(table_name = "sessions")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, default = "gen_random_uuid()", auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
|
||||
#[sea_orm(column_type = "Uuid")]
|
||||
pub mentor_id: Uuid,
|
||||
|
||||
#[sea_orm(column_type = "Uuid")]
|
||||
pub mentee_id: Uuid,
|
||||
|
||||
pub topic: String,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub description: Option<String>,
|
||||
|
||||
pub scheduled_at: DateTime<Utc>,
|
||||
|
||||
pub duration_minutes: i32,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub meeting_link: Option<String>,
|
||||
|
||||
pub session_type: String, // "video_call", "phone_call", "chat"
|
||||
|
||||
pub status: String, // "pending", "confirmed", "completed", "cancelled", "no_show"
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub feedback: Option<String>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub rating: Option<i32>, // 1-5
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub feedback_submitted_at: Option<DateTime<Utc>>,
|
||||
|
||||
pub created_at: DateTime<Utc>,
|
||||
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
from = "Column::MentorId",
|
||||
to = "super::users::Column::Id"
|
||||
)]
|
||||
Mentor,
|
||||
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
from = "Column::MenteeId",
|
||||
to = "super::users::Column::Id"
|
||||
)]
|
||||
Mentee,
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Mentor.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! SeaORM entity for Users table
|
||||
//! Corresponding to ResourceEnum::Users
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use sea_orm::entity::prelude::*;
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize, imphnen_macros::Builder)]
|
||||
#[sea_orm(table_name = "app_users")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, default = "gen_random_uuid()", auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
|
||||
#[sea_orm(unique, not_null)]
|
||||
pub email: String,
|
||||
|
||||
#[sea_orm(not_null)]
|
||||
pub password_hash: String,
|
||||
|
||||
#[sea_orm(not_null)]
|
||||
pub username: String,
|
||||
|
||||
#[sea_orm(column_name = "role_id", nullable)]
|
||||
pub role_id: Option<Uuid>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub first_name: Option<String>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub last_name: Option<String>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub avatar_url: Option<String>,
|
||||
|
||||
#[sea_orm(default = "false")]
|
||||
pub is_verified: bool,
|
||||
|
||||
#[sea_orm(default = "false")]
|
||||
pub is_active: bool,
|
||||
|
||||
|
||||
#[sea_orm(type = "jsonb", nullable)]
|
||||
pub metadata: Option<serde_json::Value>,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(not_null, default = "now()")]
|
||||
pub updated_at: DateTime<Utc>,
|
||||
|
||||
#[sea_orm(nullable)]
|
||||
pub deleted_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, sea_orm::EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::roles_permissions::Entity")]
|
||||
RolesPermissions,
|
||||
#[sea_orm(belongs_to = "super::roles::Entity", from = "Column::RoleId", to = "super::roles::Column::Id")]
|
||||
Role,
|
||||
}
|
||||
|
||||
impl Related<super::roles_permissions::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::RolesPermissions.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::roles::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Role.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
// Default implementation - SeaORM will handle timestamps automatically
|
||||
}
|
||||
|
||||
// Builder pattern for User creation
|
||||
// Generated by #[derive(Builder)]
|
||||
pub type UserBuilder = ModelBuilder;
|
||||
|
||||
impl ModelBuilder {
|
||||
pub fn build(self) -> Result<ActiveModel, String> {
|
||||
let mut active_model = <ActiveModel as std::default::Default>::default();
|
||||
|
||||
if let Some(email) = self.email {
|
||||
active_model.email = Set(email);
|
||||
} else {
|
||||
return Err("Email is required".to_string());
|
||||
}
|
||||
|
||||
if let Some(password_hash) = self.password_hash {
|
||||
active_model.password_hash = Set(password_hash);
|
||||
} else {
|
||||
return Err("Password hash is required".to_string());
|
||||
}
|
||||
|
||||
if let Some(username) = self.username {
|
||||
active_model.username = Set(username);
|
||||
} else {
|
||||
return Err("Username is required".to_string());
|
||||
}
|
||||
|
||||
if let Some(role_id) = self.role_id {
|
||||
active_model.role_id = Set(Some(role_id));
|
||||
}
|
||||
|
||||
if let Some(first_name) = self.first_name {
|
||||
active_model.first_name = Set(Some(first_name));
|
||||
}
|
||||
|
||||
if let Some(last_name) = self.last_name {
|
||||
active_model.last_name = Set(Some(last_name));
|
||||
}
|
||||
|
||||
if let Some(avatar_url) = self.avatar_url {
|
||||
active_model.avatar_url = Set(Some(avatar_url));
|
||||
}
|
||||
|
||||
if let Some(is_verified) = self.is_verified {
|
||||
active_model.is_verified = Set(is_verified);
|
||||
}
|
||||
|
||||
if let Some(is_active) = self.is_active {
|
||||
active_model.is_active = Set(is_active);
|
||||
}
|
||||
|
||||
if let Some(metadata) = self.metadata {
|
||||
active_model.metadata = Set(Some(metadata));
|
||||
}
|
||||
|
||||
Ok(active_model)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_user_model_creation() {
|
||||
let user = UserBuilder::new()
|
||||
.email("test@example.com".to_string())
|
||||
.password_hash("hashed_password".to_string())
|
||||
.username("testuser".to_string())
|
||||
.first_name("Test".to_string())
|
||||
.last_name("User".to_string())
|
||||
.is_verified(true)
|
||||
.is_active(true)
|
||||
.build();
|
||||
|
||||
assert!(user.is_ok());
|
||||
let user_model = user.unwrap();
|
||||
assert_eq!(user_model.email, Set("test@example.com".to_string()));
|
||||
assert_eq!(user_model.password_hash, Set("hashed_password".to_string()));
|
||||
assert_eq!(user_model.username, Set("testuser".to_string()));
|
||||
assert_eq!(user_model.first_name, Set(Some("Test".to_string())));
|
||||
assert_eq!(user_model.last_name, Set(Some("User".to_string())));
|
||||
assert_eq!(user_model.is_verified, Set(true));
|
||||
assert_eq!(user_model.is_active, Set(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_user_model_missing_required_fields() {
|
||||
let user = UserBuilder::new()
|
||||
.email("test@example.com".to_string())
|
||||
// Missing password_hash
|
||||
.username("testuser".to_string())
|
||||
.build();
|
||||
|
||||
assert!(user.is_err());
|
||||
assert_eq!(user.unwrap_err(), "Password hash is required");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user