bazzar/actors/order_manager/src/lib.rs

120 lines
3.5 KiB
Rust

use actix::Message;
use config::SharedAppConfig;
use database_manager::{query_db, SharedDatabase};
use model::{AccountId, AccountOrder, OrderStatus, ShoppingCart, ShoppingCartId, ShoppingCartItem};
#[macro_export]
macro_rules! order_async_handler {
($msg: ty, $async: ident, $res: ty) => {
impl actix::Handler<$msg> for OrderManager {
type Result = actix::ResponseActFuture<Self, Result<$res>>;
fn handle(&mut self, msg: $msg, _ctx: &mut Self::Context) -> Self::Result {
use actix::WrapFuture;
let db = self.db.clone();
let config = self.config.clone();
Box::pin(async { $async(msg, db, config).await }.into_actor(self))
}
}
};
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Database actor failed")]
DatabaseInternal,
#[error("Shopping cart does not exists")]
ShoppingCart,
#[error("Failed to create account order")]
CreateAccountOrder,
}
pub type Result<T> = std::result::Result<T, Error>;
pub struct OrderManager {
db: SharedDatabase,
config: SharedAppConfig,
}
impl actix::Actor for OrderManager {
type Context = actix::Context<Self>;
}
impl OrderManager {
pub fn new(config: SharedAppConfig, db: SharedDatabase) -> Self {
Self { db, config }
}
}
#[derive(Message, Debug)]
#[rtype(result = "Result<AccountOrder>")]
pub struct CreateOrder {
pub account_id: AccountId,
pub shopping_cart_id: ShoppingCartId,
}
order_async_handler!(CreateOrder, create_order, AccountOrder);
pub(crate) async fn create_order(
msg: CreateOrder,
db: SharedDatabase,
_config: SharedAppConfig,
) -> Result<AccountOrder> {
let cart: ShoppingCart = query_db!(
db,
database_manager::FindShoppingCart {
id: msg.shopping_cart_id,
},
Error::ShoppingCart,
Error::DatabaseInternal
);
let items: Vec<ShoppingCartItem> = query_db!(
db,
database_manager::AccountShoppingCartItems {
account_id: cart.buyer_id,
shopping_cart_id: Some(cart.id),
},
Error::ShoppingCart,
Error::DatabaseInternal
);
let order = query_db!(
db,
database_manager::CreateAccountOrder {
shopping_cart_id: cart.id,
buyer_id: msg.account_id,
items: items
.into_iter()
.map(|item| database_manager::create_order::OrderItem {
product_id: item.product_id,
quantity: item.quantity,
quantity_unit: item.quantity_unit,
})
.collect(),
},
Error::CreateAccountOrder,
Error::DatabaseInternal
);
Ok(order)
}
pub fn change(current: OrderStatus, next: OrderStatus) -> Option<OrderStatus> {
match (current, next) {
// paying
(OrderStatus::Confirmed, OrderStatus::Payed) => Some(OrderStatus::Payed),
// delivering
(OrderStatus::Confirmed | OrderStatus::Payed, OrderStatus::Delivered) => {
Some(OrderStatus::Delivered)
}
// cancelling
(OrderStatus::Confirmed, OrderStatus::Cancelled) => Some(OrderStatus::Cancelled),
(OrderStatus::Payed, OrderStatus::Cancelled) => Some(OrderStatus::RequireRefund),
(OrderStatus::Payed, OrderStatus::RequireRefund) => Some(OrderStatus::RequireRefund),
(OrderStatus::RequireRefund, OrderStatus::Refunded) => Some(OrderStatus::Refunded),
_ => None,
}
}