finish add/buy in frontend
This commit is contained in:
@@ -131,30 +131,37 @@ impl<'q> AsPlayer<'q> {
|
||||
///
|
||||
/// # Returns
|
||||
/// Result containing the difference in coins after operation
|
||||
pub fn buy<'a>(self, params: &Vec<(i32, Option<f32>)>) -> ActionResult<(i32, i32, i32, i32)> {
|
||||
let mut all_results: Vec<(i32, i32, i32, i32)> = Vec::with_capacity(params.len());
|
||||
pub fn buy<'a>(self, params: &Vec<(i32, Option<f32>)>) -> ActionResult<(Vec<models::Item>, (i32, i32, i32, i32))> {
|
||||
let mut cumulated_diff: Vec<(i32, i32, i32, i32)> = Vec::with_capacity(params.len());
|
||||
let mut added_items: Vec<models::Item> = Vec::with_capacity(params.len());
|
||||
for (item_id, price_mod) in params.into_iter() {
|
||||
let res = self.conn.transaction(|| {
|
||||
if let Ok((item, diff)) = self.conn.transaction(|| {
|
||||
use schema::looted::dsl::*;
|
||||
let item = schema::items::table.find(item_id).first::<models::Item>(self.conn)?;
|
||||
let new_item = models::item::NewLoot::to_player(self.id, (&item.name, item.base_price));
|
||||
let _item_added = diesel::insert_into(schema::looted::table)
|
||||
diesel::insert_into(schema::looted::table)
|
||||
.values(&new_item)
|
||||
.execute(self.conn)
|
||||
.map(|rows_updated| match rows_updated {
|
||||
1 => (),
|
||||
_ => panic!("RuntimeError: Buy made no changes at all"),
|
||||
})?;
|
||||
.execute(self.conn)?;
|
||||
let added_item = models::Item::owned_by(self.id)
|
||||
.order(id.desc())
|
||||
.first(self.conn)?;
|
||||
let sell_price = match price_mod {
|
||||
Some(modifier) => item.base_price as f32 * modifier,
|
||||
None => item.base_price as f32
|
||||
};
|
||||
DbApi::with_conn(self.conn).as_player(self.id).update_wealth(-sell_price)
|
||||
});
|
||||
if let Ok(diff) = res { all_results.push(diff); }
|
||||
DbApi::with_conn(self.conn)
|
||||
.as_player(self.id)
|
||||
.update_wealth(-sell_price)
|
||||
.map(|diff| (added_item, diff))
|
||||
}) {
|
||||
cumulated_diff.push(diff);
|
||||
added_items.push(item);
|
||||
}
|
||||
}
|
||||
Ok(all_results.into_iter().fold((0,0,0,0), |sum, diff| {
|
||||
let all_diff = cumulated_diff.into_iter().fold((0,0,0,0), |sum, diff| {
|
||||
(sum.0 + diff.0, sum.1 + diff.1, sum.2 + diff.2, sum.3 + diff.3)
|
||||
}))
|
||||
});
|
||||
Ok((added_items, all_diff))
|
||||
}
|
||||
/// Sell a set of items from this player chest
|
||||
///
|
||||
|
||||
Reference in New Issue
Block a user