fixes errors
This commit is contained in:
@@ -43,36 +43,36 @@ pub fn create_pool() -> Pool {
|
||||
}
|
||||
|
||||
/// Every possible update which can happen during a query
|
||||
/// Updates are relative to a Player
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub enum Update {
|
||||
Wealth(Wealth),
|
||||
ItemAdded(Item),
|
||||
ItemRemoved(Item),
|
||||
ItemBought(Item),
|
||||
ItemSold(Item),
|
||||
ClaimAdded(Claim),
|
||||
ClaimRemoved(Claim),
|
||||
}
|
||||
|
||||
impl Update {
|
||||
/// Change back what has been updated
|
||||
fn undo(&self, conn: &DbConnection, id: i32) -> UpdateResult {
|
||||
Ok(match self {
|
||||
Update::Wealth(diff) => AsPlayer(conn, id).update_wealth(-diff.to_gp())?,
|
||||
Update::ItemAdded(item) => LootManager(conn, id).find(item.id)?.remove(conn)?,
|
||||
Update::ItemRemoved(item) => LootManager(conn, id).add_from(&item)?,
|
||||
fn undo(&self, conn: &DbConnection, id: i32) -> QueryResult<()> {
|
||||
match self {
|
||||
Update::Wealth(diff) => { AsPlayer(conn, id).update_wealth(-diff.to_gp())?; },
|
||||
Update::ItemAdded(item) => { diesel::delete(crate::schema::loot::table.find(item.id))
|
||||
.execute(conn)?; },
|
||||
Update::ItemRemoved(item) => { LootManager(conn, id).add_from(&item)?; },
|
||||
Update::ItemBought(item) => { LootManager(conn, id).change_owner(item.id, models::item::OF_SHOP)?;},
|
||||
Update::ItemSold(item) => { LootManager(conn, models::item::SOLD).change_owner(item.id, id)?; },
|
||||
// Unused for now
|
||||
Update::ClaimAdded(claim) => vec!(Update::ClaimRemoved(*claim)),
|
||||
Update::ClaimRemoved(claim) => vec!(Update::ClaimAdded(*claim)),
|
||||
})
|
||||
Update::ClaimAdded(claim) => {},
|
||||
Update::ClaimRemoved(claim) => {},
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO: use this to wrap update in UpdateResult, allowing unified interface
|
||||
/// whether a query makes multiple updates or just one.
|
||||
enum OneOrMore {
|
||||
One(Update),
|
||||
More(Vec<Update>),
|
||||
}
|
||||
|
||||
/// Every value which can be queried
|
||||
#[derive(Debug)]
|
||||
pub enum Value {
|
||||
@@ -166,231 +166,3 @@ pub fn split_and_share(
|
||||
Ok(vec!(Update::Wealth(Wealth::from_gp(shared_total))))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(none)]
|
||||
mod tests_old {
|
||||
use super::*;
|
||||
type TestConnection = DbConnection;
|
||||
|
||||
/// Return a connection to a fresh database (stored in memory)
|
||||
fn test_connection() -> TestConnection {
|
||||
let test_conn = DbConnection::establish(":memory:").unwrap();
|
||||
diesel_migrations::run_pending_migrations(&test_conn).unwrap();
|
||||
test_conn
|
||||
}
|
||||
|
||||
/// When migrations are run, a special player with id 0 and name "Groupe"
|
||||
/// must be created.
|
||||
#[test]
|
||||
fn global_group_is_autocreated() {
|
||||
let conn = test_connection();
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
assert_eq!(players.len(), 1);
|
||||
let group = players.get(0).unwrap();
|
||||
assert_eq!(group.id, 0);
|
||||
assert_eq!(group.name, "Groupe".to_string());
|
||||
}
|
||||
|
||||
/// When a player updates wealth, a difference is returned by API.
|
||||
/// Added to the previous amount of coins, it should equal the updated weath.
|
||||
#[test]
|
||||
fn as_player_updates_wealth() {
|
||||
let conn = test_connection();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("PlayerName", 403.21)
|
||||
.unwrap();
|
||||
let diff = DbApi::with_conn(&conn)
|
||||
.as_player(1)
|
||||
.update_wealth(-401.21)
|
||||
.ok();
|
||||
// Check the returned diff
|
||||
assert_eq!(diff, Some((-1, -2, -1, -4)));
|
||||
let diff = diff.unwrap();
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
let player = players.get(1).unwrap();
|
||||
// Check that we can add old value to return diff to get resulting value
|
||||
assert_eq!(
|
||||
(player.cp, player.sp, player.gp, player.pp),
|
||||
(1 + diff.0, 2 + diff.1, 3 + diff.2, 4 + diff.3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_admin_add_player() {
|
||||
let conn = test_connection();
|
||||
let result = DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("PlayerName", 403.21);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
assert_eq!(players.len(), 2);
|
||||
let new_player = players.get(1).unwrap();
|
||||
assert_eq!(new_player.name, "PlayerName");
|
||||
assert_eq!(
|
||||
(new_player.cp, new_player.sp, new_player.gp, new_player.pp),
|
||||
(1, 2, 3, 4)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_admin_resolve_claims() {
|
||||
let conn = test_connection();
|
||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||
assert_eq!(claims.len(), 0);
|
||||
|
||||
// Add items
|
||||
assert_eq!(
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_loot(vec![("Épée", 40), ("Arc", 40),])
|
||||
.is_ok(),
|
||||
true
|
||||
);
|
||||
// Add players
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player1", 0.0)
|
||||
.unwrap();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player2", 0.0)
|
||||
.unwrap();
|
||||
// Put claims on one different item each
|
||||
DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
||||
DbApi::with_conn(&conn).as_player(2).claim(2).unwrap();
|
||||
let result = DbApi::with_conn(&conn).as_admin().resolve_claims();
|
||||
assert_eq!(result.is_ok(), true);
|
||||
// Check that both players received an item
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
for &i in [1, 2].into_iter() {
|
||||
assert_eq!(
|
||||
DbApi::with_conn(&conn).as_player(i).loot().unwrap().len(),
|
||||
1
|
||||
);
|
||||
let player = players.get(i as usize).unwrap();
|
||||
assert_eq!(player.debt, 20);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_player_claim_item() {
|
||||
let conn = test_connection();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player", 0.0)
|
||||
.unwrap();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_loot(vec![("Épée", 25)])
|
||||
.unwrap();
|
||||
// Claim an existing item
|
||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||
assert_eq!(claims.len(), 1);
|
||||
let claim = claims.get(0).unwrap();
|
||||
assert_eq!(claim.player_id, 1);
|
||||
assert_eq!(claim.loot_id, 1);
|
||||
// Claim an inexistant item
|
||||
let result = DbApi::with_conn(&conn).as_player(1).claim(2);
|
||||
assert_eq!(result.is_ok(), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_player_unclaim_item() {
|
||||
let conn = test_connection();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player", 0.0)
|
||||
.unwrap();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_loot(vec![("Épée", 25)])
|
||||
.unwrap();
|
||||
// Claim an existing item
|
||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
// Claiming twice is an error
|
||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||
assert_eq!(result.is_ok(), false);
|
||||
// Unclaiming and item
|
||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
// Check that not claimed items will not be unclaimed...
|
||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
||||
assert_eq!(result.is_ok(), false);
|
||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||
assert_eq!(claims.len(), 0);
|
||||
}
|
||||
|
||||
/// All-in-one checks one a simple buy/sell procedure
|
||||
///
|
||||
/// Checks that player's chest and wealth are updated.
|
||||
/// Checks that items are sold at half their value.
|
||||
/// Checks that a player cannot sell item he does not own.
|
||||
#[test]
|
||||
fn as_player_simple_buy_sell() {
|
||||
let conn = test_connection();
|
||||
// Adds a sword into inventory
|
||||
{
|
||||
use schema::items::dsl::*;
|
||||
diesel::insert_into(items)
|
||||
.values((name.eq("Sword"), base_price.eq(800)))
|
||||
.execute(&conn)
|
||||
.expect("Could not set up items table");
|
||||
}
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player", 1000.0)
|
||||
.unwrap();
|
||||
// Buy an item
|
||||
let bought = DbApi::with_conn(&conn).as_player(1).buy(&vec![(1, None)]);
|
||||
assert_eq!(bought.ok(), Some((0, 0, 0, -8))); // Returns diff of player wealth ?
|
||||
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
||||
assert_eq!(chest.len(), 1);
|
||||
let loot = chest.get(0).unwrap();
|
||||
assert_eq!(loot.name, "Sword");
|
||||
assert_eq!(loot.base_price, 800);
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
let player = players.get(1).unwrap();
|
||||
assert_eq!(player.pp, 2);
|
||||
// A player cannot sell loot from an other's chest
|
||||
let result = DbApi::with_conn(&conn)
|
||||
.as_player(0)
|
||||
.sell(&vec![(loot.id, None)]);
|
||||
assert_eq!(result.is_ok(), false);
|
||||
// Sell back
|
||||
let sold = DbApi::with_conn(&conn)
|
||||
.as_player(1)
|
||||
.sell(&vec![(loot.id, None)]);
|
||||
assert_eq!(sold.ok(), Some((0, 0, 0, 4)));
|
||||
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
||||
assert_eq!(chest.len(), 0);
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
let player = players.get(1).unwrap();
|
||||
assert_eq!(player.pp, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_admin_add_loot() {
|
||||
let conn = test_connection();
|
||||
assert_eq!(
|
||||
0,
|
||||
DbApi::with_conn(&conn).as_player(0).loot().unwrap().len()
|
||||
);
|
||||
let loot_to_add = vec![("Cape d'invisibilité", 8000), ("Arc long", 25)];
|
||||
let result = DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_loot(loot_to_add.clone());
|
||||
assert_eq!(result.is_ok(), true);
|
||||
let looted = DbApi::with_conn(&conn).as_player(0).loot().unwrap();
|
||||
assert_eq!(looted.len(), 2);
|
||||
// NB: Not a problem now, but this adds constraints of items being
|
||||
// created in the same order.
|
||||
for (added, to_add) in looted.into_iter().zip(loot_to_add) {
|
||||
assert_eq!(added.name, to_add.0);
|
||||
assert_eq!(added.base_price, to_add.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,18 +39,14 @@ impl Event {
|
||||
|
||||
/// TODO: why a move here ??
|
||||
/// Undo all updates in a single transaction
|
||||
pub fn undo(self, conn: &DbConnection) -> QueryResult<UpdateList> {
|
||||
pub fn undo(self, conn: &DbConnection) -> QueryResult<()> {
|
||||
conn.transaction(move || {
|
||||
if let Some(ref updates) = self.updates {
|
||||
let undone = updates.0.iter()
|
||||
// TODO: swallow errors !
|
||||
.filter_map(|u| u.undo(conn, self.player_id).ok())
|
||||
.collect();
|
||||
diesel::delete(history::table.find(self.id)).execute(conn)?;
|
||||
Ok(UpdateList(undone))
|
||||
} else {
|
||||
Ok(UpdateList(vec![]))
|
||||
for update in updates.inner() {
|
||||
update.undo(conn, self.player_id)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use diesel::expression::exists::Exists;
|
||||
use diesel::prelude::*;
|
||||
|
||||
use crate::schema::{items, loot};
|
||||
use crate::{DbConnection, QueryResult, Update, UpdateResult, Claims };
|
||||
use crate::{Claims, DbConnection, QueryResult, Update, UpdateResult};
|
||||
type ItemColumns = (loot::id, loot::name, loot::base_price);
|
||||
const ITEM_COLUMNS: ItemColumns = (loot::id, loot::name, loot::base_price);
|
||||
type OwnedBy = Select<OwnedLoot, ItemColumns>;
|
||||
@@ -33,9 +33,9 @@ impl Item {
|
||||
}
|
||||
|
||||
// Owner status
|
||||
const OF_GROUP: i32 = 0;
|
||||
const OF_SHOP: i32 = -1;
|
||||
const SOLD: i32 = -2;
|
||||
pub(crate) const OF_GROUP: i32 = 0;
|
||||
pub(crate) const OF_SHOP: i32 = -1;
|
||||
pub(crate) const SOLD: i32 = -2;
|
||||
|
||||
type WithOwner = Eq<loot::owner_id, i32>;
|
||||
type OwnedLoot = Filter<loot::table, WithOwner>;
|
||||
@@ -46,24 +46,19 @@ type OwnedLoot = Filter<loot::table, WithOwner>;
|
||||
/// OR the SOLD state.
|
||||
#[derive(Identifiable, Debug, Queryable)]
|
||||
#[table_name = "loot"]
|
||||
pub(super) struct Loot {
|
||||
pub(crate) struct Loot {
|
||||
id: i32,
|
||||
name: String,
|
||||
base_price: i32,
|
||||
owner_id: i32,
|
||||
}
|
||||
|
||||
|
||||
impl Loot {
|
||||
/// A filter on Loot that is owned by given player
|
||||
pub(super) fn owned_by(id: i32) -> OwnedLoot {
|
||||
loot::table.filter(loot::owner_id.eq(id))
|
||||
}
|
||||
|
||||
fn exists(id: i32) -> Exists<Find<loot::table, i32>> {
|
||||
exists(loot::table.find(id))
|
||||
}
|
||||
|
||||
pub(super) fn set_owner(&self, owner: i32, conn: &DbConnection) -> QueryResult<()> {
|
||||
diesel::update(loot::table.find(self.id))
|
||||
.set(loot::dsl::owner_id.eq(owner))
|
||||
@@ -98,7 +93,9 @@ impl<'q> Inventory<'q> {
|
||||
}
|
||||
|
||||
pub fn find_by_name(&self, item_name: &str) -> QueryResult<Item> {
|
||||
Ok(items::table.filter(items::dsl::name.like(item_name)).first(self.0)?)
|
||||
Ok(items::table
|
||||
.filter(items::dsl::name.like(item_name))
|
||||
.first(self.0)?)
|
||||
}
|
||||
|
||||
/// Check the inventory against a list of item names
|
||||
@@ -139,53 +136,48 @@ impl<'q> Shop<'q> {
|
||||
self.0.transaction(|| {
|
||||
let mut updates = AsPlayer(self.0, buyer).update_wealth(-sell_price)?;
|
||||
item.set_owner(buyer, self.0)?;
|
||||
updates.push(Update::ItemAdded(item.into_item()));
|
||||
updates.push(Update::ItemBought(item.into_item()));
|
||||
Ok(updates)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn buy(&self, items: Vec<(i32, Option<f64>)>, buyer: i32) -> UpdateResult {
|
||||
// TODO: check that player has enough money !
|
||||
let has_enough_gold = true;
|
||||
// TODO: check that player has enough money !
|
||||
let has_enough_gold = true;
|
||||
|
||||
if has_enough_gold {
|
||||
let mut updates = Vec::new();
|
||||
for (item_id, price_mod) in items.into_iter() {
|
||||
updates.append(
|
||||
&mut self.buy_single(buyer, item_id, price_mod)?
|
||||
)
|
||||
}
|
||||
Ok(updates)
|
||||
} else {
|
||||
unimplemented!();
|
||||
if has_enough_gold {
|
||||
let mut updates = Vec::new();
|
||||
for (item_id, price_mod) in items.into_iter() {
|
||||
updates.append(&mut self.buy_single(buyer, item_id, price_mod)?)
|
||||
}
|
||||
Ok(updates)
|
||||
} else {
|
||||
unimplemented!();
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, id: i32) -> QueryResult<Loot> {
|
||||
pub(crate) fn get(&self, id: i32) -> QueryResult<Loot> {
|
||||
Loot::owned_by(OF_SHOP).find(&id).first::<Loot>(self.0)
|
||||
}
|
||||
|
||||
pub fn replace_list(&self, items: Vec<Item>) -> QueryResult<()> {
|
||||
use self::loot::dsl::*;
|
||||
self.0.transaction(
|
||||
|| -> QueryResult<()>
|
||||
{
|
||||
// Remove all content
|
||||
diesel::delete(Loot::owned_by(OF_SHOP)).execute(self.0)?;
|
||||
// Adds new list
|
||||
for item in &items {
|
||||
let new_item = NewLoot {
|
||||
name: &item.name,
|
||||
base_price: item.base_price,
|
||||
owner_id: OF_SHOP,
|
||||
};
|
||||
diesel::insert_into(loot)
|
||||
.values(&new_item)
|
||||
.execute(self.0)?;
|
||||
}
|
||||
Ok(())
|
||||
self.0.transaction(|| -> QueryResult<()> {
|
||||
// Remove all content
|
||||
diesel::delete(Loot::owned_by(OF_SHOP)).execute(self.0)?;
|
||||
// Adds new list
|
||||
for item in &items {
|
||||
let new_item = NewLoot {
|
||||
name: &item.name,
|
||||
base_price: item.base_price,
|
||||
owner_id: OF_SHOP,
|
||||
};
|
||||
diesel::insert_into(loot)
|
||||
.values(&new_item)
|
||||
.execute(self.0)?;
|
||||
}
|
||||
)
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,10 +190,14 @@ impl<'q> LootManager<'q> {
|
||||
Ok(Item::owned_by(self.1).load(self.0)?)
|
||||
}
|
||||
|
||||
fn get(&self, item_id: i32) -> QueryResult<Loot> {
|
||||
pub(crate) fn get(&self, item_id: i32) -> QueryResult<Loot> {
|
||||
Ok(Loot::owned_by(self.1).find(item_id).first(self.0)?)
|
||||
}
|
||||
|
||||
pub(crate) fn change_owner(&self, item_id: i32, new_owner: i32) -> QueryResult<()> {
|
||||
Ok(self.get(item_id)?.set_owner(new_owner, self.0)?)
|
||||
}
|
||||
|
||||
/// Finds an item by id
|
||||
///
|
||||
/// Returns a NotFound error if an item is found by it
|
||||
@@ -217,27 +213,23 @@ impl<'q> LootManager<'q> {
|
||||
sell_value *= modifier;
|
||||
}
|
||||
self.0.transaction(|| {
|
||||
let mut updates =
|
||||
crate::AsPlayer(self.0, self.1)
|
||||
.update_wealth(sell_value)?;
|
||||
let mut updates = crate::AsPlayer(self.0, self.1).update_wealth(sell_value)?;
|
||||
to_sell.set_owner(SOLD, self.0)?;
|
||||
updates.push(Update::ItemRemoved(to_sell.into_item()));
|
||||
updates.push(Update::ItemSold(to_sell.into_item()));
|
||||
Ok(updates)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn sell(&self, items: Vec<(i32, Option<f64>)>) -> UpdateResult {
|
||||
self.0.transaction(|| {
|
||||
let mut updates = Vec::new();
|
||||
for (loot_id, price_mod) in items.into_iter() {
|
||||
updates.append(&mut self.sell_single(loot_id, price_mod)?);
|
||||
}
|
||||
Ok(updates)
|
||||
let mut updates = Vec::new();
|
||||
for (loot_id, price_mod) in items.into_iter() {
|
||||
updates.append(&mut self.sell_single(loot_id, price_mod)?);
|
||||
}
|
||||
Ok(updates)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// The last item added to the chest
|
||||
pub fn last(&self) -> QueryResult<Item> {
|
||||
Ok(Item::owned_by(self.1)
|
||||
@@ -263,7 +255,7 @@ impl<'q> LootManager<'q> {
|
||||
diesel::insert_into(loot::table)
|
||||
.values(&new_item)
|
||||
.execute(self.0)?;
|
||||
Ok(vec!(Update::ItemAdded(self.last()?)))
|
||||
Ok(vec![Update::ItemAdded(self.last()?)])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user