feat: v0.3.0 — standardize codebase, centralize infra, merge QR into CMS
- Enforce axum best practices across all 13 workspace crates (max 200 LOC/file, no comments, no unwrap, clean architecture) - Fix domain→infrastructure dependency inversions in imphnen-iam and imphnen-dimentorin - Extract imphnen-storage (MinIO) and imphnen-email (Lettre) as standalone crates - Centralize all config in ENV struct: CDN_URL, CORS_ALLOWED_ORIGINS - Centralize SMTP through imphnen-email; remove dead HackathonConfig - Centralize database: QR crate now shares main DB pool (single DATABASE_URL) - Rename QR users table to qr_users to avoid collision with main users table - Merge imphnen-qr into imphnen-cms/src/qr (13 crates, down from 14) - Restructure imphnen-hackathon flat modules into clean architecture - Remove all stale env vars from .env.example (SurrealDB, QR_JWT, Hackathon infra) - Fix Dockerfile to include all current workspace crates - Bump all crate versions 0.2.0 → 0.3.0 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
2ae43b3bcc
commit
331a4a4e88
@@ -1,83 +1,83 @@
|
||||
use crate::testimonials::domain::testimonial::TestimonialEntity;
|
||||
use imphnen_libs::ZodValidate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use zod_rs::prelude::*;
|
||||
use crate::testimonials::domain::testimonial::TestimonialEntity;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
|
||||
pub struct TestimonialsCreateRequestDto {
|
||||
#[zod(min_length(1), max_length(100))]
|
||||
pub role: String,
|
||||
#[zod(min_length(1), max_length(1000))]
|
||||
pub content: String,
|
||||
#[zod(min_length(1), max_length(100))]
|
||||
pub role: String,
|
||||
#[zod(min_length(1), max_length(1000))]
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
impl ZodValidate for TestimonialsCreateRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
Self::validate_and_parse(value).map_err(|e| e.to_string())
|
||||
}
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
Self::validate_and_parse(value).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
|
||||
pub struct TestimonialsUpdateRequestDto {
|
||||
#[zod(min_length(1), max_length(100))]
|
||||
pub role: String,
|
||||
#[zod(min_length(1), max_length(1000))]
|
||||
pub content: String,
|
||||
#[zod(min_length(1), max_length(100))]
|
||||
pub role: String,
|
||||
#[zod(min_length(1), max_length(1000))]
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
impl ZodValidate for TestimonialsUpdateRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
Self::validate_and_parse(value).map_err(|e| e.to_string())
|
||||
}
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
Self::validate_and_parse(value).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TestimonialsListItemDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub created_at: String,
|
||||
pub is_deleted: bool,
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub created_at: String,
|
||||
pub is_deleted: bool,
|
||||
}
|
||||
|
||||
impl From<TestimonialEntity> for TestimonialsListItemDto {
|
||||
fn from(e: TestimonialEntity) -> Self {
|
||||
TestimonialsListItemDto {
|
||||
id: e.id.to_string(),
|
||||
user_id: e.user_id.to_string(),
|
||||
user_fullname: e.user_fullname,
|
||||
role: e.role,
|
||||
content: e.content,
|
||||
created_at: e.created_at,
|
||||
is_deleted: e.is_deleted,
|
||||
}
|
||||
}
|
||||
fn from(e: TestimonialEntity) -> Self {
|
||||
TestimonialsListItemDto {
|
||||
id: e.id.to_string(),
|
||||
user_id: e.user_id.to_string(),
|
||||
user_fullname: e.user_fullname,
|
||||
role: e.role,
|
||||
content: e.content,
|
||||
created_at: e.created_at,
|
||||
is_deleted: e.is_deleted,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TestimonialsDetailItemDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl From<TestimonialEntity> for TestimonialsDetailItemDto {
|
||||
fn from(e: TestimonialEntity) -> Self {
|
||||
TestimonialsDetailItemDto {
|
||||
id: e.id.to_string(),
|
||||
user_id: e.user_id.to_string(),
|
||||
user_fullname: e.user_fullname,
|
||||
role: e.role,
|
||||
content: e.content,
|
||||
created_at: e.created_at,
|
||||
updated_at: e.updated_at,
|
||||
}
|
||||
}
|
||||
fn from(e: TestimonialEntity) -> Self {
|
||||
TestimonialsDetailItemDto {
|
||||
id: e.id.to_string(),
|
||||
user_id: e.user_id.to_string(),
|
||||
user_fullname: e.user_fullname,
|
||||
role: e.role,
|
||||
content: e.content,
|
||||
created_at: e.created_at,
|
||||
updated_at: e.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
use std::sync::Arc;
|
||||
use axum::{Extension, extract::Path, http::HeaderMap, http::StatusCode, response::{IntoResponse, Response}};
|
||||
use paginator_axum::PaginationQuery;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_libs::{AppState, ValidatedJson};
|
||||
use imphnen_utils::{ApiSuccess, ApiCreated, ApiPaginated, ApiMessage, extract_email};
|
||||
use imphnen_entities::ResponseSuccessDto;
|
||||
use imphnen_iam::require_auth;
|
||||
use imphnen_utils::AppError;
|
||||
use super::dto::{
|
||||
TestimonialsCreateRequestDto, TestimonialsDetailItemDto,
|
||||
TestimonialsListItemDto, TestimonialsUpdateRequestDto,
|
||||
TestimonialsCreateRequestDto, TestimonialsDetailItemDto, TestimonialsListItemDto,
|
||||
TestimonialsUpdateRequestDto,
|
||||
};
|
||||
use crate::testimonials::domain::{TestimonialEntity, TestimonialService};
|
||||
use axum::{
|
||||
Extension,
|
||||
extract::Path,
|
||||
http::HeaderMap,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use imphnen_entities::ResponseSuccessDto;
|
||||
use imphnen_iam::require_auth;
|
||||
use imphnen_libs::{AppState, ValidatedJson};
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_utils::{
|
||||
ApiCreated, ApiMessage, ApiPaginated, ApiSuccess, extract_email,
|
||||
};
|
||||
use paginator_axum::PaginationQuery;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
@@ -30,22 +38,26 @@ use crate::testimonials::domain::{TestimonialEntity, TestimonialService};
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn get_testimonial_list(
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
PaginationQuery(params): PaginationQuery,
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
PaginationQuery(params): PaginationQuery,
|
||||
) -> Response {
|
||||
match service.list(params).await {
|
||||
Ok(result) => {
|
||||
let mapped = PaginatorResponse {
|
||||
data: result.data.into_iter()
|
||||
.filter(|e| !e.is_deleted)
|
||||
.map(TestimonialsListItemDto::from)
|
||||
.collect::<Vec<_>>(),
|
||||
meta: result.meta,
|
||||
};
|
||||
ApiPaginated(mapped).into_response()
|
||||
}
|
||||
Err(e) => ApiMessage::new(StatusCode::BAD_REQUEST, e.to_string()).into_response(),
|
||||
}
|
||||
match service.list(params).await {
|
||||
Ok(result) => {
|
||||
let mapped = PaginatorResponse {
|
||||
data: result
|
||||
.data
|
||||
.into_iter()
|
||||
.filter(|e| !e.is_deleted)
|
||||
.map(TestimonialsListItemDto::from)
|
||||
.collect::<Vec<_>>(),
|
||||
meta: result.meta,
|
||||
};
|
||||
ApiPaginated(mapped).into_response()
|
||||
}
|
||||
Err(e) => {
|
||||
ApiMessage::new(StatusCode::BAD_REQUEST, e.to_string()).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -60,20 +72,25 @@ pub async fn get_testimonial_list(
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn get_testimonial_by_id(
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
Path(id): Path<String>,
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
let uuid = match Uuid::parse_str(&id) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return ApiMessage::new(StatusCode::BAD_REQUEST, format!("Invalid UUID: {e}")).into_response(),
|
||||
};
|
||||
match service.get(uuid).await {
|
||||
Ok(t) if !t.is_deleted => {
|
||||
ApiSuccess(TestimonialsDetailItemDto::from(t)).into_response()
|
||||
}
|
||||
Ok(_) => ApiMessage::new(StatusCode::NOT_FOUND, "Testimonial not found").into_response(),
|
||||
Err(e) => ApiMessage::new(StatusCode::NOT_FOUND, e.to_string()).into_response(),
|
||||
}
|
||||
let uuid = match Uuid::parse_str(&id) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
return ApiMessage::new(StatusCode::BAD_REQUEST, format!("Invalid UUID: {e}"))
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
match service.get(uuid).await {
|
||||
Ok(t) if !t.is_deleted => {
|
||||
ApiSuccess(TestimonialsDetailItemDto::from(t)).into_response()
|
||||
}
|
||||
Ok(_) => {
|
||||
ApiMessage::new(StatusCode::NOT_FOUND, "Testimonial not found").into_response()
|
||||
}
|
||||
Err(e) => ApiMessage::new(StatusCode::NOT_FOUND, e.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -87,32 +104,36 @@ pub async fn get_testimonial_by_id(
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn post_create_testimonial(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
ValidatedJson(payload): ValidatedJson<TestimonialsCreateRequestDto>,
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
ValidatedJson(payload): ValidatedJson<TestimonialsCreateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_auth!(headers.clone(), state, {
|
||||
let email = extract_email(&headers)
|
||||
.ok_or_else(|| AppError::AuthenticationError("Token tidak valid".to_string()))?;
|
||||
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
|
||||
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
|
||||
let user = user_info.basic_info;
|
||||
let user_id = Uuid::parse_str(&user.id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid user ID: {e}")))?;
|
||||
let entity = TestimonialEntity {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
user_fullname: user.fullname.clone(),
|
||||
role: payload.role,
|
||||
content: payload.content,
|
||||
is_deleted: false,
|
||||
created_at: chrono::Utc::now().to_rfc3339(),
|
||||
updated_at: chrono::Utc::now().to_rfc3339(),
|
||||
};
|
||||
let created = service.create(entity).await?;
|
||||
Ok(ApiCreated(TestimonialsDetailItemDto::from(created)))
|
||||
})
|
||||
require_auth!(headers.clone(), state, {
|
||||
let email = extract_email(&headers).ok_or_else(|| {
|
||||
AppError::AuthenticationError("Token tidak valid".to_string())
|
||||
})?;
|
||||
let user_info = state
|
||||
.user_lookup_service
|
||||
.get_user_by_email(&email, &state)
|
||||
.await
|
||||
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
|
||||
let user = user_info.basic_info;
|
||||
let user_id = Uuid::parse_str(&user.id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid user ID: {e}")))?;
|
||||
let entity = TestimonialEntity {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
user_fullname: user.fullname.clone(),
|
||||
role: payload.role,
|
||||
content: payload.content,
|
||||
is_deleted: false,
|
||||
created_at: chrono::Utc::now().to_rfc3339(),
|
||||
updated_at: chrono::Utc::now().to_rfc3339(),
|
||||
};
|
||||
let created = service.create(entity).await?;
|
||||
Ok(ApiCreated(TestimonialsDetailItemDto::from(created)))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -129,29 +150,29 @@ pub async fn post_create_testimonial(
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn patch_update_testimonial(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(payload): ValidatedJson<TestimonialsUpdateRequestDto>,
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(payload): ValidatedJson<TestimonialsUpdateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_auth!(headers, state, {
|
||||
let uuid = Uuid::parse_str(&id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
|
||||
let existing = service.get(uuid).await?;
|
||||
let entity = TestimonialEntity {
|
||||
id: existing.id,
|
||||
user_id: existing.user_id,
|
||||
user_fullname: existing.user_fullname,
|
||||
role: payload.role,
|
||||
content: payload.content,
|
||||
is_deleted: existing.is_deleted,
|
||||
created_at: existing.created_at,
|
||||
updated_at: chrono::Utc::now().to_rfc3339(),
|
||||
};
|
||||
service.update(entity).await?;
|
||||
Ok(ApiMessage::ok("Testimonial updated"))
|
||||
})
|
||||
require_auth!(headers, state, {
|
||||
let uuid = Uuid::parse_str(&id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
|
||||
let existing = service.get(uuid).await?;
|
||||
let entity = TestimonialEntity {
|
||||
id: existing.id,
|
||||
user_id: existing.user_id,
|
||||
user_fullname: existing.user_fullname,
|
||||
role: payload.role,
|
||||
content: payload.content,
|
||||
is_deleted: existing.is_deleted,
|
||||
created_at: existing.created_at,
|
||||
updated_at: chrono::Utc::now().to_rfc3339(),
|
||||
};
|
||||
service.update(entity).await?;
|
||||
Ok(ApiMessage::ok("Testimonial updated"))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -167,15 +188,15 @@ pub async fn patch_update_testimonial(
|
||||
tag = "Testimonials"
|
||||
)]
|
||||
pub async fn delete_testimonial(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn TestimonialService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_auth!(headers, state, {
|
||||
let uuid = Uuid::parse_str(&id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
|
||||
service.delete(uuid).await?;
|
||||
Ok(ApiMessage::ok("Testimonial deleted"))
|
||||
})
|
||||
require_auth!(headers, state, {
|
||||
let uuid = Uuid::parse_str(&id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
|
||||
service.delete(uuid).await?;
|
||||
Ok(ApiMessage::ok("Testimonial deleted"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,4 +2,4 @@ pub mod dto;
|
||||
pub mod handlers;
|
||||
pub mod routes;
|
||||
|
||||
pub use routes::{testimonials_public_routes, testimonials_protected_routes};
|
||||
pub use routes::{testimonials_protected_routes, testimonials_public_routes};
|
||||
|
||||
@@ -1,32 +1,47 @@
|
||||
use std::sync::Arc;
|
||||
use axum::{Router, routing::{delete, get, patch, post}, Extension};
|
||||
use sea_orm::DatabaseConnection;
|
||||
use super::handlers::{
|
||||
delete_testimonial, get_testimonial_by_id, get_testimonial_list,
|
||||
patch_update_testimonial, post_create_testimonial,
|
||||
};
|
||||
use crate::testimonials::application::TestimonialServiceImpl;
|
||||
use crate::testimonials::domain::TestimonialService;
|
||||
use crate::testimonials::infrastructure::persistence::PostgresTestimonialRepository;
|
||||
use super::handlers::{
|
||||
delete_testimonial, get_testimonial_by_id, get_testimonial_list,
|
||||
patch_update_testimonial, post_create_testimonial,
|
||||
use axum::{
|
||||
Extension, Router,
|
||||
routing::{delete, get, patch, post},
|
||||
};
|
||||
use sea_orm::DatabaseConnection;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn build_service(db: DatabaseConnection) -> Arc<dyn TestimonialService> {
|
||||
let repo = Arc::new(PostgresTestimonialRepository::new(db));
|
||||
Arc::new(TestimonialServiceImpl::new(repo))
|
||||
let repo = Arc::new(PostgresTestimonialRepository::new(db));
|
||||
Arc::new(TestimonialServiceImpl::new(repo))
|
||||
}
|
||||
|
||||
pub fn testimonials_public_routes(db: DatabaseConnection) -> Router {
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/cms/landing/testimonials", get(get_testimonial_list))
|
||||
.route("/cms/landing/testimonials/detail/{id}", get(get_testimonial_by_id))
|
||||
.layer(Extension(service))
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/cms/landing/testimonials", get(get_testimonial_list))
|
||||
.route(
|
||||
"/cms/landing/testimonials/detail/{id}",
|
||||
get(get_testimonial_by_id),
|
||||
)
|
||||
.layer(Extension(service))
|
||||
}
|
||||
|
||||
pub fn testimonials_protected_routes(db: DatabaseConnection) -> Router {
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/cms/landing/testimonials/create", post(post_create_testimonial))
|
||||
.route("/cms/landing/testimonials/update/{id}", patch(patch_update_testimonial))
|
||||
.route("/cms/landing/testimonials/delete/{id}", delete(delete_testimonial))
|
||||
.layer(Extension(service))
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route(
|
||||
"/cms/landing/testimonials/create",
|
||||
post(post_create_testimonial),
|
||||
)
|
||||
.route(
|
||||
"/cms/landing/testimonials/update/{id}",
|
||||
patch(patch_update_testimonial),
|
||||
)
|
||||
.route(
|
||||
"/cms/landing/testimonials/delete/{id}",
|
||||
delete(delete_testimonial),
|
||||
)
|
||||
.layer(Extension(service))
|
||||
}
|
||||
|
||||
+161
-129
@@ -1,159 +1,191 @@
|
||||
use std::sync::Arc;
|
||||
use crate::testimonials::domain::{
|
||||
repository::TestimonialRepository, testimonial::TestimonialEntity,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use sea_orm::prelude::*;
|
||||
use sea_orm::{ActiveValue, QueryOrder, PaginatorTrait};
|
||||
use imphnen_entities::seaorm::auth::users::Entity as UsersEntity;
|
||||
use imphnen_entities::seaorm::common::testimonials::{
|
||||
ActiveModel as TestimonialsActiveModel, Column as TestimonialsColumn,
|
||||
Entity as TestimonialsEntity,
|
||||
};
|
||||
use imphnen_utils::AppError;
|
||||
use paginator_rs::{PaginationParams, SortDirection};
|
||||
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
|
||||
use sea_orm::prelude::*;
|
||||
use sea_orm::{ActiveValue, PaginatorTrait, QueryOrder};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_entities::seaorm::common::testimonials::{
|
||||
Entity as TestimonialsEntity, Column as TestimonialsColumn, ActiveModel as TestimonialsActiveModel,
|
||||
};
|
||||
use imphnen_entities::seaorm::auth::users::Entity as UsersEntity;
|
||||
use crate::testimonials::domain::{testimonial::TestimonialEntity, repository::TestimonialRepository};
|
||||
|
||||
pub struct PostgresTestimonialRepository {
|
||||
db: Arc<DatabaseConnection>,
|
||||
db: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
impl PostgresTestimonialRepository {
|
||||
pub fn new(db: DatabaseConnection) -> Self {
|
||||
Self { db: Arc::new(db) }
|
||||
}
|
||||
pub fn new(db: DatabaseConnection) -> Self {
|
||||
Self { db: Arc::new(db) }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TestimonialRepository for PostgresTestimonialRepository {
|
||||
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<TestimonialEntity>, AppError> {
|
||||
let page = params.page.max(1);
|
||||
let per_page = params.per_page.clamp(1, 100);
|
||||
async fn find_all(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<TestimonialEntity>, AppError> {
|
||||
let page = params.page.max(1);
|
||||
let per_page = params.per_page.clamp(1, 100);
|
||||
|
||||
let mut query = TestimonialsEntity::find()
|
||||
.filter(TestimonialsColumn::IsDeleted.eq(false))
|
||||
.find_also_related(UsersEntity);
|
||||
let mut query = TestimonialsEntity::find()
|
||||
.filter(TestimonialsColumn::IsDeleted.eq(false))
|
||||
.find_also_related(UsersEntity);
|
||||
|
||||
query = match params.sort_by.as_deref() {
|
||||
Some("updated_at") => match params.sort_direction {
|
||||
Some(SortDirection::Asc) => query.order_by_asc(TestimonialsColumn::UpdatedAt),
|
||||
_ => query.order_by_desc(TestimonialsColumn::UpdatedAt),
|
||||
},
|
||||
_ => match params.sort_direction {
|
||||
Some(SortDirection::Asc) => query.order_by_asc(TestimonialsColumn::CreatedAt),
|
||||
_ => query.order_by_desc(TestimonialsColumn::CreatedAt),
|
||||
},
|
||||
};
|
||||
query = match params.sort_by.as_deref() {
|
||||
Some("updated_at") => match params.sort_direction {
|
||||
Some(SortDirection::Asc) => {
|
||||
query.order_by_asc(TestimonialsColumn::UpdatedAt)
|
||||
}
|
||||
_ => query.order_by_desc(TestimonialsColumn::UpdatedAt),
|
||||
},
|
||||
_ => match params.sort_direction {
|
||||
Some(SortDirection::Asc) => {
|
||||
query.order_by_asc(TestimonialsColumn::CreatedAt)
|
||||
}
|
||||
_ => query.order_by_desc(TestimonialsColumn::CreatedAt),
|
||||
},
|
||||
};
|
||||
|
||||
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
|
||||
let total = paginator.num_items().await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let rows = paginator.fetch_page((page - 1) as u64).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
|
||||
let total = paginator
|
||||
.num_items()
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let rows = paginator
|
||||
.fetch_page((page - 1) as u64)
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let data: Vec<TestimonialEntity> = rows.into_iter()
|
||||
.filter_map(|(t, u)| {
|
||||
u.map(|user| TestimonialEntity {
|
||||
id: t.id,
|
||||
user_id: t.user_id,
|
||||
user_fullname: format!(
|
||||
"{} {}",
|
||||
user.first_name.as_deref().unwrap_or(""),
|
||||
user.last_name.as_deref().unwrap_or("")
|
||||
).trim().to_string(),
|
||||
role: t.role,
|
||||
content: t.content,
|
||||
is_deleted: t.is_deleted,
|
||||
created_at: t.created_at.to_rfc3339(),
|
||||
updated_at: t.updated_at.to_rfc3339(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let data: Vec<TestimonialEntity> = rows
|
||||
.into_iter()
|
||||
.filter_map(|(t, u)| {
|
||||
u.map(|user| TestimonialEntity {
|
||||
id: t.id,
|
||||
user_id: t.user_id,
|
||||
user_fullname: format!(
|
||||
"{} {}",
|
||||
user.first_name.as_deref().unwrap_or(""),
|
||||
user.last_name.as_deref().unwrap_or("")
|
||||
)
|
||||
.trim()
|
||||
.to_string(),
|
||||
role: t.role,
|
||||
content: t.content,
|
||||
is_deleted: t.is_deleted,
|
||||
created_at: t.created_at.to_rfc3339(),
|
||||
updated_at: t.updated_at.to_rfc3339(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
|
||||
Ok(PaginatorResponse { data, meta })
|
||||
}
|
||||
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
|
||||
Ok(PaginatorResponse { data, meta })
|
||||
}
|
||||
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<TestimonialEntity, AppError> {
|
||||
let (testimonial, user) = TestimonialsEntity::find_by_id(id)
|
||||
.filter(TestimonialsColumn::IsDeleted.eq(false))
|
||||
.find_also_related(UsersEntity)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?;
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<TestimonialEntity, AppError> {
|
||||
let (testimonial, user) = TestimonialsEntity::find_by_id(id)
|
||||
.filter(TestimonialsColumn::IsDeleted.eq(false))
|
||||
.find_also_related(UsersEntity)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?;
|
||||
|
||||
let user = user.ok_or_else(|| AppError::NotFoundError("User not found for testimonial".to_string()))?;
|
||||
let user = user.ok_or_else(|| {
|
||||
AppError::NotFoundError("User not found for testimonial".to_string())
|
||||
})?;
|
||||
|
||||
Ok(TestimonialEntity {
|
||||
id: testimonial.id,
|
||||
user_id: testimonial.user_id,
|
||||
user_fullname: format!(
|
||||
"{} {}",
|
||||
user.first_name.as_deref().unwrap_or(""),
|
||||
user.last_name.as_deref().unwrap_or("")
|
||||
).trim().to_string(),
|
||||
role: testimonial.role,
|
||||
content: testimonial.content,
|
||||
is_deleted: testimonial.is_deleted,
|
||||
created_at: testimonial.created_at.to_rfc3339(),
|
||||
updated_at: testimonial.updated_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
Ok(TestimonialEntity {
|
||||
id: testimonial.id,
|
||||
user_id: testimonial.user_id,
|
||||
user_fullname: format!(
|
||||
"{} {}",
|
||||
user.first_name.as_deref().unwrap_or(""),
|
||||
user.last_name.as_deref().unwrap_or("")
|
||||
)
|
||||
.trim()
|
||||
.to_string(),
|
||||
role: testimonial.role,
|
||||
content: testimonial.content,
|
||||
is_deleted: testimonial.is_deleted,
|
||||
created_at: testimonial.created_at.to_rfc3339(),
|
||||
updated_at: testimonial.updated_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn create(&self, entity: TestimonialEntity) -> Result<TestimonialEntity, AppError> {
|
||||
let active_model = TestimonialsActiveModel {
|
||||
id: ActiveValue::Set(entity.id),
|
||||
user_id: ActiveValue::Set(entity.user_id),
|
||||
role: ActiveValue::Set(entity.role.clone()),
|
||||
content: ActiveValue::Set(entity.content.clone()),
|
||||
is_deleted: ActiveValue::Set(false),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
};
|
||||
async fn create(
|
||||
&self,
|
||||
entity: TestimonialEntity,
|
||||
) -> Result<TestimonialEntity, AppError> {
|
||||
let active_model = TestimonialsActiveModel {
|
||||
id: ActiveValue::Set(entity.id),
|
||||
user_id: ActiveValue::Set(entity.user_id),
|
||||
role: ActiveValue::Set(entity.role.clone()),
|
||||
content: ActiveValue::Set(entity.content.clone()),
|
||||
is_deleted: ActiveValue::Set(false),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
};
|
||||
|
||||
let inserted = active_model.insert(self.db.as_ref()).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let inserted = active_model
|
||||
.insert(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok(TestimonialEntity {
|
||||
id: inserted.id,
|
||||
user_id: inserted.user_id,
|
||||
user_fullname: entity.user_fullname,
|
||||
role: inserted.role,
|
||||
content: inserted.content,
|
||||
is_deleted: inserted.is_deleted,
|
||||
created_at: inserted.created_at.to_rfc3339(),
|
||||
updated_at: inserted.updated_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
Ok(TestimonialEntity {
|
||||
id: inserted.id,
|
||||
user_id: inserted.user_id,
|
||||
user_fullname: entity.user_fullname,
|
||||
role: inserted.role,
|
||||
content: inserted.content,
|
||||
is_deleted: inserted.is_deleted,
|
||||
created_at: inserted.created_at.to_rfc3339(),
|
||||
updated_at: inserted.updated_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError> {
|
||||
let mut active_model: TestimonialsActiveModel = TestimonialsEntity::find_by_id(entity.id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?
|
||||
.into();
|
||||
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError> {
|
||||
let mut active_model: TestimonialsActiveModel =
|
||||
TestimonialsEntity::find_by_id(entity.id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?
|
||||
.into();
|
||||
|
||||
active_model.role = ActiveValue::Set(entity.role);
|
||||
active_model.content = ActiveValue::Set(entity.content);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
active_model.role = ActiveValue::Set(entity.role);
|
||||
active_model.content = ActiveValue::Set(entity.content);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
active_model.update(self.db.as_ref()).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
active_model
|
||||
.update(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
let mut active_model: TestimonialsActiveModel = TestimonialsEntity::find_by_id(id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?
|
||||
.into();
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
let mut active_model: TestimonialsActiveModel =
|
||||
TestimonialsEntity::find_by_id(id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Testimonial not found".to_string()))?
|
||||
.into();
|
||||
|
||||
active_model.is_deleted = ActiveValue::Set(true);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
active_model.update(self.db.as_ref()).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
active_model.is_deleted = ActiveValue::Set(true);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
active_model
|
||||
.update(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user