refactor: migrate to clean architecture with trait-based DI (v0.2.0)
Complete architectural overhaul across all 12 crates: - Replace validator crate with zod-rs for all DTO validation - Replace manual pagination with paginator-rs/paginator-sea-orm - Migrate all modules (iam, cms, gacha, dimentorin) to clean architecture: domain → application → infrastructure layers - Introduce trait-based DI (Arc<dyn Trait>) at every layer for repositories and services - Delete all v1/ legacy SurrealDB-era code across every crate - Replace opaque response helpers with typed IntoResponse structs (ApiSuccess, ApiCreated, ApiPaginated, ApiMessage) - Remove dual_mode_repository, migration_validation_errors, validator.rs dead code - Zero cargo clippy warnings; release build clean Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
1b3366d735
commit
e432a1a743
@@ -0,0 +1,411 @@
|
||||
use std::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_libs::{AppState, hash_password};
|
||||
use imphnen_entities::{RolesDetailQueryDto, users::UserProfileExtensionDto};
|
||||
use imphnen_iam::users::domain::{UserRepository, UserEntity};
|
||||
use imphnen_iam::roles::domain::RoleRepository;
|
||||
use tracing::error;
|
||||
use crate::mentors::domain::{MentorEntity, MentorRepository, MentorService};
|
||||
use crate::mentors::infrastructure::http::dto::{
|
||||
MentorDetailResponseDto, MentorListResponseDto, MentorRegisterResponseDto,
|
||||
MentorUpdateRequestDto, MentorUserRegisterRequestDto, MentorVerifyRequestDto,
|
||||
};
|
||||
|
||||
pub struct MentorServiceImpl {
|
||||
repo: Arc<dyn MentorRepository>,
|
||||
state: Arc<AppState>,
|
||||
user_repo: Arc<dyn UserRepository>,
|
||||
role_repo: Arc<dyn RoleRepository>,
|
||||
}
|
||||
|
||||
impl MentorServiceImpl {
|
||||
pub fn new(
|
||||
repo: Arc<dyn MentorRepository>,
|
||||
state: Arc<AppState>,
|
||||
user_repo: Arc<dyn UserRepository>,
|
||||
role_repo: Arc<dyn RoleRepository>,
|
||||
) -> Self {
|
||||
Self { repo, state, user_repo, role_repo }
|
||||
}
|
||||
|
||||
fn build_detail_response(
|
||||
entity: &MentorEntity,
|
||||
user: Option<&imphnen_entities::UsersDetailQueryDto>,
|
||||
) -> MentorDetailResponseDto {
|
||||
MentorDetailResponseDto {
|
||||
id: entity.id.to_string(),
|
||||
user_id: entity.user_id.to_string(),
|
||||
fullname: user.map(|u| u.fullname.clone()),
|
||||
email: user.map(|u| u.email.clone()),
|
||||
legal_name: user.and_then(|u| u.legal_name.clone()),
|
||||
gender: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.gender.clone()),
|
||||
domicile: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.domicile.clone()),
|
||||
phone_for_verification: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.phone_for_verification.clone()),
|
||||
bio: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.bio.clone()),
|
||||
last_education: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.last_education.clone()),
|
||||
linkedin_url: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.linkedin_url.clone()),
|
||||
github_url: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.github_url.clone()),
|
||||
cv_url: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.cv_url.clone()),
|
||||
portfolio_url: user
|
||||
.and_then(|u| u.profile_extension.as_ref())
|
||||
.and_then(|ext| ext.portfolio_url.clone()),
|
||||
industries: entity.industries.clone(),
|
||||
expertise: entity.expertise.clone(),
|
||||
languages: entity.languages.clone(),
|
||||
current_company: entity.current_company.clone(),
|
||||
current_role: entity.current_role.clone(),
|
||||
years_of_experience: entity.years_of_experience,
|
||||
topics_of_interest: entity.topics_of_interest.clone(),
|
||||
preferred_mentee_level: entity.preferred_mentee_level.clone(),
|
||||
preferred_mentoring_formats: entity.preferred_mentoring_formats.clone(),
|
||||
availability_commitment: entity.availability_commitment.clone(),
|
||||
mentoring_rate: entity.mentoring_rate,
|
||||
status: entity.status.clone(),
|
||||
created_at: entity.created_at.to_rfc3339(),
|
||||
updated_at: entity.updated_at.to_rfc3339(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MentorService for MentorServiceImpl {
|
||||
async fn list(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<MentorListResponseDto>, AppError> {
|
||||
let result = self.repo.find_all(params).await?;
|
||||
|
||||
let mut items: Vec<MentorListResponseDto> = Vec::with_capacity(result.data.len());
|
||||
for entity in &result.data {
|
||||
let mut item = MentorListResponseDto {
|
||||
id: entity.id.to_string(),
|
||||
user_id: entity.user_id.to_string(),
|
||||
fullname: None,
|
||||
email: None,
|
||||
status: entity.status.clone(),
|
||||
created_at: entity.created_at.to_rfc3339(),
|
||||
updated_at: entity.updated_at.to_rfc3339(),
|
||||
};
|
||||
if let Ok(info) = self.state.user_lookup_service
|
||||
.get_user_by_id(entity.user_id, self.state.as_ref())
|
||||
.await
|
||||
{
|
||||
item.fullname = Some(info.basic_info.fullname);
|
||||
item.email = Some(info.basic_info.email);
|
||||
}
|
||||
items.push(item);
|
||||
}
|
||||
|
||||
Ok(PaginatorResponse { data: items, meta: result.meta })
|
||||
}
|
||||
|
||||
async fn get_by_id(&self, id: Uuid) -> Result<MentorDetailResponseDto, AppError> {
|
||||
let entity = self.repo.find_by_id(id, false).await?;
|
||||
let user = self.state.user_lookup_service
|
||||
.get_user_by_id(entity.user_id, self.state.as_ref())
|
||||
.await
|
||||
.ok()
|
||||
.map(|i| i.basic_info);
|
||||
Ok(Self::build_detail_response(&entity, user.as_ref()))
|
||||
}
|
||||
|
||||
async fn get_by_email(&self, email: &str) -> Result<MentorDetailResponseDto, AppError> {
|
||||
let user_dto = self.state.user_lookup_service
|
||||
.get_user_by_email(email, self.state.as_ref())
|
||||
.await
|
||||
.map(|i| i.basic_info)
|
||||
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
|
||||
|
||||
let user_id = Uuid::parse_str(&user_dto.id)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let entity = self.repo.find_by_user_id(user_id, false).await?;
|
||||
Ok(Self::build_detail_response(&entity, Some(&user_dto)))
|
||||
}
|
||||
|
||||
async fn register(
|
||||
&self,
|
||||
dto: MentorUserRegisterRequestDto,
|
||||
) -> Result<MentorRegisterResponseDto, AppError> {
|
||||
let user_email = dto.email.clone();
|
||||
|
||||
let user_id: Uuid = match self.user_repo.find_by_email(user_email.clone()).await {
|
||||
Ok(mut entity) => {
|
||||
let existing_user_id = Uuid::parse_str(&entity.id)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
if self.repo.find_by_user_id(existing_user_id, false).await.is_ok() {
|
||||
return Err(AppError::ConflictError(
|
||||
"Mentor profile already exists for this user".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let mentor_role = self.role_repo
|
||||
.find_by_name("Mentor".to_string())
|
||||
.await
|
||||
.map_err(|_| AppError::BadRequestError("Mentor Role Not Found".to_string()))?;
|
||||
|
||||
entity.fullname = dto.fullname.clone();
|
||||
entity.is_active = false;
|
||||
entity.role = RolesDetailQueryDto {
|
||||
id: mentor_role.id.to_string(),
|
||||
name: mentor_role.name.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
entity.password = hash_password(&dto.password).map_err(|e| {
|
||||
error!("Failed to hash password for {}: {}", user_email, e);
|
||||
AppError::InternalServerError("Failed to hash password".to_string())
|
||||
})?;
|
||||
|
||||
let mut profile_ext = entity.profile_extension.clone().unwrap_or_default();
|
||||
profile_ext.phone_number = dto.phone_number.clone();
|
||||
profile_ext.phone_for_verification = dto.identity_and_verification.phone_for_verification.clone();
|
||||
profile_ext.gender = dto.identity_and_verification.gender.clone();
|
||||
profile_ext.domicile = dto.identity_and_verification.domicile.clone();
|
||||
profile_ext.bio = Some(dto.professional_profile.bio.clone());
|
||||
profile_ext.last_education = dto.professional_profile.last_education.clone();
|
||||
profile_ext.linkedin_url = dto.professional_profile.linkedin_url.clone();
|
||||
profile_ext.github_url = dto.professional_profile.github_url.clone();
|
||||
profile_ext.cv_url = dto.professional_profile.cv_url.clone();
|
||||
profile_ext.portfolio_url = dto.professional_profile.portfolio_url.clone();
|
||||
entity.profile_extension = Some(profile_ext);
|
||||
|
||||
let uid_str = entity.id.clone();
|
||||
self.user_repo.update(entity).await.map_err(|e| {
|
||||
error!("Failed to update user {} to mentor role: {}", user_email, e);
|
||||
AppError::InternalServerError(e.to_string())
|
||||
})?;
|
||||
|
||||
Uuid::parse_str(&uid_str)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
}
|
||||
Err(_) => {
|
||||
let mentor_role = self.role_repo
|
||||
.find_by_name("Mentor".to_string())
|
||||
.await
|
||||
.map_err(|_| AppError::BadRequestError("Mentor Role Not Found".to_string()))?;
|
||||
|
||||
let hashed_password = hash_password(&dto.password).map_err(|e| {
|
||||
error!("Failed to hash password for new user {}: {}", user_email, e);
|
||||
AppError::InternalServerError("Failed to hash password".to_string())
|
||||
})?;
|
||||
|
||||
let new_user_id = Uuid::new_v4();
|
||||
let profile_ext = UserProfileExtensionDto {
|
||||
phone_number: dto.phone_number.clone(),
|
||||
phone_for_verification: dto.identity_and_verification.phone_for_verification.clone(),
|
||||
gender: dto.identity_and_verification.gender.clone(),
|
||||
domicile: dto.identity_and_verification.domicile.clone(),
|
||||
bio: Some(dto.professional_profile.bio.clone()),
|
||||
last_education: dto.professional_profile.last_education.clone(),
|
||||
linkedin_url: dto.professional_profile.linkedin_url.clone(),
|
||||
github_url: dto.professional_profile.github_url.clone(),
|
||||
cv_url: dto.professional_profile.cv_url.clone(),
|
||||
portfolio_url: dto.professional_profile.portfolio_url.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let new_entity = UserEntity {
|
||||
id: new_user_id.to_string(),
|
||||
email: dto.email.clone(),
|
||||
fullname: dto.fullname.clone(),
|
||||
legal_name: Some(dto.identity_and_verification.legal_name.clone()),
|
||||
password: hashed_password,
|
||||
is_active: false,
|
||||
role: RolesDetailQueryDto {
|
||||
id: mentor_role.id.to_string(),
|
||||
name: mentor_role.name.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
profile_extension: Some(profile_ext),
|
||||
created_at: imphnen_utils::get_iso_date(),
|
||||
updated_at: imphnen_utils::get_iso_date(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
self.user_repo.create(new_entity).await.map_err(|e| {
|
||||
error!("Failed to create new user {}: {}", user_email, e);
|
||||
AppError::InternalServerError(e.to_string())
|
||||
})?;
|
||||
|
||||
new_user_id
|
||||
}
|
||||
};
|
||||
|
||||
let new_entity = MentorEntity {
|
||||
id: Uuid::new_v4(),
|
||||
user_id,
|
||||
industries: dto.professional_profile.industries.clone(),
|
||||
expertise: dto.professional_profile.expertise.clone(),
|
||||
languages: dto.professional_profile.languages.clone(),
|
||||
current_company: dto.professional_profile.current_company.clone(),
|
||||
current_role: dto.professional_profile.current_role.clone(),
|
||||
years_of_experience: dto.professional_profile.years_of_experience,
|
||||
topics_of_interest: dto.mentoring_logistics.topics_of_interest.clone(),
|
||||
preferred_mentee_level: dto.mentoring_logistics.preferred_mentee_level.clone(),
|
||||
preferred_mentoring_formats: dto.mentoring_logistics.preferred_mentoring_formats.clone(),
|
||||
availability_commitment: dto.mentoring_logistics.availability_commitment.clone(),
|
||||
mentoring_rate: dto.mentoring_logistics.mentoring_rate_amount as f64,
|
||||
status: "pending".to_string(),
|
||||
is_deleted: false,
|
||||
created_at: chrono::Utc::now(),
|
||||
updated_at: chrono::Utc::now(),
|
||||
};
|
||||
|
||||
let mentor_id = self.repo.create(new_entity.clone()).await.map_err(|e| {
|
||||
error!("Failed to create mentor profile for {}: {}", user_email, e);
|
||||
e
|
||||
})?;
|
||||
|
||||
Ok(MentorRegisterResponseDto {
|
||||
id: mentor_id.to_string(),
|
||||
user_id: user_id.to_string(),
|
||||
email: Some(user_email),
|
||||
status: "pending".to_string(),
|
||||
created_at: new_entity.created_at.to_rfc3339(),
|
||||
updated_at: new_entity.updated_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn update(
|
||||
&self,
|
||||
id: Uuid,
|
||||
dto: MentorUpdateRequestDto,
|
||||
) -> Result<MentorDetailResponseDto, AppError> {
|
||||
let mut entity = self.repo.find_by_id(id, false).await?;
|
||||
|
||||
if let Some(val) = dto.industries { entity.industries = val; }
|
||||
if let Some(val) = dto.expertise { entity.expertise = val; }
|
||||
if let Some(val) = dto.languages { entity.languages = val; }
|
||||
if let Some(val) = dto.current_company { entity.current_company = val; }
|
||||
if let Some(val) = dto.current_role { entity.current_role = val; }
|
||||
if let Some(val) = dto.years_of_experience { entity.years_of_experience = val; }
|
||||
if let Some(val) = dto.topics_of_interest { entity.topics_of_interest = val; }
|
||||
if let Some(val) = dto.preferred_mentee_level { entity.preferred_mentee_level = val; }
|
||||
if let Some(val) = dto.preferred_mentoring_formats { entity.preferred_mentoring_formats = val; }
|
||||
if let Some(val) = dto.availability_commitment { entity.availability_commitment = val; }
|
||||
if let Some(val) = dto.mentoring_rate_amount { entity.mentoring_rate = val as f64; }
|
||||
entity.updated_at = chrono::Utc::now();
|
||||
|
||||
self.repo.update(entity).await?;
|
||||
|
||||
let updated = self.repo.find_by_id(id, false).await?;
|
||||
let user = self.state.user_lookup_service
|
||||
.get_user_by_id(updated.user_id, self.state.as_ref())
|
||||
.await
|
||||
.ok()
|
||||
.map(|i| i.basic_info);
|
||||
Ok(Self::build_detail_response(&updated, user.as_ref()))
|
||||
}
|
||||
|
||||
async fn update_me(
|
||||
&self,
|
||||
email: &str,
|
||||
dto: MentorUpdateRequestDto,
|
||||
) -> Result<MentorDetailResponseDto, AppError> {
|
||||
let user_dto = self.state.user_lookup_service
|
||||
.get_user_by_email(email, self.state.as_ref())
|
||||
.await
|
||||
.map(|i| i.basic_info)
|
||||
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
|
||||
|
||||
let user_id = Uuid::parse_str(&user_dto.id)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let mut entity = self.repo.find_by_user_id(user_id, false).await?;
|
||||
|
||||
if let Some(val) = dto.industries { entity.industries = val; }
|
||||
if let Some(val) = dto.expertise { entity.expertise = val; }
|
||||
if let Some(val) = dto.languages { entity.languages = val; }
|
||||
if let Some(val) = dto.current_company { entity.current_company = val; }
|
||||
if let Some(val) = dto.current_role { entity.current_role = val; }
|
||||
if let Some(val) = dto.years_of_experience { entity.years_of_experience = val; }
|
||||
if let Some(val) = dto.topics_of_interest { entity.topics_of_interest = val; }
|
||||
if let Some(val) = dto.preferred_mentee_level { entity.preferred_mentee_level = val; }
|
||||
if let Some(val) = dto.preferred_mentoring_formats { entity.preferred_mentoring_formats = val; }
|
||||
if let Some(val) = dto.availability_commitment { entity.availability_commitment = val; }
|
||||
if let Some(val) = dto.mentoring_rate_amount { entity.mentoring_rate = val as f64; }
|
||||
entity.updated_at = chrono::Utc::now();
|
||||
|
||||
let entity_id = entity.id;
|
||||
self.repo.update(entity).await?;
|
||||
|
||||
let updated = self.repo.find_by_id(entity_id, false).await?;
|
||||
let refreshed_user = self.state.user_lookup_service
|
||||
.get_user_by_id(updated.user_id, self.state.as_ref())
|
||||
.await
|
||||
.ok()
|
||||
.map(|i| i.basic_info);
|
||||
Ok(Self::build_detail_response(&updated, refreshed_user.as_ref()))
|
||||
}
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
self.repo.soft_delete(id).await
|
||||
}
|
||||
|
||||
async fn verify(
|
||||
&self,
|
||||
id: Uuid,
|
||||
dto: MentorVerifyRequestDto,
|
||||
) -> Result<MentorDetailResponseDto, AppError> {
|
||||
let mut entity = self.repo.find_by_id(id, false).await?;
|
||||
entity.status = dto.status;
|
||||
entity.updated_at = chrono::Utc::now();
|
||||
|
||||
self.repo.update(entity).await?;
|
||||
|
||||
let updated = self.repo.find_by_id(id, false).await?;
|
||||
let user = self.state.user_lookup_service
|
||||
.get_user_by_id(updated.user_id, self.state.as_ref())
|
||||
.await
|
||||
.ok()
|
||||
.map(|i| i.basic_info);
|
||||
Ok(Self::build_detail_response(&updated, user.as_ref()))
|
||||
}
|
||||
|
||||
async fn get_status(&self, email: &str) -> Result<String, AppError> {
|
||||
let user_dto = self.state.user_lookup_service
|
||||
.get_user_by_email(email, self.state.as_ref())
|
||||
.await
|
||||
.map(|i| i.basic_info)
|
||||
.map_err(|_| {
|
||||
AppError::NotFoundError("No mentor application found for current user".to_string())
|
||||
})?;
|
||||
|
||||
let user_id = Uuid::parse_str(&user_dto.id)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let entity = self.repo.find_by_user_id(user_id, false).await.map_err(|_| {
|
||||
AppError::NotFoundError("No mentor application found for current user".to_string())
|
||||
})?;
|
||||
|
||||
Ok(entity.status)
|
||||
}
|
||||
|
||||
async fn get_entity_by_id(
|
||||
&self,
|
||||
id: Uuid,
|
||||
include_deleted: bool,
|
||||
) -> Result<MentorEntity, AppError> {
|
||||
self.repo.find_by_id(id, include_deleted).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod mentor_service;
|
||||
|
||||
pub use mentor_service::MentorServiceImpl;
|
||||
@@ -0,0 +1,22 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MentorEntity {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub industries: Vec<String>,
|
||||
pub expertise: Vec<String>,
|
||||
pub languages: Vec<String>,
|
||||
pub current_company: String,
|
||||
pub current_role: String,
|
||||
pub years_of_experience: i32,
|
||||
pub topics_of_interest: Vec<String>,
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
pub availability_commitment: String,
|
||||
pub mentoring_rate: f64,
|
||||
pub status: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod mentor;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
|
||||
pub use mentor::MentorEntity;
|
||||
pub use repository::MentorRepository;
|
||||
pub use service::MentorService;
|
||||
@@ -0,0 +1,33 @@
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use super::mentor::MentorEntity;
|
||||
|
||||
|
||||
#[async_trait]
|
||||
pub trait MentorRepository: Send + Sync {
|
||||
async fn find_all(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<MentorEntity>, AppError>;
|
||||
|
||||
async fn find_by_id(
|
||||
&self,
|
||||
id: Uuid,
|
||||
include_deleted: bool,
|
||||
) -> Result<MentorEntity, AppError>;
|
||||
|
||||
async fn find_by_user_id(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
include_deleted: bool,
|
||||
) -> Result<MentorEntity, AppError>;
|
||||
|
||||
async fn create(&self, entity: MentorEntity) -> Result<Uuid, AppError>;
|
||||
|
||||
async fn update(&self, entity: MentorEntity) -> Result<(), AppError>;
|
||||
|
||||
async fn soft_delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use super::mentor::MentorEntity;
|
||||
use crate::mentors::infrastructure::http::dto::{
|
||||
MentorDetailResponseDto, MentorListResponseDto, MentorRegisterResponseDto,
|
||||
MentorUpdateRequestDto, MentorUserRegisterRequestDto, MentorVerifyRequestDto,
|
||||
};
|
||||
|
||||
#[async_trait]
|
||||
pub trait MentorService: Send + Sync {
|
||||
async fn list(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<MentorListResponseDto>, AppError>;
|
||||
|
||||
async fn get_by_id(&self, id: Uuid) -> Result<MentorDetailResponseDto, AppError>;
|
||||
|
||||
async fn get_by_email(&self, email: &str) -> Result<MentorDetailResponseDto, AppError>;
|
||||
|
||||
async fn register(
|
||||
&self,
|
||||
dto: MentorUserRegisterRequestDto,
|
||||
) -> Result<MentorRegisterResponseDto, AppError>;
|
||||
|
||||
async fn update(
|
||||
&self,
|
||||
id: Uuid,
|
||||
dto: MentorUpdateRequestDto,
|
||||
) -> Result<MentorDetailResponseDto, AppError>;
|
||||
|
||||
async fn update_me(
|
||||
&self,
|
||||
email: &str,
|
||||
dto: MentorUpdateRequestDto,
|
||||
) -> Result<MentorDetailResponseDto, AppError>;
|
||||
|
||||
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
|
||||
|
||||
async fn verify(
|
||||
&self,
|
||||
id: Uuid,
|
||||
dto: MentorVerifyRequestDto,
|
||||
) -> Result<MentorDetailResponseDto, AppError>;
|
||||
|
||||
async fn get_status(&self, email: &str) -> Result<String, AppError>;
|
||||
|
||||
async fn get_entity_by_id(
|
||||
&self,
|
||||
id: Uuid,
|
||||
include_deleted: bool,
|
||||
) -> Result<MentorEntity, AppError>;
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
use imphnen_libs::ZodValidate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use zod_rs::prelude::*;
|
||||
|
||||
// ============================================================
|
||||
// Response DTOs
|
||||
// ============================================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MentorListResponseDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub fullname: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub status: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MentorDetailResponseDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub fullname: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub legal_name: Option<String>,
|
||||
pub gender: Option<String>,
|
||||
pub domicile: Option<String>,
|
||||
pub phone_for_verification: Option<String>,
|
||||
pub bio: Option<String>,
|
||||
pub last_education: Option<String>,
|
||||
pub linkedin_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub cv_url: Option<String>,
|
||||
pub portfolio_url: Option<String>,
|
||||
pub industries: Vec<String>,
|
||||
pub expertise: Vec<String>,
|
||||
pub languages: Vec<String>,
|
||||
pub current_company: String,
|
||||
pub current_role: String,
|
||||
pub years_of_experience: i32,
|
||||
pub topics_of_interest: Vec<String>,
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
pub availability_commitment: String,
|
||||
pub mentoring_rate: f64,
|
||||
pub status: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MentorRegisterResponseDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub email: Option<String>,
|
||||
pub status: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Request DTOs
|
||||
// ============================================================
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
|
||||
pub struct MentorUserRegisterRequestDto {
|
||||
#[zod(email, min_length(1))]
|
||||
pub email: String,
|
||||
#[zod(min_length(8), regex(pattern = "^[A-Za-z\\d@$!%*?&]{8,}$"))]
|
||||
pub password: String,
|
||||
#[zod(min_length(2))]
|
||||
pub fullname: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_number: Option<String>,
|
||||
pub identity_and_verification: IdentityAndVerification,
|
||||
pub professional_profile: ProfessionalProfile,
|
||||
pub mentoring_logistics: MentoringLogistics,
|
||||
}
|
||||
|
||||
impl ZodValidate for MentorUserRegisterRequestDto {
|
||||
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 IdentityAndVerification {
|
||||
#[zod(min_length(3))]
|
||||
pub legal_name: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gender: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub domicile: Option<String>,
|
||||
#[zod(url)]
|
||||
pub identity_document_url: String,
|
||||
#[zod(min_length(10), max_length(15))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_for_verification: Option<String>,
|
||||
}
|
||||
|
||||
impl ZodValidate for IdentityAndVerification {
|
||||
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 ProfessionalProfile {
|
||||
#[zod(min_length(50))]
|
||||
pub bio: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub last_education: Option<String>,
|
||||
#[zod(url)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linkedin_url: Option<String>,
|
||||
#[zod(url)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub github_url: Option<String>,
|
||||
#[zod(url)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cv_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub portfolio_url: Option<String>,
|
||||
pub industries: Vec<String>,
|
||||
pub expertise: Vec<String>,
|
||||
pub languages: Vec<String>,
|
||||
#[zod(min_length(1))]
|
||||
pub current_company: String,
|
||||
#[zod(min_length(1))]
|
||||
pub current_role: String,
|
||||
#[zod(min(2.0), int)]
|
||||
pub years_of_experience: i32,
|
||||
}
|
||||
|
||||
impl ZodValidate for ProfessionalProfile {
|
||||
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 MentoringLogistics {
|
||||
pub topics_of_interest: Vec<String>,
|
||||
pub preferred_mentee_level: Vec<String>,
|
||||
pub preferred_mentoring_formats: Vec<String>,
|
||||
#[zod(min_length(5))]
|
||||
pub availability_commitment: String,
|
||||
#[zod(min(1.0))]
|
||||
pub mentoring_rate_amount: u64,
|
||||
}
|
||||
|
||||
impl ZodValidate for MentoringLogistics {
|
||||
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 MentorUpdateRequestDto {
|
||||
#[zod(min_length(3))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legal_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gender: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub domicile: Option<String>,
|
||||
#[zod(min_length(10), max_length(15))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_for_verification: Option<String>,
|
||||
#[zod(min_length(50))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bio: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub last_education: Option<String>,
|
||||
#[zod(url)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linkedin_url: Option<String>,
|
||||
#[zod(url)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub github_url: Option<String>,
|
||||
#[zod(url)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cv_url: Option<String>,
|
||||
#[zod(url)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub portfolio_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub industries: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub expertise: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub languages: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub current_company: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub current_role: Option<String>,
|
||||
#[zod(min(2.0), int)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub years_of_experience: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub topics_of_interest: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub preferred_mentee_level: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub preferred_mentoring_formats: Option<Vec<String>>,
|
||||
#[zod(min_length(5))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub availability_commitment: Option<String>,
|
||||
#[zod(min(1.0))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub mentoring_rate_amount: Option<u64>,
|
||||
}
|
||||
|
||||
impl ZodValidate for MentorUpdateRequestDto {
|
||||
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 MentorVerifyRequestDto {
|
||||
#[zod(min_length(1))]
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
impl ZodValidate for MentorVerifyRequestDto {
|
||||
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, Default)]
|
||||
pub struct MentoringRate {
|
||||
#[zod(min(1.0))]
|
||||
pub amount: u64,
|
||||
#[zod(min_length(1))]
|
||||
pub currency: String,
|
||||
#[zod(min_length(1))]
|
||||
pub per_duration: String,
|
||||
}
|
||||
|
||||
impl ZodValidate for MentoringRate {
|
||||
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 MentorRegisterFromTokenRequestDto {
|
||||
pub identity_and_verification: IdentityAndVerification,
|
||||
pub professional_profile: ProfessionalProfile,
|
||||
pub mentoring_logistics: MentoringLogistics,
|
||||
}
|
||||
|
||||
impl ZodValidate for MentorRegisterFromTokenRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
Self::validate_and_parse(value).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
use std::sync::Arc;
|
||||
use axum::{
|
||||
extract::{Extension, Path},
|
||||
http::HeaderMap,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use paginator_axum::PaginationQuery;
|
||||
use uuid::Uuid;
|
||||
use imphnen_libs::{AppState, ValidatedJson};
|
||||
use imphnen_utils::{ApiSuccess, ApiPaginated, ApiMessage, extract_email};
|
||||
use imphnen_iam::{PermissionsEnum, require_permissions};
|
||||
use imphnen_utils::AppError;
|
||||
use crate::mentors::domain::MentorService;
|
||||
use super::dto::{
|
||||
MentorDetailResponseDto, MentorListResponseDto, MentorRegisterResponseDto,
|
||||
MentorUpdateRequestDto, MentorUserRegisterRequestDto, MentorVerifyRequestDto,
|
||||
};
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/mentors/create",
|
||||
request_body = MentorUserRegisterRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Mentor registered successfully", body = MentorRegisterResponseDto),
|
||||
(status = 400, description = "[PUBLIC] Bad request - validation error"),
|
||||
(status = 409, description = "[PUBLIC] Conflict - user already has mentor profile"),
|
||||
(status = 500, description = "[PUBLIC] Internal server error")
|
||||
),
|
||||
tag = "Mentors"
|
||||
)]
|
||||
pub async fn post_register_mentor(
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
ValidatedJson(dto): ValidatedJson<MentorUserRegisterRequestDto>,
|
||||
) -> Response {
|
||||
match service.register(dto).await {
|
||||
Ok(resp) => ApiSuccess(resp).into_response(),
|
||||
Err(e) => ApiMessage::new(e.status_code(), e.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors",
|
||||
params(
|
||||
("page" = Option<u64>, Query, description = "Page number"),
|
||||
("per_page" = Option<u64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search query"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Sort order (ASC/DESC)"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get list of mentors", body = Vec<MentorListResponseDto>),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(("Bearer" = []))
|
||||
)]
|
||||
pub async fn get_mentor_list(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
PaginationQuery(params): PaginationQuery,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::ReadListMentors], {
|
||||
let result = service.list(params).await?;
|
||||
Ok(ApiPaginated(result))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get mentor by ID", body = MentorDetailResponseDto),
|
||||
(status = 404, description = "[ADMIN] Mentor not found"),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(("Bearer" = []))
|
||||
)]
|
||||
pub async fn get_mentor_by_id(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let mentor_uuid = Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid mentor ID format. Must be a valid UUID.".to_string()))?;
|
||||
require_permissions!(headers, state, [PermissionsEnum::ReadDetailMentors], {
|
||||
let dto = service.get_by_id(mentor_uuid).await?;
|
||||
Ok(ApiSuccess(dto))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/mentors/update/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID")
|
||||
),
|
||||
request_body = MentorUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Mentor updated successfully", body = MentorDetailResponseDto),
|
||||
(status = 400, description = "[ADMIN] Bad request - validation error"),
|
||||
(status = 404, description = "[ADMIN] Mentor not found"),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors - Admin",
|
||||
security(("Bearer" = []))
|
||||
)]
|
||||
pub async fn put_update_mentor(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(dto): ValidatedJson<MentorUpdateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let mentor_uuid = Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid mentor ID format. Must be a valid UUID.".to_string()))?;
|
||||
require_permissions!(headers, state, [PermissionsEnum::UpdateMentors], {
|
||||
let result = service.update(mentor_uuid, dto).await?;
|
||||
Ok(ApiSuccess(result))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/v1/mentors/delete/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Mentor deleted successfully"),
|
||||
(status = 404, description = "[ADMIN] Mentor not found"),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors - Admin",
|
||||
security(("Bearer" = []))
|
||||
)]
|
||||
pub async fn delete_mentor(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let mentor_uuid = Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid mentor ID format. Must be a valid UUID.".to_string()))?;
|
||||
require_permissions!(headers, state, [PermissionsEnum::DeleteMentors], {
|
||||
service.delete(mentor_uuid).await?;
|
||||
Ok(ApiMessage::ok("Mentor deleted successfully"))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/mentors/verify/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Mentor ID")
|
||||
),
|
||||
request_body = MentorVerifyRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Mentor verified successfully", body = MentorDetailResponseDto),
|
||||
(status = 400, description = "[ADMIN] Bad request - validation error"),
|
||||
(status = 404, description = "[ADMIN] Mentor not found"),
|
||||
(status = 500, description = "[ADMIN] Internal server error")
|
||||
),
|
||||
tag = "Mentors - Admin",
|
||||
security(("Bearer" = []))
|
||||
)]
|
||||
pub async fn put_verify_mentor(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
Path(id): Path<String>,
|
||||
ValidatedJson(dto): ValidatedJson<MentorVerifyRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let mentor_uuid = Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid mentor ID format. Must be a valid UUID.".to_string()))?;
|
||||
require_permissions!(headers, state, [PermissionsEnum::VerifyMentors], {
|
||||
let result = service.verify(mentor_uuid, dto).await?;
|
||||
Ok(ApiSuccess(result))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors/me",
|
||||
responses(
|
||||
(status = 200, description = "[MENTOR] Current user's mentor profile", body = MentorDetailResponseDto),
|
||||
(status = 401, description = "[MENTOR] Unauthorized - invalid token"),
|
||||
(status = 403, description = "[MENTOR] Mentor profile not found for current user"),
|
||||
(status = 500, description = "[MENTOR] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(("Bearer" = []))
|
||||
)]
|
||||
pub async fn get_mentor_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers.clone(), state, [PermissionsEnum::ReadOwnMentorProfile], {
|
||||
let email = extract_email(&headers)
|
||||
.ok_or_else(|| AppError::AuthenticationError("Token tidak valid".to_string()))?;
|
||||
let dto = service.get_by_email(&email).await
|
||||
.map_err(|_| AppError::ForbiddenError("Mentor profile not found for current user".to_string()))?;
|
||||
Ok(ApiSuccess(dto))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/mentors/me/update",
|
||||
request_body = MentorUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[MENTOR] Mentor profile updated successfully", body = MentorDetailResponseDto),
|
||||
(status = 400, description = "[MENTOR] Bad request - validation error"),
|
||||
(status = 401, description = "[MENTOR] Unauthorized - invalid token"),
|
||||
(status = 404, description = "[MENTOR] Mentor profile not found"),
|
||||
(status = 500, description = "[MENTOR] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(("Bearer" = []))
|
||||
)]
|
||||
pub async fn put_update_mentor_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
ValidatedJson(dto): ValidatedJson<MentorUpdateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers.clone(), state, [PermissionsEnum::UpdateOwnMentorProfile], {
|
||||
let email = extract_email(&headers)
|
||||
.ok_or_else(|| AppError::AuthenticationError("Token tidak valid".to_string()))?;
|
||||
let resp = service.update_me(&email, dto).await?;
|
||||
Ok(ApiSuccess(resp))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/mentors/update",
|
||||
request_body = MentorUpdateRequestDto,
|
||||
responses(
|
||||
(status = 400, description = "[PUBLIC] Bad request - Mentor ID is required for update"),
|
||||
),
|
||||
tag = "Mentors - Admin"
|
||||
)]
|
||||
pub async fn put_update_mentor_no_id() -> impl IntoResponse {
|
||||
ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, "Mentor ID is required for update")
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/mentors/me/status",
|
||||
responses(
|
||||
(status = 200, description = "[MENTOR] Mentor application status", body = String),
|
||||
(status = 401, description = "[MENTOR] Unauthorized - invalid token"),
|
||||
(status = 403, description = "[MENTOR] No mentor application found for current user"),
|
||||
(status = 500, description = "[MENTOR] Internal server error")
|
||||
),
|
||||
tag = "Mentors",
|
||||
security(("Bearer" = []))
|
||||
)]
|
||||
pub async fn get_mentor_status(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn MentorService>>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers.clone(), state, [PermissionsEnum::ReadOwnMentorStatus], {
|
||||
let email = extract_email(&headers)
|
||||
.ok_or_else(|| AppError::AuthenticationError("Token tidak valid".to_string()))?;
|
||||
let status = service.get_status(&email).await
|
||||
.map_err(|_| AppError::ForbiddenError("No mentor application found for current user".to_string()))?;
|
||||
Ok(ApiMessage::ok(&status))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod dto;
|
||||
pub mod handlers;
|
||||
pub mod routes;
|
||||
|
||||
pub use routes::{mentors_protected_routes, mentors_public_routes};
|
||||
@@ -0,0 +1,47 @@
|
||||
use std::sync::Arc;
|
||||
use axum::{
|
||||
routing::{delete, get, post, put},
|
||||
Extension, Router,
|
||||
};
|
||||
use sea_orm::DatabaseConnection;
|
||||
use imphnen_libs::AppState;
|
||||
use imphnen_iam::users::infrastructure::persistence::PostgresUserRepository;
|
||||
use imphnen_iam::roles::infrastructure::persistence::PostgresRoleRepository;
|
||||
use crate::mentors::application::MentorServiceImpl;
|
||||
use crate::mentors::domain::MentorService;
|
||||
use crate::mentors::infrastructure::persistence::PostgresMentorRepository;
|
||||
use super::handlers::{
|
||||
delete_mentor, get_mentor_by_id, get_mentor_list, get_mentor_me, get_mentor_status,
|
||||
post_register_mentor, put_update_mentor, put_update_mentor_me, put_update_mentor_no_id,
|
||||
put_verify_mentor,
|
||||
};
|
||||
|
||||
fn build_service(db: DatabaseConnection, state: Arc<AppState>) -> Arc<dyn MentorService> {
|
||||
let user_repo = Arc::new(PostgresUserRepository::new(db.clone()));
|
||||
let role_repo = Arc::new(PostgresRoleRepository::new(db.clone()));
|
||||
let repo = Arc::new(PostgresMentorRepository::new(db));
|
||||
Arc::new(MentorServiceImpl::new(repo, state, user_repo, role_repo))
|
||||
}
|
||||
|
||||
pub fn mentors_public_routes(db: DatabaseConnection, state: Arc<AppState>) -> Router {
|
||||
let service = build_service(db, state);
|
||||
Router::new()
|
||||
.route("/mentors/create", post(post_register_mentor))
|
||||
.layer(Extension(service))
|
||||
}
|
||||
|
||||
pub fn mentors_protected_routes(db: DatabaseConnection, state: Arc<AppState>) -> Router {
|
||||
let svc = build_service(db, Arc::clone(&state));
|
||||
Router::new()
|
||||
.route("/mentors", get(get_mentor_list))
|
||||
.route("/mentors/me", get(get_mentor_me))
|
||||
.route("/mentors/me/update", put(put_update_mentor_me))
|
||||
.route("/mentors/me/status", get(get_mentor_status))
|
||||
.route("/mentors/detail/{id}", get(get_mentor_by_id))
|
||||
.route("/mentors/update/{id}", put(put_update_mentor))
|
||||
.route("/mentors/update", put(put_update_mentor_no_id))
|
||||
.route("/mentors/delete/{id}", delete(delete_mentor))
|
||||
.route("/mentors/verify/{id}", put(put_verify_mentor))
|
||||
.layer(Extension(svc))
|
||||
.layer(Extension((*state).clone()))
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod http;
|
||||
pub mod persistence;
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod postgres_mentor_repository;
|
||||
|
||||
pub use postgres_mentor_repository::PostgresMentorRepository;
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
use std::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
use sea_orm::prelude::*;
|
||||
use sea_orm::{ActiveValue, Order, QueryOrder, PaginatorTrait};
|
||||
use paginator_rs::{PaginationParams, SortDirection};
|
||||
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
|
||||
use uuid::Uuid;
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_entities::seaorm::auth::mentors::{
|
||||
Entity as MentorsEntity,
|
||||
Column as MentorColumn,
|
||||
ActiveModel as MentorActiveModel,
|
||||
Model as MentorModel,
|
||||
};
|
||||
use crate::mentors::domain::{mentor::MentorEntity, repository::MentorRepository};
|
||||
|
||||
fn model_to_entity(model: MentorModel) -> MentorEntity {
|
||||
MentorEntity {
|
||||
id: model.id,
|
||||
user_id: model.user_id,
|
||||
industries: serde_json::from_value(
|
||||
model.industries.unwrap_or(serde_json::Value::Array(vec![])),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
expertise: serde_json::from_value(
|
||||
model.expertise.unwrap_or(serde_json::Value::Array(vec![])),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
languages: serde_json::from_value(
|
||||
model.languages.unwrap_or(serde_json::Value::Array(vec![])),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
current_company: model.current_company.unwrap_or_default(),
|
||||
current_role: model.current_role.unwrap_or_default(),
|
||||
years_of_experience: model.years_of_experience.unwrap_or(0),
|
||||
topics_of_interest: serde_json::from_value(
|
||||
model.topics_of_interest.unwrap_or(serde_json::Value::Array(vec![])),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
preferred_mentee_level: serde_json::from_str(
|
||||
&model.preferred_mentee_level.unwrap_or_default(),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
preferred_mentoring_formats: serde_json::from_value(
|
||||
model
|
||||
.preferred_mentoring_formats
|
||||
.unwrap_or(serde_json::Value::Array(vec![])),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
availability_commitment: model.availability_commitment.unwrap_or_default(),
|
||||
mentoring_rate: model.mentoring_rate.unwrap_or(0.0),
|
||||
status: model.status.unwrap_or_default(),
|
||||
is_deleted: model.is_deleted,
|
||||
created_at: model.created_at,
|
||||
updated_at: model.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PostgresMentorRepository {
|
||||
db: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
impl PostgresMentorRepository {
|
||||
pub fn new(db: DatabaseConnection) -> Self {
|
||||
Self { db: Arc::new(db) }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MentorRepository for PostgresMentorRepository {
|
||||
async fn find_all(
|
||||
&self,
|
||||
params: PaginationParams,
|
||||
) -> Result<PaginatorResponse<MentorEntity>, AppError> {
|
||||
let page = params.page.max(1);
|
||||
let per_page = params.per_page.clamp(1, 100);
|
||||
|
||||
let mut query = MentorsEntity::find()
|
||||
.filter(MentorColumn::IsDeleted.eq(false));
|
||||
|
||||
query = match params.sort_by.as_deref() {
|
||||
Some("updated_at") => match params.sort_direction {
|
||||
Some(SortDirection::Asc) => query.order_by(MentorColumn::UpdatedAt, Order::Asc),
|
||||
_ => query.order_by(MentorColumn::UpdatedAt, Order::Desc),
|
||||
},
|
||||
_ => match params.sort_direction {
|
||||
Some(SortDirection::Asc) => query.order_by(MentorColumn::CreatedAt, Order::Asc),
|
||||
_ => query.order_by(MentorColumn::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 mentors = paginator
|
||||
.fetch_page((page - 1) as u64)
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let data = mentors.into_iter().map(model_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,
|
||||
include_deleted: bool,
|
||||
) -> Result<MentorEntity, AppError> {
|
||||
let mut query = MentorsEntity::find_by_id(id);
|
||||
|
||||
if !include_deleted {
|
||||
query = query.filter(MentorColumn::IsDeleted.eq(false));
|
||||
}
|
||||
|
||||
let model = query
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Mentor not found".to_string()))?;
|
||||
|
||||
Ok(model_to_entity(model))
|
||||
}
|
||||
|
||||
async fn find_by_user_id(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
include_deleted: bool,
|
||||
) -> Result<MentorEntity, AppError> {
|
||||
let mut query = MentorsEntity::find()
|
||||
.filter(MentorColumn::UserId.eq(user_id));
|
||||
|
||||
if !include_deleted {
|
||||
query = query.filter(MentorColumn::IsDeleted.eq(false));
|
||||
}
|
||||
|
||||
let model = query
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Mentor not found".to_string()))?;
|
||||
|
||||
Ok(model_to_entity(model))
|
||||
}
|
||||
|
||||
async fn create(&self, entity: MentorEntity) -> Result<Uuid, AppError> {
|
||||
let active_model = MentorActiveModel {
|
||||
user_id: ActiveValue::Set(entity.user_id),
|
||||
industries: ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.industries)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
)),
|
||||
expertise: ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.expertise)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
)),
|
||||
languages: ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.languages)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
)),
|
||||
current_company: ActiveValue::Set(Some(entity.current_company)),
|
||||
current_role: ActiveValue::Set(Some(entity.current_role)),
|
||||
years_of_experience: ActiveValue::Set(Some(entity.years_of_experience)),
|
||||
topics_of_interest: ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.topics_of_interest)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
)),
|
||||
preferred_mentee_level: ActiveValue::Set(Some(
|
||||
serde_json::to_string(&entity.preferred_mentee_level)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
)),
|
||||
preferred_mentoring_formats: ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.preferred_mentoring_formats)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
)),
|
||||
availability_commitment: ActiveValue::Set(Some(entity.availability_commitment)),
|
||||
mentoring_rate: ActiveValue::Set(Some(entity.mentoring_rate)),
|
||||
status: ActiveValue::Set(Some(entity.status)),
|
||||
is_deleted: ActiveValue::Set(false),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let result = MentorsEntity::insert(active_model)
|
||||
.exec(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok(result.last_insert_id)
|
||||
}
|
||||
|
||||
async fn update(&self, entity: MentorEntity) -> Result<(), AppError> {
|
||||
let mut active_model: MentorActiveModel = MentorsEntity::find_by_id(entity.id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Mentor not found".to_string()))?
|
||||
.into();
|
||||
|
||||
if !entity.industries.is_empty() {
|
||||
active_model.industries = ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.industries)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
));
|
||||
}
|
||||
if !entity.expertise.is_empty() {
|
||||
active_model.expertise = ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.expertise)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
));
|
||||
}
|
||||
if !entity.languages.is_empty() {
|
||||
active_model.languages = ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.languages)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
));
|
||||
}
|
||||
if !entity.current_company.is_empty() {
|
||||
active_model.current_company = ActiveValue::Set(Some(entity.current_company));
|
||||
}
|
||||
if !entity.current_role.is_empty() {
|
||||
active_model.current_role = ActiveValue::Set(Some(entity.current_role));
|
||||
}
|
||||
active_model.years_of_experience = ActiveValue::Set(Some(entity.years_of_experience));
|
||||
if !entity.topics_of_interest.is_empty() {
|
||||
active_model.topics_of_interest = ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.topics_of_interest)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
));
|
||||
}
|
||||
if !entity.preferred_mentee_level.is_empty() {
|
||||
active_model.preferred_mentee_level = ActiveValue::Set(Some(
|
||||
serde_json::to_string(&entity.preferred_mentee_level)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
));
|
||||
}
|
||||
if !entity.preferred_mentoring_formats.is_empty() {
|
||||
active_model.preferred_mentoring_formats = ActiveValue::Set(Some(
|
||||
serde_json::to_value(&entity.preferred_mentoring_formats)
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?,
|
||||
));
|
||||
}
|
||||
if !entity.availability_commitment.is_empty() {
|
||||
active_model.availability_commitment =
|
||||
ActiveValue::Set(Some(entity.availability_commitment));
|
||||
}
|
||||
active_model.mentoring_rate = ActiveValue::Set(Some(entity.mentoring_rate));
|
||||
if !entity.status.is_empty() {
|
||||
active_model.status = ActiveValue::Set(Some(entity.status));
|
||||
}
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn soft_delete(&self, id: Uuid) -> Result<(), AppError> {
|
||||
let model = MentorsEntity::find_by_id(id)
|
||||
.filter(MentorColumn::IsDeleted.eq(false))
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("Mentor not found".to_string()))?;
|
||||
|
||||
let mut active_model: MentorActiveModel = model.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(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod application;
|
||||
pub mod domain;
|
||||
pub mod infrastructure;
|
||||
|
||||
pub use infrastructure::http::routes::{mentors_protected_routes, mentors_public_routes};
|
||||
Reference in New Issue
Block a user