refactor: migrate to clean architecture with trait-based DI (v0.2.0)

Complete architectural overhaul across all 12 crates:

- Replace validator crate with zod-rs for all DTO validation
- Replace manual pagination with paginator-rs/paginator-sea-orm
- Migrate all modules (iam, cms, gacha, dimentorin) to clean architecture:
  domain → application → infrastructure layers
- Introduce trait-based DI (Arc<dyn Trait>) at every layer for repositories and services
- Delete all v1/ legacy SurrealDB-era code across every crate
- Replace opaque response helpers with typed IntoResponse structs (ApiSuccess, ApiCreated, ApiPaginated, ApiMessage)
- Remove dual_mode_repository, migration_validation_errors, validator.rs dead code
- Zero cargo clippy warnings; release build clean

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
maulanasdqn
2026-04-02 13:39:52 +07:00
co-authored by Claude Sonnet 4.6
parent 1b3366d735
commit e432a1a743
379 changed files with 9013 additions and 30532 deletions
-25
View File
@@ -1,28 +1,3 @@
# RUST_ENV : Mode environment aplikasi (misal: development, production)
# RUST_LOG : Level logging aplikasi Rust (misal: debug, info, warn, error)
# PORT : Port yang digunakan backend service
# SURREALDB_URL : URL koneksi ke SurrealDB (gunakan ws:// untuk WebSocket)
# SURREALDB_USERNAME : Username untuk SurrealDB
# SURREALDB_PASSWORD : Password untuk SurrealDB
# SURREALDB_NAMESPACE : Namespace SurrealDB yang digunakan
# SURREALDB_DBNAME : Nama database SurrealDB
# ACCESS_TOKEN_SECRET : Secret key untuk JWT access token (ganti dengan nilai rahasia)
# REFRESH_TOKEN_SECRET : Secret key untuk JWT refresh token (ganti dengan nilai rahasia)
# SMTP_EMAIL : Email yang digunakan untuk mengirim email (SMTP)
# SMTP_PASSWORD : Password email SMTP
# SMTP_NAME : Nama pengirim email (misal: nama aplikasi)
# SMTP_HOST : Host SMTP server (misal: smtp.gmail.com)
# REDISDB_URL : URL/host Redis database
# FE_URL : URL frontend aplikasi (misal: http://localhost)
# MINIO_ENDPOINT : Endpoint MinIO object storage
# MINIO_BUCKET_NAME : Nama bucket default MinIO
# MINIO_ACCESS_KEY : Access key MinIO atau MINIO_ROOT_USER
# MINIO_SECRET_KEY : Secret key MinIO atau MINIO_ROOT_PASSWORD
# MINIO_ROOT_USER : Username root MinIO (default: minioadmin)
# MINIO_ROOT_PASSWORD : Password root MinIO (default: minioadmin)
# GOOGLE_CLIENT_ID : Client ID OAuth Google (untuk login Google)
# GOOGLE_CLIENT_SECRET : Client Secret OAuth Google
RUST_ENV=development RUST_ENV=development
RUST_LOG=debug RUST_LOG=debug
PORT=4099 PORT=4099
Generated
+128 -124
View File
@@ -626,41 +626,6 @@ dependencies = [
"typenum", "typenum",
] ]
[[package]]
name = "darling"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 2.0.111",
]
[[package]]
name = "darling_macro"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
dependencies = [
"darling_core",
"quote",
"syn 2.0.111",
]
[[package]] [[package]]
name = "der" name = "der"
version = "0.7.10" version = "0.7.10"
@@ -1451,12 +1416,6 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]] [[package]]
name = "idna" name = "idna"
version = "1.1.0" version = "1.1.0"
@@ -1480,7 +1439,7 @@ dependencies = [
[[package]] [[package]]
name = "imphnen-backend" name = "imphnen-backend"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -1508,14 +1467,14 @@ dependencies = [
"utoipa", "utoipa",
"utoipa-swagger-ui", "utoipa-swagger-ui",
"uuid", "uuid",
"validator",
] ]
[[package]] [[package]]
name = "imphnen-cms" name = "imphnen-cms"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait",
"axum", "axum",
"axum-test", "axum-test",
"chrono", "chrono",
@@ -1525,6 +1484,10 @@ dependencies = [
"imphnen-utils", "imphnen-utils",
"lazy_static", "lazy_static",
"log", "log",
"paginator-axum",
"paginator-rs",
"paginator-sea-orm",
"paginator-utils",
"rand 0.9.2", "rand 0.9.2",
"regex", "regex",
"sea-orm", "sea-orm",
@@ -1536,12 +1499,13 @@ dependencies = [
"utoipa", "utoipa",
"utoipa-swagger-ui", "utoipa-swagger-ui",
"uuid", "uuid",
"validator", "zod-rs",
"zod-rs-util",
] ]
[[package]] [[package]]
name = "imphnen-dimentorin" name = "imphnen-dimentorin"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
@@ -1556,6 +1520,10 @@ dependencies = [
"imphnen-middleware", "imphnen-middleware",
"imphnen-utils", "imphnen-utils",
"lazy_static", "lazy_static",
"paginator-axum",
"paginator-rs",
"paginator-sea-orm",
"paginator-utils",
"rand 0.9.2", "rand 0.9.2",
"regex", "regex",
"sea-orm", "sea-orm",
@@ -1567,12 +1535,13 @@ dependencies = [
"utoipa", "utoipa",
"utoipa-swagger-ui", "utoipa-swagger-ui",
"uuid", "uuid",
"validator", "zod-rs",
"zod-rs-util",
] ]
[[package]] [[package]]
name = "imphnen-entities" name = "imphnen-entities"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -1590,9 +1559,10 @@ dependencies = [
[[package]] [[package]]
name = "imphnen-gacha" name = "imphnen-gacha"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait",
"axum", "axum",
"axum-test", "axum-test",
"chrono", "chrono",
@@ -1602,6 +1572,10 @@ dependencies = [
"imphnen-utils", "imphnen-utils",
"lazy_static", "lazy_static",
"log", "log",
"paginator-axum",
"paginator-rs",
"paginator-sea-orm",
"paginator-utils",
"rand 0.9.2", "rand 0.9.2",
"rand_distr", "rand_distr",
"regex", "regex",
@@ -1614,12 +1588,13 @@ dependencies = [
"utoipa", "utoipa",
"utoipa-swagger-ui", "utoipa-swagger-ui",
"uuid", "uuid",
"validator", "zod-rs",
"zod-rs-util",
] ]
[[package]] [[package]]
name = "imphnen-gateway" name = "imphnen-gateway"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -1642,12 +1617,11 @@ dependencies = [
"tower-http", "tower-http",
"utoipa", "utoipa",
"utoipa-swagger-ui", "utoipa-swagger-ui",
"validator",
] ]
[[package]] [[package]]
name = "imphnen-iam" name = "imphnen-iam"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
@@ -1665,6 +1639,10 @@ dependencies = [
"mockall", "mockall",
"oauth2", "oauth2",
"once_cell", "once_cell",
"paginator-axum",
"paginator-rs",
"paginator-sea-orm",
"paginator-utils",
"rand 0.9.2", "rand 0.9.2",
"regex", "regex",
"reqwest", "reqwest",
@@ -1680,12 +1658,13 @@ dependencies = [
"utoipa", "utoipa",
"utoipa-swagger-ui", "utoipa-swagger-ui",
"uuid", "uuid",
"validator", "zod-rs",
"zod-rs-util",
] ]
[[package]] [[package]]
name = "imphnen-libs" name = "imphnen-libs"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"argon2", "argon2",
@@ -1714,12 +1693,12 @@ dependencies = [
"tracing-subscriber", "tracing-subscriber",
"urlencoding", "urlencoding",
"uuid", "uuid",
"validator", "zod-rs",
] ]
[[package]] [[package]]
name = "imphnen-macros" name = "imphnen-macros"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1728,7 +1707,7 @@ dependencies = [
[[package]] [[package]]
name = "imphnen-middleware" name = "imphnen-middleware"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -1753,12 +1732,11 @@ dependencies = [
"utoipa", "utoipa",
"utoipa-swagger-ui", "utoipa-swagger-ui",
"uuid", "uuid",
"validator",
] ]
[[package]] [[package]]
name = "imphnen-utils" name = "imphnen-utils"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -1768,6 +1746,10 @@ dependencies = [
"dotenvy", "dotenvy",
"imphnen-entities", "imphnen-entities",
"imphnen-libs", "imphnen-libs",
"paginator-axum",
"paginator-rs",
"paginator-sea-orm",
"paginator-utils",
"rand 0.9.2", "rand 0.9.2",
"regex", "regex",
"reqwest", "reqwest",
@@ -1780,7 +1762,7 @@ dependencies = [
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
"uuid", "uuid",
"validator", "zod-rs",
] ]
[[package]] [[package]]
@@ -2331,6 +2313,57 @@ dependencies = [
"syn 2.0.111", "syn 2.0.111",
] ]
[[package]]
name = "paginator-axum"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "599c5c103c2e05968133b94fe4e50eadd32122ec5de67d23cc4560b92d14ad89"
dependencies = [
"async-trait",
"axum",
"http",
"paginator-rs",
"paginator-utils",
"serde",
"serde_json",
]
[[package]]
name = "paginator-rs"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fdee525f1aa47af3330e699c14044c317454207668c80c9aeb8207d2c662a6c"
dependencies = [
"paginator-utils",
"serde",
"serde_json",
]
[[package]]
name = "paginator-sea-orm"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c7d707483ea0b638e24da8e8f2b4fd077bdc88dbd5832b534eee1d8e66f6974"
dependencies = [
"async-trait",
"paginator-rs",
"paginator-utils",
"sea-orm",
"serde",
"uuid",
]
[[package]]
name = "paginator-utils"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e7ca0ba9d0ec274d2dcf4aa95420bd07d5eaed5c5c20258e26fd59aa73bad2"
dependencies = [
"base64",
"serde",
"serde_json",
]
[[package]] [[package]]
name = "parking" name = "parking"
version = "2.2.1" version = "2.2.1"
@@ -3623,12 +3656,6 @@ dependencies = [
"unicode-properties", "unicode-properties",
] ]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]] [[package]]
name = "strum" name = "strum"
version = "0.26.3" version = "0.26.3"
@@ -3750,33 +3777,6 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"
[[package]]
name = "tests"
version = "0.1.0"
dependencies = [
"axum",
"chrono",
"dotenvy",
"http-body-util",
"hyper",
"hyper-util",
"imphnen-dimentorin",
"imphnen-entities",
"imphnen-iam",
"imphnen-libs",
"imphnen-utils",
"rand 0.9.2",
"serde",
"serde_json",
"strum 0.27.2",
"tokio",
"tower",
"tracing",
"uuid",
"yoke",
"yoke-derive",
]
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.69" version = "1.0.69"
@@ -4248,36 +4248,6 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "validator"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43fb22e1a008ece370ce08a3e9e4447a910e92621bb49b85d6e48a45397e7cfa"
dependencies = [
"idna",
"once_cell",
"regex",
"serde",
"serde_derive",
"serde_json",
"url",
"validator_derive",
]
[[package]]
name = "validator_derive"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7df16e474ef958526d1205f6dda359fdfab79d9aa6d54bafcb92dcd07673dca"
dependencies = [
"darling",
"once_cell",
"proc-macro-error2",
"proc-macro2",
"quote",
"syn 2.0.111",
]
[[package]] [[package]]
name = "valuable" name = "valuable"
version = "0.1.1" version = "0.1.1"
@@ -4908,6 +4878,40 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f06ae92f42f5e5c42443fd094f245eb656abf56dd7cce9b8b263236565e00f2" checksum = "2f06ae92f42f5e5c42443fd094f245eb656abf56dd7cce9b8b263236565e00f2"
[[package]]
name = "zod-rs"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b3d6798b23cf9be839aa5dc002b72ae21b52c0a112920b4397252eb152ce10b"
dependencies = [
"regex",
"serde",
"serde_json",
"zod-rs-macros",
"zod-rs-util",
]
[[package]]
name = "zod-rs-macros"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa0aeb5fc2bd71f115da362f9173505fad648bd8ec57a1ce583049a6b0acf46b"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 2.0.111",
]
[[package]]
name = "zod-rs-util"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86ea855d76c2e2839eb794cc70c4e772c575ff997c00b6daea503d42cae44adb"
dependencies = [
"serde_json",
]
[[package]] [[package]]
name = "zopfli" name = "zopfli"
version = "0.8.3" version = "0.8.3"
+6 -3
View File
@@ -1,7 +1,6 @@
[workspace] [workspace]
resolver = "2" resolver = "2"
members = [ members = [
"tests",
"imphnen-entities", # Most basic - core data structures "imphnen-entities", # Most basic - core data structures
"imphnen-macros", # Macros "imphnen-macros", # Macros
"imphnen-libs", # Depends on entities "imphnen-libs", # Depends on entities
@@ -37,7 +36,12 @@ rand = { version = "0.9.2", features = ["std", "alloc"] }
rand_distr = "0.5.1" rand_distr = "0.5.1"
tower-http = { version = "0.6.6", features = ["cors", "trace"] } tower-http = { version = "0.6.6", features = ["cors", "trace"] }
http-body-util = "0.1.3" http-body-util = "0.1.3"
validator = { version = "0.20.0", features = ["derive"] } zod-rs = { version = "0.4", features = ["macros"] }
zod-rs-util = "0.4"
paginator-rs = "0.2"
paginator-utils = "0.2"
paginator-sea-orm = { version = "0.2", features = ["sqlx-postgres", "runtime-tokio"] }
paginator-axum = "0.2"
lazy_static = "1.5.0" lazy_static = "1.5.0"
regex = "1.11.1" regex = "1.11.1"
axum-test = "17.3.0" axum-test = "17.3.0"
@@ -71,7 +75,6 @@ tokio-tungstenite = "0.27"
url = "2.5" url = "2.5"
futures-util = "0.3" futures-util = "0.3"
http = "1.3" http = "1.3"
tests = { path = "./tests" }
imphnen-iam = { path = "./imphnen-iam" } imphnen-iam = { path = "./imphnen-iam" }
imphnen-cms = { path = "./imphnen-cms" } imphnen-cms = { path = "./imphnen-cms" }
imphnen-libs = { path = "./imphnen-libs" } imphnen-libs = { path = "./imphnen-libs" }
-35
View File
@@ -1,35 +0,0 @@
@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
-30
View File
@@ -1,30 +0,0 @@
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"
-25
View File
@@ -1,25 +0,0 @@
#!/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"
-49
View File
@@ -1,49 +0,0 @@
#!/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"
+7 -6
View File
@@ -1,19 +1,20 @@
{pkgs, ...}: let { pkgs, ... }:
let
baseImage = pkgs.ociTools.pullImage { baseImage = pkgs.ociTools.pullImage {
imageName = "ubuntu"; imageName = "ubuntu";
tag = "latest"; tag = "latest";
}; };
in in
pkgs.dockerTools.buildImage { pkgs.dockerTools.buildImage {
name = "imphnen-cms-api"; name = "imphnen-backend-service";
fromImage = baseImage; fromImage = baseImage;
copyToRoot = pkgs.buildEnv { copyToRoot = pkgs.buildEnv {
name = "imphnen-cms-api"; name = "imphnen-backend-service";
paths = [ paths = [
(pkgs.stdenv.mkDerivation { (pkgs.stdenv.mkDerivation {
name = "imphnen-cms-api"; name = "imphnen-backend-service";
src = ./src; src = ./src;
buildInputs = [ buildInputs = [
@@ -29,14 +30,14 @@ in
installPhase = '' installPhase = ''
mkdir -p $out/bin mkdir -p $out/bin
cp target/release/najm-course-api $out/bin/ cp target/release/imphnen-backend-service $out/bin/
''; '';
}) })
]; ];
}; };
config = { config = {
Cmd = ["/bin/imphnen-cms-api"]; Cmd = [ "/bin/imphnen-backend-service" ];
WorkingDir = "/bin"; WorkingDir = "/bin";
}; };
} }
+14 -5
View File
@@ -5,12 +5,20 @@
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
}; };
outputs = { outputs =
{
self, self,
nixpkgs, nixpkgs,
}: let }:
supportedSystems = ["x86_64-linux" "x86_64-darwin" "aarch64-darwin" "aarch64-linux"]; let
pkgsFor = system: supportedSystems = [
"x86_64-linux"
"x86_64-darwin"
"aarch64-darwin"
"aarch64-linux"
];
pkgsFor =
system:
import nixpkgs { import nixpkgs {
inherit system; inherit system;
config = { config = {
@@ -18,7 +26,8 @@
}; };
}; };
forAllSystems = nixpkgs.lib.genAttrs supportedSystems; forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
in { in
{
packages = forAllSystems (system: { packages = forAllSystems (system: {
default = (pkgsFor system).callPackage ./default.nix { }; default = (pkgsFor system).callPackage ./default.nix { };
}); });
+1 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "imphnen-backend" name = "imphnen-backend"
version = "0.1.0" version = "0.2.0"
edition = "2021" edition = "2021"
[[bin]] [[bin]]
@@ -63,7 +63,6 @@ serde_json.workspace = true
utoipa.workspace = true utoipa.workspace = true
lazy_static.workspace = true lazy_static.workspace = true
regex.workspace = true regex.workspace = true
validator.workspace = true
axum-test.workspace = true axum-test.workspace = true
rand.workspace = true rand.workspace = true
tokio.workspace = true tokio.workspace = true
+9 -2
View File
@@ -1,9 +1,10 @@
[package] [package]
name = "imphnen-cms" name = "imphnen-cms"
version = "0.1.0" version = "0.2.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
async-trait.workspace = true
imphnen-iam.workspace = true imphnen-iam.workspace = true
imphnen-libs.workspace = true imphnen-libs.workspace = true
imphnen-utils.workspace = true imphnen-utils.workspace = true
@@ -14,7 +15,8 @@ serde_json.workspace = true
utoipa.workspace = true utoipa.workspace = true
lazy_static.workspace = true lazy_static.workspace = true
regex.workspace = true regex.workspace = true
validator.workspace = true zod-rs.workspace = true
zod-rs-util.workspace = true
axum-test.workspace = true axum-test.workspace = true
rand.workspace = true rand.workspace = true
tokio.workspace = true tokio.workspace = true
@@ -27,5 +29,10 @@ tracing.workspace = true
sea-orm.workspace = true sea-orm.workspace = true
uuid.workspace = true uuid.workspace = true
paginator-rs.workspace = true
paginator-utils.workspace = true
paginator-sea-orm.workspace = true
paginator-axum.workspace = true
[package.metadata.validator.regex] [package.metadata.validator.regex]
VALID_URL_REGEX = "^https?://" VALID_URL_REGEX = "^https?://"
@@ -0,0 +1,40 @@
use std::sync::Arc;
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::events::domain::{EventEntity, EventRepository, EventService};
pub struct EventServiceImpl {
repo: Arc<dyn EventRepository>,
}
impl EventServiceImpl {
pub fn new(repo: Arc<dyn EventRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl EventService for EventServiceImpl {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<EventEntity>, AppError> {
self.repo.find_all(params).await
}
async fn get(&self, id: Uuid) -> Result<EventEntity, AppError> {
self.repo.find_by_id(id).await
}
async fn create(&self, entity: EventEntity) -> Result<(), AppError> {
self.repo.create(entity).await
}
async fn update(&self, entity: EventEntity) -> Result<(), AppError> {
self.repo.update(entity).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
}
@@ -0,0 +1,3 @@
pub mod event_service;
pub use event_service::EventServiceImpl;
+18
View File
@@ -0,0 +1,18 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct EventEntity {
pub id: Uuid,
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
pub is_online: bool,
pub is_deleted: bool,
pub location: Option<String>,
pub start_date: DateTime<Utc>,
pub end_date: DateTime<Utc>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
+7
View File
@@ -0,0 +1,7 @@
pub mod event;
pub mod repository;
pub mod service;
pub use event::EventEntity;
pub use repository::EventRepository;
pub use service::EventService;
@@ -0,0 +1,15 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::event::EventEntity;
#[async_trait]
pub trait EventRepository: Send + Sync {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<EventEntity>, AppError>;
async fn find_by_id(&self, id: Uuid) -> Result<EventEntity, AppError>;
async fn create(&self, entity: EventEntity) -> Result<(), AppError>;
async fn update(&self, entity: EventEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
+15
View File
@@ -0,0 +1,15 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::event::EventEntity;
#[async_trait]
pub trait EventService: Send + Sync {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<EventEntity>, AppError>;
async fn get(&self, id: Uuid) -> Result<EventEntity, AppError>;
async fn create(&self, entity: EventEntity) -> Result<(), AppError>;
async fn update(&self, entity: EventEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,131 @@
use chrono::{DateTime, Utc};
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
use crate::events::domain::event::EventEntity;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventsCreateRequestDto {
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
#[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>,
pub location: Option<String>,
pub is_online: bool,
}
impl ZodValidate for EventsCreateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
}
impl From<EventsCreateRequestDto> for EventEntity {
fn from(dto: EventsCreateRequestDto) -> Self {
EventEntity {
id: Uuid::new_v4(),
name: dto.name,
description: dto.description,
detail_link: dto.detail_link,
price: dto.price,
is_online: dto.is_online,
is_deleted: false,
location: dto.location,
start_date: dto.start_date,
end_date: dto.end_date,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventsUpdateRequestDto {
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>,
pub price: f64,
pub is_online: bool,
pub description: String,
pub detail_link: String,
pub location: Option<String>,
}
impl ZodValidate for EventsUpdateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_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,
}
impl From<EventEntity> for EventsListItemDto {
fn from(e: EventEntity) -> Self {
EventsListItemDto {
id: e.id.to_string(),
name: e.name,
description: e.description,
detail_link: e.detail_link,
price: e.price,
is_online: e.is_online,
start_date: e.start_date.to_rfc3339(),
end_date: e.end_date.to_rfc3339(),
created_at: e.created_at.to_rfc3339(),
location: e.location,
is_deleted: e.is_deleted,
}
}
}
#[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>,
}
impl From<EventEntity> for EventsDetailItemDto {
fn from(e: EventEntity) -> Self {
EventsDetailItemDto {
id: e.id.to_string(),
name: e.name,
description: e.description,
detail_link: e.detail_link,
price: e.price,
is_online: e.is_online,
start_date: e.start_date.to_rfc3339(),
end_date: e.end_date.to_rfc3339(),
created_at: e.created_at.to_rfc3339(),
updated_at: e.updated_at.to_rfc3339(),
location: e.location,
}
}
}
@@ -0,0 +1,160 @@
use std::sync::Arc;
use axum::{Extension, extract::Path, http::HeaderMap, response::{IntoResponse, Response}};
use paginator_axum::PaginationQuery;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::{ApiSuccess, ApiPaginated, ApiMessage};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_utils::AppError;
use super::dto::{EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto, EventsUpdateRequestDto};
use crate::events::domain::EventService;
#[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"),
),
responses(
(status = 200, description = "[PUBLIC] Get event list")
),
tag = "Events"
)]
pub async fn get_event_list(
Extension(service): Extension<Arc<dyn EventService>>,
PaginationQuery(params): PaginationQuery,
) -> Response {
match service.list(params).await {
Ok(result) => {
let mapped = PaginatorResponse {
data: result.data.into_iter().map(EventsListItemDto::from).collect::<Vec<_>>(),
meta: result.meta,
};
ApiPaginated(mapped).into_response()
}
Err(e) => ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, e.to_string()).into_response(),
}
}
#[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(service): Extension<Arc<dyn EventService>>,
Path(id): Path<String>,
) -> Response {
let uuid = match Uuid::parse_str(&id) {
Ok(u) => u,
Err(e) => return ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, format!("Invalid UUID: {e}")).into_response(),
};
match service.get(uuid).await {
Ok(event) => ApiSuccess(EventsDetailItemDto::from(event)).into_response(),
Err(e) => ApiMessage::new(axum::http::StatusCode::NOT_FOUND, e.to_string()).into_response(),
}
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/cms/landing/events/create",
request_body = EventsCreateRequestDto,
responses(
(status = 201, description = "[ADMIN] Create new event")
),
tag = "Events"
)]
pub async fn post_create_event(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn EventService>>,
ValidatedJson(payload): ValidatedJson<EventsCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let entity = payload.into();
service.create(entity).await?;
Ok(ApiMessage::created("Event created"))
})
}
#[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")
),
tag = "Events"
)]
pub async fn patch_update_event(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn EventService>>,
Path(id): Path<String>,
ValidatedJson(payload): ValidatedJson<EventsUpdateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let existing = service.get(uuid).await?;
let entity = crate::events::domain::EventEntity {
id: existing.id,
name: payload.name,
description: payload.description,
detail_link: payload.detail_link,
price: payload.price,
is_online: payload.is_online,
location: payload.location,
start_date: payload.start_date,
end_date: payload.end_date,
is_deleted: existing.is_deleted,
created_at: existing.created_at,
updated_at: chrono::Utc::now(),
};
service.update(entity).await?;
Ok(ApiMessage::ok("Event updated"))
})
}
#[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")
),
tag = "Events"
)]
pub async fn delete_event(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn EventService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
service.delete(uuid).await?;
Ok(ApiMessage::ok("Event deleted"))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::{events_public_routes, events_protected_routes};
@@ -0,0 +1,31 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, patch, post}, Extension};
use sea_orm::DatabaseConnection;
use crate::events::application::EventServiceImpl;
use crate::events::domain::EventService;
use crate::events::infrastructure::persistence::PostgresEventRepository;
use super::handlers::{
delete_event, get_event_by_id, get_event_list, patch_update_event, post_create_event,
};
fn build_service(db: DatabaseConnection) -> Arc<dyn EventService> {
let repo = Arc::new(PostgresEventRepository::new(db));
Arc::new(EventServiceImpl::new(repo))
}
pub fn events_public_routes(db: DatabaseConnection) -> Router {
let service = build_service(db);
Router::new()
.route("/cms/landing/events", get(get_event_list))
.route("/cms/landing/events/detail/{id}", get(get_event_by_id))
.layer(Extension(service))
}
pub fn events_protected_routes(db: DatabaseConnection) -> Router {
let service = build_service(db);
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))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_event_repository;
pub use postgres_event_repository::PostgresEventRepository;
@@ -0,0 +1,149 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, Order, QueryOrder, PaginatorTrait};
use paginator_rs::{PaginationParams, SortDirection};
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::common::events::{
Entity as EventsEntity, Column as EventsColumn,
ActiveModel as EventsActiveModel, Model as EventsModel,
};
use crate::events::domain::{event::EventEntity, repository::EventRepository};
fn to_entity(model: EventsModel) -> EventEntity {
EventEntity {
id: model.id,
name: model.name,
description: model.description,
detail_link: model.detail_link,
price: model.price,
is_online: model.is_online,
is_deleted: model.is_deleted,
location: model.location,
start_date: model.start_date,
end_date: model.end_date,
created_at: model.created_at,
updated_at: model.updated_at,
}
}
pub struct PostgresEventRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresEventRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl EventRepository for PostgresEventRepository {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<EventEntity>, AppError> {
let page = params.page.max(1);
let per_page = params.per_page.clamp(1, 100);
let mut query = EventsEntity::find()
.filter(EventsColumn::IsDeleted.eq(false));
if let Some(ref search) = params.search {
query = query.filter(EventsColumn::Name.contains(&search.query));
}
query = match params.sort_by.as_deref() {
Some("name") => match params.sort_direction {
Some(SortDirection::Desc) => query.order_by(EventsColumn::Name, Order::Desc),
_ => query.order_by(EventsColumn::Name, Order::Asc),
},
_ => match params.sort_direction {
Some(SortDirection::Asc) => query.order_by(EventsColumn::CreatedAt, Order::Asc),
_ => query.order_by(EventsColumn::CreatedAt, Order::Desc),
},
};
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
let total = paginator.num_items().await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let events = paginator.fetch_page((page - 1) as u64).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let data = events.into_iter().map(to_entity).collect();
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
Ok(PaginatorResponse { data, meta })
}
async fn find_by_id(&self, id: Uuid) -> Result<EventEntity, AppError> {
let event = EventsEntity::find_by_id(id)
.filter(EventsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?;
Ok(to_entity(event))
}
async fn create(&self, entity: EventEntity) -> Result<(), AppError> {
let active_model = EventsActiveModel {
id: ActiveValue::Set(entity.id),
name: ActiveValue::Set(entity.name),
description: ActiveValue::Set(entity.description),
detail_link: ActiveValue::Set(entity.detail_link),
price: ActiveValue::Set(entity.price),
is_online: ActiveValue::Set(entity.is_online),
is_deleted: ActiveValue::Set(false),
location: ActiveValue::Set(entity.location),
start_date: ActiveValue::Set(entity.start_date),
end_date: ActiveValue::Set(entity.end_date),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
};
EventsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn update(&self, entity: EventEntity) -> Result<(), AppError> {
let mut active_model: EventsActiveModel = EventsEntity::find_by_id(entity.id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?
.into();
active_model.name = ActiveValue::Set(entity.name);
active_model.description = ActiveValue::Set(entity.description);
active_model.detail_link = ActiveValue::Set(entity.detail_link);
active_model.price = ActiveValue::Set(entity.price);
active_model.is_online = ActiveValue::Set(entity.is_online);
active_model.location = ActiveValue::Set(entity.location);
active_model.start_date = ActiveValue::Set(entity.start_date);
active_model.end_date = ActiveValue::Set(entity.end_date);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model.update(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
let mut active_model: EventsActiveModel = EventsEntity::find_by_id(id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?
.into();
active_model.is_deleted = ActiveValue::Set(true);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model.update(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod application;
pub mod domain;
pub mod infrastructure;
pub use infrastructure::http::{events_public_routes, events_protected_routes};
+4 -8
View File
@@ -1,9 +1,5 @@
pub mod v1; pub mod events;
pub mod testimonials;
pub use v1::landing; pub use events::{events_public_routes, events_protected_routes};
pub use v1::landing::events; pub use testimonials::{testimonials_public_routes, testimonials_protected_routes};
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,3 @@
pub mod testimonial_service;
pub use testimonial_service::TestimonialServiceImpl;
@@ -0,0 +1,40 @@
use std::sync::Arc;
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::testimonials::domain::{TestimonialEntity, TestimonialRepository, TestimonialService};
pub struct TestimonialServiceImpl {
repo: Arc<dyn TestimonialRepository>,
}
impl TestimonialServiceImpl {
pub fn new(repo: Arc<dyn TestimonialRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl TestimonialService for TestimonialServiceImpl {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<TestimonialEntity>, AppError> {
self.repo.find_all(params).await
}
async fn get(&self, id: Uuid) -> Result<TestimonialEntity, AppError> {
self.repo.find_by_id(id).await
}
async fn create(&self, entity: TestimonialEntity) -> Result<TestimonialEntity, AppError> {
self.repo.create(entity).await
}
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError> {
self.repo.update(entity).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
}
@@ -0,0 +1,7 @@
pub mod testimonial;
pub mod repository;
pub mod service;
pub use testimonial::TestimonialEntity;
pub use repository::TestimonialRepository;
pub use service::TestimonialService;
@@ -0,0 +1,15 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::testimonial::TestimonialEntity;
#[async_trait]
pub trait TestimonialRepository: Send + Sync {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<TestimonialEntity>, AppError>;
async fn find_by_id(&self, id: Uuid) -> Result<TestimonialEntity, AppError>;
async fn create(&self, entity: TestimonialEntity) -> Result<TestimonialEntity, AppError>;
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,15 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::testimonial::TestimonialEntity;
#[async_trait]
pub trait TestimonialService: Send + Sync {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<TestimonialEntity>, AppError>;
async fn get(&self, id: Uuid) -> Result<TestimonialEntity, AppError>;
async fn create(&self, entity: TestimonialEntity) -> Result<TestimonialEntity, AppError>;
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,13 @@
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct TestimonialEntity {
pub id: Uuid,
pub user_id: Uuid,
pub user_fullname: String,
pub role: String,
pub content: String,
pub is_deleted: bool,
pub created_at: String,
pub updated_at: String,
}
@@ -0,0 +1,83 @@
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use zod_rs::prelude::*;
use crate::testimonials::domain::testimonial::TestimonialEntity;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
pub struct TestimonialsCreateRequestDto {
#[zod(min_length(1), max_length(100))]
pub role: String,
#[zod(min_length(1), max_length(1000))]
pub content: String,
}
impl ZodValidate for TestimonialsCreateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
Self::validate_and_parse(value).map_err(|e| e.to_string())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
pub struct TestimonialsUpdateRequestDto {
#[zod(min_length(1), max_length(100))]
pub role: String,
#[zod(min_length(1), max_length(1000))]
pub content: String,
}
impl ZodValidate for TestimonialsUpdateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
Self::validate_and_parse(value).map_err(|e| e.to_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,
}
impl From<TestimonialEntity> for TestimonialsListItemDto {
fn from(e: TestimonialEntity) -> Self {
TestimonialsListItemDto {
id: e.id.to_string(),
user_id: e.user_id.to_string(),
user_fullname: e.user_fullname,
role: e.role,
content: e.content,
created_at: e.created_at,
is_deleted: e.is_deleted,
}
}
}
#[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,
}
impl From<TestimonialEntity> for TestimonialsDetailItemDto {
fn from(e: TestimonialEntity) -> Self {
TestimonialsDetailItemDto {
id: e.id.to_string(),
user_id: e.user_id.to_string(),
user_fullname: e.user_fullname,
role: e.role,
content: e.content,
created_at: e.created_at,
updated_at: e.updated_at,
}
}
}
@@ -0,0 +1,181 @@
use std::sync::Arc;
use axum::{Extension, extract::Path, http::HeaderMap, http::StatusCode, response::{IntoResponse, Response}};
use paginator_axum::PaginationQuery;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::{ApiSuccess, ApiCreated, ApiPaginated, ApiMessage, extract_email};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::require_auth;
use imphnen_utils::AppError;
use super::dto::{
TestimonialsCreateRequestDto, TestimonialsDetailItemDto,
TestimonialsListItemDto, TestimonialsUpdateRequestDto,
};
use crate::testimonials::domain::{TestimonialEntity, TestimonialService};
#[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"),
),
responses(
(status = 200, description = "[PUBLIC] Get testimonial list")
),
tag = "Testimonials"
)]
pub async fn get_testimonial_list(
Extension(service): Extension<Arc<dyn TestimonialService>>,
PaginationQuery(params): PaginationQuery,
) -> Response {
match service.list(params).await {
Ok(result) => {
let mapped = PaginatorResponse {
data: result.data.into_iter()
.filter(|e| !e.is_deleted)
.map(TestimonialsListItemDto::from)
.collect::<Vec<_>>(),
meta: result.meta,
};
ApiPaginated(mapped).into_response()
}
Err(e) => ApiMessage::new(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
}
}
#[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(service): Extension<Arc<dyn TestimonialService>>,
Path(id): Path<String>,
) -> Response {
let uuid = match Uuid::parse_str(&id) {
Ok(u) => u,
Err(e) => return ApiMessage::new(StatusCode::BAD_REQUEST, format!("Invalid UUID: {e}")).into_response(),
};
match service.get(uuid).await {
Ok(t) if !t.is_deleted => {
ApiSuccess(TestimonialsDetailItemDto::from(t)).into_response()
}
Ok(_) => ApiMessage::new(StatusCode::NOT_FOUND, "Testimonial not found").into_response(),
Err(e) => ApiMessage::new(StatusCode::NOT_FOUND, e.to_string()).into_response(),
}
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/cms/landing/testimonials/create",
request_body = TestimonialsCreateRequestDto,
responses(
(status = 201, description = "[USER] Create new testimonial", body = ResponseSuccessDto<TestimonialsDetailItemDto>)
),
tag = "Testimonials"
)]
pub async fn post_create_testimonial(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn TestimonialService>>,
ValidatedJson(payload): ValidatedJson<TestimonialsCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_auth!(headers.clone(), state, {
let email = extract_email(&headers)
.ok_or_else(|| AppError::AuthenticationError("Token tidak valid".to_string()))?;
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
let user = user_info.basic_info;
let user_id = Uuid::parse_str(&user.id)
.map_err(|e| AppError::BadRequestError(format!("Invalid user ID: {e}")))?;
let entity = TestimonialEntity {
id: Uuid::new_v4(),
user_id,
user_fullname: user.fullname.clone(),
role: payload.role,
content: payload.content,
is_deleted: false,
created_at: chrono::Utc::now().to_rfc3339(),
updated_at: chrono::Utc::now().to_rfc3339(),
};
let created = service.create(entity).await?;
Ok(ApiCreated(TestimonialsDetailItemDto::from(created)))
})
}
#[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")
),
tag = "Testimonials"
)]
pub async fn patch_update_testimonial(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn TestimonialService>>,
Path(id): Path<String>,
ValidatedJson(payload): ValidatedJson<TestimonialsUpdateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_auth!(headers, state, {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let existing = service.get(uuid).await?;
let entity = TestimonialEntity {
id: existing.id,
user_id: existing.user_id,
user_fullname: existing.user_fullname,
role: payload.role,
content: payload.content,
is_deleted: existing.is_deleted,
created_at: existing.created_at,
updated_at: chrono::Utc::now().to_rfc3339(),
};
service.update(entity).await?;
Ok(ApiMessage::ok("Testimonial updated"))
})
}
#[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")
),
tag = "Testimonials"
)]
pub async fn delete_testimonial(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn TestimonialService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_auth!(headers, state, {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
service.delete(uuid).await?;
Ok(ApiMessage::ok("Testimonial deleted"))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::{testimonials_public_routes, testimonials_protected_routes};
@@ -0,0 +1,32 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, patch, post}, Extension};
use sea_orm::DatabaseConnection;
use crate::testimonials::application::TestimonialServiceImpl;
use crate::testimonials::domain::TestimonialService;
use crate::testimonials::infrastructure::persistence::PostgresTestimonialRepository;
use super::handlers::{
delete_testimonial, get_testimonial_by_id, get_testimonial_list,
patch_update_testimonial, post_create_testimonial,
};
fn build_service(db: DatabaseConnection) -> Arc<dyn TestimonialService> {
let repo = Arc::new(PostgresTestimonialRepository::new(db));
Arc::new(TestimonialServiceImpl::new(repo))
}
pub fn testimonials_public_routes(db: DatabaseConnection) -> Router {
let service = build_service(db);
Router::new()
.route("/cms/landing/testimonials", get(get_testimonial_list))
.route("/cms/landing/testimonials/detail/{id}", get(get_testimonial_by_id))
.layer(Extension(service))
}
pub fn testimonials_protected_routes(db: DatabaseConnection) -> Router {
let service = build_service(db);
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))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_testimonial_repository;
pub use postgres_testimonial_repository::PostgresTestimonialRepository;
@@ -0,0 +1,159 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, QueryOrder, PaginatorTrait};
use paginator_rs::{PaginationParams, SortDirection};
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::common::testimonials::{
Entity as TestimonialsEntity, Column as TestimonialsColumn, ActiveModel as TestimonialsActiveModel,
};
use imphnen_entities::seaorm::auth::users::Entity as UsersEntity;
use crate::testimonials::domain::{testimonial::TestimonialEntity, repository::TestimonialRepository};
pub struct PostgresTestimonialRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresTestimonialRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl TestimonialRepository for PostgresTestimonialRepository {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<TestimonialEntity>, AppError> {
let page = params.page.max(1);
let per_page = params.per_page.clamp(1, 100);
let mut query = TestimonialsEntity::find()
.filter(TestimonialsColumn::IsDeleted.eq(false))
.find_also_related(UsersEntity);
query = match params.sort_by.as_deref() {
Some("updated_at") => match params.sort_direction {
Some(SortDirection::Asc) => query.order_by_asc(TestimonialsColumn::UpdatedAt),
_ => query.order_by_desc(TestimonialsColumn::UpdatedAt),
},
_ => match params.sort_direction {
Some(SortDirection::Asc) => query.order_by_asc(TestimonialsColumn::CreatedAt),
_ => query.order_by_desc(TestimonialsColumn::CreatedAt),
},
};
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
let total = paginator.num_items().await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let rows = paginator.fetch_page((page - 1) as u64).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let data: Vec<TestimonialEntity> = rows.into_iter()
.filter_map(|(t, u)| {
u.map(|user| TestimonialEntity {
id: t.id,
user_id: t.user_id,
user_fullname: format!(
"{} {}",
user.first_name.as_deref().unwrap_or(""),
user.last_name.as_deref().unwrap_or("")
).trim().to_string(),
role: t.role,
content: t.content,
is_deleted: t.is_deleted,
created_at: t.created_at.to_rfc3339(),
updated_at: t.updated_at.to_rfc3339(),
})
})
.collect();
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
Ok(PaginatorResponse { data, meta })
}
async fn find_by_id(&self, id: Uuid) -> Result<TestimonialEntity, AppError> {
let (testimonial, user) = TestimonialsEntity::find_by_id(id)
.filter(TestimonialsColumn::IsDeleted.eq(false))
.find_also_related(UsersEntity)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?;
let user = user.ok_or_else(|| AppError::NotFoundError("User not found for testimonial".to_string()))?;
Ok(TestimonialEntity {
id: testimonial.id,
user_id: testimonial.user_id,
user_fullname: format!(
"{} {}",
user.first_name.as_deref().unwrap_or(""),
user.last_name.as_deref().unwrap_or("")
).trim().to_string(),
role: testimonial.role,
content: testimonial.content,
is_deleted: testimonial.is_deleted,
created_at: testimonial.created_at.to_rfc3339(),
updated_at: testimonial.updated_at.to_rfc3339(),
})
}
async fn create(&self, entity: TestimonialEntity) -> Result<TestimonialEntity, AppError> {
let active_model = TestimonialsActiveModel {
id: ActiveValue::Set(entity.id),
user_id: ActiveValue::Set(entity.user_id),
role: ActiveValue::Set(entity.role.clone()),
content: ActiveValue::Set(entity.content.clone()),
is_deleted: ActiveValue::Set(false),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
};
let inserted = active_model.insert(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(TestimonialEntity {
id: inserted.id,
user_id: inserted.user_id,
user_fullname: entity.user_fullname,
role: inserted.role,
content: inserted.content,
is_deleted: inserted.is_deleted,
created_at: inserted.created_at.to_rfc3339(),
updated_at: inserted.updated_at.to_rfc3339(),
})
}
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError> {
let mut active_model: TestimonialsActiveModel = TestimonialsEntity::find_by_id(entity.id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?
.into();
active_model.role = ActiveValue::Set(entity.role);
active_model.content = ActiveValue::Set(entity.content);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model.update(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
let mut active_model: TestimonialsActiveModel = TestimonialsEntity::find_by_id(id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?
.into();
active_model.is_deleted = ActiveValue::Set(true);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model.update(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod application;
pub mod domain;
pub mod infrastructure;
pub use infrastructure::http::{testimonials_public_routes, testimonials_protected_routes};
View File
View File
@@ -1,139 +0,0 @@
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
})
}
@@ -1,152 +0,0 @@
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,
}
}
}
@@ -1,220 +0,0 @@
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())
}
}
@@ -1,94 +0,0 @@
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()
}
}
}
@@ -1,102 +0,0 @@
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()),
}
}
}
-38
View File
@@ -1,38 +0,0 @@
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))
}
-7
View File
@@ -1,7 +0,0 @@
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;

Some files were not shown because too many files have changed in this diff Show More