Compare commits
149
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
+49
-8
@@ -1,8 +1,49 @@
|
||||
PORT=
|
||||
SURREALDB_URL=
|
||||
SURREALDB_USERNAME=
|
||||
SURREALDB_PASSWORD=
|
||||
SURREALDB_NAMESPACE=
|
||||
SURREALDB_DBNAME=
|
||||
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"
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Deploy
|
||||
name: Deploy to Ancikri
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -25,10 +25,10 @@ jobs:
|
||||
- name: Stop service on VPS before upload
|
||||
uses: appleboy/ssh-action@v0.1.7
|
||||
with:
|
||||
host: ${{ secrets.VPS_IP }}
|
||||
username: ${{ secrets.VPS_USER }}
|
||||
key: ${{ secrets.VPS_SSH_KEY }}
|
||||
port: ${{ secrets.VPS_PORT }}
|
||||
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"
|
||||
@@ -37,10 +37,10 @@ jobs:
|
||||
- name: Upload artifact to VPS
|
||||
uses: appleboy/scp-action@v0.1.7
|
||||
with:
|
||||
host: ${{ secrets.VPS_IP }}
|
||||
username: ${{ secrets.VPS_USER }}
|
||||
key: ${{ secrets.VPS_SSH_KEY }}
|
||||
port: ${{ secrets.VPS_PORT }}
|
||||
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
|
||||
@@ -49,10 +49,10 @@ jobs:
|
||||
- name: Deploy to server
|
||||
uses: appleboy/ssh-action@v0.1.7
|
||||
with:
|
||||
host: ${{ secrets.VPS_IP }}
|
||||
username: ${{ secrets.VPS_USER }}
|
||||
key: ${{ secrets.VPS_SSH_KEY }}
|
||||
port: ${{ secrets.VPS_PORT }}
|
||||
host: ${{ secrets.VPS_ANCIKRI_IP }}
|
||||
username: ${{ secrets.VPS_ANCIKRI_USER }}
|
||||
key: ${{ secrets.VPS_ANCIKRI_SSH_KEY }}
|
||||
port: ${{ secrets.VPS_ANCIKRI_PORT }}
|
||||
script: |
|
||||
set -e
|
||||
|
||||
@@ -13,3 +13,4 @@
|
||||
.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
+1236
-711
File diff suppressed because it is too large
Load Diff
+71
-28
@@ -1,44 +1,87 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
members = [
|
||||
"tests",
|
||||
"imphnen-iam",
|
||||
"imphnen-libs",
|
||||
"imphnen-utils",
|
||||
"imphnen-gacha",
|
||||
"imphnen-gateway",
|
||||
"imphnen-backend",
|
||||
"imphnen-entities",
|
||||
"imphnen-dimentorin",
|
||||
"imphnen-middleware",
|
||||
"imphnen-entities", # Most basic - core data structures
|
||||
"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-hackathon", # Hackathon service, depends on core services
|
||||
"imphnen-gateway", # API gateway, depends on all services
|
||||
"imphnen-backend", # Main application, depends on all services
|
||||
]
|
||||
|
||||
|
||||
[workspace.dependencies]
|
||||
axum = { version = "0.8.1", features = ["multipart"] }
|
||||
log = "0.4.25"
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
serde_json = "1.0.138"
|
||||
tokio = { version = "1.43.0" }
|
||||
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"] }
|
||||
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"] }
|
||||
lettre = { version = "0.11.12", features = ["tokio1-native-tls"] }
|
||||
surrealdb = { version = "2.2.1", features = ["kv-mem"] }
|
||||
thiserror = "2.0.11"
|
||||
anyhow = "1.0.97"
|
||||
rand = "0.9.0"
|
||||
tower-http = { version = "0.6.2", features = ["cors"] }
|
||||
validator = { version = "0.12", features = ["derive"] }
|
||||
lazy_static = "1.4.0"
|
||||
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"] }
|
||||
surrealdb = { version = "2.3.7", features = ["kv-mem", "kv-fdb"] }
|
||||
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.2.0"
|
||||
fancy-regex = "0.14.0"
|
||||
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"
|
||||
|
||||
|
||||
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-hackathon = { path = "./imphnen-hackathon" }
|
||||
imphnen-middleware = { path = "./imphnen-middleware" }
|
||||
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
|
||||
+37
-12
@@ -1,22 +1,47 @@
|
||||
FROM rust:1.83-slim-bullseye AS builder
|
||||
FROM rust:1.86-alpine AS builder
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
libssl-dev \
|
||||
pkg-config \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN apk add --no-cache \
|
||||
curl \
|
||||
musl-dev \
|
||||
openssl-dev \
|
||||
openssl-libs-static \
|
||||
pkgconfig
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY ./src ./src
|
||||
|
||||
RUN cargo build --release && strip /app/target/release/imphnen-backend-service
|
||||
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"' _ {} \;
|
||||
|
||||
FROM gcr.io/distroless/cc AS runner
|
||||
RUN echo '[package]\nname = "tests"\nversion = "0.1.0"\nedition = "2021"' > tests/Cargo.toml
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /app/target/release/imphnen-backend-service .
|
||||
RUN echo -e '[package]\nname = "tests"\nversion = "0.1.0"\nedition = "2021"' > tests/Cargo.toml
|
||||
|
||||
CMD ["/app/imphnen-backend-service"]
|
||||
|
||||
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"]
|
||||
@@ -6,12 +6,13 @@
|
||||
|
||||
This repository serves as the **monorepo** for all backend services of IMPHNEN. It encompasses several main services:
|
||||
|
||||
1. **Core Service** - Provides fundamental functionalities and shared resources for other services.
|
||||
2. **IAM Service** - Handles identity and access management across IMPHNEN applications.
|
||||
3. **CMS Service** - Supports the cms services by IMPHNEN [Landing Page website](https://imphnen.dev/).
|
||||
4. **Gacha Service** - Supports the gacha services by IMPHNEN [Gacha website](https://gacha.imphnen.dev/).
|
||||
5. **Dimentorin Service** - Supports the mentoring services by IMPHNEN [Dimentorin website](https://dimentorin.imphnen.dev/).
|
||||
6. **Gateway Service** - Acts as the API gateway, routing requests to appropriate 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
|
||||
|
||||
@@ -39,7 +40,7 @@ This repository serves as the **monorepo** for all backend services of IMPHNEN.
|
||||
if you use unix based system
|
||||
|
||||
```sh
|
||||
sh apply-env.sh
|
||||
source ./apply-env.sh
|
||||
```
|
||||
|
||||
- Modify the `.env` files with your specific configuration settings.
|
||||
@@ -49,7 +50,15 @@ This repository serves as the **monorepo** for all backend services of IMPHNEN.
|
||||
Ensure you have [Rust](https://www.rust-lang.org/) installed. Then, run:
|
||||
|
||||
```sh
|
||||
cargo build
|
||||
cargo fetch
|
||||
```
|
||||
|
||||
4. **Run the seeders**:
|
||||
|
||||
to run the seeders, run:
|
||||
|
||||
```sh
|
||||
cargo run --bin seeder
|
||||
```
|
||||
|
||||
## How to Run
|
||||
@@ -64,10 +73,16 @@ To run the services in development mode:
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
2. **Run the desired service**. For example, to run the Core Service:
|
||||
2. **Run using cargo run**. For example, to run the Core Service:
|
||||
|
||||
```sh
|
||||
cargo run -p imphnen-core-service --bin api
|
||||
cargo run --bin api
|
||||
```
|
||||
|
||||
3. **Run using cargo watch**. For example, to run the Core Service:
|
||||
|
||||
```sh
|
||||
cargo watch -x "run --bin api"
|
||||
```
|
||||
|
||||
### Production
|
||||
@@ -77,17 +92,25 @@ For production deployment:
|
||||
1. **Build the Docker image**:
|
||||
|
||||
```sh
|
||||
docker build -t imphnen-backend-service .
|
||||
docker build -t imphnen-backend .
|
||||
```
|
||||
|
||||
2. **Run the Docker container**:
|
||||
|
||||
```sh
|
||||
docker run -d --env-file .env -p 8080:8080 imphnen-backend-service
|
||||
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.
|
||||
|
||||
@@ -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,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"
|
||||
@@ -14,3 +14,19 @@ services:
|
||||
command: start --log trace --user root --pass root
|
||||
ports:
|
||||
- "8000:8000"
|
||||
|
||||
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:
|
||||
minio_data:
|
||||
|
||||
@@ -3,12 +3,64 @@ name = "imphnen-backend"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[[bin]]
|
||||
name = "api"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "clear_db_test"
|
||||
path = "src/bin/clear_db_test.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_teams"
|
||||
path = "src/bin/seed_teams.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_hackathons"
|
||||
path = "src/bin/seed_hackathons.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "seed_test_data"
|
||||
path = "src/bin/seed_test_data.rs"
|
||||
|
||||
[dependencies]
|
||||
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
|
||||
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
|
||||
imphnen-gateway = { version = "0.1.0", path = "../imphnen-gateway" }
|
||||
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
|
||||
imphnen-iam = { version = "0.1.0", path = "../imphnen-iam" }
|
||||
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
|
||||
imphnen-hackathon.workspace = true
|
||||
axum.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
@@ -25,3 +77,9 @@ 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
|
||||
tokio-tungstenite.workspace = true
|
||||
url.workspace = true
|
||||
futures-util.workspace = true
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use env_logger;
|
||||
use imphnen_gateway::gateway_service;
|
||||
use imphnen_libs::axum_init;
|
||||
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
|
||||
use url::Url;
|
||||
use futures_util::{StreamExt, SinkExt};
|
||||
use serde_json::json;
|
||||
|
||||
// Menentukan kredensial dan detail koneksi secara langsung sebagai string statis
|
||||
static SURREALDB_URL_WS: &str = "ws://localhost:8000/rpc";
|
||||
static SURREALDB_USERNAME: &str = "root";
|
||||
static SURREALDB_PASSWORD: &str = "root";
|
||||
static SURREALDB_NAMESPACE: &str = "test";
|
||||
static SURREALDB_DBNAME: &str = "test";
|
||||
|
||||
// Daftar tabel sebagai variabel static yang tidak dapat diubah
|
||||
static TABLES_TO_CLEAR: &[&str] = &[
|
||||
"app_events", "users", "roles", "permissions", "gacha_rolls",
|
||||
"mentor_users", "gacha_claims", "gacha_credits", "gacha_items",
|
||||
"mentor_profiles", "roles_permissions", "testimonials",
|
||||
];
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Tidak perlu memuat env lagi, karena kita menggunakan nilai hardcoded
|
||||
// imphnen_libs::enviroment::load_env(); // Baris ini tidak lagi dibutuhkan
|
||||
// let env = Env::new(); // Baris ini tidak lagi dibutuhkan
|
||||
|
||||
println!("DEBUG: URL WS: {}", SURREALDB_URL_WS);
|
||||
println!("DEBUG: Username: {}", SURREALDB_USERNAME);
|
||||
println!("DEBUG: Namespace: {}", SURREALDB_NAMESPACE);
|
||||
println!("DEBUG: Database: {}", SURREALDB_DBNAME);
|
||||
|
||||
let url = Url::parse(SURREALDB_URL_WS)?; // Menggunakan SURREALDB_URL_WS statis
|
||||
|
||||
let (ws_stream, _) = connect_async(url.as_str()).await?;
|
||||
let (mut write, mut read) = ws_stream.split();
|
||||
|
||||
// Authenticate (signin)
|
||||
let signin_query = json!({
|
||||
"method": "signin",
|
||||
"params": [{
|
||||
"user": SURREALDB_USERNAME, // Menggunakan SURREALDB_USERNAME statis
|
||||
"pass": SURREALDB_PASSWORD, // Menggunakan SURREALDB_PASSWORD statis
|
||||
}],
|
||||
"id": 1
|
||||
}).to_string();
|
||||
println!("DEBUG: Sending signin query: {}", signin_query);
|
||||
write.send(Message::Text(signin_query.into())).await?;
|
||||
|
||||
let signin_response = read.next().await.ok_or("Failed to read signin response")?;
|
||||
let signin_response_msg = signin_response?;
|
||||
let signin_response_str = signin_response_msg.to_text()?;
|
||||
println!("DEBUG: Signin response: {}", signin_response_str);
|
||||
if signin_response_str.contains("\"error\":") {
|
||||
return Err(format!("Signin failed: {}", signin_response_str).into());
|
||||
}
|
||||
|
||||
// Use namespace and database
|
||||
let use_query = json!({
|
||||
"method": "use",
|
||||
"params": [SURREALDB_NAMESPACE, SURREALDB_DBNAME], // Menggunakan NS & DB statis
|
||||
"id": 2
|
||||
}).to_string();
|
||||
println!("DEBUG: Sending use query: {}", use_query);
|
||||
write.send(Message::Text(use_query.into())).await?;
|
||||
|
||||
let use_response = read.next().await.ok_or("Failed to read use response")?;
|
||||
let use_response_msg = use_response?;
|
||||
let use_response_str = use_response_msg.to_text()?;
|
||||
println!("DEBUG: Use response: {}", use_response_str);
|
||||
if use_response_str.contains("\"error\":") {
|
||||
return Err(format!("USE command failed: {}", use_response_str).into());
|
||||
}
|
||||
|
||||
println!("INFO: Attempting to clear database tables via WebSocket...");
|
||||
|
||||
let mut all_clear = true;
|
||||
for (i, table) in TABLES_TO_CLEAR.iter().enumerate() {
|
||||
let remove_query = format!("REMOVE TABLE {};", table);
|
||||
let query_json = json!({
|
||||
"method": "query",
|
||||
"params": [remove_query],
|
||||
"id": i + 3
|
||||
}).to_string();
|
||||
|
||||
println!("DEBUG: Attempting REMOVE TABLE {}: {}", table, query_json);
|
||||
write.send(Message::Text(query_json.into())).await?;
|
||||
let response_result = read.next().await.ok_or("Stream ended unexpectedly")?;
|
||||
|
||||
|
||||
|
||||
match response_result {
|
||||
Ok(msg) => {
|
||||
let response_str = msg.to_text()?;
|
||||
if response_str.contains("\"error\":") {
|
||||
println!("WARN: Failed to REMOVE TABLE {}: {}. Attempting DELETE type::{}.", table, response_str, table);
|
||||
let delete_all_query = format!("DELETE FROM {};", table);
|
||||
let delete_all_json = json!({
|
||||
"method": "query",
|
||||
"params": [delete_all_query],
|
||||
"id": i + 300
|
||||
}).to_string();
|
||||
|
||||
println!("DEBUG: Attempting DELETE {}: {}", table, delete_all_json);
|
||||
write.send(Message::Text(delete_all_json.into())).await?;
|
||||
let delete_response_result = read.next().await.ok_or("Stream ended unexpectedly during DELETE type::")?;
|
||||
|
||||
match delete_response_result {
|
||||
Ok(delete_msg) => {
|
||||
let delete_response_str = delete_msg.to_text()?;
|
||||
if delete_response_str.contains("\"error\":") {
|
||||
println!("ERROR: Failed to DELETE type::{} : {}", table, delete_response_str);
|
||||
all_clear = false;
|
||||
} else {
|
||||
println!("INFO: Successfully DELETED type:: table: {}", table);
|
||||
|
||||
}
|
||||
},
|
||||
Err(delete_e) => {
|
||||
println!("ERROR: Error receiving response for DELETE type:: table {}: {}", table, delete_e);
|
||||
all_clear = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("INFO: Successfully REMOVED TABLE: {}", table);
|
||||
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
println!("ERROR: Error receiving response for REMOVE TABLE {}: {}", table, e);
|
||||
all_clear = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if table is empty after deletion attempt
|
||||
let select_query = format!("SELECT * FROM {} LIMIT 1;", table);
|
||||
let select_json = json!({
|
||||
"method": "query",
|
||||
"params": [select_query],
|
||||
"id": i + 1000
|
||||
}).to_string();
|
||||
write.send(Message::Text(select_json.into())).await?;
|
||||
let select_response_result = read.next().await.ok_or("Stream ended unexpectedly during SELECT check")?;
|
||||
match select_response_result {
|
||||
Ok(select_msg) => {
|
||||
let select_response_str = select_msg.to_text()?;
|
||||
if select_response_str.contains("does not exist") {
|
||||
println!("CHECK: Table '{}' does not exist after clear attempt (success).", table);
|
||||
} else if select_response_str.contains("\"result\":[]") || select_response_str.contains("\"result\":[[]]") {
|
||||
println!("CHECK: Table '{}' is empty after clear attempt.", table);
|
||||
} else {
|
||||
println!("WARNING: Table '{}' is NOT empty after clear attempt! Response: {}", table, select_response_str);
|
||||
all_clear = false;
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
println!("ERROR: Error receiving response for SELECT check on table {}: {}", table, e);
|
||||
all_clear = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("INFO: Database clearing complete.");
|
||||
|
||||
if !all_clear {
|
||||
eprintln!("ERROR: One or more tables could not be cleared. Check logs for details.");
|
||||
return Err("Database clearing failed for one or more tables.".into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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,103 @@
|
||||
use imphnen_cms::v1::landing::events::events_schema::EventsSchema;
|
||||
use imphnen_utils::{get_iso_date};
|
||||
use std::error::Error;
|
||||
use surrealdb::engine::any;
|
||||
use surrealdb::{opt::auth::Root, sql::Thing, Uuid}; // Added Uuid
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
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",
|
||||
),
|
||||
];
|
||||
|
||||
for (
|
||||
name,
|
||||
description,
|
||||
detail_link,
|
||||
price,
|
||||
location,
|
||||
is_online,
|
||||
start_date,
|
||||
end_date,
|
||||
) in events
|
||||
{
|
||||
let uuid = Uuid::new_v4().to_string(); // Generate new UUID
|
||||
let event = EventsSchema {
|
||||
id: Thing::from(("app_events", uuid.as_str())), // Use generated UUID
|
||||
name: name.into(),
|
||||
description: description.into(),
|
||||
detail_link: detail_link.into(),
|
||||
price,
|
||||
location,
|
||||
is_online,
|
||||
is_deleted: false,
|
||||
start_date: start_date.into(),
|
||||
end_date: end_date.into(),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
};
|
||||
|
||||
db.create::<Option<EventsSchema>>(("app_events", uuid.as_str())) // Use generated UUID
|
||||
.content(event)
|
||||
.await?;
|
||||
|
||||
println!(
|
||||
"✅ Inserted event: {} ({})",
|
||||
name,
|
||||
if is_online { "Online" } else { "In-person" }
|
||||
);
|
||||
}
|
||||
|
||||
println!("✅ All Events seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use imphnen_utils::{get_iso_date};
|
||||
use std::error::Error;
|
||||
use surrealdb::opt::auth::Root;
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
use surrealdb::engine::any;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
db.query("DELETE type::thing('app_gacha_items', $id)")
|
||||
.bind(("id", "1"))
|
||||
.await?;
|
||||
db.query("DELETE type::thing('app_gacha_rolls', $id)")
|
||||
.bind(("id", "test-gacha-roll-001"))
|
||||
.await?;
|
||||
let gacha_item_id = "1";
|
||||
db.query("CREATE type::thing('app_gacha_items', $id) SET name = $name, image_url = $image_url, is_deleted = $is_deleted, created_at = $created_at, updated_at = $updated_at")
|
||||
.bind(("id", gacha_item_id))
|
||||
.bind(("name", "Test Gacha Item"))
|
||||
.bind(("image_url", "https://example.com/gacha_item.png"))
|
||||
.bind(("is_deleted", false))
|
||||
.bind(("created_at", get_iso_date()))
|
||||
.bind(("updated_at", get_iso_date()))
|
||||
.await?;
|
||||
println!("Gacha Item seeded successfully!");
|
||||
|
||||
let gacha_roll_id = "test-gacha-roll-001";
|
||||
db.query("CREATE type::thing('app_gacha_rolls', $id) SET item = $item, quantity = $quantity, weight = $weight, is_deleted = $is_deleted, created_at = $created_at, updated_at = $updated_at")
|
||||
.bind(("id", gacha_roll_id))
|
||||
.bind(("item", Thing::from(("app_gacha_items", gacha_item_id))))
|
||||
.bind(("quantity", 10))
|
||||
.bind(("weight", 1.0))
|
||||
.bind(("is_deleted", false))
|
||||
.bind(("created_at", get_iso_date()))
|
||||
.bind(("updated_at", get_iso_date()))
|
||||
.await?;
|
||||
println!("Gacha Roll seeded successfully!");
|
||||
|
||||
println!("✅ Gacha items and rolls seeded.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use imphnen_hackathon::v1::hackathon::hackathon_schema::{
|
||||
HackathonSchema, HackathonEventsSchema, HackathonTimelineSchema, HackathonSubmissionsSchema,
|
||||
HackathonStatus, HackathonEventType, HackathonPhase, SubmissionStatus, Prize
|
||||
};
|
||||
use imphnen_utils::get_iso_date;
|
||||
use std::error::Error;
|
||||
use surrealdb::{opt::auth::Root, sql::Thing};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
use surrealdb::engine::any;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
// Sample hackathon data
|
||||
let hackathons = vec![
|
||||
(
|
||||
"hackathon-001",
|
||||
"AI Innovation Challenge 2025",
|
||||
"Build the next generation of AI-powered applications that solve real-world problems.",
|
||||
"2025-10-15T09:00:00Z",
|
||||
"2025-10-17T18:00:00Z",
|
||||
"2025-10-01T23:59:59Z",
|
||||
Some(100),
|
||||
HackathonStatus::RegistrationOpen,
|
||||
Some("Artificial Intelligence & Machine Learning".to_string()),
|
||||
Some("1. All code must be original\n2. Teams can have 2-5 members\n3. Projects must use AI/ML technologies".to_string()),
|
||||
Some(vec![
|
||||
Prize { position: 1, title: "Grand Prize".to_string(), description: Some("Winner gets full scholarship".to_string()), value: Some("$10,000".to_string()) },
|
||||
Prize { position: 2, title: "Second Place".to_string(), description: Some("Runner-up prize".to_string()), value: Some("$5,000".to_string()) },
|
||||
Prize { position: 3, title: "Third Place".to_string(), description: Some("Third place prize".to_string()), value: Some("$2,500".to_string()) },
|
||||
]),
|
||||
vec!["c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2".to_string()], // admin user
|
||||
),
|
||||
(
|
||||
"hackathon-002",
|
||||
"Green Tech Hackathon",
|
||||
"Develop sustainable technology solutions for environmental challenges.",
|
||||
"2025-11-20T10:00:00Z",
|
||||
"2025-11-22T17:00:00Z",
|
||||
"2025-11-05T23:59:59Z",
|
||||
Some(75),
|
||||
HackathonStatus::Draft,
|
||||
Some("Sustainability & Green Technology".to_string()),
|
||||
Some("Focus on renewable energy, waste reduction, and environmental monitoring.".to_string()),
|
||||
Some(vec![
|
||||
Prize { position: 1, title: "Eco Champion".to_string(), description: Some("Best environmental impact".to_string()), value: Some("$7,500".to_string()) },
|
||||
Prize { position: 2, title: "Innovation Award".to_string(), description: Some("Most innovative solution".to_string()), value: Some("$3,500".to_string()) },
|
||||
]),
|
||||
vec!["c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2".to_string()],
|
||||
),
|
||||
];
|
||||
|
||||
// Sample hackathon events
|
||||
let hackathon_events = vec![
|
||||
(
|
||||
"hackathon-001",
|
||||
"event-001",
|
||||
"Opening Ceremony",
|
||||
Some("Welcome and kickoff event for the AI Innovation Challenge".to_string()),
|
||||
HackathonEventType::Ceremony,
|
||||
"2025-10-15T09:00:00Z",
|
||||
"2025-10-15T10:00:00Z",
|
||||
Some("Main Auditorium".to_string()),
|
||||
None,
|
||||
Some(150),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"hackathon-001",
|
||||
"event-002",
|
||||
"AI Workshop: Getting Started",
|
||||
Some("Introduction to AI frameworks and tools".to_string()),
|
||||
HackathonEventType::Workshop,
|
||||
"2025-10-15T14:00:00Z",
|
||||
"2025-10-15T16:00:00Z",
|
||||
None,
|
||||
Some("https://zoom.us/meeting/ai-workshop".to_string()),
|
||||
Some(80),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"hackathon-001",
|
||||
"event-003",
|
||||
"Judging Session",
|
||||
Some("Final project presentations and judging".to_string()),
|
||||
HackathonEventType::Judging,
|
||||
"2025-10-17T14:00:00Z",
|
||||
"2025-10-17T17:00:00Z",
|
||||
Some("Innovation Lab".to_string()),
|
||||
None,
|
||||
Some(100),
|
||||
true,
|
||||
),
|
||||
];
|
||||
|
||||
// Sample hackathon timeline
|
||||
let hackathon_timeline = vec![
|
||||
(
|
||||
"hackathon-001",
|
||||
HackathonPhase::Registration,
|
||||
"Registration Phase",
|
||||
Some("Register your team and submit initial project ideas".to_string()),
|
||||
"2025-10-01T00:00:00Z",
|
||||
"2025-10-10T23:59:59Z",
|
||||
true,
|
||||
1,
|
||||
),
|
||||
(
|
||||
"hackathon-001",
|
||||
HackathonPhase::Ideation,
|
||||
"Ideation & Planning",
|
||||
Some("Brainstorm and plan your AI solution".to_string()),
|
||||
"2025-10-11T00:00:00Z",
|
||||
"2025-10-14T23:59:59Z",
|
||||
false,
|
||||
2,
|
||||
),
|
||||
(
|
||||
"hackathon-001",
|
||||
HackathonPhase::Development,
|
||||
"Development Sprint",
|
||||
Some("Build your AI-powered application".to_string()),
|
||||
"2025-10-15T00:00:00Z",
|
||||
"2025-10-16T23:59:59Z",
|
||||
false,
|
||||
3,
|
||||
),
|
||||
(
|
||||
"hackathon-001",
|
||||
HackathonPhase::Submission,
|
||||
"Project Submission",
|
||||
Some("Submit your final project and demo video".to_string()),
|
||||
"2025-10-17T00:00:00Z",
|
||||
"2025-10-17T12:00:00Z",
|
||||
false,
|
||||
4,
|
||||
),
|
||||
(
|
||||
"hackathon-001",
|
||||
HackathonPhase::Judging,
|
||||
"Judging & Awards",
|
||||
Some("Presentations and prize ceremony".to_string()),
|
||||
"2025-10-17T13:00:00Z",
|
||||
"2025-10-17T18:00:00Z",
|
||||
false,
|
||||
5,
|
||||
),
|
||||
];
|
||||
|
||||
// Sample hackathon submissions
|
||||
let hackathon_submissions = vec![
|
||||
(
|
||||
"hackathon-001",
|
||||
"team-dev-001",
|
||||
"AI-Powered Health Monitor",
|
||||
"A machine learning application that predicts health risks using wearable device data.",
|
||||
Some("https://github.com/team-dev/ai-health-monitor".to_string()),
|
||||
Some("https://demo.ai-health-monitor.com".to_string()),
|
||||
None,
|
||||
vec!["Python".to_string(), "TensorFlow".to_string(), "React".to_string()],
|
||||
SubmissionStatus::Submitted,
|
||||
"2025-10-17T11:30:00Z",
|
||||
),
|
||||
(
|
||||
"hackathon-001",
|
||||
"team-design-001",
|
||||
"Smart City Traffic Optimizer",
|
||||
"AI system that optimizes traffic flow using computer vision and predictive analytics.",
|
||||
Some("https://github.com/team-design/smart-traffic".to_string()),
|
||||
Some("https://demo.smart-traffic.com".to_string()),
|
||||
Some("https://slides.smart-traffic.com/presentation".to_string()),
|
||||
vec!["JavaScript".to_string(), "Node.js".to_string(), "OpenCV".to_string()],
|
||||
SubmissionStatus::UnderReview,
|
||||
"2025-10-17T10:45:00Z",
|
||||
),
|
||||
];
|
||||
|
||||
// Seed hackathons
|
||||
for (
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
start_date,
|
||||
end_date,
|
||||
registration_deadline,
|
||||
max_participants,
|
||||
status,
|
||||
theme,
|
||||
rules,
|
||||
prizes,
|
||||
organizers,
|
||||
) in hackathons {
|
||||
db.query("DELETE type::thing('app_hackathons', $id)")
|
||||
.bind(("id", id))
|
||||
.await?;
|
||||
|
||||
let hackathon = HackathonSchema {
|
||||
id: Thing::from(("app_hackathons", id)),
|
||||
name: name.into(),
|
||||
description: description.into(),
|
||||
start_date: DateTime::parse_from_rfc3339(start_date)?.with_timezone(&Utc),
|
||||
end_date: DateTime::parse_from_rfc3339(end_date)?.with_timezone(&Utc),
|
||||
registration_deadline: DateTime::parse_from_rfc3339(registration_deadline)?.with_timezone(&Utc),
|
||||
max_participants,
|
||||
status,
|
||||
theme,
|
||||
rules,
|
||||
prizes,
|
||||
previous_winners: None,
|
||||
organizers,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonSchema>>(("app_hackathons", id))
|
||||
.content(hackathon)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted hackathon: {name}");
|
||||
}
|
||||
|
||||
// Seed hackathon events
|
||||
for (
|
||||
hackathon_id,
|
||||
event_id,
|
||||
title,
|
||||
description,
|
||||
event_type,
|
||||
start_time,
|
||||
end_time,
|
||||
location,
|
||||
virtual_link,
|
||||
max_attendees,
|
||||
is_mandatory,
|
||||
) in hackathon_events {
|
||||
db.query("DELETE type::thing('app_hackathon_events', $id)")
|
||||
.bind(("id", event_id))
|
||||
.await?;
|
||||
|
||||
let event = HackathonEventsSchema {
|
||||
id: Thing::from(("app_hackathon_events", event_id)),
|
||||
hackathon_id: Thing::from(("app_hackathons", hackathon_id)),
|
||||
title: title.into(),
|
||||
description,
|
||||
event_type,
|
||||
start_time: DateTime::parse_from_rfc3339(start_time)?.with_timezone(&Utc),
|
||||
end_time: DateTime::parse_from_rfc3339(end_time)?.with_timezone(&Utc),
|
||||
location,
|
||||
virtual_link,
|
||||
max_attendees,
|
||||
is_mandatory,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonEventsSchema>>(("app_hackathon_events", event_id))
|
||||
.content(event)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted hackathon event: {title}");
|
||||
}
|
||||
|
||||
// Seed hackathon timeline
|
||||
for (
|
||||
hackathon_id,
|
||||
phase,
|
||||
title,
|
||||
description,
|
||||
start_date,
|
||||
end_date,
|
||||
is_active,
|
||||
order,
|
||||
) in hackathon_timeline {
|
||||
let timeline_id = format!("timeline-{}-{}", hackathon_id, order);
|
||||
|
||||
db.query("DELETE type::thing('app_hackathon_timeline', $id)")
|
||||
.bind(("id", timeline_id.clone()))
|
||||
.await?;
|
||||
|
||||
let timeline = HackathonTimelineSchema {
|
||||
id: Thing::from(("app_hackathon_timeline", timeline_id.as_str())),
|
||||
hackathon_id: Thing::from(("app_hackathons", hackathon_id)),
|
||||
phase,
|
||||
title: title.into(),
|
||||
description,
|
||||
start_date: DateTime::parse_from_rfc3339(start_date)?.with_timezone(&Utc),
|
||||
end_date: DateTime::parse_from_rfc3339(end_date)?.with_timezone(&Utc),
|
||||
is_active,
|
||||
order,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonTimelineSchema>>(("app_hackathon_timeline", timeline_id))
|
||||
.content(timeline)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted hackathon timeline: {title}");
|
||||
}
|
||||
|
||||
// Seed hackathon submissions
|
||||
for (
|
||||
hackathon_id,
|
||||
team_id,
|
||||
project_name,
|
||||
description,
|
||||
repository_url,
|
||||
demo_url,
|
||||
slides_url,
|
||||
technologies,
|
||||
submission_status,
|
||||
submitted_at,
|
||||
) in hackathon_submissions {
|
||||
let submission_id = format!("submission-{}-{}", hackathon_id, team_id);
|
||||
|
||||
db.query("DELETE type::thing('app_hackathon_submissions', $id)")
|
||||
.bind(("id", submission_id.clone()))
|
||||
.await?;
|
||||
|
||||
let submission = HackathonSubmissionsSchema {
|
||||
id: Thing::from(("app_hackathon_submissions", submission_id.as_str())),
|
||||
hackathon_id: Thing::from(("app_hackathons", hackathon_id)),
|
||||
judge_feedback: None,
|
||||
team_id: Some(Thing::from(("app_teams", team_id))),
|
||||
project_name: Some(project_name.into()),
|
||||
description: Some(description.into()),
|
||||
repository_url,
|
||||
upload_file_url: None,
|
||||
demo_url,
|
||||
slides_url,
|
||||
technologies: Some(technologies),
|
||||
contact_instagram: None,
|
||||
contact_twitter: None,
|
||||
contact_linkedin: None,
|
||||
contact_facebook: None,
|
||||
contact_youtube: None,
|
||||
contact_tiktok: None,
|
||||
contact_other: None,
|
||||
submission_status: Some(submission_status),
|
||||
submitted_at: Some(DateTime::parse_from_rfc3339(submitted_at)?.with_timezone(&Utc)),
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonSubmissionsSchema>>(("app_hackathon_submissions", submission_id))
|
||||
.content(submission)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted hackathon submission: {project_name}");
|
||||
}
|
||||
|
||||
println!("✅ All Hackathons seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use imphnen_utils::{get_iso_date, hash_password};
|
||||
use serde_json::json;
|
||||
use std::error::Error;
|
||||
use surrealdb::opt::auth::Root;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
use surrealdb::engine::any;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
db.query("DELETE type::thing('app_mentors', $id)")
|
||||
.bind(("id", "e6f78d23-83bf-5c2b-bcd4-001345678901"))
|
||||
.await?;
|
||||
|
||||
db.query("DELETE type::thing('app_users', $id)")
|
||||
.bind(("id", "e6f78d23-83bf-5c2b-bcd4-001345678901"))
|
||||
.await?;
|
||||
|
||||
use surrealdb::sql::Thing;
|
||||
db.query("CREATE type::thing('app_users', $id) SET fullname = $fullname, email = $email, password = $password, avatar = $avatar, phone_number = $phone_number, is_active = $is_active, is_deleted = $is_deleted, mentor_id = $mentor_id, gender = $gender, birthdate = $birthdate, role = $role, legal_name = $legal_name, domicile = $domicile, identity_document_url = $identity_document_url, phone_for_verification = $phone_for_verification, bio = $bio, last_education = $last_education, linkedin_url = $linkedin_url, github_url = $github_url, cv_url = $cv_url, portfolio_url = $portfolio_url, created_at = $created_at, updated_at = $updated_at")
|
||||
.bind(("id", "e6f78d23-83bf-5c2b-bcd4-001345678901"))
|
||||
.bind(("fullname", "Mentor User"))
|
||||
.bind(("email", "mentor@example.com"))
|
||||
.bind(("password", hash_password("password").unwrap()))
|
||||
.bind(("avatar", Option::<String>::None))
|
||||
.bind(("phone_number", "081234567890"))
|
||||
.bind(("is_active", true))
|
||||
.bind(("is_deleted", false))
|
||||
.bind(("mentor_id", Option::<Thing>::None))
|
||||
.bind(("gender", "male"))
|
||||
.bind(("birthdate", "1990-05-15"))
|
||||
.bind(("role", Thing::from(("app_roles", "3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a"))))
|
||||
.bind(("legal_name", "Mentor User"))
|
||||
.bind(("domicile", "Jakarta, Indonesia"))
|
||||
// .bind(("identity_document_url", "https://example.com/ktp.jpg"))
|
||||
.bind(("phone_for_verification", "081234567890"))
|
||||
.bind(("bio", "Saya adalah mentor backend Rust dengan pengalaman 5 tahun dalam pengembangan aplikasi backend yang scalable dan performant."))
|
||||
.bind(("last_education", "S1 Teknik Informatika"))
|
||||
.bind(("linkedin_url", "https://linkedin.com/in/mentor"))
|
||||
.bind(("github_url", "https://github.com/mentor"))
|
||||
.bind(("cv_url", Option::<String>::None))
|
||||
.bind(("portfolio_url", Option::<String>::None))
|
||||
.bind(("created_at", get_iso_date()))
|
||||
.bind(("updated_at", get_iso_date()))
|
||||
.await?;
|
||||
|
||||
db.query("CREATE type::thing('app_mentors', $id) SET user_id = $user_id, industries = $industries, expertise = $expertise, languages = $languages, current_company = $current_company, current_role = $current_role, years_of_experience = $years_of_experience, topics_of_interest = $topics_of_interest, preferred_mentee_level = $preferred_mentee_level, preferred_mentoring_formats = $preferred_mentoring_formats, availability_commitment = $availability_commitment, mentoring_rate = $mentoring_rate, status = $status, is_deleted = $is_deleted, created_at = $created_at, updated_at = $updated_at")
|
||||
.bind(("id", "e6f78d23-83bf-5c2b-bcd4-001345678901"))
|
||||
.bind(("user_id", Thing::from(("app_users", "e6f78d23-83bf-5c2b-bcd4-001345678901"))))
|
||||
.bind(("industries", vec!["Software", "Education"]))
|
||||
.bind(("expertise", vec!["Rust", "Microservices"]))
|
||||
.bind(("languages", vec!["Indonesian", "English"]))
|
||||
.bind(("current_company", "PT Contoh"))
|
||||
.bind(("current_role", "Senior Backend Engineer"))
|
||||
.bind(("years_of_experience", 5))
|
||||
.bind(("topics_of_interest", vec!["Rust Programming", "Backend Development"]))
|
||||
.bind(("preferred_mentee_level", vec!["beginner", "intermediate"]))
|
||||
.bind(("preferred_mentoring_formats", vec!["online", "offline"]))
|
||||
.bind(("availability_commitment", "2 jam per minggu untuk mentoring online dan offline"))
|
||||
.bind(("mentoring_rate", json!({
|
||||
"amount": 100000,
|
||||
"currency": "IDR",
|
||||
"per_duration": "hour"
|
||||
})))
|
||||
.bind(("status", "verified"))
|
||||
.bind(("is_deleted", false))
|
||||
.bind(("created_at", get_iso_date()))
|
||||
.bind(("updated_at", get_iso_date()))
|
||||
.await?;
|
||||
println!("Mentor created successfully!");
|
||||
println!("Updating user with mentor_id...");
|
||||
|
||||
db.query("UPDATE type::thing('app_users', $id) SET mentor_id = $mentor_id")
|
||||
.bind(("id", "e6f78d23-83bf-5c2b-bcd4-001345678901"))
|
||||
.bind((
|
||||
"mentor_id",
|
||||
Thing::from(("app_mentors", "e6f78d23-83bf-5c2b-bcd4-001345678901")),
|
||||
))
|
||||
.await?;
|
||||
println!("User updated with mentor_id successfully!");
|
||||
|
||||
println!("✅ Inserted mentor user: mentor@example.com");
|
||||
println!("✅ Mentor user seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,145 +1,77 @@
|
||||
use imphnen_utils::{get_iso_date, Env};
|
||||
use imphnen_iam::PermissionsEnum;
|
||||
use imphnen_utils::{get_iso_date};
|
||||
use serde_json::json;
|
||||
use std::error::Error;
|
||||
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, Surreal};
|
||||
use surrealdb::engine::any;
|
||||
use surrealdb::opt::auth::Root;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = Env::new();
|
||||
let db = Surreal::new::<Ws>(env.surrealdb_url).await?;
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace)
|
||||
.use_db(env.surrealdb_dbname)
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
let permissions = vec![
|
||||
(
|
||||
"023e2dfe-93c3-4008-94a8-b5dff403f73b",
|
||||
"Create Users",
|
||||
Some("2025-01-29T06:08:23.838311+00"),
|
||||
Some("2025-01-29T06:08:23.838312+00"),
|
||||
),
|
||||
(
|
||||
"0269ed71-0ae0-4c43-ad29-e3d861d8f9a0",
|
||||
"Create Permissions",
|
||||
Some("2025-01-29T05:11:01.265+00"),
|
||||
Some("2025-01-29T05:11:01.265001+00"),
|
||||
),
|
||||
(
|
||||
"299cb4d5-6556-4cc9-b6c1-32e6d31e0f9b",
|
||||
"Update Permissions",
|
||||
Some("2025-01-29T05:11:01.265+00"),
|
||||
Some("2025-01-29T05:11:01.265001+00"),
|
||||
),
|
||||
(
|
||||
"319ee593-ff0a-4f29-bbaf-9feb3174a3a2",
|
||||
"Create Roles",
|
||||
Some("2025-01-29T05:11:01.265+00"),
|
||||
Some("2025-01-29T05:11:01.265001+00"),
|
||||
),
|
||||
(
|
||||
"319ee593-ff0a-4f29-bbaf-9feb3174a3a6",
|
||||
"Read Detail Users",
|
||||
Some("2025-01-29T05:11:01.265+00"),
|
||||
Some("2025-01-29T05:11:01.265001+00"),
|
||||
),
|
||||
(
|
||||
"35b0d992-65c8-4b62-b030-e6e0320e4048",
|
||||
"Delete Roles",
|
||||
Some("2025-01-29T05:34:40.621554+00"),
|
||||
Some("2025-01-29T05:34:40.621555+00"),
|
||||
),
|
||||
(
|
||||
"4da8b434-89f9-4d91-85ae-eebd63cdbeda",
|
||||
"Update Activate Users",
|
||||
Some("2025-02-01T12:38:09.741726+00"),
|
||||
Some("2025-02-01T12:38:09.741727+00"),
|
||||
),
|
||||
(
|
||||
"73888d18-b3e9-4f62-95a5-ba2c0d69fccb",
|
||||
"Read Detail Roles",
|
||||
Some("2025-01-29T05:13:06.445925+00"),
|
||||
Some("2025-01-29T10:31:46.408564+00"),
|
||||
),
|
||||
(
|
||||
"7c15e31d-36e2-49f9-97db-138c03fb0cf6",
|
||||
"Read List Users",
|
||||
Some("2025-01-28T15:02:41.772931+00"),
|
||||
Some("2025-01-28T15:02:41.772933+00"),
|
||||
),
|
||||
(
|
||||
"7d4b1379-4960-416a-b045-98cd82c0cac9",
|
||||
"Read Detail Sessions",
|
||||
Some("2025-02-24T16:52:26.886664+00"),
|
||||
Some("2025-02-24T16:52:26.886673+00"),
|
||||
),
|
||||
(
|
||||
"8195eeb8-e64f-4172-aa57-596492c84a72",
|
||||
"Read List Permissions",
|
||||
Some("2025-01-28T15:05:28.6299+00"),
|
||||
Some("2025-01-28T15:05:28.629901+00"),
|
||||
),
|
||||
(
|
||||
"81eba91d-b8ab-44b9-bbfe-4e6da2f98952",
|
||||
"Read List Tests",
|
||||
Some("2025-02-24T16:52:27.179542+00"),
|
||||
Some("2025-02-24T16:52:27.179551+00"),
|
||||
),
|
||||
(
|
||||
"9164ca6e-c7e3-4238-a15f-f36ab9577e7e",
|
||||
"Read List Roles",
|
||||
Some("2025-01-29T05:34:40.621554+00"),
|
||||
Some("2025-01-29T05:34:40.621555+00"),
|
||||
),
|
||||
(
|
||||
"96df0689-2ae9-4894-bf00-837c19415e5c",
|
||||
"Delete Users",
|
||||
Some("2025-02-02T06:52:05.195565+00"),
|
||||
Some("2025-02-02T06:52:05.195565+00"),
|
||||
),
|
||||
(
|
||||
"98b3dc4c-0124-461f-afcd-166637c5e6e8",
|
||||
"Update Users",
|
||||
Some("2025-01-29T05:34:40.621554+00"),
|
||||
Some("2025-01-29T05:34:40.621555+00"),
|
||||
),
|
||||
(
|
||||
"a00d5608-4c48-4542-845c-dfe004687022",
|
||||
"Update Roles",
|
||||
Some("2025-01-29T05:34:40.621554+00"),
|
||||
Some("2025-01-29T05:34:40.621555+00"),
|
||||
),
|
||||
(
|
||||
"b2dc3928-86ba-4c59-a03d-0b57d5183ebc",
|
||||
"Delete Permissions",
|
||||
Some("2025-01-29T05:14:22.511084+00"),
|
||||
Some("2025-01-29T05:14:22.511085+00"),
|
||||
),
|
||||
(
|
||||
"dad435cf-042c-41bd-a946-cea61ed2ffbc",
|
||||
"Read Detail Permissions",
|
||||
Some("2025-01-28T15:07:10.990214+00"),
|
||||
Some("2025-01-28T15:07:10.990214+00"),
|
||||
),
|
||||
];
|
||||
for (id, name, _created_at, _updated_at) in permissions {
|
||||
|
||||
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,
|
||||
] {
|
||||
db.query("CREATE type::thing('app_permissions', $id) CONTENT $data")
|
||||
.bind(("id", id))
|
||||
.bind(("id", permission.id()))
|
||||
.bind((
|
||||
"data",
|
||||
json!({
|
||||
"name": name,
|
||||
"is_deleted": false,
|
||||
"created_at": get_iso_date(),
|
||||
"updated_at": get_iso_date()
|
||||
"name": permission.to_string(),
|
||||
"is_deleted": false,
|
||||
"created_at": get_iso_date(),
|
||||
"updated_at": get_iso_date()
|
||||
}),
|
||||
))
|
||||
.await?;
|
||||
println!("✅ Inserted: {}", name);
|
||||
println!("✅ Inserted: {permission}");
|
||||
}
|
||||
|
||||
println!("✅ All Permissions seeded");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
use imphnen_utils::{get_iso_date, Env};
|
||||
use imphnen_utils::{get_iso_date};
|
||||
use serde_json::json;
|
||||
use std::error::Error;
|
||||
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, Surreal};
|
||||
|
||||
use surrealdb::engine::any;
|
||||
use surrealdb::opt::auth::Root;
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = Env::new();
|
||||
let db = Surreal::new::<Ws>(env.surrealdb_url).await?;
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace)
|
||||
.use_db(env.surrealdb_dbname)
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
let roles = vec![
|
||||
@@ -26,7 +26,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
(
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
"User",
|
||||
None,
|
||||
Some("2025-02-28T14:53:58.576688+00"),
|
||||
Some("2025-02-28T14:53:58.576688+00"),
|
||||
),
|
||||
(
|
||||
@@ -44,12 +44,21 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
(
|
||||
"f6b03f25-e416-4893-ac88-caaa690afb07",
|
||||
"Admin",
|
||||
None,
|
||||
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, _updated_at) in roles {
|
||||
db.query("DELETE type::thing('app_roles', $id)")
|
||||
.bind(("id", id))
|
||||
.await?;
|
||||
db.query("CREATE type::thing('app_roles', $id) CONTENT $data")
|
||||
.bind(("id", id))
|
||||
.bind((
|
||||
@@ -63,7 +72,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
}),
|
||||
))
|
||||
.await?;
|
||||
println!("✅ Inserted role: {}", name);
|
||||
println!("✅ Inserted role: {name}");
|
||||
}
|
||||
println!("✅ All Roles seeded");
|
||||
Ok(())
|
||||
|
||||
@@ -1,57 +1,115 @@
|
||||
use imphnen_iam::{get_iso_date, make_thing, Env};
|
||||
use imphnen_iam::{get_iso_date, make_thing, PermissionsEnum};
|
||||
use std::error::Error;
|
||||
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, Surreal};
|
||||
use surrealdb::engine::any;
|
||||
use surrealdb::opt::auth::Root;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = Env::new();
|
||||
let db = Surreal::new::<Ws>(env.surrealdb_url).await?;
|
||||
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
|
||||
db.use_ns(env.surrealdb_namespace)
|
||||
.use_db(env.surrealdb_dbname)
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
db.query("DEFINE INDEX user_email_index ON TABLE users COLUMNS email UNIQUE;")
|
||||
|
||||
.await?;
|
||||
db.query("DEFINE INDEX role_name_idx ON TABLE roles COLUMNS name UNIQUE;")
|
||||
|
||||
.await?;
|
||||
|
||||
println!("✅ Index 'user_email_index' defined on table 'users' for column 'email'.");
|
||||
|
||||
let admin_permissions = vec![
|
||||
"023e2dfe-93c3-4008-94a8-b5dff403f73b",
|
||||
"0269ed71-0ae0-4c43-ad29-e3d861d8f9a0",
|
||||
"299cb4d5-6556-4cc9-b6c1-32e6d31e0f9b",
|
||||
"319ee593-ff0a-4f29-bbaf-9feb3174a3a2",
|
||||
"319ee593-ff0a-4f29-bbaf-9feb3174a3a6",
|
||||
"35b0d992-65c8-4b62-b030-e6e0320e4048",
|
||||
"4da8b434-89f9-4d91-85ae-eebd63cdbeda",
|
||||
"73888d18-b3e9-4f62-95a5-ba2c0d69fccb",
|
||||
"7c15e31d-36e2-49f9-97db-138c03fb0cf6",
|
||||
"7d4b1379-4960-416a-b045-98cd82c0cac9",
|
||||
"8195eeb8-e64f-4172-aa57-596492c84a72",
|
||||
"81eba91d-b8ab-44b9-bbfe-4e6da2f98952",
|
||||
"9164ca6e-c7e3-4238-a15f-f36ab9577e7e",
|
||||
"96df0689-2ae9-4894-bf00-837c19415e5c",
|
||||
"98b3dc4c-0124-461f-afcd-166637c5e6e8",
|
||||
"a00d5608-4c48-4542-845c-dfe004687022",
|
||||
"b2dc3928-86ba-4c59-a03d-0b57d5183ebc",
|
||||
"dad435cf-042c-41bd-a946-cea61ed2ffbc",
|
||||
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,
|
||||
PermissionsEnum::ManageAllTeams,
|
||||
],
|
||||
),
|
||||
(
|
||||
"60f1aeb7-dad2-4e06-bcb5-be1ba510c906",
|
||||
vec![PermissionsEnum::ActivateUsers],
|
||||
),
|
||||
("6d4fea5d-4a08-4b8a-9782-f2ab2183dcf0", vec![]),
|
||||
];
|
||||
|
||||
let admin_role_id = "f6b03f25-e416-4893-ac88-caaa690afb07";
|
||||
for (role_id, permissions) in roles_permissions {
|
||||
let permission_refs: Vec<_> = permissions
|
||||
.iter()
|
||||
.map(|perm| make_thing("app_permissions", &perm.id()))
|
||||
.collect();
|
||||
|
||||
let permission_refs_admin: Vec<_> = admin_permissions
|
||||
.into_iter()
|
||||
.map(|perm_id| make_thing("app_permissions", perm_id))
|
||||
.collect();
|
||||
|
||||
db.query("UPDATE type::thing('app_roles', $role_id) SET permissions = $permissions, updated_at = $updated_at WHERE is_deleted = false")
|
||||
.bind(("role_id", admin_role_id))
|
||||
.bind(("permissions", permission_refs_admin))
|
||||
.bind(("updated_at", get_iso_date()))
|
||||
.await?;
|
||||
|
||||
println!("✅ All permissions successfully added to each role");
|
||||
db.query("UPDATE type::thing('app_roles', $role_id) SET permissions = $permissions, updated_at = $updated_at WHERE is_deleted = false")
|
||||
.bind(("role_id", role_id))
|
||||
.bind(("permissions", permission_refs))
|
||||
.bind(("updated_at", get_iso_date()))
|
||||
.await?;
|
||||
println!("✅ Permissions updated for role: {role_id}");
|
||||
}
|
||||
|
||||
println!("✅ All roles permissions updated!");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
use imphnen_iam::v1::teams::TeamsSchema;
|
||||
use imphnen_utils::get_iso_date;
|
||||
use std::error::Error;
|
||||
use surrealdb::{opt::auth::Root, sql::Thing};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
use surrealdb::engine::any;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
let teams = vec![
|
||||
(
|
||||
"team-dev-001",
|
||||
"Development Team",
|
||||
Some("Core development team for the platform".to_string()),
|
||||
"c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2", // admin user
|
||||
true,
|
||||
Some(10),
|
||||
Some(vec!["Rust".to_string(), "Backend".to_string()]),
|
||||
Some("Remote".to_string()),
|
||||
),
|
||||
(
|
||||
"team-design-001",
|
||||
"Design Team",
|
||||
Some("UI/UX design team".to_string()),
|
||||
"c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2", // admin user
|
||||
true,
|
||||
Some(5),
|
||||
Some(vec!["Figma".to_string(), "Design".to_string()]),
|
||||
Some("Remote".to_string()),
|
||||
),
|
||||
(
|
||||
"team-qa-001",
|
||||
"Quality Assurance Team",
|
||||
Some("Testing and quality assurance team".to_string()),
|
||||
"c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2", // admin user
|
||||
false,
|
||||
Some(8),
|
||||
Some(vec!["Testing".to_string(), "Automation".to_string()]),
|
||||
Some("Remote".to_string()),
|
||||
),
|
||||
];
|
||||
|
||||
for (id, name, description, leader_id, is_open, max_members, skills_required, location) in teams {
|
||||
db.query("DELETE type::thing('app_teams', $id)")
|
||||
.bind(("id", id))
|
||||
.await?;
|
||||
|
||||
let team = TeamsSchema {
|
||||
id: Thing::from(("app_teams", id)),
|
||||
name: name.into(),
|
||||
description,
|
||||
leader_id: Thing::from(("app_users", leader_id)),
|
||||
is_open,
|
||||
max_members,
|
||||
skills_required,
|
||||
location,
|
||||
avatar: None,
|
||||
website_url: None,
|
||||
github_url: None,
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
};
|
||||
|
||||
db.create::<Option<TeamsSchema>>(("app_teams", id))
|
||||
.content(team)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted team: {name}");
|
||||
}
|
||||
|
||||
println!("✅ All Teams seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
use imphnen_cms::v1::landing::events::events_schema::EventsSchema;
|
||||
use imphnen_cms::v1::landing::testimonials::testimonials_schema::TestimonialsSchema;
|
||||
use imphnen_dimentorin::v1::mentors::mentors_schema::MentorSchema;
|
||||
use imphnen_dimentorin::v1::mentors::mentors_dto::MentoringRate;
|
||||
use imphnen_hackathon::v1::hackathon::hackathon_schema::{
|
||||
HackathonSchema, HackathonEventsSchema, HackathonTimelineSchema,
|
||||
HackathonStatus, HackathonEventType, HackathonPhase
|
||||
};
|
||||
use imphnen_utils::get_iso_date;
|
||||
use std::error::Error;
|
||||
use surrealdb::{opt::auth::Root, sql::Thing};
|
||||
use chrono::Utc;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
use surrealdb::engine::any;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
// Seed Events - handle existing data
|
||||
let event = EventsSchema {
|
||||
id: Thing::from(("app_events", "1")),
|
||||
name: "Test Event".to_string(),
|
||||
description: "Test event description".to_string(),
|
||||
detail_link: "https://example.com/event".to_string(),
|
||||
price: 50.0,
|
||||
is_online: true,
|
||||
start_date: get_iso_date(),
|
||||
end_date: get_iso_date(),
|
||||
location: None,
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
};
|
||||
match db.create::<Option<EventsSchema>>(("app_events", "1"))
|
||||
.content(event)
|
||||
.await {
|
||||
Ok(_) => println!("✅ Inserted test event"),
|
||||
Err(_) => println!("⚠️ Test event already exists, skipping"),
|
||||
};
|
||||
|
||||
// Seed Testimonials - handle existing data
|
||||
let testimonial = TestimonialsSchema {
|
||||
id: Thing::from(("app_testimonials", "1")),
|
||||
user: Thing::from(("app_users", "c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")),
|
||||
role: "Student".to_string(),
|
||||
content: "This is a great platform!".to_string(),
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
};
|
||||
match db.create::<Option<TestimonialsSchema>>(("app_testimonials", "1"))
|
||||
.content(testimonial)
|
||||
.await {
|
||||
Ok(_) => println!("✅ Inserted test testimonial"),
|
||||
Err(_) => println!("⚠️ Test testimonial already exists, skipping"),
|
||||
};
|
||||
|
||||
// Seed Hackathon - handle existing data
|
||||
let hackathon = HackathonSchema {
|
||||
id: Thing::from(("app_hackathons", "1")),
|
||||
name: "Test Hackathon".to_string(),
|
||||
description: "Test hackathon description".to_string(),
|
||||
start_date: Utc::now() + chrono::Duration::days(30),
|
||||
end_date: Utc::now() + chrono::Duration::days(37),
|
||||
registration_deadline: Utc::now() + chrono::Duration::days(25),
|
||||
max_participants: Some(100),
|
||||
status: HackathonStatus::Draft,
|
||||
theme: Some("Technology".to_string()),
|
||||
rules: Some("Follow the rules".to_string()),
|
||||
prizes: Some(vec![]),
|
||||
previous_winners: Some(vec![]),
|
||||
organizers: vec!["c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2".to_string()],
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
match db.create::<Option<HackathonSchema>>(("app_hackathons", "1"))
|
||||
.content(hackathon)
|
||||
.await {
|
||||
Ok(_) => println!("✅ Inserted test hackathon"),
|
||||
Err(_) => println!("⚠️ Test hackathon already exists, skipping"),
|
||||
};
|
||||
|
||||
// Seed Hackathon Event
|
||||
let hackathon_event = HackathonEventsSchema {
|
||||
id: Thing::from(("app_hackathon_events", "test-event-001")),
|
||||
hackathon_id: Thing::from(("app_hackathons", "1")),
|
||||
title: "Test Event".to_string(),
|
||||
description: Some("Test hackathon event description".to_string()),
|
||||
event_type: HackathonEventType::Workshop,
|
||||
start_time: Utc::now() + chrono::Duration::days(30),
|
||||
end_time: Utc::now() + chrono::Duration::days(30) + chrono::Duration::hours(6),
|
||||
location: Some("Online".to_string()),
|
||||
virtual_link: None,
|
||||
max_attendees: Some(50),
|
||||
is_mandatory: false,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
// Try to create hackathon event, skip if already exists
|
||||
match db.create::<Option<HackathonEventsSchema>>(("app_hackathon_events", "test-event-001"))
|
||||
.content(hackathon_event)
|
||||
.await {
|
||||
Ok(_) => println!("✅ Inserted test hackathon event"),
|
||||
Err(_) => println!("⚠️ Test hackathon event already exists, skipping"),
|
||||
};
|
||||
|
||||
// Seed Hackathon Timeline
|
||||
let hackathon_timeline = HackathonTimelineSchema {
|
||||
id: Thing::from(("app_hackathon_timeline", "test-timeline-001")),
|
||||
hackathon_id: Thing::from(("app_hackathons", "1")),
|
||||
phase: HackathonPhase::Registration,
|
||||
title: "Test Timeline".to_string(),
|
||||
description: Some("Test hackathon timeline description".to_string()),
|
||||
start_date: Utc::now(),
|
||||
end_date: Utc::now() + chrono::Duration::days(7),
|
||||
is_active: true,
|
||||
order: 1,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
// Try to create hackathon timeline, skip if already exists
|
||||
match db.create::<Option<HackathonTimelineSchema>>(("app_hackathon_timeline", "test-timeline-001"))
|
||||
.content(hackathon_timeline)
|
||||
.await {
|
||||
Ok(_) => println!("✅ Inserted test hackathon timeline"),
|
||||
Err(_) => println!("⚠️ Test hackathon timeline already exists, skipping"),
|
||||
};
|
||||
|
||||
// Seed Mentor - handle existing data
|
||||
let mentor = MentorSchema {
|
||||
id: Thing::from(("app_mentors", "e6f78d23-83bf-5c2b-bcd4-001345678901")),
|
||||
user_id: Some(Thing::from(("app_users", "e6f78d23-83bf-5c2b-bcd4-001345678901"))),
|
||||
industries: vec!["Technology".to_string(), "Education".to_string()],
|
||||
expertise: vec!["Software Development".to_string()],
|
||||
languages: vec!["English".to_string(), "Indonesian".to_string()],
|
||||
current_company: "Tech Corp".to_string(),
|
||||
current_role: "Senior Engineer".to_string(),
|
||||
years_of_experience: 5,
|
||||
topics_of_interest: vec!["Rust".to_string(), "Web Development".to_string()],
|
||||
preferred_mentee_level: vec!["Beginner".to_string()],
|
||||
preferred_mentoring_formats: vec!["1:1".to_string(), "Group".to_string()],
|
||||
availability_commitment: "Weekly".to_string(),
|
||||
mentoring_rate: MentoringRate {
|
||||
amount: 100,
|
||||
currency: "IDR".to_string(),
|
||||
per_duration: "hour".to_string(),
|
||||
},
|
||||
status: "active".to_string(),
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
};
|
||||
match db.create::<Option<MentorSchema>>(("app_mentors", "e6f78d23-83bf-5c2b-bcd4-001345678901"))
|
||||
.content(mentor)
|
||||
.await {
|
||||
Ok(_) => println!("✅ Inserted test mentor"),
|
||||
Err(_) => println!("⚠️ Test mentor already exists, skipping"),
|
||||
};
|
||||
|
||||
println!("✅ All test data seeded successfully");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use imphnen_hackathon::v1::hackathon::hackathon_schema::{
|
||||
HackathonSchema, HackathonTimelineSchema, HackathonSubmissionsSchema,
|
||||
HackathonStatus, HackathonPhase, SubmissionStatus, Prize,
|
||||
};
|
||||
use imphnen_iam::{UsersSchema, v1::teams::TeamsSchema};
|
||||
use imphnen_utils::{get_iso_date, hash_password};
|
||||
use std::error::Error;
|
||||
use surrealdb::{opt::auth::Root, sql::Thing};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
use surrealdb::engine::any;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
// Test users for submission testing
|
||||
let test_users = vec![
|
||||
(
|
||||
"test-user-001",
|
||||
"testuser1@example.com",
|
||||
"Test User 1",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059", // User role
|
||||
),
|
||||
(
|
||||
"test-user-002",
|
||||
"testuser2@example.com",
|
||||
"Test User 2",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"test-user-003",
|
||||
"testuser3@example.com",
|
||||
"Test User 3",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
];
|
||||
|
||||
// Test teams for submission testing
|
||||
let test_teams = vec![
|
||||
(
|
||||
"test-team-001",
|
||||
"Test Team Alpha",
|
||||
Some("Team for testing hackathon submissions".to_string()),
|
||||
"test-user-001", // team leader
|
||||
true,
|
||||
Some(5),
|
||||
Some(vec!["JavaScript".to_string(), "React".to_string()]),
|
||||
Some("Remote".to_string()),
|
||||
),
|
||||
(
|
||||
"test-team-002",
|
||||
"Test Team Beta",
|
||||
Some("Another team for testing submissions".to_string()),
|
||||
"test-user-002",
|
||||
true,
|
||||
Some(4),
|
||||
Some(vec!["Python".to_string(), "Django".to_string()]),
|
||||
Some("Remote".to_string()),
|
||||
),
|
||||
];
|
||||
|
||||
// Test hackathon for submission testing
|
||||
let test_hackathons = vec![
|
||||
(
|
||||
"test-hackathon-001",
|
||||
"Test Hackathon 2025",
|
||||
"Hackathon for testing submission functionality.",
|
||||
"2025-12-01T09:00:00Z",
|
||||
"2025-12-03T18:00:00Z",
|
||||
"2025-11-25T23:59:59Z",
|
||||
Some(50),
|
||||
HackathonStatus::RegistrationOpen,
|
||||
Some("Testing & Development".to_string()),
|
||||
Some("1. Test all submission features\n2. Teams can have 2-5 members\n3. Submit by deadline".to_string()),
|
||||
Some(vec![
|
||||
Prize { position: 1, title: "Test Winner".to_string(), description: Some("Best test submission".to_string()), value: Some("$1,000".to_string()) },
|
||||
Prize { position: 2, title: "Test Runner-up".to_string(), description: Some("Second best submission".to_string()), value: Some("$500".to_string()) },
|
||||
]),
|
||||
vec!["c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2".to_string()], // admin user
|
||||
),
|
||||
];
|
||||
|
||||
// Test hackathon timeline
|
||||
let test_timeline = vec![
|
||||
(
|
||||
"test-hackathon-001",
|
||||
HackathonPhase::Registration,
|
||||
"Registration Phase",
|
||||
Some("Register your team for the test hackathon".to_string()),
|
||||
"2025-11-20T00:00:00Z",
|
||||
"2025-11-25T23:59:59Z",
|
||||
true,
|
||||
1,
|
||||
),
|
||||
(
|
||||
"test-hackathon-001",
|
||||
HackathonPhase::Development,
|
||||
"Development Phase",
|
||||
Some("Build your test project".to_string()),
|
||||
"2025-12-01T00:00:00Z",
|
||||
"2025-12-02T23:59:59Z",
|
||||
false,
|
||||
2,
|
||||
),
|
||||
(
|
||||
"test-hackathon-001",
|
||||
HackathonPhase::Submission,
|
||||
"Submission Phase",
|
||||
Some("Submit your test project".to_string()),
|
||||
"2025-12-03T00:00:00Z",
|
||||
"2025-12-03T12:00:00Z",
|
||||
false,
|
||||
3,
|
||||
),
|
||||
];
|
||||
|
||||
// Test submissions
|
||||
let test_submissions = vec![
|
||||
(
|
||||
"test-hackathon-001",
|
||||
"test-team-001",
|
||||
"Test Project Alpha",
|
||||
"A comprehensive test project demonstrating all features.",
|
||||
Some("https://github.com/test-team-alpha/test-project".to_string()),
|
||||
Some("https://demo.test-project-alpha.com".to_string()),
|
||||
Some("https://slides.test-project-alpha.com".to_string()),
|
||||
vec!["JavaScript".to_string(), "React".to_string(), "Node.js".to_string()],
|
||||
SubmissionStatus::Draft,
|
||||
"2025-12-02T10:00:00Z",
|
||||
),
|
||||
(
|
||||
"test-hackathon-001",
|
||||
"test-team-002",
|
||||
"Test Project Beta",
|
||||
"Another test project with different technologies.",
|
||||
Some("https://github.com/test-team-beta/test-project".to_string()),
|
||||
Some("https://demo.test-project-beta.com".to_string()),
|
||||
None,
|
||||
vec!["Python".to_string(), "Django".to_string(), "PostgreSQL".to_string()],
|
||||
SubmissionStatus::Submitted,
|
||||
"2025-12-03T09:30:00Z",
|
||||
),
|
||||
];
|
||||
|
||||
// Seed test users
|
||||
for (id, email, fullname, role_id) in test_users {
|
||||
db.query("DELETE type::thing('app_users', $id)")
|
||||
.bind(("id", id))
|
||||
.await?;
|
||||
|
||||
let user = UsersSchema {
|
||||
id: Thing::from(("app_users", id)),
|
||||
fullname: fullname.into(),
|
||||
legal_name: Some(format!("{} Legal Name", fullname)),
|
||||
email: email.into(),
|
||||
password: hash_password("password").unwrap(),
|
||||
avatar: Some("https://example.com/avatar.jpg".into()),
|
||||
phone_number: "081234567890".into(),
|
||||
phone_for_verification: Some("081234567890".into()),
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
mentor_id: None,
|
||||
gender: Some("male".into()),
|
||||
birthdate: Some("1995-01-01".into()),
|
||||
domicile: Some("Jakarta, Indonesia".into()),
|
||||
bio: Some(format!("{} is a test user for hackathon submissions.", fullname)),
|
||||
last_education: Some("S1 Computer Science".into()),
|
||||
linkedin_url: Some("https://linkedin.com/in/testuser".into()),
|
||||
github_url: Some("https://github.com/testuser".into()),
|
||||
cv_url: Some("https://example.com/cv.pdf".into()),
|
||||
portfolio_url: Some("https://example.com/portfolio".into()),
|
||||
website_url: Some("https://example.com/website".into()),
|
||||
twitter_url: Some("https://twitter.com/testuser".into()),
|
||||
location: Some("Jakarta, Indonesia".into()),
|
||||
skills: Some(vec!["JavaScript".to_string(), "Python".to_string()]),
|
||||
experience: None,
|
||||
education: None,
|
||||
career_status: Some("Developer".into()),
|
||||
role: Thing::from(("app_roles", role_id)),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
};
|
||||
|
||||
db.create::<Option<UsersSchema>>(("app_users", id))
|
||||
.content(user)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted test user: {fullname} ({email})");
|
||||
}
|
||||
|
||||
// Seed test teams
|
||||
for (id, name, description, leader_id, is_open, max_members, skills_required, location) in test_teams {
|
||||
db.query("DELETE type::thing('app_teams', $id)")
|
||||
.bind(("id", id))
|
||||
.await?;
|
||||
|
||||
let team = TeamsSchema {
|
||||
id: Thing::from(("app_teams", id)),
|
||||
name: name.into(),
|
||||
description,
|
||||
leader_id: Thing::from(("app_users", leader_id)),
|
||||
is_open,
|
||||
max_members,
|
||||
skills_required,
|
||||
location,
|
||||
avatar: None,
|
||||
website_url: None,
|
||||
github_url: None,
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
};
|
||||
|
||||
db.create::<Option<TeamsSchema>>(("app_teams", id))
|
||||
.content(team)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted test team: {name}");
|
||||
}
|
||||
|
||||
// Seed test hackathons
|
||||
for (
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
start_date,
|
||||
end_date,
|
||||
registration_deadline,
|
||||
max_participants,
|
||||
status,
|
||||
theme,
|
||||
rules,
|
||||
prizes,
|
||||
organizers,
|
||||
) in test_hackathons {
|
||||
db.query("DELETE type::thing('app_hackathons', $id)")
|
||||
.bind(("id", id))
|
||||
.await?;
|
||||
|
||||
let hackathon = HackathonSchema {
|
||||
id: Thing::from(("app_hackathons", id)),
|
||||
name: name.into(),
|
||||
description: description.into(),
|
||||
start_date: DateTime::parse_from_rfc3339(start_date)?.with_timezone(&Utc),
|
||||
end_date: DateTime::parse_from_rfc3339(end_date)?.with_timezone(&Utc),
|
||||
registration_deadline: DateTime::parse_from_rfc3339(registration_deadline)?.with_timezone(&Utc),
|
||||
max_participants,
|
||||
status: status.clone(),
|
||||
theme: theme.clone(),
|
||||
rules: rules.clone(),
|
||||
prizes: prizes.clone(),
|
||||
previous_winners: None,
|
||||
organizers: organizers.clone(),
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonSchema>>(("app_hackathons", id))
|
||||
.content(hackathon)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted test hackathon: {name}");
|
||||
// Also create an alias canonical id 'test-hackathon' so tests referencing
|
||||
// /v1/hackathons/test-hackathon/... can find a hackathon record.
|
||||
if id != "test-hackathon" && id.starts_with("test-hackathon") {
|
||||
let alias_id = "test-hackathon";
|
||||
db.query("DELETE type::thing('app_hackathons', $id)")
|
||||
.bind(("id", alias_id))
|
||||
.await?;
|
||||
|
||||
let alias_hackathon = HackathonSchema {
|
||||
id: Thing::from(("app_hackathons", alias_id)),
|
||||
name: name.into(),
|
||||
description: description.into(),
|
||||
start_date: DateTime::parse_from_rfc3339(start_date)?.with_timezone(&Utc),
|
||||
end_date: DateTime::parse_from_rfc3339(end_date)?.with_timezone(&Utc),
|
||||
registration_deadline: DateTime::parse_from_rfc3339(registration_deadline)?.with_timezone(&Utc),
|
||||
max_participants,
|
||||
status: status.clone(),
|
||||
theme: theme.clone(),
|
||||
rules: rules.clone(),
|
||||
prizes: prizes.clone(),
|
||||
previous_winners: None,
|
||||
organizers: organizers.clone(),
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonSchema>>(("app_hackathons", alias_id))
|
||||
.content(alias_hackathon)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted test hackathon alias: {alias_id}");
|
||||
}
|
||||
}
|
||||
|
||||
// Seed test hackathon timeline
|
||||
for (
|
||||
hackathon_id,
|
||||
phase,
|
||||
title,
|
||||
description,
|
||||
start_date,
|
||||
end_date,
|
||||
is_active,
|
||||
order,
|
||||
) in test_timeline {
|
||||
let timeline_id = format!("test-timeline-{}-{}", hackathon_id, order);
|
||||
|
||||
db.query("DELETE type::thing('app_hackathon_timeline', $id)")
|
||||
.bind(("id", timeline_id.clone()))
|
||||
.await?;
|
||||
|
||||
let timeline = HackathonTimelineSchema {
|
||||
id: Thing::from(("app_hackathon_timeline", timeline_id.as_str())),
|
||||
hackathon_id: Thing::from(("app_hackathons", hackathon_id)),
|
||||
phase: phase.clone(),
|
||||
title: title.into(),
|
||||
description: description.clone(),
|
||||
start_date: DateTime::parse_from_rfc3339(start_date)?.with_timezone(&Utc),
|
||||
end_date: DateTime::parse_from_rfc3339(end_date)?.with_timezone(&Utc),
|
||||
is_active,
|
||||
order,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonTimelineSchema>>(("app_hackathon_timeline", timeline_id))
|
||||
.content(timeline)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted test hackathon timeline: {title}");
|
||||
|
||||
// Also create alias timeline entries for the canonical test id 'test-hackathon'
|
||||
if hackathon_id != "test-hackathon" && hackathon_id.starts_with("test-hackathon") {
|
||||
let alias_hackathon_id = "test-hackathon";
|
||||
let alias_timeline_id = format!("test-timeline-{}-{}", alias_hackathon_id, order);
|
||||
|
||||
db.query("DELETE type::thing('app_hackathon_timeline', $id)")
|
||||
.bind(("id", alias_timeline_id.clone()))
|
||||
.await?;
|
||||
|
||||
let alias_timeline = HackathonTimelineSchema {
|
||||
id: Thing::from(("app_hackathon_timeline", alias_timeline_id.as_str())),
|
||||
hackathon_id: Thing::from(("app_hackathons", alias_hackathon_id)),
|
||||
phase: phase.clone(),
|
||||
title: title.into(),
|
||||
description: description.clone(),
|
||||
start_date: DateTime::parse_from_rfc3339(start_date)?.with_timezone(&Utc),
|
||||
end_date: DateTime::parse_from_rfc3339(end_date)?.with_timezone(&Utc),
|
||||
is_active,
|
||||
order,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonTimelineSchema>>( ("app_hackathon_timeline", alias_timeline_id.clone()) )
|
||||
.content(alias_timeline)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted test hackathon timeline alias: {alias_timeline_id}");
|
||||
}
|
||||
}
|
||||
|
||||
// Seed test hackathon submissions
|
||||
for (
|
||||
hackathon_id,
|
||||
team_id,
|
||||
project_name,
|
||||
description,
|
||||
repository_url,
|
||||
demo_url,
|
||||
slides_url,
|
||||
technologies,
|
||||
submission_status,
|
||||
submitted_at,
|
||||
) in test_submissions {
|
||||
let submission_id = format!("test-submission-{}-{}", hackathon_id, team_id);
|
||||
|
||||
db.query("DELETE type::thing('app_hackathon_submissions', $id)")
|
||||
.bind(("id", submission_id.clone()))
|
||||
.await?;
|
||||
|
||||
let submission = HackathonSubmissionsSchema {
|
||||
id: Thing::from(("app_hackathon_submissions", submission_id.as_str())),
|
||||
hackathon_id: Thing::from(("app_hackathons", hackathon_id)),
|
||||
team_id: Some(Thing::from(("app_teams", team_id))),
|
||||
project_name: Some(project_name.into()),
|
||||
description: Some(description.into()),
|
||||
repository_url,
|
||||
upload_file_url: None,
|
||||
demo_url,
|
||||
slides_url,
|
||||
technologies: Some(technologies),
|
||||
contact_instagram: None,
|
||||
contact_twitter: None,
|
||||
contact_linkedin: None,
|
||||
contact_facebook: None,
|
||||
contact_youtube: None,
|
||||
contact_tiktok: None,
|
||||
contact_other: None,
|
||||
submission_status: Some(submission_status),
|
||||
judge_feedback: None,
|
||||
submitted_at: Some(DateTime::parse_from_rfc3339(submitted_at)?.with_timezone(&Utc)),
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
};
|
||||
|
||||
db.create::<Option<HackathonSubmissionsSchema>>(("app_hackathon_submissions", submission_id))
|
||||
.content(submission)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted test hackathon submission: {project_name}");
|
||||
}
|
||||
|
||||
println!("✅ All test submission data seeded");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,19 +1,20 @@
|
||||
use imphnen_iam::UsersSchema;
|
||||
use imphnen_utils::{get_iso_date, hash_password, Env};
|
||||
use imphnen_utils::{get_iso_date, hash_password};
|
||||
use std::error::Error;
|
||||
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, sql::Thing, Surreal};
|
||||
|
||||
use surrealdb::{opt::auth::Root, sql::Thing};
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let env = Env::new();
|
||||
let db = Surreal::new::<Ws>(env.surrealdb_url).await?;
|
||||
let env = &imphnen_libs::environment::ENV;
|
||||
use surrealdb::engine::any;
|
||||
let db = any::connect(&env.surrealdb_url).await?;
|
||||
db.signin(Root {
|
||||
username: &env.surrealdb_username,
|
||||
password: &env.surrealdb_password,
|
||||
})
|
||||
.await?;
|
||||
db.use_ns(env.surrealdb_namespace)
|
||||
.use_db(env.surrealdb_dbname)
|
||||
db.use_ns(env.surrealdb_namespace.clone())
|
||||
.use_db(env.surrealdb_dbname.clone())
|
||||
.await?;
|
||||
|
||||
let users = vec![
|
||||
@@ -35,20 +36,60 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
"User",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"testuser1-id",
|
||||
"testuser1@example.com",
|
||||
"Test User 1",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"testuser2-id",
|
||||
"testuser2@example.com",
|
||||
"Test User 2",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
(
|
||||
"testuser3-id",
|
||||
"testuser3@example.com",
|
||||
"Test User 3",
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
];
|
||||
|
||||
for (id, email, fullname, role_id) in users {
|
||||
db.query("DELETE type::thing('app_users', $id)")
|
||||
.bind(("id", id))
|
||||
.await?;
|
||||
|
||||
let user = UsersSchema {
|
||||
id: Thing::from(("app_users", id)),
|
||||
fullname: fullname.into(),
|
||||
legal_name: Some(format!("{} Legal Name", fullname)),
|
||||
email: email.into(),
|
||||
password: hash_password("password").unwrap(),
|
||||
avatar: None,
|
||||
avatar: Some("https://example.com/avatar.jpg".into()),
|
||||
phone_number: "081234567890".into(),
|
||||
phone_for_verification: Some("081234567890".into()),
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
gender: None,
|
||||
birthdate: None,
|
||||
mentor_id: None,
|
||||
gender: Some("male".into()),
|
||||
birthdate: Some("1990-05-15".into()),
|
||||
domicile: Some("Jakarta, Indonesia".into()),
|
||||
// identity_document_url: None, // Sudah tidak dipakai, bisa dihapus dari schema jika tidak diperlukan
|
||||
bio: Some(format!("{} adalah user dengan data pribadi lengkap untuk testing.", fullname)),
|
||||
last_education: Some("S1 Teknik Informatika".into()),
|
||||
linkedin_url: Some("https://linkedin.com/in/user".into()),
|
||||
github_url: Some("https://github.com/user".into()),
|
||||
cv_url: Some("https://example.com/cv.pdf".into()),
|
||||
portfolio_url: Some("https://example.com/portfolio".into()),
|
||||
website_url: Some("https://example.com/website".into()),
|
||||
twitter_url: Some("https://twitter.com/user".into()),
|
||||
location: Some("Jakarta, Indonesia".into()),
|
||||
skills: Some(vec!["JavaScript".into(), "React".into(), "Node.js".into()]),
|
||||
experience: None,
|
||||
education: None,
|
||||
career_status: Some("Senior Developer".into()),
|
||||
role: Thing::from(("app_roles", role_id)),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
@@ -58,7 +99,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
.content(user)
|
||||
.await?;
|
||||
|
||||
println!("✅ Inserted user: {} ({})", fullname, email);
|
||||
println!("✅ Inserted user: {fullname} ({email})");
|
||||
}
|
||||
|
||||
println!("✅ All Users seeded");
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
use std::error::Error;
|
||||
use std::process::Command;
|
||||
|
||||
fn run_seed(bin: &str) -> Result<(), Box<dyn Error>> {
|
||||
println!("🔧 Seeding: {bin}");
|
||||
let status = Command::new("cargo").args(["run", "--bin", 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_hackathons")?;
|
||||
run_seed("seed_gacha_rolls")?;
|
||||
run_seed("seed_mentor_user")?;
|
||||
run_seed("seed_test_data")?;
|
||||
println!("\n✅ All seeding completed successfully.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -3,6 +3,8 @@ use imphnen_libs::axum_init;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
axum_init(|surrealdb_ws, surrealdb_mem| async {
|
||||
gateway_service(surrealdb_ws, surrealdb_mem).await
|
||||
})
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
[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
|
||||
surrealdb.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
|
||||
|
||||
[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,129 @@
|
||||
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};
|
||||
use imphnen_libs::{
|
||||
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
|
||||
ResponseSuccessDto, ValidatedJson,
|
||||
};
|
||||
use imphnen_iam::{PermissionsEnum, require_permissions};
|
||||
|
||||
#[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 {
|
||||
EventsService::get_event_by_id(&state, 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], {
|
||||
EventsService::delete_event(&state, id).await
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
// Custom URL validator that ensures valid HTTP/HTTPS URLs
|
||||
pub fn validate_url(url: &str) -> Result<(), ValidationError> {
|
||||
lazy_static! {
|
||||
static ref VALID_URL_REGEX: Regex = Regex::new(r"^https?://[^\s$.?#].[^\s]*$").unwrap();
|
||||
}
|
||||
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: Thing,
|
||||
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.id.to_raw(),
|
||||
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,167 @@
|
||||
use super::{events_dto::EventsQueryDto, events_schema::EventsSchema};
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_libs::{AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto};
|
||||
use imphnen_utils::{DetailQueryBuilder, ListQueryBuilder, get_id, get_iso_date, make_thing};
|
||||
use std::time::Instant;
|
||||
use tracing::instrument;
|
||||
use tracing::info;
|
||||
|
||||
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 query = ListQueryBuilder::new(ResourceEnum::Events.to_string())
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_pagination(meta.page, Some(10))
|
||||
.with_sorting(meta.sort_by.as_deref(), meta.order.as_deref())
|
||||
.build();
|
||||
info!(query = %query, "Executing SurrealDB query");
|
||||
let res: Vec<EventsQueryDto> =
|
||||
self.state.surrealdb_ws.query(query).await?.take(0)?;
|
||||
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: String) -> Result<EventsQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
// Attempt to parse the ID. If it's a full Thing (e.g., "events:some_id"), extract the ID part.
|
||||
// Otherwise, assume it's already the raw ID.
|
||||
let parsed_id = if id.contains(":") {
|
||||
let thing = make_thing(ResourceEnum::Events.to_string().as_str(), &id);
|
||||
get_id(&thing)?.1.to_string()
|
||||
} else {
|
||||
id.clone()
|
||||
};
|
||||
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::Events.to_string())
|
||||
.with_id(&parsed_id)
|
||||
.with_select_fields(vec!["*"]);
|
||||
let sql = builder.build();
|
||||
info!(query = %sql, "Executing SurrealDB query");
|
||||
let result: Option<EventsQueryDto> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
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?}");
|
||||
}
|
||||
|
||||
match result {
|
||||
Some(event) => {
|
||||
if event.is_deleted {
|
||||
bail!("Event not found");
|
||||
}
|
||||
Ok(event)
|
||||
}
|
||||
None => bail!("Event not found"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_create_event(&self, data: EventsSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let query_str = format!("CREATE {} CONTENT ...", ResourceEnum::Events);
|
||||
info!(query = %query_str, "Executing SurrealDB query");
|
||||
let record: Option<EventsSchema> = db
|
||||
.create(ResourceEnum::Events.to_string())
|
||||
.content(data)
|
||||
.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?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success create event".into()),
|
||||
None => bail!("Failed to create event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_update_event(&self, data: EventsSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let existing = self.query_event_by_id(data.id.id.to_raw()).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("Event already deleted");
|
||||
}
|
||||
|
||||
let merged = EventsSchema {
|
||||
created_at: existing.created_at,
|
||||
updated_at: get_iso_date(),
|
||||
..data
|
||||
};
|
||||
|
||||
let record_key = get_id(&merged.id)?;
|
||||
let query_str = format!("UPDATE {:?} MERGE ...", record_key);
|
||||
info!(query = %query_str, "Executing SurrealDB query");
|
||||
let record: Option<EventsSchema> = db.update(record_key).merge(merged).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?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success update event".into()),
|
||||
None => bail!("Failed to update event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_event(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let event = self.query_event_by_id(id).await?;
|
||||
if event.is_deleted {
|
||||
bail!("Event not found");
|
||||
}
|
||||
|
||||
let record_key = get_id(&event.id)?;
|
||||
let query_str = format!("UPDATE {:?} MERGE {{ is_deleted: true }}", record_key);
|
||||
info!(query = %query_str, "Executing SurrealDB query");
|
||||
let record: Option<EventsSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.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?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success delete event".into()),
|
||||
None => bail!("Failed to delete event"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use imphnen_utils::{get_iso_date, make_thing};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::Uuid;
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
use super::events_dto::{
|
||||
EventsCreateRequestDto, EventsQueryDto, EventsUpdateRequestDto,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct EventsSchema {
|
||||
pub id: Thing,
|
||||
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: make_thing(
|
||||
&ResourceEnum::Events.to_string(),
|
||||
&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: make_thing(
|
||||
&ResourceEnum::Events.to_string(),
|
||||
&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: make_thing(&ResourceEnum::Events.to_string(), &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,101 @@
|
||||
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,
|
||||
};
|
||||
|
||||
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: String) -> 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.id.to_raw(),
|
||||
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),
|
||||
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),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_event(state: &AppState, id: String) -> Response {
|
||||
let repo = EventsRepository::new(state);
|
||||
match repo.query_delete_event(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
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,132 @@
|
||||
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,
|
||||
};
|
||||
|
||||
#[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 {
|
||||
TestimonialsService::get_testimonial_by_id(&state, 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, {
|
||||
TestimonialsService::delete_testimonial(&state, id, &authenticated_user).await
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use imphnen_iam::v1::users::UsersSchema;
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
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: Thing,
|
||||
pub user: UsersSchema,
|
||||
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.id.to_raw(),
|
||||
user_id: self.user.id.id.to_raw(),
|
||||
user_fullname: self.user.fullname,
|
||||
role: self.role,
|
||||
content: self.content,
|
||||
created_at: self.created_at,
|
||||
is_deleted: self.is_deleted,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
use super::{
|
||||
testimonials_dto::TestimonialsQueryDto, testimonials_schema::TestimonialsSchema,
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_libs::{AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto};
|
||||
use imphnen_utils::{DetailQueryBuilder, ListQueryBuilder, get_id, get_iso_date};
|
||||
use serde_json;
|
||||
use std::time::Instant;
|
||||
use tracing::instrument;
|
||||
use tracing::info;
|
||||
|
||||
pub struct TestimonialsRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> TestimonialsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, meta), err)]
|
||||
pub async fn query_testimonial_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<TestimonialsQueryDto>>> {
|
||||
let now = Instant::now();
|
||||
let query = ListQueryBuilder::new(ResourceEnum::Testimonials.to_string())
|
||||
.with_select_fields(vec!["*", "user.* as user"])
|
||||
.with_pagination(meta.page, Some(10))
|
||||
.with_sorting(meta.sort_by.as_deref(), meta.order.as_deref())
|
||||
.build();
|
||||
info!(query = %query, "Executing SurrealDB query");
|
||||
let res: Vec<TestimonialsQueryDto> =
|
||||
self.state.surrealdb_ws.query(query).await?.take(0)?;
|
||||
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 data = ResponseListSuccessDto {
|
||||
data: res,
|
||||
meta: None,
|
||||
};
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_testimonial_by_id(
|
||||
&self,
|
||||
id: String,
|
||||
) -> Result<TestimonialsQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
// Extract raw id if id is a thing string
|
||||
let raw_id = if id.contains(':') {
|
||||
id.split(':').last().unwrap().trim_matches(|c| c == '⟨' || c == '⟩').to_string()
|
||||
} else {
|
||||
id
|
||||
};
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::Testimonials.to_string())
|
||||
.with_id(&raw_id)
|
||||
.with_condition("is_deleted = false")
|
||||
.with_select_fields(vec!["*", "user.* as user"]);
|
||||
let sql = builder.build();
|
||||
info!(query = %sql, "Executing SurrealDB query");
|
||||
let result: Option<TestimonialsQueryDto> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
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?}");
|
||||
}
|
||||
|
||||
match result {
|
||||
Some(testimonial) => {
|
||||
if testimonial.is_deleted {
|
||||
bail!("Testimonial not found");
|
||||
}
|
||||
Ok(testimonial)
|
||||
}
|
||||
None => bail!("Testimonial not found"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_create_testimonial(
|
||||
&self,
|
||||
data: TestimonialsSchema,
|
||||
) -> Result<TestimonialsSchema> { // Change return type from String to TestimonialsSchema
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
info!(
|
||||
resource = %ResourceEnum::Testimonials.to_string(),
|
||||
payload = ?data,
|
||||
"Executing SurrealDB create"
|
||||
);
|
||||
let record: Option<TestimonialsSchema> = db
|
||||
.create(ResourceEnum::Testimonials.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
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?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(created_testimonial) => Ok(created_testimonial), // Return the created testimonial
|
||||
None => bail!("Failed to create testimonial"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_update_testimonial(
|
||||
&self,
|
||||
data: TestimonialsSchema,
|
||||
) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let existing = self.query_testimonial_by_id(data.id.id.to_raw()).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("Testimonial already deleted");
|
||||
}
|
||||
|
||||
let merged = TestimonialsSchema {
|
||||
created_at: existing.created_at,
|
||||
updated_at: get_iso_date(),
|
||||
user: existing.user.id,
|
||||
..data
|
||||
};
|
||||
|
||||
let record_key = get_id(&merged.id)?;
|
||||
info!(
|
||||
record_key = ?record_key,
|
||||
payload = ?merged,
|
||||
"Executing SurrealDB update"
|
||||
);
|
||||
let record: Option<TestimonialsSchema> =
|
||||
db.update(record_key).merge(merged).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?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success update testimonial".into()),
|
||||
None => bail!("Failed to update testimonial"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_testimonial(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let testimonial = self.query_testimonial_by_id(id).await?;
|
||||
if testimonial.is_deleted {
|
||||
bail!("Testimonial not found");
|
||||
}
|
||||
|
||||
let record_key = get_id(&testimonial.id)?;
|
||||
info!(
|
||||
record_key = ?record_key,
|
||||
"Executing SurrealDB soft delete"
|
||||
);
|
||||
let record: Option<TestimonialsSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.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?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success delete testimonial".into()),
|
||||
None => bail!("Failed to delete testimonial"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use imphnen_utils::{get_iso_date, make_thing};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::Uuid;
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
use super::testimonials_dto::{
|
||||
TestimonialsCreateRequestDto, TestimonialsQueryDto, TestimonialsUpdateRequestDto,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TestimonialsSchema {
|
||||
pub id: Thing,
|
||||
pub user: Thing,
|
||||
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: make_thing(
|
||||
&ResourceEnum::Testimonials.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user: make_thing(
|
||||
&ResourceEnum::Users.to_string(),
|
||||
&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: 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: &Thing) -> Self {
|
||||
Self {
|
||||
id: make_thing(
|
||||
&ResourceEnum::Testimonials.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user: user_id.clone(),
|
||||
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: &Thing,
|
||||
) -> Self {
|
||||
// Normalize id: accept either raw id (uuid) or Thing-formatted id like "table:⟨id⟩"
|
||||
let raw_id = if id.contains(':') {
|
||||
id.split(':').last().unwrap().trim_matches(|c| c == '⟨' || c == '⟩').to_string()
|
||||
} else {
|
||||
id
|
||||
};
|
||||
|
||||
Self {
|
||||
id: make_thing(&ResourceEnum::Testimonials.to_string(), &raw_id),
|
||||
role: payload.role,
|
||||
content: payload.content,
|
||||
updated_at: get_iso_date(),
|
||||
user: user_id.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
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,
|
||||
};
|
||||
|
||||
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: String) -> 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.to_raw(),
|
||||
user_id: testimonial.user.id.to_raw(),
|
||||
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.to_raw(),
|
||||
user_id: created_testimonial.user.id.to_raw(),
|
||||
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),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_testimonial(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
_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),
|
||||
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;
|
||||
@@ -4,10 +4,13 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
|
||||
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
|
||||
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
|
||||
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
|
||||
@@ -22,3 +25,8 @@ chrono.workspace = true
|
||||
anyhow.workspace = true
|
||||
tower-http.workspace = true
|
||||
utoipa-swagger-ui.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dotenvy.workspace = true
|
||||
http-body-util.workspace = true
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
pub fn add(left: u64, right: u64) -> u64 {
|
||||
left + right
|
||||
}
|
||||
pub mod v1;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
// 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,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
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 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 {
|
||||
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 {
|
||||
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 {
|
||||
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 {
|
||||
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 imphnen_utils::extract_id;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
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: Thing,
|
||||
pub user_id: Thing,
|
||||
// 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: MentoringRate,
|
||||
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: MentoringRate,
|
||||
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,
|
||||
#[validate(length(min = 1, message = "Phone number is required"))]
|
||||
pub phone_number: 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"
|
||||
))]
|
||||
pub phone_for_verification: 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: MentoringRate,
|
||||
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: MentoringRate,
|
||||
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: extract_id(&dto.id),
|
||||
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: extract_id(&dto.id),
|
||||
user_id: extract_id(&dto.user_id),
|
||||
// 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.map(|id| extract_id(&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,296 @@
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_iam::{get_id, make_thing};
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
use crate::v1::mentors::mentors_dto::MentorDetailWithUserDto;
|
||||
use crate::v1::mentors::{MentorInsertDto, MentorSchema};
|
||||
use imphnen_libs::{AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto};
|
||||
use imphnen_utils::{DetailQueryBuilder, QueryListBuilder, get_iso_date};
|
||||
use serde_json::{Map, Value};
|
||||
use std::time::Instant;
|
||||
use tracing::instrument;
|
||||
use tracing::info;
|
||||
|
||||
pub struct MentorsRepository<'a> {
|
||||
pub state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> MentorsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, meta), err)]
|
||||
pub async fn query_mentor_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<MentorDetailWithUserDto>>> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let mentors_table = ResourceEnum::Mentors.to_string();
|
||||
let builder = QueryListBuilder::new(db, &mentors_table, &meta)
|
||||
.search_field("user_id.legal_name") // Search in user data instead
|
||||
.select_fields(vec![
|
||||
"id",
|
||||
"user_id",
|
||||
// Personal data comes from user relation, not mentor table
|
||||
"industries",
|
||||
"expertise",
|
||||
"languages",
|
||||
"current_company",
|
||||
"current_role",
|
||||
"years_of_experience",
|
||||
"topics_of_interest",
|
||||
"preferred_mentee_level",
|
||||
"preferred_mentoring_formats",
|
||||
"availability_commitment",
|
||||
"mentoring_rate",
|
||||
"status",
|
||||
"is_deleted",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
]);
|
||||
let result = builder.build().await?;
|
||||
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 data = result.data.into_iter().collect();
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email, include_deleted), err)]
|
||||
pub async fn query_mentor_by_email(
|
||||
&self,
|
||||
email: String,
|
||||
include_deleted: bool,
|
||||
) -> Result<MentorDetailWithUserDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let mut builder = DetailQueryBuilder::new(ResourceEnum::Mentors.to_string())
|
||||
.with_where("user_id.email", Some(email.clone())) // Search in user table
|
||||
.with_select_fields(vec![
|
||||
"id",
|
||||
"user_id",
|
||||
// Personal data comes from user relation, not mentor table
|
||||
"industries",
|
||||
"expertise",
|
||||
"languages",
|
||||
"current_company",
|
||||
"current_role",
|
||||
"years_of_experience",
|
||||
"topics_of_interest",
|
||||
"preferred_mentee_level",
|
||||
"preferred_mentoring_formats",
|
||||
"availability_commitment",
|
||||
"mentoring_rate",
|
||||
"status",
|
||||
"is_deleted",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
]);
|
||||
|
||||
if !include_deleted {
|
||||
builder = builder.with_condition("is_deleted = false");
|
||||
}
|
||||
|
||||
let sql = builder.build();
|
||||
info!(query = %sql, "Executing SurrealDB query in query_mentor_by_email");
|
||||
let mentor_opt: Option<MentorDetailWithUserDto> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
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?}");
|
||||
}
|
||||
let Some(mentor) = mentor_opt else {
|
||||
bail!("Mentor not found");
|
||||
};
|
||||
Ok(mentor)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id, include_deleted), err)]
|
||||
pub async fn query_mentor_by_id(
|
||||
&self,
|
||||
id: &Thing,
|
||||
include_deleted: bool,
|
||||
) -> Result<MentorDetailWithUserDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
// Validate ID format first
|
||||
let mentor_id = match get_id(id) {
|
||||
Ok((_, id_str)) => id_str,
|
||||
Err(_) => bail!("Invalid mentor ID format"),
|
||||
};
|
||||
|
||||
let mentors_table = ResourceEnum::Mentors.to_string();
|
||||
|
||||
// Build query with proper ID binding
|
||||
let mut builder = DetailQueryBuilder::new(mentors_table.clone())
|
||||
.with_id(mentor_id) // Use the extracted ID string
|
||||
.with_select_fields(vec![
|
||||
"id",
|
||||
"user_id",
|
||||
// Personal data comes from user relation, not mentor table
|
||||
"industries",
|
||||
"expertise",
|
||||
"languages",
|
||||
"current_company",
|
||||
"current_role",
|
||||
"years_of_experience",
|
||||
"topics_of_interest",
|
||||
"preferred_mentee_level",
|
||||
"preferred_mentoring_formats",
|
||||
"availability_commitment",
|
||||
"mentoring_rate",
|
||||
"status",
|
||||
"is_deleted",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
]);
|
||||
|
||||
if !include_deleted {
|
||||
builder = builder.with_condition("is_deleted = false");
|
||||
}
|
||||
|
||||
let sql = builder.build();
|
||||
info!(query = %sql, "Executing SurrealDB query in query_mentor_by_id");
|
||||
|
||||
let mentor_opt: Option<MentorDetailWithUserDto> = builder
|
||||
.apply_bindings(db.query(sql))
|
||||
.await?
|
||||
.take(0)?;
|
||||
|
||||
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?}");
|
||||
}
|
||||
|
||||
let Some(mentor) = mentor_opt else {
|
||||
bail!("Mentor not found");
|
||||
};
|
||||
|
||||
Ok(mentor)
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_create_mentor(&self, data: MentorSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let dto: MentorInsertDto = data.into();
|
||||
let resource = ResourceEnum::Mentors.to_string();
|
||||
info!(query = %resource, "Executing SurrealDB create in query_create_mentor");
|
||||
let record: Option<MentorSchema> = db
|
||||
.create(resource)
|
||||
.content(dto.clone())
|
||||
.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?}");
|
||||
}
|
||||
match record {
|
||||
Some(mentor) => {
|
||||
let id_str = mentor.id.id.to_raw();
|
||||
let _user = format!("{:?}", mentor.user_id);
|
||||
Ok(id_str)
|
||||
}
|
||||
None => {
|
||||
bail!("Failed to create mentor")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_update_mentor(&self, data: MentorSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let id_ref = &data.id;
|
||||
let record_key = get_id(id_ref)?;
|
||||
let _existing = self.query_mentor_by_id(id_ref, false).await?;
|
||||
|
||||
let mut merged_data_json: Map<String, Value> =
|
||||
serde_json::to_value(data.clone())
|
||||
.map_err(|e| anyhow::anyhow!("Failed to serialize MentorSchema: {}", e))?
|
||||
.as_object()
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
merged_data_json.remove("id");
|
||||
merged_data_json.remove("user_id");
|
||||
merged_data_json.remove("created_at");
|
||||
|
||||
merged_data_json.insert("updated_at".to_string(), Value::String(get_iso_date()));
|
||||
|
||||
info!(query = ?record_key, "Executing SurrealDB update in query_update_mentor");
|
||||
let record: Option<MentorSchema> =
|
||||
db.update(record_key).merge(merged_data_json).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?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success update mentor".into()),
|
||||
None => {
|
||||
bail!("Failed to update mentor")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_mentor(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let thing = make_thing(ResourceEnum::Mentors.to_string().as_str(), &id);
|
||||
let record_key = get_id(&thing)?;
|
||||
|
||||
let mentor_to_delete_res = self.query_mentor_by_id(&thing, true).await;
|
||||
|
||||
let _mentor_to_delete = match mentor_to_delete_res {
|
||||
Ok(mentor) => {
|
||||
if mentor.is_deleted {
|
||||
bail!("Mentor is already soft deleted");
|
||||
}
|
||||
mentor
|
||||
}
|
||||
Err(e) => {
|
||||
if e.to_string().contains("Mentor has been deleted") {
|
||||
bail!("Mentor is already soft deleted");
|
||||
} else {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut patch = Map::new();
|
||||
patch.insert("is_deleted".to_string(), Value::Bool(true));
|
||||
patch.insert("updated_at".to_string(), Value::String(get_iso_date()));
|
||||
|
||||
info!(query = ?record_key, "Executing SurrealDB soft delete in query_delete_mentor");
|
||||
let record: Option<MentorSchema> = db.update(record_key).merge(patch).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?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success soft delete mentor".into()),
|
||||
None => {
|
||||
bail!("Failed to soft delete mentor")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
use super::{
|
||||
MentorDetailQueryDto, MentorUpdateRequestDto,
|
||||
MentoringLogistics, MentoringRate, ProfessionalProfile,
|
||||
};
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use imphnen_utils::{get_iso_date, make_thing};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{Uuid, sql::Thing};
|
||||
|
||||
#[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: MentoringRate,
|
||||
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: MentoringRate {
|
||||
amount: 0,
|
||||
currency: "IDR".to_string(),
|
||||
per_duration: "hour".to_string(),
|
||||
},
|
||||
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: MentoringRate {
|
||||
amount: mentoring_logistics.mentoring_rate_amount,
|
||||
currency: "IDR".to_string(),
|
||||
per_duration: "hour".to_string(),
|
||||
},
|
||||
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.amount = val;
|
||||
}
|
||||
|
||||
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,464 @@
|
||||
use crate::v1::mentors::{
|
||||
MentorDetailQueryDto, 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::{
|
||||
AuthRepository, RolesEnum, RolesRepository, UsersRepository, UsersSchema,
|
||||
};
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use imphnen_utils::{
|
||||
common_response, success_list_response, success_response, validate_request,
|
||||
};
|
||||
use surrealdb::Uuid;
|
||||
use surrealdb::sql::Thing;
|
||||
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.surrealdb_mem.clone());
|
||||
|
||||
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 = dto.fullname.clone();
|
||||
user_schema.phone_number = dto.phone_number.clone();
|
||||
// Update personal data from identity_and_verification
|
||||
user_schema.legal_name = Some(dto.identity_and_verification.legal_name.clone());
|
||||
user_schema.gender = dto.identity_and_verification.gender.clone();
|
||||
user_schema.domicile = dto.identity_and_verification.domicile.clone();
|
||||
user_schema.phone_for_verification = Some(dto.identity_and_verification.phone_for_verification.clone());
|
||||
// Update personal data from professional_profile
|
||||
user_schema.bio = Some(dto.professional_profile.bio.clone());
|
||||
user_schema.last_education = dto.professional_profile.last_education.clone();
|
||||
user_schema.linkedin_url = dto.professional_profile.linkedin_url.clone();
|
||||
user_schema.github_url = dto.professional_profile.github_url.clone();
|
||||
user_schema.cv_url = dto.professional_profile.cv_url.clone();
|
||||
user_schema.portfolio_url = dto.professional_profile.portfolio_url.clone();
|
||||
user_schema.updated_at = imphnen_utils::get_iso_date();
|
||||
|
||||
let hashed_password = match imphnen_utils::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 = 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.role =
|
||||
imphnen_utils::make_thing_from_enum(ResourceEnum::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 imphnen_utils::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 new_user_schema = UsersSchema {
|
||||
id: imphnen_utils::make_thing_from_enum(
|
||||
ResourceEnum::Users,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
email: dto.email,
|
||||
fullname: dto.fullname,
|
||||
password: hashed_password,
|
||||
phone_number: dto.phone_number,
|
||||
// Store personal data from identity_and_verification in user
|
||||
legal_name: Some(dto.identity_and_verification.legal_name.clone()),
|
||||
gender: dto.identity_and_verification.gender.clone(),
|
||||
domicile: dto.identity_and_verification.domicile.clone(),
|
||||
phone_for_verification: Some(dto.identity_and_verification.phone_for_verification.clone()),
|
||||
// Store personal data from professional_profile in user
|
||||
bio: Some(dto.professional_profile.bio.clone()),
|
||||
last_education: dto.professional_profile.last_education.clone(),
|
||||
linkedin_url: dto.professional_profile.linkedin_url.clone(),
|
||||
github_url: dto.professional_profile.github_url.clone(),
|
||||
cv_url: dto.professional_profile.cv_url.clone(),
|
||||
portfolio_url: dto.professional_profile.portfolio_url.clone(),
|
||||
created_at: imphnen_utils::get_iso_date(),
|
||||
updated_at: imphnen_utils::get_iso_date(),
|
||||
role: imphnen_utils::make_thing_from_enum(
|
||||
ResourceEnum::Roles,
|
||||
&mentor_role.id,
|
||||
),
|
||||
is_active: false,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let otp = imphnen_utils::generate_otp::OtpManager::generate_otp();
|
||||
|
||||
match auth_repo
|
||||
.query_store_otp(final_user_email.clone(), otp.clone())
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
let message = format!("your otp code is {}", otp.code);
|
||||
if let Err(_err) =
|
||||
imphnen_utils::send_email(&final_user_email, "OTP Verification", &message)
|
||||
{
|
||||
error!("Failed to send OTP email to {}: {}", final_user_email, _err);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&_err.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(_err) => {
|
||||
error!("Failed to store OTP for {}: {}", final_user_email, _err);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&_err.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mentor_schema = MentorSchema::create(
|
||||
dto.professional_profile,
|
||||
dto.mentoring_logistics,
|
||||
user_id.to_raw(),
|
||||
);
|
||||
|
||||
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 = MentorDetailQueryDto::from(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 = Thing::from((ResourceEnum::Mentors.to_string().as_str(), 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.to_raw(),
|
||||
user_id: mentor.user_id.to_raw(),
|
||||
// Personal data from user
|
||||
fullname: Some(user.fullname),
|
||||
email: Some(user.email),
|
||||
legal_name: user.legal_name,
|
||||
gender: user.gender,
|
||||
domicile: user.domicile,
|
||||
phone_for_verification: user.phone_for_verification,
|
||||
bio: user.bio,
|
||||
last_education: user.last_education,
|
||||
linkedin_url: user.linkedin_url,
|
||||
github_url: user.github_url,
|
||||
cv_url: user.cv_url,
|
||||
portfolio_url: user.portfolio_url,
|
||||
// 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 thing_id = Thing::from((ResourceEnum::Mentors.to_string().as_str(), id));
|
||||
let existing_mentor = match repo.query_mentor_by_id(&thing_id, false).await {
|
||||
Ok(mentor) => mentor,
|
||||
Err(_e) => return common_response(StatusCode::NOT_FOUND, &_e.to_string()),
|
||||
};
|
||||
|
||||
let mut schema = MentorSchema::from(MentorDetailQueryDto::from(existing_mentor));
|
||||
schema = schema.update(dto);
|
||||
|
||||
match repo.query_update_mentor(schema).await {
|
||||
Ok(_) => {
|
||||
let updated_mentor =
|
||||
repo.query_mentor_by_id(&thing_id, false).await.unwrap();
|
||||
let response_dto =
|
||||
MentorDetailResponseDto::from(MentorDetailQueryDto::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.to_string()).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(MentorDetailQueryDto::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(MentorDetailQueryDto::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(MentorDetailQueryDto::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 thing_id = Thing::from((ResourceEnum::Mentors.to_string().as_str(), id));
|
||||
let existing_mentor = match repo.query_mentor_by_id(&thing_id, false).await {
|
||||
Ok(mentor) => mentor,
|
||||
Err(_e) => return common_response(StatusCode::NOT_FOUND, &_e.to_string()),
|
||||
};
|
||||
|
||||
let mut schema = MentorSchema::from(MentorDetailQueryDto::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(&thing_id, false).await.unwrap();
|
||||
let response_dto =
|
||||
MentorDetailResponseDto::from(MentorDetailQueryDto::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,365 @@
|
||||
use super::{SessionDetailQueryDto, SessionListQueryDto, SessionSchema};
|
||||
use imphnen_libs::AppState;
|
||||
use imphnen_utils::get_id;
|
||||
use serde::Deserialize;
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
pub struct SessionsRepository<'a> {
|
||||
pub state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> SessionsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Create Session
|
||||
// ============================================
|
||||
pub async fn create_session(&self, schema: SessionSchema) -> Result<SessionSchema, String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let created: Option<SessionSchema> = db
|
||||
.create("sessions")
|
||||
.content(schema)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create session: {}", e))?;
|
||||
|
||||
created.ok_or_else(|| "Session creation returned None".to_string())
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Session by ID
|
||||
// ============================================
|
||||
pub async fn query_session_by_id(&self, id: &Thing) -> Result<Option<SessionSchema>, String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(id).map_err(|e| e.to_string())?;
|
||||
let session: Option<SessionSchema> = db
|
||||
.select(record_key)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch session: {}", e))?;
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Session Detail with User Info
|
||||
// ============================================
|
||||
pub async fn query_session_detail(&self, id: &Thing) -> Result<Option<SessionDetailQueryDto>, String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let query = r#"
|
||||
SELECT
|
||||
id,
|
||||
mentor_id,
|
||||
mentee_id,
|
||||
topic,
|
||||
description,
|
||||
scheduled_at,
|
||||
duration_minutes,
|
||||
meeting_link,
|
||||
session_type,
|
||||
status,
|
||||
feedback,
|
||||
rating,
|
||||
feedback_submitted_at,
|
||||
created_at,
|
||||
updated_at,
|
||||
(SELECT fullname FROM $parent.mentor_id.user_id)[0].fullname AS mentor_fullname,
|
||||
(SELECT fullname FROM $parent.mentee_id)[0].fullname AS mentee_fullname
|
||||
FROM type::thing($table, $id)
|
||||
"#;
|
||||
|
||||
let mut result = db
|
||||
.query(query)
|
||||
.bind(("table", "sessions"))
|
||||
.bind(("id", id.id.to_string()))
|
||||
.await
|
||||
.map_err(|e| format!("Failed to query session detail: {}", e))?;
|
||||
|
||||
let session: Option<SessionDetailQueryDto> = result
|
||||
.take(0)
|
||||
.map_err(|e| format!("Failed to parse session detail: {}", e))?;
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// List Mentor's Sessions
|
||||
// ============================================
|
||||
pub async fn query_mentor_sessions(
|
||||
&self,
|
||||
mentor_id: &Thing,
|
||||
status_filter: Option<String>,
|
||||
) -> Result<Vec<SessionListQueryDto>, String> {
|
||||
let query = if let Some(_status) = status_filter.as_ref() {
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
mentor_id,
|
||||
mentee_id,
|
||||
topic,
|
||||
scheduled_at,
|
||||
duration_minutes,
|
||||
session_type,
|
||||
status,
|
||||
rating,
|
||||
created_at,
|
||||
(SELECT fullname FROM $parent.mentee_id)[0].fullname AS mentee_fullname,
|
||||
(SELECT email FROM $parent.mentee_id)[0].email AS mentee_email
|
||||
FROM sessions
|
||||
WHERE mentor_id = $mentor_id AND status = $status
|
||||
ORDER BY scheduled_at DESC
|
||||
"#
|
||||
} else {
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
mentor_id,
|
||||
mentee_id,
|
||||
topic,
|
||||
scheduled_at,
|
||||
duration_minutes,
|
||||
session_type,
|
||||
status,
|
||||
rating,
|
||||
created_at,
|
||||
(SELECT fullname FROM $parent.mentee_id)[0].fullname AS mentee_fullname,
|
||||
(SELECT email FROM $parent.mentee_id)[0].email AS mentee_email
|
||||
FROM sessions
|
||||
WHERE mentor_id = $mentor_id
|
||||
ORDER BY scheduled_at DESC
|
||||
"#
|
||||
};
|
||||
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let mentor_id_clone = mentor_id.clone();
|
||||
let mut result = if let Some(status_val) = status_filter {
|
||||
db.query(query)
|
||||
.bind(("mentor_id", mentor_id_clone))
|
||||
.bind(("status", status_val))
|
||||
.await
|
||||
} else {
|
||||
db.query(query)
|
||||
.bind(("mentor_id", mentor_id_clone))
|
||||
.await
|
||||
}
|
||||
.map_err(|e| format!("Failed to query mentor sessions: {}", e))?;
|
||||
|
||||
let sessions: Vec<SessionListQueryDto> = result
|
||||
.take(0)
|
||||
.map_err(|e| format!("Failed to parse mentor sessions: {}", e))?;
|
||||
|
||||
Ok(sessions)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// List User's Sessions (as mentee)
|
||||
// ============================================
|
||||
pub async fn query_user_sessions(
|
||||
&self,
|
||||
user_id: &Thing,
|
||||
status_filter: Option<String>,
|
||||
) -> Result<Vec<SessionListQueryDto>, String> {
|
||||
let query = if let Some(_status) = status_filter.as_ref() {
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
mentor_id,
|
||||
mentee_id,
|
||||
topic,
|
||||
scheduled_at,
|
||||
duration_minutes,
|
||||
session_type,
|
||||
status,
|
||||
rating,
|
||||
created_at,
|
||||
(SELECT fullname FROM $parent.mentee_id)[0].fullname AS mentee_fullname,
|
||||
(SELECT email FROM $parent.mentee_id)[0].email AS mentee_email
|
||||
FROM sessions
|
||||
WHERE mentee_id = $user_id AND status = $status
|
||||
ORDER BY scheduled_at DESC
|
||||
"#
|
||||
} else {
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
mentor_id,
|
||||
mentee_id,
|
||||
topic,
|
||||
scheduled_at,
|
||||
duration_minutes,
|
||||
session_type,
|
||||
status,
|
||||
rating,
|
||||
created_at,
|
||||
(SELECT fullname FROM $parent.mentee_id)[0].fullname AS mentee_fullname,
|
||||
(SELECT email FROM $parent.mentee_id)[0].email AS mentee_email
|
||||
FROM sessions
|
||||
WHERE mentee_id = $user_id
|
||||
ORDER BY scheduled_at DESC
|
||||
"#
|
||||
};
|
||||
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let user_id_clone = user_id.clone();
|
||||
let mut result = if let Some(status_val) = status_filter {
|
||||
db.query(query)
|
||||
.bind(("user_id", user_id_clone))
|
||||
.bind(("status", status_val))
|
||||
.await
|
||||
} else {
|
||||
db.query(query)
|
||||
.bind(("user_id", user_id_clone))
|
||||
.await
|
||||
}
|
||||
.map_err(|e| format!("Failed to query user sessions: {}", e))?;
|
||||
|
||||
let sessions: Vec<SessionListQueryDto> = result
|
||||
.take(0)
|
||||
.map_err(|e| format!("Failed to parse user sessions: {}", e))?;
|
||||
|
||||
Ok(sessions)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Booked Dates for Mentor
|
||||
// ============================================
|
||||
pub async fn query_booked_dates(&self, mentor_id: &Thing) -> Result<Vec<String>, String> {
|
||||
let query = r#"
|
||||
SELECT scheduled_at FROM sessions
|
||||
WHERE mentor_id = $mentor_id
|
||||
AND status IN ['pending', 'confirmed']
|
||||
ORDER BY scheduled_at ASC
|
||||
"#;
|
||||
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let mentor_id_clone = mentor_id.clone();
|
||||
let mut result = db
|
||||
.query(query)
|
||||
.bind(("mentor_id", mentor_id_clone))
|
||||
.await
|
||||
.map_err(|e| format!("Failed to query booked dates: {}", e))?;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DateOnly {
|
||||
scheduled_at: String,
|
||||
}
|
||||
|
||||
let dates: Vec<DateOnly> = result
|
||||
.take(0)
|
||||
.map_err(|e| format!("Failed to parse booked dates: {}", e))?;
|
||||
|
||||
Ok(dates.into_iter().map(|d| d.scheduled_at).collect())
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Update Session
|
||||
// ============================================
|
||||
pub async fn update_session(&self, id: &Thing, schema: SessionSchema) -> Result<SessionSchema, String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(id).map_err(|e| e.to_string())?;
|
||||
let updated: Option<SessionSchema> = db
|
||||
.update(record_key)
|
||||
.content(schema)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to update session: {}", e))?;
|
||||
|
||||
updated.ok_or_else(|| "Session update returned None".to_string())
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Count Mentor Sessions
|
||||
// ============================================
|
||||
pub async fn count_mentor_sessions(
|
||||
&self,
|
||||
mentor_id: &Thing,
|
||||
status_filter: Option<String>,
|
||||
) -> Result<usize, String> {
|
||||
let query = if status_filter.is_some() {
|
||||
"SELECT count() FROM sessions WHERE mentor_id = $mentor_id AND status = $status GROUP ALL"
|
||||
} else {
|
||||
"SELECT count() FROM sessions WHERE mentor_id = $mentor_id GROUP ALL"
|
||||
};
|
||||
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let mentor_id_clone = mentor_id.clone();
|
||||
let mut result = if let Some(status_val) = status_filter {
|
||||
db.query(query)
|
||||
.bind(("mentor_id", mentor_id_clone))
|
||||
.bind(("status", status_val))
|
||||
.await
|
||||
} else {
|
||||
db.query(query)
|
||||
.bind(("mentor_id", mentor_id_clone))
|
||||
.await
|
||||
}
|
||||
.map_err(|e| format!("Failed to count mentor sessions: {}", e))?;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct CountResult {
|
||||
count: usize,
|
||||
}
|
||||
|
||||
let count_result: Option<CountResult> = result
|
||||
.take(0)
|
||||
.map_err(|e| format!("Failed to parse count: {}", e))?;
|
||||
|
||||
Ok(count_result.map(|r| r.count).unwrap_or(0))
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Count User Sessions
|
||||
// ============================================
|
||||
pub async fn count_user_sessions(
|
||||
&self,
|
||||
user_id: &Thing,
|
||||
status_filter: Option<String>,
|
||||
) -> Result<usize, String> {
|
||||
let query = if status_filter.is_some() {
|
||||
"SELECT count() FROM sessions WHERE mentee_id = $user_id AND status = $status GROUP ALL"
|
||||
} else {
|
||||
"SELECT count() FROM sessions WHERE mentee_id = $user_id GROUP ALL"
|
||||
};
|
||||
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let user_id_clone = user_id.clone();
|
||||
let mut result = if let Some(status_val) = status_filter {
|
||||
db.query(query)
|
||||
.bind(("user_id", user_id_clone))
|
||||
.bind(("status", status_val))
|
||||
.await
|
||||
} else {
|
||||
db.query(query)
|
||||
.bind(("user_id", user_id_clone))
|
||||
.await
|
||||
}
|
||||
.map_err(|e| format!("Failed to count user sessions: {}", e))?;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct CountResult {
|
||||
count: usize,
|
||||
}
|
||||
|
||||
let count_result: Option<CountResult> = result
|
||||
.take(0)
|
||||
.map_err(|e| format!("Failed to parse count: {}", e))?;
|
||||
|
||||
Ok(count_result.map(|r| r.count).unwrap_or(0))
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Delete Session (soft delete)
|
||||
// ============================================
|
||||
// Delete Session (soft delete)
|
||||
// ============================================
|
||||
pub async fn delete_session(&self, id: &Thing) -> Result<(), String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(id).map_err(|e| e.to_string())?;
|
||||
let _: Option<SessionSchema> = db
|
||||
.delete(record_key)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to delete session: {}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
use super::{BookSessionRequestDto, SessionFeedbackRequestDto, UpdateSessionStatusRequestDto};
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use imphnen_utils::{get_iso_date, make_thing};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{sql::Thing, Uuid};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct SessionSchema {
|
||||
pub id: Thing,
|
||||
pub mentor_id: Thing,
|
||||
pub mentee_id: Thing,
|
||||
pub topic: String,
|
||||
pub description: Option<String>,
|
||||
pub scheduled_at: String, // ISO 8601 datetime
|
||||
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<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl Default for SessionSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: make_thing(
|
||||
ResourceEnum::Sessions.to_string().as_str(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
mentor_id: make_thing(
|
||||
ResourceEnum::Mentors.to_string().as_str(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
mentee_id: make_thing(
|
||||
ResourceEnum::Users.to_string().as_str(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
topic: String::new(),
|
||||
description: None,
|
||||
scheduled_at: get_iso_date(),
|
||||
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: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionSchema {
|
||||
pub fn from_book_request(
|
||||
mentor_id: Thing,
|
||||
mentee_id: Thing,
|
||||
request: BookSessionRequestDto,
|
||||
) -> Self {
|
||||
Self {
|
||||
mentor_id,
|
||||
mentee_id,
|
||||
topic: request.topic,
|
||||
description: request.description,
|
||||
scheduled_at: request.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 = get_iso_date();
|
||||
}
|
||||
|
||||
pub fn add_feedback(&mut self, request: SessionFeedbackRequestDto) {
|
||||
self.feedback = Some(request.feedback);
|
||||
self.rating = Some(request.rating);
|
||||
self.feedback_submitted_at = Some(get_iso_date());
|
||||
self.updated_at = get_iso_date();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
use super::{
|
||||
AvailabilitySlotDto, BookSessionRequestDto, BookSessionResponseDto, MentorAvailabilityDto,
|
||||
SessionFeedbackRequestDto, SessionFeedbackResponseDto, SessionListItemDto,
|
||||
SessionListResponseDto, SessionSchema, SessionsRepository, UpdateSessionStatusRequestDto,
|
||||
UpdateSessionStatusResponseDto,
|
||||
};
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use chrono::{Duration, Utc};
|
||||
use imphnen_entities::ResponseSuccessDto;
|
||||
use imphnen_libs::AppState;
|
||||
use imphnen_utils::{common_response, extract_id, get_iso_date, make_thing, success_response, validate_request};
|
||||
|
||||
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 mentor_thing = make_thing("mentors", &mentor_id);
|
||||
let mentee_thing = make_thing("users", &user_id);
|
||||
|
||||
let schema = SessionSchema::from_book_request(mentor_thing.clone(), mentee_thing.clone(), dto);
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
match repo.create_session(schema).await {
|
||||
Ok(created) => {
|
||||
let response = BookSessionResponseDto {
|
||||
id: extract_id(&created.id),
|
||||
mentor_id: extract_id(&created.mentor_id),
|
||||
mentee_id: extract_id(&created.mentee_id),
|
||||
topic: created.topic,
|
||||
description: created.description,
|
||||
scheduled_at: created.scheduled_at,
|
||||
duration_minutes: created.duration_minutes,
|
||||
session_type: created.session_type,
|
||||
status: created.status,
|
||||
created_at: created.created_at,
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Mentor's Sessions
|
||||
// ============================================
|
||||
pub async fn get_mentor_sessions(
|
||||
state: &AppState,
|
||||
mentor_id: String,
|
||||
_user_email: String,
|
||||
status_filter: Option<String>,
|
||||
) -> Response {
|
||||
let mentor_thing = make_thing("mentors", &mentor_id);
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
|
||||
// Get count and sessions
|
||||
let count = match repo.count_mentor_sessions(&mentor_thing, 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_thing, 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),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get User's Sessions (as mentee)
|
||||
// ============================================
|
||||
pub async fn get_user_sessions(
|
||||
state: &AppState,
|
||||
user_id: String,
|
||||
status_filter: Option<String>,
|
||||
) -> Response {
|
||||
let user_thing = make_thing("users", &user_id);
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
|
||||
// Get count and sessions
|
||||
let count = match repo.count_user_sessions(&user_thing, 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_thing, 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),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Get Mentor Availability
|
||||
// ============================================
|
||||
pub async fn get_mentor_availability(state: &AppState, mentor_id: String) -> Response {
|
||||
let mentor_thing = make_thing("mentors", &mentor_id);
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
match repo.query_booked_dates(&mentor_thing).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),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 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 session_thing = make_thing("sessions", &session_id);
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
match repo.query_session_by_id(&session_thing).await {
|
||||
Ok(Some(mut session)) => {
|
||||
session.update_status(dto.clone());
|
||||
match repo.update_session(&session_thing, session).await {
|
||||
Ok(updated) => {
|
||||
let response = UpdateSessionStatusResponseDto {
|
||||
id: extract_id(&updated.id),
|
||||
status: updated.status,
|
||||
meeting_link: updated.meeting_link,
|
||||
updated_at: updated.updated_at,
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e),
|
||||
}
|
||||
}
|
||||
Ok(None) => common_response(StatusCode::NOT_FOUND, "Session not found"),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e),
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 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 session_thing = make_thing("sessions", &session_id);
|
||||
|
||||
let repo = SessionsRepository::new(state);
|
||||
match repo.query_session_by_id(&session_thing).await {
|
||||
Ok(Some(mut session)) => {
|
||||
// Authorization: Only mentee can submit feedback
|
||||
let mentee_id = extract_id(&session.mentee_id);
|
||||
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.add_feedback(dto.clone());
|
||||
match repo.update_session(&session_thing, session).await {
|
||||
Ok(updated) => {
|
||||
let response = SessionFeedbackResponseDto {
|
||||
id: extract_id(&updated.id),
|
||||
feedback: dto.feedback,
|
||||
rating: dto.rating,
|
||||
submitted_at: updated.feedback_submitted_at.unwrap_or_else(get_iso_date),
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response })
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e),
|
||||
}
|
||||
}
|
||||
Ok(None) => common_response(StatusCode::NOT_FOUND, "Session not found"),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -6,6 +6,12 @@ edition = "2024"
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
utoipa.workspace = true
|
||||
surrealdb.workspace = true
|
||||
anyhow.workspace = true
|
||||
thiserror.workspace = true
|
||||
uuid.workspace = true
|
||||
strum.workspace = true
|
||||
strum_macros.workspace = true
|
||||
chrono.workspace = true
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
/// Schema untuk audit log yang mencatat semua aksi admin
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct AuditLogSchema {
|
||||
/// ID unik dari log
|
||||
pub id: Option<Thing>,
|
||||
/// ID pengguna yang melakukan aksi
|
||||
pub user_id: String,
|
||||
/// Email pengguna
|
||||
pub user_email: String,
|
||||
/// Tipe aksi yang dilakukan (CREATE, UPDATE, DELETE, etc.)
|
||||
pub action: String,
|
||||
/// Resource yang terkena aksi
|
||||
pub resource: String,
|
||||
/// ID resource yang terkena aksi
|
||||
pub resource_id: Option<String>,
|
||||
/// Data sebelum perubahan (untuk UPDATE/DELETE)
|
||||
pub old_data: Option<serde_json::Value>,
|
||||
/// Data setelah perubahan (untuk CREATE/UPDATE)
|
||||
pub new_data: Option<serde_json::Value>,
|
||||
/// IP address pengguna
|
||||
pub ip_address: String,
|
||||
/// User agent pengguna
|
||||
pub user_agent: Option<String>,
|
||||
/// Timestamp ketika aksi dilakukan
|
||||
pub timestamp: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Schema untuk rate limiting menggunakan SurrealDB memori
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct RateLimitSchema {
|
||||
/// ID unik (IP address)
|
||||
pub id: Option<Thing>,
|
||||
/// IP address klien
|
||||
pub ip_address: String,
|
||||
/// Jumlah request dalam window saat ini
|
||||
pub request_count: u32,
|
||||
/// Timestamp pertama request dalam window
|
||||
pub first_request_time: DateTime<Utc>,
|
||||
/// Timestamp terakhir request
|
||||
pub last_request_time: DateTime<Utc>,
|
||||
/// Window duration dalam detik
|
||||
pub window_duration_secs: u64,
|
||||
}
|
||||
|
||||
impl RateLimitSchema {
|
||||
/// Buat instance baru RateLimitSchema
|
||||
pub fn new(ip_address: String, window_duration_secs: u64) -> Self {
|
||||
let now = Utc::now();
|
||||
Self {
|
||||
id: None,
|
||||
ip_address,
|
||||
request_count: 1,
|
||||
first_request_time: now,
|
||||
last_request_time: now,
|
||||
window_duration_secs,
|
||||
}
|
||||
}
|
||||
|
||||
/// Periksa apakah rate limit sudah terlampaui
|
||||
pub fn is_rate_limited(&self, max_requests: u32) -> bool {
|
||||
self.request_count > max_requests
|
||||
}
|
||||
|
||||
/// Perbarui counter dan timestamp
|
||||
pub fn increment(&mut self) {
|
||||
self.request_count += 1;
|
||||
self.last_request_time = Utc::now();
|
||||
}
|
||||
|
||||
/// Reset counter jika window sudah expired
|
||||
pub fn reset_if_expired(&mut self) -> bool {
|
||||
let now = Utc::now();
|
||||
let duration = now - self.first_request_time;
|
||||
|
||||
if duration.num_seconds() >= self.window_duration_secs as i64 {
|
||||
self.request_count = 1;
|
||||
self.first_request_time = now;
|
||||
self.last_request_time = now;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,4 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{
|
||||
engine::{local::Db, remote::ws::Client},
|
||||
Surreal,
|
||||
};
|
||||
use utoipa::{IntoParams, ToSchema};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
@@ -54,13 +50,12 @@ pub struct ResponseListSuccessDto<T: Serialize> {
|
||||
pub meta: Option<MetaResponseDto>,
|
||||
}
|
||||
|
||||
pub type SurrealWsClient = Surreal<Client>;
|
||||
pub type SurrealMemClient = Surreal<Db>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub surrealdb_ws: SurrealWsClient,
|
||||
pub surrealdb_mem: SurrealMemClient,
|
||||
#[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)]
|
||||
|
||||
@@ -1,26 +1,58 @@
|
||||
pub mod error {
|
||||
use axum::Json;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::response::Response;
|
||||
use axum::Json;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("database error")]
|
||||
Db,
|
||||
#[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 {
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(self.to_string())).into_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<surrealdb::Error> for Error {
|
||||
fn from(error: surrealdb::Error) -> Self {
|
||||
eprintln!("{error}");
|
||||
Self::Db
|
||||
Self::Db(error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StatusCode> for Error {
|
||||
fn from(status: StatusCode) -> Self {
|
||||
Self::StatusCode(status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,32 @@
|
||||
pub mod common_dto;
|
||||
pub mod error_dto;
|
||||
pub use common_dto::*;
|
||||
pub use error_dto::*;
|
||||
pub mod users;
|
||||
pub mod permissions;
|
||||
pub mod audit_log;
|
||||
|
||||
// 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;
|
||||
|
||||
// Explicit audit_log exports
|
||||
pub use audit_log::AuditLogSchema;
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
use std::fmt;
|
||||
use uuid::Uuid;
|
||||
use strum_macros::EnumIter;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, 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,
|
||||
|
||||
// Team permissions
|
||||
ReadListTeams,
|
||||
ReadDetailTeams,
|
||||
|
||||
// Administrator permissions
|
||||
ManageAllUsers,
|
||||
ManageAllRoles,
|
||||
ManageAllPermissions,
|
||||
ManageAllTeams,
|
||||
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",
|
||||
|
||||
// Team permissions
|
||||
PermissionsEnum::ReadListTeams => "Read List Teams",
|
||||
PermissionsEnum::ReadDetailTeams => "Read Detail Teams",
|
||||
|
||||
// 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::ManageAllTeams => "Manage All Teams",
|
||||
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(),
|
||||
|
||||
// Team permissions
|
||||
PermissionsEnum::ReadListTeams => "e1f23456-7890-1234-5678-90abcdef1234".to_string(),
|
||||
PermissionsEnum::ReadDetailTeams => "f2345678-8901-2345-6789-01bcdef23456".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::ManageAllTeams => "a3b4c5d6-7890-1234-5678-3456789012ab".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,
|
||||
|
||||
// Team permissions
|
||||
PermissionsEnum::ReadListTeams,
|
||||
PermissionsEnum::ReadDetailTeams,
|
||||
|
||||
// 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::ManageAllTeams,
|
||||
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.as_ref().map(|id| id.id.to_raw()).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<Thing>,
|
||||
pub name: Option<String>,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use crate::permissions::{PermissionsQueryDto, PermissionsItemDto};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct ExperienceDto {
|
||||
pub id: String,
|
||||
pub company: String,
|
||||
pub position: String,
|
||||
pub duration: String,
|
||||
pub period: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct EducationDto {
|
||||
pub id: String,
|
||||
pub institution: String,
|
||||
pub degree: String,
|
||||
pub field: String,
|
||||
pub period: String,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RolesDetailQueryDto {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub permissions: Option<Vec<Option<PermissionsQueryDto>>>,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for RolesDetailQueryDto {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: Thing::from(("".to_string(), surrealdb::sql::Id::Number(0))),
|
||||
name: String::new(),
|
||||
permissions: None,
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
|
||||
pub struct RolesDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub permissions: Vec<PermissionsItemDto>,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl RolesDetailItemDto {
|
||||
pub fn from(dto: &RolesDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.id.to_raw(),
|
||||
name: dto.name.clone(),
|
||||
is_deleted: dto.is_deleted,
|
||||
permissions: dto
|
||||
.permissions
|
||||
.as_ref()
|
||||
.unwrap_or(&vec![])
|
||||
.iter()
|
||||
.filter_map(|p| p.as_ref())
|
||||
.map(PermissionsItemDto::from)
|
||||
.collect(),
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersDetailQueryDto {
|
||||
pub id: Thing,
|
||||
pub fullname: String,
|
||||
pub legal_name: Option<String>,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub phone_for_verification: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub gender: Option<String>,
|
||||
pub birthdate: Option<String>,
|
||||
pub domicile: 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>,
|
||||
pub website_url: Option<String>,
|
||||
pub twitter_url: Option<String>,
|
||||
pub location: Option<String>,
|
||||
pub skills: Option<Vec<String>>,
|
||||
pub experience: Option<Vec<ExperienceDto>>,
|
||||
pub education: Option<Vec<EducationDto>>,
|
||||
pub career_status: Option<String>,
|
||||
pub password: String,
|
||||
pub role: RolesDetailQueryDto,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub mentor_id: Option<Thing>,
|
||||
}
|
||||
|
||||
impl UsersDetailQueryDto {
|
||||
pub fn from(self) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,10 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
|
||||
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
|
||||
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
|
||||
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
|
||||
@@ -22,3 +23,6 @@ chrono.workspace = true
|
||||
anyhow.workspace = true
|
||||
tower-http.workspace = true
|
||||
utoipa-swagger-ui.workspace = true
|
||||
rand_distr.workspace = true
|
||||
log.workspace = true
|
||||
tracing.workspace = true
|
||||
@@ -1,9 +1,43 @@
|
||||
use imphnen_entities::*;
|
||||
use imphnen_libs::*;
|
||||
use imphnen_utils::*;
|
||||
|
||||
pub mod v1;
|
||||
pub use imphnen_entities::*;
|
||||
pub use imphnen_libs::*;
|
||||
pub use imphnen_utils::*;
|
||||
pub use v1::*;
|
||||
|
||||
// Re-export core entity types used across the gacha system
|
||||
pub use imphnen_entities::{
|
||||
CountResult,
|
||||
Error,
|
||||
ExperienceDto,
|
||||
EducationDto,
|
||||
MessageResponseDto,
|
||||
MetaRequestDto,
|
||||
MetaResponseDto,
|
||||
PermissionsEnum,
|
||||
PermissionsItemDto,
|
||||
PermissionsQueryDto,
|
||||
ResponseListSuccessDto,
|
||||
ResponseSuccessDto,
|
||||
UsersDetailQueryDto,
|
||||
};
|
||||
|
||||
// Explicitly import only what we need from libs and utils to avoid pollution
|
||||
pub use imphnen_libs::{
|
||||
AppState,
|
||||
MinioService,
|
||||
};
|
||||
|
||||
pub use imphnen_utils::{
|
||||
bind_filter,
|
||||
csrf_token,
|
||||
extract_email,
|
||||
generate_date,
|
||||
generate_otp,
|
||||
get_id,
|
||||
logger,
|
||||
make_thing,
|
||||
query_builder,
|
||||
query_list,
|
||||
response_format,
|
||||
serde_helpers,
|
||||
validator,
|
||||
};
|
||||
|
||||
// Re-export public v1 API
|
||||
pub use v1::gacha_router;
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct GachaClaimRequestDto {
|
||||
#[validate(length(min = 1, message = "User ID must not be empty"))]
|
||||
pub user_id: String,
|
||||
|
||||
#[validate(length(min = 1, message = "Item ID must not be empty"))]
|
||||
pub item_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GachaClaimDto {
|
||||
pub id: String,
|
||||
pub user: String,
|
||||
pub item: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct GachaClaimDtoRaw {
|
||||
pub id: Thing,
|
||||
pub user: Thing,
|
||||
pub item: Thing,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
use super::GachaClaimSchema;
|
||||
use crate::{AppState, ResourceEnum};
|
||||
use anyhow::{Result, bail};
|
||||
|
||||
pub struct GachaClaimRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> GachaClaimRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_gacha_claim_by_id(
|
||||
&self,
|
||||
id: String,
|
||||
) -> Result<GachaClaimSchema> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let result: Option<GachaClaimSchema> = db
|
||||
.select((ResourceEnum::GachaClaims.to_string(), id.clone()))
|
||||
.await?;
|
||||
match result {
|
||||
Some(claim) if !claim.is_deleted => Ok(claim),
|
||||
_ => bail!("Gacha Claim not found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_create_gacha_claim(
|
||||
&self,
|
||||
data: GachaClaimSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<GachaClaimSchema> = db
|
||||
.create(ResourceEnum::GachaClaims.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success create Gacha Claim".into()),
|
||||
None => bail!("Failed to create Gacha Claim"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
use crate::{ResourceEnum, make_thing};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{Uuid, sql::Thing};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct GachaClaimSchema {
|
||||
pub id: Thing,
|
||||
pub user: Thing,
|
||||
pub item: Thing,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for GachaClaimSchema {
|
||||
fn default() -> Self {
|
||||
GachaClaimSchema {
|
||||
id: make_thing(
|
||||
&ResourceEnum::GachaClaims.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user: make_thing(
|
||||
&ResourceEnum::Users.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
item: make_thing(
|
||||
&ResourceEnum::GachaItems.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
pub mod gacha_claim_dto;
|
||||
pub mod gacha_claim_repository;
|
||||
pub mod gacha_claim_schema;
|
||||
|
||||
pub use gacha_claim_dto::*;
|
||||
pub use gacha_claim_repository::*;
|
||||
pub use gacha_claim_schema::*;
|
||||
@@ -0,0 +1,66 @@
|
||||
use axum::Extension;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Json, extract::Path};
|
||||
use imphnen_iam::{PermissionsEnum, permissions_guard};
|
||||
use crate::AppState;
|
||||
use imphnen_entities::{MessageResponseDto, ResponseSuccessDto};
|
||||
use crate::v1::gacha_claims::{GachaClaimItemDto, GachaClaimRequestDto, GachaClaimService};
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/gacha/claims/detail/{id}",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
params(("id" = String, Path, description = "Gacha Claim ID")),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get Gacha Claim by ID", body = ResponseSuccessDto<GachaClaimItemDto>)
|
||||
),
|
||||
tag = "Gacha"
|
||||
)]
|
||||
pub async fn get_detail_gacha_claim(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadDetailGachaClaims],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_user, state)) => GachaClaimService::get_gacha_claim_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/gacha/claims/create",
|
||||
request_body = GachaClaimRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "[ADMIN] Create new gacha claim", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Gacha"
|
||||
)]
|
||||
pub async fn post_create_gacha_claim(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<GachaClaimRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::CreateGachaClaims],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_user, state)) => GachaClaimService::create_gacha_claim(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use crate::v1::gacha_items::GachaItemDto;
|
||||
use crate::v1::gacha_items::gacha_items_schema::GachaItemSchema;
|
||||
use imphnen_iam::{UsersDetailItemDto, UsersDetailQueryDto};
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
// Custom validator for user ID format (UUID-like validation)
|
||||
pub fn validate_user_id_format(user_id: &str) -> Result<(), ValidationError> {
|
||||
lazy_static! {
|
||||
static ref UUID_REGEX: Regex = Regex::new(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$").unwrap();
|
||||
}
|
||||
if UUID_REGEX.is_match(user_id) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("invalid_format"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct GachaClaimRequestDto {
|
||||
#[validate(length(min = 1, message = "User ID must not be empty"))]
|
||||
#[validate(custom(
|
||||
function = "validate_user_id_format",
|
||||
message = "User ID must be a valid UUID"
|
||||
))]
|
||||
pub user_id: String,
|
||||
|
||||
#[validate(length(min = 1, message = "Item ID must not be empty"))]
|
||||
pub item_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GachaClaimItemDto {
|
||||
pub id: String,
|
||||
pub user: UsersDetailItemDto,
|
||||
pub item: GachaItemDto,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct GachaClaimQueryDto {
|
||||
pub id: Thing,
|
||||
pub user: UsersDetailQueryDto,
|
||||
pub item: GachaItemSchema,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl GachaClaimItemDto {
|
||||
pub fn from(dto: &GachaClaimQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.id.to_raw(),
|
||||
user: UsersDetailItemDto::from(&dto.user),
|
||||
item: GachaItemDto::from(dto.item.clone()),
|
||||
is_deleted: dto.is_deleted,
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use crate::v1::gacha_claims::gacha_claims_dto::GachaClaimQueryDto;
|
||||
use crate::v1::gacha_claims::gacha_claims_schema::GachaClaimSchema;
|
||||
use crate::AppState;
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_iam::DetailQueryBuilder;
|
||||
use std::time::Instant;
|
||||
use tracing::{instrument, info};
|
||||
|
||||
pub struct GachaClaimRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> GachaClaimRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_gacha_claim_by_id(
|
||||
&self,
|
||||
id: String,
|
||||
) -> Result<GachaClaimQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::GachaClaims.to_string())
|
||||
.with_id(id.clone())
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch("item")
|
||||
.with_fetch("user");
|
||||
let sql = builder.build();
|
||||
info!(query = %sql, "Executing SurrealDB query");
|
||||
let result: Option<GachaClaimQueryDto> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_gacha_claim_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
match result {
|
||||
Some(claim) if !claim.is_deleted => Ok(claim),
|
||||
_ => bail!("Gacha Claim not found"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_create_gacha_claim(
|
||||
&self,
|
||||
data: GachaClaimSchema,
|
||||
) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
info!(
|
||||
resource = %ResourceEnum::GachaClaims.to_string(),
|
||||
content = ?data,
|
||||
"Executing SurrealDB create query"
|
||||
);
|
||||
let record: Option<GachaClaimSchema> = db
|
||||
.create(ResourceEnum::GachaClaims.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_gacha_claim' took: {elapsed:.2?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success create Gacha Claim".into()),
|
||||
None => bail!("Failed to create Gacha Claim"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use crate::v1::gacha_rolls::gacha_rolls_dto::GachaRollQueryDto;
|
||||
use crate::{make_thing};
|
||||
use imphnen_iam::get_iso_date;
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{Uuid, sql::Thing};
|
||||
|
||||
use crate::v1::gacha_claims::gacha_claims_dto::GachaClaimRequestDto;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct GachaClaimSchema {
|
||||
pub id: Thing,
|
||||
pub user: Thing,
|
||||
pub item: Thing,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for GachaClaimSchema {
|
||||
fn default() -> Self {
|
||||
GachaClaimSchema {
|
||||
id: make_thing(
|
||||
&ResourceEnum::GachaClaims.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user: make_thing(
|
||||
&ResourceEnum::Users.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
item: make_thing(
|
||||
&ResourceEnum::GachaItems.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GachaClaimSchema {
|
||||
pub fn from(dto: GachaClaimRequestDto) -> Self {
|
||||
Self {
|
||||
id: make_thing(
|
||||
&ResourceEnum::GachaClaims.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user: make_thing(&ResourceEnum::Users.to_string(), &dto.user_id),
|
||||
item: make_thing(&ResourceEnum::GachaItems.to_string(), &dto.item_id),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn roll(roll: GachaRollQueryDto, user_id: Thing) -> Self {
|
||||
Self {
|
||||
id: make_thing(
|
||||
&ResourceEnum::GachaClaims.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user: user_id,
|
||||
// roll.item is optional at the DTO level; assume caller ensured a valid item exists
|
||||
item: roll
|
||||
.item
|
||||
.as_ref()
|
||||
.map(|i| i.id.clone())
|
||||
.unwrap_or_else(|| make_thing(&ResourceEnum::GachaItems.to_string(), &Uuid::new_v4().to_string())),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use crate::AppState;
|
||||
use imphnen_entities::ResponseSuccessDto;
|
||||
use imphnen_utils::{common_response, success_response, validate_request};
|
||||
use crate::v1::gacha_claims::gacha_claims_dto::{GachaClaimItemDto, GachaClaimRequestDto};
|
||||
use crate::v1::gacha_claims::gacha_claims_repository::GachaClaimRepository;
|
||||
use crate::v1::gacha_claims::gacha_claims_schema::GachaClaimSchema;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Response;
|
||||
|
||||
pub struct GachaClaimService;
|
||||
|
||||
impl GachaClaimService {
|
||||
pub async fn get_gacha_claim_by_id(state: &AppState, id: String) -> Response {
|
||||
let repo = GachaClaimRepository::new(state);
|
||||
match repo.query_gacha_claim_by_id(id).await {
|
||||
Ok(claim) => success_response(ResponseSuccessDto {
|
||||
data: GachaClaimItemDto::from(&claim),
|
||||
}),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_gacha_claim(
|
||||
state: &AppState,
|
||||
payload: GachaClaimRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = GachaClaimRepository::new(state);
|
||||
let schema = GachaClaimSchema::from(payload);
|
||||
match repo.query_create_gacha_claim(schema).await {
|
||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{get, post},
|
||||
};
|
||||
|
||||
pub mod gacha_claims_controller;
|
||||
pub mod gacha_claims_dto;
|
||||
pub mod gacha_claims_repository;
|
||||
pub mod gacha_claims_schema;
|
||||
pub mod gacha_claims_service;
|
||||
|
||||
// Export only public API functions
|
||||
pub use gacha_claims_controller::{post_create_gacha_claim, get_detail_gacha_claim};
|
||||
pub use gacha_claims_dto::{GachaClaimItemDto, GachaClaimRequestDto};
|
||||
pub use gacha_claims_service::GachaClaimService;
|
||||
|
||||
/// Creates router for gacha claims endpoints
|
||||
pub fn gacha_claim_router() -> Router {
|
||||
Router::new()
|
||||
.route("/create", post(post_create_gacha_claim))
|
||||
.route("/detail/{id}", get(get_detail_gacha_claim))
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use axum::{
|
||||
extract::Json,
|
||||
http::HeaderMap,
|
||||
response::Response,
|
||||
Extension,
|
||||
};
|
||||
use crate::AppState;
|
||||
use crate::v1::gacha_credits::gacha_credits_dto::GachaCreditRequestDto;
|
||||
use crate::v1::gacha_credits::gacha_credits_service::GachaCreditService;
|
||||
|
||||
pub struct GachaCreditController;
|
||||
|
||||
impl GachaCreditController {
|
||||
pub async fn get_user_credits(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
) -> Response {
|
||||
GachaCreditService::get_user_credits(&headers, &state).await
|
||||
}
|
||||
|
||||
pub async fn add_user_credits(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<GachaCreditRequestDto>,
|
||||
) -> Response {
|
||||
GachaCreditService::add_user_credits(&headers, &state, payload).await
|
||||
}
|
||||
|
||||
pub async fn consume_user_credit(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
) -> Response {
|
||||
GachaCreditService::consume_user_credit(&headers, &state).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct GachaCreditRequestDto {
|
||||
#[validate(length(min = 1, message = "User ID must not be empty"))]
|
||||
pub user_id: String,
|
||||
|
||||
#[validate(range(
|
||||
min = 1,
|
||||
message = "Amount must be at least 1 credit"
|
||||
))]
|
||||
pub amount: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GachaCreditResponseDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub available_rolls: i32,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl From<&crate::v1::gacha_credits::gacha_credits_schema::GachaCreditSchema> for GachaCreditResponseDto {
|
||||
fn from(credit: &crate::v1::gacha_credits::gacha_credits_schema::GachaCreditSchema) -> Self {
|
||||
Self {
|
||||
id: credit.id.id.to_raw(),
|
||||
user_id: credit.user.id.to_raw(),
|
||||
available_rolls: credit.available_rolls,
|
||||
is_deleted: credit.is_deleted,
|
||||
created_at: credit.created_at.clone(),
|
||||
updated_at: credit.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
use crate::v1::gacha_credits::gacha_credits_dto::GachaCreditRequestDto;
|
||||
use crate::v1::gacha_credits::gacha_credits_schema::GachaCreditSchema;
|
||||
use crate::AppState;
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_iam::make_thing;
|
||||
use std::time::Instant;
|
||||
use surrealdb::Uuid;
|
||||
use tracing::{instrument, info};
|
||||
|
||||
pub struct GachaCreditRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> GachaCreditRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, user_id), err)]
|
||||
pub async fn query_by_user_id(
|
||||
&self,
|
||||
user_id: String,
|
||||
) -> Result<Option<GachaCreditSchema>> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let sql = format!(
|
||||
"SELECT * FROM {} WHERE user = type::thing('{}', $user_id) AND is_deleted = false LIMIT 1",
|
||||
ResourceEnum::GachaCredits,
|
||||
ResourceEnum::Users.as_str()
|
||||
);
|
||||
info!(query = %sql, "Executing SurrealDB query");
|
||||
let result: Vec<GachaCreditSchema> =
|
||||
db.query(sql).bind(("user_id", user_id)).await?.take(0)?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_by_user_id' took: {elapsed:.2?}");
|
||||
}
|
||||
Ok(result.into_iter().next())
|
||||
}
|
||||
|
||||
#[instrument(skip(self, user_id), err)]
|
||||
pub async fn query_consume_credit(&self, user_id: String) -> Result<()> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let credit_opt = self.query_by_user_id(user_id).await?;
|
||||
let Some(mut credit) = credit_opt else {
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!(
|
||||
"Query 'query_consume_credit' took: {elapsed:.2?} (no credit to consume)"
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
if credit.available_rolls <= 0 {
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!(
|
||||
"Query 'query_consume_credit' took: {elapsed:.2?} (no rolls remaining)"
|
||||
);
|
||||
}
|
||||
bail!("No extra roll credits remaining");
|
||||
}
|
||||
credit.available_rolls -= 1;
|
||||
info!(operation = "update", table = %ResourceEnum::GachaCredits.to_string(), id = %credit.id.id.to_raw(), "Executing SurrealDB update for consume_credit");
|
||||
let _: Option<GachaCreditSchema> = db
|
||||
.update((
|
||||
&ResourceEnum::GachaCredits.to_string(),
|
||||
credit.id.id.to_raw(),
|
||||
))
|
||||
.merge(credit)
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_consume_credit' took: {elapsed:.2?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument(skip(self, payload), err)]
|
||||
pub async fn query_add_credit(
|
||||
&self,
|
||||
payload: GachaCreditRequestDto,
|
||||
) -> Result<()> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
if let Some(mut credit) = self.query_by_user_id(payload.user_id.clone()).await? {
|
||||
credit.available_rolls += payload.amount;
|
||||
info!(operation = "update", table = %ResourceEnum::GachaCredits.to_string(), id = %credit.id.id.to_raw(), "Executing SurrealDB update for add_credit");
|
||||
let _: Option<GachaCreditSchema> = db
|
||||
.update((
|
||||
&ResourceEnum::GachaCredits.to_string(),
|
||||
credit.id.id.to_raw(),
|
||||
))
|
||||
.merge(credit)
|
||||
.await?;
|
||||
} else {
|
||||
let data = GachaCreditSchema {
|
||||
id: make_thing(
|
||||
&ResourceEnum::GachaCredits.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user: make_thing(&ResourceEnum::Users.to_string(), &payload.user_id),
|
||||
available_rolls: payload.amount,
|
||||
..Default::default()
|
||||
};
|
||||
info!(operation = "create", table = %ResourceEnum::GachaCredits.to_string(), "Executing SurrealDB create for add_credit");
|
||||
let _: Option<GachaCreditSchema> = db
|
||||
.create(ResourceEnum::GachaCredits.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
}
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_add_credit' took: {elapsed:.2?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use axum::{Router, routing::get};
|
||||
use axum::routing::post;
|
||||
|
||||
pub fn gacha_credit_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(crate::v1::gacha_credits::GachaCreditController::get_user_credits))
|
||||
.route("/add", post(crate::v1::gacha_credits::GachaCreditController::add_user_credits))
|
||||
.route("/consume", post(crate::v1::gacha_credits::GachaCreditController::consume_user_credit))
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
use imphnen_iam::get_iso_date;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GachaCreditSchema {
|
||||
pub id: Thing,
|
||||
pub user: Thing,
|
||||
pub available_rolls: i32,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for GachaCreditSchema {
|
||||
fn default() -> Self {
|
||||
GachaCreditSchema {
|
||||
id: Thing::from(("app_gacha_credits", "uuid")),
|
||||
user: Thing::from(("app_users", "uuid")),
|
||||
available_rolls: 0,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GachaCreditSchema {
|
||||
pub fn from(&self) -> Self {
|
||||
Self {
|
||||
id: self.id.clone(),
|
||||
user: self.user.clone(),
|
||||
available_rolls: self.available_rolls,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use crate::AppState;
|
||||
use imphnen_entities::ResponseSuccessDto;
|
||||
use imphnen_utils::{errors::AppError, error_response};
|
||||
use imphnen_utils::{common_response, success_response, validate_request};
|
||||
use crate::v1::gacha_credits::gacha_credits_dto::{GachaCreditRequestDto, GachaCreditResponseDto};
|
||||
use crate::v1::gacha_credits::gacha_credits_repository::GachaCreditRepository;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Response;
|
||||
use imphnen_iam::UsersRepository;
|
||||
use imphnen_utils::extract_email;
|
||||
|
||||
pub struct GachaCreditService;
|
||||
|
||||
impl GachaCreditService {
|
||||
pub async fn get_user_credits(headers: &axum::http::HeaderMap, state: &AppState) -> Response {
|
||||
let repo = GachaCreditRepository::new(state);
|
||||
let repo_user = UsersRepository::new(state);
|
||||
let Some(email) = extract_email(headers) else {
|
||||
return error_response(AppError::AuthenticationError("Unauthorized".into()));
|
||||
};
|
||||
|
||||
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
|
||||
return error_response(AppError::NotFoundError("User not found".into()));
|
||||
};
|
||||
|
||||
match repo.query_by_user_id(user.id.id.to_raw()).await {
|
||||
Ok(Some(credit)) => {
|
||||
let response_dto = GachaCreditResponseDto::from(&credit);
|
||||
success_response(ResponseSuccessDto { data: response_dto })
|
||||
}
|
||||
Ok(None) => {
|
||||
// Return empty credits if no record exists
|
||||
let response_dto = GachaCreditResponseDto {
|
||||
id: "".to_string(),
|
||||
user_id: user.id.id.to_raw(),
|
||||
available_rolls: 0,
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
};
|
||||
success_response(ResponseSuccessDto { data: response_dto })
|
||||
}
|
||||
Err(e) => error_response(AppError::InternalServerError(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn add_user_credits(
|
||||
headers: &axum::http::HeaderMap,
|
||||
state: &AppState,
|
||||
payload: GachaCreditRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
|
||||
let repo = GachaCreditRepository::new(state);
|
||||
let repo_user = UsersRepository::new(state);
|
||||
let Some(email) = extract_email(headers) else {
|
||||
return error_response(AppError::AuthenticationError("Unauthorized".into()));
|
||||
};
|
||||
|
||||
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
|
||||
return error_response(AppError::NotFoundError("User not found".into()));
|
||||
};
|
||||
|
||||
// Ensure the user can only modify their own credits
|
||||
if payload.user_id != user.id.id.to_raw() {
|
||||
return error_response(AppError::AuthorizationError("You can only modify your own credits".into()));
|
||||
}
|
||||
|
||||
let amount = payload.amount; // Extract amount before moving payload
|
||||
match repo.query_add_credit(payload).await {
|
||||
Ok(_) => common_response(
|
||||
StatusCode::OK,
|
||||
&format!("Added {} credits successfully", amount)
|
||||
),
|
||||
Err(e) => error_response(AppError::InternalServerError(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn consume_user_credit(headers: &axum::http::HeaderMap, state: &AppState) -> Response {
|
||||
let repo = GachaCreditRepository::new(state);
|
||||
let repo_user = UsersRepository::new(state);
|
||||
let Some(email) = extract_email(headers) else {
|
||||
return error_response(AppError::AuthenticationError("Unauthorized".into()));
|
||||
};
|
||||
|
||||
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
|
||||
return error_response(AppError::NotFoundError("User not found".into()));
|
||||
};
|
||||
|
||||
match repo.query_consume_credit(user.id.id.to_raw()).await {
|
||||
Ok(_) => common_response(StatusCode::OK, "Consumed 1 credit successfully"),
|
||||
Err(e) => error_response(AppError::BadRequestError(e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
pub mod gacha_credits_controller;
|
||||
pub mod gacha_credits_dto;
|
||||
pub mod gacha_credits_repository;
|
||||
pub mod gacha_credits_schema;
|
||||
pub mod gacha_credits_service;
|
||||
pub mod gacha_credits_router;
|
||||
|
||||
// Export only public types and functions
|
||||
pub use gacha_credits_controller::GachaCreditController;
|
||||
pub use gacha_credits_dto::{GachaCreditRequestDto, GachaCreditResponseDto};
|
||||
pub use gacha_credits_repository::GachaCreditRepository;
|
||||
pub use gacha_credits_service::GachaCreditService;
|
||||
pub use gacha_credits_router::gacha_credit_router;
|
||||
@@ -1,30 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct GachaItemRequestDto {
|
||||
#[validate(length(min = 1, message = "Item name must not be empty"))]
|
||||
pub name: String,
|
||||
#[validate(length(min = 1, message = "Image URL must not be empty"))]
|
||||
pub image_url: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GachaItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct GachaItemDtoRaw {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user