use std::collections::HashMap;
use std::sync::Arc;
use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use backbone_core::http::{ApiResponse, BackboneCrudHandler};
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;
use crate::domain::entity::*;
use crate::application::service::{MailNotificationService, ServiceError};
use crate::presentation::dto::{CreateMailNotificationDto, UpdateMailNotificationDto, PatchMailNotificationDto, MailNotificationResponseDto};
use crate::domain::state_machine::{MailNotificationHooksState, MailNotificationHooksStateMachine, MailNotificationHooksTransition};
#[derive(Debug, thiserror::Error)]
pub enum MailNotificationError {
#[error("Not found: {0}")]
NotFound(String),
#[error("Validation error: {0}")]
Validation(String),
#[error("Database error: {0}")]
Database(String),
#[error("Internal error: {0}")]
Internal(String),
#[error("One status row per (message, partner) for the inbox/email channel — enforced by partial unique index mail_notification_message_partner_uniq (WHERE res_partner_id IS NOT NULL AND notification_type IN ('inbox','email')). The sms channel is 1:many by uuid and sits outside this unique.: {0}")]
MailNotificationMessagePartnerDuplicate(String),
}
impl From<ServiceError> for MailNotificationError {
fn from(err: ServiceError) -> Self {
match err {
ServiceError::NotFound => Self::NotFound(err.to_string()),
ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
ServiceError::Repository(ref e) => Self::Database(e.to_string()),
ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
}
}
}
impl axum::response::IntoResponse for MailNotificationError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "MAILNOTIFICATION_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "MAILNOTIFICATION_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAILNOTIFICATION_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAILNOTIFICATION_INTERNAL_ERROR"),
Self::MailNotificationMessagePartnerDuplicate(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAILNOTIFICATION_MAIL_NOTIFICATION_MESSAGE_PARTNER_DUPLICATE"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod mail_notification_errors {
pub const MAIL_NOTIFICATION_MESSAGE_PARTNER_DUPLICATE: &str = "MAILNOTIFICATION_MAIL_NOTIFICATION_MESSAGE_PARTNER_DUPLICATE";
}
pub fn create_mail_notification_routes(service: Arc<MailNotificationService>) -> Router {
BackboneCrudHandler::<MailNotificationService, MailNotification, CreateMailNotificationDto, UpdateMailNotificationDto, MailNotificationResponseDto>::routes(
service,
"/mail_notifications",
)
}
pub fn create_mail_notification_read_routes(service: Arc<MailNotificationService>) -> Router {
BackboneCrudHandler::<MailNotificationService, MailNotification, CreateMailNotificationDto, UpdateMailNotificationDto, MailNotificationResponseDto>::read_routes(
service,
"/mail_notifications",
)
}
pub fn create_mail_notification_write_routes(service: Arc<MailNotificationService>) -> Router {
BackboneCrudHandler::<MailNotificationService, MailNotification, CreateMailNotificationDto, UpdateMailNotificationDto, MailNotificationResponseDto>::write_routes(
service,
"/mail_notifications",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_mail_notification_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<MailNotificationService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_mail_notification_routes(service)
.layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
let auth = auth_layer.clone();
async move {
let token = req.headers()
.get(axum::http::header::AUTHORIZATION)
.and_then(|h| h.to_str().ok())
.and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
.unwrap_or("");
match auth.authenticate(token).await {
Ok(ctx) => {
req.extensions_mut().insert(ctx);
next.run(req).await
}
Err(_) => {
(axum::http::StatusCode::UNAUTHORIZED,
axum::Json(serde_json::json!({
"success": false,
"error": "unauthorized",
"message": "Authentication required"
}))
).into_response()
}
}
}
}))
}
pub async fn dispatch_started_transition(
axum::extract::State(service): axum::extract::State<Arc<MailNotificationService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = MailNotificationHooksTransition::DispatchStarted.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_notification:transition:dispatch_started");
let has_update_perm = auth.permissions.iter().any(|p| p == "mail_notification:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailNotificationResponseDto>::error("Insufficient permissions for dispatch_started transition")));
}
}
let current_state: MailNotificationHooksState = entity.notification_status.to_string().parse()
.unwrap_or(MailNotificationHooksState::default());
let sm = MailNotificationHooksStateMachine::from_state(current_state);
if !sm.can_transition(MailNotificationHooksTransition::DispatchStarted) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailNotificationResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("notification_status".to_string(), serde_json::Value::String("Process".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: MailNotificationResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
}
}
pub async fn smtp_accepted_transition(
axum::extract::State(service): axum::extract::State<Arc<MailNotificationService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = MailNotificationHooksTransition::SmtpAccepted.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_notification:transition:smtp_accepted");
let has_update_perm = auth.permissions.iter().any(|p| p == "mail_notification:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailNotificationResponseDto>::error("Insufficient permissions for smtp_accepted transition")));
}
}
let current_state: MailNotificationHooksState = entity.notification_status.to_string().parse()
.unwrap_or(MailNotificationHooksState::default());
let sm = MailNotificationHooksStateMachine::from_state(current_state);
if !sm.can_transition(MailNotificationHooksTransition::SmtpAccepted) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailNotificationResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("notification_status".to_string(), serde_json::Value::String("Pending".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: MailNotificationResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
}
}
pub async fn delivery_confirmed_transition(
axum::extract::State(service): axum::extract::State<Arc<MailNotificationService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = MailNotificationHooksTransition::DeliveryConfirmed.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_notification:transition:delivery_confirmed");
let has_update_perm = auth.permissions.iter().any(|p| p == "mail_notification:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailNotificationResponseDto>::error("Insufficient permissions for delivery_confirmed transition")));
}
}
let current_state: MailNotificationHooksState = entity.notification_status.to_string().parse()
.unwrap_or(MailNotificationHooksState::default());
let sm = MailNotificationHooksStateMachine::from_state(current_state);
if !sm.can_transition(MailNotificationHooksTransition::DeliveryConfirmed) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailNotificationResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("notification_status".to_string(), serde_json::Value::String("Sent".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: MailNotificationResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
}
}
pub async fn instant_delivered_transition(
axum::extract::State(service): axum::extract::State<Arc<MailNotificationService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = MailNotificationHooksTransition::InstantDelivered.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_notification:transition:instant_delivered");
let has_update_perm = auth.permissions.iter().any(|p| p == "mail_notification:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailNotificationResponseDto>::error("Insufficient permissions for instant_delivered transition")));
}
}
let current_state: MailNotificationHooksState = entity.notification_status.to_string().parse()
.unwrap_or(MailNotificationHooksState::default());
let sm = MailNotificationHooksStateMachine::from_state(current_state);
if !sm.can_transition(MailNotificationHooksTransition::InstantDelivered) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailNotificationResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("notification_status".to_string(), serde_json::Value::String("Sent".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: MailNotificationResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
}
}
pub async fn bounced_transition(
axum::extract::State(service): axum::extract::State<Arc<MailNotificationService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = MailNotificationHooksTransition::Bounced.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_notification:transition:bounced");
let has_update_perm = auth.permissions.iter().any(|p| p == "mail_notification:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailNotificationResponseDto>::error("Insufficient permissions for bounced transition")));
}
}
let current_state: MailNotificationHooksState = entity.notification_status.to_string().parse()
.unwrap_or(MailNotificationHooksState::default());
let sm = MailNotificationHooksStateMachine::from_state(current_state);
if !sm.can_transition(MailNotificationHooksTransition::Bounced) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailNotificationResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("notification_status".to_string(), serde_json::Value::String("Bounce".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: MailNotificationResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
}
}
pub async fn send_failed_transition(
axum::extract::State(service): axum::extract::State<Arc<MailNotificationService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = MailNotificationHooksTransition::SendFailed.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_notification:transition:send_failed");
let has_update_perm = auth.permissions.iter().any(|p| p == "mail_notification:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailNotificationResponseDto>::error("Insufficient permissions for send_failed transition")));
}
}
let current_state: MailNotificationHooksState = entity.notification_status.to_string().parse()
.unwrap_or(MailNotificationHooksState::default());
let sm = MailNotificationHooksStateMachine::from_state(current_state);
if !sm.can_transition(MailNotificationHooksTransition::SendFailed) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailNotificationResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("notification_status".to_string(), serde_json::Value::String("Exception".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: MailNotificationResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
}
}
pub async fn canceled_transition(
axum::extract::State(service): axum::extract::State<Arc<MailNotificationService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = MailNotificationHooksTransition::Canceled.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_notification:transition:canceled");
let has_update_perm = auth.permissions.iter().any(|p| p == "mail_notification:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailNotificationResponseDto>::error("Insufficient permissions for canceled transition")));
}
}
let current_state: MailNotificationHooksState = entity.notification_status.to_string().parse()
.unwrap_or(MailNotificationHooksState::default());
let sm = MailNotificationHooksStateMachine::from_state(current_state);
if !sm.can_transition(MailNotificationHooksTransition::Canceled) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailNotificationResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("notification_status".to_string(), serde_json::Value::String("Canceled".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: MailNotificationResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailNotificationResponseDto>::not_found("MailNotification", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailNotificationResponseDto>::error(e.to_string()))),
}
}
pub fn create_mail_notification_transition_routes(service: Arc<MailNotificationService>) -> Router {
use axum::routing::post;
Router::new()
.route("/mail_notifications/:id/transitions/dispatch_started", post(dispatch_started_transition))
.route("/mail_notifications/:id/transitions/smtp_accepted", post(smtp_accepted_transition))
.route("/mail_notifications/:id/transitions/delivery_confirmed", post(delivery_confirmed_transition))
.route("/mail_notifications/:id/transitions/instant_delivered", post(instant_delivered_transition))
.route("/mail_notifications/:id/transitions/bounced", post(bounced_transition))
.route("/mail_notifications/:id/transitions/send_failed", post(send_failed_transition))
.route("/mail_notifications/:id/transitions/canceled", post(canceled_transition))
.with_state(service)
}