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,40 +1,43 @@
|
||||
use std::sync::Arc;
|
||||
use crate::events::domain::{EventEntity, EventRepository, EventService};
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::AppError;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use crate::events::domain::{EventEntity, EventRepository, EventService};
|
||||
|
||||
pub struct EventServiceImpl {
|
||||
repo: Arc<dyn EventRepository>,
|
||||
repo: Arc<dyn EventRepository>,
|
||||
}
|
||||
|
||||
impl EventServiceImpl {
|
||||
pub fn new(repo: Arc<dyn EventRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
pub fn new(repo: Arc<dyn EventRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EventService for EventServiceImpl {
|
||||
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<EventEntity>, AppError> {
|
||||
self.repo.find_all(params).await
|
||||
}
|
||||
async fn list(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<EventEntity>, AppError> {
|
||||
self.repo.find_all(params).await
|
||||
}
|
||||
|
||||
async fn get(&self, id: Uuid) -> Result<EventEntity, AppError> {
|
||||
self.repo.find_by_id(id).await
|
||||
}
|
||||
async fn get(&self, id: Uuid) -> Result<EventEntity, AppError> {
|
||||
self.repo.find_by_id(id).await
|
||||
}
|
||||
|
||||
async fn create(&self, entity: EventEntity) -> Result<(), AppError> {
|
||||
self.repo.create(entity).await
|
||||
}
|
||||
async fn create(&self, entity: EventEntity) -> Result<(), AppError> {
|
||||
self.repo.create(entity).await
|
||||
}
|
||||
|
||||
async fn update(&self, entity: EventEntity) -> Result<(), AppError> {
|
||||
self.repo.update(entity).await
|
||||
}
|
||||
async fn update(&self, entity: EventEntity) -> Result<(), AppError> {
|
||||
self.repo.update(entity).await
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
self.repo.delete(id).await
|
||||
}
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
self.repo.delete(id).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,16 +3,16 @@ use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EventEntity {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub is_deleted: bool,
|
||||
pub location: Option<String>,
|
||||
pub start_date: DateTime<Utc>,
|
||||
pub end_date: DateTime<Utc>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub is_deleted: bool,
|
||||
pub location: Option<String>,
|
||||
pub start_date: DateTime<Utc>,
|
||||
pub end_date: DateTime<Utc>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
use super::event::EventEntity;
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::AppError;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use super::event::EventEntity;
|
||||
|
||||
#[async_trait]
|
||||
pub trait EventRepository: Send + Sync {
|
||||
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<EventEntity>, AppError>;
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<EventEntity, AppError>;
|
||||
async fn create(&self, entity: EventEntity) -> Result<(), AppError>;
|
||||
async fn update(&self, entity: EventEntity) -> Result<(), AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
async fn find_all(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<EventEntity>, AppError>;
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<EventEntity, AppError>;
|
||||
async fn create(&self, entity: EventEntity) -> Result<(), AppError>;
|
||||
async fn update(&self, entity: EventEntity) -> Result<(), AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
use super::event::EventEntity;
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::AppError;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use super::event::EventEntity;
|
||||
|
||||
#[async_trait]
|
||||
pub trait EventService: Send + Sync {
|
||||
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<EventEntity>, AppError>;
|
||||
async fn get(&self, id: Uuid) -> Result<EventEntity, AppError>;
|
||||
async fn create(&self, entity: EventEntity) -> Result<(), AppError>;
|
||||
async fn update(&self, entity: EventEntity) -> Result<(), AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
async fn list(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<EventEntity>, AppError>;
|
||||
async fn get(&self, id: Uuid) -> Result<EventEntity, AppError>;
|
||||
async fn create(&self, entity: EventEntity) -> Result<(), AppError>;
|
||||
async fn update(&self, entity: EventEntity) -> Result<(), AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
}
|
||||
|
||||
@@ -1,131 +1,131 @@
|
||||
use crate::events::domain::event::EventEntity;
|
||||
use chrono::{DateTime, Utc};
|
||||
use imphnen_libs::ZodValidate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use uuid::Uuid;
|
||||
use crate::events::domain::event::EventEntity;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct EventsCreateRequestDto {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub end_date: DateTime<Utc>,
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub start_date: DateTime<Utc>,
|
||||
pub location: Option<String>,
|
||||
pub is_online: bool,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub end_date: DateTime<Utc>,
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub start_date: DateTime<Utc>,
|
||||
pub location: Option<String>,
|
||||
pub is_online: bool,
|
||||
}
|
||||
|
||||
impl ZodValidate for EventsCreateRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
|
||||
}
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<EventsCreateRequestDto> for EventEntity {
|
||||
fn from(dto: EventsCreateRequestDto) -> Self {
|
||||
EventEntity {
|
||||
id: Uuid::new_v4(),
|
||||
name: dto.name,
|
||||
description: dto.description,
|
||||
detail_link: dto.detail_link,
|
||||
price: dto.price,
|
||||
is_online: dto.is_online,
|
||||
is_deleted: false,
|
||||
location: dto.location,
|
||||
start_date: dto.start_date,
|
||||
end_date: dto.end_date,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
fn from(dto: EventsCreateRequestDto) -> Self {
|
||||
EventEntity {
|
||||
id: Uuid::new_v4(),
|
||||
name: dto.name,
|
||||
description: dto.description,
|
||||
detail_link: dto.detail_link,
|
||||
price: dto.price,
|
||||
is_online: dto.is_online,
|
||||
is_deleted: false,
|
||||
location: dto.location,
|
||||
start_date: dto.start_date,
|
||||
end_date: dto.end_date,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct EventsUpdateRequestDto {
|
||||
pub name: String,
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub end_date: DateTime<Utc>,
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub start_date: DateTime<Utc>,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub location: Option<String>,
|
||||
pub name: String,
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub end_date: DateTime<Utc>,
|
||||
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
|
||||
pub start_date: DateTime<Utc>,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub location: Option<String>,
|
||||
}
|
||||
|
||||
impl ZodValidate for EventsUpdateRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
|
||||
}
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct EventsListItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub created_at: String,
|
||||
pub location: Option<String>,
|
||||
pub is_deleted: bool,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub created_at: String,
|
||||
pub location: Option<String>,
|
||||
pub is_deleted: bool,
|
||||
}
|
||||
|
||||
impl From<EventEntity> for EventsListItemDto {
|
||||
fn from(e: EventEntity) -> Self {
|
||||
EventsListItemDto {
|
||||
id: e.id.to_string(),
|
||||
name: e.name,
|
||||
description: e.description,
|
||||
detail_link: e.detail_link,
|
||||
price: e.price,
|
||||
is_online: e.is_online,
|
||||
start_date: e.start_date.to_rfc3339(),
|
||||
end_date: e.end_date.to_rfc3339(),
|
||||
created_at: e.created_at.to_rfc3339(),
|
||||
location: e.location,
|
||||
is_deleted: e.is_deleted,
|
||||
}
|
||||
}
|
||||
fn from(e: EventEntity) -> Self {
|
||||
EventsListItemDto {
|
||||
id: e.id.to_string(),
|
||||
name: e.name,
|
||||
description: e.description,
|
||||
detail_link: e.detail_link,
|
||||
price: e.price,
|
||||
is_online: e.is_online,
|
||||
start_date: e.start_date.to_rfc3339(),
|
||||
end_date: e.end_date.to_rfc3339(),
|
||||
created_at: e.created_at.to_rfc3339(),
|
||||
location: e.location,
|
||||
is_deleted: e.is_deleted,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct EventsDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub location: Option<String>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub detail_link: String,
|
||||
pub price: f64,
|
||||
pub is_online: bool,
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub location: Option<String>,
|
||||
}
|
||||
|
||||
impl From<EventEntity> for EventsDetailItemDto {
|
||||
fn from(e: EventEntity) -> Self {
|
||||
EventsDetailItemDto {
|
||||
id: e.id.to_string(),
|
||||
name: e.name,
|
||||
description: e.description,
|
||||
detail_link: e.detail_link,
|
||||
price: e.price,
|
||||
is_online: e.is_online,
|
||||
start_date: e.start_date.to_rfc3339(),
|
||||
end_date: e.end_date.to_rfc3339(),
|
||||
created_at: e.created_at.to_rfc3339(),
|
||||
updated_at: e.updated_at.to_rfc3339(),
|
||||
location: e.location,
|
||||
}
|
||||
}
|
||||
fn from(e: EventEntity) -> Self {
|
||||
EventsDetailItemDto {
|
||||
id: e.id.to_string(),
|
||||
name: e.name,
|
||||
description: e.description,
|
||||
detail_link: e.detail_link,
|
||||
price: e.price,
|
||||
is_online: e.is_online,
|
||||
start_date: e.start_date.to_rfc3339(),
|
||||
end_date: e.end_date.to_rfc3339(),
|
||||
created_at: e.created_at.to_rfc3339(),
|
||||
updated_at: e.updated_at.to_rfc3339(),
|
||||
location: e.location,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
use std::sync::Arc;
|
||||
use axum::{Extension, extract::Path, http::HeaderMap, response::{IntoResponse, Response}};
|
||||
use paginator_axum::PaginationQuery;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_libs::{AppState, ValidatedJson};
|
||||
use imphnen_utils::{ApiSuccess, ApiPaginated, ApiMessage};
|
||||
use super::dto::{
|
||||
EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto,
|
||||
EventsUpdateRequestDto,
|
||||
};
|
||||
use crate::events::domain::EventService;
|
||||
use axum::{
|
||||
Extension,
|
||||
extract::Path,
|
||||
http::HeaderMap,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use imphnen_entities::ResponseSuccessDto;
|
||||
use imphnen_iam::{PermissionsEnum, require_permissions};
|
||||
use imphnen_libs::{AppState, ValidatedJson};
|
||||
use imphnen_utils::AppError;
|
||||
use super::dto::{EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto, EventsUpdateRequestDto};
|
||||
use crate::events::domain::EventService;
|
||||
use imphnen_utils::{ApiMessage, ApiPaginated, ApiSuccess};
|
||||
use paginator_axum::PaginationQuery;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
@@ -27,19 +35,24 @@ use crate::events::domain::EventService;
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn get_event_list(
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
PaginationQuery(params): PaginationQuery,
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
PaginationQuery(params): PaginationQuery,
|
||||
) -> Response {
|
||||
match service.list(params).await {
|
||||
Ok(result) => {
|
||||
let mapped = PaginatorResponse {
|
||||
data: result.data.into_iter().map(EventsListItemDto::from).collect::<Vec<_>>(),
|
||||
meta: result.meta,
|
||||
};
|
||||
ApiPaginated(mapped).into_response()
|
||||
}
|
||||
Err(e) => ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, e.to_string()).into_response(),
|
||||
}
|
||||
match service.list(params).await {
|
||||
Ok(result) => {
|
||||
let mapped = PaginatorResponse {
|
||||
data: result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(EventsListItemDto::from)
|
||||
.collect::<Vec<_>>(),
|
||||
meta: result.meta,
|
||||
};
|
||||
ApiPaginated(mapped).into_response()
|
||||
}
|
||||
Err(e) => ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, e.to_string())
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -54,17 +67,24 @@ pub async fn get_event_list(
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn get_event_by_id(
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
Path(id): Path<String>,
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
let uuid = match Uuid::parse_str(&id) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, format!("Invalid UUID: {e}")).into_response(),
|
||||
};
|
||||
match service.get(uuid).await {
|
||||
Ok(event) => ApiSuccess(EventsDetailItemDto::from(event)).into_response(),
|
||||
Err(e) => ApiMessage::new(axum::http::StatusCode::NOT_FOUND, e.to_string()).into_response(),
|
||||
}
|
||||
let uuid = match Uuid::parse_str(&id) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
return ApiMessage::new(
|
||||
axum::http::StatusCode::BAD_REQUEST,
|
||||
format!("Invalid UUID: {e}"),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
match service.get(uuid).await {
|
||||
Ok(event) => ApiSuccess(EventsDetailItemDto::from(event)).into_response(),
|
||||
Err(e) => ApiMessage::new(axum::http::StatusCode::NOT_FOUND, e.to_string())
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -78,16 +98,16 @@ pub async fn get_event_by_id(
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn post_create_event(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
ValidatedJson(payload): ValidatedJson<EventsCreateRequestDto>,
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
ValidatedJson(payload): ValidatedJson<EventsCreateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
let entity = payload.into();
|
||||
service.create(entity).await?;
|
||||
Ok(ApiMessage::created("Event created"))
|
||||
})
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
let entity = payload.into();
|
||||
service.create(entity).await?;
|
||||
Ok(ApiMessage::created("Event created"))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -104,33 +124,33 @@ pub async fn post_create_event(
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn patch_update_event(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(payload): ValidatedJson<EventsUpdateRequestDto>,
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(payload): ValidatedJson<EventsUpdateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
let uuid = Uuid::parse_str(&id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
|
||||
let existing = service.get(uuid).await?;
|
||||
let entity = crate::events::domain::EventEntity {
|
||||
id: existing.id,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
detail_link: payload.detail_link,
|
||||
price: payload.price,
|
||||
is_online: payload.is_online,
|
||||
location: payload.location,
|
||||
start_date: payload.start_date,
|
||||
end_date: payload.end_date,
|
||||
is_deleted: existing.is_deleted,
|
||||
created_at: existing.created_at,
|
||||
updated_at: chrono::Utc::now(),
|
||||
};
|
||||
service.update(entity).await?;
|
||||
Ok(ApiMessage::ok("Event updated"))
|
||||
})
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
let uuid = Uuid::parse_str(&id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
|
||||
let existing = service.get(uuid).await?;
|
||||
let entity = crate::events::domain::EventEntity {
|
||||
id: existing.id,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
detail_link: payload.detail_link,
|
||||
price: payload.price,
|
||||
is_online: payload.is_online,
|
||||
location: payload.location,
|
||||
start_date: payload.start_date,
|
||||
end_date: payload.end_date,
|
||||
is_deleted: existing.is_deleted,
|
||||
created_at: existing.created_at,
|
||||
updated_at: chrono::Utc::now(),
|
||||
};
|
||||
service.update(entity).await?;
|
||||
Ok(ApiMessage::ok("Event updated"))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -146,15 +166,15 @@ pub async fn patch_update_event(
|
||||
tag = "Events"
|
||||
)]
|
||||
pub async fn delete_event(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn EventService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
let uuid = Uuid::parse_str(&id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
|
||||
service.delete(uuid).await?;
|
||||
Ok(ApiMessage::ok("Event deleted"))
|
||||
})
|
||||
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
|
||||
let uuid = Uuid::parse_str(&id)
|
||||
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
|
||||
service.delete(uuid).await?;
|
||||
Ok(ApiMessage::ok("Event deleted"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,4 +2,4 @@ pub mod dto;
|
||||
pub mod handlers;
|
||||
pub mod routes;
|
||||
|
||||
pub use routes::{events_public_routes, events_protected_routes};
|
||||
pub use routes::{events_protected_routes, events_public_routes};
|
||||
|
||||
@@ -1,31 +1,35 @@
|
||||
use std::sync::Arc;
|
||||
use axum::{Router, routing::{delete, get, patch, post}, Extension};
|
||||
use sea_orm::DatabaseConnection;
|
||||
use super::handlers::{
|
||||
delete_event, get_event_by_id, get_event_list, patch_update_event,
|
||||
post_create_event,
|
||||
};
|
||||
use crate::events::application::EventServiceImpl;
|
||||
use crate::events::domain::EventService;
|
||||
use crate::events::infrastructure::persistence::PostgresEventRepository;
|
||||
use super::handlers::{
|
||||
delete_event, get_event_by_id, get_event_list, patch_update_event, post_create_event,
|
||||
use axum::{
|
||||
Extension, Router,
|
||||
routing::{delete, get, patch, post},
|
||||
};
|
||||
use sea_orm::DatabaseConnection;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn build_service(db: DatabaseConnection) -> Arc<dyn EventService> {
|
||||
let repo = Arc::new(PostgresEventRepository::new(db));
|
||||
Arc::new(EventServiceImpl::new(repo))
|
||||
let repo = Arc::new(PostgresEventRepository::new(db));
|
||||
Arc::new(EventServiceImpl::new(repo))
|
||||
}
|
||||
|
||||
pub fn events_public_routes(db: DatabaseConnection) -> Router {
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/cms/landing/events", get(get_event_list))
|
||||
.route("/cms/landing/events/detail/{id}", get(get_event_by_id))
|
||||
.layer(Extension(service))
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/cms/landing/events", get(get_event_list))
|
||||
.route("/cms/landing/events/detail/{id}", get(get_event_by_id))
|
||||
.layer(Extension(service))
|
||||
}
|
||||
|
||||
pub fn events_protected_routes(db: DatabaseConnection) -> Router {
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/cms/landing/events/create", post(post_create_event))
|
||||
.route("/cms/landing/events/update/{id}", patch(patch_update_event))
|
||||
.route("/cms/landing/events/delete/{id}", delete(delete_event))
|
||||
.layer(Extension(service))
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/cms/landing/events/create", post(post_create_event))
|
||||
.route("/cms/landing/events/update/{id}", patch(patch_update_event))
|
||||
.route("/cms/landing/events/delete/{id}", delete(delete_event))
|
||||
.layer(Extension(service))
|
||||
}
|
||||
|
||||
@@ -1,149 +1,161 @@
|
||||
use std::sync::Arc;
|
||||
use crate::events::domain::{event::EventEntity, repository::EventRepository};
|
||||
use async_trait::async_trait;
|
||||
use sea_orm::prelude::*;
|
||||
use sea_orm::{ActiveValue, Order, QueryOrder, PaginatorTrait};
|
||||
use imphnen_entities::seaorm::common::events::{
|
||||
ActiveModel as EventsActiveModel, Column as EventsColumn, Entity as EventsEntity,
|
||||
Model as EventsModel,
|
||||
};
|
||||
use imphnen_utils::AppError;
|
||||
use paginator_rs::{PaginationParams, SortDirection};
|
||||
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
|
||||
use sea_orm::prelude::*;
|
||||
use sea_orm::{ActiveValue, Order, PaginatorTrait, QueryOrder};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_entities::seaorm::common::events::{
|
||||
Entity as EventsEntity, Column as EventsColumn,
|
||||
ActiveModel as EventsActiveModel, Model as EventsModel,
|
||||
};
|
||||
use crate::events::domain::{event::EventEntity, repository::EventRepository};
|
||||
|
||||
fn to_entity(model: EventsModel) -> EventEntity {
|
||||
EventEntity {
|
||||
id: model.id,
|
||||
name: model.name,
|
||||
description: model.description,
|
||||
detail_link: model.detail_link,
|
||||
price: model.price,
|
||||
is_online: model.is_online,
|
||||
is_deleted: model.is_deleted,
|
||||
location: model.location,
|
||||
start_date: model.start_date,
|
||||
end_date: model.end_date,
|
||||
created_at: model.created_at,
|
||||
updated_at: model.updated_at,
|
||||
}
|
||||
EventEntity {
|
||||
id: model.id,
|
||||
name: model.name,
|
||||
description: model.description,
|
||||
detail_link: model.detail_link,
|
||||
price: model.price,
|
||||
is_online: model.is_online,
|
||||
is_deleted: model.is_deleted,
|
||||
location: model.location,
|
||||
start_date: model.start_date,
|
||||
end_date: model.end_date,
|
||||
created_at: model.created_at,
|
||||
updated_at: model.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PostgresEventRepository {
|
||||
db: Arc<DatabaseConnection>,
|
||||
db: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
impl PostgresEventRepository {
|
||||
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 EventRepository for PostgresEventRepository {
|
||||
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<EventEntity>, AppError> {
|
||||
let page = params.page.max(1);
|
||||
let per_page = params.per_page.clamp(1, 100);
|
||||
async fn find_all(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<EventEntity>, AppError> {
|
||||
let page = params.page.max(1);
|
||||
let per_page = params.per_page.clamp(1, 100);
|
||||
|
||||
let mut query = EventsEntity::find()
|
||||
.filter(EventsColumn::IsDeleted.eq(false));
|
||||
let mut query = EventsEntity::find().filter(EventsColumn::IsDeleted.eq(false));
|
||||
|
||||
if let Some(ref search) = params.search {
|
||||
query = query.filter(EventsColumn::Name.contains(&search.query));
|
||||
}
|
||||
if let Some(ref search) = params.search {
|
||||
query = query.filter(EventsColumn::Name.contains(&search.query));
|
||||
}
|
||||
|
||||
query = match params.sort_by.as_deref() {
|
||||
Some("name") => match params.sort_direction {
|
||||
Some(SortDirection::Desc) => query.order_by(EventsColumn::Name, Order::Desc),
|
||||
_ => query.order_by(EventsColumn::Name, Order::Asc),
|
||||
},
|
||||
_ => match params.sort_direction {
|
||||
Some(SortDirection::Asc) => query.order_by(EventsColumn::CreatedAt, Order::Asc),
|
||||
_ => query.order_by(EventsColumn::CreatedAt, Order::Desc),
|
||||
},
|
||||
};
|
||||
query = match params.sort_by.as_deref() {
|
||||
Some("name") => match params.sort_direction {
|
||||
Some(SortDirection::Desc) => query.order_by(EventsColumn::Name, Order::Desc),
|
||||
_ => query.order_by(EventsColumn::Name, Order::Asc),
|
||||
},
|
||||
_ => match params.sort_direction {
|
||||
Some(SortDirection::Asc) => {
|
||||
query.order_by(EventsColumn::CreatedAt, Order::Asc)
|
||||
}
|
||||
_ => query.order_by(EventsColumn::CreatedAt, Order::Desc),
|
||||
},
|
||||
};
|
||||
|
||||
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
|
||||
let total = paginator.num_items().await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let events = paginator.fetch_page((page - 1) as u64).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
|
||||
let total = paginator
|
||||
.num_items()
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let events = paginator
|
||||
.fetch_page((page - 1) as u64)
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let data = events.into_iter().map(to_entity).collect();
|
||||
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
|
||||
Ok(PaginatorResponse { data, meta })
|
||||
}
|
||||
let data = events.into_iter().map(to_entity).collect();
|
||||
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
|
||||
Ok(PaginatorResponse { data, meta })
|
||||
}
|
||||
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<EventEntity, AppError> {
|
||||
let event = EventsEntity::find_by_id(id)
|
||||
.filter(EventsColumn::IsDeleted.eq(false))
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?;
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<EventEntity, AppError> {
|
||||
let event = EventsEntity::find_by_id(id)
|
||||
.filter(EventsColumn::IsDeleted.eq(false))
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?;
|
||||
|
||||
Ok(to_entity(event))
|
||||
}
|
||||
Ok(to_entity(event))
|
||||
}
|
||||
|
||||
async fn create(&self, entity: EventEntity) -> Result<(), AppError> {
|
||||
let active_model = EventsActiveModel {
|
||||
id: ActiveValue::Set(entity.id),
|
||||
name: ActiveValue::Set(entity.name),
|
||||
description: ActiveValue::Set(entity.description),
|
||||
detail_link: ActiveValue::Set(entity.detail_link),
|
||||
price: ActiveValue::Set(entity.price),
|
||||
is_online: ActiveValue::Set(entity.is_online),
|
||||
is_deleted: ActiveValue::Set(false),
|
||||
location: ActiveValue::Set(entity.location),
|
||||
start_date: ActiveValue::Set(entity.start_date),
|
||||
end_date: ActiveValue::Set(entity.end_date),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
};
|
||||
async fn create(&self, entity: EventEntity) -> Result<(), AppError> {
|
||||
let active_model = EventsActiveModel {
|
||||
id: ActiveValue::Set(entity.id),
|
||||
name: ActiveValue::Set(entity.name),
|
||||
description: ActiveValue::Set(entity.description),
|
||||
detail_link: ActiveValue::Set(entity.detail_link),
|
||||
price: ActiveValue::Set(entity.price),
|
||||
is_online: ActiveValue::Set(entity.is_online),
|
||||
is_deleted: ActiveValue::Set(false),
|
||||
location: ActiveValue::Set(entity.location),
|
||||
start_date: ActiveValue::Set(entity.start_date),
|
||||
end_date: ActiveValue::Set(entity.end_date),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
};
|
||||
|
||||
EventsEntity::insert(active_model)
|
||||
.exec(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
EventsEntity::insert(active_model)
|
||||
.exec(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update(&self, entity: EventEntity) -> Result<(), AppError> {
|
||||
let mut active_model: EventsActiveModel = EventsEntity::find_by_id(entity.id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?
|
||||
.into();
|
||||
async fn update(&self, entity: EventEntity) -> Result<(), AppError> {
|
||||
let mut active_model: EventsActiveModel = EventsEntity::find_by_id(entity.id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?
|
||||
.into();
|
||||
|
||||
active_model.name = ActiveValue::Set(entity.name);
|
||||
active_model.description = ActiveValue::Set(entity.description);
|
||||
active_model.detail_link = ActiveValue::Set(entity.detail_link);
|
||||
active_model.price = ActiveValue::Set(entity.price);
|
||||
active_model.is_online = ActiveValue::Set(entity.is_online);
|
||||
active_model.location = ActiveValue::Set(entity.location);
|
||||
active_model.start_date = ActiveValue::Set(entity.start_date);
|
||||
active_model.end_date = ActiveValue::Set(entity.end_date);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
active_model.name = ActiveValue::Set(entity.name);
|
||||
active_model.description = ActiveValue::Set(entity.description);
|
||||
active_model.detail_link = ActiveValue::Set(entity.detail_link);
|
||||
active_model.price = ActiveValue::Set(entity.price);
|
||||
active_model.is_online = ActiveValue::Set(entity.is_online);
|
||||
active_model.location = ActiveValue::Set(entity.location);
|
||||
active_model.start_date = ActiveValue::Set(entity.start_date);
|
||||
active_model.end_date = ActiveValue::Set(entity.end_date);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
active_model.update(self.db.as_ref()).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
active_model
|
||||
.update(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
let mut active_model: EventsActiveModel = EventsEntity::find_by_id(id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?
|
||||
.into();
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
let mut active_model: EventsActiveModel = EventsEntity::find_by_id(id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?
|
||||
.into();
|
||||
|
||||
active_model.is_deleted = ActiveValue::Set(true);
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
active_model.update(self.db.as_ref()).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,4 +2,4 @@ pub mod application;
|
||||
pub mod domain;
|
||||
pub mod infrastructure;
|
||||
|
||||
pub use infrastructure::http::{events_public_routes, events_protected_routes};
|
||||
pub use infrastructure::http::{events_protected_routes, events_public_routes};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
pub mod events;
|
||||
pub mod testimonials;
|
||||
pub mod qr;
|
||||
|
||||
pub use events::{events_public_routes, events_protected_routes};
|
||||
pub use testimonials::{testimonials_public_routes, testimonials_protected_routes};
|
||||
pub use events::{events_protected_routes, events_public_routes};
|
||||
pub use testimonials::{testimonials_protected_routes, testimonials_public_routes};
|
||||
pub use qr::qr_router;
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
use async_trait::async_trait;
|
||||
use image::{DynamicImage, GenericImageView, ImageFormat, imageops};
|
||||
use imphnen_utils::errors::AppError;
|
||||
use qrcode::QrCode;
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::qr::campaigns::domain::{
|
||||
entity::{CampaignEntity, CreateCampaignInput},
|
||||
repository::CampaignRepository,
|
||||
service::QrCampaignService,
|
||||
};
|
||||
|
||||
pub struct QrCampaignServiceImpl {
|
||||
repo: Arc<dyn CampaignRepository>,
|
||||
}
|
||||
|
||||
impl QrCampaignServiceImpl {
|
||||
pub fn new(repo: Arc<dyn CampaignRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl QrCampaignService for QrCampaignServiceImpl {
|
||||
async fn create(
|
||||
&self,
|
||||
name: String,
|
||||
url: String,
|
||||
created_by: Uuid,
|
||||
) -> Result<CampaignEntity, AppError> {
|
||||
let qr = QrCode::new(url.as_bytes())
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let qr_img = qr
|
||||
.render::<image::Luma<u8>>()
|
||||
.min_dimensions(256, 256)
|
||||
.build();
|
||||
let mut qr_bytes = Vec::new();
|
||||
DynamicImage::ImageLuma8(qr_img)
|
||||
.write_to(&mut Cursor::new(&mut qr_bytes), ImageFormat::Png)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let input = CreateCampaignInput {
|
||||
name,
|
||||
url,
|
||||
created_by,
|
||||
qr_code_data: qr_bytes,
|
||||
};
|
||||
self.repo.create(input).await
|
||||
}
|
||||
|
||||
async fn list_all(&self) -> Result<Vec<CampaignEntity>, AppError> {
|
||||
self.repo.find_all().await
|
||||
}
|
||||
|
||||
async fn get_active_qr_data(&self) -> Result<Option<Vec<u8>>, AppError> {
|
||||
self.repo.find_active_qr_data().await
|
||||
}
|
||||
|
||||
async fn set_active(&self, id: Uuid) -> Result<CampaignEntity, AppError> {
|
||||
self.repo.set_active(id).await
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
self.repo.delete(id).await
|
||||
}
|
||||
|
||||
async fn process_image(&self, image_bytes: Vec<u8>) -> Result<Vec<u8>, AppError> {
|
||||
let qr_data = self
|
||||
.repo
|
||||
.find_active_qr_data()
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFoundError("No active campaign".to_string()))?;
|
||||
|
||||
let img = image::load_from_memory(&image_bytes)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid image format".to_string()))?;
|
||||
|
||||
let qr_img = image::load_from_memory(&qr_data).map_err(|_| {
|
||||
AppError::InternalServerError("Failed to load QR data".to_string())
|
||||
})?;
|
||||
|
||||
let (w, h) = img.dimensions();
|
||||
let qr_size = (std::cmp::min(w, h) / 5).max(100);
|
||||
|
||||
let qr_resized =
|
||||
qr_img.resize_exact(qr_size, qr_size, imageops::FilterType::Nearest);
|
||||
|
||||
let mut output = img.to_rgba8();
|
||||
let x = (w - qr_size - 10) as i64;
|
||||
let y = (h - qr_size - 10) as i64;
|
||||
imageops::overlay(&mut output, &qr_resized.to_rgba8(), x, y);
|
||||
|
||||
let mut out_bytes = Vec::new();
|
||||
DynamicImage::ImageRgba8(output)
|
||||
.write_to(&mut Cursor::new(&mut out_bytes), ImageFormat::Png)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok(out_bytes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod campaign_service;
|
||||
@@ -0,0 +1,22 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct CampaignEntity {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub is_active: bool,
|
||||
pub created_by: Uuid,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
pub created_at: Option<DateTime<Utc>>,
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
pub struct CreateCampaignInput {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub created_by: Uuid,
|
||||
pub qr_code_data: Vec<u8>,
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod entity;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
@@ -0,0 +1,17 @@
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::errors::AppError;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::entity::{CampaignEntity, CreateCampaignInput};
|
||||
|
||||
#[async_trait]
|
||||
pub trait CampaignRepository: Send + Sync {
|
||||
async fn create(
|
||||
&self,
|
||||
input: CreateCampaignInput,
|
||||
) -> Result<CampaignEntity, AppError>;
|
||||
async fn find_all(&self) -> Result<Vec<CampaignEntity>, AppError>;
|
||||
async fn find_active_qr_data(&self) -> Result<Option<Vec<u8>>, AppError>;
|
||||
async fn set_active(&self, id: Uuid) -> Result<CampaignEntity, AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::errors::AppError;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::entity::CampaignEntity;
|
||||
|
||||
#[async_trait]
|
||||
pub trait QrCampaignService: Send + Sync {
|
||||
async fn create(
|
||||
&self,
|
||||
name: String,
|
||||
url: String,
|
||||
created_by: Uuid,
|
||||
) -> Result<CampaignEntity, AppError>;
|
||||
async fn list_all(&self) -> Result<Vec<CampaignEntity>, AppError>;
|
||||
async fn get_active_qr_data(&self) -> Result<Option<Vec<u8>>, AppError>;
|
||||
async fn set_active(&self, id: Uuid) -> Result<CampaignEntity, AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
async fn process_image(&self, image_bytes: Vec<u8>) -> Result<Vec<u8>, AppError>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct CreateCampaignRequest {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct CampaignResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub is_active: bool,
|
||||
pub created_by: Uuid,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
pub created_at: Option<DateTime<Utc>>,
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Multipart, Path},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use imphnen_utils::{errors::AppError, response_format::ApiSuccess};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::qr::{
|
||||
campaigns::{
|
||||
domain::service::QrCampaignService,
|
||||
infrastructure::http::dto::CreateCampaignRequest,
|
||||
},
|
||||
middleware::qr_auth::QrAuthUser,
|
||||
};
|
||||
|
||||
pub async fn create_campaign_handler(
|
||||
Extension(service): Extension<Arc<dyn QrCampaignService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
Json(body): Json<CreateCampaignRequest>,
|
||||
) -> Result<Response, AppError> {
|
||||
if auth_user.role != "admin" {
|
||||
return Err(AppError::ForbiddenError(
|
||||
"Admin access required".to_string(),
|
||||
));
|
||||
}
|
||||
let campaign = service
|
||||
.create(body.name, body.url, auth_user.user_id)
|
||||
.await?;
|
||||
Ok(imphnen_utils::response_format::ApiCreated(campaign).into_response())
|
||||
}
|
||||
|
||||
pub async fn list_campaigns_handler(
|
||||
Extension(service): Extension<Arc<dyn QrCampaignService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
) -> Result<Response, AppError> {
|
||||
if auth_user.role != "admin" {
|
||||
return Err(AppError::ForbiddenError(
|
||||
"Admin access required".to_string(),
|
||||
));
|
||||
}
|
||||
let campaigns = service.list_all().await?;
|
||||
Ok(ApiSuccess(campaigns).into_response())
|
||||
}
|
||||
|
||||
pub async fn activate_campaign_handler(
|
||||
Extension(service): Extension<Arc<dyn QrCampaignService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Response, AppError> {
|
||||
if auth_user.role != "admin" {
|
||||
return Err(AppError::ForbiddenError(
|
||||
"Admin access required".to_string(),
|
||||
));
|
||||
}
|
||||
let campaign = service.set_active(id).await?;
|
||||
Ok(ApiSuccess(campaign).into_response())
|
||||
}
|
||||
|
||||
pub async fn delete_campaign_handler(
|
||||
Extension(service): Extension<Arc<dyn QrCampaignService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Response, AppError> {
|
||||
if auth_user.role != "admin" {
|
||||
return Err(AppError::ForbiddenError(
|
||||
"Admin access required".to_string(),
|
||||
));
|
||||
}
|
||||
service.delete(id).await?;
|
||||
Ok(
|
||||
imphnen_utils::response_format::ApiMessage::ok("Campaign deleted successfully")
|
||||
.into_response(),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn process_image_handler(
|
||||
Extension(service): Extension<Arc<dyn QrCampaignService>>,
|
||||
Extension(_auth_user): Extension<QrAuthUser>,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<Response, AppError> {
|
||||
let mut image_bytes = Vec::new();
|
||||
while let Some(field) = multipart
|
||||
.next_field()
|
||||
.await
|
||||
.map_err(|e| AppError::BadRequestError(e.to_string()))?
|
||||
{
|
||||
if field.name() == Some("file") {
|
||||
image_bytes = field
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(|e| AppError::BadRequestError(e.to_string()))?
|
||||
.to_vec();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if image_bytes.is_empty() {
|
||||
return Err(AppError::BadRequestError("No file provided".to_string()));
|
||||
}
|
||||
let png_bytes = service.process_image(image_bytes).await?;
|
||||
Ok(([(axum::http::header::CONTENT_TYPE, "image/png")], png_bytes).into_response())
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod dto;
|
||||
pub mod handlers;
|
||||
pub mod routes;
|
||||
@@ -0,0 +1,41 @@
|
||||
use axum::{
|
||||
Extension, Router,
|
||||
middleware::from_fn,
|
||||
routing::{delete, post, put},
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::qr::{
|
||||
campaigns::{
|
||||
application::campaign_service::QrCampaignServiceImpl,
|
||||
domain::{repository::CampaignRepository, service::QrCampaignService},
|
||||
infrastructure::{
|
||||
http::handlers::{
|
||||
activate_campaign_handler, create_campaign_handler, delete_campaign_handler,
|
||||
list_campaigns_handler, process_image_handler,
|
||||
},
|
||||
persistence::postgres_campaign_repository::PostgresCampaignRepository,
|
||||
},
|
||||
},
|
||||
middleware::qr_auth::qr_auth_middleware,
|
||||
};
|
||||
|
||||
pub fn qr_campaigns_routes(pool: Arc<PgPool>) -> Router {
|
||||
let repo: Arc<dyn CampaignRepository> =
|
||||
Arc::new(PostgresCampaignRepository::new(pool.clone()));
|
||||
let service: Arc<dyn QrCampaignService> =
|
||||
Arc::new(QrCampaignServiceImpl::new(repo));
|
||||
|
||||
Router::new()
|
||||
.route(
|
||||
"/campaigns",
|
||||
post(create_campaign_handler).get(list_campaigns_handler),
|
||||
)
|
||||
.route("/campaigns/:id/activate", put(activate_campaign_handler))
|
||||
.route("/campaigns/:id", delete(delete_campaign_handler))
|
||||
.route("/campaigns/process-image", post(process_image_handler))
|
||||
.layer(Extension(service))
|
||||
.layer(Extension(pool))
|
||||
.layer(from_fn(qr_auth_middleware))
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod http;
|
||||
pub mod persistence;
|
||||
@@ -0,0 +1 @@
|
||||
pub mod postgres_campaign_repository;
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::errors::AppError;
|
||||
use sqlx::FromRow;
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::qr::campaigns::domain::{
|
||||
entity::{CampaignEntity, CreateCampaignInput},
|
||||
repository::CampaignRepository,
|
||||
};
|
||||
|
||||
#[derive(FromRow)]
|
||||
struct CampaignRow {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub is_active: bool,
|
||||
pub created_by: Uuid,
|
||||
pub expires_at: chrono::DateTime<chrono::Utc>,
|
||||
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
impl From<CampaignRow> for CampaignEntity {
|
||||
fn from(row: CampaignRow) -> Self {
|
||||
CampaignEntity {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
url: row.url,
|
||||
is_active: row.is_active,
|
||||
created_by: row.created_by,
|
||||
expires_at: row.expires_at,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PostgresCampaignRepository {
|
||||
pool: Arc<PgPool>,
|
||||
}
|
||||
|
||||
impl PostgresCampaignRepository {
|
||||
pub fn new(pool: Arc<PgPool>) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CampaignRepository for PostgresCampaignRepository {
|
||||
async fn create(
|
||||
&self,
|
||||
input: CreateCampaignInput,
|
||||
) -> Result<CampaignEntity, AppError> {
|
||||
let mut tx = self
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
sqlx::query("UPDATE qr_campaigns SET is_active = false, updated_at = NOW()")
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let id = Uuid::new_v4();
|
||||
let campaign = sqlx::query_as::<_, CampaignRow>(
|
||||
"INSERT INTO qr_campaigns (id, name, url, qr_code_data, is_active, created_by, expires_at) \
|
||||
VALUES ($1, $2, $3, $4, true, $5, NOW() + INTERVAL '30 days') \
|
||||
RETURNING id, name, url, is_active, created_by, expires_at, created_at, updated_at",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(&input.name)
|
||||
.bind(&input.url)
|
||||
.bind(&input.qr_code_data)
|
||||
.bind(input.created_by)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok(campaign.into())
|
||||
}
|
||||
|
||||
async fn find_all(&self) -> Result<Vec<CampaignEntity>, AppError> {
|
||||
sqlx::query_as::<_, CampaignRow>(
|
||||
"SELECT id, name, url, is_active, created_by, expires_at, created_at, updated_at \
|
||||
FROM qr_campaigns ORDER BY created_at DESC",
|
||||
)
|
||||
.fetch_all(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))
|
||||
.map(|rows| rows.into_iter().map(Into::into).collect())
|
||||
}
|
||||
|
||||
async fn find_active_qr_data(&self) -> Result<Option<Vec<u8>>, AppError> {
|
||||
let row = sqlx::query_as::<_, (Vec<u8>,)>(
|
||||
"SELECT qr_code_data FROM qr_campaigns WHERE is_active = true LIMIT 1",
|
||||
)
|
||||
.fetch_optional(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok(row.map(|r| r.0))
|
||||
}
|
||||
|
||||
async fn set_active(&self, id: Uuid) -> Result<CampaignEntity, AppError> {
|
||||
let mut tx = self
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
sqlx::query("UPDATE qr_campaigns SET is_active = false, updated_at = NOW()")
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let campaign = sqlx::query_as::<_, CampaignRow>(
|
||||
"UPDATE qr_campaigns SET is_active = true, updated_at = NOW() WHERE id = $1 \
|
||||
RETURNING id, name, url, is_active, created_by, expires_at, created_at, updated_at",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok(campaign.into())
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
sqlx::query("DELETE FROM qr_campaigns WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod application;
|
||||
pub mod domain;
|
||||
pub mod infrastructure;
|
||||
pub use infrastructure::http::routes::qr_campaigns_routes;
|
||||
@@ -0,0 +1 @@
|
||||
pub mod qr_auth;
|
||||
@@ -0,0 +1,69 @@
|
||||
use axum::http::StatusCode;
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::Request,
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use imphnen_libs::decode_access_token;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct QrAuthUser {
|
||||
pub user_id: Uuid,
|
||||
pub role: String,
|
||||
}
|
||||
|
||||
pub async fn qr_auth_middleware(
|
||||
axum::Extension(pool): axum::Extension<Arc<PgPool>>,
|
||||
mut request: Request<Body>,
|
||||
next: Next,
|
||||
) -> Result<Response, Response> {
|
||||
let auth_header = request
|
||||
.headers()
|
||||
.get("Authorization")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.ok_or_else(|| {
|
||||
(StatusCode::UNAUTHORIZED, "Missing Authorization header").into_response()
|
||||
})?;
|
||||
|
||||
let token = auth_header.strip_prefix("Bearer ").ok_or_else(|| {
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid Authorization header format",
|
||||
)
|
||||
.into_response()
|
||||
})?;
|
||||
|
||||
let token_data = decode_access_token(token).map_err(|_| {
|
||||
(StatusCode::UNAUTHORIZED, "Invalid or expired token").into_response()
|
||||
})?;
|
||||
|
||||
let user_id = Uuid::parse_str(&token_data.claims.user_id).map_err(|_| {
|
||||
(StatusCode::UNAUTHORIZED, "Invalid user ID in token").into_response()
|
||||
})?;
|
||||
|
||||
let _ = sqlx::query(
|
||||
"INSERT INTO qr_users (id, email, name, role, provider) VALUES ($1, $2, $2, 'user', 'external') ON CONFLICT (id) DO NOTHING"
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&token_data.claims.sub)
|
||||
.execute(pool.as_ref())
|
||||
.await;
|
||||
|
||||
let role: String = sqlx::query_scalar("SELECT role FROM qr_users WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_optional(pool.as_ref())
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_else(|| "user".to_string());
|
||||
|
||||
request
|
||||
.extensions_mut()
|
||||
.insert(QrAuthUser { user_id, role });
|
||||
Ok(next.run(request).await)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
pub mod campaigns;
|
||||
pub mod middleware;
|
||||
pub mod users;
|
||||
|
||||
use axum::Router;
|
||||
use sea_orm::DatabaseConnection;
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn qr_router(db: DatabaseConnection) -> Router {
|
||||
let pool: Arc<PgPool> = Arc::new(db.get_postgres_connection_pool().clone());
|
||||
Router::new()
|
||||
.merge(users::infrastructure::http::routes::qr_users_routes(pool.clone()))
|
||||
.merge(campaigns::infrastructure::http::routes::qr_campaigns_routes(pool))
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod user_service;
|
||||
@@ -0,0 +1,62 @@
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::errors::AppError;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::qr::users::domain::{
|
||||
entity::{UpdateUserInput, UserEntity},
|
||||
repository::UserRepository,
|
||||
service::QrUserService,
|
||||
};
|
||||
|
||||
pub struct QrUserServiceImpl {
|
||||
repo: Arc<dyn UserRepository>,
|
||||
}
|
||||
|
||||
impl QrUserServiceImpl {
|
||||
pub fn new(repo: Arc<dyn UserRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl QrUserService for QrUserServiceImpl {
|
||||
async fn get_profile(&self, user_id: Uuid) -> Result<UserEntity, AppError> {
|
||||
self
|
||||
.repo
|
||||
.find_by_id(user_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFoundError("User not found".to_string()))
|
||||
}
|
||||
|
||||
async fn update_profile(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
input: UpdateUserInput,
|
||||
) -> Result<UserEntity, AppError> {
|
||||
if let Some(ref email) = input.email
|
||||
&& email.trim().is_empty()
|
||||
{
|
||||
return Err(AppError::ValidationError(
|
||||
"Email cannot be empty".to_string(),
|
||||
));
|
||||
}
|
||||
self.repo.update(user_id, input).await
|
||||
}
|
||||
|
||||
async fn list_all(&self) -> Result<Vec<UserEntity>, AppError> {
|
||||
self.repo.find_all().await
|
||||
}
|
||||
|
||||
async fn update_role(
|
||||
&self,
|
||||
id: Uuid,
|
||||
role: String,
|
||||
) -> Result<UserEntity, AppError> {
|
||||
self.repo.update_role(id, role).await
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
self.repo.delete(id).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct UserEntity {
|
||||
pub id: Uuid,
|
||||
pub email: String,
|
||||
pub name: String,
|
||||
pub role: String,
|
||||
pub provider: String,
|
||||
pub created_at: Option<DateTime<Utc>>,
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
pub struct UpdateUserInput {
|
||||
pub name: Option<String>,
|
||||
pub email: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod entity;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
@@ -0,0 +1,22 @@
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::errors::AppError;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::entity::{UpdateUserInput, UserEntity};
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserRepository: Send + Sync {
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<Option<UserEntity>, AppError>;
|
||||
async fn find_all(&self) -> Result<Vec<UserEntity>, AppError>;
|
||||
async fn update(
|
||||
&self,
|
||||
id: Uuid,
|
||||
input: UpdateUserInput,
|
||||
) -> Result<UserEntity, AppError>;
|
||||
async fn update_role(
|
||||
&self,
|
||||
id: Uuid,
|
||||
role: String,
|
||||
) -> Result<UserEntity, AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::errors::AppError;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::entity::{UpdateUserInput, UserEntity};
|
||||
|
||||
#[async_trait]
|
||||
pub trait QrUserService: Send + Sync {
|
||||
async fn get_profile(&self, user_id: Uuid) -> Result<UserEntity, AppError>;
|
||||
async fn update_profile(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
input: UpdateUserInput,
|
||||
) -> Result<UserEntity, AppError>;
|
||||
async fn list_all(&self) -> Result<Vec<UserEntity>, AppError>;
|
||||
async fn update_role(
|
||||
&self,
|
||||
id: Uuid,
|
||||
role: String,
|
||||
) -> Result<UserEntity, AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct UpdateProfileRequest {
|
||||
pub name: Option<String>,
|
||||
pub email: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct UpdateRoleRequest {
|
||||
pub role: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct UserResponse {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
pub name: String,
|
||||
pub role: String,
|
||||
pub provider: String,
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::Path,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use imphnen_utils::{errors::AppError, response_format::ApiSuccess};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::qr::{
|
||||
middleware::qr_auth::QrAuthUser,
|
||||
users::{
|
||||
domain::{entity::UpdateUserInput, service::QrUserService},
|
||||
infrastructure::http::dto::{UpdateProfileRequest, UpdateRoleRequest},
|
||||
},
|
||||
};
|
||||
|
||||
pub async fn get_me_handler(
|
||||
Extension(service): Extension<Arc<dyn QrUserService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
) -> Result<Response, AppError> {
|
||||
let user = service.get_profile(auth_user.user_id).await?;
|
||||
Ok(ApiSuccess(user).into_response())
|
||||
}
|
||||
|
||||
pub async fn update_me_handler(
|
||||
Extension(service): Extension<Arc<dyn QrUserService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
Json(body): Json<UpdateProfileRequest>,
|
||||
) -> Result<Response, AppError> {
|
||||
let input = UpdateUserInput {
|
||||
name: body.name,
|
||||
email: body.email,
|
||||
};
|
||||
let user = service.update_profile(auth_user.user_id, input).await?;
|
||||
Ok(ApiSuccess(user).into_response())
|
||||
}
|
||||
|
||||
pub async fn list_users_handler(
|
||||
Extension(service): Extension<Arc<dyn QrUserService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
) -> Result<Response, AppError> {
|
||||
if auth_user.role != "admin" {
|
||||
return Err(AppError::ForbiddenError(
|
||||
"Admin access required".to_string(),
|
||||
));
|
||||
}
|
||||
let users = service.list_all().await?;
|
||||
Ok(ApiSuccess(users).into_response())
|
||||
}
|
||||
|
||||
pub async fn update_role_handler(
|
||||
Extension(service): Extension<Arc<dyn QrUserService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<UpdateRoleRequest>,
|
||||
) -> Result<Response, AppError> {
|
||||
if auth_user.role != "admin" {
|
||||
return Err(AppError::ForbiddenError(
|
||||
"Admin access required".to_string(),
|
||||
));
|
||||
}
|
||||
let user = service.update_role(id, body.role).await?;
|
||||
Ok(ApiSuccess(user).into_response())
|
||||
}
|
||||
|
||||
pub async fn delete_user_handler(
|
||||
Extension(service): Extension<Arc<dyn QrUserService>>,
|
||||
Extension(auth_user): Extension<QrAuthUser>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Response, AppError> {
|
||||
if auth_user.role != "admin" {
|
||||
return Err(AppError::ForbiddenError(
|
||||
"Admin access required".to_string(),
|
||||
));
|
||||
}
|
||||
service.delete(id).await?;
|
||||
Ok(
|
||||
imphnen_utils::response_format::ApiMessage::ok("User deleted successfully")
|
||||
.into_response(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod dto;
|
||||
pub mod handlers;
|
||||
pub mod routes;
|
||||
@@ -0,0 +1,37 @@
|
||||
use axum::{
|
||||
Extension, Router,
|
||||
middleware::from_fn,
|
||||
routing::{delete, get, put},
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::qr::{
|
||||
middleware::qr_auth::qr_auth_middleware,
|
||||
users::{
|
||||
application::user_service::QrUserServiceImpl,
|
||||
domain::{repository::UserRepository, service::QrUserService},
|
||||
infrastructure::{
|
||||
http::handlers::{
|
||||
delete_user_handler, get_me_handler, list_users_handler, update_me_handler,
|
||||
update_role_handler,
|
||||
},
|
||||
persistence::postgres_user_repository::PostgresUserRepository,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
pub fn qr_users_routes(pool: Arc<PgPool>) -> Router {
|
||||
let repo: Arc<dyn UserRepository> =
|
||||
Arc::new(PostgresUserRepository::new(pool.clone()));
|
||||
let service: Arc<dyn QrUserService> = Arc::new(QrUserServiceImpl::new(repo));
|
||||
|
||||
Router::new()
|
||||
.route("/users/me", get(get_me_handler).put(update_me_handler))
|
||||
.route("/users", get(list_users_handler))
|
||||
.route("/users/:id/role", put(update_role_handler))
|
||||
.route("/users/:id", delete(delete_user_handler))
|
||||
.layer(Extension(service))
|
||||
.layer(Extension(pool))
|
||||
.layer(from_fn(qr_auth_middleware))
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod http;
|
||||
pub mod persistence;
|
||||
@@ -0,0 +1 @@
|
||||
pub mod postgres_user_repository;
|
||||
@@ -0,0 +1,112 @@
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::errors::AppError;
|
||||
use sqlx::FromRow;
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::qr::users::domain::{
|
||||
entity::{UpdateUserInput, UserEntity},
|
||||
repository::UserRepository,
|
||||
};
|
||||
|
||||
#[derive(FromRow)]
|
||||
struct UserRow {
|
||||
pub id: Uuid,
|
||||
pub email: String,
|
||||
pub name: String,
|
||||
pub role: String,
|
||||
pub provider: String,
|
||||
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
impl From<UserRow> for UserEntity {
|
||||
fn from(row: UserRow) -> Self {
|
||||
UserEntity {
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
name: row.name,
|
||||
role: row.role,
|
||||
provider: row.provider,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PostgresUserRepository {
|
||||
pool: Arc<PgPool>,
|
||||
}
|
||||
|
||||
impl PostgresUserRepository {
|
||||
pub fn new(pool: Arc<PgPool>) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UserRepository for PostgresUserRepository {
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<Option<UserEntity>, AppError> {
|
||||
sqlx::query_as::<_, UserRow>(
|
||||
"SELECT id, email, name, role, provider, created_at, updated_at FROM qr_users WHERE id = $1",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))
|
||||
.map(|opt| opt.map(Into::into))
|
||||
}
|
||||
|
||||
async fn find_all(&self) -> Result<Vec<UserEntity>, AppError> {
|
||||
sqlx::query_as::<_, UserRow>(
|
||||
"SELECT id, email, name, role, provider, created_at, updated_at FROM qr_users ORDER BY created_at DESC",
|
||||
)
|
||||
.fetch_all(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))
|
||||
.map(|rows| rows.into_iter().map(Into::into).collect())
|
||||
}
|
||||
|
||||
async fn update(
|
||||
&self,
|
||||
id: Uuid,
|
||||
input: UpdateUserInput,
|
||||
) -> Result<UserEntity, AppError> {
|
||||
sqlx::query_as::<_, UserRow>(
|
||||
"UPDATE qr_users SET name = COALESCE($1, name), email = COALESCE($2, email), updated_at = NOW() WHERE id = $3 RETURNING id, email, name, role, provider, created_at, updated_at",
|
||||
)
|
||||
.bind(input.name)
|
||||
.bind(input.email)
|
||||
.bind(id)
|
||||
.fetch_one(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
async fn update_role(
|
||||
&self,
|
||||
id: Uuid,
|
||||
role: String,
|
||||
) -> Result<UserEntity, AppError> {
|
||||
sqlx::query_as::<_, UserRow>(
|
||||
"UPDATE qr_users SET role = $1, updated_at = NOW() WHERE id = $2 RETURNING id, email, name, role, provider, created_at, updated_at",
|
||||
)
|
||||
.bind(role)
|
||||
.bind(id)
|
||||
.fetch_one(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
sqlx::query("DELETE FROM qr_users WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod application;
|
||||
pub mod domain;
|
||||
pub mod infrastructure;
|
||||
pub use infrastructure::http::routes::qr_users_routes;
|
||||
@@ -1,40 +1,48 @@
|
||||
use std::sync::Arc;
|
||||
use crate::testimonials::domain::{
|
||||
TestimonialEntity, TestimonialRepository, TestimonialService,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::AppError;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use crate::testimonials::domain::{TestimonialEntity, TestimonialRepository, TestimonialService};
|
||||
|
||||
pub struct TestimonialServiceImpl {
|
||||
repo: Arc<dyn TestimonialRepository>,
|
||||
repo: Arc<dyn TestimonialRepository>,
|
||||
}
|
||||
|
||||
impl TestimonialServiceImpl {
|
||||
pub fn new(repo: Arc<dyn TestimonialRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
pub fn new(repo: Arc<dyn TestimonialRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TestimonialService for TestimonialServiceImpl {
|
||||
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<TestimonialEntity>, AppError> {
|
||||
self.repo.find_all(params).await
|
||||
}
|
||||
async fn list(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<TestimonialEntity>, AppError> {
|
||||
self.repo.find_all(params).await
|
||||
}
|
||||
|
||||
async fn get(&self, id: Uuid) -> Result<TestimonialEntity, AppError> {
|
||||
self.repo.find_by_id(id).await
|
||||
}
|
||||
async fn get(&self, id: Uuid) -> Result<TestimonialEntity, AppError> {
|
||||
self.repo.find_by_id(id).await
|
||||
}
|
||||
|
||||
async fn create(&self, entity: TestimonialEntity) -> Result<TestimonialEntity, AppError> {
|
||||
self.repo.create(entity).await
|
||||
}
|
||||
async fn create(
|
||||
&self,
|
||||
entity: TestimonialEntity,
|
||||
) -> Result<TestimonialEntity, AppError> {
|
||||
self.repo.create(entity).await
|
||||
}
|
||||
|
||||
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError> {
|
||||
self.repo.update(entity).await
|
||||
}
|
||||
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError> {
|
||||
self.repo.update(entity).await
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
self.repo.delete(id).await
|
||||
}
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
self.repo.delete(id).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
pub mod testimonial;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
pub mod testimonial;
|
||||
|
||||
pub use testimonial::TestimonialEntity;
|
||||
pub use repository::TestimonialRepository;
|
||||
pub use service::TestimonialService;
|
||||
pub use testimonial::TestimonialEntity;
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
use super::testimonial::TestimonialEntity;
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::AppError;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use super::testimonial::TestimonialEntity;
|
||||
|
||||
#[async_trait]
|
||||
pub trait TestimonialRepository: Send + Sync {
|
||||
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<TestimonialEntity>, AppError>;
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<TestimonialEntity, AppError>;
|
||||
async fn create(&self, entity: TestimonialEntity) -> Result<TestimonialEntity, AppError>;
|
||||
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
async fn find_all(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<TestimonialEntity>, AppError>;
|
||||
async fn find_by_id(&self, id: Uuid) -> Result<TestimonialEntity, AppError>;
|
||||
async fn create(
|
||||
&self,
|
||||
entity: TestimonialEntity,
|
||||
) -> Result<TestimonialEntity, AppError>;
|
||||
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
use super::testimonial::TestimonialEntity;
|
||||
use async_trait::async_trait;
|
||||
use imphnen_utils::AppError;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use super::testimonial::TestimonialEntity;
|
||||
|
||||
#[async_trait]
|
||||
pub trait TestimonialService: Send + Sync {
|
||||
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<TestimonialEntity>, AppError>;
|
||||
async fn get(&self, id: Uuid) -> Result<TestimonialEntity, AppError>;
|
||||
async fn create(&self, entity: TestimonialEntity) -> Result<TestimonialEntity, AppError>;
|
||||
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
async fn list(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<TestimonialEntity>, AppError>;
|
||||
async fn get(&self, id: Uuid) -> Result<TestimonialEntity, AppError>;
|
||||
async fn create(
|
||||
&self,
|
||||
entity: TestimonialEntity,
|
||||
) -> Result<TestimonialEntity, AppError>;
|
||||
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError>;
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@ use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TestimonialEntity {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub user_fullname: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,4 +2,6 @@ pub mod application;
|
||||
pub mod domain;
|
||||
pub mod infrastructure;
|
||||
|
||||
pub use infrastructure::http::{testimonials_public_routes, testimonials_protected_routes};
|
||||
pub use infrastructure::http::{
|
||||
testimonials_protected_routes, testimonials_public_routes,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user