Compare commits
217
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b429b3a9c7 | ||
|
|
6fe495eed1 | ||
|
|
97c2fce7be | ||
|
|
98c46611fb | ||
|
|
fbfe3dcd51 | ||
|
|
5cc5a3dfe1 | ||
|
|
95ae55c9df | ||
|
|
f7ca67d720 | ||
|
|
02421e9bc2 | ||
|
|
5e2b0d3caf | ||
|
|
b9a51ce6cc | ||
|
|
d4a6c4c9ea | ||
|
|
ece6499e2b | ||
|
|
1caaa8404b | ||
|
|
cb6eef2054 | ||
|
|
e77797d7bb | ||
|
|
d5ccf4cf75 | ||
|
|
1a36698962 | ||
|
|
15a2ee1950 | ||
|
|
bef8482402 | ||
|
|
768e583f81 | ||
|
|
1ca6d8f47c | ||
|
|
3fcfb3709e | ||
|
|
6915a97d79 | ||
|
|
6f596efadd | ||
|
|
b6b5f48055 | ||
|
|
789b20c278 | ||
|
|
884b679ba8 | ||
|
|
6ef624c169 | ||
|
|
c10443f881 | ||
|
|
466ba3391a | ||
|
|
8c2527d61e | ||
|
|
018124f7b3 | ||
|
|
7749f6fdec | ||
|
|
b27e4a4404 | ||
|
|
3dde67a4ac | ||
|
|
49abcf28c3 | ||
|
|
9cecc8fa05 | ||
|
|
a32f54873b | ||
|
|
af41a98111 | ||
|
|
4c435708c0 | ||
|
|
ac462ea771 | ||
|
|
3e52223730 | ||
|
|
01e479350b | ||
|
|
b0cf9817d7 | ||
|
|
e530eba60d | ||
|
|
ef1d63e893 | ||
|
|
5859af5294 | ||
|
|
c12da948aa | ||
|
|
3cde18360c | ||
|
|
14b22328de | ||
|
|
96debc210a | ||
|
|
b80662188f | ||
|
|
7b9ce6cda1 | ||
|
|
1bb2d6a419 | ||
|
|
14690a378f | ||
|
|
17cc4ccdba | ||
|
|
1b7368a4b7 | ||
|
|
ff2e14d5f9 | ||
|
|
012aff60ef | ||
|
|
f3d88e2ac9 | ||
|
|
0e48b6755f | ||
|
|
7056f8c8a6 | ||
|
|
4ecdcd12d2 | ||
|
|
dd4a73e360 | ||
|
|
49e0a89ad1 | ||
|
|
82b85abe8f | ||
|
|
df11aa5eb8 | ||
|
|
ac44867ec1 | ||
|
|
7205afe43b | ||
|
|
b1c678c72b | ||
|
|
fa3687c6be | ||
|
|
ba46a19a5a | ||
|
|
8cdbca24ba | ||
|
|
8f981572cd | ||
|
|
39b75f410f | ||
|
|
6da1b2a7e7 | ||
|
|
acccae9f7c | ||
|
|
e7c17784cc | ||
|
|
042e0b4eff | ||
|
|
0b51a56dee | ||
|
|
cb98440b65 | ||
|
|
3c19d262f3 | ||
|
|
bdffe85544 | ||
|
|
9ed619e3fd | ||
|
|
00fd7e1907 | ||
|
|
b70126734e | ||
|
|
6af9461079 | ||
|
|
57b3662951 | ||
|
|
c0c08f2821 | ||
|
|
8402415649 | ||
|
|
01e20baa45 | ||
|
|
10dc869eaf | ||
|
|
199d0c885e | ||
|
|
89ef48a57e | ||
|
|
da1826ebba | ||
|
|
874986f1d6 | ||
|
|
bbff555a06 | ||
|
|
d3eb687a58 | ||
|
|
c5516d4006 | ||
|
|
5f51dd281d | ||
|
|
f6232832af | ||
|
|
277cf0770d | ||
|
|
650728a385 | ||
|
|
3cc3e2a7d8 | ||
|
|
39fc2f86ad | ||
|
|
7bd0ef2274 | ||
|
|
b40a430c49 | ||
|
|
44b1e09551 | ||
|
|
1b9251b2dd | ||
|
|
34b6cdabfb | ||
|
|
a25e896fa2 | ||
|
|
adf3ef8e28 | ||
|
|
ad46687f07 | ||
|
|
0ba04abee9 | ||
|
|
1e25a5b496 | ||
|
|
d7178c792d | ||
|
|
d2754de9ef | ||
|
|
cda950ed7e | ||
|
|
c6a95c1231 | ||
|
|
86116b8157 | ||
|
|
ac06224ed1 | ||
|
|
83e765f358 | ||
|
|
558e0ce568 | ||
|
|
148cf3a5cd | ||
|
|
ee9d23e01b | ||
|
|
1a2e0c58b6 | ||
|
|
e66f1f1634 | ||
|
|
6f45cf80c8 | ||
|
|
02be09506a | ||
|
|
b88ecd1361 | ||
|
|
fa435994f2 | ||
|
|
16c613d699 | ||
|
|
f598dedb3b | ||
|
|
cfa251337f | ||
|
|
cca9aa6318 | ||
|
|
f1e4e02697 | ||
|
|
a3c2715a85 | ||
|
|
89cc631fb0 | ||
|
|
36c12110c2 | ||
|
|
070060365a | ||
|
|
68e816f956 | ||
|
|
48db5f07ef | ||
|
|
a4b5d91906 | ||
|
|
9878279660 | ||
|
|
465cbee2c3 | ||
|
|
33a2ae86c6 | ||
|
|
d906fc4747 | ||
|
|
055ef6ac8e | ||
|
|
e63658c082 | ||
|
|
f4b0ed0a4a | ||
|
|
1e5ed26f76 | ||
|
|
d97095a38d | ||
|
|
e48507901e | ||
|
|
a43ef8ec04 | ||
|
|
874f25aa80 | ||
|
|
12a730a394 | ||
|
|
bdcd41f54d | ||
|
|
96fb8eb7d3 | ||
|
|
d2c333dbd6 | ||
|
|
054f0f63ff | ||
|
|
eb05ea5994 | ||
|
|
4f870ec4c9 | ||
|
|
31f9b6cfea | ||
|
|
07a93ff0b7 | ||
|
|
d2b098ed92 | ||
|
|
09a7f4371a | ||
|
|
b4bf78f0d6 | ||
|
|
de9c5a6dc1 | ||
|
|
8a661df059 | ||
|
|
c7c16d4197 | ||
|
|
3aec0346a9 | ||
|
|
8d2f720de1 | ||
|
|
4b8da68df4 | ||
|
|
6460979bab | ||
|
|
3ae9dbd717 | ||
|
|
0816566d03 | ||
|
|
a97044edfc | ||
|
|
9d92a9a136 | ||
|
|
8e12c79ea6 | ||
|
|
5777268441 | ||
|
|
34eaa418d5 | ||
|
|
77f12610dd | ||
|
|
5be737ad70 | ||
|
|
0ae1e26ba8 | ||
|
|
79721b7af6 | ||
|
|
093e290221 | ||
|
|
1e6957720e | ||
|
|
a0f263bb4f | ||
|
|
413a28c089 | ||
|
|
a90e8662e1 | ||
|
|
955d384f96 | ||
|
|
ea5ece9ab2 | ||
|
|
8ff532bb67 | ||
|
|
eb6cfd51ae | ||
|
|
11d6249007 | ||
|
|
497c250e6d | ||
|
|
2872c1827a | ||
|
|
f9c49d44b5 | ||
|
|
12043f027c | ||
|
|
0c28d34d57 | ||
|
|
271b00c2c4 | ||
|
|
b096f4129a | ||
|
|
7ab036f5f7 | ||
|
|
9ffe808797 | ||
|
|
acfb8259bc | ||
|
|
298144bd36 | ||
|
|
ff9d8cba69 | ||
|
|
8b2769706e | ||
|
|
b8606ef0bb | ||
|
|
44de53a49d | ||
|
|
9abab01b9c | ||
|
|
53414687ff | ||
|
|
d2ec21c7b1 | ||
|
|
4deee3a9cb | ||
|
|
b50ce2b060 | ||
|
|
ffc72367d5 |
@@ -0,0 +1,2 @@
|
|||||||
|
[target.x86_64-pc-windows-msvc]
|
||||||
|
linker = "rust-lld.exe"
|
||||||
+59
-4
@@ -1,4 +1,59 @@
|
|||||||
PORT=
|
# RUST_ENV : Mode environment aplikasi (misal: development, production)
|
||||||
DATABASE_URL=
|
# RUST_LOG : Level logging aplikasi Rust (misal: debug, info, warn, error)
|
||||||
ACCESS_TOKEN_SECRET=
|
# PORT : Port yang digunakan backend service
|
||||||
REFRESH_TOKEN_SECRET=
|
# SURREALDB_URL : URL koneksi ke SurrealDB (gunakan ws:// untuk WebSocket)
|
||||||
|
# SURREALDB_USERNAME : Username untuk SurrealDB
|
||||||
|
# SURREALDB_PASSWORD : Password untuk SurrealDB
|
||||||
|
# SURREALDB_NAMESPACE : Namespace SurrealDB yang digunakan
|
||||||
|
# SURREALDB_DBNAME : Nama database SurrealDB
|
||||||
|
# ACCESS_TOKEN_SECRET : Secret key untuk JWT access token (ganti dengan nilai rahasia)
|
||||||
|
# REFRESH_TOKEN_SECRET : Secret key untuk JWT refresh token (ganti dengan nilai rahasia)
|
||||||
|
# SMTP_EMAIL : Email yang digunakan untuk mengirim email (SMTP)
|
||||||
|
# SMTP_PASSWORD : Password email SMTP
|
||||||
|
# SMTP_NAME : Nama pengirim email (misal: nama aplikasi)
|
||||||
|
# SMTP_HOST : Host SMTP server (misal: smtp.gmail.com)
|
||||||
|
# REDISDB_URL : URL/host Redis database
|
||||||
|
# FE_URL : URL frontend aplikasi (misal: http://localhost)
|
||||||
|
# MINIO_ENDPOINT : Endpoint MinIO object storage
|
||||||
|
# MINIO_BUCKET_NAME : Nama bucket default MinIO
|
||||||
|
# MINIO_ACCESS_KEY : Access key MinIO atau MINIO_ROOT_USER
|
||||||
|
# MINIO_SECRET_KEY : Secret key MinIO atau MINIO_ROOT_PASSWORD
|
||||||
|
# MINIO_ROOT_USER : Username root MinIO (default: minioadmin)
|
||||||
|
# MINIO_ROOT_PASSWORD : Password root MinIO (default: minioadmin)
|
||||||
|
# GOOGLE_CLIENT_ID : Client ID OAuth Google (untuk login Google)
|
||||||
|
# GOOGLE_CLIENT_SECRET : Client Secret OAuth Google
|
||||||
|
|
||||||
|
RUST_ENV=development
|
||||||
|
RUST_LOG=debug
|
||||||
|
PORT=4099
|
||||||
|
SURREALDB_URL=ws://localhost:8000/rpc
|
||||||
|
SURREALDB_USERNAME=root
|
||||||
|
SURREALDB_PASSWORD=root
|
||||||
|
SURREALDB_NAMESPACE=test
|
||||||
|
SURREALDB_DBNAME=test
|
||||||
|
ACCESS_TOKEN_SECRET=your-access-token-secret-key-here
|
||||||
|
REFRESH_TOKEN_SECRET=your-refresh-token-secret-key-here
|
||||||
|
SMTP_EMAIL=your-email@example.com
|
||||||
|
SMTP_PASSWORD=your-smtp-password
|
||||||
|
SMTP_NAME="Your App Name"
|
||||||
|
SMTP_HOST=smtp.gmail.com
|
||||||
|
REDISDB_URL=localhost
|
||||||
|
FE_URL=http://localhost
|
||||||
|
MINIO_ENDPOINT=http://localhost:9000
|
||||||
|
MINIO_BUCKET_NAME=default_bucket
|
||||||
|
MINIO_ACCESS_KEY=minioadmin
|
||||||
|
MINIO_SECRET_KEY=minioadmin
|
||||||
|
MINIO_SECURE=false
|
||||||
|
|
||||||
|
GOOGLE_CLIENT_ID="your_google_client_id"
|
||||||
|
GOOGLE_CLIENT_SECRET="your_google_client_secret"
|
||||||
|
POOL_SIZE=10
|
||||||
|
CONNECT_TIMEOUT=30
|
||||||
|
IDLE_TIMEOUT=60
|
||||||
|
MAX_LIFETIME=1800
|
||||||
|
STATEMENT_TIMEOUT=30000
|
||||||
|
IDLE_IN_TRANSACTION_SESSION_TIMEOUT=60000
|
||||||
|
SSLMODE=require
|
||||||
|
RETRY_ATTEMPTS=3
|
||||||
|
RETRY_DELAY=1
|
||||||
|
GOOGLE_REDIRECT_URL=http://localhost:8000/api/v1/auth/google/callback
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
name: Deploy to Ancikri
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- develop
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Set up Rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Build the project
|
||||||
|
run: cargo build --release
|
||||||
|
|
||||||
|
- name: Stop service on VPS before upload
|
||||||
|
uses: appleboy/ssh-action@v0.1.7
|
||||||
|
with:
|
||||||
|
host: ${{ secrets.VPS_ANCIKRI_IP }}
|
||||||
|
username: ${{ secrets.VPS_ANCIKRI_USER }}
|
||||||
|
key: ${{ secrets.VPS_ANCIKRI_SSH_KEY }}
|
||||||
|
port: ${{ secrets.VPS_ANCIKRI_PORT }}
|
||||||
|
script: |
|
||||||
|
set -e
|
||||||
|
echo "Stopping the service before uploading the binary"
|
||||||
|
sudo systemctl stop imphnen-backend-service
|
||||||
|
|
||||||
|
- name: Upload artifact to VPS
|
||||||
|
uses: appleboy/scp-action@v0.1.7
|
||||||
|
with:
|
||||||
|
host: ${{ secrets.VPS_ANCIKRI_IP }}
|
||||||
|
username: ${{ secrets.VPS_ANCIKRI_USER }}
|
||||||
|
key: ${{ secrets.VPS_ANCIKRI_SSH_KEY }}
|
||||||
|
port: ${{ secrets.VPS_ANCIKRI_PORT }}
|
||||||
|
source: ./target/release/*
|
||||||
|
target: /opt/imphnen-backend-service/imphnen-backend-service
|
||||||
|
rm: true
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
|
- name: Deploy to server
|
||||||
|
uses: appleboy/ssh-action@v0.1.7
|
||||||
|
with:
|
||||||
|
host: ${{ secrets.VPS_ANCIKRI_IP }}
|
||||||
|
username: ${{ secrets.VPS_ANCIKRI_USER }}
|
||||||
|
key: ${{ secrets.VPS_ANCIKRI_SSH_KEY }}
|
||||||
|
port: ${{ secrets.VPS_ANCIKRI_PORT }}
|
||||||
|
script: |
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "Restarting the service"
|
||||||
|
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
|
||||||
|
sudo systemctl restart imphnen-backend-service
|
||||||
|
|
||||||
|
echo "Deployment completed successfully"
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
name: Rust
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ["develop"]
|
||||||
|
pull_request:
|
||||||
|
branches: ["develop"]
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_TERM_COLOR: always
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Build
|
||||||
|
run: cargo build --verbose
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
# Nix
|
# Nix
|
||||||
/.direnv
|
/.direnv
|
||||||
|
/Cargo.nix
|
||||||
|
|
||||||
# Environment
|
# Environment
|
||||||
.envrc
|
.envrc
|
||||||
@@ -12,3 +13,4 @@
|
|||||||
.env.development
|
.env.development
|
||||||
.env.staging
|
.env.staging
|
||||||
.env.production
|
.env.production
|
||||||
|
**/**.log
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
/cache
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
||||||
|
# * For C, use cpp
|
||||||
|
# * For JavaScript, use typescript
|
||||||
|
# Special requirements:
|
||||||
|
# * csharp: Requires the presence of a .sln file in the project folder.
|
||||||
|
language: rust
|
||||||
|
|
||||||
|
# the encoding used by text files in the project
|
||||||
|
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
|
||||||
|
encoding: "utf-8"
|
||||||
|
|
||||||
|
# whether to use the project's gitignore file to ignore files
|
||||||
|
# Added on 2025-04-07
|
||||||
|
ignore_all_files_in_gitignore: true
|
||||||
|
# list of additional paths to ignore
|
||||||
|
# same syntax as gitignore, so you can use * and **
|
||||||
|
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
||||||
|
# Added (renamed) on 2025-04-07
|
||||||
|
ignored_paths: []
|
||||||
|
|
||||||
|
# whether the project is in read-only mode
|
||||||
|
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||||
|
# Added on 2025-04-18
|
||||||
|
read_only: false
|
||||||
|
|
||||||
|
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
||||||
|
# Below is the complete list of tools for convenience.
|
||||||
|
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||||
|
# execute `uv run scripts/print_tool_overview.py`.
|
||||||
|
#
|
||||||
|
# * `activate_project`: Activates a project by name.
|
||||||
|
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||||
|
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||||
|
# * `delete_lines`: Deletes a range of lines within a file.
|
||||||
|
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
||||||
|
# * `execute_shell_command`: Executes a shell command.
|
||||||
|
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
||||||
|
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
||||||
|
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
||||||
|
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||||
|
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||||
|
# * `initial_instructions`: Gets the initial instructions for the current project.
|
||||||
|
# Should only be used in settings where the system prompt cannot be set,
|
||||||
|
# e.g. in clients you have no control over, like Claude Desktop.
|
||||||
|
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||||
|
# * `insert_at_line`: Inserts content at a given line in a file.
|
||||||
|
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||||
|
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||||
|
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
||||||
|
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||||
|
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
||||||
|
# * `read_file`: Reads a file within the project directory.
|
||||||
|
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
||||||
|
# * `remove_project`: Removes a project from the Serena configuration.
|
||||||
|
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
||||||
|
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
||||||
|
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
||||||
|
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||||
|
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
||||||
|
# * `switch_modes`: Activates modes by providing a list of their names
|
||||||
|
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
||||||
|
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
||||||
|
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
||||||
|
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
||||||
|
excluded_tools: []
|
||||||
|
|
||||||
|
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||||
|
# (contrary to the memories, which are loaded on demand).
|
||||||
|
initial_prompt: ""
|
||||||
|
|
||||||
|
project_name: "imphnen-backend-service"
|
||||||
Generated
+2171
-587
File diff suppressed because it is too large
Load Diff
+83
-15
@@ -1,24 +1,92 @@
|
|||||||
[package]
|
[workspace]
|
||||||
name = "imphnen-cms-be"
|
resolver = "2"
|
||||||
version = "0.1.0"
|
members = [
|
||||||
edition = "2021"
|
"tests",
|
||||||
|
"imphnen-entities", # Most basic - core data structures
|
||||||
|
"imphnen-macros", # Macros
|
||||||
|
"imphnen-libs", # Depends on entities
|
||||||
|
"imphnen-utils", # Depends on libs and entities
|
||||||
|
"imphnen-middleware",# Utility for permissions
|
||||||
|
"imphnen-iam", # Core auth service, depends on libs, utils, entities
|
||||||
|
"imphnen-cms", # Content management, depends on core services
|
||||||
|
"imphnen-gacha", # Game mechanics, depends on core services
|
||||||
|
"imphnen-dimentorin",# Learning platform, depends on core services
|
||||||
|
"imphnen-gateway", # API gateway, depends on all services
|
||||||
|
"imphnen-backend", # Main application, depends on all services
|
||||||
|
]
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
axum = { version = "0.8.1", features = ["multipart"] }
|
[workspace.dependencies]
|
||||||
log = "0.4.25"
|
async-trait = "0.1.83"
|
||||||
sea-orm = { version = "1.1.4", features = ["sqlx-postgres", "macros", "with-json", "with-uuid", "runtime-tokio", "runtime-tokio-native-tls"] }
|
oauth2 = "5.0.0"
|
||||||
serde = { version = "1.0.217", features = ["derive"] }
|
reqwest = { version = "0.12.23", features = ["json"] }
|
||||||
serde_json = "1.0.138"
|
serde_json = "1.0.142"
|
||||||
tokio = { version = "1.43.0", features = ["full"] }
|
axum = { version = "0.8.4", features = ["multipart", "macros"] }
|
||||||
|
log = "0.4.27"
|
||||||
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
|
tokio = { version = "1.47.1", features = ["full"] }
|
||||||
argon2 = { version = "0.5.3", features = ["password-hash"] }
|
argon2 = { version = "0.5.3", features = ["password-hash"] }
|
||||||
jsonwebtoken = "9.3.1"
|
jsonwebtoken = "9.3.1"
|
||||||
chrono = "0.4.39"
|
chrono = "0.4.41"
|
||||||
utoipa = { version = "5.3.1", features = ["axum_extras"] }
|
utoipa = { version = "5.4.0", features = ["axum_extras"] }
|
||||||
utoipa-swagger-ui = { version = "9.0.0", features = ["axum"] }
|
utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] }
|
||||||
redis = "0.28.2"
|
lettre = { version = "0.11.18", features = ["tokio1-native-tls"] }
|
||||||
|
thiserror = "2.0.14"
|
||||||
|
anyhow = "1.0.99"
|
||||||
|
rand = { version = "0.9.2", features = ["std", "alloc"] }
|
||||||
|
rand_distr = "0.5.1"
|
||||||
|
tower-http = { version = "0.6.6", features = ["cors", "trace"] }
|
||||||
|
http-body-util = "0.1.3"
|
||||||
|
validator = { version = "0.20.0", features = ["derive"] }
|
||||||
|
lazy_static = "1.5.0"
|
||||||
|
regex = "1.11.1"
|
||||||
|
axum-test = "17.3.0"
|
||||||
|
axum-extra = { version = "0.10.1", features = ["typed-header"] }
|
||||||
|
fancy-regex = "0.16.1"
|
||||||
|
futures = "0.3.31"
|
||||||
|
tower = "0.5.2"
|
||||||
|
env_logger = "0.11.8"
|
||||||
|
tracing = "0.1.41"
|
||||||
|
uuid = { version = "1.18.0", features = ["v4", "fast-rng", "serde"] }
|
||||||
|
strum = { version = "0.27.2", features = ["derive"] }
|
||||||
|
strum_macros = "0.27.2"
|
||||||
|
base64 = "0.22.1"
|
||||||
|
sha2 = "0.10.9"
|
||||||
|
hmac = "0.12"
|
||||||
|
hex = "0.4"
|
||||||
|
urlencoding = "2.1"
|
||||||
|
hyper = "1.6.0"
|
||||||
|
hyper-util = "0.1.16"
|
||||||
|
minio = "0.3.0"
|
||||||
|
sea-orm = { version = "1.1", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros", "with-chrono", "uuid"] }
|
||||||
|
num_cpus = "1.16.0"
|
||||||
|
|
||||||
|
|
||||||
|
tokio-test = "0.4.4"
|
||||||
|
mockall = "0.13.1"
|
||||||
|
once_cell = "1.21.3"
|
||||||
|
dotenvy = "0.15.7"
|
||||||
|
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
|
||||||
|
tokio-tungstenite = "0.27"
|
||||||
|
url = "2.5"
|
||||||
|
futures-util = "0.3"
|
||||||
|
http = "1.3"
|
||||||
|
tests = { path = "./tests" }
|
||||||
|
imphnen-iam = { path = "./imphnen-iam" }
|
||||||
|
imphnen-cms = { path = "./imphnen-cms" }
|
||||||
|
imphnen-libs = { path = "./imphnen-libs" }
|
||||||
|
imphnen-utils = { path = "./imphnen-utils" }
|
||||||
|
imphnen-gacha = { path = "./imphnen-gacha" }
|
||||||
|
imphnen-gateway = { path = "./imphnen-gateway" }
|
||||||
|
imphnen-backend = { path = "./imphnen-backend" }
|
||||||
|
imphnen-entities = { path = "./imphnen-entities" }
|
||||||
|
imphnen-dimentorin = { path = "./imphnen-dimentorin" }
|
||||||
|
imphnen-middleware = { path = "./imphnen-middleware" }
|
||||||
|
imphnen-macros = { path = "./imphnen-macros" }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
lto = "fat"
|
lto = "fat"
|
||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
panic = "abort"
|
panic = "abort"
|
||||||
opt-level = "z"
|
opt-level = "z"
|
||||||
|
|
||||||
|
|||||||
+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 \
|
RUN apk add --no-cache \
|
||||||
build-essential \
|
curl \
|
||||||
libssl-dev \
|
musl-dev \
|
||||||
pkg-config \
|
openssl-dev \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
openssl-libs-static \
|
||||||
|
pkgconfig
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY Cargo.toml Cargo.lock ./
|
COPY Cargo.toml Cargo.lock ./
|
||||||
COPY ./src ./src
|
|
||||||
|
|
||||||
RUN cargo build --release && strip /app/target/release/imphnen-cms-api
|
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-cms-api .
|
RUN echo -e '[package]\nname = "tests"\nversion = "0.1.0"\nedition = "2021"' > tests/Cargo.toml
|
||||||
|
|
||||||
CMD ["/app/imphnen-cms-api"]
|
|
||||||
|
COPY imphnen-backend ./imphnen-backend
|
||||||
|
COPY imphnen-cms ./imphnen-cms
|
||||||
|
COPY imphnen-dimentorin ./imphnen-dimentorin
|
||||||
|
COPY imphnen-entities ./imphnen-entities
|
||||||
|
COPY imphnen-gacha ./imphnen-gacha
|
||||||
|
COPY imphnen-gateway ./imphnen-gateway
|
||||||
|
COPY imphnen-iam ./imphnen-iam
|
||||||
|
COPY imphnen-libs ./imphnen-libs
|
||||||
|
COPY imphnen-middleware ./imphnen-middleware
|
||||||
|
COPY imphnen-utils ./imphnen-utils
|
||||||
|
COPY tests ./tests
|
||||||
|
|
||||||
|
RUN RUSTFLAGS="-C target-cpu=generic -C opt-level=s -C panic=abort -C codegen-units=1 -C strip=symbols" \
|
||||||
|
cargo build -p imphnen-backend --release && \
|
||||||
|
strip target/release/api && \
|
||||||
|
upx --best --lzma target/release/api 2>/dev/null || true
|
||||||
|
|
||||||
|
FROM scratch AS runner
|
||||||
|
COPY --from=builder /app/target/release/api /api
|
||||||
|
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||||
|
ENTRYPOINT ["/api"]
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
# IMPHNEN Backend Service
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="docs/logo.svg" alt="IMPHNEN">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
This repository serves as the **monorepo** for all backend services of IMPHNEN. It encompasses several main services:
|
||||||
|
|
||||||
|
1. **IMPHNEN-Backend** - Provides fundamental functionalities and shared resources for other services.
|
||||||
|
2. **IMPHNEN-IAM** - Handles identity and access management across IMPHNEN applications.
|
||||||
|
3. **IMPHNEN-CMS** - Supports the cms services by IMPHNEN [Landing Page website](https://imphnen.dev/).
|
||||||
|
4. **IMPHNEN-Gacha** - Supports the gacha services by IMPHNEN [Gacha website](https://gacha.imphnen.dev/).
|
||||||
|
5. **IMPHNEN-Dimentorin** - Supports the mentoring services by IMPHNEN [Dimentorin website](https://dimentorin.imphnen.dev/).
|
||||||
|
6. **IMPHNEN-Gateway** - Acts as the API gateway, routing requests to appropriate services.
|
||||||
|
7. **IMPHNEN-Middleware** - Acts as the middleware for the API Gateway, providing authentication and authorization.
|
||||||
|
|
||||||
|
## How to Install
|
||||||
|
|
||||||
|
1. **Clone the repository**:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone https://github.com/IMPHNEN/imphnen-backend-service.git
|
||||||
|
cd imphnen-backend-service
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Set up the environment**:
|
||||||
|
|
||||||
|
- Copy the example environment files:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
if you use windows based system
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./apply-env.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
if you use unix based system
|
||||||
|
|
||||||
|
```sh
|
||||||
|
source ./apply-env.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
- Modify the `.env` files with your specific configuration settings.
|
||||||
|
|
||||||
|
3. **Install dependencies**:
|
||||||
|
|
||||||
|
Ensure you have [Rust](https://www.rust-lang.org/) installed. Then, run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Run the seeders**:
|
||||||
|
|
||||||
|
to run the seeders, run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo run --bin seeder
|
||||||
|
```
|
||||||
|
|
||||||
|
## How to Run
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
To run the services in development mode:
|
||||||
|
|
||||||
|
1. **Start the database and other dependencies** using Docker Compose:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Run using cargo run**. For example, to run the Core Service:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo run --bin api
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Run using cargo watch**. For example, to run the Core Service:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo watch -x "run --bin api"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Production
|
||||||
|
|
||||||
|
For production deployment:
|
||||||
|
|
||||||
|
1. **Build the Docker image**:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker build -t imphnen-backend .
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Run the Docker container**:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker run --name imphnen-backend -d --env-file .env -p 3000:3000 imphnen-backend
|
||||||
|
```
|
||||||
|
|
||||||
|
Adjust the port and environment variables as needed.
|
||||||
|
|
||||||
|
## How to Run the Tests
|
||||||
|
|
||||||
|
1. **Run the tests**:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo test -p tests
|
||||||
|
```
|
||||||
|
|
||||||
|
## How to Contribute
|
||||||
|
|
||||||
|
1. **Fork the repository** and clone it locally.
|
||||||
|
2. **Create a new branch** for your feature or fix:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git checkout -b feat/your-feature-name
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Make your changes**, commit them, and push to your forked repository.
|
||||||
|
4. **Create a pull request** to the `develop` branch of this repository.
|
||||||
|
|
||||||
|
If you encounter any issues or have questions, feel free to create a new issue in the repository.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
_Note: For detailed API documentation, please refer to our [API Docs](https://api.imphnen.dev/docs)._
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
:: Cek apakah file .env ada
|
||||||
|
if not exist ".env" (
|
||||||
|
echo File .env tidak ditemukan di direktori saat ini.
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
echo Memuat variabel dari .env...
|
||||||
|
|
||||||
|
:: Baca file .env baris per baris
|
||||||
|
for /f "tokens=*" %%a in ('type ".env" ^| findstr /v "^$" ^| findstr /v "^#"') do (
|
||||||
|
echo.%%a | findstr "=" >nul && (
|
||||||
|
for /f "tokens=1,2 delims==" %%b in ("%%a") do (
|
||||||
|
set "key=%%b"
|
||||||
|
set "value=%%c"
|
||||||
|
:: Trim whitespace
|
||||||
|
call :trimValue key value
|
||||||
|
echo Set variabel: %%b=%%c
|
||||||
|
setx %%b %%c >nul
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Semua variabel telah dimuat.
|
||||||
|
endlocal
|
||||||
|
goto :eof
|
||||||
|
|
||||||
|
:: Fungsi trim (sederhana)
|
||||||
|
:trimValue
|
||||||
|
set "%1=%[%1]%"
|
||||||
|
set "%2=%[%2]%"
|
||||||
|
goto :eof
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
function Set-TempEnvFromDotEnv {
|
||||||
|
param (
|
||||||
|
[string]$envFilePath
|
||||||
|
)
|
||||||
|
|
||||||
|
if (-Not (Test-Path $envFilePath)) {
|
||||||
|
Write-Error "The .env file at path '$envFilePath' does not exist."
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
$envContent = Get-Content $envFilePath
|
||||||
|
|
||||||
|
foreach ($line in $envContent) {
|
||||||
|
$trimmedLine = $line.Trim()
|
||||||
|
|
||||||
|
if (-Not [string]::IsNullOrWhiteSpace($trimmedLine) -and -Not $trimmedLine.StartsWith("#")) {
|
||||||
|
$keyValue = $trimmedLine -split "=", 2
|
||||||
|
if ($keyValue.Length -eq 2) {
|
||||||
|
$key = $keyValue[0].Trim()
|
||||||
|
$value = $keyValue[1].Trim()
|
||||||
|
[System.Environment]::SetEnvironmentVariable($key, $value, [System.EnvironmentVariableTarget]::Process)
|
||||||
|
Write-Host "Set temporary environment variable: $key=$value"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "All environment variables from '$envFilePath' have been set temporarily."
|
||||||
|
}
|
||||||
|
|
||||||
|
Set-TempEnvFromDotEnv -envFilePath ".env"
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set_temp_env_from_dotenv() {
|
||||||
|
local env_file_path="$1"
|
||||||
|
|
||||||
|
if [[ ! -f "$env_file_path" ]]; then
|
||||||
|
echo "Error: The .env file at path '$env_file_path' does not exist."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
while IFS= read -r line || [[ -n "$line" ]]; do
|
||||||
|
trimmed_line=$(echo "$line" | xargs)
|
||||||
|
|
||||||
|
if [[ -n "$trimmed_line" && ! "$trimmed_line" =~ ^# ]]; then
|
||||||
|
key=$(echo "$trimmed_line" | cut -d '=' -f 1 | xargs)
|
||||||
|
value=$(echo "$trimmed_line" | cut -d '=' -f 2- | xargs)
|
||||||
|
export "$key=$value"
|
||||||
|
echo "Set temporary environment variable: $key=$value"
|
||||||
|
fi
|
||||||
|
done < "$env_file_path"
|
||||||
|
|
||||||
|
echo "All environment variables from '$env_file_path' have been set temporarily."
|
||||||
|
}
|
||||||
|
|
||||||
|
set_temp_env_from_dotenv ".env"
|
||||||
@@ -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"
|
||||||
@@ -6,3 +6,41 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "${PORT}:${PORT}"
|
- "${PORT}:${PORT}"
|
||||||
env_file: ".env"
|
env_file: ".env"
|
||||||
|
depends_on:
|
||||||
|
- postgres
|
||||||
|
|
||||||
|
postgres:
|
||||||
|
image: postgres:15-alpine
|
||||||
|
container_name: imphnen_postgres
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-imphnen}
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
||||||
|
ports:
|
||||||
|
- "${POSTGRES_PORT:-5432}:5432"
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-imphnen}"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 30s
|
||||||
|
|
||||||
|
minio:
|
||||||
|
image: minio/minio:latest
|
||||||
|
container_name: minio
|
||||||
|
ports:
|
||||||
|
- "9000:9000"
|
||||||
|
- "9001:9001"
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: minioadmin
|
||||||
|
MINIO_ROOT_PASSWORD: minioadmin
|
||||||
|
command: server /data --console-address ":9001"
|
||||||
|
volumes:
|
||||||
|
- minio_data:/data
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
minio_data:
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 351 KiB |
Generated
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1739020877,
|
||||||
|
"narHash": "sha256-mIvECo/NNdJJ/bXjNqIh8yeoSjVLAuDuTUzAo7dzs8Y=",
|
||||||
|
"owner": "nixos",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "a79cfe0ebd24952b580b1cf08cd906354996d547",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nixos",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -1,24 +1,32 @@
|
|||||||
{
|
{
|
||||||
description = "IMPHNEN CMS API Nix Flake";
|
description = "IMPHNEN Backend Service Nix Flake";
|
||||||
|
|
||||||
inputs = {
|
inputs = {
|
||||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||||
};
|
};
|
||||||
|
|
||||||
outputs = {
|
outputs = {
|
||||||
self,
|
self,
|
||||||
nixpkgs,
|
nixpkgs,
|
||||||
}: let
|
}: let
|
||||||
supportedSystems = ["x86_64-linux" "x86_64-darwin" "aarch64-darwin" "aarch64-linux"];
|
supportedSystems = ["x86_64-linux" "x86_64-darwin" "aarch64-darwin" "aarch64-linux"];
|
||||||
|
pkgsFor = system:
|
||||||
|
import nixpkgs {
|
||||||
|
inherit system;
|
||||||
|
config = {
|
||||||
|
allowUnfree = true;
|
||||||
|
};
|
||||||
|
};
|
||||||
forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
|
forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
|
||||||
pkgsFor = nixpkgs.legacyPackages;
|
|
||||||
in {
|
in {
|
||||||
packages = forAllSystems (system: {
|
packages = forAllSystems (system: {
|
||||||
default = pkgsFor.${system}.callPackage ./default.nix {};
|
default = (pkgsFor system).callPackage ./default.nix {};
|
||||||
});
|
});
|
||||||
devShells = forAllSystems (system: {
|
devShells = forAllSystems (system: {
|
||||||
default = pkgsFor.${system}.callPackage ./shell.nix {};
|
default = (pkgsFor system).callPackage ./shell.nix {};
|
||||||
});
|
});
|
||||||
dockerImages = forAllSystems (system: {
|
dockerImages = forAllSystems (system: {
|
||||||
tryOutApi = pkgsFor.${system}.callPackage ./docker.nix {};
|
tryOutApi = (pkgsFor system).callPackage ./docker.nix {};
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
[package]
|
||||||
|
name = "imphnen-backend"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "api"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "create_schema"
|
||||||
|
path = "src/bin/create_schema.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "seeder"
|
||||||
|
path = "src/bin/seeder.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "seed_events"
|
||||||
|
path = "src/bin/seed_events.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "seed_gacha_rolls"
|
||||||
|
path = "src/bin/seed_gacha_rolls.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "seed_mentor_user"
|
||||||
|
path = "src/bin/seed_mentor_user.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "seed_permissions"
|
||||||
|
path = "src/bin/seed_permissions.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "seed_roles"
|
||||||
|
path = "src/bin/seed_roles.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "seed_roles_permissions"
|
||||||
|
path = "src/bin/seed_roles_permissions.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "seed_test_data"
|
||||||
|
path = "src/bin/seed_test_data.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "test_postgres"
|
||||||
|
path = "src/bin/test_postgres.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
sea-orm.workspace = true
|
||||||
|
imphnen-libs.workspace = true
|
||||||
|
imphnen-utils.workspace = true
|
||||||
|
imphnen-gateway.workspace = true
|
||||||
|
imphnen-entities.workspace = true
|
||||||
|
imphnen-iam.workspace = true
|
||||||
|
imphnen-cms.workspace = true
|
||||||
|
imphnen-gacha.workspace = true
|
||||||
|
imphnen-dimentorin.workspace = true
|
||||||
|
axum.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
utoipa.workspace = true
|
||||||
|
lazy_static.workspace = true
|
||||||
|
regex.workspace = true
|
||||||
|
validator.workspace = true
|
||||||
|
axum-test.workspace = true
|
||||||
|
rand.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
chrono.workspace = true
|
||||||
|
anyhow.workspace = true
|
||||||
|
tower-http.workspace = true
|
||||||
|
utoipa-swagger-ui.workspace = true
|
||||||
|
env_logger.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
uuid.workspace=true
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// API entry point using PostgreSQL (SurrealDB migration complete)
|
||||||
|
// This file has been updated to use SeaORM with PostgreSQL instead of SurrealDB
|
||||||
|
use imphnen_gateway::gateway_service;
|
||||||
|
use imphnen_libs::axum_init;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
axum_init(|postgres_db| async {
|
||||||
|
// Gateway service now uses PostgreSQL exclusively (SeaORM)
|
||||||
|
// SurrealDB dependencies have been completely removed
|
||||||
|
gateway_service(postgres_db).await
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use sea_orm::{Statement, ConnectionTrait};
|
||||||
|
use std::error::Error;
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let args: Vec<String> = env::args().collect();
|
||||||
|
// New default behavior: execute by default; use --dry-run to preview only.
|
||||||
|
let dry_run = args.iter().any(|s| s == "--dry-run" || s == "--no-exec" || s == "--dry");
|
||||||
|
let force = args.iter().any(|s| s == "--force" || s == "-f");
|
||||||
|
|
||||||
|
println!("🔎 Clear DB script - WARNING: This will remove data from tables\n");
|
||||||
|
println!("Note: script now runs by default (no --yes required). To preview without executing, use --dry-run.\n");
|
||||||
|
|
||||||
|
// List of tables to truncate (order doesn't matter with CASCADE)
|
||||||
|
let tables = vec![
|
||||||
|
"gacha_claims",
|
||||||
|
"gacha_rolls",
|
||||||
|
"gacha_items",
|
||||||
|
"gacha_credits",
|
||||||
|
"audit_logs",
|
||||||
|
"rate_limits",
|
||||||
|
"testimonials",
|
||||||
|
"events",
|
||||||
|
"app_mentors",
|
||||||
|
"app_sessions",
|
||||||
|
"app_roles_permissions",
|
||||||
|
"app_permissions",
|
||||||
|
"app_roles",
|
||||||
|
"app_users",
|
||||||
|
];
|
||||||
|
|
||||||
|
let postgres_config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(postgres_config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
// Filter tables that actually exist in the database
|
||||||
|
let mut existing_tables: Vec<&str> = vec![];
|
||||||
|
for t in tables.iter() {
|
||||||
|
let check_sql = format!(
|
||||||
|
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '{}') as exists;",
|
||||||
|
t
|
||||||
|
);
|
||||||
|
let stmt = Statement::from_string(db.get_database_backend(), check_sql);
|
||||||
|
if let Ok(Some(row)) = pg_conn.query_one(stmt).await {
|
||||||
|
let exists_val: Option<bool> = row.try_get("", "exists").ok();
|
||||||
|
if exists_val.unwrap_or(false) {
|
||||||
|
existing_tables.push(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if existing_tables.is_empty() {
|
||||||
|
println!("No configured tables found to clear - nothing to do.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let truncate_sql = format!(
|
||||||
|
"TRUNCATE TABLE {} RESTART IDENTITY CASCADE;",
|
||||||
|
existing_tables.join(", ")
|
||||||
|
);
|
||||||
|
|
||||||
|
println!("The script will run the following SQL (on the DB configured by env vars):\n\n{}", truncate_sql);
|
||||||
|
|
||||||
|
// Prevent accidental execution in production without explicit force flag
|
||||||
|
let env_name = std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string());
|
||||||
|
if env_name == "production" && !force {
|
||||||
|
println!("Security: RUST_ENV=production; the script will NOT run without --force. Use --force to override.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if dry_run {
|
||||||
|
println!("Dry run enabled. No changes applied. To execute, re-run without --dry-run or use --force (in production).");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("Executing truncate...\n");
|
||||||
|
|
||||||
|
let postgres_config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(postgres_config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
let stmt = Statement::from_string(db.get_database_backend(), truncate_sql);
|
||||||
|
match pg_conn.execute(stmt).await {
|
||||||
|
Ok(_) => println!("✅ Successfully cleared DB tables"),
|
||||||
|
Err(e) => println!("❌ Failed to clear DB tables: {}", e),
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use sea_orm::{ConnectionTrait, Database, Schema, DbBackend, EntityTrait};
|
||||||
|
use imphnen_libs::postgres::PostgresConfig;
|
||||||
|
use imphnen_entities::seaorm::{auth, common, gacha};
|
||||||
|
use sea_orm::sea_query::Table;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
println!("🛠️ Creating database schema...");
|
||||||
|
|
||||||
|
let config = PostgresConfig::from_env()?;
|
||||||
|
let db = Database::connect(&config.database_url).await?;
|
||||||
|
let builder = db.get_database_backend();
|
||||||
|
|
||||||
|
println!(" Database connected. Creating/updating tables...");
|
||||||
|
|
||||||
|
// Dropping and recreating tables to ensure schema is up-to-date
|
||||||
|
// This is safer for development/testing environments to prevent schema drift.
|
||||||
|
drop_and_create_table(&db, builder, "app_roles", auth::roles::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "app_permissions", auth::permissions::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "app_users", auth::users::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "app_roles_permissions", auth::roles_permissions::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "app_mentors", auth::mentors::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "app_sessions", auth::sessions::Entity).await?;
|
||||||
|
|
||||||
|
drop_and_create_table(&db, builder, "events", common::events::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "testimonials", common::testimonials::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "audit_logs", common::audit_log::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "rate_limits", common::rate_limit::Entity).await?;
|
||||||
|
|
||||||
|
drop_and_create_table(&db, builder, "gacha_credits", gacha::gacha_credits::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "gacha_items", gacha::gacha_items::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "gacha_rolls", gacha::gacha_rolls::Entity).await?;
|
||||||
|
drop_and_create_table(&db, builder, "gacha_claims", gacha::gacha_claims::Entity).await?;
|
||||||
|
|
||||||
|
println!("✅ Schema creation completed.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn drop_and_create_table<E>(
|
||||||
|
db: &sea_orm::DatabaseConnection,
|
||||||
|
builder: DbBackend,
|
||||||
|
name: &str,
|
||||||
|
entity: E,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> // Return Result
|
||||||
|
where
|
||||||
|
E: EntityTrait,
|
||||||
|
{
|
||||||
|
let schema = Schema::new(builder);
|
||||||
|
|
||||||
|
// Drop table if it exists
|
||||||
|
let drop_stmt = Table::drop().table(entity).if_exists().cascade().to_owned(); // Added .cascade()
|
||||||
|
db.execute(builder.build(&drop_stmt)).await?; // Propagate error
|
||||||
|
println!(" Dropped table if exists: {}", name);
|
||||||
|
|
||||||
|
// Create table
|
||||||
|
let mut create_stmt = schema.create_table_from_entity(entity);
|
||||||
|
create_stmt.if_not_exists();
|
||||||
|
|
||||||
|
db.execute(builder.build(&create_stmt)).await?; // Propagate error
|
||||||
|
println!(" ✅ Created table: {}", name);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use imphnen_libs::jsonwebtoken::encode_access_token;
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args: Vec<String> = env::args().collect();
|
||||||
|
if args.len() < 2 {
|
||||||
|
eprintln!("Usage: mk_token <email_or_sub>");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
let sub = args[1].clone();
|
||||||
|
// Use sub as both sub and user_id
|
||||||
|
match encode_access_token(sub.clone(), sub.clone()) {
|
||||||
|
Ok(token) => println!("{}", token),
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("Failed to generate token: {:?}", e);
|
||||||
|
std::process::exit(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use imphnen_entities::seaorm::common::events::{ActiveModel as EventsActiveModel, Entity as EventEntity};
|
||||||
|
use sea_orm::{ActiveValue::Set, ActiveModelTrait, EntityTrait, ColumnTrait, QueryFilter};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use chrono::Utc; // Removed NaiveDateTime as it was unused
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let postgres_config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(postgres_config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
let events = vec![
|
||||||
|
(
|
||||||
|
"Tech Conference 2025",
|
||||||
|
"Annual technology conference featuring the latest innovations in software development, AI, and cloud computing.",
|
||||||
|
"https://techconf2025.example.com",
|
||||||
|
150.0,
|
||||||
|
Some("Jakarta Convention Center".to_string()),
|
||||||
|
false,
|
||||||
|
"2025-06-15T09:00:00Z",
|
||||||
|
"2025-06-17T18:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Online Web Development Workshop",
|
||||||
|
"Comprehensive workshop covering modern web development frameworks including React, Vue, and Angular.",
|
||||||
|
"https://webdev-workshop.example.com",
|
||||||
|
75.0,
|
||||||
|
None,
|
||||||
|
true,
|
||||||
|
"2025-07-10T14:00:00Z",
|
||||||
|
"2025-07-10T17:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Startup Pitch Competition",
|
||||||
|
"Exciting competition where emerging startups present their innovative ideas to a panel of expert judges and investors.",
|
||||||
|
"https://startup-pitch.example.com",
|
||||||
|
25.0,
|
||||||
|
Some("Innovation Hub Surabaya".to_string()),
|
||||||
|
false,
|
||||||
|
"2025-08-05T10:00:00Z",
|
||||||
|
"2025-08-05T16:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Digital Marketing Masterclass",
|
||||||
|
"Learn advanced digital marketing strategies, social media optimization, and data-driven marketing techniques.",
|
||||||
|
"https://digital-marketing.example.com",
|
||||||
|
100.0,
|
||||||
|
None,
|
||||||
|
true,
|
||||||
|
"2025-09-20T13:00:00Z",
|
||||||
|
"2025-09-22T15:00:00Z",
|
||||||
|
),
|
||||||
|
// Additional Events
|
||||||
|
(
|
||||||
|
"Rust Programming Bootcamp",
|
||||||
|
"Intensive 3-day bootcamp to master Rust fundamentals and advanced concepts.",
|
||||||
|
"https://rust-bootcamp.example.com",
|
||||||
|
200.0,
|
||||||
|
Some("Bandung Digital Valley".to_string()),
|
||||||
|
false,
|
||||||
|
"2025-10-01T09:00:00Z",
|
||||||
|
"2025-10-03T17:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"AI & Machine Learning Summit",
|
||||||
|
"Global summit discussing the future of AI and its impact on industries.",
|
||||||
|
"https://ai-summit.example.com",
|
||||||
|
300.0,
|
||||||
|
Some("Bali Nusa Dua Convention Center".to_string()),
|
||||||
|
false,
|
||||||
|
"2025-11-15T08:00:00Z",
|
||||||
|
"2025-11-17T18:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Cybersecurity Awareness Webinar",
|
||||||
|
"Free webinar on best practices for personal and corporate cybersecurity.",
|
||||||
|
"https://cybersecurity-webinar.example.com",
|
||||||
|
0.0,
|
||||||
|
None,
|
||||||
|
true,
|
||||||
|
"2025-12-05T14:00:00Z",
|
||||||
|
"2025-12-05T16:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Cloud Computing Workshop",
|
||||||
|
"Hands-on workshop on deploying scalable applications using AWS and Azure.",
|
||||||
|
"https://cloud-workshop.example.com",
|
||||||
|
120.0,
|
||||||
|
None,
|
||||||
|
true,
|
||||||
|
"2026-01-20T10:00:00Z",
|
||||||
|
"2026-01-22T15:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Blockchain for Finance",
|
||||||
|
"Exploring the applications of blockchain technology in the financial sector.",
|
||||||
|
"https://blockchain-finance.example.com",
|
||||||
|
180.0,
|
||||||
|
Some("Jakarta Ritz-Carlton".to_string()),
|
||||||
|
false,
|
||||||
|
"2026-02-10T09:00:00Z",
|
||||||
|
"2026-02-11T17:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Game Development Jam",
|
||||||
|
"48-hour game development marathon for indie developers.",
|
||||||
|
"https://game-jam.example.com",
|
||||||
|
50.0,
|
||||||
|
Some("Yogyakarta Creative Hub".to_string()),
|
||||||
|
false,
|
||||||
|
"2026-03-15T18:00:00Z",
|
||||||
|
"2026-03-17T18:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"UX/UI Design Principles",
|
||||||
|
"Masterclass on creating intuitive and user-friendly interfaces.",
|
||||||
|
"https://uxui-design.example.com",
|
||||||
|
90.0,
|
||||||
|
None,
|
||||||
|
true,
|
||||||
|
"2026-04-05T13:00:00Z",
|
||||||
|
"2026-04-07T16:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Data Science Fundamentals",
|
||||||
|
"Introduction to data analysis, visualization, and statistical modeling.",
|
||||||
|
"https://data-science.example.com",
|
||||||
|
110.0,
|
||||||
|
None,
|
||||||
|
true,
|
||||||
|
"2026-05-12T10:00:00Z",
|
||||||
|
"2026-05-14T15:00:00Z",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"IoT Innovation Expo",
|
||||||
|
"Showcase of the latest Internet of Things devices and solutions.",
|
||||||
|
"https://iot-expo.example.com",
|
||||||
|
50.0,
|
||||||
|
Some("Surabaya Expo Center".to_string()),
|
||||||
|
false,
|
||||||
|
"2026-06-20T09:00:00Z",
|
||||||
|
"2026-06-22T18:00:00Z",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
detail_link,
|
||||||
|
price,
|
||||||
|
location,
|
||||||
|
is_online,
|
||||||
|
start_date_str, // Renamed to avoid conflict
|
||||||
|
end_date_str, // Renamed to avoid conflict
|
||||||
|
) in events
|
||||||
|
{
|
||||||
|
// Check if event already exists by name
|
||||||
|
let existing = EventEntity::find().filter(<EventEntity as EntityTrait>::Column::Name.eq(name)).one(db).await?;
|
||||||
|
if existing.is_some() {
|
||||||
|
println!("ℹ️ Skipping (already exists): {name}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let uuid = Uuid::new_v4(); // Generate a Uuid
|
||||||
|
let mut event_model: EventsActiveModel = Default::default();
|
||||||
|
event_model.id = Set(uuid);
|
||||||
|
event_model.name = Set(name.to_string());
|
||||||
|
event_model.description = Set(description.to_string());
|
||||||
|
event_model.detail_link = Set(detail_link.to_string());
|
||||||
|
event_model.price = Set(price);
|
||||||
|
event_model.is_online = Set(is_online);
|
||||||
|
event_model.location = Set(location.clone());
|
||||||
|
event_model.start_date = Set(chrono::DateTime::parse_from_rfc3339(start_date_str)?.with_timezone(&chrono::Utc));
|
||||||
|
event_model.end_date = Set(chrono::DateTime::parse_from_rfc3339(end_date_str)?.with_timezone(&chrono::Utc));
|
||||||
|
event_model.is_deleted = Set(false); // Explicitly set is_deleted
|
||||||
|
event_model.created_at = Set(Utc::now()); // Explicitly set created_at
|
||||||
|
event_model.updated_at = Set(Utc::now()); // Explicitly set updated_at
|
||||||
|
|
||||||
|
|
||||||
|
event_model.insert(db).await?;
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"✅ Inserted event: {} ({})",
|
||||||
|
name,
|
||||||
|
if is_online { "Online" } else { "In-person" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("✅ All Events seeded");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use imphnen_entities::seaorm::gacha::gacha_items::ActiveModel as GachaItemActiveModel;
|
||||||
|
use imphnen_entities::seaorm::gacha::gacha_rolls::ActiveModel as GachaRollActiveModel;
|
||||||
|
use sea_orm::ActiveModelTrait;
|
||||||
|
use sea_orm::ActiveValue::Set;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use sea_orm::ConnectionTrait;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
// Check if gacha item already exists
|
||||||
|
let check_item_sql = "SELECT id FROM app_gacha_items WHERE item_code = 'ITEM_TEST_1' LIMIT 1";
|
||||||
|
let item_result = pg_conn.query_one(sea_orm::Statement::from_string(db.get_database_backend(), check_item_sql)).await?;
|
||||||
|
let gacha_item_uuid = if let Some(ref row) = item_result {
|
||||||
|
// Item exists, get its ID
|
||||||
|
row.try_get("", "id")?
|
||||||
|
} else {
|
||||||
|
// Item doesn't exist, create it
|
||||||
|
// Note: We can't easily delete by a fixed ID since it's a UUID, but the insert will fail if there's a conflict
|
||||||
|
let _ = pg_conn.execute(sea_orm::Statement::from_string(db.get_database_backend(), "DELETE FROM app_gacha_items WHERE item_code = 'ITEM_TEST_1'".to_string())).await.ok();
|
||||||
|
|
||||||
|
// Create gacha item via SeaORM
|
||||||
|
let new_uuid = Uuid::new_v4();
|
||||||
|
let mut item_model: GachaItemActiveModel = Default::default();
|
||||||
|
item_model.id = Set(new_uuid);
|
||||||
|
item_model.item_code = Set("ITEM_TEST_1".to_string());
|
||||||
|
item_model.name = Set("Test Gacha Item".to_string());
|
||||||
|
item_model.description = Set("Test item for gacha".to_string());
|
||||||
|
item_model.rarity = Set("common".to_string());
|
||||||
|
item_model.type_ = Set("item".to_string());
|
||||||
|
item_model.category = Set("test".to_string());
|
||||||
|
item_model.value = Set(1);
|
||||||
|
item_model.weight = Set(1.0);
|
||||||
|
item_model.stock = Set(10);
|
||||||
|
item_model.is_limited = Set(false);
|
||||||
|
item_model.created_at = Set(chrono::Utc::now());
|
||||||
|
item_model.updated_at = Set(chrono::Utc::now());
|
||||||
|
item_model.insert(db).await?;
|
||||||
|
println!("Gacha Item seeded successfully!");
|
||||||
|
new_uuid
|
||||||
|
};
|
||||||
|
|
||||||
|
// Always try to insert the roll, relying on the database constraints to prevent duplicates if needed
|
||||||
|
let gacha_roll_id = Uuid::new_v4();
|
||||||
|
let mut roll_model: GachaRollActiveModel = Default::default();
|
||||||
|
roll_model.id = Set(gacha_roll_id);
|
||||||
|
roll_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
|
||||||
|
roll_model.gacha_id = Set(Uuid::new_v4().to_string());
|
||||||
|
roll_model.item_id = Set(gacha_item_uuid);
|
||||||
|
roll_model.weight = Set(1.0);
|
||||||
|
roll_model.quantity = Set(10);
|
||||||
|
roll_model.is_deleted = Set(false);
|
||||||
|
roll_model.created_at = Set(Some(chrono::Utc::now().naive_utc()));
|
||||||
|
roll_model.updated_at = Set(Some(chrono::Utc::now().naive_utc()));
|
||||||
|
roll_model.insert(db).await?;
|
||||||
|
println!("Gacha Roll seeded successfully!");
|
||||||
|
let gacha_roll_id = Uuid::new_v4();
|
||||||
|
let mut roll_model: GachaRollActiveModel = Default::default();
|
||||||
|
roll_model.id = Set(gacha_roll_id);
|
||||||
|
roll_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
|
||||||
|
roll_model.gacha_id = Set(Uuid::new_v4().to_string());
|
||||||
|
roll_model.item_id = Set(gacha_item_uuid);
|
||||||
|
roll_model.weight = Set(1.0);
|
||||||
|
roll_model.quantity = Set(10);
|
||||||
|
roll_model.is_deleted = Set(false);
|
||||||
|
roll_model.created_at = Set(Some(chrono::Utc::now().naive_utc()));
|
||||||
|
roll_model.updated_at = Set(Some(chrono::Utc::now().naive_utc()));
|
||||||
|
roll_model.insert(db).await?;
|
||||||
|
println!("✅ Gacha items and rolls seeded.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use imphnen_libs::hash_password;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::error::Error;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use imphnen_entities::seaorm::auth::users::ActiveModel as UsersActiveModel;
|
||||||
|
use imphnen_entities::seaorm::auth::mentors::ActiveModel as MentorsActiveModel;
|
||||||
|
use imphnen_entities::seaorm::auth::roles::{Entity as RoleEntity, Column as RoleColumn};
|
||||||
|
use sea_orm::{ActiveModelTrait, ConnectionTrait, ActiveValue::Set, EntityTrait, QueryFilter, ColumnTrait};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
let _ = pg_conn.execute(sea_orm::Statement::from_string(db.get_database_backend(), "DELETE FROM app_mentors WHERE id = 'e6f78d23-83bf-5c2b-bcd4-001345678901'".to_string())).await.ok();
|
||||||
|
let _ = pg_conn.execute(sea_orm::Statement::from_string(db.get_database_backend(), "DELETE FROM app_users WHERE email = 'mentor@example.com'".to_string())).await.ok();
|
||||||
|
|
||||||
|
// Find Mentor role
|
||||||
|
let role = RoleEntity::find()
|
||||||
|
.filter(RoleColumn::Name.eq("Mentor"))
|
||||||
|
.one(db)
|
||||||
|
.await?
|
||||||
|
.ok_or("Role 'Mentor' not found")?;
|
||||||
|
|
||||||
|
// Insert user with Mentor role
|
||||||
|
let user_id = Uuid::new_v4();
|
||||||
|
let mut user_model: UsersActiveModel = Default::default();
|
||||||
|
user_model.id = Set(user_id);
|
||||||
|
user_model.email = Set("mentor@example.com".to_string());
|
||||||
|
user_model.password_hash = Set(hash_password("password").unwrap());
|
||||||
|
user_model.username = Set("mentor@example.com".to_string());
|
||||||
|
user_model.first_name = Set(Some("Mentor".to_string()));
|
||||||
|
user_model.last_name = Set(Some("User".to_string()));
|
||||||
|
user_model.avatar_url = Set(Some("https://example.com/avatar.jpg".to_string()));
|
||||||
|
user_model.is_active = Set(true);
|
||||||
|
user_model.is_verified = Set(true);
|
||||||
|
user_model.role_id = Set(Some(role.id));
|
||||||
|
user_model.created_at = Set(chrono::Utc::now());
|
||||||
|
user_model.updated_at = Set(chrono::Utc::now());
|
||||||
|
user_model.insert(db).await?;
|
||||||
|
|
||||||
|
// Insert mentor
|
||||||
|
let mentor_id = Uuid::new_v4();
|
||||||
|
let mut mentor_model: MentorsActiveModel = Default::default();
|
||||||
|
mentor_model.id = Set(mentor_id);
|
||||||
|
mentor_model.user_id = Set(user_id);
|
||||||
|
mentor_model.industries = Set(Some(json!( ["Software", "Education"] )));
|
||||||
|
mentor_model.expertise = Set(Some(json!( ["Rust", "Microservices"] )));
|
||||||
|
mentor_model.languages = Set(Some(json!( ["Indonesian", "English"] )));
|
||||||
|
mentor_model.current_company = Set(Some("PT Contoh".to_string()));
|
||||||
|
mentor_model.current_role = Set(Some("Senior Backend Engineer".to_string()));
|
||||||
|
mentor_model.years_of_experience = Set(Some(5));
|
||||||
|
mentor_model.topics_of_interest = Set(Some(json!( ["Rust Programming", "Backend Development"] )));
|
||||||
|
mentor_model.preferred_mentee_level = Set(Some("beginner".to_string()));
|
||||||
|
mentor_model.preferred_mentoring_formats = Set(Some(json!( ["online", "offline"] )));
|
||||||
|
mentor_model.availability_commitment = Set(Some("2 jam per minggu untuk mentoring online dan offline".to_string()));
|
||||||
|
mentor_model.mentoring_rate = Set(Some(100000.0));
|
||||||
|
mentor_model.status = Set(Some("verified".to_string()));
|
||||||
|
mentor_model.is_deleted = Set(false);
|
||||||
|
mentor_model.created_at = Set(chrono::Utc::now());
|
||||||
|
mentor_model.updated_at = Set(chrono::Utc::now());
|
||||||
|
mentor_model.insert(db).await?;
|
||||||
|
println!("Mentor created successfully!");
|
||||||
|
|
||||||
|
println!("✅ Inserted mentor user: mentor@example.com");
|
||||||
|
println!("✅ Mentor user seeded");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use imphnen_iam::PermissionsEnum;
|
||||||
|
use std::error::Error;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use imphnen_entities::seaorm::auth::permissions::ActiveModel as PermissionActiveModel;
|
||||||
|
use imphnen_entities::seaorm::auth::permissions::Entity as PermissionEntity;
|
||||||
|
use sea_orm::ActiveValue::Set;
|
||||||
|
use sea_orm::{ActiveModelTrait};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
for permission in [
|
||||||
|
PermissionsEnum::ReadListUsers,
|
||||||
|
PermissionsEnum::ReadDetailUsers,
|
||||||
|
PermissionsEnum::CreateUsers,
|
||||||
|
PermissionsEnum::DeleteUsers,
|
||||||
|
PermissionsEnum::UpdateUsers,
|
||||||
|
PermissionsEnum::ActivateUsers,
|
||||||
|
PermissionsEnum::ReadListRoles,
|
||||||
|
PermissionsEnum::ReadDetailRoles,
|
||||||
|
PermissionsEnum::CreateRoles,
|
||||||
|
PermissionsEnum::DeleteRoles,
|
||||||
|
PermissionsEnum::UpdateRoles,
|
||||||
|
PermissionsEnum::ReadListPermissions,
|
||||||
|
PermissionsEnum::ReadDetailPermissions,
|
||||||
|
PermissionsEnum::CreatePermissions,
|
||||||
|
PermissionsEnum::DeletePermissions,
|
||||||
|
PermissionsEnum::UpdatePermissions,
|
||||||
|
PermissionsEnum::CreateGachaClaims,
|
||||||
|
PermissionsEnum::ReadDetailGachaClaims,
|
||||||
|
PermissionsEnum::ReadListGachaItems,
|
||||||
|
PermissionsEnum::ReadDetailGachaItems,
|
||||||
|
PermissionsEnum::CreateGachaItems,
|
||||||
|
PermissionsEnum::DeleteGachaItems,
|
||||||
|
PermissionsEnum::UpdateGachaItems,
|
||||||
|
PermissionsEnum::ReadDetailGachaRolls,
|
||||||
|
PermissionsEnum::CreateGachaRolls,
|
||||||
|
PermissionsEnum::ExecuteGachaRolls,
|
||||||
|
PermissionsEnum::ReadListMentors,
|
||||||
|
PermissionsEnum::ReadDetailMentors,
|
||||||
|
PermissionsEnum::RegisterMentors,
|
||||||
|
PermissionsEnum::ReadOwnMentorProfile,
|
||||||
|
PermissionsEnum::UpdateOwnMentorProfile,
|
||||||
|
PermissionsEnum::ReadOwnMentorStatus,
|
||||||
|
PermissionsEnum::UpdateMentors,
|
||||||
|
PermissionsEnum::VerifyMentors,
|
||||||
|
PermissionsEnum::DeleteMentors,
|
||||||
|
PermissionsEnum::Administrator,
|
||||||
|
] {
|
||||||
|
// permission.id() returns a string, try parse to uuid
|
||||||
|
let parsed_id = Uuid::parse_str(&permission.id()).unwrap_or_else(|_| Uuid::new_v4());
|
||||||
|
|
||||||
|
// Check if permission already exists
|
||||||
|
let existing = PermissionEntity::find_by_id(parsed_id).one(db).await?;
|
||||||
|
if existing.is_some() {
|
||||||
|
println!("ℹ️ Skipping (already exists): {permission}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert permission using active model
|
||||||
|
let mut perm_model: PermissionActiveModel = Default::default();
|
||||||
|
perm_model.id = Set(parsed_id);
|
||||||
|
perm_model.name = Set(permission.to_string());
|
||||||
|
perm_model.is_deleted = Set(false);
|
||||||
|
perm_model.created_at = Set(Utc::now());
|
||||||
|
perm_model.updated_at = Set(Utc::now());
|
||||||
|
perm_model.insert(db).await?;
|
||||||
|
println!("✅ Inserted: {permission}");
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("✅ All Permissions seeded");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use imphnen_entities::seaorm::auth::roles::{RoleBuilder, Entity as RoleEntity};
|
||||||
|
use sea_orm::{ActiveModelTrait, ActiveValue::Set, EntityTrait};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use chrono::Utc; // Added chrono
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
let roles = vec![
|
||||||
|
(
|
||||||
|
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
|
||||||
|
"Staf",
|
||||||
|
Some("2025-02-24T16:52:27.630453+00"),
|
||||||
|
Some("2025-02-24T16:52:27.630461+00"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
"User",
|
||||||
|
Some("2025-02-28T14:53:58.576688+00"),
|
||||||
|
Some("2025-02-28T14:53:58.576688+00"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"60f1aeb7-dad2-4e06-bcb5-be1ba510c906",
|
||||||
|
"Staff Aktivasi User",
|
||||||
|
Some("2025-02-20T02:47:09.660640+00"),
|
||||||
|
Some("2025-02-20T02:48:30.083283+00"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"6d4fea5d-4a08-4b8a-9782-f2ab2183dcf0",
|
||||||
|
"Admin Pembayaran",
|
||||||
|
Some("2025-01-29T05:39:28.562667+00"),
|
||||||
|
Some("2025-03-12T22:56:29.597416+00"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"f6b03f25-e416-4893-ac88-caaa690afb07",
|
||||||
|
"Admin",
|
||||||
|
Some("2025-02-22T15:38:39.868306+00"),
|
||||||
|
Some("2025-02-22T15:38:39.868306+00"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a",
|
||||||
|
"Mentor",
|
||||||
|
Some("2025-07-06T10:00:00.000000+00"),
|
||||||
|
Some("2025-07-06T10:00:00.000000+00"),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (id, name, _created_at_str, _updated_at_str) in roles { // Renamed to avoid conflict
|
||||||
|
let uuid = Uuid::parse_str(id).unwrap_or_else(|_| Uuid::new_v4());
|
||||||
|
|
||||||
|
// Check if role already exists
|
||||||
|
let existing = RoleEntity::find_by_id(uuid).one(db).await?;
|
||||||
|
if existing.is_some() {
|
||||||
|
println!("ℹ️ Skipping (already exists): {name}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete existing by id to avoid duplicates (original logic, replaced by existence check)
|
||||||
|
// let _ = pg_conn.execute(sea_orm::Statement::from_string(db.get_database_backend(), format!("DELETE FROM app_roles WHERE id = '{}'", uuid))).await.ok();
|
||||||
|
|
||||||
|
let role_model = RoleBuilder::new()
|
||||||
|
.name(name.to_string())
|
||||||
|
.description("System generated role".to_string())
|
||||||
|
.permissions(vec![])
|
||||||
|
.is_default(false)
|
||||||
|
.build()?;
|
||||||
|
let mut role_model = role_model;
|
||||||
|
role_model.id = Set(uuid);
|
||||||
|
role_model.is_system_role = Set(true); // Set the missing field
|
||||||
|
role_model.created_at = Set(Utc::now()); // Set created_at
|
||||||
|
role_model.updated_at = Set(Utc::now()); // Set updated_at
|
||||||
|
|
||||||
|
role_model.insert(db).await?;
|
||||||
|
println!("✅ Inserted role: {name}");
|
||||||
|
}
|
||||||
|
println!("✅ All Roles seeded");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
use imphnen_iam::PermissionsEnum;
|
||||||
|
use std::error::Error;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use imphnen_entities::seaorm::auth::roles::Entity as RolesEntity;
|
||||||
|
use imphnen_entities::seaorm::auth::roles::ActiveModel as RoleActiveModel;
|
||||||
|
use sea_orm::ActiveValue::Set;
|
||||||
|
use sea_orm::EntityTrait;
|
||||||
|
use sea_orm::ActiveModelTrait;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use serde_json::Value as JsonValue;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
// Ensure indexes are present if needed (placeholders) - we don't modify schema here
|
||||||
|
|
||||||
|
println!("✅ Index 'user_email_index' defined on table 'users' for column 'email'.");
|
||||||
|
|
||||||
|
let roles_permissions = vec![
|
||||||
|
(
|
||||||
|
"f6b03f25-e416-4893-ac88-caaa690afb07",
|
||||||
|
vec![
|
||||||
|
// Only Administrator permission - grants access to everything
|
||||||
|
PermissionsEnum::Administrator,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a",
|
||||||
|
vec![
|
||||||
|
PermissionsEnum::ReadListUsers, // Added ReadListUsers permission
|
||||||
|
PermissionsEnum::ReadOwnMentorProfile,
|
||||||
|
PermissionsEnum::UpdateOwnMentorProfile,
|
||||||
|
PermissionsEnum::ReadOwnMentorStatus,
|
||||||
|
PermissionsEnum::ReadListMentors,
|
||||||
|
PermissionsEnum::ReadDetailMentors,
|
||||||
|
PermissionsEnum::ReadListGachaItems,
|
||||||
|
PermissionsEnum::ReadDetailGachaItems,
|
||||||
|
PermissionsEnum::ReadDetailGachaRolls,
|
||||||
|
PermissionsEnum::CreateGachaRolls,
|
||||||
|
PermissionsEnum::ExecuteGachaRolls,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
vec![
|
||||||
|
PermissionsEnum::ReadListGachaItems,
|
||||||
|
PermissionsEnum::ReadDetailGachaItems,
|
||||||
|
PermissionsEnum::ReadListUsers,
|
||||||
|
PermissionsEnum::ReadDetailUsers,
|
||||||
|
PermissionsEnum::CreateGachaClaims,
|
||||||
|
PermissionsEnum::ReadDetailGachaClaims,
|
||||||
|
PermissionsEnum::ReadDetailGachaRolls,
|
||||||
|
PermissionsEnum::CreateGachaRolls,
|
||||||
|
PermissionsEnum::ExecuteGachaRolls,
|
||||||
|
PermissionsEnum::RegisterMentors,
|
||||||
|
PermissionsEnum::ReadListMentors,
|
||||||
|
PermissionsEnum::ReadDetailMentors,
|
||||||
|
PermissionsEnum::ReadOwnMentorProfile,
|
||||||
|
PermissionsEnum::ReadOwnMentorStatus,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
|
||||||
|
vec![
|
||||||
|
// Staff should be able to list roles and permissions in tests
|
||||||
|
PermissionsEnum::ReadListRoles,
|
||||||
|
PermissionsEnum::ReadListPermissions,
|
||||||
|
PermissionsEnum::ReadListUsers,
|
||||||
|
PermissionsEnum::ReadListMentors,
|
||||||
|
PermissionsEnum::ReadDetailUsers,
|
||||||
|
PermissionsEnum::ActivateUsers,
|
||||||
|
PermissionsEnum::ReadDetailRoles,
|
||||||
|
PermissionsEnum::ReadDetailPermissions,
|
||||||
|
PermissionsEnum::ReadListGachaItems,
|
||||||
|
PermissionsEnum::ReadDetailGachaItems,
|
||||||
|
PermissionsEnum::ReadListMentors,
|
||||||
|
PermissionsEnum::ReadDetailMentors,
|
||||||
|
PermissionsEnum::ReadDetailGachaRolls,
|
||||||
|
PermissionsEnum::CreateGachaRolls,
|
||||||
|
PermissionsEnum::ExecuteGachaRolls,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"60f1aeb7-dad2-4e06-bcb5-be1ba510c906",
|
||||||
|
vec![PermissionsEnum::ActivateUsers],
|
||||||
|
),
|
||||||
|
("6d4fea5d-4a08-4b8a-9782-f2ab2183dcf0", vec![]),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (role_id, permissions) in roles_permissions {
|
||||||
|
let role_uuid = Uuid::parse_str(role_id).unwrap_or_else(|_| Uuid::new_v4());
|
||||||
|
// Map permissions enum to JSON array of permission ids
|
||||||
|
let json_permissions = JsonValue::Array(
|
||||||
|
permissions.iter().map(|p| JsonValue::String(p.id())).collect()
|
||||||
|
);
|
||||||
|
|
||||||
|
// Find role and update permissions
|
||||||
|
if let Some(role_model) = RolesEntity::find_by_id(role_uuid).one(db).await? {
|
||||||
|
let mut am: RoleActiveModel = role_model.into();
|
||||||
|
am.permissions = Set(Some(json_permissions));
|
||||||
|
am.update(db).await?;
|
||||||
|
println!("✅ Permissions updated for role: {role_id}");
|
||||||
|
} else {
|
||||||
|
println!("⚠️ Role with id {role_id} not found, skipping permissions update");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("✅ All roles permissions updated!");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use imphnen_entities::seaorm::common::events::ActiveModel as EventsActiveModel;
|
||||||
|
use imphnen_entities::seaorm::common::testimonials::ActiveModel as TestimonialsActiveModel;
|
||||||
|
use imphnen_entities::seaorm::auth::mentors::ActiveModel as MentorsActiveModel;
|
||||||
|
use sea_orm::ActiveValue::Set;
|
||||||
|
use sea_orm::ActiveModelTrait;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use serde_json::json;
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
// Seed Events - handle existing data
|
||||||
|
let uuid = Uuid::new_v4().to_string();
|
||||||
|
let mut event_model: EventsActiveModel = Default::default();
|
||||||
|
event_model.id = Set(Uuid::parse_str(&uuid)?);
|
||||||
|
event_model.name = Set("Test Event".to_string());
|
||||||
|
event_model.description = Set("Test event description".to_string());
|
||||||
|
event_model.detail_link = Set("https://example.com/event".to_string());
|
||||||
|
event_model.price = Set(50.0);
|
||||||
|
event_model.is_online = Set(true);
|
||||||
|
event_model.start_date = Set(Utc::now());
|
||||||
|
event_model.end_date = Set(Utc::now() + chrono::Duration::days(1));
|
||||||
|
event_model.location = Set(None);
|
||||||
|
event_model.is_deleted = Set(false);
|
||||||
|
match event_model.insert(db).await {
|
||||||
|
Ok(_) => println!("✅ Inserted test event"),
|
||||||
|
Err(_) => println!("⚠️ Test event already exists or could not be inserted, skipping"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Seed Testimonials - handle existing data
|
||||||
|
let mut testimonial_model: TestimonialsActiveModel = Default::default();
|
||||||
|
testimonial_model.id = Set(Uuid::parse_str("00000000-0000-0000-0000-000000000001")?);
|
||||||
|
testimonial_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
|
||||||
|
testimonial_model.role = Set("Student".to_string());
|
||||||
|
testimonial_model.content = Set("This is a great platform!".to_string());
|
||||||
|
testimonial_model.is_deleted = Set(false);
|
||||||
|
match testimonial_model.insert(db).await {
|
||||||
|
Ok(_) => println!("✅ Inserted test testimonial"),
|
||||||
|
Err(_) => println!("⚠️ Test testimonial already exists or could not be inserted, skipping"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Seed Mentor - handle existing data
|
||||||
|
let mentor_id = Uuid::new_v4();
|
||||||
|
let mut mentor_model: MentorsActiveModel = Default::default();
|
||||||
|
mentor_model.id = Set(mentor_id);
|
||||||
|
// Use the admin user ID instead of a random one
|
||||||
|
mentor_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
|
||||||
|
mentor_model.industries = Set(Some(json!( ["Technology", "Education"] )));
|
||||||
|
mentor_model.expertise = Set(Some(json!( ["Software Development"] )));
|
||||||
|
mentor_model.languages = Set(Some(json!( ["English", "Indonesian"] )));
|
||||||
|
mentor_model.current_company = Set(Some("Tech Corp".to_string()));
|
||||||
|
mentor_model.current_role = Set(Some("Senior Engineer".to_string()));
|
||||||
|
mentor_model.years_of_experience = Set(Some(5));
|
||||||
|
mentor_model.topics_of_interest = Set(Some(json!( ["Rust", "Web Development"] )));
|
||||||
|
mentor_model.preferred_mentee_level = Set(Some("Beginner".to_string()));
|
||||||
|
mentor_model.preferred_mentoring_formats = Set(Some(json!( ["1:1", "Group"] )));
|
||||||
|
mentor_model.availability_commitment = Set(Some("Weekly".to_string()));
|
||||||
|
mentor_model.mentoring_rate = Set(Some(100.0));
|
||||||
|
mentor_model.status = Set(Some("active".to_string()));
|
||||||
|
mentor_model.is_deleted = Set(false);
|
||||||
|
mentor_model.created_at = Set(chrono::Utc::now());
|
||||||
|
mentor_model.updated_at = Set(chrono::Utc::now());
|
||||||
|
// Create mentor record via SeaORM active model
|
||||||
|
mentor_model.insert(db).await?;
|
||||||
|
println!("✅ Inserted test mentor via SeaORM");
|
||||||
|
|
||||||
|
println!("✅ All test data seeded successfully");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use imphnen_libs::hash_password;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
|
||||||
|
use imphnen_entities::seaorm::auth::users::Entity as UserEntity; // Added for dynamic role lookup
|
||||||
|
use imphnen_entities::seaorm::auth::users::ActiveModel as UsersActiveModel;
|
||||||
|
|
||||||
|
use sea_orm::{ActiveModelTrait, ActiveValue::Set, EntityTrait, IntoActiveModel};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use std::error::Error;
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
let postgres_config = PostgresConfig::from_env()?;
|
||||||
|
let pg_conn = PostgresConnection::new(postgres_config).await?;
|
||||||
|
let db = &pg_conn.conn;
|
||||||
|
|
||||||
|
let users = vec![
|
||||||
|
(
|
||||||
|
"c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2",
|
||||||
|
"admin@example.com",
|
||||||
|
"Admin",
|
||||||
|
"f6b03f25-e416-4893-ac88-caaa690afb07",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"a4d23fb5-9e31-423c-9842-fbd6e75a5298",
|
||||||
|
"staff@example.com",
|
||||||
|
"Staff",
|
||||||
|
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"d5e89c12-72af-4b1a-abc3-ff1234567890",
|
||||||
|
"user@example.com",
|
||||||
|
"User",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"665a3cfc-ea5f-4bcd-8769-4a6d8d1451d4",
|
||||||
|
"testuser1@example.com",
|
||||||
|
"Test User 1",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059", // Fixed UUID
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"3972c139-a450-416c-93b0-c42539dc780f",
|
||||||
|
"testuser2@example.com",
|
||||||
|
"Test User 2",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"b426c0a9-0efb-4e26-b078-4f18767255f3",
|
||||||
|
"testuser3@example.com",
|
||||||
|
"Test User 3",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059", // Fixed UUID
|
||||||
|
),
|
||||||
|
// Additional Users for Volume and Variety
|
||||||
|
(
|
||||||
|
"11111111-1111-1111-1111-111111111111",
|
||||||
|
"user4@example.com",
|
||||||
|
"User Four",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"22222222-2222-2222-2222-222222222222",
|
||||||
|
"user5@example.com",
|
||||||
|
"User Five",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"33333333-3333-3333-3333-333333333333",
|
||||||
|
"mentor2@example.com",
|
||||||
|
"Mentor Two",
|
||||||
|
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a", // Mentor Role
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"44444444-4444-4444-4444-444444444444",
|
||||||
|
"staff2@example.com",
|
||||||
|
"Staff Two",
|
||||||
|
"50133429-f4b1-4249-9f97-7b86e6ee9d86", // Staff Role
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"55555555-5555-5555-5555-555555555555",
|
||||||
|
"user6@example.com",
|
||||||
|
"User Six",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"66666666-6666-6666-6666-666666666666",
|
||||||
|
"user7@example.com",
|
||||||
|
"User Seven",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"77777777-7777-7777-7777-777777777777",
|
||||||
|
"user8@example.com",
|
||||||
|
"User Eight",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"88888888-8888-8888-8888-888888888888",
|
||||||
|
"user9@example.com",
|
||||||
|
"User Nine",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"99999999-9999-9999-9999-999999999999",
|
||||||
|
"user10@example.com",
|
||||||
|
"User Ten",
|
||||||
|
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (id, email, fullname, role_id_str) in users { // role_id_str directly contains UUID
|
||||||
|
let role_uuid = Some(Uuid::parse_str(role_id_str)
|
||||||
|
.map_err(|e| format!("Invalid UUID for role: {role_id_str} - {e}"))?);
|
||||||
|
|
||||||
|
// Build SeaORM ActiveModel for users
|
||||||
|
let uid = Uuid::parse_str(id)?; // Should always be valid UUID strings from test data
|
||||||
|
|
||||||
|
let names: Vec<&str> = fullname.split_whitespace().collect();
|
||||||
|
let first_name = names.first().map(|s| s.to_string());
|
||||||
|
let last_name = if names.len() > 1 { Some(names[1..].join(" ")) } else { None };
|
||||||
|
|
||||||
|
let password = "password";
|
||||||
|
let hashed = hash_password(password).unwrap();
|
||||||
|
|
||||||
|
// Explicit Upsert Logic
|
||||||
|
let existing_user = UserEntity::find_by_id(uid).one(db).await?;
|
||||||
|
let is_update = existing_user.is_some();
|
||||||
|
|
||||||
|
let mut user_model: UsersActiveModel = if let Some(existing) = existing_user {
|
||||||
|
println!("🔄 Updating user: {fullname} ({email})");
|
||||||
|
existing.into_active_model()
|
||||||
|
} else {
|
||||||
|
println!("✅ Inserting user: {fullname} ({email})");
|
||||||
|
let mut active: UsersActiveModel = Default::default();
|
||||||
|
active.id = Set(uid);
|
||||||
|
active.created_at = Set(Utc::now());
|
||||||
|
active
|
||||||
|
};
|
||||||
|
|
||||||
|
user_model.email = Set(email.to_string());
|
||||||
|
user_model.password_hash = Set(hashed);
|
||||||
|
user_model.username = Set(email.to_string());
|
||||||
|
user_model.first_name = Set(first_name);
|
||||||
|
user_model.last_name = Set(last_name);
|
||||||
|
user_model.avatar_url = Set(Some("https://example.com/avatar.jpg".to_string()));
|
||||||
|
user_model.is_verified = Set(true);
|
||||||
|
user_model.is_active = Set(true);
|
||||||
|
user_model.role_id = Set(role_uuid);
|
||||||
|
user_model.updated_at = Set(Utc::now());
|
||||||
|
|
||||||
|
if is_update {
|
||||||
|
user_model.update(db).await?;
|
||||||
|
} else {
|
||||||
|
user_model.insert(db).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println!("✅ All Users seeded");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#![allow(clippy::all)]
|
||||||
|
|
||||||
|
use std::error::Error;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
fn run_seed(bin: &str) -> Result<(), Box<dyn Error>> {
|
||||||
|
println!("🔧 Seeding: {bin}");
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
let status = Command::new(format!("./target/release/{}.exe", bin)).status()?;
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
let status = Command::new(format!("./target/release/{}", bin)).status()?;
|
||||||
|
|
||||||
|
if !status.success() {
|
||||||
|
Err(format!("❌ Failed to run seed: {bin}").into())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
println!("🚀 Running all seeders...\n");
|
||||||
|
|
||||||
|
run_seed("seed_permissions")?;
|
||||||
|
run_seed("seed_roles")?;
|
||||||
|
run_seed("seed_roles_permissions")?;
|
||||||
|
run_seed("seed_users")?;
|
||||||
|
run_seed("seed_events")?;
|
||||||
|
run_seed("seed_gacha_rolls")?;
|
||||||
|
run_seed("seed_mentor_user")?;
|
||||||
|
run_seed("seed_test_data")?;
|
||||||
|
println!("\n✅ All seeding completed successfully.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
//! PostgreSQL Connection Test Program
|
||||||
|
//! This program tests the PostgreSQL integration with SeaORM
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection, PostgresError};
|
||||||
|
use imphnen_entities::seaorm::auth::users::{Entity as UsersEntity, Model as UserModel};
|
||||||
|
use imphnen_entities::seaorm::auth::roles::{Entity as RolesEntity, Model as RoleModel};
|
||||||
|
use sea_orm::{EntityTrait, ActiveModelTrait, Set, TransactionTrait, DbErr, PaginatorTrait};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
println!("🚀 Starting PostgreSQL Connection Test");
|
||||||
|
println!("=====================================");
|
||||||
|
|
||||||
|
// Load configuration from environment
|
||||||
|
let config = PostgresConfig::from_env()?;
|
||||||
|
println!("✅ Configuration loaded successfully");
|
||||||
|
println!(" Database URL: {}", config.database_url.replace("postgres://", "postgres://****:****@"));
|
||||||
|
println!(" Pool size: {}", config.pool_size);
|
||||||
|
println!(" Connect timeout: {}s", config.connect_timeout);
|
||||||
|
println!(" Retry attempts: {}", config.retry_attempts);
|
||||||
|
|
||||||
|
// Test connection
|
||||||
|
println!("\n🔌 Testing PostgreSQL connection...");
|
||||||
|
match test_connection(config).await {
|
||||||
|
Ok(()) => {
|
||||||
|
println!("✅ All PostgreSQL tests passed successfully!");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("❌ PostgreSQL test failed: {}", e);
|
||||||
|
Err(e.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn test_connection(config: PostgresConfig) -> Result<(), PostgresError> {
|
||||||
|
// Create connection
|
||||||
|
println!(" Creating PostgreSQL connection...");
|
||||||
|
let postgres_conn = PostgresConnection::new(config).await?;
|
||||||
|
let connection = Arc::new(postgres_conn);
|
||||||
|
println!(" ✅ Connection established successfully");
|
||||||
|
|
||||||
|
// Test basic connectivity
|
||||||
|
println!(" Testing basic connectivity...");
|
||||||
|
test_basic_connectivity(&connection).await?;
|
||||||
|
println!(" ✅ Basic connectivity test passed");
|
||||||
|
|
||||||
|
// Test table existence
|
||||||
|
println!(" Testing table existence...");
|
||||||
|
test_table_existence(&connection).await?;
|
||||||
|
println!(" ✅ Table existence test passed");
|
||||||
|
|
||||||
|
// Test CRUD operations
|
||||||
|
println!(" Testing CRUD operations...");
|
||||||
|
test_crud_operations(&connection).await?;
|
||||||
|
println!(" ✅ CRUD operations test passed");
|
||||||
|
|
||||||
|
// Test transaction support
|
||||||
|
println!(" Testing transaction support...");
|
||||||
|
test_transactions(&connection).await?;
|
||||||
|
println!(" ✅ Transaction support test passed");
|
||||||
|
|
||||||
|
// Test error handling
|
||||||
|
println!(" Testing error handling...");
|
||||||
|
test_error_handling(&connection).await?;
|
||||||
|
println!(" ✅ Error handling test passed");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn test_basic_connectivity(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||||
|
// Execute a simple query
|
||||||
|
let statement = sea_orm::Statement::from_string(
|
||||||
|
connection.get_database_backend(),
|
||||||
|
"SELECT 1 as test_value, current_timestamp as current_time".to_string()
|
||||||
|
);
|
||||||
|
|
||||||
|
let result = connection.query_one(statement).await?
|
||||||
|
.ok_or_else(|| PostgresError::ConnectionError(sea_orm::DbErr::Custom("No results returned".to_string())))?;
|
||||||
|
|
||||||
|
// Verify we got expected results
|
||||||
|
let test_value: Option<i32> = result.try_get("", "test_value").ok();
|
||||||
|
let current_time: Option<String> = result.try_get("", "current_time").ok();
|
||||||
|
|
||||||
|
if test_value != Some(1) {
|
||||||
|
return Err(PostgresError::ConnectionError(sea_orm::DbErr::Custom(
|
||||||
|
format!("Expected test_value=1, got {:?}", test_value)
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if current_time.is_none() {
|
||||||
|
return Err(PostgresError::ConnectionError(sea_orm::DbErr::Custom(
|
||||||
|
"Expected current_time to be set".to_string()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
println!(" 📝 Query result: test_value={:?}, current_time={:?}", test_value, current_time);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn test_table_existence(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||||
|
// Test if our tables exist
|
||||||
|
use sea_orm::EntityTrait;
|
||||||
|
|
||||||
|
println!(" 📋 Checking users table...");
|
||||||
|
let user_count = UsersEntity::find()
|
||||||
|
.count(&connection.conn)
|
||||||
|
.await
|
||||||
|
.map_err(PostgresError::ConnectionError)?;
|
||||||
|
println!(" 📊 Users table accessible, current count: {}", user_count);
|
||||||
|
|
||||||
|
println!(" 📋 Checking roles table...");
|
||||||
|
let role_count = RolesEntity::find()
|
||||||
|
.count(&connection.conn)
|
||||||
|
.await
|
||||||
|
.map_err(PostgresError::ConnectionError)?;
|
||||||
|
println!(" 📊 Roles table accessible, current count: {}", role_count);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn test_crud_operations(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||||
|
use sea_orm::{ActiveModelTrait, Set};
|
||||||
|
|
||||||
|
// Create test user
|
||||||
|
println!(" ➕ Creating test user...");
|
||||||
|
let test_user_id = Uuid::new_v4();
|
||||||
|
let now = Utc::now();
|
||||||
|
|
||||||
|
let user_model = imphnen_entities::seaorm::auth::users::ActiveModel {
|
||||||
|
id: Set(test_user_id),
|
||||||
|
email: Set(format!("test_user_{}@example.com", test_user_id)),
|
||||||
|
password_hash: Set("test_password_hash".to_string()),
|
||||||
|
username: Set(format!("testuser_{}", test_user_id)),
|
||||||
|
first_name: Set(Some("Test".to_string())),
|
||||||
|
last_name: Set(Some("User".to_string())),
|
||||||
|
avatar_url: Set(None),
|
||||||
|
is_verified: Set(false),
|
||||||
|
is_active: Set(true),
|
||||||
|
metadata: Set(None),
|
||||||
|
role_id: Set(None),
|
||||||
|
created_at: Set(now),
|
||||||
|
updated_at: Set(now),
|
||||||
|
deleted_at: Set(None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let created_user = user_model.insert(&connection.conn)
|
||||||
|
.await
|
||||||
|
.map_err(PostgresError::ConnectionError)?;
|
||||||
|
|
||||||
|
println!(" ✅ Created user with ID: {}", created_user.id);
|
||||||
|
|
||||||
|
// Read user
|
||||||
|
println!(" 🔍 Reading test user...");
|
||||||
|
let found_user = UsersEntity::find_by_id(test_user_id)
|
||||||
|
.one(&connection.conn)
|
||||||
|
.await
|
||||||
|
.map_err(PostgresError::ConnectionError)?
|
||||||
|
.ok_or_else(|| PostgresError::ConnectionError(sea_orm::DbErr::Custom("User not found after creation".to_string())))?;
|
||||||
|
|
||||||
|
println!(" ✅ Found user: {} ({})", found_user.username, found_user.email);
|
||||||
|
|
||||||
|
// Update user
|
||||||
|
println!(" ✏️ Updating test user...");
|
||||||
|
let mut update_model: imphnen_entities::seaorm::auth::users::ActiveModel = found_user.into();
|
||||||
|
update_model.first_name = Set(Some("Updated".to_string()));
|
||||||
|
update_model.updated_at = Set(Utc::now());
|
||||||
|
|
||||||
|
let updated_user = update_model.update(&connection.conn)
|
||||||
|
.await
|
||||||
|
.map_err(PostgresError::ConnectionError)?;
|
||||||
|
|
||||||
|
println!(" ✅ Updated user first name to: {:?}", updated_user.first_name);
|
||||||
|
|
||||||
|
// Delete user
|
||||||
|
println!(" 🗑️ Deleting test user...");
|
||||||
|
UsersEntity::delete_by_id(updated_user.id)
|
||||||
|
.exec(&connection.conn)
|
||||||
|
.await
|
||||||
|
.map_err(PostgresError::ConnectionError)?;
|
||||||
|
|
||||||
|
println!(" ✅ Test user deleted successfully");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn test_transactions(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||||
|
println!(" 💰 Testing transaction support...");
|
||||||
|
|
||||||
|
// Test transaction with rollback
|
||||||
|
let transaction_result = connection.conn.transaction(|txn| {
|
||||||
|
Box::pin(async move {
|
||||||
|
// Create a test user within transaction
|
||||||
|
let test_user_id = Uuid::new_v4();
|
||||||
|
let now = Utc::now();
|
||||||
|
|
||||||
|
let user_model = imphnen_entities::seaorm::auth::users::ActiveModel {
|
||||||
|
id: Set(test_user_id),
|
||||||
|
email: Set(format!("transaction_test_{}@example.com", test_user_id)),
|
||||||
|
password_hash: Set("transaction_password_hash".to_string()),
|
||||||
|
username: Set(format!("transaction_user_{}", test_user_id)),
|
||||||
|
first_name: Set(Some("Transaction".to_string())),
|
||||||
|
last_name: Set(Some("Test".to_string())),
|
||||||
|
avatar_url: Set(None),
|
||||||
|
is_verified: Set(false),
|
||||||
|
is_active: Set(true),
|
||||||
|
metadata: Set(None),
|
||||||
|
role_id: Set(None),
|
||||||
|
created_at: Set(now),
|
||||||
|
updated_at: Set(now),
|
||||||
|
deleted_at: Set(None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let _created_user = user_model.insert(txn)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Simulate an error to trigger rollback (return a sea_orm::DbErr so the TransactionError matches)
|
||||||
|
Err::<(), DbErr>(DbErr::Custom("Simulated transaction failure".to_string()))
|
||||||
|
})
|
||||||
|
}).await;
|
||||||
|
|
||||||
|
// Transaction should fail and rollback
|
||||||
|
match transaction_result {
|
||||||
|
Err(e) => {
|
||||||
|
let e_text = format!("{:?}", e);
|
||||||
|
if e_text.contains("Simulated transaction failure") {
|
||||||
|
println!(" ✅ Transaction failed as expected, rollback successful");
|
||||||
|
} else {
|
||||||
|
return Err(PostgresError::OperationFailed(format!("Unexpected transaction result: {}", e_text)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(_) => {
|
||||||
|
return Err(PostgresError::OperationFailed("Unexpected transaction result: transaction unexpectedly succeeded".to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify user was not created (due to rollback)
|
||||||
|
let user_exists = UsersEntity::find_by_id(Uuid::nil()) // Use nil UUID as we don't know the actual ID
|
||||||
|
.one(&connection.conn)
|
||||||
|
.await
|
||||||
|
.map_err(PostgresError::ConnectionError)?
|
||||||
|
.is_some();
|
||||||
|
|
||||||
|
if user_exists {
|
||||||
|
println!(" ⚠️ User found despite rollback - this might indicate an issue");
|
||||||
|
} else {
|
||||||
|
println!(" ✅ Transaction rollback verified - user not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn test_error_handling(connection: &Arc<PostgresConnection>) -> Result<(), PostgresError> {
|
||||||
|
println!(" ⚠️ Testing error handling...");
|
||||||
|
|
||||||
|
// Test invalid UUID
|
||||||
|
println!(" 🔍 Testing invalid UUID handling...");
|
||||||
|
let invalid_uuid = Uuid::nil(); // This should exist or be handled gracefully
|
||||||
|
|
||||||
|
match UsersEntity::find_by_id(invalid_uuid)
|
||||||
|
.one(&connection.conn)
|
||||||
|
.await
|
||||||
|
.map_err(PostgresError::ConnectionError)?
|
||||||
|
{
|
||||||
|
Some(_) => println!(" ✅ Found user with nil UUID (expected in some cases)"),
|
||||||
|
None => println!(" ✅ No user found with nil UUID (expected)"),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test invalid query
|
||||||
|
println!(" 🔍 Testing invalid query handling...");
|
||||||
|
let invalid_statement = sea_orm::Statement::from_string(
|
||||||
|
connection.get_database_backend(),
|
||||||
|
"SELECT * FROM non_existent_table".to_string()
|
||||||
|
);
|
||||||
|
|
||||||
|
match connection.execute(invalid_statement).await {
|
||||||
|
Err(_) => println!(" ✅ Invalid query properly handled with error"),
|
||||||
|
Ok(_) => println!(" ⚠️ Invalid query unexpectedly succeeded"),
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional utility functions for comprehensive testing
|
||||||
|
pub mod test_utils {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Create a test PostgreSQL configuration
|
||||||
|
pub fn create_test_config() -> PostgresConfig {
|
||||||
|
PostgresConfig {
|
||||||
|
database_url: "postgres://postgres:postgres@localhost:5432/imphnen_test".to_string(),
|
||||||
|
pool_size: 5,
|
||||||
|
connect_timeout: 10,
|
||||||
|
idle_timeout: 30,
|
||||||
|
max_lifetime: Some(600),
|
||||||
|
retry_attempts: 2,
|
||||||
|
retry_delay: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a test user model
|
||||||
|
pub fn create_test_user_model() -> UserModel {
|
||||||
|
UserModel {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
email: format!("test_{}@example.com", Uuid::new_v4()),
|
||||||
|
password_hash: "test_password_hash".to_string(),
|
||||||
|
username: format!("testuser_{}", Uuid::new_v4()),
|
||||||
|
first_name: Some("Test".to_string()),
|
||||||
|
last_name: Some("User".to_string()),
|
||||||
|
avatar_url: None,
|
||||||
|
is_verified: false,
|
||||||
|
is_active: true,
|
||||||
|
metadata: None,
|
||||||
|
role_id: None,
|
||||||
|
created_at: Utc::now(),
|
||||||
|
updated_at: Utc::now(),
|
||||||
|
deleted_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a test role model
|
||||||
|
pub fn create_test_role_model() -> RoleModel {
|
||||||
|
RoleModel {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
name: format!("test_role_{}", Uuid::new_v4()),
|
||||||
|
description: "Test role description".to_string(),
|
||||||
|
permissions: Some(serde_json::json!(["test.permission"])),
|
||||||
|
is_system_role: false,
|
||||||
|
is_default: false,
|
||||||
|
created_at: Utc::now(),
|
||||||
|
updated_at: Utc::now(),
|
||||||
|
deleted_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_create_test_config() {
|
||||||
|
let config = test_utils::create_test_config();
|
||||||
|
assert_eq!(config.pool_size, 5);
|
||||||
|
assert_eq!(config.connect_timeout, 10);
|
||||||
|
assert!(config.database_url.contains("imphnen_test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_create_test_user_model() {
|
||||||
|
let user = test_utils::create_test_user_model();
|
||||||
|
assert!(!user.email.is_empty());
|
||||||
|
assert!(!user.username.is_empty());
|
||||||
|
assert!(user.is_active);
|
||||||
|
// is_admin field removed; instead, check role-based permission or is_active
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_create_test_role_model() {
|
||||||
|
let role = test_utils::create_test_role_model();
|
||||||
|
assert!(!role.name.is_empty());
|
||||||
|
assert!(role.permissions.is_some());
|
||||||
|
assert!(!role.is_system_role);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
use imphnen_gateway::gateway_service;
|
||||||
|
use imphnen_libs::axum_init;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
let _ = axum_init(|postgres_conn| async {
|
||||||
|
// PostgreSQL is now the primary database - SurrealDB has been completely removed
|
||||||
|
gateway_service(postgres_conn).await
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
[package]
|
||||||
|
name = "imphnen-cms"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
imphnen-iam.workspace = true
|
||||||
|
imphnen-libs.workspace = true
|
||||||
|
imphnen-utils.workspace = true
|
||||||
|
imphnen-entities.workspace = true
|
||||||
|
axum.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
utoipa.workspace = true
|
||||||
|
lazy_static.workspace = true
|
||||||
|
regex.workspace = true
|
||||||
|
validator.workspace = true
|
||||||
|
axum-test.workspace = true
|
||||||
|
rand.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
chrono.workspace = true
|
||||||
|
anyhow.workspace = true
|
||||||
|
tower-http.workspace = true
|
||||||
|
utoipa-swagger-ui.workspace = true
|
||||||
|
log.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
sea-orm.workspace = true
|
||||||
|
uuid.workspace = true
|
||||||
|
|
||||||
|
[package.metadata.validator.regex]
|
||||||
|
VALID_URL_REGEX = "^https?://"
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
pub mod v1;
|
||||||
|
|
||||||
|
pub use v1::landing;
|
||||||
|
pub use v1::landing::events;
|
||||||
|
pub use v1::landing::testimonials;
|
||||||
|
pub use v1::landing::events::events_public_routes;
|
||||||
|
pub use v1::landing::events::events_protected_routes;
|
||||||
|
pub use v1::landing::testimonials::testimonials_public_routes;
|
||||||
|
pub use v1::landing::testimonials::testimonials_protected_routes;
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
use super::{
|
||||||
|
events_dto::{
|
||||||
|
EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto,
|
||||||
|
EventsUpdateRequestDto,
|
||||||
|
},
|
||||||
|
events_service::EventsService,
|
||||||
|
};
|
||||||
|
use axum::extract::{Path, Query};
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::{Extension, http::HeaderMap, http::StatusCode};
|
||||||
|
use imphnen_libs::{
|
||||||
|
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
|
||||||
|
ResponseSuccessDto, ValidatedJson,
|
||||||
|
};
|
||||||
|
use imphnen_iam::{PermissionsEnum, require_permissions};
|
||||||
|
use imphnen_utils::common_response;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/v1/cms/landing/events",
|
||||||
|
params(
|
||||||
|
("page" = Option<i64>, Query, description = "Page number"),
|
||||||
|
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||||
|
("search" = Option<String>, Query, description = "Search keyword"),
|
||||||
|
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||||
|
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||||
|
("filter" = Option<String>, Query, description = "Filter value"),
|
||||||
|
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||||
|
),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "[PUBLIC] Get event list", body = ResponseListSuccessDto<Vec<EventsListItemDto>>)
|
||||||
|
),
|
||||||
|
tag = "Events"
|
||||||
|
)]
|
||||||
|
pub async fn get_event_list(
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Query(meta): Query<MetaRequestDto>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
EventsService::get_event_list(&state, meta).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/v1/cms/landing/events/detail/{id}",
|
||||||
|
params(
|
||||||
|
("id" = String, Path, description = "Event ID")
|
||||||
|
),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "[PUBLIC] Get event by ID", body = ResponseSuccessDto<EventsDetailItemDto>)
|
||||||
|
),
|
||||||
|
tag = "Events"
|
||||||
|
)]
|
||||||
|
pub async fn get_event_by_id(
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
let parsed_id = match Uuid::parse_str(&id) {
|
||||||
|
Ok(uuid) => uuid,
|
||||||
|
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
|
||||||
|
};
|
||||||
|
EventsService::get_event_by_id(&state, parsed_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
security(
|
||||||
|
("Bearer" = [])
|
||||||
|
),
|
||||||
|
path = "/v1/cms/landing/events/create",
|
||||||
|
request_body = EventsCreateRequestDto,
|
||||||
|
responses(
|
||||||
|
(status = 201, description = "[ADMIN] Create new event", body = MessageResponseDto)
|
||||||
|
),
|
||||||
|
tag = "Events"
|
||||||
|
)]
|
||||||
|
pub async fn post_create_event(
|
||||||
|
headers: HeaderMap,
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
ValidatedJson(payload): ValidatedJson<EventsCreateRequestDto>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||||
|
EventsService::create_event(&state, payload).await
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
patch,
|
||||||
|
security(
|
||||||
|
("Bearer" = [])
|
||||||
|
),
|
||||||
|
path = "/v1/cms/landing/events/update/{id}",
|
||||||
|
params(
|
||||||
|
("id" = String, Path, description = "Event ID")
|
||||||
|
),
|
||||||
|
request_body = EventsUpdateRequestDto,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "[ADMIN] Update event", body = MessageResponseDto)
|
||||||
|
),
|
||||||
|
tag = "Events"
|
||||||
|
)]
|
||||||
|
pub async fn patch_update_event(
|
||||||
|
headers: HeaderMap,
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
ValidatedJson(payload): ValidatedJson<EventsUpdateRequestDto>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||||
|
EventsService::update_event(&state, id, payload).await
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
delete,
|
||||||
|
security(
|
||||||
|
("Bearer" = [])
|
||||||
|
),
|
||||||
|
path = "/v1/cms/landing/events/delete/{id}",
|
||||||
|
params(
|
||||||
|
("id" = String, Path, description = "Event ID")
|
||||||
|
),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "[ADMIN] Soft delete event", body = MessageResponseDto)
|
||||||
|
),
|
||||||
|
tag = "Events"
|
||||||
|
)]
|
||||||
|
pub async fn delete_event(
|
||||||
|
headers: HeaderMap,
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||||
|
let parsed_id = match Uuid::parse_str(&id) {
|
||||||
|
Ok(uuid) => uuid,
|
||||||
|
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
|
||||||
|
};
|
||||||
|
EventsService::delete_event(&state, parsed_id).await
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use regex::Regex;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
use validator::{Validate, ValidationError};
|
||||||
|
|
||||||
|
// Custom URL validator that ensures valid HTTP/HTTPS URLs
|
||||||
|
static VALID_URL_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^https?://[^\s$.?#].[^\s]*$").unwrap());
|
||||||
|
|
||||||
|
pub fn validate_url(url: &str) -> Result<(), ValidationError> {
|
||||||
|
if VALID_URL_REGEX.is_match(url) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(ValidationError::new("invalid_url"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom validator for future dates
|
||||||
|
pub fn validate_future_date(end_date: &DateTime<Utc>) -> Result<(), ValidationError> {
|
||||||
|
let now = Utc::now();
|
||||||
|
if end_date > &now {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(ValidationError::new("future_date"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom validator for event date ranges (for combined validation)
|
||||||
|
pub fn validate_date_range(start_date: &DateTime<Utc>, end_date: &DateTime<Utc>) -> Result<(), ValidationError> {
|
||||||
|
if start_date <= end_date {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(ValidationError::new("date_range"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
|
pub struct EventsCreateRequestDto {
|
||||||
|
#[validate(length(min = 1, max = 100, message = "Name must be between 1 and 100 characters"))]
|
||||||
|
pub name: String,
|
||||||
|
|
||||||
|
#[validate(length(min = 1, max = 1000, message = "Description must be between 1 and 1000 characters"))]
|
||||||
|
pub description: String,
|
||||||
|
|
||||||
|
#[validate(custom(
|
||||||
|
function = "validate_url",
|
||||||
|
message = "Detail link must be a valid HTTP/HTTPS URL"
|
||||||
|
))]
|
||||||
|
pub detail_link: String,
|
||||||
|
|
||||||
|
#[validate(range(min = 0.0, max = 1_000_000.0, message = "Price must be between 0 and 1,000,000"))]
|
||||||
|
pub price: f64,
|
||||||
|
|
||||||
|
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||||
|
#[validate(custom(
|
||||||
|
function = "validate_future_date",
|
||||||
|
message = "End date must be in the future"
|
||||||
|
))]
|
||||||
|
pub end_date: DateTime<Utc>,
|
||||||
|
|
||||||
|
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||||
|
pub start_date: DateTime<Utc>,
|
||||||
|
|
||||||
|
#[validate(length(max = 200, message = "Location name cannot exceed 200 characters"))]
|
||||||
|
pub location: Option<String>,
|
||||||
|
pub is_online: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
|
pub struct EventsUpdateRequestDto {
|
||||||
|
#[validate(length(min = 1, message = "Name is required"))]
|
||||||
|
pub name: String,
|
||||||
|
|
||||||
|
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||||
|
pub end_date: DateTime<Utc>,
|
||||||
|
|
||||||
|
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||||
|
pub start_date: DateTime<Utc>,
|
||||||
|
|
||||||
|
#[validate(range(min = 0.0, message = "Price cannot be negative"))]
|
||||||
|
pub price: f64,
|
||||||
|
pub is_online: bool,
|
||||||
|
pub description: String,
|
||||||
|
#[validate(url(message = "Detail link must be a valid URL"))]
|
||||||
|
pub detail_link: String,
|
||||||
|
pub location: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
|
pub struct EventsListItemDto {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub detail_link: String,
|
||||||
|
pub price: f64,
|
||||||
|
pub is_online: bool,
|
||||||
|
pub start_date: String,
|
||||||
|
pub end_date: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub location: Option<String>,
|
||||||
|
pub is_deleted: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
|
pub struct EventsDetailItemDto {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub detail_link: String,
|
||||||
|
pub price: f64,
|
||||||
|
pub is_online: bool,
|
||||||
|
pub start_date: String,
|
||||||
|
pub end_date: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub updated_at: String,
|
||||||
|
pub location: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct EventsQueryDto {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub detail_link: String,
|
||||||
|
pub price: f64,
|
||||||
|
pub is_online: bool,
|
||||||
|
pub is_deleted: bool,
|
||||||
|
pub start_date: String,
|
||||||
|
pub end_date: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub updated_at: String,
|
||||||
|
pub location: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventsQueryDto {
|
||||||
|
pub fn from(self) -> EventsListItemDto {
|
||||||
|
EventsListItemDto {
|
||||||
|
id: self.id,
|
||||||
|
name: self.name,
|
||||||
|
description: self.description,
|
||||||
|
detail_link: self.detail_link,
|
||||||
|
price: self.price,
|
||||||
|
location: self.location,
|
||||||
|
is_online: self.is_online,
|
||||||
|
start_date: self.start_date,
|
||||||
|
end_date: self.end_date,
|
||||||
|
created_at: self.created_at,
|
||||||
|
is_deleted: self.is_deleted,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
use sea_orm::prelude::*;
|
||||||
|
use sea_orm::{ActiveValue, QueryOrder};
|
||||||
|
use std::time::Instant;
|
||||||
|
use tracing::instrument;
|
||||||
|
use uuid::Uuid; // Added Uuid import
|
||||||
|
use imphnen_entities::seaorm::common::events::{Entity as EventsEntity, Column as EventsColumn, Model as EventsModel};
|
||||||
|
use imphnen_libs::{AppState, MetaRequestDto, ResponseListSuccessDto, AppStatePostgresExt};
|
||||||
|
use imphnen_utils::AppError;
|
||||||
|
use imphnen_utils::Result;
|
||||||
|
use crate::events::events_dto::EventsQueryDto;
|
||||||
|
use crate::events::events_schema::EventsSchema;
|
||||||
|
|
||||||
|
pub struct EventsRepository<'a> {
|
||||||
|
state: &'a AppState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> EventsRepository<'a> {
|
||||||
|
pub fn new(state: &'a AppState) -> Self {
|
||||||
|
Self { state }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, meta), err)]
|
||||||
|
pub async fn query_event_list(
|
||||||
|
&self,
|
||||||
|
meta: MetaRequestDto,
|
||||||
|
) -> Result<ResponseListSuccessDto<Vec<EventsQueryDto>>> {
|
||||||
|
let now = Instant::now();
|
||||||
|
let page = meta.page.unwrap_or(1);
|
||||||
|
let page_size = 10u64;
|
||||||
|
let _offset = (page - 1) * page_size;
|
||||||
|
|
||||||
|
let mut query = EventsEntity::find()
|
||||||
|
.filter(EventsColumn::IsDeleted.eq(false)); // Add sorting
|
||||||
|
if let Some(sort_by) = &meta.sort_by {
|
||||||
|
match sort_by.as_str() {
|
||||||
|
"created_at" => {
|
||||||
|
if meta.order.as_deref() == Some("desc") {
|
||||||
|
query = query.order_by_desc(EventsColumn::CreatedAt);
|
||||||
|
} else {
|
||||||
|
query = query.order_by_asc(EventsColumn::CreatedAt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"name" => {
|
||||||
|
if meta.order.as_deref() == Some("desc") {
|
||||||
|
query = query.order_by_desc(EventsColumn::Name);
|
||||||
|
} else {
|
||||||
|
query = query.order_by_asc(EventsColumn::Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
query = query.order_by_desc(EventsColumn::CreatedAt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
query = query.order_by_desc(EventsColumn::CreatedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
let paginator = query.paginate(self.state.postgres_db(), page_size);
|
||||||
|
let events: Vec<EventsModel> = paginator.fetch_page(page - 1).await?;
|
||||||
|
|
||||||
|
let res: Vec<EventsQueryDto> = events.into_iter().map(|model| EventsQueryDto {
|
||||||
|
id: model.id.to_string(),
|
||||||
|
name: model.name,
|
||||||
|
description: model.description,
|
||||||
|
detail_link: model.detail_link,
|
||||||
|
price: model.price,
|
||||||
|
is_online: model.is_online,
|
||||||
|
is_deleted: model.is_deleted,
|
||||||
|
start_date: model.start_date.to_rfc3339(),
|
||||||
|
end_date: model.end_date.to_rfc3339(),
|
||||||
|
created_at: model.created_at.to_rfc3339(),
|
||||||
|
updated_at: model.updated_at.to_rfc3339(),
|
||||||
|
location: model.location,
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
let elapsed = now.elapsed();
|
||||||
|
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||||
|
== "development"
|
||||||
|
{
|
||||||
|
println!("Query 'query_event_list' took: {elapsed:.2?}");
|
||||||
|
}
|
||||||
|
let data = ResponseListSuccessDto {
|
||||||
|
data: res,
|
||||||
|
meta: None,
|
||||||
|
};
|
||||||
|
Ok(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, id), err)]
|
||||||
|
pub async fn query_event_by_id(&self, id: Uuid) -> Result<EventsQueryDto> {
|
||||||
|
let now = Instant::now();
|
||||||
|
|
||||||
|
let event = EventsEntity::find_by_id(id)
|
||||||
|
.filter(EventsColumn::IsDeleted.eq(false))
|
||||||
|
.one(self.state.postgres_db())
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Event not found"))?;
|
||||||
|
|
||||||
|
let result = EventsQueryDto {
|
||||||
|
id: event.id.to_string(),
|
||||||
|
name: event.name,
|
||||||
|
description: event.description,
|
||||||
|
detail_link: event.detail_link,
|
||||||
|
price: event.price,
|
||||||
|
is_online: event.is_online,
|
||||||
|
is_deleted: event.is_deleted,
|
||||||
|
start_date: event.start_date.to_rfc3339(),
|
||||||
|
end_date: event.end_date.to_rfc3339(),
|
||||||
|
created_at: event.created_at.to_rfc3339(),
|
||||||
|
updated_at: event.updated_at.to_rfc3339(),
|
||||||
|
location: event.location,
|
||||||
|
};
|
||||||
|
|
||||||
|
let elapsed = now.elapsed();
|
||||||
|
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||||
|
== "development"
|
||||||
|
{
|
||||||
|
println!("Query 'query_event_by_id' took: {elapsed:.2?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, data), err)]
|
||||||
|
pub async fn query_create_event(&self, data: EventsSchema) -> Result<String> {
|
||||||
|
let now = Instant::now();
|
||||||
|
|
||||||
|
let active_model = imphnen_entities::seaorm::common::events::ActiveModel {
|
||||||
|
id: ActiveValue::Set(Uuid::parse_str(&data.id)?),
|
||||||
|
name: ActiveValue::Set(data.name),
|
||||||
|
description: ActiveValue::Set(data.description),
|
||||||
|
detail_link: ActiveValue::Set(data.detail_link),
|
||||||
|
price: ActiveValue::Set(data.price),
|
||||||
|
is_online: ActiveValue::Set(data.is_online),
|
||||||
|
is_deleted: ActiveValue::Set(data.is_deleted),
|
||||||
|
location: ActiveValue::Set(data.location),
|
||||||
|
start_date: ActiveValue::Set(chrono::DateTime::parse_from_rfc3339(&data.start_date)?.with_timezone(&chrono::Utc)),
|
||||||
|
end_date: ActiveValue::Set(chrono::DateTime::parse_from_rfc3339(&data.end_date)?.with_timezone(&chrono::Utc)),
|
||||||
|
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||||
|
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let _result = EventsEntity::insert(active_model).exec(self.state.postgres_db()).await?;
|
||||||
|
|
||||||
|
let elapsed = now.elapsed();
|
||||||
|
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||||
|
== "development"
|
||||||
|
{
|
||||||
|
println!("Query 'query_create_event' took: {elapsed:.2?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok("Success create event".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, data), err)]
|
||||||
|
pub async fn query_update_event(&self, data: EventsSchema) -> Result<String> {
|
||||||
|
let now = Instant::now();
|
||||||
|
|
||||||
|
let existing = self.query_event_by_id(Uuid::parse_str(&data.id)?).await?;
|
||||||
|
if existing.is_deleted {
|
||||||
|
return Err(AppError::BadRequestError("Event already deleted".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut active_model: imphnen_entities::seaorm::common::events::ActiveModel = EventsEntity::find_by_id(Uuid::parse_str(&data.id)?)
|
||||||
|
.one(self.state.postgres_db())
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Event not found"))?
|
||||||
|
.into();
|
||||||
|
|
||||||
|
active_model.name = ActiveValue::Set(data.name);
|
||||||
|
active_model.description = ActiveValue::Set(data.description);
|
||||||
|
active_model.detail_link = ActiveValue::Set(data.detail_link);
|
||||||
|
active_model.price = ActiveValue::Set(data.price);
|
||||||
|
active_model.is_online = ActiveValue::Set(data.is_online);
|
||||||
|
active_model.location = ActiveValue::Set(data.location);
|
||||||
|
active_model.start_date = ActiveValue::Set(chrono::DateTime::parse_from_rfc3339(&data.start_date)?.with_timezone(&chrono::Utc));
|
||||||
|
active_model.end_date = ActiveValue::Set(chrono::DateTime::parse_from_rfc3339(&data.end_date)?.with_timezone(&chrono::Utc));
|
||||||
|
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||||
|
|
||||||
|
active_model.update(self.state.postgres_db()).await?;
|
||||||
|
|
||||||
|
let elapsed = now.elapsed();
|
||||||
|
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||||
|
== "development"
|
||||||
|
{
|
||||||
|
println!("Query 'query_update_event' took: {elapsed:.2?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok("Success update event".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, id), err)]
|
||||||
|
pub async fn query_delete_event(&self, id: Uuid) -> Result<String> {
|
||||||
|
let now = Instant::now();
|
||||||
|
let event = self.query_event_by_id(id).await?;
|
||||||
|
if event.is_deleted {
|
||||||
|
return Err(AppError::NotFoundError("Event not found".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut active_model: imphnen_entities::seaorm::common::events::ActiveModel = EventsEntity::find_by_id(id)
|
||||||
|
.one(self.state.postgres_db())
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Event not found"))?
|
||||||
|
.into();
|
||||||
|
|
||||||
|
active_model.is_deleted = ActiveValue::Set(true);
|
||||||
|
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||||
|
|
||||||
|
active_model.update(self.state.postgres_db()).await?;
|
||||||
|
|
||||||
|
let elapsed = now.elapsed();
|
||||||
|
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||||
|
== "development"
|
||||||
|
{
|
||||||
|
println!("Query 'query_delete_event' took: {elapsed:.2?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok("Success delete event".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
use imphnen_utils::get_iso_date;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::events_dto::{
|
||||||
|
EventsCreateRequestDto, EventsQueryDto, EventsUpdateRequestDto,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct EventsSchema {
|
||||||
|
pub id: String,
|
||||||
|
pub price: f64,
|
||||||
|
pub is_online: bool,
|
||||||
|
pub is_deleted: bool,
|
||||||
|
pub name: String,
|
||||||
|
pub end_date: String,
|
||||||
|
pub start_date: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub updated_at: String,
|
||||||
|
pub description: String,
|
||||||
|
pub detail_link: String,
|
||||||
|
pub location: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for EventsSchema {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
id: Uuid::new_v4().to_string(),
|
||||||
|
name: String::new(),
|
||||||
|
description: String::new(),
|
||||||
|
detail_link: String::new(),
|
||||||
|
price: 0.0,
|
||||||
|
location: None,
|
||||||
|
is_online: false,
|
||||||
|
is_deleted: false,
|
||||||
|
start_date: String::new(),
|
||||||
|
end_date: String::new(),
|
||||||
|
created_at: get_iso_date(),
|
||||||
|
updated_at: get_iso_date(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventsSchema {
|
||||||
|
pub fn from(dto: EventsQueryDto) -> Self {
|
||||||
|
Self {
|
||||||
|
id: dto.id,
|
||||||
|
name: dto.name,
|
||||||
|
description: dto.description,
|
||||||
|
detail_link: dto.detail_link,
|
||||||
|
price: dto.price,
|
||||||
|
location: dto.location,
|
||||||
|
is_online: dto.is_online,
|
||||||
|
is_deleted: false,
|
||||||
|
start_date: dto.start_date,
|
||||||
|
end_date: dto.end_date,
|
||||||
|
created_at: dto.created_at,
|
||||||
|
updated_at: dto.updated_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create(payload: EventsCreateRequestDto) -> Self {
|
||||||
|
Self {
|
||||||
|
id: Uuid::new_v4().to_string(),
|
||||||
|
name: payload.name,
|
||||||
|
description: payload.description,
|
||||||
|
detail_link: payload.detail_link,
|
||||||
|
price: payload.price,
|
||||||
|
location: payload.location,
|
||||||
|
is_online: payload.is_online,
|
||||||
|
is_deleted: false,
|
||||||
|
end_date: payload.end_date.to_string(),
|
||||||
|
start_date: payload.start_date.to_string(),
|
||||||
|
created_at: get_iso_date(),
|
||||||
|
updated_at: get_iso_date(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(payload: EventsUpdateRequestDto, id: String) -> Self {
|
||||||
|
Self {
|
||||||
|
id,
|
||||||
|
name: payload.name,
|
||||||
|
price: payload.price,
|
||||||
|
location: payload.location,
|
||||||
|
is_online: payload.is_online,
|
||||||
|
description: payload.description,
|
||||||
|
detail_link: payload.detail_link,
|
||||||
|
end_date: payload.end_date.to_string(),
|
||||||
|
start_date: payload.start_date.to_string(),
|
||||||
|
updated_at: get_iso_date(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
use super::{
|
||||||
|
events_dto::{
|
||||||
|
EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto, EventsQueryDto,
|
||||||
|
EventsUpdateRequestDto,
|
||||||
|
},
|
||||||
|
events_repository::EventsRepository,
|
||||||
|
events_schema::EventsSchema,
|
||||||
|
};
|
||||||
|
use axum::{http::StatusCode, response::Response};
|
||||||
|
use imphnen_libs::{
|
||||||
|
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||||
|
};
|
||||||
|
use imphnen_utils::{
|
||||||
|
common_response, success_list_response, success_response, validate_request,
|
||||||
|
};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub struct EventsService;
|
||||||
|
|
||||||
|
impl EventsService {
|
||||||
|
pub async fn get_event_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||||
|
let repo = EventsRepository::new(state);
|
||||||
|
match repo.query_event_list(meta).await {
|
||||||
|
Ok(data) => {
|
||||||
|
let items: Vec<EventsListItemDto> = data
|
||||||
|
.data
|
||||||
|
.into_iter()
|
||||||
|
.filter(|e| !e.is_deleted)
|
||||||
|
.map(EventsQueryDto::from)
|
||||||
|
.collect();
|
||||||
|
let response = ResponseListSuccessDto {
|
||||||
|
data: items,
|
||||||
|
meta: data.meta,
|
||||||
|
};
|
||||||
|
success_list_response(response)
|
||||||
|
}
|
||||||
|
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_event_by_id(state: &AppState, id: Uuid) -> Response {
|
||||||
|
let repo = EventsRepository::new(state);
|
||||||
|
match repo.query_event_by_id(id).await {
|
||||||
|
Ok(event) if !event.is_deleted => success_response(ResponseSuccessDto {
|
||||||
|
data: EventsDetailItemDto {
|
||||||
|
id: event.id,
|
||||||
|
name: event.name,
|
||||||
|
description: event.description,
|
||||||
|
detail_link: event.detail_link,
|
||||||
|
price: event.price,
|
||||||
|
is_online: event.is_online,
|
||||||
|
start_date: event.start_date,
|
||||||
|
end_date: event.end_date,
|
||||||
|
created_at: event.created_at,
|
||||||
|
updated_at: event.updated_at,
|
||||||
|
location: event.location,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
Ok(_) => common_response(StatusCode::NOT_FOUND, "Event not found"),
|
||||||
|
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_event(
|
||||||
|
state: &AppState,
|
||||||
|
payload: EventsCreateRequestDto,
|
||||||
|
) -> Response {
|
||||||
|
if let Err((status, message)) = validate_request(&payload) {
|
||||||
|
return common_response(status, &message);
|
||||||
|
}
|
||||||
|
let repo = EventsRepository::new(state);
|
||||||
|
let schema = EventsSchema::create(payload);
|
||||||
|
match repo.query_create_event(schema).await {
|
||||||
|
Ok(msg) => common_response(StatusCode::CREATED, msg.as_str()),
|
||||||
|
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_event(
|
||||||
|
state: &AppState,
|
||||||
|
id: String,
|
||||||
|
payload: EventsUpdateRequestDto,
|
||||||
|
) -> Response {
|
||||||
|
if let Err((status, message)) = validate_request(&payload) {
|
||||||
|
return common_response(status, &message);
|
||||||
|
}
|
||||||
|
let repo = EventsRepository::new(state);
|
||||||
|
let schema = EventsSchema::update(payload, id);
|
||||||
|
match repo.query_update_event(schema).await {
|
||||||
|
Ok(msg) => common_response(StatusCode::OK, msg.as_str()),
|
||||||
|
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_event(state: &AppState, id: Uuid) -> Response {
|
||||||
|
let repo = EventsRepository::new(state);
|
||||||
|
match repo.query_delete_event(id).await {
|
||||||
|
Ok(msg) => common_response(StatusCode::OK, msg.as_str()),
|
||||||
|
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
use axum::{
|
||||||
|
Router,
|
||||||
|
routing::{delete, get, patch, post},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub mod events_controller;
|
||||||
|
pub mod events_dto;
|
||||||
|
pub mod events_repository;
|
||||||
|
pub mod events_schema;
|
||||||
|
pub mod events_service;
|
||||||
|
|
||||||
|
// Export only the necessary public items
|
||||||
|
pub use events_dto::{
|
||||||
|
EventsCreateRequestDto,
|
||||||
|
EventsUpdateRequestDto,
|
||||||
|
EventsListItemDto,
|
||||||
|
EventsDetailItemDto,
|
||||||
|
};
|
||||||
|
pub use events_controller::{
|
||||||
|
get_event_list,
|
||||||
|
get_event_by_id,
|
||||||
|
post_create_event,
|
||||||
|
patch_update_event,
|
||||||
|
delete_event,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn events_public_routes() -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/cms/landing/events", get(get_event_list))
|
||||||
|
.route("/cms/landing/events/detail/{id}", get(get_event_by_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn events_protected_routes() -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/cms/landing/events/create", post(post_create_event))
|
||||||
|
.route("/cms/landing/events/update/{id}", patch(patch_update_event))
|
||||||
|
.route("/cms/landing/events/delete/{id}", delete(delete_event))
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
pub mod events;
|
||||||
|
pub mod testimonials;
|
||||||
|
|
||||||
|
pub use events::events_public_routes;
|
||||||
|
pub use events::events_protected_routes;
|
||||||
|
pub use testimonials::testimonials_public_routes;
|
||||||
|
pub use testimonials::testimonials_protected_routes;
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
use axum::{
|
||||||
|
Router,
|
||||||
|
routing::{delete, get, patch, post},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub mod testimonials_controller;
|
||||||
|
pub mod testimonials_dto;
|
||||||
|
pub mod testimonials_repository;
|
||||||
|
pub mod testimonials_schema;
|
||||||
|
pub mod testimonials_service;
|
||||||
|
|
||||||
|
// Export only the necessary public items
|
||||||
|
pub use testimonials_dto::{
|
||||||
|
TestimonialsCreateRequestDto,
|
||||||
|
TestimonialsUpdateRequestDto,
|
||||||
|
TestimonialsListItemDto,
|
||||||
|
TestimonialsDetailItemDto,
|
||||||
|
};
|
||||||
|
pub use testimonials_controller::{
|
||||||
|
get_testimonial_list,
|
||||||
|
get_testimonial_by_id,
|
||||||
|
post_create_testimonial,
|
||||||
|
patch_update_testimonial,
|
||||||
|
delete_testimonial,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn testimonials_public_routes() -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/cms/landing/testimonials", get(get_testimonial_list))
|
||||||
|
.route("/cms/landing/testimonials/detail/{id}", get(get_testimonial_by_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn testimonials_protected_routes() -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/cms/landing/testimonials/create", post(post_create_testimonial))
|
||||||
|
.route("/cms/landing/testimonials/update/{id}", patch(patch_update_testimonial))
|
||||||
|
.route("/cms/landing/testimonials/delete/{id}", delete(delete_testimonial))
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
use super::{
|
||||||
|
testimonials_dto::{
|
||||||
|
TestimonialsCreateRequestDto, TestimonialsDetailItemDto,
|
||||||
|
TestimonialsListItemDto, TestimonialsUpdateRequestDto,
|
||||||
|
},
|
||||||
|
testimonials_service::TestimonialsService,
|
||||||
|
};
|
||||||
|
use axum::extract::{Path, Query};
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::{Extension, http::HeaderMap};
|
||||||
|
use imphnen_iam::{UsersDetailQueryDto, require_auth};
|
||||||
|
use imphnen_libs::{
|
||||||
|
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
|
||||||
|
ResponseSuccessDto, ValidatedJson,
|
||||||
|
};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use imphnen_utils::common_response;
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/v1/cms/landing/testimonials",
|
||||||
|
params(
|
||||||
|
("page" = Option<i64>, Query, description = "Page number"),
|
||||||
|
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||||
|
("search" = Option<String>, Query, description = "Search keyword"),
|
||||||
|
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||||
|
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||||
|
("filter" = Option<String>, Query, description = "Filter value"),
|
||||||
|
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||||
|
),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "[PUBLIC] Get testimonial list", body = ResponseListSuccessDto<Vec<TestimonialsListItemDto>>)
|
||||||
|
),
|
||||||
|
tag = "Testimonials"
|
||||||
|
)]
|
||||||
|
pub async fn get_testimonial_list(
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Query(meta): Query<MetaRequestDto>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
TestimonialsService::get_testimonial_list(&state, meta).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
get,
|
||||||
|
path = "/v1/cms/landing/testimonials/detail/{id}",
|
||||||
|
params(
|
||||||
|
("id" = String, Path, description = "Testimonial ID")
|
||||||
|
),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "[PUBLIC] Get testimonial by ID", body = ResponseSuccessDto<TestimonialsDetailItemDto>)
|
||||||
|
),
|
||||||
|
tag = "Testimonials"
|
||||||
|
)]
|
||||||
|
pub async fn get_testimonial_by_id(
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
let parsed_id = match Uuid::parse_str(&id) {
|
||||||
|
Ok(uuid) => uuid,
|
||||||
|
Err(e) => return common_response(axum::http::StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
|
||||||
|
};
|
||||||
|
TestimonialsService::get_testimonial_by_id(&state, parsed_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
post,
|
||||||
|
security(
|
||||||
|
("Bearer" = [])
|
||||||
|
),
|
||||||
|
path = "/v1/cms/landing/testimonials/create",
|
||||||
|
request_body = TestimonialsCreateRequestDto,
|
||||||
|
responses(
|
||||||
|
(status = 201, description = "[USER] Create new testimonial", body = MessageResponseDto)
|
||||||
|
),
|
||||||
|
tag = "Testimonials"
|
||||||
|
)]
|
||||||
|
pub async fn post_create_testimonial(
|
||||||
|
headers: HeaderMap,
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
|
||||||
|
ValidatedJson(payload): ValidatedJson<TestimonialsCreateRequestDto>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
require_auth!(headers, state, {
|
||||||
|
TestimonialsService::create_testimonial(&state, payload, &authenticated_user).await
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
patch,
|
||||||
|
security(
|
||||||
|
("Bearer" = [])
|
||||||
|
),
|
||||||
|
path = "/v1/cms/landing/testimonials/update/{id}",
|
||||||
|
params(
|
||||||
|
("id" = String, Path, description = "Testimonial ID")
|
||||||
|
),
|
||||||
|
request_body = TestimonialsUpdateRequestDto,
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "[USER] Update testimonial", body = MessageResponseDto)
|
||||||
|
),
|
||||||
|
tag = "Testimonials"
|
||||||
|
)]
|
||||||
|
pub async fn patch_update_testimonial(
|
||||||
|
headers: HeaderMap,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
|
||||||
|
ValidatedJson(payload): ValidatedJson<TestimonialsUpdateRequestDto>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
require_auth!(headers, state, {
|
||||||
|
TestimonialsService::update_testimonial(&state, id, payload, &authenticated_user).await
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[utoipa::path(
|
||||||
|
delete,
|
||||||
|
security(
|
||||||
|
("Bearer" = [])
|
||||||
|
),
|
||||||
|
path = "/v1/cms/landing/testimonials/delete/{id}",
|
||||||
|
params(
|
||||||
|
("id" = String, Path, description = "Testimonial ID")
|
||||||
|
),
|
||||||
|
responses(
|
||||||
|
(status = 200, description = "[USER] Soft delete testimonial", body = MessageResponseDto)
|
||||||
|
),
|
||||||
|
tag = "Testimonials"
|
||||||
|
)]
|
||||||
|
pub async fn delete_testimonial(
|
||||||
|
headers: HeaderMap,
|
||||||
|
Extension(state): Extension<AppState>,
|
||||||
|
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
require_auth!(headers, state, {
|
||||||
|
let parsed_id = match Uuid::parse_str(&id) {
|
||||||
|
Ok(uuid) => uuid,
|
||||||
|
Err(e) => return common_response(axum::http::StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
|
||||||
|
};
|
||||||
|
TestimonialsService::delete_testimonial(&state, parsed_id, &authenticated_user).await
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
use lazy_static::lazy_static;
|
||||||
|
use regex::Regex;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
use validator::{Validate, ValidationError};
|
||||||
|
|
||||||
|
// Custom validator for content length and format
|
||||||
|
pub fn validate_testimonial_content(content: &str) -> Result<(), ValidationError> {
|
||||||
|
lazy_static! {
|
||||||
|
static ref CONTENT_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9\s.,!?'-]+$").unwrap();
|
||||||
|
}
|
||||||
|
if CONTENT_REGEX.is_match(content) && content.len() <= 1000 {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(ValidationError::new("invalid_content"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
|
pub struct TestimonialsCreateRequestDto {
|
||||||
|
#[validate(length(min = 1, max = 100, message = "Role must be between 1 and 100 characters"))]
|
||||||
|
pub role: String,
|
||||||
|
|
||||||
|
#[validate(length(
|
||||||
|
min = 1,
|
||||||
|
max = 1000,
|
||||||
|
message = "Content must be between 1 and 1000 characters"
|
||||||
|
))]
|
||||||
|
#[validate(custom(
|
||||||
|
function = "validate_testimonial_content",
|
||||||
|
message = "Content contains invalid characters or is too long"
|
||||||
|
))]
|
||||||
|
pub content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||||
|
pub struct TestimonialsUpdateRequestDto {
|
||||||
|
#[validate(length(min = 1, max = 100, message = "Role must be between 1 and 100 characters"))]
|
||||||
|
pub role: String,
|
||||||
|
|
||||||
|
#[validate(length(
|
||||||
|
min = 1,
|
||||||
|
max = 1000,
|
||||||
|
message = "Content must be between 1 and 1000 characters"
|
||||||
|
))]
|
||||||
|
#[validate(custom(
|
||||||
|
function = "validate_testimonial_content",
|
||||||
|
message = "Content contains invalid characters or is too long"
|
||||||
|
))]
|
||||||
|
pub content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
|
pub struct TestimonialsListItemDto {
|
||||||
|
pub id: String,
|
||||||
|
pub user_id: String,
|
||||||
|
pub user_fullname: String,
|
||||||
|
pub role: String,
|
||||||
|
pub content: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub is_deleted: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
|
pub struct TestimonialsDetailItemDto {
|
||||||
|
pub id: String,
|
||||||
|
pub user_id: String,
|
||||||
|
pub user_fullname: String,
|
||||||
|
pub role: String,
|
||||||
|
pub content: String,
|
||||||
|
pub created_at: String,
|
||||||
|
pub updated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct TestimonialsQueryDto {
|
||||||
|
pub id: String,
|
||||||
|
pub user_id: String,
|
||||||
|
pub user_fullname: String,
|
||||||
|
pub role: String,
|
||||||
|
pub content: String,
|
||||||
|
pub is_deleted: bool,
|
||||||
|
pub created_at: String,
|
||||||
|
pub updated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestimonialsQueryDto {
|
||||||
|
pub fn from(self) -> TestimonialsListItemDto {
|
||||||
|
TestimonialsListItemDto {
|
||||||
|
id: self.id,
|
||||||
|
user_id: self.user_id,
|
||||||
|
user_fullname: self.user_fullname,
|
||||||
|
role: self.role,
|
||||||
|
content: self.content,
|
||||||
|
created_at: self.created_at,
|
||||||
|
is_deleted: self.is_deleted,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user