finish add/buy in frontend

This commit is contained in:
2019-10-03 12:37:22 +02:00
parent 2e7afa9bb0
commit 60b489e8fd
6 changed files with 50 additions and 42 deletions

View File

@@ -131,30 +131,37 @@ impl<'q> AsPlayer<'q> {
/// ///
/// # Returns /// # Returns
/// Result containing the difference in coins after operation /// Result containing the difference in coins after operation
pub fn buy<'a>(self, params: &Vec<(i32, Option<f32>)>) -> ActionResult<(i32, i32, i32, i32)> { pub fn buy<'a>(self, params: &Vec<(i32, Option<f32>)>) -> ActionResult<(Vec<models::Item>, (i32, i32, i32, i32))> {
let mut all_results: Vec<(i32, i32, i32, i32)> = Vec::with_capacity(params.len()); 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() { 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 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 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) .values(&new_item)
.execute(self.conn) .execute(self.conn)?;
.map(|rows_updated| match rows_updated { let added_item = models::Item::owned_by(self.id)
1 => (), .order(id.desc())
_ => panic!("RuntimeError: Buy made no changes at all"), .first(self.conn)?;
})?;
let sell_price = match price_mod { let sell_price = match price_mod {
Some(modifier) => item.base_price as f32 * modifier, Some(modifier) => item.base_price as f32 * modifier,
None => item.base_price as f32 None => item.base_price as f32
}; };
DbApi::with_conn(self.conn).as_player(self.id).update_wealth(-sell_price) DbApi::with_conn(self.conn)
}); .as_player(self.id)
if let Ok(diff) = res { all_results.push(diff); } .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) (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 /// Sell a set of items from this player chest
/// ///

View File

@@ -117,12 +117,6 @@ export const AppStorage = {
switchPlayerChestVisibility () { switchPlayerChestVisibility () {
if (this.debug) console.log('switchPlayerChestVisibility', !this.state.show_player_chest) if (this.debug) console.log('switchPlayerChestVisibility', !this.state.show_player_chest)
this.state.show_player_chest = !this.state.show_player_chest this.state.show_player_chest = !this.state.show_player_chest
},
// TODO
// get the content of a player Chest, retrieve form cache or fetched
// will replace hack that loads *all* chest...
getPlayerLoot (playerId) {
}, },
updatePlayerWealth (goldValue) { updatePlayerWealth (goldValue) {
return Api.updateWealth(this.state.player_id, goldValue) return Api.updateWealth(this.state.player_id, goldValue)
@@ -147,25 +141,23 @@ export const AppStorage = {
}, },
buyItems (items) { buyItems (items) {
return Api.buyItems(this.state.player_id, items) return Api.buyItems(this.state.player_id, items)
.then(diff => this.__updatePlayerWealth(diff)) .then(([items, diff]) => {
.then(() => { this.__updatePlayerWealth(diff)
// Add items to the player loot // Add items to the player loot
console.log(items); // TODO: needs refactoring because player mutation happens in
// 2 different places
return items;
}); });
}, },
sellItems (items) { sellItems (items) {
return Api.sellItems(this.state.player_id, items) return Api.sellItems(this.state.player_id, items)
.then(diff => this.__updatePlayerWealth(diff)) .then(diff => this.__updatePlayerWealth(diff))
.then(() => {
// Remove items from player chest
console.log(items);
});
}, },
// Withdraws a claim. // Withdraws a claim.
cancelRequest(itemId) { cancelRequest(itemId) {
const playerId = this.state.player_id const playerId = this.state.player_id
return Api.unClaim(playerId, itemId) return Api.unClaim(playerId, itemId)
.then(done => { .then(_ => {
var idx = this.state.player_claims[playerId].indexOf(itemId); var idx = this.state.player_claims[playerId].indexOf(itemId);
if (idx > -1) { if (idx > -1) {
this.state.player_claims[playerId].splice(idx, 1); this.state.player_claims[playerId].splice(idx, 1);

View File

@@ -23,11 +23,20 @@ export default {
}, },
buyItems(items) { buyItems(items) {
AppStorage.buyItems(items) AppStorage.buyItems(items)
.then(_ => this.notifications.push(`Bought ${items.length} items`)) .then((items) => {
this.notifications.push(`Bought ${items.length} items`)
this.loot = this.loot.concat(items);
})
}, },
sellItems (items) { sellItems (items) {
AppStorage.sellItems(items) AppStorage.sellItems(items)
.then(_ => this.notifications.push(`Sold ${items.length} items`)) .then(_ => {
this.notifications.push(`Sold ${items.length} items`)
for (var idx in items) {
var to_remove = items[idx][0];
this.loot = this.loot.filter((item) => item.id != to_remove);
}
})
}, },
parseLoot (items) { parseLoot (items) {
this.loot = []; this.loot = [];

View File

@@ -84,7 +84,7 @@ pub(crate) fn serve() -> std::io::Result<()> {
.data(pool.clone()) .data(pool.clone())
.wrap( .wrap(
Cors::new() Cors::new()
.allowed_origin("http://localhost:8088") .allowed_origin("http://localhost:8080")
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"]) .allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
.max_age(3600), .max_age(3600),
) )