Compare commits

..
Author SHA1 Message Date
MythEclipse 02be09506a refactor: update surrealdb client usage to support 'any' engine type 2025-06-29 23:23:18 +07:00
Maulana SodiqinandGitHub b88ecd1361 Merge pull request #37 from bakunya/develop
crud testi: acc banh
2025-06-29 00:34:44 +07:00
0x6d696b7566616e fa435994f2 crud testi 2025-06-29 00:01:00 +07:00
Maulana SodiqinandGitHub 16c613d699 Merge pull request #36 from IMPHNEN/feat/dotenv-dynamic-engine-seeder
feat: add dotenvy for environment variable management
2025-06-28 20:50:20 +07:00
MythEclipse f598dedb3b feat: add dotenvy for environment variable management and improve error handling in Env struct 2025-06-28 20:21:20 +07:00
Maulana SodiqinandGitHub cfa251337f Create deploy-to-ancikri.yml 2025-05-30 15:40:41 +07:00
Maulana Sodiqin cca9aa6318 chore: optimize dockerfile 2025-05-26 23:41:00 +07:00
Maulana Sodiqin f1e4e02697 fix: landing 2025-05-26 23:09:01 +07:00
Maulana SodiqinandGitHub a3c2715a85 Merge pull request #25 from bakunya/develop
feat: cms event
2025-05-26 15:28:05 +07:00
0x6d696b7566616e 89cc631fb0 feat: cms event 2025-05-26 14:11:17 +07:00
Maulana Sodiqin 36c12110c2 fixing dockerfile 2025-05-22 22:29:28 +07:00
Maulana Sodiqin 070060365a docs: update readme 2025-05-22 16:18:15 +07:00
Maulana Sodiqin 68e816f956 fix: schema default value 2025-05-22 15:25:24 +07:00
Maulana Sodiqin 48db5f07ef fix: register roles missmatch 2025-05-22 15:13:58 +07:00
Maulana Sodiqin a4b5d91906 chore: setup folder structure 2025-05-22 00:40:40 +07:00
Maulana Sodiqin 9878279660 feat: add gacha credits 2025-05-22 00:31:36 +07:00
Maulana Sodiqin 465cbee2c3 feat: finishing gacha feature 2025-05-21 19:37:30 +07:00
Maulana Sodiqin 33a2ae86c6 fix: unit tests 2025-05-21 11:35:35 +07:00
Maulana Sodiqin d906fc4747 chore: update query list 2025-05-20 16:57:45 +07:00
Maulana Sodiqin 055ef6ac8e feat: adjust readme and add new seeder script 2025-05-20 11:54:15 +07:00
Maulana Sodiqin e63658c082 feat: add gacha and init cms 2025-05-20 10:45:01 +07:00
Maulana SodiqinandGitHub f4b0ed0a4a Merge pull request #24 from IMPHNEN/chore/normalize-code
chore: normalize code
2025-05-20 01:50:58 +07:00
Maulana Sodiqin 1e5ed26f76 chore: cleaning code 2025-05-20 01:49:50 +07:00
Maulana Sodiqin d97095a38d chore: cleaning code 2025-05-20 00:26:24 +07:00
Maulana Sodiqin e48507901e chore: normalize code #2 2025-05-18 03:12:20 +07:00
Maulana Sodiqin a43ef8ec04 chore: normalize code 2025-05-17 02:08:59 +07:00
Maulana SodiqinandGitHub 874f25aa80 Merge pull request #23 from bakunya/develop
transform id(thing) to id(string) on get role, permission, users
2025-05-04 17:24:13 +07:00
Bakunya 12a730a394 transform id(thing) to id(string) on get role, permission, users 2025-05-04 17:07:20 +07:00
Bakunya bdcd41f54d transform id(thing) to id(string) on get role, permission, users 2025-05-04 16:37:11 +07:00
Maulana SodiqinandGitHub 96fb8eb7d3 Merge pull request #22 from IMPHNEN/feat/split-middleware
feat: split middleware
2025-04-07 20:43:59 +07:00
161 changed files with 4605 additions and 3521 deletions
+65
View File
@@ -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"
Generated
+215 -87
View File
@@ -115,6 +115,56 @@ dependencies = [
"libc",
]
[[package]]
name = "anstream"
version = "0.6.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9"
[[package]]
name = "anstyle-parse"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c"
dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e"
dependencies = [
"anstyle",
"once_cell",
"windows-sys 0.59.0",
]
[[package]]
name = "any_ascii"
version = "0.3.2"
@@ -123,9 +173,9 @@ checksum = "ea50b14b7a4b9343f8c627a7a53c52076482bd4bdad0a24fd3ec533ed616cc2c"
[[package]]
name = "anyhow"
version = "1.0.97"
version = "1.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f"
checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487"
[[package]]
name = "approx"
@@ -357,9 +407,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "axum"
version = "0.8.3"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de45108900e1f9b9242f7f2e254aa3e2c029c921c258fe9e6b4217eeebd54288"
checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5"
dependencies = [
"axum-core",
"bytes",
@@ -736,9 +786,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chrono"
version = "0.4.40"
version = "0.4.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c"
checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d"
dependencies = [
"android-tzdata",
"iana-time-zone",
@@ -796,6 +846,12 @@ dependencies = [
"inout",
]
[[package]]
name = "colorchoice"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@@ -1036,10 +1092,16 @@ dependencies = [
]
[[package]]
name = "doc-comment"
version = "0.3.3"
name = "dotenvy"
version = "0.15.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
[[package]]
name = "double-ended-peekable"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0d05e1c0dbad51b52c38bda7adceef61b9efc2baf04acfe8726a8c4630a6f57"
[[package]]
name = "earcutr"
@@ -1097,6 +1159,29 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d"
[[package]]
name = "env_filter"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0"
dependencies = [
"log",
"regex",
]
[[package]]
name = "env_logger"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f"
dependencies = [
"anstream",
"anstyle",
"env_filter",
"jiff",
"log",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -1385,7 +1470,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62ddb1950450d67efee2bbc5e429c68d052a822de3aad010d28b351fbb705224"
dependencies = [
"approx 0.5.1",
"arbitrary",
"num-traits",
"rstar",
"serde",
@@ -1492,12 +1576,6 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "heck"
version = "0.5.0"
@@ -1847,19 +1925,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed"
[[package]]
name = "imphnen-backend-service"
name = "imphnen-backend"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"axum-test",
"chrono",
"env_logger",
"imphnen-cms",
"imphnen-entities",
"imphnen-gateway-service",
"imphnen-gateway",
"imphnen-iam",
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -1872,7 +1953,7 @@ dependencies = [
]
[[package]]
name = "imphnen-cms-service"
name = "imphnen-cms"
version = "0.1.0"
dependencies = [
"anyhow",
@@ -1880,10 +1961,11 @@ dependencies = [
"axum-test",
"chrono",
"imphnen-entities",
"imphnen-iam",
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -1896,7 +1978,7 @@ dependencies = [
]
[[package]]
name = "imphnen-dimentorin-service"
name = "imphnen-dimentorin"
version = "0.1.0"
dependencies = [
"anyhow",
@@ -1907,7 +1989,7 @@ dependencies = [
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -1931,7 +2013,7 @@ dependencies = [
]
[[package]]
name = "imphnen-gacha-service"
name = "imphnen-gacha"
version = "0.1.0"
dependencies = [
"anyhow",
@@ -1939,10 +2021,12 @@ dependencies = [
"axum-test",
"chrono",
"imphnen-entities",
"imphnen-iam",
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"rand_distr",
"regex",
"serde",
"serde_json",
@@ -1955,20 +2039,22 @@ dependencies = [
]
[[package]]
name = "imphnen-gateway-service"
name = "imphnen-gateway"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"axum-test",
"chrono",
"imphnen-cms",
"imphnen-entities",
"imphnen-iam-service",
"imphnen-gacha",
"imphnen-iam",
"imphnen-libs",
"imphnen-middleware-service",
"imphnen-middleware",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -1981,7 +2067,7 @@ dependencies = [
]
[[package]]
name = "imphnen-iam-service"
name = "imphnen-iam"
version = "0.1.0"
dependencies = [
"anyhow",
@@ -1992,7 +2078,7 @@ dependencies = [
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -2011,16 +2097,18 @@ dependencies = [
"argon2",
"axum",
"chrono",
"dotenvy",
"imphnen-entities",
"jsonwebtoken",
"lettre",
"log",
"serde",
"surrealdb",
"tokio",
]
[[package]]
name = "imphnen-middleware-service"
name = "imphnen-middleware"
version = "0.1.0"
dependencies = [
"anyhow",
@@ -2029,11 +2117,11 @@ dependencies = [
"chrono",
"futures",
"imphnen-entities",
"imphnen-iam-service",
"imphnen-iam",
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -2056,7 +2144,7 @@ dependencies = [
"chrono",
"imphnen-entities",
"imphnen-libs",
"rand 0.9.0",
"rand 0.9.1",
"serde",
"serde_json",
"surrealdb",
@@ -2100,6 +2188,12 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "itertools"
version = "0.10.5"
@@ -2120,9 +2214,9 @@ dependencies = [
[[package]]
name = "itertools"
version = "0.13.0"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
@@ -2133,6 +2227,30 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "jiff"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f02000660d30638906021176af16b17498bd0d12813dbfe7b276d8bc7f3c0806"
dependencies = [
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
"serde",
]
[[package]]
name = "jiff-static"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c30758ddd7188629c6713fc45d1188af4f44c90582311d0c8d8c9907f60c48"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.100",
]
[[package]]
name = "js-sys"
version = "0.3.77"
@@ -2197,9 +2315,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "lettre"
version = "0.11.15"
version = "0.11.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "759bc2b8eabb6a30b235d6f716f7f36479f4b38cbe65b8747aefee51f89e8437"
checksum = "87ffd14fa289730e3ad68edefdc31f603d56fe716ec38f2076bb7410e09147c2"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -2611,23 +2729,26 @@ dependencies = [
[[package]]
name = "object_store"
version = "0.10.2"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6da452820c715ce78221e8202ccc599b4a52f3e1eb3eedb487b680c81a8e3f3"
checksum = "d94ac16b433c0ccf75326388c893d2835ab7457ea35ab8ba5d745c053ef5fa16"
dependencies = [
"async-trait",
"bytes",
"chrono",
"futures",
"http",
"humantime",
"itertools 0.13.0",
"itertools 0.14.0",
"parking_lot",
"percent-encoding",
"snafu",
"thiserror 2.0.12",
"tokio",
"tracing",
"url",
"walkdir",
"wasm-bindgen-futures",
"web-time",
]
[[package]]
@@ -2869,6 +2990,21 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "portable-atomic"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e"
[[package]]
name = "portable-atomic-util"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507"
dependencies = [
"portable-atomic",
]
[[package]]
name = "powerfmt"
version = "0.2.0"
@@ -3029,7 +3165,7 @@ checksum = "b820744eb4dc9b57a3398183639c511b5a26d2ed702cedd3febaa1393caa22cc"
dependencies = [
"bytes",
"getrandom 0.3.2",
"rand 0.9.0",
"rand 0.9.1",
"ring",
"rustc-hash",
"rustls",
@@ -3106,13 +3242,12 @@ dependencies = [
[[package]]
name = "rand"
version = "0.9.0"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94"
checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.3",
"zerocopy 0.8.24",
]
[[package]]
@@ -3153,6 +3288,16 @@ dependencies = [
"getrandom 0.3.2",
]
[[package]]
name = "rand_distr"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"
dependencies = [
"num-traits",
"rand 0.9.1",
]
[[package]]
name = "rawpointer"
version = "0.2.1"
@@ -3512,7 +3657,7 @@ dependencies = [
"futures-util",
"http",
"mime",
"rand 0.9.0",
"rand 0.9.1",
"thiserror 2.0.12",
]
@@ -3906,28 +4051,6 @@ dependencies = [
"serde",
]
[[package]]
name = "snafu"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4de37ad025c587a29e8f3f5605c00f70b98715ef90b9061a815b9e59e9042d6"
dependencies = [
"doc-comment",
"snafu-derive",
]
[[package]]
name = "snafu-derive"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990079665f075b699031e9c08fd3ab99be5029b96f3b78dc0709e8f77e4efebf"
dependencies = [
"heck 0.4.1",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "snap"
version = "1.1.1"
@@ -4045,7 +4168,7 @@ version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [
"heck 0.5.0",
"heck",
"proc-macro2",
"quote",
"rustversion",
@@ -4060,9 +4183,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "surrealdb"
version = "2.2.1"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa1aa87197bad9dd12c93350533a8da09bae064a411f445c97ca0e64faabc304"
checksum = "12a5a2d3f0d40d8b0bc2e3a327663c0cdffe7d35508ccabc810dab8281cf251d"
dependencies = [
"arrayvec",
"async-channel",
@@ -4071,6 +4194,7 @@ dependencies = [
"dmp",
"futures",
"geo",
"getrandom 0.3.2",
"indexmap 2.9.0",
"path-clean",
"pharos",
@@ -4101,9 +4225,9 @@ dependencies = [
[[package]]
name = "surrealdb-core"
version = "2.2.1"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ceb9f421e07af67b06c57ea7a8b08c3b4e4677de483435ca6d69bd00600a571"
checksum = "032f20c01cf3a5569f47c857da280abb7b6ff1e443bf58b993c3c28d2d802859"
dependencies = [
"addr",
"affinitypool",
@@ -4132,6 +4256,7 @@ dependencies = [
"fuzzy-matcher",
"geo",
"geo-types",
"getrandom 0.3.2",
"hex",
"http",
"ipnet",
@@ -4192,24 +4317,21 @@ dependencies = [
[[package]]
name = "surrealkv"
version = "0.8.1"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e28eec56aca077c245bf5f9e08876fdcce58b5361e77a0b94a92fd47e1990ad4"
checksum = "6d43d55edab1e65c7704486016f98e9eac61c97474921dbac094af2cd16e16c3"
dependencies = [
"ahash 0.8.11",
"async-channel",
"bytes",
"chrono",
"crc32fast",
"futures",
"double-ended-peekable",
"getrandom 0.2.15",
"lru",
"parking_lot",
"quick_cache 0.6.12",
"revision 0.10.0",
"tokio",
"vart 0.9.2",
"wasm-bindgen-futures",
]
[[package]]
@@ -4317,7 +4439,7 @@ dependencies = [
"axum-test",
"chrono",
"imphnen-entities",
"imphnen-iam-service",
"imphnen-iam",
"imphnen-libs",
"imphnen-utils",
"serde_json",
@@ -4442,9 +4564,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.44.2"
version = "1.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48"
checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165"
dependencies = [
"backtrace",
"bytes",
@@ -4552,9 +4674,9 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.2"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697"
checksum = "0fdb0c213ca27a9f57ab69ddb290fd80d970922355b83ae380b395d3986b8a2e"
dependencies = [
"bitflags",
"bytes",
@@ -4664,7 +4786,7 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "470dbf6591da1b39d43c14523b2b469c86879a53e8b758c8e090a470fe7b1fbe"
dependencies = [
"rand 0.9.0",
"rand 0.9.1",
"serde",
"web-time",
]
@@ -4765,6 +4887,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "utoipa"
version = "5.3.1"
+25 -11
View File
@@ -1,33 +1,47 @@
[workspace]
resolver = "2"
members = [
"imphnen-*",
"tests",
"imphnen-iam",
"imphnen-cms",
"imphnen-libs",
"imphnen-utils",
"imphnen-gacha",
"imphnen-gateway",
"imphnen-backend",
"imphnen-entities",
"imphnen-dimentorin",
"imphnen-middleware",
]
[workspace.dependencies]
axum = { version = "0.8.1", features = ["multipart"] }
axum = { version = "0.8.4", features = ["multipart"] }
log = "0.4.25"
serde = { version = "1.0.217", features = ["derive"] }
serde_json = "1.0.138"
tokio = { version = "1.43.0" }
tokio = { version = "1.45.0" }
argon2 = { version = "0.5.3", features = ["password-hash"] }
jsonwebtoken = "9.3.1"
chrono = "0.4.39"
chrono = "0.4.41"
utoipa = { version = "5.3.1", features = ["axum_extras"] }
utoipa-swagger-ui = { version = "9.0.0", features = ["axum"] }
lettre = { version = "0.11.12", features = ["tokio1-native-tls"] }
surrealdb = { version = "2.2.1", features = ["kv-mem"] }
thiserror = "2.0.11"
anyhow = "1.0.97"
rand = "0.9.0"
tower-http = { version = "0.6.2", features = ["cors"] }
lettre = { version = "0.11.16", features = ["tokio1-native-tls"] }
surrealdb = { version = "2.3.2", features = ["kv-mem"] }
thiserror = "2.0.12"
anyhow = "1.0.98"
rand = { version = "0.9.1", features = ["std", "alloc"] }
rand_distr = "0.5.1"
tower-http = { version = "0.6.4", features = ["cors"] }
validator = { version = "0.12", features = ["derive"] }
lazy_static = "1.4.0"
regex = "1.11.1"
axum-test = "17.2.0"
fancy-regex = "0.14.0"
futures = "0.3.31"
tower = "0.5.2"
env_logger = "0.11.8"
dotenvy = "0.15.7"
[profile.release]
lto = "fat"
codegen-units = 1
+37 -12
View File
@@ -1,22 +1,47 @@
FROM rust:1.83-slim-bullseye AS builder
FROM rust:1.85-alpine AS builder
RUN apt-get update && apt-get install -y \
build-essential \
libssl-dev \
pkg-config \
&& rm -rf /var/lib/apt/lists/*
RUN apk add --no-cache \
curl \
musl-dev \
openssl-dev \
openssl-libs-static \
pkgconfig
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY ./src ./src
RUN cargo build --release && strip /app/target/release/imphnen-backend-service
RUN mkdir -p imphnen-backend/src imphnen-cms/src imphnen-dimentorin/src \
imphnen-entities/src imphnen-gacha/src imphnen-gateway/src \
imphnen-iam/src imphnen-libs/src imphnen-middleware/src \
imphnen-utils/src tests/src && \
echo "fn main() {}" > imphnen-backend/src/main.rs && \
find . -name "src" -type d -exec sh -c 'echo "// dummy" > "$1/lib.rs"' _ {} \;
FROM gcr.io/distroless/cc AS runner
RUN echo '[package]\nname = "tests"\nversion = "0.1.0"\nedition = "2021"' > tests/Cargo.toml
WORKDIR /app
COPY --from=builder /app/target/release/imphnen-backend-service .
RUN echo -e '[package]\nname = "tests"\nversion = "0.1.0"\nedition = "2021"' > tests/Cargo.toml
CMD ["/app/imphnen-backend-service"]
COPY imphnen-backend ./imphnen-backend
COPY imphnen-cms ./imphnen-cms
COPY imphnen-dimentorin ./imphnen-dimentorin
COPY imphnen-entities ./imphnen-entities
COPY imphnen-gacha ./imphnen-gacha
COPY imphnen-gateway ./imphnen-gateway
COPY imphnen-iam ./imphnen-iam
COPY imphnen-libs ./imphnen-libs
COPY imphnen-middleware ./imphnen-middleware
COPY imphnen-utils ./imphnen-utils
COPY tests ./tests
RUN RUSTFLAGS="-C target-cpu=generic -C opt-level=s -C panic=abort -C codegen-units=1 -C strip=symbols" \
cargo build -p imphnen-backend --release && \
strip target/release/api && \
upx --best --lzma target/release/api 2>/dev/null || true
FROM scratch AS runner
COPY --from=builder /app/target/release/api /api
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
ENTRYPOINT ["/api"]
+35 -12
View File
@@ -6,12 +6,13 @@
This repository serves as the **monorepo** for all backend services of IMPHNEN. It encompasses several main services:
1. **Core Service** - Provides fundamental functionalities and shared resources for other services.
2. **IAM Service** - Handles identity and access management across IMPHNEN applications.
3. **CMS Service** - Supports the cms services by IMPHNEN [Landing Page website](https://imphnen.dev/).
4. **Gacha Service** - Supports the gacha services by IMPHNEN [Gacha website](https://gacha.imphnen.dev/).
5. **Dimentorin Service** - Supports the mentoring services by IMPHNEN [Dimentorin website](https://dimentorin.imphnen.dev/).
6. **Gateway Service** - Acts as the API gateway, routing requests to appropriate services.
1. **IMPHNEN-Backend** - Provides fundamental functionalities and shared resources for other services.
2. **IMPHNEN-IAM** - Handles identity and access management across IMPHNEN applications.
3. **IMPHNEN-CMS** - Supports the cms services by IMPHNEN [Landing Page website](https://imphnen.dev/).
4. **IMPHNEN-Gacha** - Supports the gacha services by IMPHNEN [Gacha website](https://gacha.imphnen.dev/).
5. **IMPHNEN-Dimentorin** - Supports the mentoring services by IMPHNEN [Dimentorin website](https://dimentorin.imphnen.dev/).
6. **IMPHNEN-Gateway** - Acts as the API gateway, routing requests to appropriate services.
7. **IMPHNEN-Middleware** - Acts as the middleware for the API Gateway, providing authentication and authorization.
## How to Install
@@ -39,7 +40,7 @@ This repository serves as the **monorepo** for all backend services of IMPHNEN.
if you use unix based system
```sh
sh apply-env.sh
source ./apply-env.sh
```
- Modify the `.env` files with your specific configuration settings.
@@ -49,7 +50,15 @@ This repository serves as the **monorepo** for all backend services of IMPHNEN.
Ensure you have [Rust](https://www.rust-lang.org/) installed. Then, run:
```sh
cargo build
cargo fetch
```
4. **Run the seeders**:
to run the seeders, run:
```sh
cargo run --bin seeder
```
## How to Run
@@ -64,10 +73,16 @@ To run the services in development mode:
docker-compose up -d
```
2. **Run the desired service**. For example, to run the Core Service:
2. **Run using cargo run**. For example, to run the Core Service:
```sh
cargo run -p imphnen-core-service --bin api
cargo run --bin api
```
3. **Run using cargo watch**. For example, to run the Core Service:
```sh
cargo watch -x "run --bin api"
```
### Production
@@ -77,17 +92,25 @@ For production deployment:
1. **Build the Docker image**:
```sh
docker build -t imphnen-backend-service .
docker build -t imphnen-backend .
```
2. **Run the Docker container**:
```sh
docker run -d --env-file .env -p 8080:8080 imphnen-backend-service
docker run --name imphnen-backend -d --env-file .env -p 3000:3000 imphnen-backend
```
Adjust the port and environment variables as needed.
## How to Run the Tests
1. **Run the tests**:
```sh
cargo test -p tests
```
## How to Contribute
1. **Fork the repository** and clone it locally.
+35
View File
@@ -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
@@ -1,12 +1,15 @@
[package]
name = "imphnen-gacha-service"
name = "imphnen-backend"
version = "0.1.0"
edition = "2024"
edition = "2021"
[dependencies]
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-gateway = { version = "0.1.0", path = "../imphnen-gateway" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-iam = { version = "0.1.0", path = "../imphnen-iam" }
imphnen-cms = { version = "0.1.0", path = "../imphnen-cms" }
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -21,4 +24,5 @@ tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
utoipa-swagger-ui.workspace = true
env_logger.workspace = true
@@ -1,8 +1,10 @@
use imphnen_gateway_service::gateway_service;
use env_logger;
use imphnen_gateway::gateway_service;
use imphnen_libs::axum_init;
#[tokio::main]
async fn main() {
env_logger::init();
axum_init(|surrealdb_ws, surrealdb_mem| async {
gateway_service(surrealdb_ws, surrealdb_mem).await
})
+93
View File
@@ -0,0 +1,93 @@
use imphnen_cms::v1::landing::events::events_schema::EventsSchema;
use imphnen_utils::{get_iso_date, Env};
use std::error::Error;
use surrealdb::engine::any;
use surrealdb::{opt::auth::Root, sql::Thing};
use imphnen_libs::enviroment::load_env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
load_env();
let env = Env::new();
let db = any::connect(&env.surrealdb_url).await?;
db.signin(Root {
username: &env.surrealdb_username,
password: &env.surrealdb_password,
})
.await?;
db.use_ns(env.surrealdb_namespace)
.use_db(env.surrealdb_dbname)
.await?;
let events = vec![
(
"e1a2b3c4-5d6e-7f8g-9h0i-1j2k3l4m5n6o",
"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",
),
(
"f2b3c4d5-6e7f-8g9h-0i1j-2k3l4m5n6o7p",
"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",
),
(
"g3c4d5e6-7f8g-9h0i-1j2k-3l4m5n6o7p8q",
"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",
),
(
"h4d5e6f7-8g9h-0i1j-2k3l-4m5n6o7p8q9r",
"Digital Marketing Masterclass",
"Learn advanced digital marketing strategies, social media optimization, and data-driven marketing techniques.",
"https://digital-marketing.example.com",
100.0,
None,
true,
"2025-09-20T13:00:00Z",
"2025-09-22T15:00:00Z",
),
];
for (id, name, description, detail_link, price, location, is_online, start_date, end_date) in events {
let event = EventsSchema {
id: Thing::from(("app_events", id)),
name: name.into(),
description: description.into(),
detail_link: detail_link.into(),
price,
location,
is_online,
is_deleted: false,
start_date: start_date.into(),
end_date: end_date.into(),
created_at: get_iso_date(),
updated_at: get_iso_date(),
};
db.create::<Option<EventsSchema>>(("app_events", id))
.content(event)
.await?;
println!("✅ Inserted event: {} ({})", name, if is_online { "Online" } else { "In-person" });
}
println!("✅ All Events seeded");
Ok(())
}
@@ -0,0 +1,69 @@
use imphnen_iam::PermissionsEnum;
use imphnen_libs::enviroment::load_env;
use imphnen_utils::{get_iso_date, Env};
use serde_json::json;
use std::error::Error;
use surrealdb::engine::any;
use surrealdb::opt::auth::Root;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
load_env();
let env = Env::new();
let db = any::connect(&env.surrealdb_url).await?;
db.signin(Root {
username: &env.surrealdb_username,
password: &env.surrealdb_password,
})
.await?;
db.use_ns(env.surrealdb_namespace)
.use_db(env.surrealdb_dbname)
.await?;
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,
] {
db.query("CREATE type::thing('app_permissions', $id) CONTENT $data")
.bind(("id", permission.id()))
.bind((
"data",
json!({
"name": permission.to_string(),
"is_deleted": false,
"created_at": get_iso_date(),
"updated_at": get_iso_date()
}),
))
.await?;
println!("✅ Inserted: {}", permission.to_string());
}
println!("✅ All Permissions seeded");
Ok(())
}
@@ -1,12 +1,14 @@
use imphnen_utils::{get_iso_date, Env};
use serde_json::json;
use std::error::Error;
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, Surreal};
use surrealdb::opt::auth::Root;
use imphnen_libs::enviroment::load_env;
use surrealdb::engine::any;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
load_env();
let env = Env::new();
let db = Surreal::new::<Ws>(env.surrealdb_url).await?;
let db = any::connect(&env.surrealdb_url).await?;
db.signin(Root {
username: &env.surrealdb_username,
password: &env.surrealdb_password,
@@ -65,6 +67,6 @@ async fn main() -> Result<(), Box<dyn Error>> {
.await?;
println!("✅ Inserted role: {}", name);
}
println!("Semua role berhasil disimpan ke SurrealDB!");
println!("All Roles seeded");
Ok(())
}
@@ -0,0 +1,58 @@
use imphnen_iam::{get_iso_date, make_thing, Env, PermissionsEnum};
use std::error::Error;
use surrealdb::opt::auth::Root;
use surrealdb::engine::any;
use imphnen_libs::enviroment::load_env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
load_env();
let env = Env::new();
let db = any::connect(&env.surrealdb_url).await?;
db.signin(Root {
username: &env.surrealdb_username,
password: &env.surrealdb_password,
})
.await?;
db.use_ns(env.surrealdb_namespace)
.use_db(env.surrealdb_dbname)
.await?;
let permission_refs_admin: Vec<_> = [
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,
]
.iter()
.map(|perm| make_thing("app_permissions", perm.id()))
.collect();
let admin_role_id = "f6b03f25-e416-4893-ac88-caaa690afb07";
db.query("UPDATE type::thing('app_roles', $role_id) SET permissions = $permissions, updated_at = $updated_at WHERE is_deleted = false")
.bind(("role_id", admin_role_id))
.bind(("permissions", permission_refs_admin))
.bind(("updated_at", get_iso_date()))
.await?;
println!("✅ All permissions successfully added to Admin role");
Ok(())
}
@@ -1,35 +1,14 @@
use imphnen_iam::UsersSchema;
use imphnen_libs::enviroment::load_env;
use imphnen_utils::{get_iso_date, hash_password, Env};
use serde::{Deserialize, Serialize};
use std::error::Error;
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, sql::Thing, Surreal};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UsersSchema {
pub id: Thing,
pub fullname: String,
pub email: String,
pub password: String,
pub avatar: Option<String>,
pub phone_number: String,
pub referral_code: Option<String>,
pub referred_by: Option<String>,
pub identity_number: Option<String>,
pub is_active: bool,
pub is_deleted: bool,
pub student_type: String,
pub religion: Option<String>,
pub gender: Option<String>,
pub birthdate: Option<String>,
pub is_profile_completed: bool,
pub role: Thing,
pub created_at: String,
pub updated_at: String,
}
use surrealdb::{opt::auth::Root, sql::Thing};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
load_env();
let env = Env::new();
let db = Surreal::new::<Ws>(env.surrealdb_url).await?;
use surrealdb::engine::any;
let db = any::connect(&env.surrealdb_url).await?;
db.signin(Root {
username: &env.surrealdb_username,
password: &env.surrealdb_password,
@@ -68,16 +47,10 @@ async fn main() -> Result<(), Box<dyn Error>> {
password: hash_password("password").unwrap(),
avatar: None,
phone_number: "081234567890".into(),
referral_code: None,
referred_by: None,
identity_number: None,
is_active: true,
is_deleted: false,
student_type: "TNI".into(),
religion: None,
gender: None,
birthdate: None,
is_profile_completed: false,
role: Thing::from(("app_roles", role_id)),
created_at: get_iso_date(),
updated_at: get_iso_date(),
@@ -90,6 +63,6 @@ async fn main() -> Result<(), Box<dyn Error>> {
println!("✅ Inserted user: {} ({})", fullname, email);
}
println!("Semua users berhasil disimpan ke SurrealDB!");
println!("All Users seeded");
Ok(())
}
+26
View File
@@ -0,0 +1,26 @@
use std::error::Error;
use std::process::Command;
fn run_seed(bin: &str) -> Result<(), Box<dyn Error>> {
println!("🔧 Seeding: {bin}");
let status = Command::new("cargo").args(["run", "--bin", bin]).status()?;
if !status.success() {
Err(format!("❌ Failed to run seed: {bin}").into())
} else {
Ok(())
}
}
fn main() -> Result<(), Box<dyn Error>> {
println!("🚀 Running all seeders...\n");
run_seed("seed_permissions")?;
run_seed("seed_roles")?;
run_seed("seed_roles_permissions")?;
run_seed("seed_users")?;
run_seed("seed_events")?;
println!("\n✅ All seeding completed successfully.");
Ok(())
}
@@ -1,4 +1,4 @@
use imphnen_gateway_service::gateway_service;
use imphnen_gateway::gateway_service;
use imphnen_libs::axum_init;
#[tokio::main]
@@ -1,12 +1,13 @@
[package]
name = "imphnen-dimentorin-service"
name = "imphnen-cms"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-iam = { version = "0.1.0", path = "../imphnen-iam" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -21,4 +22,4 @@ tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
utoipa-swagger-ui.workspace = true
+2
View File
@@ -0,0 +1,2 @@
pub mod v1;
pub use v1::*;
@@ -0,0 +1,119 @@
use super::{
events_dto::{
EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto,
EventsUpdateRequestDto,
},
events_service::EventsService,
};
use axum::extract::{Path, Query};
use axum::response::IntoResponse;
use axum::{Extension, Json};
use imphnen_libs::{
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
ResponseSuccessDto,
};
#[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 = "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 = "Get event by ID", body = ResponseSuccessDto<EventsDetailItemDto>)
),
tag = "Events"
)]
pub async fn get_event_by_id(
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
EventsService::get_event_by_id(&state, id).await
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/cms/landing/events/create",
request_body = EventsCreateRequestDto,
responses(
(status = 201, description = "Create new event", body = MessageResponseDto)
),
tag = "Events"
)]
pub async fn post_create_event(
Extension(state): Extension<AppState>,
Json(payload): Json<EventsCreateRequestDto>,
) -> impl IntoResponse {
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 = "Update event", body = MessageResponseDto)
),
tag = "Events"
)]
pub async fn patch_update_event(
Extension(state): Extension<AppState>,
Path(id): Path<String>,
Json(payload): Json<EventsUpdateRequestDto>,
) -> impl IntoResponse {
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 = "Soft delete event", body = MessageResponseDto)
),
tag = "Events"
)]
pub async fn delete_event(
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
EventsService::delete_event(&state, id).await
}
@@ -0,0 +1,121 @@
use chrono::{DateTime, Utc};
use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
use validator::Validate;
// Lazy static regex for URL validation
lazy_static! {
static ref VALID_URL_REGEX: Regex = Regex::new(r"^https?://").unwrap();
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct EventsCreateRequestDto {
#[validate(length(min = 1, message = "Name is required"))]
pub name: String,
#[validate(length(min = 1, message = "Description is required"))]
pub description: String,
#[validate(regex(
path = "VALID_URL_REGEX",
message = "Detail link must be a valid URL"
))]
pub detail_link: String,
#[validate(range(min = 0, message = "Price cannot be negative"))]
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,
}
#[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>,
pub price: f64,
pub is_online: bool,
pub description: String,
pub detail_link: String,
pub location: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventsListItemDto {
pub id: String,
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
pub is_online: bool,
pub start_date: String,
pub end_date: String,
pub created_at: String,
pub location: Option<String>,
pub is_deleted: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventsDetailItemDto {
pub id: String,
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
pub is_online: bool,
pub start_date: String,
pub end_date: String,
pub created_at: String,
pub updated_at: String,
pub location: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EventsQueryDto {
pub id: Thing,
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
pub is_online: bool,
pub is_deleted: bool,
pub start_date: String,
pub end_date: String,
pub created_at: String,
pub updated_at: String,
pub location: Option<String>,
}
impl EventsQueryDto {
pub fn from(self) -> EventsListItemDto {
EventsListItemDto {
id: self.id.id.to_raw(),
name: self.name,
description: self.description,
detail_link: self.detail_link,
price: self.price,
location: self.location,
is_online: self.is_online,
start_date: self.start_date,
end_date: self.end_date,
created_at: self.created_at,
is_deleted: self.is_deleted,
}
}
}
@@ -0,0 +1,113 @@
use super::{events_dto::EventsQueryDto, events_schema::EventsSchema};
use anyhow::{Result, bail};
use imphnen_libs::{AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto};
use imphnen_utils::{DetailQueryBuilder, ListQueryBuilder, get_id, get_iso_date};
pub struct EventsRepository<'a> {
state: &'a AppState,
}
impl<'a> EventsRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_event_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<EventsQueryDto>>> {
let query = ListQueryBuilder::new(&ResourceEnum::Events.to_string())
.with_select_fields(vec!["*"])
.with_pagination(meta.page, Some(10))
.with_sorting(meta.sort_by.as_deref(), meta.order.as_deref())
.build();
let res: Vec<EventsQueryDto> =
self.state.surrealdb_ws.query(query).await?.take(0)?;
let data = ResponseListSuccessDto {
data: res,
meta: None,
};
Ok(data)
}
// Get event by ID
pub async fn query_event_by_id(&self, id: String) -> Result<EventsQueryDto> {
let db = &self.state.surrealdb_ws;
let builder = DetailQueryBuilder::new(ResourceEnum::Events.to_string())
.with_id(&id)
.with_select_fields(vec!["*"]);
let sql = builder.build();
let result: Option<EventsQueryDto> =
builder.apply_bindings(db.query(sql)).await?.take(0)?;
match result {
Some(event) => {
if event.is_deleted {
bail!("Event not found");
}
Ok(event)
}
None => bail!("Event not found"),
}
}
// Create new event
pub async fn query_create_event(&self, data: EventsSchema) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record: Option<EventsSchema> = db
.create(ResourceEnum::Events.to_string())
.content(data)
.await?;
match record {
Some(_) => Ok("Success create event".into()),
None => bail!("Failed to create event"),
}
}
// Update existing event
pub async fn query_update_event(&self, data: EventsSchema) -> Result<String> {
let db = &self.state.surrealdb_ws;
// Cek apakah event ada
let existing = self.query_event_by_id(data.id.id.to_raw()).await?;
if existing.is_deleted {
bail!("Event already deleted");
}
// Merge field tertentu jika diperlukan
let merged = EventsSchema {
created_at: existing.created_at,
updated_at: get_iso_date(),
..data
};
let record_key = get_id(&merged.id)?;
let record: Option<EventsSchema> = db.update(record_key).merge(merged).await?;
match record {
Some(_) => Ok("Success update event".into()),
None => bail!("Failed to update event"),
}
}
// Soft delete event (mark is_deleted = true)
pub async fn query_delete_event(&self, id: String) -> Result<String> {
let db = &self.state.surrealdb_ws;
let event = self.query_event_by_id(id).await?;
if event.is_deleted {
bail!("Event not found");
}
let record_key = get_id(&event.id)?;
let record: Option<EventsSchema> = db
.update(record_key)
.merge(serde_json::json!({ "is_deleted": true }))
.await?;
match record {
Some(_) => Ok("Success delete event".into()),
None => bail!("Failed to delete event"),
}
}
}
@@ -0,0 +1,100 @@
use imphnen_libs::ResourceEnum;
use surrealdb::Uuid;
use surrealdb::sql::Thing;
use serde::{Deserialize, Serialize};
use imphnen_utils::{get_iso_date, make_thing};
use super::events_dto::{EventsCreateRequestDto, EventsQueryDto, EventsUpdateRequestDto};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EventsSchema {
pub id: Thing,
pub price: f64,
pub is_online: bool,
pub is_deleted: bool,
pub name: String,
pub end_date: String,
pub start_date: String,
pub created_at: String,
pub updated_at: String,
pub description: String,
pub detail_link: String,
pub location: Option<String>,
}
impl Default for EventsSchema {
fn default() -> Self {
Self {
id: make_thing(
&ResourceEnum::Events.to_string(),
&Uuid::new_v4().to_string(),
),
name: String::new(),
description: String::new(),
detail_link: String::new(),
price: 0.0,
location: None,
is_online: false,
is_deleted: false,
start_date: String::new(),
end_date: String::new(),
created_at: get_iso_date(),
updated_at: get_iso_date(),
}
}
}
impl EventsSchema {
pub fn from(dto: EventsQueryDto) -> Self {
Self {
id: dto.id,
name: dto.name,
description: dto.description,
detail_link: dto.detail_link,
price: dto.price,
location: dto.location,
is_online: dto.is_online,
is_deleted: false,
start_date: dto.start_date,
end_date: dto.end_date,
created_at: dto.created_at,
updated_at: dto.updated_at,
}
}
pub fn create(payload: EventsCreateRequestDto) -> Self {
Self {
id: make_thing(
&ResourceEnum::Events.to_string(),
&Uuid::new_v4().to_string(),
),
name: payload.name,
description: payload.description,
detail_link: payload.detail_link,
price: payload.price,
location: payload.location,
is_online: payload.is_online,
is_deleted: false,
end_date: payload.end_date.to_string(),
start_date: payload.start_date.to_string(),
created_at: get_iso_date(),
updated_at: get_iso_date(),
}
}
pub fn update(payload: EventsUpdateRequestDto, id: String) -> Self {
Self {
id: make_thing(&ResourceEnum::Events.to_string(), &id),
name: payload.name,
price: payload.price,
location: payload.location,
is_online: payload.is_online,
description: payload.description,
detail_link: payload.detail_link,
end_date: payload.end_date.to_string(),
start_date: payload.start_date.to_string(),
updated_at: get_iso_date(),
..Default::default()
}
}
}
@@ -0,0 +1,86 @@
use super::{
events_dto::{EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto, EventsQueryDto, EventsUpdateRequestDto},
events_repository::EventsRepository,
events_schema::EventsSchema,
};
use imphnen_libs::{AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto};
use imphnen_utils::{common_response, success_list_response, success_response, validate_request};
use axum::{http::StatusCode, response::Response};
pub struct EventsService;
impl EventsService {
pub async fn get_event_list(state: &AppState, meta: MetaRequestDto) -> Response {
let repo = EventsRepository::new(state);
match repo.query_event_list(meta).await {
Ok(data) => {
let items: Vec<EventsListItemDto> = data.data
.into_iter()
.filter(|e| !e.is_deleted)
.map(EventsQueryDto::from)
.collect();
let response = ResponseListSuccessDto {
data: items,
meta: data.meta,
};
success_list_response(response)
}
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn get_event_by_id(state: &AppState, id: String) -> Response {
let repo = EventsRepository::new(state);
match repo.query_event_by_id(id).await {
Ok(event) if !event.is_deleted => success_response(ResponseSuccessDto {
data: EventsDetailItemDto {
id: event.id.id.to_raw(),
name: event.name,
description: event.description,
detail_link: event.detail_link,
price: event.price,
is_online: event.is_online,
start_date: event.start_date,
end_date: event.end_date,
created_at: event.created_at,
updated_at: event.updated_at,
location: event.location,
},
}),
Ok(_) => common_response(StatusCode::NOT_FOUND, "Event not found"),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_event(state: &AppState, payload: EventsCreateRequestDto) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = EventsRepository::new(state);
let schema = EventsSchema::create(payload);
match repo.query_create_event(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn update_event(state: &AppState, id: String, payload: EventsUpdateRequestDto) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = EventsRepository::new(state);
let schema = EventsSchema::update(payload, id);
match repo.query_update_event(schema).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn delete_event(state: &AppState, id: String) -> Response {
let repo = EventsRepository::new(state);
match repo.query_delete_event(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
}
+44
View File
@@ -0,0 +1,44 @@
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;
pub use events_controller::*;
pub use events_dto::*;
pub use events_repository::*;
pub use events_schema::*;
pub use events_service::*;
pub fn events_public_routes() -> Router {
Router::new()
.route(
"/cms/landing/events",
get(events_controller::get_event_list),
)
.route(
"/cms/landing/events/detail/{id}",
get(events_controller::get_event_by_id),
)
}
pub fn events_protected_routes() -> Router {
Router::new()
.route(
"/cms/landing/events/create",
post(events_controller::post_create_event),
)
.route(
"/cms/landing/events/update/{id}",
patch(events_controller::patch_update_event),
)
.route(
"/cms/landing/events/delete/{id}",
delete(events_controller::delete_event),
)
}
+5
View File
@@ -0,0 +1,5 @@
pub mod events;
pub mod testimonials;
pub use events::*;
pub use testimonials::*;
@@ -0,0 +1,44 @@
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;
pub use testimonials_controller::*;
pub use testimonials_dto::*;
pub use testimonials_repository::*;
pub use testimonials_schema::*;
pub use testimonials_service::*;
pub fn testimonials_public_routes() -> Router {
Router::new()
.route(
"/cms/landing/testimonials",
get(testimonials_controller::get_testimonial_list),
)
.route(
"/cms/landing/testimonials/detail/{id}",
get(testimonials_controller::get_testimonial_by_id),
)
}
pub fn testimonials_protected_routes() -> Router {
Router::new()
.route(
"/cms/landing/testimonials/create",
post(testimonials_controller::post_create_testimonial),
)
.route(
"/cms/landing/testimonials/update/{id}",
patch(testimonials_controller::patch_update_testimonial),
)
.route(
"/cms/landing/testimonials/delete/{id}",
delete(testimonials_controller::delete_testimonial),
)
}
@@ -0,0 +1,125 @@
use super::{
testimonials_dto::{
TestimonialsCreateRequestDto, TestimonialsDetailItemDto,
TestimonialsListItemDto, TestimonialsUpdateRequestDto,
},
testimonials_service::TestimonialsService,
};
use axum::extract::{Path, Query};
use axum::response::IntoResponse;
use axum::{Extension, Json};
use imphnen_iam::UsersDetailQueryDto;
use imphnen_libs::{
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
ResponseSuccessDto,
};
#[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 = "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 = "Get testimonial by ID", body = ResponseSuccessDto<TestimonialsDetailItemDto>)
),
tag = "Testimonials"
)]
pub async fn get_testimonial_by_id(
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
TestimonialsService::get_testimonial_by_id(&state, id).await
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/cms/landing/testimonials/create",
request_body = TestimonialsCreateRequestDto,
responses(
(status = 201, description = "Create new testimonial", body = MessageResponseDto)
),
tag = "Testimonials"
)]
pub async fn post_create_testimonial(
Extension(state): Extension<AppState>,
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
Json(payload): Json<TestimonialsCreateRequestDto>,
) -> impl IntoResponse {
println!("Authenticated User Now: {:?}", authenticated_user);
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 = "Update testimonial", body = MessageResponseDto)
),
tag = "Testimonials"
)]
pub async fn patch_update_testimonial(
Path(id): Path<String>,
Extension(state): Extension<AppState>,
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
Json(payload): Json<TestimonialsUpdateRequestDto>,
) -> impl IntoResponse {
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 = "Soft delete testimonial", body = MessageResponseDto)
),
tag = "Testimonials"
)]
pub async fn delete_testimonial(
Extension(state): Extension<AppState>,
Extension(authenticated_user): Extension<UsersDetailQueryDto>,
Path(id): Path<String>,
) -> impl IntoResponse {
TestimonialsService::delete_testimonial(&state, id, &authenticated_user).await
}
@@ -0,0 +1,78 @@
use imphnen_iam::users::UsersSchema;
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
use validator::Validate;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct TestimonialsCreateRequestDto {
#[validate(length(min = 1, message = "Role is required"))]
pub role: String,
#[validate(length(
min = 1,
max = 500,
message = "Content must be between 1 and 500 characters"
))]
pub content: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct TestimonialsUpdateRequestDto {
#[validate(length(min = 1, message = "Role is required"))]
pub role: String,
#[validate(length(
min = 1,
max = 500,
message = "Content must be between 1 and 500 characters"
))]
pub content: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct TestimonialsListItemDto {
pub id: String,
pub user_id: String,
pub user_fullname: String, // Assuming we'll fetch user's full name
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, // Assuming we'll fetch user's full name
pub role: String,
pub content: String,
pub created_at: String,
pub updated_at: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TestimonialsQueryDto {
pub id: Thing,
pub user: UsersSchema, // Change from Thing to UsersSchema
pub role: String,
pub content: String,
pub is_deleted: bool,
pub created_at: String,
pub updated_at: String,
}
impl TestimonialsQueryDto {
pub fn from(self) -> TestimonialsListItemDto {
TestimonialsListItemDto {
id: self.id.id.to_raw(),
user_id: self.user.id.id.to_raw(),
user_fullname: self.user.fullname, // Extract fullname from UsersSchema
role: self.role,
content: self.content,
created_at: self.created_at,
is_deleted: self.is_deleted,
}
}
}
@@ -0,0 +1,120 @@
use super::{
testimonials_dto::TestimonialsQueryDto, testimonials_schema::TestimonialsSchema,
};
use anyhow::{Result, bail};
use imphnen_libs::{AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto};
use imphnen_utils::{DetailQueryBuilder, ListQueryBuilder, get_id, get_iso_date};
pub struct TestimonialsRepository<'a> {
state: &'a AppState,
}
impl<'a> TestimonialsRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_testimonial_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<TestimonialsQueryDto>>> {
let query = ListQueryBuilder::new(&ResourceEnum::Testimonials.to_string())
.with_select_fields(vec!["*", "user.* as user"]) // Select user details
.with_pagination(meta.page, Some(10))
.with_sorting(meta.sort_by.as_deref(), meta.order.as_deref())
.build();
let res: Vec<TestimonialsQueryDto> =
self.state.surrealdb_ws.query(query).await?.take(0)?;
let data = ResponseListSuccessDto {
data: res,
meta: None,
};
Ok(data)
}
pub async fn query_testimonial_by_id(
&self,
id: String,
) -> Result<TestimonialsQueryDto> {
let db = &self.state.surrealdb_ws;
let builder = DetailQueryBuilder::new(ResourceEnum::Testimonials.to_string())
.with_id(&id)
.with_select_fields(vec!["*", "user.* as user"]); // Select user details
let sql = builder.build();
let result: Option<TestimonialsQueryDto> =
builder.apply_bindings(db.query(sql)).await?.take(0)?;
match result {
Some(testimonial) => {
if testimonial.is_deleted {
bail!("Testimonial not found");
}
Ok(testimonial)
}
None => bail!("Testimonial not found"),
}
}
pub async fn query_create_testimonial(
&self,
data: TestimonialsSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record: Option<TestimonialsSchema> = db
.create(ResourceEnum::Testimonials.to_string())
.content(data)
.await?;
match record {
Some(_) => Ok("Success create testimonial".into()),
None => bail!("Failed to create testimonial"),
}
}
pub async fn query_update_testimonial(
&self,
data: TestimonialsSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let existing = self.query_testimonial_by_id(data.id.id.to_raw()).await?;
if existing.is_deleted {
bail!("Testimonial already deleted");
}
let merged = TestimonialsSchema {
created_at: existing.created_at,
updated_at: get_iso_date(),
user: existing.user.id, // Preserve user ID
..data
};
let record_key = get_id(&merged.id)?;
let record: Option<TestimonialsSchema> =
db.update(record_key).merge(merged).await?;
match record {
Some(_) => Ok("Success update testimonial".into()),
None => bail!("Failed to update testimonial"),
}
}
pub async fn query_delete_testimonial(&self, id: String) -> Result<String> {
let db = &self.state.surrealdb_ws;
let testimonial = self.query_testimonial_by_id(id).await?;
if testimonial.is_deleted {
bail!("Testimonial not found");
}
let record_key = get_id(&testimonial.id)?;
let record: Option<TestimonialsSchema> = db
.update(record_key)
.merge(serde_json::json!({ "is_deleted": true }))
.await?;
match record {
Some(_) => Ok("Success delete testimonial".into()),
None => bail!("Failed to delete testimonial"),
}
}
}
@@ -0,0 +1,84 @@
use imphnen_libs::ResourceEnum;
use imphnen_utils::{get_iso_date, make_thing};
use serde::{Deserialize, Serialize};
use surrealdb::Uuid;
use surrealdb::sql::Thing;
use super::testimonials_dto::{
TestimonialsCreateRequestDto, TestimonialsQueryDto, TestimonialsUpdateRequestDto,
};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TestimonialsSchema {
pub id: Thing,
pub user: Thing, // Link to app_users table
pub role: String,
pub content: String,
pub is_deleted: bool,
pub created_at: String,
pub updated_at: String,
}
impl Default for TestimonialsSchema {
fn default() -> Self {
Self {
id: make_thing(
&ResourceEnum::Testimonials.to_string(),
&Uuid::new_v4().to_string(),
),
user: make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(), // Placeholder, will be replaced by actual user ID
),
role: String::new(),
content: String::new(),
is_deleted: false,
created_at: get_iso_date(),
updated_at: get_iso_date(),
}
}
}
impl TestimonialsSchema {
pub fn from(dto: TestimonialsQueryDto) -> Self {
Self {
id: dto.id,
user: dto.user.id,
role: dto.role,
content: dto.content,
is_deleted: dto.is_deleted,
created_at: dto.created_at,
updated_at: dto.updated_at,
}
}
pub fn create(payload: TestimonialsCreateRequestDto, user_id: &Thing) -> Self {
Self {
id: make_thing(
&ResourceEnum::Testimonials.to_string(),
&Uuid::new_v4().to_string(),
),
user: user_id.clone(),
role: payload.role,
content: payload.content,
is_deleted: false,
created_at: get_iso_date(),
updated_at: get_iso_date(),
}
}
pub fn update(
payload: TestimonialsUpdateRequestDto,
id: String,
user_id: &Thing,
) -> Self {
Self {
id: make_thing(&ResourceEnum::Testimonials.to_string(), &id),
role: payload.role,
content: payload.content,
updated_at: get_iso_date(),
user: user_id.clone(),
..Default::default()
}
}
}
@@ -0,0 +1,108 @@
use super::{
testimonials_dto::{
TestimonialsCreateRequestDto, TestimonialsDetailItemDto,
TestimonialsListItemDto, TestimonialsUpdateRequestDto,
},
testimonials_repository::TestimonialsRepository,
testimonials_schema::TestimonialsSchema,
};
use axum::{http::StatusCode, response::Response};
use imphnen_libs::{
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
};
use imphnen_utils::{
common_response, success_list_response, success_response, validate_request,
};
pub struct TestimonialsService;
impl TestimonialsService {
pub async fn get_testimonial_list(
state: &AppState,
meta: MetaRequestDto,
) -> Response {
let repo = TestimonialsRepository::new(state);
match repo.query_testimonial_list(meta).await {
Ok(data) => {
let items: Vec<TestimonialsListItemDto> = data
.data
.into_iter()
.filter(|e| !e.is_deleted)
.map(|e| e.from())
.collect();
let response = ResponseListSuccessDto {
data: items,
meta: data.meta,
};
success_list_response(response)
}
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn get_testimonial_by_id(state: &AppState, id: String) -> Response {
let repo = TestimonialsRepository::new(state);
match repo.query_testimonial_by_id(id).await {
Ok(testimonial) if !testimonial.is_deleted => {
success_response(ResponseSuccessDto {
data: TestimonialsDetailItemDto {
id: testimonial.id.id.to_raw(),
user_id: testimonial.user.id.id.to_raw(),
user_fullname: testimonial.user.fullname,
role: testimonial.role,
content: testimonial.content,
created_at: testimonial.created_at,
updated_at: testimonial.updated_at,
},
})
}
Ok(_) => common_response(StatusCode::NOT_FOUND, "Testimonial not found"),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_testimonial(
state: &AppState,
payload: TestimonialsCreateRequestDto,
authenticated_user: &imphnen_iam::UsersDetailQueryDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = TestimonialsRepository::new(state);
let schema = TestimonialsSchema::create(payload, &authenticated_user.id);
match repo.query_create_testimonial(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn update_testimonial(
state: &AppState,
id: String,
payload: TestimonialsUpdateRequestDto,
authenticated_user: &imphnen_iam::UsersDetailQueryDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = TestimonialsRepository::new(state);
let schema = TestimonialsSchema::update(payload, id, &authenticated_user.id);
match repo.query_update_testimonial(schema).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn delete_testimonial(
state: &AppState,
id: String,
_authenticated_user: &imphnen_iam::UsersDetailQueryDto,
) -> Response {
let repo = TestimonialsRepository::new(state);
match repo.query_delete_testimonial(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod landing;
pub use landing::*;
@@ -1,145 +0,0 @@
use imphnen_utils::{get_iso_date, Env};
use serde_json::json;
use std::error::Error;
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, Surreal};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let env = Env::new();
let db = Surreal::new::<Ws>(env.surrealdb_url).await?;
db.signin(Root {
username: &env.surrealdb_username,
password: &env.surrealdb_password,
})
.await?;
db.use_ns(env.surrealdb_namespace)
.use_db(env.surrealdb_dbname)
.await?;
let permissions = vec![
(
"023e2dfe-93c3-4008-94a8-b5dff403f73b",
"Create Users",
Some("2025-01-29T06:08:23.838311+00"),
Some("2025-01-29T06:08:23.838312+00"),
),
(
"0269ed71-0ae0-4c43-ad29-e3d861d8f9a0",
"Create Permissions",
None,
None,
),
(
"299cb4d5-6556-4cc9-b6c1-32e6d31e0f9b",
"Update Permissions",
Some("2025-01-29T05:11:01.265+00"),
Some("2025-01-29T05:11:01.265001+00"),
),
(
"319ee593-ff0a-4f29-bbaf-9feb3174a3a2",
"Create Roles",
None,
None,
),
(
"319ee593-ff0a-4f29-bbaf-9feb3174a3a6",
"Read Detail Users",
None,
None,
),
(
"35b0d992-65c8-4b62-b030-e6e0320e4048",
"Delete Roles",
None,
None,
),
(
"4da8b434-89f9-4d91-85ae-eebd63cdbeda",
"Update Activate Users",
Some("2025-02-01T12:38:09.741726+00"),
Some("2025-02-01T12:38:09.741727+00"),
),
(
"73888d18-b3e9-4f62-95a5-ba2c0d69fccb",
"Read Detail Roles",
Some("2025-01-29T05:13:06.445925+00"),
Some("2025-01-29T10:31:46.408564+00"),
),
(
"7c15e31d-36e2-49f9-97db-138c03fb0cf6",
"Read List Users",
Some("2025-01-28T15:02:41.772931+00"),
Some("2025-01-28T15:02:41.772933+00"),
),
(
"7d4b1379-4960-416a-b045-98cd82c0cac9",
"Read Detail Sessions",
Some("2025-02-24T16:52:26.886664+00"),
Some("2025-02-24T16:52:26.886673+00"),
),
(
"8195eeb8-e64f-4172-aa57-596492c84a72",
"Read List Permissions",
Some("2025-01-28T15:05:28.6299+00"),
Some("2025-01-28T15:05:28.629901+00"),
),
(
"81eba91d-b8ab-44b9-bbfe-4e6da2f98952",
"Read List Tests",
Some("2025-02-24T16:52:27.179542+00"),
Some("2025-02-24T16:52:27.179551+00"),
),
(
"9164ca6e-c7e3-4238-a15f-f36ab9577e7e",
"Read List Roles",
None,
None,
),
(
"96df0689-2ae9-4894-bf00-837c19415e5c",
"Delete Users",
Some("2025-02-02T06:52:05.195565+00"),
Some("2025-02-02T06:52:05.195565+00"),
),
(
"98b3dc4c-0124-461f-afcd-166637c5e6e8",
"Update Users",
Some("2025-01-29T05:34:40.621554+00"),
Some("2025-01-29T05:34:40.621555+00"),
),
(
"a00d5608-4c48-4542-845c-dfe004687022",
"Update Roles",
None,
None,
),
(
"b2dc3928-86ba-4c59-a03d-0b57d5183ebc",
"Delete Permissions",
Some("2025-01-29T05:14:22.511084+00"),
Some("2025-01-29T05:14:22.511085+00"),
),
(
"dad435cf-042c-41bd-a946-cea61ed2ffbc",
"Read Detail Permissions",
Some("2025-01-28T15:07:10.990214+00"),
Some("2025-01-28T15:07:10.990214+00"),
),
];
for (id, name, _created_at, _updated_at) in permissions {
db.query("CREATE type::thing('app_permissions', $id) CONTENT $data")
.bind(("id", id))
.bind((
"data",
json!({
"name": name,
"is_deleted": false,
"created_at": get_iso_date(),
"updated_at": get_iso_date()
}),
))
.await?;
println!("✅ Inserted: {}", name);
}
println!("✅ Semua permissions berhasil disimpan ke SurrealDB!");
Ok(())
}
@@ -1,59 +0,0 @@
use imphnen_utils::{get_iso_date, make_thing, Env};
use std::error::Error;
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, Surreal};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let env = Env::new();
let db = Surreal::new::<Ws>(env.surrealdb_url).await?;
db.signin(Root {
username: &env.surrealdb_username,
password: &env.surrealdb_password,
})
.await?;
db.use_ns(env.surrealdb_namespace)
.use_db(env.surrealdb_dbname)
.await?;
let role_permissions = vec![
(
"50133429-f4b1-4249-9f97-7b86e6ee9d86", // Staf
vec![
"7c15e31d-36e2-49f9-97db-138c03fb0cf6", // Read List Users
"319ee593-ff0a-4f29-bbaf-9feb3174a3a6", // Read Detail Users
],
),
(
"f6b03f25-e416-4893-ac88-caaa690afb07", // Admin
vec![
"023e2dfe-93c3-4008-94a8-b5dff403f73b", // Create Users
"96df0689-2ae9-4894-bf00-837c19415e5c", // Delete Users
"98b3dc4c-0124-461f-afcd-166637c5e6e8", // Update Users
"319ee593-ff0a-4f29-bbaf-9feb3174a3a6", // Read Detail Users
"7c15e31d-36e2-49f9-97db-138c03fb0cf6", // Read List Users
"9164ca6e-c7e3-4238-a15f-f36ab9577e7e", // Read List Roles
"319ee593-ff0a-4f29-bbaf-9feb3174a3a2", // Create Roles
"a00d5608-4c48-4542-845c-dfe004687022", // Update Roles
"35b0d992-65c8-4b62-b030-e6e0320e4048", // Delete Roles
],
),
];
for (role_id, permission_ids) in role_permissions {
let permission_refs: Vec<_> = permission_ids
.into_iter()
.map(|perm_id| make_thing("app_permissions", perm_id))
.collect();
db.query("UPDATE type::thing('app_roles', $role_id) SET permissions = $permissions, updated_at = $updated_at")
.bind(("role_id", role_id))
.bind(("permissions", permission_refs))
.bind(("updated_at", get_iso_date()))
.await?;
println!("✅ Updated permissions for role ID: {}", role_id);
}
println!("✅ Semua roles telah diperbarui dengan permissions di SurrealDB!");
Ok(())
}
-14
View File
@@ -1,14 +0,0 @@
pub fn add(left: u64, right: u64) -> u64 {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
@@ -1,12 +1,12 @@
[package]
name = "imphnen-cms-service"
name = "imphnen-dimentorin"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -21,4 +21,4 @@ tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
utoipa-swagger-ui.workspace = true
View File
+2 -2
View File
@@ -6,6 +6,6 @@ edition = "2024"
[dependencies]
axum.workspace = true
serde.workspace = true
surrealdb = { workspace = true, features = ["kv-mem"] }
thiserror.workspace = true
utoipa.workspace = true
surrealdb.workspace = true
thiserror.workspace = true
+3 -2
View File
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};
use surrealdb::{
engine::{local::Db, remote::ws::Client},
engine::local::Db,
engine::any::Any,
Surreal,
};
use utoipa::{IntoParams, ToSchema};
@@ -54,7 +55,7 @@ pub struct ResponseListSuccessDto<T: Serialize> {
pub meta: Option<MetaResponseDto>,
}
pub type SurrealWsClient = Surreal<Client>;
pub type SurrealWsClient = Surreal<Any>;
pub type SurrealMemClient = Surreal<Db>;
#[derive(Clone)]
@@ -1,35 +0,0 @@
use crate::{ResourceEnum, make_thing};
use serde::{Deserialize, Serialize};
use surrealdb::{Uuid, sql::Thing};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaClaimSchema {
pub id: Thing,
pub user: Thing,
pub item: Thing,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for GachaClaimSchema {
fn default() -> Self {
GachaClaimSchema {
id: make_thing(
&ResourceEnum::GachaClaims.to_string(),
&Uuid::new_v4().to_string(),
),
user: make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(),
),
item: make_thing(
&ResourceEnum::GachaItems.to_string(),
&Uuid::new_v4().to_string(),
),
is_deleted: false,
created_at: None,
updated_at: None,
}
}
}
@@ -1,7 +0,0 @@
pub mod gacha_claim_dto;
pub mod gacha_claim_repository;
pub mod gacha_claim_schema;
pub use gacha_claim_dto::*;
pub use gacha_claim_repository::*;
pub use gacha_claim_schema::*;
@@ -1,7 +0,0 @@
pub mod gacha_item_dto;
pub mod gacha_item_repository;
pub mod gacha_item_schema;
pub use gacha_item_dto::*;
pub use gacha_item_repository::*;
pub use gacha_item_schema::*;
@@ -1,39 +0,0 @@
use super::GachaRollSchema;
use crate::{AppState, ResourceEnum};
use anyhow::{Result, bail};
pub struct GachaRollRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaRollRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_gacha_roll_by_id(&self, id: String) -> Result<GachaRollSchema> {
let db = &self.state.surrealdb_ws;
let result: Option<GachaRollSchema> = db
.select((ResourceEnum::GachaRolls.to_string(), id.clone()))
.await?;
match result {
Some(roll) if !roll.is_deleted => Ok(roll),
_ => bail!("Gacha Roll not found"),
}
}
pub async fn query_create_gacha_roll(
&self,
data: GachaRollSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record: Option<GachaRollSchema> = db
.create(ResourceEnum::GachaRolls.to_string())
.content(data)
.await?;
match record {
Some(_) => Ok("Success create Gacha Roll".into()),
None => bail!("Failed to create Gacha Roll"),
}
}
}
@@ -1,7 +0,0 @@
pub mod gacha_roll_dto;
pub mod gacha_roll_repository;
pub mod gacha_roll_schema;
pub use gacha_roll_dto::*;
pub use gacha_roll_repository::*;
pub use gacha_roll_schema::*;
-7
View File
@@ -1,7 +0,0 @@
pub mod gacha_claim;
pub mod gacha_item;
pub mod gacha_roll;
pub use gacha_claim::*;
pub use gacha_item::*;
pub use gacha_roll::*;
@@ -1,13 +1,13 @@
[package]
name = "imphnen-backend-service"
name = "imphnen-gacha"
version = "0.1.0"
edition = "2021"
edition = "2024"
[dependencies]
imphnen-iam ={ version = "0.1.0", path = "../imphnen-iam" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-gateway-service = { version = "0.1.0", path = "../imphnen-gateway-service" }
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -23,3 +23,4 @@ chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
rand_distr.workspace = true
@@ -3,6 +3,7 @@ use imphnen_libs::*;
use imphnen_utils::*;
pub mod v1;
pub use imphnen_entities::*;
pub use imphnen_libs::*;
pub use imphnen_utils::*;
@@ -0,0 +1,66 @@
use axum::Extension;
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use axum::{Json, extract::Path};
use imphnen_iam::{PermissionsEnum, permissions_guard};
use imphnen_libs::{AppState, MessageResponseDto, ResponseSuccessDto};
use super::{GachaClaimItemDto, GachaClaimRequestDto, GachaClaimService};
#[utoipa::path(
get,
path = "/v1/gacha/claims/detail/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Gacha Claim ID")),
responses(
(status = 200, description = "Get Gacha Claim by ID", body = ResponseSuccessDto<GachaClaimItemDto>)
),
tag = "Gacha"
)]
pub async fn get_detail_gacha_claim(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::CreateGachaClaims],
)
.await
{
Ok(_) => GachaClaimService::get_gacha_claim_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/gacha/claims/create",
request_body = GachaClaimRequestDto,
responses(
(status = 201, description = "Create new gacha claim", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn post_create_gacha_claim(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<GachaClaimRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::CreateGachaClaims],
)
.await
{
Ok(_) => GachaClaimService::create_gacha_claim(&state, payload).await,
Err(response) => response,
}
}
@@ -1,3 +1,5 @@
use crate::{GachaItemDto, GachaItemSchema};
use imphnen_iam::{UsersDetailItemDto, UsersDetailQueryDto};
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
@@ -7,27 +9,39 @@ use validator::Validate;
pub struct GachaClaimRequestDto {
#[validate(length(min = 1, message = "User ID must not be empty"))]
pub user_id: String,
#[validate(length(min = 1, message = "Item ID must not be empty"))]
pub item_id: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaClaimDto {
pub struct GachaClaimItemDto {
pub id: String,
pub user: String,
pub item: String,
pub user: UsersDetailItemDto,
pub item: GachaItemDto,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaClaimDtoRaw {
pub struct GachaClaimQueryDto {
pub id: Thing,
pub user: Thing,
pub item: Thing,
pub user: UsersDetailQueryDto,
pub item: GachaItemSchema,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl GachaClaimItemDto {
pub fn from(dto: &GachaClaimQueryDto) -> Self {
Self {
id: dto.id.id.to_raw(),
user: UsersDetailItemDto::from(&dto.user),
item: GachaItemDto::from(dto.item.clone()),
is_deleted: dto.is_deleted,
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
}
}
}
@@ -1,6 +1,7 @@
use super::GachaClaimSchema;
use super::{GachaClaimQueryDto, GachaClaimSchema};
use crate::{AppState, ResourceEnum};
use anyhow::{Result, bail};
use imphnen_iam::DetailQueryBuilder;
pub struct GachaClaimRepository<'a> {
state: &'a AppState,
@@ -14,11 +15,16 @@ impl<'a> GachaClaimRepository<'a> {
pub async fn query_gacha_claim_by_id(
&self,
id: String,
) -> Result<GachaClaimSchema> {
) -> Result<GachaClaimQueryDto> {
let db = &self.state.surrealdb_ws;
let result: Option<GachaClaimSchema> = db
.select((ResourceEnum::GachaClaims.to_string(), id.clone()))
.await?;
let builder = DetailQueryBuilder::new(ResourceEnum::GachaClaims.to_string())
.with_id(id.clone())
.with_select_fields(vec!["*"])
.with_fetch("item")
.with_fetch("user");
let sql = builder.build();
let result: Option<GachaClaimQueryDto> =
builder.apply_bindings(db.query(sql)).await?.take(0)?;
match result {
Some(claim) if !claim.is_deleted => Ok(claim),
_ => bail!("Gacha Claim not found"),
@@ -0,0 +1,64 @@
use crate::{GachaRollQueryDto, ResourceEnum, make_thing};
use imphnen_iam::get_iso_date;
use serde::{Deserialize, Serialize};
use surrealdb::{Uuid, sql::Thing};
use super::GachaClaimRequestDto;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaClaimSchema {
pub id: Thing,
pub user: Thing,
pub item: Thing,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for GachaClaimSchema {
fn default() -> Self {
GachaClaimSchema {
id: make_thing(
&ResourceEnum::GachaClaims.to_string(),
&Uuid::new_v4().to_string(),
),
user: make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(),
),
item: make_thing(
&ResourceEnum::GachaItems.to_string(),
&Uuid::new_v4().to_string(),
),
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
impl GachaClaimSchema {
pub fn from(dto: GachaClaimRequestDto) -> Self {
Self {
id: make_thing(
&ResourceEnum::GachaClaims.to_string(),
&Uuid::new_v4().to_string(),
),
user: make_thing(&ResourceEnum::Users.to_string(), &dto.user_id),
item: make_thing(&ResourceEnum::GachaItems.to_string(), &dto.item_id),
..Default::default()
}
}
pub fn roll(roll: GachaRollQueryDto, user_id: Thing) -> Self {
Self {
id: make_thing(
&ResourceEnum::GachaClaims.to_string(),
&Uuid::new_v4().to_string(),
),
user: user_id,
item: roll.item.id.clone(),
..Default::default()
}
}
}
@@ -0,0 +1,36 @@
use crate::{
AppState, GachaClaimItemDto, GachaClaimRepository, GachaClaimRequestDto,
GachaClaimSchema, ResponseSuccessDto, common_response, success_response,
validate_request,
};
use axum::http::StatusCode;
use axum::response::Response;
pub struct GachaClaimService;
impl GachaClaimService {
pub async fn get_gacha_claim_by_id(state: &AppState, id: String) -> Response {
let repo = GachaClaimRepository::new(state);
match repo.query_gacha_claim_by_id(id).await {
Ok(claim) => success_response(ResponseSuccessDto {
data: GachaClaimItemDto::from(&claim),
}),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_gacha_claim(
state: &AppState,
payload: GachaClaimRequestDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = GachaClaimRepository::new(state);
let schema = GachaClaimSchema::from(payload);
match repo.query_create_gacha_claim(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
}
+22
View File
@@ -0,0 +1,22 @@
use axum::{
Router,
routing::{get, post},
};
pub mod gacha_claims_controller;
pub mod gacha_claims_dto;
pub mod gacha_claims_repository;
pub mod gacha_claims_schema;
pub mod gacha_claims_service;
pub use gacha_claims_controller::*;
pub use gacha_claims_dto::*;
pub use gacha_claims_repository::*;
pub use gacha_claims_schema::*;
pub use gacha_claims_service::*;
pub fn gacha_claim_router() -> Router {
Router::new()
.route("/create", post(post_create_gacha_claim))
.route("/detail/{id}", get(get_detail_gacha_claim))
}
@@ -0,0 +1,7 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GachaCreditRequestDto {
pub user_id: String,
pub amount: i32,
}
@@ -0,0 +1,82 @@
use super::{GachaCreditRequestDto, GachaCreditSchema};
use crate::{AppState, ResourceEnum};
use anyhow::{Result, bail};
use imphnen_iam::make_thing;
use surrealdb::Uuid;
pub struct GachaCreditRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaCreditRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_by_user_id(
&self,
user_id: String,
) -> Result<Option<GachaCreditSchema>> {
let db = &self.state.surrealdb_ws;
let sql = format!(
"SELECT * FROM {} WHERE user = {}:⟨$user_id⟩ AND is_deleted = false LIMIT 1",
ResourceEnum::GachaCredits.to_string(),
ResourceEnum::Users.to_string()
);
let result: Vec<GachaCreditSchema> =
db.query(sql).bind(("user_id", user_id)).await?.take(0)?;
Ok(result.into_iter().next())
}
pub async fn query_consume_credit(&self, user_id: String) -> Result<()> {
let db = &self.state.surrealdb_ws;
let credit_opt = self.query_by_user_id(user_id).await?;
let Some(mut credit) = credit_opt else {
return Ok(());
};
if credit.available_rolls <= 0 {
bail!("No extra roll credits remaining");
}
credit.available_rolls -= 1;
let _: Option<GachaCreditSchema> = db
.update((
&ResourceEnum::GachaCredits.to_string(),
credit.id.id.to_raw(),
))
.merge(credit)
.await?;
Ok(())
}
pub async fn query_add_credit(
&self,
payload: GachaCreditRequestDto,
) -> Result<()> {
let db = &self.state.surrealdb_ws;
if let Some(mut credit) = self.query_by_user_id(payload.user_id.clone()).await? {
credit.available_rolls += payload.amount;
let _: Option<GachaCreditSchema> = db
.update((
&ResourceEnum::GachaCredits.to_string(),
credit.id.id.to_raw(),
))
.merge(credit)
.await?;
} else {
let data = GachaCreditSchema::from(&GachaCreditSchema {
id: make_thing(
&ResourceEnum::GachaCredits.to_string(),
&Uuid::new_v4().to_string(),
),
user: make_thing(&ResourceEnum::Users.to_string(), &payload.user_id),
available_rolls: payload.amount,
..Default::default()
});
let _: Option<GachaCreditSchema> = db
.create(&ResourceEnum::GachaCredits.to_string())
.content(data)
.await?;
}
Ok(())
}
}
@@ -0,0 +1,39 @@
use imphnen_iam::get_iso_date;
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GachaCreditSchema {
pub id: Thing,
pub user: Thing,
pub available_rolls: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for GachaCreditSchema {
fn default() -> Self {
GachaCreditSchema {
id: Thing::from(("app_gacha_credits", "uuid")),
user: Thing::from(("app_users", "uuid")),
available_rolls: 0,
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
impl GachaCreditSchema {
pub fn from(&self) -> Self {
Self {
id: self.id.clone(),
user: self.user.clone(),
available_rolls: self.available_rolls,
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
@@ -0,0 +1,7 @@
pub mod gacha_credits_dto;
pub mod gacha_credits_repository;
pub mod gacha_credits_schema;
pub use gacha_credits_dto::*;
pub use gacha_credits_repository::*;
pub use gacha_credits_schema::*;
@@ -0,0 +1,164 @@
use crate::{
AppState, GachaItemDto, GachaItemRequestDto, GachaItemService, MessageResponseDto,
MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
};
use axum::{
Extension, Json,
extract::{Path, Query},
http::HeaderMap,
response::IntoResponse,
};
use imphnen_iam::{PermissionsEnum, permissions_guard};
#[utoipa::path(
get,
path = "/v1/gacha/items",
security(
("Bearer" = [])
),
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 = "Get gacha item list", body = ResponseListSuccessDto<Vec<GachaItemDto>>)
),
tag = "Gacha"
)]
pub async fn get_gacha_item_list(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Query(meta): Query<MetaRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::ReadListGachaItems],
)
.await
{
Ok(_) => GachaItemService::get_gacha_item_list(&state, meta).await,
Err(response) => response,
}
}
#[utoipa::path(
get,
path = "/v1/gacha/items/detail/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Gacha Item ID")),
responses(
(status = 200, description = "Get gacha item by ID", body = ResponseSuccessDto<GachaItemDto>)
),
tag = "Gacha"
)]
pub async fn get_gacha_item_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::ReadDetailGachaItems],
)
.await
{
Ok(_) => GachaItemService::get_gacha_item_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
path = "/v1/gacha/items/create",
security(
("Bearer" = [])
),
request_body = GachaItemRequestDto,
responses(
(status = 201, description = "Create gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn post_create_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<GachaItemRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::CreateGachaItems],
)
.await
{
Ok(_) => GachaItemService::create_gacha_item(&state, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
put,
path = "/v1/gacha/items/update/{id}",
security(
("Bearer" = [])
),
request_body = GachaItemRequestDto,
responses(
(status = 200, description = "Update gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn put_update_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
Json(payload): Json<GachaItemRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::UpdateGachaItems],
)
.await
{
Ok(_) => GachaItemService::update_gacha_item(&state, payload, id).await,
Err(response) => response,
}
}
#[utoipa::path(
delete,
path = "/v1/gacha/items/delete/{id}",
security(
("Bearer" = [])
),
responses(
(status = 200, description = "Delete gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn delete_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::DeleteGachaItems],
)
.await
{
Ok(_) => GachaItemService::delete_gacha_item(&state, id).await,
Err(response) => response,
}
}
@@ -1,5 +1,5 @@
use super::GachaItemSchema;
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
use validator::Validate;
@@ -20,11 +20,14 @@ pub struct GachaItemDto {
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaItemDtoRaw {
pub id: Thing,
pub name: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
impl GachaItemDto {
pub fn from(dto: GachaItemSchema) -> Self {
Self {
id: dto.id.id.to_raw(),
name: dto.name.clone(),
is_deleted: dto.is_deleted,
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
}
}
}
@@ -1,9 +1,10 @@
use super::GachaItemSchema;
use crate::{
AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto, get_id,
make_thing, query_list_with_meta,
AppState, GachaItemDto, MetaRequestDto, ResourceEnum, ResponseListSuccessDto,
get_id, make_thing,
};
use anyhow::{Result, bail};
use imphnen_iam::QueryListBuilder;
pub struct GachaItemRepository<'a> {
state: &'a AppState,
@@ -17,19 +18,27 @@ impl<'a> GachaItemRepository<'a> {
pub async fn query_gacha_item_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<GachaItemSchema>>> {
let mut conditions = vec!["is_deleted = false".into()];
if meta.search.is_some() {
conditions.push("string::contains(name, $search)".into());
}
query_list_with_meta(
&self.state.surrealdb_ws,
&ResourceEnum::GachaItems.to_string(),
&meta,
conditions,
None,
)
.await
) -> Result<ResponseListSuccessDto<Vec<GachaItemDto>>> {
let raw_result: ResponseListSuccessDto<Vec<GachaItemSchema>> =
QueryListBuilder::new(
&self.state.surrealdb_ws,
&ResourceEnum::GachaItems.to_string(),
&meta,
)
.with_condition("is_deleted = false")
.search_field("name")
.select_fields(vec!["*"])
.build()
.await?;
let data = raw_result
.data
.into_iter()
.map(GachaItemDto::from)
.collect();
Ok(ResponseListSuccessDto {
data,
meta: raw_result.meta,
})
}
pub async fn query_gacha_item_by_id(&self, id: String) -> Result<GachaItemSchema> {
@@ -1,7 +1,10 @@
use crate::{ResourceEnum, make_thing};
use imphnen_iam::get_iso_date;
use serde::{Deserialize, Serialize};
use surrealdb::{Uuid, sql::Thing};
use super::GachaItemRequestDto;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaItemSchema {
pub id: Thing,
@@ -22,8 +25,22 @@ impl Default for GachaItemSchema {
name: String::new(),
image_url: String::new(),
is_deleted: false,
created_at: None,
updated_at: None,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
impl GachaItemSchema {
pub fn from(dto: GachaItemRequestDto) -> Self {
Self {
id: make_thing(
&ResourceEnum::GachaItems.to_string(),
&Uuid::new_v4().to_string(),
),
name: dto.name,
image_url: dto.image_url,
..Default::default()
}
}
}
@@ -0,0 +1,95 @@
use crate::{
AppState, GachaItemDto, GachaItemRepository, GachaItemRequestDto, GachaItemSchema,
MetaRequestDto, ResourceEnum, ResponseListSuccessDto, ResponseSuccessDto,
common_response, make_thing, success_list_response, success_response,
validate_request,
};
use axum::http::StatusCode;
use axum::response::Response;
pub struct GachaItemService;
impl GachaItemService {
pub async fn get_gacha_item_list(
state: &AppState,
meta: MetaRequestDto,
) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_gacha_item_list(meta).await {
Ok(data) => {
let response = ResponseListSuccessDto {
data: data.data,
meta: data.meta,
};
success_list_response(response)
}
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn get_gacha_item_by_id(state: &AppState, id: String) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_gacha_item_by_id(id).await {
Ok(item) => success_response(ResponseSuccessDto {
data: GachaItemDto::from(item),
}),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_gacha_item(
state: &AppState,
payload: GachaItemRequestDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = GachaItemRepository::new(state);
let schema = GachaItemSchema::from(payload);
match repo.query_create_gacha_item(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn update_gacha_item(
state: &AppState,
payload: GachaItemRequestDto,
id: String,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = GachaItemRepository::new(state);
let schema = GachaItemSchema {
id: make_thing(&ResourceEnum::GachaItems.to_string(), &id),
name: payload.name,
image_url: payload.image_url,
..Default::default()
};
match repo.query_update_gacha_item(schema).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => {
if e.to_string().contains("not found") {
common_response(StatusCode::NOT_FOUND, "Gacha Item not found")
} else {
common_response(StatusCode::BAD_REQUEST, &e.to_string())
}
}
}
}
pub async fn delete_gacha_item(state: &AppState, id: String) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_delete_gacha_item(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => {
if e.to_string().contains("not found") {
common_response(StatusCode::NOT_FOUND, "Gacha Item not found")
} else {
common_response(StatusCode::BAD_REQUEST, &e.to_string())
}
}
}
}
}
+25
View File
@@ -0,0 +1,25 @@
use axum::{
Router,
routing::{delete, get, post, put},
};
pub mod gacha_items_controller;
pub mod gacha_items_dto;
pub mod gacha_items_repository;
pub mod gacha_items_schema;
pub mod gacha_items_service;
pub use gacha_items_controller::*;
pub use gacha_items_dto::*;
pub use gacha_items_repository::*;
pub use gacha_items_schema::*;
pub use gacha_items_service::*;
pub fn gacha_item_router() -> Router {
Router::new()
.route("/", get(get_gacha_item_list))
.route("/create", post(post_create_gacha_item))
.route("/detail/{id}", get(get_gacha_item_by_id))
.route("/update/{id}", put(put_update_gacha_item))
.route("/delete/{id}", delete(delete_gacha_item))
}
@@ -0,0 +1,93 @@
use crate::{
AppState, GachaRollItemDto, GachaRollRequestDto, GachaRollService,
MessageResponseDto, ResponseSuccessDto,
};
use axum::{
Extension, Json, extract::Path, http::HeaderMap, response::IntoResponse,
};
use imphnen_iam::{PermissionsEnum, permissions_guard};
#[utoipa::path(
get,
path = "/v1/gacha/rolls/detail/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Gacha Roll ID")),
responses(
(status = 200, description = "Get Gacha Roll by ID", body = ResponseSuccessDto<GachaRollItemDto>)
),
tag = "Gacha"
)]
pub async fn get_detail_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::ReadDetailGachaRolls],
)
.await
{
Ok(_) => GachaRollService::get_gacha_roll_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
path = "/v1/gacha/rolls/create",
security(
("Bearer" = [])
),
request_body = GachaRollRequestDto,
responses(
(status = 201, description = "Create new gacha roll", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn post_create_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<GachaRollRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::CreateGachaRolls],
)
.await
{
Ok(_) => GachaRollService::create_gacha_roll(&state, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
path = "/v1/gacha/rolls/execute",
security(
("Bearer" = [])
),
responses(
(status = 200, description = "Execute and get 1 gacha result", body = ResponseSuccessDto<GachaRollItemDto>)
),
tag = "Gacha"
)]
pub async fn post_execute_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::ExecuteGachaRolls],
)
.await
{
Ok(_) => GachaRollService::execute_roll_once(headers, &state).await,
Err(response) => response,
}
}
@@ -1,3 +1,4 @@
use crate::{GachaItemDto, GachaItemSchema};
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
@@ -7,30 +8,41 @@ use validator::Validate;
pub struct GachaRollRequestDto {
#[validate(length(min = 1, message = "Item ID must not be empty"))]
pub item_id: String,
#[validate(range(min = 1, message = "Weight must be greater than zero"))]
pub weight: f32,
#[validate(range(min = 1, message = "Quantity must be at least 1"))]
pub quantity: i32,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaRollDto {
pub struct GachaRollItemDto {
pub id: String,
pub item: String,
pub weight: String,
pub item: GachaItemDto,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl GachaRollItemDto {
pub fn from(dto: &GachaRollQueryDto) -> Self {
Self {
id: dto.id.id.to_raw(),
item: GachaItemDto::from(dto.item.clone()),
weight: dto.weight.clone(),
quantity: dto.quantity,
is_deleted: dto.is_deleted,
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaRollDtoRaw {
pub struct GachaRollQueryDto {
pub id: Thing,
pub item: Thing,
pub weight: String,
pub item: GachaItemSchema,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
@@ -0,0 +1,79 @@
use super::GachaRollQueryDto;
use super::GachaRollSchema;
use crate::{AppState, DetailQueryBuilder, ResourceEnum};
use anyhow::{Result, bail};
use imphnen_iam::ListQueryBuilder;
use rand::prelude::*;
use rand::rng;
use rand_distr::weighted::WeightedIndex;
pub struct GachaRollRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaRollRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_gacha_roll_by_id(
&self,
id: String,
) -> Result<GachaRollQueryDto> {
let db = &self.state.surrealdb_ws;
let builder = DetailQueryBuilder::new(ResourceEnum::GachaRolls.to_string())
.with_id(id.clone())
.with_select_fields(vec!["*"])
.with_fetch("item");
let sql = builder.build();
let result: Option<GachaRollQueryDto> =
builder.apply_bindings(db.query(sql)).await?.take(0)?;
match result {
Some(roll) if !roll.is_deleted => Ok(roll),
_ => bail!("Gacha Roll not found"),
}
}
pub async fn query_create_gacha_roll(
&self,
data: GachaRollSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record: Option<GachaRollSchema> = db
.create(ResourceEnum::GachaRolls.to_string())
.content(data)
.await?;
match record {
Some(_) => Ok("Success create Gacha Roll".into()),
None => bail!("Failed to create Gacha Roll"),
}
}
pub async fn query_all_active_rolls(&self) -> Result<Vec<GachaRollQueryDto>> {
let db = &self.state.surrealdb_ws;
let builder = ListQueryBuilder::new(ResourceEnum::GachaRolls.to_string())
.with_select_fields(vec!["*"])
.with_fetch(Some(vec!["item"]));
let sql = builder.build();
let result: Vec<GachaRollQueryDto> = db.query(sql).await?.take(0)?;
Ok(result)
}
pub fn roll_once(rolls: &[GachaRollQueryDto]) -> Option<GachaRollQueryDto> {
let filtered: Vec<_> = rolls
.iter()
.filter(|r| !r.is_deleted && r.quantity > 0)
.collect();
let weights: Vec<f32> = filtered
.iter()
.map(|r| r.weight * r.quantity as f32)
.collect();
if weights.iter().all(|&w| w <= 0.0) {
return None;
}
let dist = WeightedIndex::new(&weights).ok()?;
let mut rng = rng();
let index = dist.sample(&mut rng);
Some(filtered[index].clone())
}
}
@@ -1,7 +1,10 @@
use crate::{ResourceEnum, make_thing};
use imphnen_iam::get_iso_date;
use serde::{Deserialize, Serialize};
use surrealdb::{Uuid, sql::Thing};
use super::GachaRollRequestDto;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaRollSchema {
pub id: Thing,
@@ -24,11 +27,26 @@ impl Default for GachaRollSchema {
&ResourceEnum::GachaItems.to_string(),
&Uuid::new_v4().to_string(),
),
weight: 0.2,
quantity: 2,
weight: 0.0,
quantity: 0,
is_deleted: false,
created_at: None,
updated_at: None,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
impl GachaRollSchema {
pub fn create(dto: GachaRollRequestDto) -> Self {
Self {
id: make_thing(
&ResourceEnum::GachaRolls.to_string(),
&Uuid::new_v4().to_string(),
),
item: make_thing(&ResourceEnum::GachaItems.to_string(), &dto.item_id),
weight: dto.weight,
quantity: dto.quantity,
..Default::default()
}
}
}
@@ -0,0 +1,66 @@
use crate::{
AppState, GachaClaimRepository, GachaClaimSchema, GachaRollItemDto,
GachaRollRepository, GachaRollRequestDto, GachaRollSchema, ResponseSuccessDto,
common_response, success_response, validate_request,
};
use axum::http::{HeaderMap, StatusCode};
use axum::response::Response;
use imphnen_iam::{UsersRepository, extract_email};
pub struct GachaRollService;
impl GachaRollService {
pub async fn get_gacha_roll_by_id(state: &AppState, id: String) -> Response {
let repo = GachaRollRepository::new(state);
match repo.query_gacha_roll_by_id(id).await {
Ok(roll) => success_response(ResponseSuccessDto {
data: GachaRollItemDto::from(&roll),
}),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_gacha_roll(
state: &AppState,
payload: GachaRollRequestDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let schema = GachaRollSchema::create(payload);
let repo = GachaRollRepository::new(state);
match repo.query_create_gacha_roll(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn execute_roll_once(headers: HeaderMap, state: &AppState) -> Response {
let repo = GachaRollRepository::new(state);
let repo_claim = GachaClaimRepository::new(state);
let repo_user = UsersRepository::new(state);
let Some(email) = extract_email(&headers) else {
return common_response(StatusCode::UNAUTHORIZED, "Unauthorized");
};
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
return common_response(StatusCode::NOT_FOUND, "User not found");
};
match repo.query_all_active_rolls().await {
Ok(rolls) => match GachaRollRepository::roll_once(&rolls) {
Some(roll) => {
let claim = GachaClaimSchema::roll(roll.clone(), user.id);
match repo_claim.query_create_gacha_claim(claim).await {
Ok(_) => success_response(ResponseSuccessDto {
data: GachaRollItemDto::from(&roll),
}),
Err(e) => {
common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
}
}
}
None => common_response(StatusCode::NOT_FOUND, "No rollable item available"),
},
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
}
+22
View File
@@ -0,0 +1,22 @@
pub mod gacha_rolls_controller;
pub mod gacha_rolls_dto;
pub mod gacha_rolls_repository;
pub mod gacha_rolls_schema;
pub mod gacha_rolls_service;
use axum::{
Router,
routing::{get, post},
};
pub use gacha_rolls_controller::*;
pub use gacha_rolls_dto::*;
pub use gacha_rolls_repository::*;
pub use gacha_rolls_schema::*;
pub use gacha_rolls_service::*;
pub fn gacha_roll_router() -> Router {
Router::new()
.route("/create", post(post_create_gacha_roll))
.route("/execute", post(post_execute_gacha_roll))
.route("/detail/{id}", get(get_detail_gacha_roll))
}
+18
View File
@@ -0,0 +1,18 @@
use axum::Router;
pub mod gacha_claims;
pub mod gacha_credits;
pub mod gacha_items;
pub mod gacha_rolls;
pub use gacha_claims::*;
pub use gacha_credits::*;
pub use gacha_items::*;
pub use gacha_rolls::*;
pub fn gacha_router() -> Router {
Router::new()
.nest("/gacha/claims", gacha_claim_router())
.nest("/gacha/items", gacha_item_router())
.nest("/gacha/rolls", gacha_roll_router())
}
View File
-26
View File
@@ -1,26 +0,0 @@
[package]
name = "imphnen-gateway-service"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-iam-service = { version = "0.1.0", path = "../imphnen-iam-service" }
imphnen-middleware-service = { version = "0.1.0", path = "../imphnen-middleware-service" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
utoipa.workspace = true
lazy_static.workspace = true
regex.workspace = true
validator.workspace = true
axum-test.workspace = true
surrealdb.workspace = true
rand.workspace = true
tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
-30
View File
@@ -1,30 +0,0 @@
use axum::{
Extension, Router, middleware::from_fn, response::Redirect, routing::get,
};
use imphnen_entities::{AppState, SurrealMemClient, SurrealWsClient};
use imphnen_iam_service::{iam_protected_routes, iam_public_routes};
pub mod docs;
pub use docs::*;
use imphnen_middleware_service::{auth_middleware, cors_middleware};
use utoipa_swagger_ui::SwaggerUi;
pub async fn gateway_service(
surrealdb_ws: SurrealWsClient,
surrealdb_mem: SurrealMemClient,
) -> Router {
let state = AppState {
surrealdb_ws,
surrealdb_mem,
};
let public_routes = iam_public_routes();
let protected_routes = iam_protected_routes().layer(from_fn(auth_middleware));
Router::new()
.route("/", get(Redirect::to("/docs")))
.nest("/v1", public_routes.merge(protected_routes))
.merge(SwaggerUi::new("/docs").url("/openapi.json", docs_router()))
.layer(cors_middleware())
.layer(Extension(state.clone()))
}
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "imphnen-gateway"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-iam = { version = "0.1.0", path = "../imphnen-iam" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-gacha = { version = "0.1.0", path = "../imphnen-gacha" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-middleware = { version = "0.1.0", path = "../imphnen-middleware" }
imphnen-cms = { version = "0.1.0", path = "../imphnen-cms" }
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
utoipa.workspace = true
lazy_static.workspace = true
regex.workspace = true
validator.workspace = true
axum-test.workspace = true
surrealdb.workspace = true
rand.workspace = true
tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
@@ -1,11 +1,13 @@
use imphnen_iam_service::{
auth, permissions, roles, users, AuthLoginRequestDto, AuthLoginResponsetDto, AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
AuthNewPasswordRequestDto, AuthRefreshTokenRequestDto, MessageResponseDto, MetaRequestDto, MetaResponseDto, PermissionsItemDto, PermissionsRequestDto, ResponseListSuccessDto, ResponseSuccessDto, RolesItemDto, RolesRequestCreateDto, RolesRequestUpdateDto, TokenDto, UsersCreateRequestDto, UsersDetailItemDto, UsersItemDto, UsersListItemDto, UsersUpdateRequestDto
use imphnen_iam::{
auth, permissions, roles, users, AuthLoginRequestDto, AuthLoginResponsetDto, AuthNewPasswordRequestDto, AuthRefreshTokenRequestDto, AuthResendOtpRequestDto, AuthVerifyEmailRequestDto, MessageResponseDto, MetaRequestDto, MetaResponseDto, PermissionsItemDto, PermissionsRequestDto, ResponseListSuccessDto, ResponseSuccessDto, RolesDetailItemDto, RolesListItemDto, RolesRequestCreateDto, RolesRequestUpdateDto, TokenDto, UsersCreateRequestDto, UsersDetailItemDto, UsersListItemDto, UsersUpdateRequestDto
};
use utoipa::{
openapi::security::{Http, HttpAuthScheme, SecurityScheme},
Modify, OpenApi,
};
use imphnen_gacha::{gacha_claims, gacha_items, gacha_rolls, GachaClaimItemDto, GachaClaimRequestDto, GachaItemDto, GachaItemRequestDto, GachaRollItemDto, GachaRollRequestDto};
use imphnen_cms::{events_controller, events_dto::{EventsDetailItemDto, EventsListItemDto}, testimonials_controller, testimonials_dto::{TestimonialsCreateRequestDto, TestimonialsDetailItemDto, TestimonialsListItemDto, TestimonialsUpdateRequestDto}};
#[derive(OpenApi)]
#[openapi(
@@ -34,7 +36,27 @@ use utoipa::{
permissions::permissions_controller::get_permission_by_id,
permissions::permissions_controller::post_create_permission,
permissions::permissions_controller::put_update_permission,
permissions::permissions_controller::delete_permission
permissions::permissions_controller::delete_permission,
gacha_claims::get_detail_gacha_claim,
gacha_claims::post_create_gacha_claim,
gacha_items::get_gacha_item_list,
gacha_items::get_gacha_item_by_id,
gacha_items::post_create_gacha_item,
gacha_items::put_update_gacha_item,
gacha_items::delete_gacha_item,
gacha_rolls::get_detail_gacha_roll,
gacha_rolls::post_create_gacha_roll,
gacha_rolls::post_execute_gacha_roll,
events_controller::get_event_list,
events_controller::get_event_by_id,
events_controller::post_create_event,
events_controller::patch_update_event,
events_controller::delete_event,
testimonials_controller::get_testimonial_list,
testimonials_controller::get_testimonial_by_id,
testimonials_controller::post_create_testimonial,
testimonials_controller::patch_update_testimonial,
testimonials_controller::delete_testimonial,
),
components(
schemas(
@@ -48,22 +70,39 @@ use utoipa::{
AuthNewPasswordRequestDto,
AuthRefreshTokenRequestDto,
ResponseSuccessDto<TokenDto>,
RolesItemDto,
RolesListItemDto,
RolesRequestCreateDto,
RolesRequestUpdateDto,
PermissionsRequestDto,
PermissionsItemDto,
UsersItemDto,
UsersDetailItemDto,
UsersListItemDto,
UsersUpdateRequestDto,
UsersCreateRequestDto,
GachaClaimItemDto,
GachaClaimRequestDto,
GachaItemDto,
GachaItemRequestDto,
GachaRollItemDto,
GachaRollRequestDto,
ResponseListSuccessDto<Vec<GachaItemDto>>,
ResponseSuccessDto<GachaRollItemDto>,
ResponseSuccessDto<GachaItemDto>,
ResponseSuccessDto<GachaClaimItemDto>,
ResponseSuccessDto<AuthLoginResponsetDto>,
ResponseListSuccessDto<Vec<RolesItemDto>>,
ResponseSuccessDto<RolesItemDto>,
ResponseListSuccessDto<Vec<RolesListItemDto>>,
ResponseSuccessDto<RolesDetailItemDto>,
ResponseListSuccessDto<Vec<UsersListItemDto>>,
ResponseSuccessDto<UsersDetailItemDto>,
ResponseListSuccessDto<Vec<PermissionsItemDto>>,
ResponseSuccessDto<PermissionsItemDto>
ResponseSuccessDto<PermissionsItemDto>,
ResponseListSuccessDto<Vec<EventsListItemDto>>,
ResponseSuccessDto<EventsDetailItemDto>,
ResponseListSuccessDto<Vec<TestimonialsListItemDto>>,
ResponseSuccessDto<TestimonialsDetailItemDto>,
TestimonialsCreateRequestDto,
TestimonialsUpdateRequestDto,
MessageResponseDto,
)
),
info(
@@ -102,4 +141,4 @@ impl Modify for SecurityAddon {
pub fn docs_router() -> utoipa::openapi::OpenApi {
ApiDoc::openapi()
}
}
+46
View File
@@ -0,0 +1,46 @@
use axum::{
Extension, Router, middleware::from_fn, response::Redirect, routing::get,
};
use imphnen_cms::{
events_protected_routes, events_public_routes, testimonials_protected_routes,
testimonials_public_routes,
};
use imphnen_entities::{AppState, SurrealMemClient, SurrealWsClient};
use imphnen_gacha::gacha_router;
use imphnen_iam::{iam_protected_routes, iam_public_routes};
use imphnen_middleware::{auth_middleware, cors_middleware};
use utoipa_swagger_ui::SwaggerUi;
pub mod docs;
pub use docs::*;
pub async fn gateway_service(
surrealdb_ws: SurrealWsClient,
surrealdb_mem: SurrealMemClient,
) -> Router {
let state = AppState {
surrealdb_ws,
surrealdb_mem,
};
let public_routes = Router::new()
.merge(iam_public_routes())
.merge(testimonials_public_routes())
.merge(events_public_routes());
let protected_routes = Router::new()
.merge(iam_protected_routes())
.merge(events_protected_routes())
.merge(testimonials_protected_routes())
.merge(gacha_router())
.layer(from_fn(auth_middleware));
let routes = public_routes.merge(protected_routes);
Router::new()
.route("/", get(Redirect::to("/docs")))
.nest("/v1", routes)
.merge(SwaggerUi::new("/docs").url("/openapi.json", docs_router()))
.layer(cors_middleware())
.layer(Extension(state))
}
@@ -1,43 +0,0 @@
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PermissionsEnum {
ReadListUsers,
ReadDetailUsers,
CreateUsers,
DeleteUsers,
UpdateUsers,
ReadListRoles,
ReadDetailRoles,
CreateRoles,
DeleteRoles,
UpdateRoles,
ReadListPermissions,
ReadDetailPermissions,
CreatePermissions,
DeletePermissions,
UpdatePermissions,
}
impl fmt::Display for PermissionsEnum {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let permission_str = match self {
PermissionsEnum::ReadListUsers => "Read List Users",
PermissionsEnum::ReadDetailUsers => "Read Detail Users",
PermissionsEnum::CreateUsers => "Create Users",
PermissionsEnum::DeleteUsers => "Delete Users",
PermissionsEnum::UpdateUsers => "Update Users",
PermissionsEnum::ReadListRoles => "Read List Roles",
PermissionsEnum::ReadDetailRoles => "Read Detail Roles",
PermissionsEnum::CreateRoles => "Create Roles",
PermissionsEnum::DeleteRoles => "Delete Roles",
PermissionsEnum::UpdateRoles => "Update Roles",
PermissionsEnum::ReadListPermissions => "Read List Permissions",
PermissionsEnum::ReadDetailPermissions => "Read Detail Permissions",
PermissionsEnum::CreatePermissions => "Create Permissions",
PermissionsEnum::DeletePermissions => "Delete Permissions",
PermissionsEnum::UpdatePermissions => "Update Permissions",
};
write!(f, "{}", permission_str)
}
}
@@ -1,205 +0,0 @@
use super::{
RolesItemByIdDto, RolesItemByIdDtoRaw, RolesRequestCreateDto,
RolesRequestUpdateDto, RolesSchema,
};
use crate::{
extract_id, get_id, make_thing, query_list_with_meta, AppState, MetaRequestDto,
PermissionsItemDto, ResourceEnum, ResponseListSuccessDto,
};
use anyhow::{bail, Result};
use surrealdb::sql::Thing;
use surrealdb::Uuid;
pub struct RolesRepository<'a> {
state: &'a AppState,
}
impl<'a> RolesRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_raw_role_by_id(&self, id: &str) -> Result<RolesSchema> {
let db = &self.state.surrealdb_ws;
let role: Option<RolesSchema> =
db.select((ResourceEnum::Roles.to_string(), id)).await?;
match role {
Some(r) if !r.is_deleted => Ok(r),
_ => bail!("Role not found"),
}
}
pub async fn query_role_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<RolesSchema>>> {
let mut conditions = vec!["is_deleted = false".into()];
if meta.search.is_some() {
conditions.push("string::contains(name, $search)".into());
}
if meta.filter_by.is_some() && meta.filter.is_some() {
let filter_by = meta.filter_by.as_ref().unwrap();
conditions.push(format!("{} = $filter", filter_by));
}
query_list_with_meta(
&self.state.surrealdb_ws,
&ResourceEnum::Roles.to_string(),
&meta,
conditions,
None,
)
.await
}
pub async fn query_role_by_name(&self, name: String) -> Result<RolesItemByIdDto> {
let db = &self.state.surrealdb_ws;
let sql = format!(
"SELECT *, permissions FROM {} WHERE name = $name AND is_deleted = false LIMIT 1 FETCH permissions",
ResourceEnum::Roles.to_string()
);
let mut result = db.query(sql).bind(("name", name.clone())).await?;
let role: Option<RolesItemByIdDtoRaw> = result.take(0)?;
let role = match role {
Some(r) if !r.is_deleted => r,
_ => bail!("Role not found"),
};
let permissions = role
.permissions
.into_iter()
.map(|perm| PermissionsItemDto {
id: extract_id(&perm.id),
name: perm.name,
created_at: perm.created_at,
updated_at: perm.updated_at,
})
.collect::<Vec<_>>();
Ok(RolesItemByIdDto {
id: extract_id(&role.id),
name: role.name,
is_deleted: role.is_deleted,
permissions,
created_at: role.created_at,
updated_at: role.updated_at,
})
}
pub async fn query_role_by_id(&self, id: String) -> Result<RolesItemByIdDto> {
let db = &self.state.surrealdb_ws;
let query = format!(
"SELECT *, permissions.* AS permissions
FROM app_roles:{} WHERE is_deleted = false FETCH permissions",
id
);
let mut result = db.query(query).await?;
let role: Option<RolesItemByIdDtoRaw> = result.take(0)?;
let role = match role {
Some(r) if !r.is_deleted => r,
_ => bail!("Role not found"),
};
let permissions = role
.permissions
.into_iter()
.map(|perm| PermissionsItemDto {
id: extract_id(&perm.id),
name: perm.name,
created_at: perm.created_at,
updated_at: perm.updated_at,
})
.collect::<Vec<_>>();
Ok(RolesItemByIdDto {
id: extract_id(&role.id),
name: role.name,
is_deleted: role.is_deleted,
permissions,
created_at: role.created_at,
updated_at: role.updated_at,
})
}
pub async fn query_create_role(
&self,
payload: RolesRequestCreateDto,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let role_id = Uuid::new_v4().to_string();
let permission_things: Vec<Thing> = payload
.permissions
.iter()
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
.collect();
let role = RolesSchema {
id: make_thing(&ResourceEnum::Roles.to_string(), &role_id),
name: payload.name,
is_deleted: false,
permissions: permission_things,
created_at: Some(crate::get_iso_date()),
updated_at: Some(crate::get_iso_date()),
};
let _: Option<RolesSchema> = db
.create((&ResourceEnum::Roles.to_string(), role_id))
.content(role)
.await?;
Ok("Role with permissions created successfully".into())
}
pub async fn query_update_role(
&self,
id: String,
data: RolesRequestUpdateDto,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let thing_id = make_thing(&ResourceEnum::Roles.to_string(), &id);
let existing = self.query_raw_role_by_id(&id).await?;
if existing.is_deleted {
bail!("Role already deleted");
}
let permissions: Vec<Thing> = if let Some(permission_ids) = &data.permissions {
permission_ids
.iter()
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
.collect()
} else {
existing
.permissions
.iter()
.map(|p| make_thing(&ResourceEnum::Permissions.to_string(), &p.id.to_raw()))
.collect()
};
let merged = RolesSchema {
id: thing_id,
name: data.name.unwrap_or(existing.name),
permissions,
is_deleted: existing.is_deleted,
created_at: existing.created_at,
updated_at: Some(crate::get_iso_date()),
};
let record: Option<RolesSchema> =
db.update(get_id(&merged.id)?).content(merged).await?;
match record {
Some(_) => Ok("Success update role".into()),
None => bail!("Failed to update role"),
}
}
pub async fn query_delete_role(&self, id: String) -> Result<String> {
let db = &self.state.surrealdb_ws;
let role_id = make_thing(&ResourceEnum::Roles.to_string(), &id);
let role = self.query_role_by_id(role_id.id.to_raw()).await?;
if role.is_deleted {
bail!("Role already deleted");
}
let record_key = get_id(&role_id)?;
let record: Option<RolesSchema> = db
.update(record_key)
.merge(serde_json::json!({ "is_deleted": true }))
.await?;
match record {
Some(_) => Ok("Success delete role".into()),
None => bail!("Failed to delete role"),
}
}
}
@@ -1,33 +0,0 @@
use serde::{Deserialize, Serialize};
use surrealdb::{sql::Thing, Uuid};
use crate::{make_thing, ResourceEnum};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RolesSchema {
pub id: Thing,
pub name: String,
pub is_deleted: bool,
pub permissions: Vec<Thing>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for RolesSchema {
fn default() -> Self {
RolesSchema {
id: make_thing(
&ResourceEnum::Roles.to_string(),
&Uuid::new_v4().to_string(),
),
permissions: vec![make_thing(
&ResourceEnum::Permissions.to_string(),
&Uuid::new_v4().to_string(),
)],
name: String::new(),
is_deleted: false,
created_at: None,
updated_at: None,
}
}
}
@@ -1,317 +0,0 @@
use super::{
UsersActiveInactiveSchema, UsersItemDto, UsersItemDtoRaw, UsersListItemDto,
UsersListItemDtoRaw, UsersSchema, UsersSetNewPasswordSchema,
};
use crate::{
extract_id, get_id, make_thing, query_list_with_meta, AppState, MetaRequestDto,
PermissionsItemDto, PermissionsItemDtoRaw, ResourceEnum, ResponseListSuccessDto,
RolesItemDto, RolesItemDtoRaw,
};
use anyhow::{anyhow, bail, Result};
pub struct UsersRepository<'a> {
state: &'a AppState,
}
impl<'a> UsersRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_user_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<UsersListItemDto>>> {
let db = &self.state.surrealdb_ws;
let mut conditions = vec!["is_deleted = false".to_string()];
if let Some(search) = meta.search.as_deref() {
if !search.is_empty() {
conditions.push("string::contains(fullname ?? '', $search)".to_string());
}
}
if let (Some(filter_by), Some(_filter)) =
(meta.filter_by.as_ref(), meta.filter.as_ref())
{
conditions.push(format!("{} = $filter", filter_by));
}
let where_clause = if !conditions.is_empty() {
format!("WHERE {}", conditions.join(" AND "))
} else {
String::new()
};
let limit = meta.per_page.unwrap_or(10);
let page = meta.page.unwrap_or(1);
if page < 1 || limit < 1 {
return Err(anyhow!("Invalid pagination parameters"));
}
let start = (page - 1) * limit;
let select_query = format!(
"
SELECT
id,
role.name AS role,
fullname,
email,
avatar,
phone_number,
is_active,
gender,
birthdate,
created_at,
updated_at
FROM {}
{}
LIMIT {} START {}
FETCH role
",
ResourceEnum::Users.to_string(),
where_clause,
limit,
start
);
let raw_result = query_list_with_meta::<UsersListItemDtoRaw>(
db,
&ResourceEnum::Users.to_string(),
&meta,
vec![],
Some(select_query),
)
.await?;
let transformed_data = raw_result
.data
.into_iter()
.map(|user| UsersListItemDto {
id: extract_id(&user.id),
fullname: user.fullname,
email: user.email,
avatar: user.avatar,
phone_number: user.phone_number,
is_active: user.is_active,
role: user.role.unwrap_or_else(|| "-".into()),
created_at: user.created_at,
updated_at: user.updated_at,
})
.collect::<Vec<_>>();
Ok(ResponseListSuccessDto {
data: transformed_data,
meta: raw_result.meta,
})
}
pub async fn query_user_by_email(&self, email: String) -> Result<UsersItemDtoRaw> {
let db = &self.state.surrealdb_ws;
let sql = format!(
"SELECT *, role AS role FROM {} WHERE email = $email AND is_deleted = false LIMIT 1 FETCH role, role.permissions",
ResourceEnum::Users.to_string()
);
let response: Option<UsersItemDtoRaw> = db
.query(sql)
.bind(("email", email.clone()))
.await?
.take(0)?;
match response {
Some(user) if !user.role.is_deleted => {
let permissions = user
.role
.permissions
.into_iter()
.map(|perm| PermissionsItemDtoRaw {
id: perm.id,
name: perm.name,
created_at: perm.created_at,
updated_at: perm.updated_at,
})
.collect::<Vec<_>>();
Ok(UsersItemDtoRaw {
id: user.id,
fullname: user.fullname,
email: user.email,
avatar: user.avatar,
phone_number: user.phone_number,
is_active: user.is_active,
is_deleted: user.is_deleted,
gender: user.gender,
birthdate: user.birthdate,
password: user.password,
created_at: user.created_at,
updated_at: user.updated_at,
role: RolesItemDtoRaw {
id: user.role.id,
name: user.role.name,
permissions,
created_at: user.role.created_at,
updated_at: user.role.updated_at,
is_deleted: user.role.is_deleted,
},
})
}
_ => bail!("User not found"),
}
}
pub async fn query_user_by_id(&self, id: String) -> Result<UsersItemDto> {
let db = &self.state.surrealdb_ws;
let query = format!(
"SELECT *, role AS role FROM app_users:⟨{}⟩ FETCH role, role.permissions",
id
);
let mut result = db.query(query).await?;
let response: Option<UsersItemDtoRaw> = result.take(0)?;
match response {
Some(user) if !user.role.is_deleted => {
let permissions = user
.role
.permissions
.into_iter()
.map(|perm| PermissionsItemDto {
id: extract_id(&perm.id),
name: perm.name,
created_at: perm.created_at,
updated_at: perm.updated_at,
})
.collect::<Vec<_>>();
Ok(UsersItemDto {
id: extract_id(&user.id),
fullname: user.fullname,
email: user.email,
avatar: user.avatar,
phone_number: user.phone_number,
is_active: user.is_active,
is_deleted: user.is_deleted,
gender: user.gender,
birthdate: user.birthdate,
password: user.password,
role: RolesItemDto {
id: extract_id(&user.role.id),
name: user.role.name,
permissions,
created_at: user.role.created_at,
updated_at: user.role.updated_at,
},
created_at: user.created_at,
updated_at: user.updated_at,
})
}
_ => bail!("User not found"),
}
}
pub async fn query_create_user(&self, data: UsersSchema) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record: Option<UsersSchema> = db
.create(ResourceEnum::Users.to_string())
.content(data)
.await?;
match record {
Some(_) => Ok("Success create user".into()),
None => bail!("Failed to create user"),
}
}
pub async fn query_update_user(&self, data: UsersSchema) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record_key = get_id(&data.id)?;
let existing = self.query_user_by_id(data.id.id.to_raw()).await?;
if existing.is_deleted {
bail!("User already deleted");
}
let merged = UsersSchema {
password: existing.password,
created_at: existing.created_at,
role: make_thing("app_roles", &existing.role.id),
..data.clone()
};
let record: Option<UsersSchema> = db.update(record_key).merge(merged).await?;
match record {
Some(_) => Ok("Success update user".into()),
None => bail!("Failed to update user"),
}
}
pub async fn query_active_inactive_user(
&self,
email: String,
data: UsersActiveInactiveSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let user = self.query_user_by_email(email.clone()).await?;
if user.is_deleted {
bail!("User already deleted");
}
let record_key = get_id(&user.id)?;
let record: Option<UsersSchema> = db
.update(record_key)
.merge(UsersActiveInactiveSchema {
is_active: data.is_active,
})
.await?;
match record {
Some(_) => Ok("Success update user".into()),
None => bail!("Failed to update user"),
}
}
pub async fn query_active_inactive_user_by_id(
&self,
id: String,
data: UsersActiveInactiveSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record: Option<UsersSchema> = db
.update((ResourceEnum::Users.to_string(), id))
.merge(UsersActiveInactiveSchema {
is_active: data.is_active,
})
.await?;
match record {
Some(_) => Ok("Success update user".into()),
None => bail!("Failed to update user"),
}
}
pub async fn query_update_password_user(
&self,
email: String,
data: UsersSetNewPasswordSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let user = self.query_user_by_email(email).await?;
let record: Option<UsersSetNewPasswordSchema> = db
.update((ResourceEnum::Users.to_string(), user.id.id.to_raw()))
.merge(UsersSetNewPasswordSchema {
password: data.password.clone(),
})
.await?;
dbg!(record.clone());
match record {
Some(_) => Ok("Success update password user".into()),
None => bail!("Failed to update password user"),
}
}
pub async fn query_delete_user(&self, id: String) -> Result<String> {
let db = &self.state.surrealdb_ws;
let user_id = make_thing(&ResourceEnum::Users.to_string(), &id);
let user = self.query_user_by_id(user_id.id.to_raw()).await?;
if user.is_deleted {
bail!("User already deleted");
}
let id = make_thing(&ResourceEnum::Users.to_string(), &user.id);
let record_key = get_id(&id)?;
let record: Option<UsersSchema> = db
.update(record_key)
.merge(serde_json::json!({ "is_deleted": true }))
.await?;
match record {
Some(_) => Ok("Success delete user".into()),
None => bail!("Failed to delete user"),
}
}
}
@@ -1,56 +0,0 @@
use crate::{get_iso_date, make_thing, ResourceEnum};
use serde::{Deserialize, Serialize};
use surrealdb::{sql::Thing, Uuid};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UsersSchema {
pub id: Thing,
pub fullname: String,
pub email: String,
pub password: String,
pub avatar: Option<String>,
pub phone_number: String,
pub is_active: bool,
pub is_deleted: bool,
pub gender: Option<String>,
pub birthdate: Option<String>,
pub role: Thing,
pub created_at: String,
pub updated_at: String,
}
impl Default for UsersSchema {
fn default() -> Self {
UsersSchema {
id: make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(),
),
fullname: String::new(),
email: String::new(),
password: String::new(),
avatar: None,
phone_number: String::new(),
is_active: false,
is_deleted: false,
gender: None,
birthdate: None,
role: make_thing(
&ResourceEnum::Roles.to_string(),
&Uuid::new_v4().to_string(),
),
created_at: get_iso_date(),
updated_at: get_iso_date(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UsersSetNewPasswordSchema {
pub password: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UsersActiveInactiveSchema {
pub is_active: bool,
}
@@ -1,12 +1,12 @@
[package]
name = "imphnen-iam-service"
name = "imphnen-iam"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -21,4 +21,4 @@ tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
utoipa-swagger-ui.workspace = true
@@ -7,6 +7,7 @@ pub mod v1;
pub use imphnen_entities::*;
pub use imphnen_libs::*;
pub use imphnen_utils::*;
pub use v1::*;
pub fn create_test_user(
@@ -27,6 +28,7 @@ pub fn create_test_user(
gender: None,
birthdate: None,
role: make_thing("app_roles", role_id),
..Default::default()
created_at: get_iso_date(),
updated_at: get_iso_date(),
}
}
@@ -1,25 +1,18 @@
use crate::RolesItemDto;
use lazy_static::lazy_static;
use regex::Regex;
use crate::UsersDetailItemDto;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::{Validate, ValidationError};
lazy_static! {
static ref PASSWORD_REGEX: Regex = Regex::new(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$").unwrap();
}
fn validate_password_complexity(password: &str) -> Result<(), ValidationError> {
let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
let has_digit = password.chars().any(|c| c.is_ascii_digit());
let has_special = password.chars().any(|c| "@$!%*?&".contains(c));
if has_uppercase && has_lowercase && has_digit && has_special {
Ok(())
} else {
Err(ValidationError::new("complexity"))
}
let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
let has_digit = password.chars().any(|c| c.is_ascii_digit());
let has_special = password.chars().any(|c| "@$!%*?&".contains(c));
if has_uppercase && has_lowercase && has_digit && has_special {
Ok(())
} else {
Err(ValidationError::new("complexity"))
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
@@ -33,23 +26,10 @@ pub struct AuthLoginRequestDto {
pub password: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthUserItemDto {
pub id: String,
pub role: RolesItemDto,
pub fullname: String,
pub email: String,
pub avatar: Option<String>,
pub phone_number: String,
pub is_active: bool,
pub gender: Option<String>,
pub birthdate: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthLoginResponsetDto {
pub token: TokenDto,
pub user: AuthUserItemDto,
pub user: UsersDetailItemDto,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
@@ -77,28 +57,7 @@ pub struct AuthRegisterRequestDto {
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
pub fullname: String,
#[validate(length(min = 1, message = "Student type is required"))]
pub student_type: String,
#[validate(length(
min = 10,
message = "Phone number at least have 10 character"
))]
pub phone_number: String,
#[validate(length(
max = 4,
message = "Referal code cannot be more than 4 character"
))]
pub referral_code: Option<String>,
pub referred_by: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthActiveInactiveRequestDto {
pub is_active: bool,
#[validate(
length(min = 1, message = "Email cannot be empty"),
email(message = "Email not valid")
)]
pub email: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
@@ -128,10 +87,14 @@ pub struct AuthRefreshTokenRequestDto {
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthNewPasswordRequestDto {
pub token: String,
#[validate(length(min = 1, message = "Token cannot be empty"))]
#[validate(regex(
path = "PASSWORD_REGEX",
pub token: String,
#[validate(length(
min = 8,
message = "Password must have at least 8 characters"
))]
#[validate(custom(
function = "validate_password_complexity",
message = "Password must include uppercase, lowercase, number, and special character"
))]
pub password: String,
@@ -148,8 +111,8 @@ pub struct AuthSetNewPasswordRequestDto {
min = 8,
message = "Password must have at least 8 characters"
))]
#[validate(regex(
path = "PASSWORD_REGEX",
#[validate(custom(
function = "validate_password_complexity",
message = "Password must include uppercase, lowercase, number, and special character"
))]
pub password: String,

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