Compare commits

...
67 Commits
Author SHA1 Message Date
Maulana Sodiqin e63658c082 feat: add gacha and init cms 2025-05-20 10:45:01 +07:00
Maulana Sodiqin 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 Sodiqin 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 Sodiqin 96fb8eb7d3 Merge pull request #22 from IMPHNEN/feat/split-middleware
feat: split middleware
2025-04-07 20:43:59 +07:00
Maulana Sodiqin d2c333dbd6 feat: split middleware 2025-04-07 20:41:14 +07:00
Maulana Sodiqin 054f0f63ff chore: adjust README.md 2025-04-07 20:08:26 +07:00
Maulana Sodiqin eb05ea5994 feat: add gacha service 2025-04-07 00:50:57 +07:00
Maulana Sodiqin 4f870ec4c9 fix: unit test 2025-04-06 23:35:02 +07:00
Maulana Sodiqin 31f9b6cfea feat: microservice ready 2025-04-06 22:13:46 +07:00
Maulana Sodiqin 07a93ff0b7 Merge pull request #21 from bakunya/develop
fix otp and password validation
2025-04-06 20:09:17 +07:00
Bakunya d2b098ed92 fix otp and password validation 2025-04-06 19:15:01 +07:00
Maulana Sodiqin 09a7f4371a chore: remove uneeded cargo package 2025-04-06 13:28:15 +07:00
Maulana Sodiqin b4bf78f0d6 chore: re-map project structure to using multi workspace paradigm 2025-04-06 13:25:44 +07:00
Maulana Sodiqin de9c5a6dc1 feat: implement guard 2025-04-02 09:35:37 +07:00
Maulana Sodiqin 8a661df059 feat: add image url to gacha DTO 2025-04-01 20:05:07 +07:00
Maulana Sodiqin c7c16d4197 feat: add image url 2025-04-01 20:04:28 +07:00
Maulana Sodiqin 3aec0346a9 fix: wrong id 2025-04-01 20:01:40 +07:00
Maulana Sodiqin 8d2f720de1 feat: add gacha 2025-04-01 20:00:00 +07:00
Maulana Sodiqin 4b8da68df4 feat: gacha 2025-03-30 18:58:17 +07:00
Maulana Sodiqin 6460979bab feat: complete backend service 2025-03-30 16:08:58 +07:00
Maulana Sodiqin 3ae9dbd717 feat: success test 2025-03-30 14:13:45 +07:00
Maulana Sodiqin 0816566d03 feat: update logic 2025-03-30 02:46:16 +07:00
Maulana Sodiqin a97044edfc fix: seeder roles permissions 2025-03-28 17:18:07 +07:00
Maulana Sodiqin 9d92a9a136 feat: pagination 2025-03-26 13:06:34 +07:00
Maulana Sodiqin 8e12c79ea6 feat: permissions controller 2025-03-25 20:50:42 +07:00
Maulana Sodiqin 5777268441 feat: fixing role and auth test 2025-03-25 19:30:02 +07:00
Maulana Sodiqin 34eaa418d5 feat: roles router 2025-03-25 10:48:34 +07:00
Maulana Sodiqin 77f12610dd fix: test user 2025-03-24 13:12:54 +07:00
Maulana Sodiqin 5be737ad70 chore: add test coverage 2025-03-23 20:42:38 +07:00
Maulana Sodiqin 0ae1e26ba8 chore: complete unit test of user and authentication system 2025-03-23 12:32:00 +07:00
Maulana Sodiqin 79721b7af6 chore: implement unit test 2025-03-23 07:56:43 +07:00
Maulana Sodiqin 093e290221 feat: complete auth system 2025-03-23 01:19:17 +07:00
Maulana Sodiqin 1e6957720e feat: user management 2025-03-21 17:00:19 +07:00
Maulana Sodiqin a0f263bb4f feat: update query 2025-03-21 13:25:22 +07:00
Maulana Sodiqin 413a28c089 feat: setup data 2025-03-21 05:36:00 +07:00
Maulana Sodiqin a90e8662e1 feat: initial commit 2025-03-20 22:41:20 +07:00
Maulana Sodiqin 955d384f96 fix: docker 2025-03-20 17:36:43 +07:00
Maulana Sodiqin ea5ece9ab2 feat: initial commit 2025-03-20 17:33:57 +07:00
Maulana Sodiqin 8ff532bb67 fix: cors 2025-03-20 17:07:38 +07:00
Maulana Sodiqin eb6cfd51ae feat: auth functionality 2025-03-19 23:17:50 +07:00
Maulana Sodiqin 11d6249007 feat: docs 2025-03-19 20:55:29 +07:00
Maulana Sodiqin 497c250e6d fix: change deployed branch 2025-03-19 19:34:57 +07:00
Maulana Sodiqin 2872c1827a feat: deploy 2025-03-19 19:33:56 +07:00
Maulana Sodiqin f9c49d44b5 feat: gacha roll 2025-03-19 05:34:39 +07:00
Maulana Sodiqin 12043f027c feat: gacha roll, user auth 2025-03-18 14:13:53 +07:00
Maulana Sodiqin 0c28d34d57 feat: apply env 2025-03-17 09:27:19 +07:00
Maulana Sodiqin 271b00c2c4 feat: create gacha item 2025-03-15 02:23:27 +07:00
Maulana Sodiqin b096f4129a feat: add middleware 2025-03-15 01:53:20 +07:00
Maulana Sodiqin 7ab036f5f7 feat: user relation 2025-03-14 17:50:37 +07:00
Maulana Sodiqin 9ffe808797 feat: basic auth 2025-03-14 09:53:20 +07:00
Maulana Sodiqin acfb8259bc feat: auth 2025-03-13 23:40:16 +07:00
Maulana Sodiqin 298144bd36 chore: fix nix 2025-02-26 15:55:48 +07:00
Maulana Sodiqin ff9d8cba69 feat: add cargo 2025-02-26 15:45:39 +07:00
Maulana Sodiqin 8b2769706e feat: add cargo 2025-02-26 15:45:05 +07:00
Maulana Sodiqin b8606ef0bb chore: remove seaorm 2025-02-25 02:02:01 +07:00
Maulana Sodiqin 44de53a49d feat: implement surrealdb and redis 2025-02-25 02:00:19 +07:00
Maulana Sodiqin 9abab01b9c chore: re-format file 2025-02-16 01:09:55 +07:00
Maulana Sodiqin 53414687ff chore: initial commit 2025-02-16 01:02:51 +07:00
Maulana Sodiqin d2ec21c7b1 chore: add readme 2025-02-08 01:16:14 +07:00
Maulana Sodiqin 4deee3a9cb chore: configure action 2025-02-08 01:10:48 +07:00
Maulana Sodiqin b50ce2b060 Merge pull request #1 from IMPHNEN/feat/auth-login
feat: auth login
2025-02-08 01:09:57 +07:00
155 changed files with 12079 additions and 1228 deletions
+5 -1
View File
@@ -1,4 +1,8 @@
PORT=
DATABASE_URL=
SURREALDB_URL=
SURREALDB_USERNAME=
SURREALDB_PASSWORD=
SURREALDB_NAMESPACE=
SURREALDB_DBNAME=
ACCESS_TOKEN_SECRET=
REFRESH_TOKEN_SECRET=
+65
View File
@@ -0,0 +1,65 @@
name: Deploy
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_IP }}
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_SSH_KEY }}
port: ${{ secrets.VPS_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_IP }}
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_SSH_KEY }}
port: ${{ secrets.VPS_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_IP }}
username: ${{ secrets.VPS_USER }}
key: ${{ secrets.VPS_SSH_KEY }}
port: ${{ secrets.VPS_PORT }}
script: |
set -e
echo "Restarting the service"
sudo systemctl daemon-reload
sudo systemctl restart imphnen-backend-service
echo "Deployment completed successfully"
+19
View File
@@ -0,0 +1,19 @@
name: Rust
on:
push:
branches: ["develop"]
pull_request:
branches: ["develop"]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build
run: cargo build --verbose
+1
View File
@@ -4,6 +4,7 @@
# Nix
/.direnv
/Cargo.nix
# Environment
.envrc
Generated
+3229 -871
View File
File diff suppressed because it is too large Load Diff
+35 -10
View File
@@ -1,21 +1,46 @@
[package]
name = "imphnen-cms-be"
version = "0.1.0"
edition = "2021"
[workspace]
resolver = "2"
members = [
"tests",
"imphnen-iam",
"imphnen-cms",
"imphnen-libs",
"imphnen-utils",
"imphnen-gacha",
"imphnen-gateway",
"imphnen-backend",
"imphnen-entities",
"imphnen-dimentorin",
"imphnen-middleware",
]
[dependencies]
axum = { version = "0.8.1", features = ["multipart"] }
[workspace.dependencies]
axum = { version = "0.8.4", features = ["multipart"] }
log = "0.4.25"
sea-orm = { version = "1.1.4", features = ["sqlx-postgres", "macros", "with-json", "with-uuid", "runtime-tokio", "runtime-tokio-native-tls"] }
serde = { version = "1.0.217", features = ["derive"] }
serde_json = "1.0.138"
tokio = { version = "1.43.0", features = ["full"] }
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"] }
redis = "0.28.2"
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"
[profile.release]
lto = "fat"
+3 -3
View File
@@ -11,12 +11,12 @@ WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY ./src ./src
RUN cargo build --release && strip /app/target/release/imphnen-cms-api
RUN cargo build --release && strip /app/target/release/imphnen-backend-service
FROM gcr.io/distroless/cc AS runner
WORKDIR /app
COPY --from=builder /app/target/release/imphnen-cms-api .
COPY --from=builder /app/target/release/imphnen-backend-service .
CMD ["/app/imphnen-cms-api"]
CMD ["/app/imphnen-backend-service"]
+107
View File
@@ -0,0 +1,107 @@
# IMPHNEN Backend Service
<p align="center">
<img src="docs/logo.svg" alt="IMPHNEN">
</p>
This repository serves as the **monorepo** for all backend services of IMPHNEN. It encompasses several main services:
1. **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.
## How to Install
1. **Clone the repository**:
```sh
git clone https://github.com/IMPHNEN/imphnen-backend-service.git
cd imphnen-backend-service
```
2. **Set up the environment**:
- Copy the example environment files:
```sh
cp .env.example .env
```
if you use windows based system
```sh
./apply-env.ps1
```
if you use unix based system
```sh
sh apply-env.sh
```
- Modify the `.env` files with your specific configuration settings.
3. **Install dependencies**:
Ensure you have [Rust](https://www.rust-lang.org/) installed. Then, run:
```sh
cargo build
```
## How to Run
### Development
To run the services in development mode:
1. **Start the database and other dependencies** using Docker Compose:
```sh
docker-compose up -d
```
2. **Run the desired service**. For example, to run the Core Service:
```sh
cargo run -p imphnen-core-service --bin api
```
### Production
For production deployment:
1. **Build the Docker image**:
```sh
docker build -t imphnen-backend-service .
```
2. **Run the Docker container**:
```sh
docker run -d --env-file .env -p 8080:8080 imphnen-backend-service
```
Adjust the port and environment variables as needed.
## How to Contribute
1. **Fork the repository** and clone it locally.
2. **Create a new branch** for your feature or fix:
```sh
git checkout -b feat/your-feature-name
```
3. **Make your changes**, commit them, and push to your forked repository.
4. **Create a pull request** to the `develop` branch of this repository.
If you encounter any issues or have questions, feel free to create a new issue in the repository.
---
_Note: For detailed API documentation, please refer to our [API Docs](https://api.imphnen.dev/docs)._
+30
View File
@@ -0,0 +1,30 @@
function Set-TempEnvFromDotEnv {
param (
[string]$envFilePath
)
if (-Not (Test-Path $envFilePath)) {
Write-Error "The .env file at path '$envFilePath' does not exist."
return
}
$envContent = Get-Content $envFilePath
foreach ($line in $envContent) {
$trimmedLine = $line.Trim()
if (-Not [string]::IsNullOrWhiteSpace($trimmedLine) -and -Not $trimmedLine.StartsWith("#")) {
$keyValue = $trimmedLine -split "=", 2
if ($keyValue.Length -eq 2) {
$key = $keyValue[0].Trim()
$value = $keyValue[1].Trim()
[System.Environment]::SetEnvironmentVariable($key, $value, [System.EnvironmentVariableTarget]::Process)
Write-Host "Set temporary environment variable: $key=$value"
}
}
}
Write-Host "All environment variables from '$envFilePath' have been set temporarily."
}
Set-TempEnvFromDotEnv -envFilePath ".env"
+25
View File
@@ -0,0 +1,25 @@
#!/bin/bash
set_temp_env_from_dotenv() {
local env_file_path="$1"
if [[ ! -f "$env_file_path" ]]; then
echo "Error: The .env file at path '$env_file_path' does not exist."
return 1
fi
while IFS= read -r line || [[ -n "$line" ]]; do
trimmed_line=$(echo "$line" | xargs)
if [[ -n "$trimmed_line" && ! "$trimmed_line" =~ ^# ]]; then
key=$(echo "$trimmed_line" | cut -d '=' -f 1 | xargs)
value=$(echo "$trimmed_line" | cut -d '=' -f 2- | xargs)
export "$key=$value"
echo "Set temporary environment variable: $key=$value"
fi
done < "$env_file_path"
echo "All environment variables from '$env_file_path' have been set temporarily."
}
set_temp_env_from_dotenv ".env"
+8
View File
@@ -6,3 +6,11 @@ services:
ports:
- "${PORT}:${PORT}"
env_file: ".env"
depends_on:
- surrealdb
surrealdb:
image: surrealdb/surrealdb:latest
command: start --log trace --user root --pass root
ports:
- "8000:8000"
+9
View File
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 351 KiB

Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1739020877,
"narHash": "sha256-mIvECo/NNdJJ/bXjNqIh8yeoSjVLAuDuTUzAo7dzs8Y=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "a79cfe0ebd24952b580b1cf08cd906354996d547",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+13 -5
View File
@@ -1,24 +1,32 @@
{
description = "IMPHNEN CMS API Nix Flake";
description = "IMPHNEN Backend Service Nix Flake";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
};
outputs = {
self,
nixpkgs,
}: let
supportedSystems = ["x86_64-linux" "x86_64-darwin" "aarch64-darwin" "aarch64-linux"];
pkgsFor = system:
import nixpkgs {
inherit system;
config = {
allowUnfree = true;
};
};
forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
pkgsFor = nixpkgs.legacyPackages;
in {
packages = forAllSystems (system: {
default = pkgsFor.${system}.callPackage ./default.nix {};
default = (pkgsFor system).callPackage ./default.nix {};
});
devShells = forAllSystems (system: {
default = pkgsFor.${system}.callPackage ./shell.nix {};
default = (pkgsFor system).callPackage ./shell.nix {};
});
dockerImages = forAllSystems (system: {
tryOutApi = pkgsFor.${system}.callPackage ./docker.nix {};
tryOutApi = (pkgsFor system).callPackage ./docker.nix {};
});
};
}
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "imphnen-backend"
version = "0.1.0"
edition = "2021"
[dependencies]
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-gateway = { version = "0.1.0", path = "../imphnen-gateway" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-iam = { version = "0.1.0", path = "../imphnen-iam" }
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
env_logger.workspace = true
+12
View File
@@ -0,0 +1,12 @@
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
})
.await;
}
+145
View File
@@ -0,0 +1,145 @@
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",
Some("2025-01-29T05:11:01.265+00"),
Some("2025-01-29T05:11:01.265001+00"),
),
(
"299cb4d5-6556-4cc9-b6c1-32e6d31e0f9b",
"Update Permissions",
Some("2025-01-29T05:11:01.265+00"),
Some("2025-01-29T05:11:01.265001+00"),
),
(
"319ee593-ff0a-4f29-bbaf-9feb3174a3a2",
"Create Roles",
Some("2025-01-29T05:11:01.265+00"),
Some("2025-01-29T05:11:01.265001+00"),
),
(
"319ee593-ff0a-4f29-bbaf-9feb3174a3a6",
"Read Detail Users",
Some("2025-01-29T05:11:01.265+00"),
Some("2025-01-29T05:11:01.265001+00"),
),
(
"35b0d992-65c8-4b62-b030-e6e0320e4048",
"Delete Roles",
Some("2025-01-29T05:34:40.621554+00"),
Some("2025-01-29T05:34:40.621555+00"),
),
(
"4da8b434-89f9-4d91-85ae-eebd63cdbeda",
"Update Activate Users",
Some("2025-02-01T12:38:09.741726+00"),
Some("2025-02-01T12:38:09.741727+00"),
),
(
"73888d18-b3e9-4f62-95a5-ba2c0d69fccb",
"Read Detail Roles",
Some("2025-01-29T05:13:06.445925+00"),
Some("2025-01-29T10:31:46.408564+00"),
),
(
"7c15e31d-36e2-49f9-97db-138c03fb0cf6",
"Read List Users",
Some("2025-01-28T15:02:41.772931+00"),
Some("2025-01-28T15:02:41.772933+00"),
),
(
"7d4b1379-4960-416a-b045-98cd82c0cac9",
"Read Detail Sessions",
Some("2025-02-24T16:52:26.886664+00"),
Some("2025-02-24T16:52:26.886673+00"),
),
(
"8195eeb8-e64f-4172-aa57-596492c84a72",
"Read List Permissions",
Some("2025-01-28T15:05:28.6299+00"),
Some("2025-01-28T15:05:28.629901+00"),
),
(
"81eba91d-b8ab-44b9-bbfe-4e6da2f98952",
"Read List Tests",
Some("2025-02-24T16:52:27.179542+00"),
Some("2025-02-24T16:52:27.179551+00"),
),
(
"9164ca6e-c7e3-4238-a15f-f36ab9577e7e",
"Read List Roles",
Some("2025-01-29T05:34:40.621554+00"),
Some("2025-01-29T05:34:40.621555+00"),
),
(
"96df0689-2ae9-4894-bf00-837c19415e5c",
"Delete Users",
Some("2025-02-02T06:52:05.195565+00"),
Some("2025-02-02T06:52:05.195565+00"),
),
(
"98b3dc4c-0124-461f-afcd-166637c5e6e8",
"Update Users",
Some("2025-01-29T05:34:40.621554+00"),
Some("2025-01-29T05:34:40.621555+00"),
),
(
"a00d5608-4c48-4542-845c-dfe004687022",
"Update Roles",
Some("2025-01-29T05:34:40.621554+00"),
Some("2025-01-29T05:34:40.621555+00"),
),
(
"b2dc3928-86ba-4c59-a03d-0b57d5183ebc",
"Delete Permissions",
Some("2025-01-29T05:14:22.511084+00"),
Some("2025-01-29T05:14:22.511085+00"),
),
(
"dad435cf-042c-41bd-a946-cea61ed2ffbc",
"Read Detail Permissions",
Some("2025-01-28T15:07:10.990214+00"),
Some("2025-01-28T15:07:10.990214+00"),
),
];
for (id, name, _created_at, _updated_at) in permissions {
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!("✅ All Permissions seeded");
Ok(())
}
+70
View File
@@ -0,0 +1,70 @@
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 roles = vec![
(
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
"Staf",
Some("2025-02-24T16:52:27.630453+00"),
Some("2025-02-24T16:52:27.630461+00"),
),
(
"5713cb37-dc02-4e87-8048-d7a41d352059",
"User",
None,
Some("2025-02-28T14:53:58.576688+00"),
),
(
"60f1aeb7-dad2-4e06-bcb5-be1ba510c906",
"Staff Aktivasi User",
Some("2025-02-20T02:47:09.660640+00"),
Some("2025-02-20T02:48:30.083283+00"),
),
(
"6d4fea5d-4a08-4b8a-9782-f2ab2183dcf0",
"Admin Pembayaran",
Some("2025-01-29T05:39:28.562667+00"),
Some("2025-03-12T22:56:29.597416+00"),
),
(
"f6b03f25-e416-4893-ac88-caaa690afb07",
"Admin",
None,
Some("2025-02-22T15:38:39.868306+00"),
),
];
for (id, name, _created_at, _updated_at) in roles {
db.query("CREATE type::thing('app_roles', $id) CONTENT $data")
.bind(("id", id))
.bind((
"data",
json!({
"name": name,
"permissions": [],
"is_deleted": false,
"created_at": get_iso_date(),
"updated_at": get_iso_date(),
}),
))
.await?;
println!("✅ Inserted role: {}", name);
}
println!("✅ All Roles seeded");
Ok(())
}
@@ -0,0 +1,57 @@
use imphnen_iam::{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 admin_permissions = vec![
"023e2dfe-93c3-4008-94a8-b5dff403f73b",
"0269ed71-0ae0-4c43-ad29-e3d861d8f9a0",
"299cb4d5-6556-4cc9-b6c1-32e6d31e0f9b",
"319ee593-ff0a-4f29-bbaf-9feb3174a3a2",
"319ee593-ff0a-4f29-bbaf-9feb3174a3a6",
"35b0d992-65c8-4b62-b030-e6e0320e4048",
"4da8b434-89f9-4d91-85ae-eebd63cdbeda",
"73888d18-b3e9-4f62-95a5-ba2c0d69fccb",
"7c15e31d-36e2-49f9-97db-138c03fb0cf6",
"7d4b1379-4960-416a-b045-98cd82c0cac9",
"8195eeb8-e64f-4172-aa57-596492c84a72",
"81eba91d-b8ab-44b9-bbfe-4e6da2f98952",
"9164ca6e-c7e3-4238-a15f-f36ab9577e7e",
"96df0689-2ae9-4894-bf00-837c19415e5c",
"98b3dc4c-0124-461f-afcd-166637c5e6e8",
"a00d5608-4c48-4542-845c-dfe004687022",
"b2dc3928-86ba-4c59-a03d-0b57d5183ebc",
"dad435cf-042c-41bd-a946-cea61ed2ffbc",
];
let admin_role_id = "f6b03f25-e416-4893-ac88-caaa690afb07";
let permission_refs_admin: Vec<_> = admin_permissions
.into_iter()
.map(|perm_id| make_thing("app_permissions", perm_id))
.collect();
db.query("UPDATE type::thing('app_roles', $role_id) SET permissions = $permissions, updated_at = $updated_at WHERE is_deleted = false")
.bind(("role_id", admin_role_id))
.bind(("permissions", permission_refs_admin))
.bind(("updated_at", get_iso_date()))
.await?;
println!("✅ All permissions successfully added to each role");
Ok(())
}
+66
View File
@@ -0,0 +1,66 @@
use imphnen_iam::UsersSchema;
use imphnen_utils::{get_iso_date, hash_password, Env};
use std::error::Error;
use surrealdb::{engine::remote::ws::Ws, opt::auth::Root, sql::Thing, 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 users = vec![
(
"c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2",
"admin@example.com",
"Admin",
"f6b03f25-e416-4893-ac88-caaa690afb07",
),
(
"a4d23fb5-9e31-423c-9842-fbd6e75a5298",
"staff@example.com",
"Staff",
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
),
(
"d5e89c12-72af-4b1a-abc3-ff1234567890",
"user@example.com",
"User",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
];
for (id, email, fullname, role_id) in users {
let user = UsersSchema {
id: Thing::from(("app_users", id)),
fullname: fullname.into(),
email: email.into(),
password: hash_password("password").unwrap(),
avatar: None,
phone_number: "081234567890".into(),
is_active: true,
is_deleted: false,
gender: None,
birthdate: None,
role: Thing::from(("app_roles", role_id)),
created_at: get_iso_date(),
updated_at: get_iso_date(),
};
db.create::<Option<UsersSchema>>(("app_users", id))
.content(user)
.await?;
println!("✅ Inserted user: {} ({})", fullname, email);
}
println!("✅ All Users seeded");
Ok(())
}
+10
View File
@@ -0,0 +1,10 @@
use imphnen_gateway::gateway_service;
use imphnen_libs::axum_init;
#[tokio::main]
async fn main() {
axum_init(|surrealdb_ws, surrealdb_mem| async {
gateway_service(surrealdb_ws, surrealdb_mem).await
})
.await;
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "imphnen-cms"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
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
+14
View File
@@ -0,0 +1,14 @@
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);
}
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "imphnen-dimentorin"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
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
+14
View File
@@ -0,0 +1,14 @@
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);
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "imphnen-entities"
version = "0.1.0"
edition = "2024"
[dependencies]
axum.workspace = true
serde.workspace = true
utoipa.workspace = true
surrealdb.workspace = true
thiserror.workspace = true
+69
View File
@@ -0,0 +1,69 @@
use serde::{Deserialize, Serialize};
use surrealdb::{
engine::{local::Db, remote::ws::Client},
Surreal,
};
use utoipa::{IntoParams, ToSchema};
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct MessageResponseDto {
pub message: String,
pub version: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, IntoParams)]
pub struct MetaRequestDto {
pub page: Option<u64>,
pub per_page: Option<u64>,
pub search: Option<String>,
pub sort_by: Option<String>,
pub order: Option<String>,
pub filter: Option<String>,
pub filter_by: Option<String>,
}
impl Default for MetaRequestDto {
fn default() -> Self {
MetaRequestDto {
page: Some(1),
per_page: Some(10),
search: None,
sort_by: None,
order: None,
filter: None,
filter_by: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, IntoParams)]
pub struct MetaResponseDto {
pub page: Option<u64>,
pub per_page: Option<u64>,
pub total: Option<u64>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct ResponseSuccessDto<T: Serialize> {
pub data: T,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct ResponseListSuccessDto<T: Serialize> {
pub data: T,
pub meta: Option<MetaResponseDto>,
}
pub type SurrealWsClient = Surreal<Client>;
pub type SurrealMemClient = Surreal<Db>;
#[derive(Clone)]
pub struct AppState {
pub surrealdb_ws: SurrealWsClient,
pub surrealdb_mem: SurrealMemClient,
}
#[derive(Debug, serde::Deserialize)]
pub struct CountResult {
pub count: u64,
}
+26
View File
@@ -0,0 +1,26 @@
pub mod error {
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::response::Response;
use axum::Json;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("database error")]
Db,
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
(StatusCode::INTERNAL_SERVER_ERROR, Json(self.to_string())).into_response()
}
}
impl From<surrealdb::Error> for Error {
fn from(error: surrealdb::Error) -> Self {
eprintln!("{error}");
Self::Db
}
}
}
@@ -1,3 +1,4 @@
pub mod common_dto;
pub mod error_dto;
pub use common_dto::*;
pub use error_dto::*;
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "imphnen-gacha"
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-entities = { version = "0.1.0", path = "../imphnen-entities" }
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
rand_distr.workspace = true
+10
View File
@@ -0,0 +1,10 @@
use imphnen_entities::*;
use imphnen_libs::*;
use imphnen_utils::*;
pub mod v1;
pub use imphnen_entities::*;
pub use imphnen_libs::*;
pub use imphnen_utils::*;
pub use v1::*;
@@ -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,
}
}
@@ -0,0 +1,47 @@
use crate::{GachaItemDto, GachaItemSchema};
use imphnen_iam::{UsersDetailItemDto, UsersDetailQueryDto};
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
use validator::Validate;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct GachaClaimRequestDto {
#[validate(length(min = 1, message = "User ID must not be empty"))]
pub user_id: String,
#[validate(length(min = 1, message = "Item ID must not be empty"))]
pub item_id: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaClaimItemDto {
pub id: String,
pub user: UsersDetailItemDto,
pub item: GachaItemDto,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaClaimQueryDto {
pub id: Thing,
pub user: UsersDetailQueryDto,
pub item: GachaItemSchema,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl GachaClaimItemDto {
pub fn from(dto: &GachaClaimQueryDto) -> Self {
Self {
id: dto.id.id.to_raw(),
user: UsersDetailItemDto::from(&dto.user),
item: GachaItemDto::from(&dto.item),
is_deleted: dto.is_deleted,
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
}
}
}
@@ -0,0 +1,48 @@
use super::{GachaClaimQueryDto, GachaClaimSchema};
use crate::{AppState, ResourceEnum};
use anyhow::{Result, bail};
use imphnen_iam::DetailQueryBuilder;
pub struct GachaClaimRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaClaimRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_gacha_claim_by_id(
&self,
id: String,
) -> Result<GachaClaimQueryDto> {
let db = &self.state.surrealdb_ws;
let builder = DetailQueryBuilder::new(ResourceEnum::GachaClaims.to_string())
.with_id(id.clone())
.with_select_fields(vec!["*"])
.with_fetch("item")
.with_fetch("user");
let sql = builder.build();
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"),
}
}
pub async fn query_create_gacha_claim(
&self,
data: GachaClaimSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record: Option<GachaClaimSchema> = db
.create(ResourceEnum::GachaClaims.to_string())
.content(data)
.await?;
match record {
Some(_) => Ok("Success create Gacha Claim".into()),
None => bail!("Failed to create Gacha Claim"),
}
}
}
@@ -0,0 +1,53 @@
use crate::{ResourceEnum, make_thing};
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: None,
updated_at: None,
}
}
}
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),
is_deleted: false,
created_at: None,
updated_at: None,
}
}
}
@@ -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_claim_controller;
pub mod gacha_claim_dto;
pub mod gacha_claim_repository;
pub mod gacha_claim_schema;
pub mod gacha_claim_service;
pub use gacha_claim_controller::*;
pub use gacha_claim_dto::*;
pub use gacha_claim_repository::*;
pub use gacha_claim_schema::*;
pub use gacha_claim_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,166 @@
use crate::{
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
ResponseSuccessDto,
gacha_item_dto::{GachaItemDto, GachaItemRequestDto},
gacha_item_service::GachaItemService,
};
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,
}
}
@@ -0,0 +1,33 @@
use super::GachaItemSchema;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::Validate;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct GachaItemRequestDto {
#[validate(length(min = 1, message = "Item name must not be empty"))]
pub name: String,
#[validate(length(min = 1, message = "Image URL must not be empty"))]
pub image_url: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaItemDto {
pub id: String,
pub name: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
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(),
}
}
}
@@ -0,0 +1,109 @@
use super::GachaItemSchema;
use crate::{
AppState, GachaItemDto, MetaRequestDto, ResourceEnum, ResponseListSuccessDto,
get_id, make_thing, query_list_with_meta,
};
use anyhow::{Result, bail};
pub struct GachaItemRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaItemRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
pub async fn query_gacha_item_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<GachaItemDto>>> {
let raw_result: ResponseListSuccessDto<Vec<GachaItemSchema>> =
query_list_with_meta(
&self.state.surrealdb_ws,
&ResourceEnum::GachaItems.to_string(),
&meta,
vec!["is_deleted = false".into()],
None,
"name",
Some(vec!["*"]),
None,
)
.await?;
let transformed_data = raw_result
.data
.into_iter()
.map(|gacha_item| GachaItemDto::from(&gacha_item))
.collect();
Ok(ResponseListSuccessDto {
data: transformed_data,
meta: raw_result.meta,
})
}
pub async fn query_gacha_item_by_id(&self, id: String) -> Result<GachaItemSchema> {
let db = &self.state.surrealdb_ws;
let result: Option<GachaItemSchema> = db
.select((ResourceEnum::GachaItems.to_string(), id.clone()))
.await?;
match result {
Some(item) if !item.is_deleted => Ok(item),
_ => bail!("Gacha Item not found"),
}
}
pub async fn query_create_gacha_item(
&self,
data: GachaItemSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record: Option<GachaItemSchema> = db
.create(ResourceEnum::GachaItems.to_string())
.content(data)
.await?;
match record {
Some(_) => Ok("Success create Gacha Item".into()),
None => bail!("Failed to create Gacha Item"),
}
}
pub async fn query_update_gacha_item(
&self,
data: GachaItemSchema,
) -> Result<String> {
let db = &self.state.surrealdb_ws;
let record_key = get_id(&data.id)?;
let existing = self.query_gacha_item_by_id(data.id.id.to_raw()).await?;
if existing.is_deleted {
bail!("Gacha Item already deleted");
}
let merged = GachaItemSchema {
created_at: existing.created_at,
..data.clone()
};
let record: Option<GachaItemSchema> =
db.update(record_key).merge(merged).await?;
match record {
Some(_) => Ok("Success update Gacha Item".into()),
None => bail!("Failed to update Gacha Item"),
}
}
pub async fn query_delete_gacha_item(&self, id: String) -> Result<String> {
let db = &self.state.surrealdb_ws;
let item_id = make_thing(&ResourceEnum::GachaItems.to_string(), &id);
let item = self.query_gacha_item_by_id(item_id.id.to_raw()).await?;
if item.is_deleted {
bail!("Gacha Item already deleted");
}
let record_key = get_id(&item.id)?;
let record: Option<GachaItemSchema> = db
.update(record_key)
.merge(serde_json::json!({ "is_deleted": true }))
.await?;
match record {
Some(_) => Ok("Success delete Gacha Item".into()),
None => bail!("Failed to delete Gacha Item"),
}
}
}
@@ -0,0 +1,48 @@
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,
pub name: String,
pub image_url: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for GachaItemSchema {
fn default() -> Self {
GachaItemSchema {
id: make_thing(
&ResourceEnum::GachaItems.to_string(),
&Uuid::new_v4().to_string(),
),
name: String::new(),
image_url: String::new(),
is_deleted: false,
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,
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
@@ -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_item_controller;
pub mod gacha_item_dto;
pub mod gacha_item_repository;
pub mod gacha_item_schema;
pub mod gacha_item_service;
pub use gacha_item_controller::*;
pub use gacha_item_dto::*;
pub use gacha_item_repository::*;
pub use gacha_item_schema::*;
pub use gacha_item_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,94 @@
use crate::{
AppState, MessageResponseDto, ResponseSuccessDto,
gacha_roll_dto::{GachaRollItemDto, GachaRollRequestDto},
gacha_roll_service::GachaRollService,
};
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(&state).await,
Err(response) => response,
}
}

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