fixes some misbehaviour

This commit is contained in:
2019-11-07 15:55:58 +01:00
parent 4925afbeb5
commit 1cc9c2eefa
6 changed files with 94 additions and 30 deletions

View File

@@ -177,17 +177,26 @@ pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
}) })
} }
/// Split up and share group money among selected players /// Split up and share an certain amount of group money among selected players
///
/// The group first solve players debts,
/// then give what's left.
///
/// # Returns
///
/// A Wealth update with the amount of money actually shared
pub fn split_and_share( pub fn split_and_share(
conn: &DbConnection, conn: &DbConnection,
amount: i32, amount: i32,
players: &Vec<i32>, players: &Vec<i32>,
) -> QueryResult<Wealth> { ) -> UpdateResult {
let share = ( let share = (
amount / (players.len() + 1) as i32 amount / (players.len() + 1) as i32
// +1 share for the group // +1 share for the group
) as f64; ) as f64;
conn.transaction(|| { conn.transaction(|| {
// What we actually give, negative value
let mut diff = 0.0;
for p in players { for p in players {
let player = Players(conn).find(*p)?; let player = Players(conn).find(*p)?;
// Take debt into account // Take debt into account
@@ -196,13 +205,14 @@ pub fn split_and_share(
AsPlayer(conn, *p).update_debt(-player.debt)?; AsPlayer(conn, *p).update_debt(-player.debt)?;
AsPlayer(conn, *p).update_wealth(rest)?; AsPlayer(conn, *p).update_wealth(rest)?;
AsPlayer(conn, 0).update_wealth(-rest)?; AsPlayer(conn, 0).update_wealth(-rest)?;
diff -= rest;
} }
_ => { _ => {
AsPlayer(conn, *p).update_debt(-share as i32)?; AsPlayer(conn, *p).update_debt(-share as i32)?;
} }
} }
} }
Ok(Wealth::from_gp(share)) Ok(Update::Wealth(Wealth::from_gp(diff)))
}) })
} }

View File

