use actix_identity::Identity; use actix_web::{HttpResponse, Responder, Result, post, web}; use log::debug; use crate::{ app::App, storage::sql::{ barcode::{Barcode, BarcodeId, BarcodeIdStub}, insert::Operations, unit::UnitAmount, }, }; /// Buy an barcode #[utoipa::path( responses( ( status = OK, description = "Barcode successfully bought", ), ( status = NOT_FOUND, description = "Barcode id was not found", ), ( status = UNAUTHORIZED, description = "You did not login before calling this endpoint", ), ( status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String, ) ), params( ( "barcode_id" = BarcodeId, description = "The numeric value of the barcode" ), ( "times" = u16, description = "How often to buy the barcode" ), ) )] #[post("/barcode/{barcode_id}/buy/{times}")] pub(crate) async fn buy_barcode( app: web::Data, path: web::Path<(BarcodeIdStub, u16)>, _user: Identity, ) -> Result { let (barcode_id, times) = path.into_inner(); let mut ops = Operations::new("buy barcode unit"); let barcode = Barcode::from_id(&app, barcode_id.into()).await?; match barcode { Some(barcode) => { for _ in 0..times { barcode.buy(&mut ops); } ops.apply(&app).await?; Ok(HttpResponse::Ok().finish()) } None => Ok(HttpResponse::NotFound().finish()), } } /// Consume an barcode #[utoipa::path( responses( ( status = OK, description = "Barcode successfully consumed", ), ( status = NOT_FOUND, description = "Barcode id was not found", ), ( status = UNAUTHORIZED, description = "You did not login before calling this endpoint", ), ( status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String, ) ), params( ( "id" = BarcodeId, description = "The numeric value of the barcode" ), ), request_body = UnitAmount, )] #[post("/barcode/{id}/consume")] pub(crate) async fn consume_barcode( app: web::Data, barcode_id: web::Path, unit_amount: web::Json, _user: Identity, ) -> Result { let mut ops = Operations::new("consume barcode unit"); let barcode = Barcode::from_id(&app, barcode_id.into_inner().into()).await?; debug!("Starting consume for barcode: {barcode:?}"); match barcode { Some(barcode) => { barcode .consume(&app, unit_amount.into_inner(), &mut ops) .await?; ops.apply(&app).await?; Ok(HttpResponse::Ok().finish()) } None => Ok(HttpResponse::NotFound().finish()), } }