@@ -1,6 +1,6 @@
use crate::{DbConnection, QueryResult};
use diesel::prelude::*; use diesel::prelude::*;
use crate::{DbConnection, QueryResult, Update, UpdateResult};
use crate::models::{self, item::Loot}; use crate::models::{self, item::Loot};
use crate::schema::claims; use crate::schema::claims;
@@ -54,7 +54,7 @@ impl<'q> Claims<'q> {
/// Will validate that the claimed item exists and is /// Will validate that the claimed item exists and is
/// actually owned by the group. /// actually owned by the group.
/// Duplicates are also ignored. /// Duplicates are also ignored.
pub fn add(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> { pub fn add(self, player_id: i32, loot_id: i32) -> UpdateResult {
// We need to validate that the claimed item exists // We need to validate that the claimed item exists
// AND is actually owned by group (id 0) // AND is actually owned by group (id 0)
let _item = models::item::LootManager(self.0, 0).find(loot_id)?; let _item = models::item::LootManager(self.0, 0).find(loot_id)?;
@@ -68,16 +68,22 @@ impl<'q> Claims<'q> {
.values(&claim) .values(&claim)
.execute(self.0)?; .execute(self.0)?;
// Return the created claim // Return the created claim
Ok(
Update::ClaimAdded(
claims::table claims::table
.order(claims::dsl::id.desc()) .order(claims::dsl::id.desc())
.first::<Claim>(self.0) .first::<Claim>(self.0)?
)
)
} }
/// Removes a claim from database, returning it /// Removes a claim from database, returning it
pub fn remove(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> { pub fn remove(self, player_id: i32, loot_id: i32) -> UpdateResult {
let claim = self.find(player_id, loot_id)?; let claim = self.find(player_id, loot_id)?;
claim.remove(self.0)?; claim.remove(self.0)?;
Ok(claim) Ok(
Update::ClaimRemoved(claim)
)
} }
pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> { pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> {
@@ -86,6 +92,15 @@ impl<'q> Claims<'q> {
.load(self.0) .load(self.0)
} }
pub(crate) fn delete_for_loot(&self, loot_id: i32) -> QueryResult<usize> {
diesel::delete(
claims::table
.filter(claims::dsl::loot_id.eq(loot_id))
)
.execute(self.0)
}
pub(crate) fn grouped_by_item(&self) -> QueryResult<Vec<(models::item::Item, Vec<Claim>)>> { pub(crate) fn grouped_by_item(&self) -> QueryResult<Vec<(models::item::Item, Vec<Claim>)>> {
let group_loot: Vec<Loot> = Loot::owned_by(0).load(self.0)?; let group_loot: Vec<Loot> = Loot::owned_by(0).load(self.0)?;
let claims = claims::table.load(self.0)?.grouped_by(&group_loot); let claims = claims::table.load(self.0)?.grouped_by(&group_loot);

View File

@@ -3,7 +3,7 @@ use diesel::expression::exists::Exists;
use diesel::prelude::*; use diesel::prelude::*;
use crate::schema::{items, looted}; use crate::schema::{items, looted};
use crate::{DbConnection, QueryResult, Update, UpdateResult }; use crate::{DbConnection, QueryResult, Update, UpdateResult, Claims };
type ItemColumns = (looted::id, looted::name, looted::base_price); type ItemColumns = (looted::id, looted::name, looted::base_price);
const ITEM_COLUMNS: ItemColumns = (looted::id, looted::name, looted::base_price); const ITEM_COLUMNS: ItemColumns = (looted::id, looted::name, looted::base_price);
type OwnedBy = Select<OwnedLoot, ItemColumns>; type OwnedBy = Select<OwnedLoot, ItemColumns>;
@@ -28,9 +28,16 @@ impl Item {
} }
pub fn remove(self, conn: &DbConnection) -> UpdateResult { pub fn remove(self, conn: &DbConnection) -> UpdateResult {
conn.transaction(
|| -> UpdateResult
{
Claims(conn).delete_for_loot(self.id)?;
diesel::delete(looted::table.find(self.id)).execute(conn)?; diesel::delete(looted::table.find(self.id)).execute(conn)?;
Ok(Update::ItemRemoved(self)) Ok(Update::ItemRemoved(self))
} }
)
}
fn owned_by(player: i32) -> OwnedBy { fn owned_by(player: i32) -> OwnedBy {
Loot::owned_by(player).select(ITEM_COLUMNS) Loot::owned_by(player).select(ITEM_COLUMNS)

View File

@@ -140,8 +140,8 @@ mod tests {
fn test_diff_adding() { fn test_diff_adding() {
use super::Wealth; use super::Wealth;
/// Let say we add 0.08 gp // Let say we add 0.08 gp
/// 1.23 + 0.08 gold is 1.31, diff is cp: -2, sp: +1 // 1.23 + 0.08 gold is 1.31, diff is cp: -2, sp: +1
let old = Wealth::from_gp(1.23); let old = Wealth::from_gp(1.23);
let new = Wealth::from_gp(1.31); let new = Wealth::from_gp(1.31);
let diff = new - old; let diff = new - old;
@@ -154,8 +154,8 @@ mod tests {
fn test_diff_subbing() { fn test_diff_subbing() {
use super::Wealth; use super::Wealth;
/// Let say we sub 0.08 gp // Let say we sub 0.08 gp
/// 1.31 - 0.08 gold is 1.23, diff is cp: +2, sp: -1 // 1.31 - 0.08 gold is 1.23, diff is cp: +2, sp: -1
let old = Wealth::from_gp(1.31); let old = Wealth::from_gp(1.31);
let new = Wealth::from_gp(1.23); let new = Wealth::from_gp(1.23);
let diff = new - old; let diff = new - old;

View File

@@ -1,11 +1,14 @@
use diesel::connection::Connection;
use lootalot_db::{self as db, DbConnection, Update, Value}; use lootalot_db::{self as db, DbConnection, Update, Value};
use std::collections::HashSet;
pub type IdList = Vec<i32>;
pub type ItemListWithMods = Vec<(i32, Option<f64>)>; pub type ItemListWithMods = Vec<(i32, Option<f64>)>;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct BuySellParams { pub struct BuySellParams {
pub items: ItemListWithMods, pub items: ItemListWithMods,
players: Option<Vec<i32>>, players: Option<IdList>,
global_mod: Option<f64>, global_mod: Option<f64>,
} }
@@ -66,6 +69,7 @@ pub enum ApiActions {
UpdateWealth(i32, f64), UpdateWealth(i32, f64),
BuyItems(i32, BuySellParams), BuyItems(i32, BuySellParams),
SellItems(i32, BuySellParams), SellItems(i32, BuySellParams),
ClaimItems(i32, IdList),
ClaimItem(i32, i32), ClaimItem(i32, i32),
UnclaimItem(i32, i32), UnclaimItem(i32, i32),
UndoLastAction(i32), UndoLastAction(i32),
@@ -161,18 +165,23 @@ pub fn execute(
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i); .fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
match id { match id {
0 => { 0 => {
let players = params.players.expect("The player list should be passed in !"); let players = params
let share = db::split_and_share( .players
conn, .unwrap_or(db::Players(conn).all()?.into_iter().map(|p| p.id).collect());
total_amount.to_gp() as i32, let shared = db::split_and_share(conn, total_amount.to_gp() as i32, &players)?;
&players, let shared_amount = {
)?; if let Update::Wealth(amount) = shared {
amount.to_gp()
} else {
panic!("cannot happen")
}
};
response.notify(format!( response.notify(format!(
"Les objets ont été vendus, chaque joueur a reçu {} po", "Les objets ont été vendus, les joueurs ont reçu (au total) {} po",
share.to_gp() shared_amount
)); ));
//response.push_update(Update::GroupShare(players, share)); //response.push_update(Update::GroupShare(players, share));
response.push_update(Update::Wealth(share)); response.push_update(shared);
} }
_ => { _ => {
response.notify(format!( response.notify(format!(
@@ -186,15 +195,31 @@ pub fn execute(
Some((id, "Vente d'objets")) Some((id, "Vente d'objets"))
} }
ApiActions::ClaimItem(id, item) => { ApiActions::ClaimItem(id, item) => {
response.push_update(Update::ClaimAdded(db::Claims(conn).add(id, item)?)); response.push_update(db::Claims(conn).add(id, item)?);
response.notify("Pour moi !".to_string()); response.notify("Pour moi !".to_string());
None None
} }
ApiActions::UnclaimItem(id, item) => { ApiActions::UnclaimItem(id, item) => {
response.push_update(Update::ClaimRemoved(db::Claims(conn).remove(id, item)?)); response.push_update(db::Claims(conn).remove(id, item)?);
response.notify("Bof! Finalement non.".to_string()); response.notify("Bof! Finalement non.".to_string());
None None
} }
ApiActions::ClaimItems(id, items) => {
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
let current_claims: HashSet<i32> =
db::Claims(conn).all()?.iter().filter(|c| c.player_id == id).map(|c| c.loot_id).collect();
let new_claims: HashSet<i32> = items.into_iter().collect();
// Claims to delete
for item in current_claims.difference(&new_claims) {
response.push_update(db::Claims(conn).remove(id, *item)?);
}
// Claims to add
for item in new_claims.difference(&current_claims) {
response.push_update(db::Claims(conn).add(id, *item)?);
}
Ok(Some((id, "Requête(s) mises(s) à jour")))
})?
}
ApiActions::UndoLastAction(id) => { ApiActions::UndoLastAction(id) => {
if let Ok(event) = db::models::history::get_last_of_player(conn, id) { if let Ok(event) = db::models::history::get_last_of_player(conn, id) {
let name = String::from(event.name()); let name = String::from(event.name());

View File

@@ -10,6 +10,7 @@ use crate::api;
type AppPool = web::Data<db::Pool>; type AppPool = web::Data<db::Pool>;
type PlayerId = web::Path<i32>; type PlayerId = web::Path<i32>;
type ItemId = web::Json<i32>; type ItemId = web::Json<i32>;
type IdList = web::Json<api::IdList>;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
struct NewGroupLoot { struct NewGroupLoot {
@@ -66,6 +67,12 @@ fn configure_api(config: &mut web::ServiceConfig) {
.service( .service(
web::resource("/claims") web::resource("/claims")
//.route(web::get().to_async(endpoints::player_claims)) //.route(web::get().to_async(endpoints::player_claims))
.route(web::post().to_async(
|pool, (player, data): (PlayerId, IdList)|
{
db_call(pool, Q::ClaimItems(*player, data.clone()))
}
))
.route(web::put().to_async( .route(web::put().to_async(
|pool, (player, data): (PlayerId, ItemId)| { |pool, (player, data): (PlayerId, ItemId)| {
db_call(pool, Q::ClaimItem(*player, *data)) db_call(pool, Q::ClaimItem(*player, *data))
@@ -142,7 +149,7 @@ pub fn serve() -> std::io::Result<()> {
.configure(configure_api) .configure(configure_api)
.wrap( .wrap(
Cors::new() Cors::new()
.allowed_origin("http://localhost:8080") .allowed_origin("http://localhost:8088")
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"]) .allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
.max_age(3600), .max_age(3600),
) )