Merge branch 'refactoring' of rust/lootalot into master
This commit is contained in:
@@ -7,14 +7,14 @@ Un gestionnaire de trésors pour des joueurs de Donjon&Dragons(tm).
|
|||||||
## Fonctionnalités prévues
|
## Fonctionnalités prévues
|
||||||
|
|
||||||
* Ajouter des objets
|
* Ajouter des objets
|
||||||
☐ Acheter
|
☑ Acheter
|
||||||
☐ Ajouter un trésor (objet par objet ou par liste)
|
☐ Ajouter un trésor (objet par objet ou par liste)
|
||||||
* Répartir les objets entre les joueurs et le groupe
|
* Répartir les objets entre les joueurs et le groupe
|
||||||
☐ Demander un objet
|
☑ Demander un objet
|
||||||
☐ Résoudre un conflit
|
☐ Résoudre un conflit
|
||||||
☐ Finaliser la répartition après un délai défini
|
☐ Finaliser la répartition après un délai défini
|
||||||
* Vendre les objets du groupe et répartir équitablement leur valeur entre les joueurs
|
* Vendre les objets du groupe et répartir équitablement leur valeur entre les joueurs
|
||||||
☐ Possibilité d'indiquer une variation du prix de vente globale et/ou pour chaque objet
|
☑ Possibilité d'indiquer une variation du prix de vente globale et/ou pour chaque objet
|
||||||
☐ Possibilité d'indiquer des joueurs exclus de la répartition
|
☐ Possibilité d'indiquer des joueurs exclus de la répartition
|
||||||
* Gérer les comptes du groupe et des joueurs
|
* Gérer les comptes du groupe et des joueurs
|
||||||
☑ Afficher le solde actuel et la dette envers le groupe
|
☑ Afficher le solde actuel et la dette envers le groupe
|
||||||
|
|||||||
@@ -4,8 +4,10 @@
|
|||||||
//! This module wraps all needed database operations.
|
//! This module wraps all needed database operations.
|
||||||
//! It exports a public API for integration with various clients (REST Api, CLI, ...)
|
//! It exports a public API for integration with various clients (REST Api, CLI, ...)
|
||||||
extern crate dotenv;
|
extern crate dotenv;
|
||||||
#[macro_use] extern crate diesel;
|
#[macro_use]
|
||||||
#[macro_use] extern crate serde_derive;
|
extern crate diesel;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
use diesel::query_dsl::RunQueryDsl;
|
use diesel::query_dsl::RunQueryDsl;
|
||||||
@@ -14,326 +16,18 @@ use diesel::r2d2::{self, ConnectionManager};
|
|||||||
pub mod models;
|
pub mod models;
|
||||||
mod schema;
|
mod schema;
|
||||||
|
|
||||||
|
pub use models::{
|
||||||
|
claim::{Claim, Claims},
|
||||||
|
item::{Item, LootManager, Inventory},
|
||||||
|
player::{Player, Wealth, Players, AsPlayer},
|
||||||
|
};
|
||||||
|
|
||||||
/// The connection used
|
/// The connection used
|
||||||
pub type DbConnection = SqliteConnection;
|
pub type DbConnection = SqliteConnection;
|
||||||
/// A pool of connections
|
/// A pool of connections
|
||||||
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
|
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
|
||||||
/// The result of a query on DB
|
/// The result of a query on DB
|
||||||
pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
||||||
/// The result of an action provided by DbApi
|
|
||||||
pub type ActionResult<R> = Result<R, diesel::result::Error>;
|
|
||||||
|
|
||||||
|
|
||||||
/// A wrapper providing an API over the database
|
|
||||||
/// It offers a convenient way to deal with connection.
|
|
||||||
///
|
|
||||||
/// # Note
|
|
||||||
/// All methods consumes the DbApi, so that only one action
|
|
||||||
/// can be performed using a single instance.
|
|
||||||
///
|
|
||||||
/// # Todo list
|
|
||||||
/// ```text
|
|
||||||
/// v .as_player()
|
|
||||||
/// // Needs an action's history (one entry only should be enough)
|
|
||||||
/// x .undo_last_action() -> Success status
|
|
||||||
/// v .as_admin()
|
|
||||||
/// // When adding loot, an identifier should be used to build some kind of history
|
|
||||||
/// vx .add_loot(identifier, [items_desc]) -> Success status
|
|
||||||
/// x .sell_loot([players], [excluded_item_ids]) -> Success status (bool, player_share)
|
|
||||||
/// // Claims should be resolved after a certain delay
|
|
||||||
/// x .set_claims_timeout()
|
|
||||||
/// v .resolve_claims()
|
|
||||||
/// v .add_player(player_data)
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
pub struct DbApi<'q>(&'q DbConnection);
|
|
||||||
|
|
||||||
impl<'q> DbApi<'q> {
|
|
||||||
/// Returns a DbApi using the user given connection
|
|
||||||
///
|
|
||||||
/// # Usage
|
|
||||||
/// ```
|
|
||||||
/// use lootalot_db::{DbConnection, DbApi};
|
|
||||||
/// # use diesel::connection::Connection;
|
|
||||||
/// let conn = DbConnection::establish(":memory:").unwrap();
|
|
||||||
/// let api = DbApi::with_conn(&conn);
|
|
||||||
/// ```
|
|
||||||
pub fn with_conn(conn: &'q DbConnection) -> Self {
|
|
||||||
Self(conn)
|
|
||||||
}
|
|
||||||
/// Fetch the list of all players
|
|
||||||
pub fn fetch_players(self) -> QueryResult<Vec<models::Player>> {
|
|
||||||
Ok(schema::players::table.load::<models::Player>(self.0)?)
|
|
||||||
}
|
|
||||||
/// Fetch the inventory of items
|
|
||||||
///
|
|
||||||
/// TODO: remove limit used for debug
|
|
||||||
pub fn fetch_inventory(self) -> QueryResult<Vec<models::Item>> {
|
|
||||||
Ok(schema::items::table.limit(100).load::<models::Item>(self.0)?)
|
|
||||||
}
|
|
||||||
/// Fetch all existing claims
|
|
||||||
pub fn fetch_claims(self) -> QueryResult<Vec<models::Claim>> {
|
|
||||||
Ok(schema::claims::table.load::<models::Claim>(self.0)?)
|
|
||||||
}
|
|
||||||
/// Wrapper for acting as a specific player
|
|
||||||
///
|
|
||||||
/// # Usage
|
|
||||||
/// ```
|
|
||||||
/// # use lootalot_db::{DbConnection, DbApi};
|
|
||||||
/// # use diesel::connection::Connection;
|
|
||||||
/// # let conn = DbConnection::establish(":memory:").unwrap();
|
|
||||||
/// # let api = DbApi::with_conn(&conn);
|
|
||||||
/// let player_id: i32 = 1; // Id that references player in DB
|
|
||||||
/// let player = api.as_player(player_id);
|
|
||||||
/// ```
|
|
||||||
pub fn as_player(self, id: i32) -> AsPlayer<'q> {
|
|
||||||
AsPlayer { id, conn: self.0 }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wrapper for acting as the admin
|
|
||||||
pub fn as_admin(self) -> AsAdmin<'q> {
|
|
||||||
AsAdmin(self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A wrapper for interactions of players with the database.
|
|
||||||
/// Possible actions are exposed as methods
|
|
||||||
pub struct AsPlayer<'q> {
|
|
||||||
id: i32,
|
|
||||||
conn: &'q DbConnection,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'q> AsPlayer<'q> {
|
|
||||||
/// Fetch the content of a player's chest
|
|
||||||
///
|
|
||||||
/// # Usage
|
|
||||||
/// ```
|
|
||||||
/// # extern crate diesel_migrations;
|
|
||||||
/// # use lootalot_db::{DbConnection, DbApi};
|
|
||||||
/// # use diesel::connection::Connection;
|
|
||||||
/// # let conn = DbConnection::establish(":memory:").unwrap();
|
|
||||||
/// # diesel_migrations::run_pending_migrations(&conn).unwrap();
|
|
||||||
/// # let api = DbApi::with_conn(&conn);
|
|
||||||
/// // Get loot of player with id of 1
|
|
||||||
/// let loot = api.as_player(1).loot().unwrap();
|
|
||||||
/// assert_eq!(format!("{:?}", loot), "[]".to_string());
|
|
||||||
/// ```
|
|
||||||
pub fn loot(self) -> QueryResult<Vec<models::Item>> {
|
|
||||||
Ok(models::Item::owned_by(self.id).load(self.conn)?)
|
|
||||||
}
|
|
||||||
/// Buy a batch of items and add them to this player chest
|
|
||||||
///
|
|
||||||
/// Items can only be bought from inventory. Hence, the use
|
|
||||||
/// of the entity's id in 'items' table.
|
|
||||||
///
|
|
||||||
/// # Params
|
|
||||||
/// List of (Item's id in inventory, Option<Price modifier>)
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// Result containing the difference in coins after operation
|
|
||||||
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() {
|
|
||||||
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);
|
|
||||||
diesel::insert_into(schema::looted::table)
|
|
||||||
.values(&new_item)
|
|
||||||
.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)
|
|
||||||
.map(|diff| (added_item, diff))
|
|
||||||
}) {
|
|
||||||
cumulated_diff.push(diff);
|
|
||||||
added_items.push(item);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// Result containing the difference in coins after operation
|
|
||||||
pub fn sell(
|
|
||||||
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());
|
|
||||||
for (loot_id, price_mod) in params.into_iter() {
|
|
||||||
let res = self.conn.transaction(|| {
|
|
||||||
use schema::looted::dsl::*;
|
|
||||||
let loot = looted
|
|
||||||
.find(loot_id)
|
|
||||||
.first::<models::Loot>(self.conn)?;
|
|
||||||
if loot.owner != self.id {
|
|
||||||
// If the item does not belong to player,
|
|
||||||
// it can't be what we're looking for
|
|
||||||
return Err(diesel::result::Error::NotFound);
|
|
||||||
}
|
|
||||||
let mut sell_value = loot.base_price as f32 / 2.0;
|
|
||||||
if let Some(modifier) = price_mod {
|
|
||||||
sell_value *= modifier;
|
|
||||||
}
|
|
||||||
let _deleted = diesel::delete(looted.find(loot_id))
|
|
||||||
.execute(self.conn)?;
|
|
||||||
DbApi::with_conn(self.conn).as_player(self.id).update_wealth(sell_value)
|
|
||||||
});
|
|
||||||
if let Ok(diff) = res {
|
|
||||||
all_results.push(diff)
|
|
||||||
} else {
|
|
||||||
// TODO: need to find a better way to deal with errors
|
|
||||||
return Err(diesel::result::Error::NotFound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(all_results.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)
|
|
||||||
}))
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds the value in gold to the player's wealth.
|
|
||||||
///
|
|
||||||
/// Value can be negative to substract wealth.
|
|
||||||
pub fn update_wealth(self, value_in_gp: f32) -> ActionResult<(i32, i32, i32, i32)> {
|
|
||||||
use schema::players::dsl::*;
|
|
||||||
let current_wealth = players
|
|
||||||
.find(self.id)
|
|
||||||
.select((cp, sp, gp, pp))
|
|
||||||
.first::<models::Wealth>(self.conn)?;
|
|
||||||
// TODO: improve thisdiesel dependant transaction
|
|
||||||
// should be move inside a WealthUpdate method
|
|
||||||
let updated_wealth = models::Wealth::from_gp(current_wealth.to_gp() + value_in_gp);
|
|
||||||
// Difference in coins that is sent back
|
|
||||||
let (old, new) = (current_wealth.as_tuple(), updated_wealth.as_tuple());
|
|
||||||
let diff = (new.0 - old.0, new.1 - old.1, new.2 - old.2, new.3 - old.3);
|
|
||||||
diesel::update(players)
|
|
||||||
.filter(id.eq(self.id))
|
|
||||||
.set(&updated_wealth)
|
|
||||||
.execute(self.conn)
|
|
||||||
.map(|r| match r {
|
|
||||||
1 => diff,
|
|
||||||
_ => panic!("RuntimeError: UpdateWealth did no changes at all!"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
/// Put a claim on a specific item
|
|
||||||
pub fn claim(self, item: i32) -> ActionResult<()> {
|
|
||||||
let exists: bool = diesel::select(models::Loot::exists(item)).get_result(self.conn)?;
|
|
||||||
if !exists {
|
|
||||||
return Err(diesel::result::Error::NotFound);
|
|
||||||
};
|
|
||||||
let claim = models::claim::NewClaim::new(self.id, item);
|
|
||||||
diesel::insert_into(schema::claims::table)
|
|
||||||
.values(&claim)
|
|
||||||
.execute(self.conn)
|
|
||||||
.map(|rows_updated| match rows_updated {
|
|
||||||
1 => (),
|
|
||||||
_ => panic!("RuntimeError: Claim did no change at all!"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
/// Withdraw claim
|
|
||||||
pub fn unclaim(self, item: i32) -> ActionResult<()> {
|
|
||||||
use schema::claims::dsl::*;
|
|
||||||
diesel::delete(
|
|
||||||
claims
|
|
||||||
.filter(loot_id.eq(item))
|
|
||||||
.filter(player_id.eq(self.id)),
|
|
||||||
)
|
|
||||||
.execute(self.conn)
|
|
||||||
.and_then(|rows_updated| match rows_updated {
|
|
||||||
1 => Ok(()),
|
|
||||||
0 => Err(diesel::result::Error::NotFound),
|
|
||||||
_ => panic!("RuntimeError: UnclaimItem did not make expected changes"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wrapper for interactions of admins with the DB.
|
|
||||||
pub struct AsAdmin<'q>(&'q DbConnection);
|
|
||||||
|
|
||||||
impl<'q> AsAdmin<'q> {
|
|
||||||
/// Adds a player to the database
|
|
||||||
///
|
|
||||||
/// Takes the player name and starting wealth (in gold value).
|
|
||||||
pub fn add_player(self, name: &str, start_wealth: f32) -> ActionResult<()> {
|
|
||||||
diesel::insert_into(schema::players::table)
|
|
||||||
.values(&models::player::NewPlayer::create(name, start_wealth))
|
|
||||||
.execute(self.0)
|
|
||||||
.map(|rows_updated| match rows_updated {
|
|
||||||
1 => (),
|
|
||||||
_ => panic!("RuntimeError: AddPlayer did not make expected changes"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a list of items to the group loot
|
|
||||||
///
|
|
||||||
/// This offers complete control other created items, so that unique
|
|
||||||
/// items can be easily added. A user interface shall deal with
|
|
||||||
/// filling theses values for known items in inventory.
|
|
||||||
///
|
|
||||||
/// # Params
|
|
||||||
/// List of (name, base_price) values for the new items
|
|
||||||
pub fn add_loot(self, items: Vec<models::item::Item>) -> ActionResult<()> {
|
|
||||||
for item_desc in items.iter() {
|
|
||||||
let new_item = models::item::NewLoot::to_group(item_desc);
|
|
||||||
diesel::insert_into(schema::looted::table)
|
|
||||||
.values(&new_item)
|
|
||||||
.execute(self.0)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolve all pending claims and dispatch claimed items.
|
|
||||||
///
|
|
||||||
/// When a player gets an item, it's debt is increased by this item sell value
|
|
||||||
pub fn resolve_claims(self) -> ActionResult<()> {
|
|
||||||
// Fetch all claims, grouped by items.
|
|
||||||
let loot = models::Loot::owned_by(0).load(self.0)?;
|
|
||||||
let claims = schema::claims::table
|
|
||||||
.load::<models::Claim>(self.0)?
|
|
||||||
.grouped_by(&loot);
|
|
||||||
// For each claimed item
|
|
||||||
let data = loot.into_iter().zip(claims).collect::<Vec<_>>();
|
|
||||||
dbg!(&data);
|
|
||||||
|
|
||||||
for (loot, claims) in data {
|
|
||||||
match claims.len() {
|
|
||||||
1 => {
|
|
||||||
let claim = claims.get(0).unwrap();
|
|
||||||
let player_id = claim.player_id;
|
|
||||||
self.0.transaction(|| {
|
|
||||||
use schema::looted::dsl::*;
|
|
||||||
diesel::update(looted.find(claim.loot_id))
|
|
||||||
.set(owner_id.eq(player_id))
|
|
||||||
.execute(self.0)?;
|
|
||||||
diesel::delete(schema::claims::table.find(claim.id))
|
|
||||||
.execute(self.0)?;
|
|
||||||
{
|
|
||||||
use schema::players::dsl::*;
|
|
||||||
diesel::update(players.find(player_id))
|
|
||||||
.set(debt.eq(debt + (loot.base_price / 2)))
|
|
||||||
.execute(self.0)
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
},
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets up a connection pool and returns it.
|
/// Sets up a connection pool and returns it.
|
||||||
/// Uses the DATABASE_URL environment variable (must be set)
|
/// Uses the DATABASE_URL environment variable (must be set)
|
||||||
@@ -346,8 +40,88 @@ pub fn create_pool() -> Pool {
|
|||||||
.expect("Failed to create pool.")
|
.expect("Failed to create pool.")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
/// Sells a single item inside a transaction
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// The deleted entity and the updated Wealth (as a difference from previous value)
|
||||||
|
pub fn sell_item_transaction(
|
||||||
|
conn: &DbConnection,
|
||||||
|
id: i32,
|
||||||
|
loot_id: i32,
|
||||||
|
price_mod: Option<f64>,
|
||||||
|
) -> QueryResult<(Item, Wealth)> {
|
||||||
|
conn.transaction(|| {
|
||||||
|
let deleted = LootManager(conn, id)
|
||||||
|
.remove(loot_id)?;
|
||||||
|
let mut sell_value =
|
||||||
|
deleted.base_price as f64 / 2.0;
|
||||||
|
if let Some(modifier) = price_mod {
|
||||||
|
sell_value *= modifier;
|
||||||
|
}
|
||||||
|
let wealth = AsPlayer(conn, id)
|
||||||
|
.update_wealth(sell_value)?;
|
||||||
|
Ok((deleted, wealth))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Buys a single item, copied from inventory.
|
||||||
|
/// Runs inside a transaction
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// The created entity and the updated Wealth (as a difference from previous value)
|
||||||
|
pub fn buy_item_from_inventory(
|
||||||
|
conn: &DbConnection,
|
||||||
|
id: i32,
|
||||||
|
item_id: i32,
|
||||||
|
price_mod: Option<f64>,
|
||||||
|
) -> QueryResult<(Item, Wealth)> {
|
||||||
|
conn.transaction(|| {
|
||||||
|
// Find item in inventory
|
||||||
|
let item = Inventory(conn).find(item_id)?;
|
||||||
|
let new_item = LootManager(conn, id).add_from(&item)?;
|
||||||
|
let sell_price = match price_mod {
|
||||||
|
Some(modifier) => item.base_price as f64 * modifier,
|
||||||
|
None => item.base_price as f64,
|
||||||
|
};
|
||||||
|
AsPlayer(conn, id)
|
||||||
|
.update_wealth(-sell_price)
|
||||||
|
.map(|diff| (new_item, diff))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch all existing claims
|
||||||
|
pub fn fetch_claims(conn: &DbConnection) -> QueryResult<Vec<models::Claim>> {
|
||||||
|
schema::claims::table.load::<models::Claim>(conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve all pending claims and dispatch claimed items.
|
||||||
|
///
|
||||||
|
/// When a player gets an item, it's debt is increased by this item sell value
|
||||||
|
pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
|
||||||
|
let data = models::claim::Claims(conn).grouped_by_item()?;
|
||||||
|
dbg!(&data);
|
||||||
|
|
||||||
|
for (item, claims) in data {
|
||||||
|
match claims.len() {
|
||||||
|
1 => {
|
||||||
|
let claim = claims.get(0).unwrap();
|
||||||
|
let player_id = claim.player_id;
|
||||||
|
conn.transaction(|| {
|
||||||
|
claim.resolve_claim(conn)?;
|
||||||
|
//models::item::LootManager(self.0, 0).set_owner(claim.loot_id, claim.player_id)?;
|
||||||
|
models::player::AsPlayer(conn, player_id).update_debt(item.sell_value())
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[cfg(none)]
|
||||||
|
mod tests_old {
|
||||||
use super::*;
|
use super::*;
|
||||||
type TestConnection = DbConnection;
|
type TestConnection = DbConnection;
|
||||||
|
|
||||||
@@ -419,13 +193,22 @@ mod tests {
|
|||||||
assert_eq!(claims.len(), 0);
|
assert_eq!(claims.len(), 0);
|
||||||
|
|
||||||
// Add items
|
// Add items
|
||||||
assert_eq!(DbApi::with_conn(&conn).as_admin().add_loot(vec![
|
assert_eq!(
|
||||||
("Épée", 40),
|
DbApi::with_conn(&conn)
|
||||||
("Arc", 40),
|
.as_admin()
|
||||||
]).is_ok(), true);
|
.add_loot(vec![("Épée", 40), ("Arc", 40),])
|
||||||
|
.is_ok(),
|
||||||
|
true
|
||||||
|
);
|
||||||
// Add players
|
// Add players
|
||||||
DbApi::with_conn(&conn).as_admin().add_player("Player1", 0.0).unwrap();
|
DbApi::with_conn(&conn)
|
||||||
DbApi::with_conn(&conn).as_admin().add_player("Player2", 0.0).unwrap();
|
.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
|
// Put claims on one different item each
|
||||||
DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
||||||
DbApi::with_conn(&conn).as_player(2).claim(2).unwrap();
|
DbApi::with_conn(&conn).as_player(2).claim(2).unwrap();
|
||||||
@@ -434,7 +217,10 @@ mod tests {
|
|||||||
// Check that both players received an item
|
// Check that both players received an item
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
for &i in [1, 2].into_iter() {
|
for &i in [1, 2].into_iter() {
|
||||||
assert_eq!(DbApi::with_conn(&conn).as_player(i).loot().unwrap().len(), 1);
|
assert_eq!(
|
||||||
|
DbApi::with_conn(&conn).as_player(i).loot().unwrap().len(),
|
||||||
|
1
|
||||||
|
);
|
||||||
let player = players.get(i as usize).unwrap();
|
let player = players.get(i as usize).unwrap();
|
||||||
assert_eq!(player.debt, 20);
|
assert_eq!(player.debt, 20);
|
||||||
}
|
}
|
||||||
@@ -512,9 +298,7 @@ mod tests {
|
|||||||
.add_player("Player", 1000.0)
|
.add_player("Player", 1000.0)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
// Buy an item
|
// Buy an item
|
||||||
let bought = DbApi::with_conn(&conn)
|
let bought = DbApi::with_conn(&conn).as_player(1).buy(&vec![(1, None)]);
|
||||||
.as_player(1)
|
|
||||||
.buy(&vec![(1, None)]);
|
|
||||||
assert_eq!(bought.ok(), Some((0, 0, 0, -8))); // Returns diff of player wealth ?
|
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();
|
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
||||||
assert_eq!(chest.len(), 1);
|
assert_eq!(chest.len(), 1);
|
||||||
@@ -525,10 +309,14 @@ mod tests {
|
|||||||
let player = players.get(1).unwrap();
|
let player = players.get(1).unwrap();
|
||||||
assert_eq!(player.pp, 2);
|
assert_eq!(player.pp, 2);
|
||||||
// A player cannot sell loot from an other's chest
|
// A player cannot sell loot from an other's chest
|
||||||
let result = DbApi::with_conn(&conn).as_player(0).sell(&vec![(loot.id, None)]);
|
let result = DbApi::with_conn(&conn)
|
||||||
|
.as_player(0)
|
||||||
|
.sell(&vec![(loot.id, None)]);
|
||||||
assert_eq!(result.is_ok(), false);
|
assert_eq!(result.is_ok(), false);
|
||||||
// Sell back
|
// Sell back
|
||||||
let sold = DbApi::with_conn(&conn).as_player(1).sell(&vec![(loot.id, None)]);
|
let sold = DbApi::with_conn(&conn)
|
||||||
|
.as_player(1)
|
||||||
|
.sell(&vec![(loot.id, None)]);
|
||||||
assert_eq!(sold.ok(), Some((0, 0, 0, 4)));
|
assert_eq!(sold.ok(), Some((0, 0, 0, 4)));
|
||||||
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
||||||
assert_eq!(chest.len(), 0);
|
assert_eq!(chest.len(), 0);
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
use crate::models::item::Loot;
|
use crate::{DbConnection, QueryResult};
|
||||||
|
use diesel::prelude::*;
|
||||||
|
|
||||||
|
use crate::models::{self, item::Loot};
|
||||||
use crate::schema::claims;
|
use crate::schema::claims;
|
||||||
|
|
||||||
/// A Claim is a request by a single player on an item from group chest.
|
/// A Claim is a request by a single player on an item from group chest.
|
||||||
#[derive(Identifiable, Queryable, Associations, Serialize, Debug)]
|
#[derive(Identifiable, Queryable, Associations, Serialize, Deserialize, Debug)]
|
||||||
#[belongs_to(Loot)]
|
#[belongs_to(Loot)]
|
||||||
pub struct Claim {
|
pub struct Claim {
|
||||||
/// DB Identifier
|
/// DB Identifier
|
||||||
@@ -15,15 +18,152 @@ pub struct Claim {
|
|||||||
pub resolve: i32,
|
pub resolve: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Claim {
|
||||||
|
pub fn resolve_claim(&self, conn: &DbConnection) -> QueryResult<()> {
|
||||||
|
let loot: Loot = Loot::find(self.loot_id).first(conn)?;
|
||||||
|
loot.set_owner(self.player_id, conn)?;
|
||||||
|
self.remove(conn)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&self, conn: &DbConnection) -> QueryResult<()> {
|
||||||
|
diesel::delete(claims::table.find(self.id)).execute(conn)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Claims<'q>(pub &'q DbConnection);
|
||||||
|
|
||||||
|
impl<'q> Claims<'q> {
|
||||||
|
pub fn all(&self) -> QueryResult<Vec<Claim>> {
|
||||||
|
claims::table.load(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds a single claim by association of player and loot ids.
|
||||||
|
pub fn find(&self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
||||||
|
claims::table
|
||||||
|
.filter(claims::dsl::player_id.eq(player_id))
|
||||||
|
.filter(claims::dsl::loot_id.eq(loot_id))
|
||||||
|
.first(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a claim in database and returns it
|
||||||
|
pub fn add(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
||||||
|
// We need to validate that the claimed item exists
|
||||||
|
// AND is actually owned by group (id 0)
|
||||||
|
let _item = models::item::LootManager(self.0, 0).find(loot_id)?;
|
||||||
|
// We also check if claims does not already exists
|
||||||
|
if let Ok(_) = self.find(player_id, loot_id) {
|
||||||
|
return Err(diesel::result::Error::RollbackTransaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
let claim = NewClaim::new(player_id, loot_id);
|
||||||
|
diesel::insert_into(claims::table)
|
||||||
|
.values(&claim)
|
||||||
|
.execute(self.0)?;
|
||||||
|
// Return the created claim
|
||||||
|
claims::table
|
||||||
|
.order(claims::dsl::id.desc())
|
||||||
|
.first::<Claim>(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes a claim from database, returning it
|
||||||
|
pub fn remove(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
||||||
|
let claim = self.find(player_id, loot_id)?;
|
||||||
|
claim.remove(self.0)?;
|
||||||
|
Ok(claim)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> {
|
||||||
|
claims::table
|
||||||
|
.filter(claims::dsl::loot_id.eq(loot_id))
|
||||||
|
.load(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 claims = claims::table.load(self.0)?.grouped_by(&group_loot);
|
||||||
|
Ok(group_loot
|
||||||
|
.into_iter()
|
||||||
|
.map(|loot| loot.into_item())
|
||||||
|
.zip(claims)
|
||||||
|
.collect::<Vec<_>>())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Insertable, Debug)]
|
#[derive(Insertable, Debug)]
|
||||||
#[table_name = "claims"]
|
#[table_name = "claims"]
|
||||||
pub(crate) struct NewClaim {
|
struct NewClaim {
|
||||||
player_id: i32,
|
player_id: i32,
|
||||||
loot_id: i32,
|
loot_id: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NewClaim {
|
impl NewClaim {
|
||||||
pub(crate) fn new(player_id: i32, loot_id: i32) -> Self {
|
fn new(player_id: i32, loot_id: i32) -> Self {
|
||||||
Self { player_id, loot_id }
|
Self { player_id, loot_id }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
type TestResult = Result<(), diesel::result::Error>;
|
||||||
|
|
||||||
|
fn test_connection() -> Result<DbConnection, diesel::result::Error> {
|
||||||
|
let conn =
|
||||||
|
DbConnection::establish(":memory:").map_err(|_| diesel::result::Error::NotFound)?;
|
||||||
|
diesel_migrations::run_pending_migrations(&conn)
|
||||||
|
.map_err(|_| diesel::result::Error::NotFound)?;
|
||||||
|
let manager = models::player::Players(&conn);
|
||||||
|
manager.add("Player1", 0.0)?;
|
||||||
|
manager.add("Player2", 0.0)?;
|
||||||
|
crate::LootManager(&conn, 0).add_from(&crate::Item {
|
||||||
|
id: 0,
|
||||||
|
name: "Epee".to_string(),
|
||||||
|
base_price: 30,
|
||||||
|
})?;
|
||||||
|
crate::LootManager(&conn, 1).add_from(&crate::Item {
|
||||||
|
id: 0,
|
||||||
|
name: "Arc".to_string(),
|
||||||
|
base_price: 20,
|
||||||
|
})?;
|
||||||
|
Ok(conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_claim() -> TestResult {
|
||||||
|
let conn = test_connection()?;
|
||||||
|
Claims(&conn).add(1, 1)?;
|
||||||
|
assert_eq!(Claims(&conn).all()?.len(), 1);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cannot_duplicate_by_adding() -> TestResult {
|
||||||
|
let conn = test_connection()?;
|
||||||
|
Claims(&conn).add(1, 1)?;
|
||||||
|
let res = Claims(&conn).add(1, 1);
|
||||||
|
assert_eq!(res.is_err(), true);
|
||||||
|
assert_eq!(Claims(&conn).all()?.len(), 1);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn remove_claim() -> TestResult {
|
||||||
|
let conn = test_connection()?;
|
||||||
|
let claim = Claims(&conn).add(1, 1)?;
|
||||||
|
claim.remove(&conn);
|
||||||
|
assert_eq!(Claims(&conn).all()?.len(), 0);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cannot_only_claim_from_group() -> TestResult {
|
||||||
|
let conn = test_connection()?;
|
||||||
|
let claim = Claims(&conn).add(1, 2);
|
||||||
|
assert_eq!(claim.is_err(), true);
|
||||||
|
assert_eq!(Claims(&conn).all()?.len(), 0);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,17 +1,14 @@
|
|||||||
use crate::schema::looted;
|
|
||||||
use diesel::dsl::{exists, Eq, Filter, Find, Select};
|
use diesel::dsl::{exists, Eq, Filter, Find, Select};
|
||||||
use diesel::expression::exists::Exists;
|
use diesel::expression::exists::Exists;
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
|
||||||
|
use crate::schema::{items, looted};
|
||||||
|
use crate::{DbConnection, QueryResult};
|
||||||
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>;
|
||||||
|
|
||||||
/// Represents a unique item in inventory
|
/// Represents a basic item
|
||||||
///
|
|
||||||
/// It is also used as a public representation of Loot, since owner
|
|
||||||
/// information is implicit.
|
|
||||||
/// Or maybe this is a little too confusing ??
|
|
||||||
#[derive(Debug, Queryable, Serialize, Deserialize, Clone)]
|
#[derive(Debug, Queryable, Serialize, Deserialize, Clone)]
|
||||||
pub struct Item {
|
pub struct Item {
|
||||||
pub id: i32,
|
pub id: i32,
|
||||||
@@ -20,37 +17,123 @@ pub struct Item {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Item {
|
impl Item {
|
||||||
/// Public proxy for Loot::owned_by that selects only Item fields
|
pub fn value(&self) -> i32 {
|
||||||
pub fn owned_by(player: i32) -> OwnedBy {
|
self.base_price
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sell_value(&self) -> i32 {
|
||||||
|
self.base_price / 2
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned_by(player: i32) -> OwnedBy {
|
||||||
Loot::owned_by(player).select(ITEM_COLUMNS)
|
Loot::owned_by(player).select(ITEM_COLUMNS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct Inventory<'q>(pub &'q DbConnection);
|
||||||
|
|
||||||
|
impl<'q> Inventory<'q> {
|
||||||
|
pub fn all(&self) -> QueryResult<Vec<Item>> {
|
||||||
|
items::table.load::<Item>(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find(&self, item_id: i32) -> QueryResult<Item> {
|
||||||
|
items::table.find(item_id).first::<Item>(self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type WithOwner = Eq<looted::owner_id, i32>;
|
type WithOwner = Eq<looted::owner_id, i32>;
|
||||||
type OwnedLoot = Filter<looted::table, WithOwner>;
|
type OwnedLoot = Filter<looted::table, WithOwner>;
|
||||||
|
|
||||||
/// Represents an item that has been looted
|
/// Represents an item that has been looted,
|
||||||
#[derive(Identifiable, Debug, Queryable, Serialize)]
|
/// hence has an owner.
|
||||||
|
#[derive(Identifiable, Debug, Queryable)]
|
||||||
#[table_name = "looted"]
|
#[table_name = "looted"]
|
||||||
pub(crate) struct Loot {
|
pub(super) struct Loot {
|
||||||
id: i32,
|
id: i32,
|
||||||
name: String,
|
name: String,
|
||||||
pub(crate) base_price: i32,
|
base_price: i32,
|
||||||
pub(crate) owner: i32,
|
owner: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Loot {
|
impl Loot {
|
||||||
/// A filter on Loot that is owned by given player
|
/// A filter on Loot that is owned by given player
|
||||||
pub(crate) fn owned_by(id: i32) -> OwnedLoot {
|
pub(super) fn owned_by(id: i32) -> OwnedLoot {
|
||||||
looted::table.filter(looted::owner_id.eq(id))
|
looted::table.filter(looted::owner_id.eq(id))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn owns(player: i32, item: i32) -> Exists<Find<OwnedLoot, i32>> {
|
fn exists(id: i32) -> Exists<Find<looted::table, i32>> {
|
||||||
exists(Loot::owned_by(player).find(item))
|
exists(looted::table.find(id))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn exists(id: i32) -> Exists<Find<looted::table, i32>> {
|
pub(super) fn set_owner(&self, owner: i32, conn: &DbConnection) -> QueryResult<()> {
|
||||||
exists(looted::table.find(id))
|
diesel::update(looted::table.find(self.id))
|
||||||
|
.set(looted::dsl::owner_id.eq(owner))
|
||||||
|
.execute(conn)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn into_item(self) -> Item {
|
||||||
|
Item {
|
||||||
|
id: self.id,
|
||||||
|
name: self.name,
|
||||||
|
base_price: self.base_price,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn find(id: i32) -> Find<looted::table, i32> {
|
||||||
|
looted::table.find(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Manager for a player's loot
|
||||||
|
pub struct LootManager<'q>(pub &'q DbConnection, pub i32);
|
||||||
|
|
||||||
|
impl<'q> LootManager<'q> {
|
||||||
|
/// All items from this player chest
|
||||||
|
pub fn all(&self) -> QueryResult<Vec<Item>> {
|
||||||
|
Ok(Item::owned_by(self.1).load(self.0)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds an item by id
|
||||||
|
pub fn find(&self, loot_id: i32) -> QueryResult<Item> {
|
||||||
|
Ok(Loot::find(loot_id).first(self.0).and_then(|loot: Loot| {
|
||||||
|
if loot.owner != self.1 {
|
||||||
|
Err(diesel::result::Error::NotFound)
|
||||||
|
} else {
|
||||||
|
Ok(Item {
|
||||||
|
id: loot.id,
|
||||||
|
name: loot.name,
|
||||||
|
base_price: loot.base_price,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last item added to the chest
|
||||||
|
pub fn last(&self) -> QueryResult<Item> {
|
||||||
|
Ok(Item::owned_by(self.1)
|
||||||
|
.order(looted::dsl::id.desc())
|
||||||
|
.first(self.0)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a copy of the given item inside player chest
|
||||||
|
pub fn add_from(self, item: &Item) -> QueryResult<Item> {
|
||||||
|
let new_item = NewLoot {
|
||||||
|
name: &item.name,
|
||||||
|
base_price: item.base_price,
|
||||||
|
owner_id: self.1,
|
||||||
|
};
|
||||||
|
diesel::insert_into(looted::table)
|
||||||
|
.values(&new_item)
|
||||||
|
.execute(self.0)?;
|
||||||
|
self.last()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(self, item_id: i32) -> QueryResult<Item> {
|
||||||
|
let deleted = self.find(item_id)?;
|
||||||
|
diesel::delete(looted::table.find(deleted.id)).execute(self.0)?;
|
||||||
|
Ok(deleted)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,28 +143,8 @@ impl Loot {
|
|||||||
/// to the id of buying player otherwise.
|
/// to the id of buying player otherwise.
|
||||||
#[derive(Insertable)]
|
#[derive(Insertable)]
|
||||||
#[table_name = "looted"]
|
#[table_name = "looted"]
|
||||||
pub(crate) struct NewLoot<'a> {
|
struct NewLoot<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
||||||
base_price: i32,
|
base_price: i32,
|
||||||
owner_id: i32,
|
owner_id: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> NewLoot<'a> {
|
|
||||||
/// A new loot going to the group (loot procedure)
|
|
||||||
pub(crate) fn to_group(desc: &'a Item) -> Self {
|
|
||||||
Self {
|
|
||||||
name: &desc.name,
|
|
||||||
base_price: desc.base_price,
|
|
||||||
owner_id: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A new loot going to a specific player (buy procedure)
|
|
||||||
pub(crate) fn to_player(player: i32, desc: &'a Item) -> Self {
|
|
||||||
Self {
|
|
||||||
name: &desc.name,
|
|
||||||
base_price: desc.base_price,
|
|
||||||
owner_id: player,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
pub(super) mod claim;
|
pub mod claim;
|
||||||
pub(super) mod item;
|
pub mod item;
|
||||||
pub(super) mod player;
|
pub mod player;
|
||||||
|
|
||||||
pub use claim::Claim;
|
pub use claim::Claim;
|
||||||
pub use item::{Item};
|
pub use item::Item;
|
||||||
pub(crate) use item::Loot;
|
|
||||||
pub use player::{Player, Wealth};
|
pub use player::{Player, Wealth};
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
use crate::schema::players;
|
use crate::schema::players;
|
||||||
|
use crate::{DbConnection, QueryResult};
|
||||||
|
use diesel::prelude::*;
|
||||||
|
|
||||||
/// Representation of a player in database
|
/// Representation of a player in database
|
||||||
#[derive(Debug, Queryable, Serialize)]
|
#[derive(Identifiable, Queryable, Serialize, Deserialize, Debug)]
|
||||||
pub struct Player {
|
pub struct Player {
|
||||||
/// DB Identitier
|
/// DB Identitier
|
||||||
pub id: i32,
|
pub id: i32,
|
||||||
@@ -20,7 +22,52 @@ pub struct Player {
|
|||||||
pub pp: i32,
|
pub pp: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unpack a floating value in gold pieces to integer
|
pub struct Players<'q>(pub &'q DbConnection);
|
||||||
|
|
||||||
|
impl<'q> Players<'q> {
|
||||||
|
pub fn all(&self) -> QueryResult<Vec<Player>> {
|
||||||
|
players::table.load(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find(&self, id: i32) -> QueryResult<Player> {
|
||||||
|
players::table.find(id).first(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add(&self, name: &str, wealth: f64) -> QueryResult<Player> {
|
||||||
|
diesel::insert_into(players::table)
|
||||||
|
.values(&NewPlayer::create(name, wealth))
|
||||||
|
.execute(self.0)?;
|
||||||
|
players::table.order(players::dsl::id.desc()).first(self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AsPlayer<'q>(pub &'q DbConnection, pub i32);
|
||||||
|
|
||||||
|
impl<'q> AsPlayer<'q> {
|
||||||
|
pub fn update_wealth(&self, value_in_gp: f64) -> QueryResult<Wealth> {
|
||||||
|
use crate::schema::players::dsl::*;
|
||||||
|
let current_wealth = players
|
||||||
|
.find(self.1)
|
||||||
|
.select((cp, sp, gp, pp))
|
||||||
|
.first::<Wealth>(self.0)?;
|
||||||
|
let updated_wealth = Wealth::from_gp(current_wealth.to_gp() + value_in_gp);
|
||||||
|
diesel::update(players)
|
||||||
|
.filter(id.eq(self.1))
|
||||||
|
.set(&updated_wealth)
|
||||||
|
.execute(self.0)?;
|
||||||
|
// Difference in coins that is sent back
|
||||||
|
Ok(updated_wealth - current_wealth)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_debt(&self, value_in_gp: i32) -> QueryResult<()> {
|
||||||
|
diesel::update(players::table.find(self.1))
|
||||||
|
.set(players::dsl::debt.eq(players::dsl::debt + value_in_gp))
|
||||||
|
.execute(self.0)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unpack a floating value of gold pieces to integer
|
||||||
/// values of copper, silver, gold and platinum pieces
|
/// values of copper, silver, gold and platinum pieces
|
||||||
///
|
///
|
||||||
/// # Note
|
/// # Note
|
||||||
@@ -28,7 +75,7 @@ pub struct Player {
|
|||||||
/// The conversion is slightly different than standard rules :
|
/// The conversion is slightly different than standard rules :
|
||||||
/// ``` 1pp = 100gp = 1000sp = 10000 cp ```
|
/// ``` 1pp = 100gp = 1000sp = 10000 cp ```
|
||||||
///
|
///
|
||||||
fn unpack_gold_value(gold: f32) -> (i32, i32, i32, i32) {
|
fn unpack_gold_value(gold: f64) -> (i32, i32, i32, i32) {
|
||||||
let rest = (gold.fract() * 100.0).round() as i32;
|
let rest = (gold.fract() * 100.0).round() as i32;
|
||||||
let gold = gold.trunc() as i32;
|
let gold = gold.trunc() as i32;
|
||||||
let pp = gold / 100;
|
let pp = gold / 100;
|
||||||
@@ -42,7 +89,7 @@ fn unpack_gold_value(gold: f32) -> (i32, i32, i32, i32) {
|
|||||||
///
|
///
|
||||||
/// Values are held as individual pieces counts.
|
/// Values are held as individual pieces counts.
|
||||||
/// Allows conversion from and to a floating amount of gold pieces.
|
/// Allows conversion from and to a floating amount of gold pieces.
|
||||||
#[derive(Queryable, AsChangeset, Debug)]
|
#[derive(Queryable, AsChangeset, Serialize, Deserialize, Debug)]
|
||||||
#[table_name = "players"]
|
#[table_name = "players"]
|
||||||
pub struct Wealth {
|
pub struct Wealth {
|
||||||
pub cp: i32,
|
pub cp: i32,
|
||||||
@@ -60,7 +107,7 @@ impl Wealth {
|
|||||||
/// let wealth = Wealth::from_gp(403.21);
|
/// let wealth = Wealth::from_gp(403.21);
|
||||||
/// assert_eq!(wealth.as_tuple(), (1, 2, 3, 4));
|
/// assert_eq!(wealth.as_tuple(), (1, 2, 3, 4));
|
||||||
/// ```
|
/// ```
|
||||||
pub fn from_gp(gp: f32) -> Self {
|
pub fn from_gp(gp: f64) -> Self {
|
||||||
let (cp, sp, gp, pp) = unpack_gold_value(gp);
|
let (cp, sp, gp, pp) = unpack_gold_value(gp);
|
||||||
Self { cp, sp, gp, pp }
|
Self { cp, sp, gp, pp }
|
||||||
}
|
}
|
||||||
@@ -69,13 +116,13 @@ impl Wealth {
|
|||||||
/// # Examples
|
/// # Examples
|
||||||
/// ```
|
/// ```
|
||||||
/// # use lootalot_db::models::Wealth;
|
/// # use lootalot_db::models::Wealth;
|
||||||
/// let wealth = Wealth{ pp: 4, gp: 3, sp: 2, cp: 1};
|
/// let wealth = Wealth{ pp: 4, gp: 5, sp: 8, cp: 4};
|
||||||
/// assert_eq!(wealth.to_gp(), 403.21);
|
/// assert_eq!(wealth.to_gp(), 405.84);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn to_gp(&self) -> f32 {
|
pub fn to_gp(&self) -> f64 {
|
||||||
let i = self.pp * 100 + self.gp;
|
let i = self.pp * 100 + self.gp;
|
||||||
let f = (self.sp * 10 + self.cp) as f32 / 100.0;
|
let f = (self.sp * 10 + self.cp) as f64 / 100.0;
|
||||||
i as f32 + f
|
i as f64 + f
|
||||||
}
|
}
|
||||||
/// Pack the counts inside a tuple, from lower to higher coin value.
|
/// Pack the counts inside a tuple, from lower to higher coin value.
|
||||||
pub fn as_tuple(&self) -> (i32, i32, i32, i32) {
|
pub fn as_tuple(&self) -> (i32, i32, i32, i32) {
|
||||||
@@ -83,6 +130,37 @@ impl Wealth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
use std::ops::Sub;
|
||||||
|
|
||||||
|
impl Sub for Wealth {
|
||||||
|
type Output = Self;
|
||||||
|
/// What needs to be added to 'other' so that
|
||||||
|
/// the result equals 'self'
|
||||||
|
fn sub(self, other: Self) -> Self {
|
||||||
|
Wealth {
|
||||||
|
cp: self.cp - other.cp,
|
||||||
|
sp: self.sp - other.sp,
|
||||||
|
gp: self.gp - other.gp,
|
||||||
|
pp: self.pp - other.pp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use std::ops::Add;
|
||||||
|
|
||||||
|
impl Add for Wealth {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn add(self, other: Self) -> Self {
|
||||||
|
Wealth {
|
||||||
|
cp: self.cp + other.cp,
|
||||||
|
sp: self.sp + other.sp,
|
||||||
|
gp: self.gp + other.gp,
|
||||||
|
pp: self.pp + other.pp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Representation of a new player record
|
/// Representation of a new player record
|
||||||
#[derive(Insertable)]
|
#[derive(Insertable)]
|
||||||
#[table_name = "players"]
|
#[table_name = "players"]
|
||||||
@@ -95,7 +173,7 @@ pub(crate) struct NewPlayer<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> NewPlayer<'a> {
|
impl<'a> NewPlayer<'a> {
|
||||||
pub(crate) fn create(name: &'a str, wealth_in_gp: f32) -> Self {
|
pub(crate) fn create(name: &'a str, wealth_in_gp: f64) -> Self {
|
||||||
let (cp, sp, gp, pp) = Wealth::from_gp(wealth_in_gp).as_tuple();
|
let (cp, sp, gp, pp) = Wealth::from_gp(wealth_in_gp).as_tuple();
|
||||||
Self {
|
Self {
|
||||||
name,
|
name,
|
||||||
@@ -114,12 +192,16 @@ mod tests {
|
|||||||
fn test_unpack_gold_values() {
|
fn test_unpack_gold_values() {
|
||||||
use super::unpack_gold_value;
|
use super::unpack_gold_value;
|
||||||
let test_values = [
|
let test_values = [
|
||||||
|
(0.01, (1, 0, 0, 0)),
|
||||||
|
(0.1, (0, 1, 0, 0)),
|
||||||
(1.0, (0, 0, 1, 0)),
|
(1.0, (0, 0, 1, 0)),
|
||||||
(1.23, (3, 2, 1, 0)),
|
(1.23, (3, 2, 1, 0)),
|
||||||
(1.03, (3, 0, 1, 0)),
|
(1.03, (3, 0, 1, 0)),
|
||||||
(100.23, (3, 2, 0, 1)),
|
(100.23, (3, 2, 0, 1)),
|
||||||
(-100.23, (-3, -2, -0, -1)),
|
(-100.23, (-3, -2, -0, -1)),
|
||||||
(10189.23, (3, 2, 89, 101)),
|
(10189.23, (3, 2, 89, 101)),
|
||||||
|
(141805.9, (0, 9, 5, 1418)),
|
||||||
|
(123141805.9, (0, 9, 5, 1231418)),
|
||||||
(-8090.20, (0, -2, -90, -80)),
|
(-8090.20, (0, -2, -90, -80)),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -40,9 +40,4 @@ joinable!(claims -> looted (loot_id));
|
|||||||
joinable!(claims -> players (player_id));
|
joinable!(claims -> players (player_id));
|
||||||
joinable!(looted -> players (owner_id));
|
joinable!(looted -> players (owner_id));
|
||||||
|
|
||||||
allow_tables_to_appear_in_same_query!(
|
allow_tables_to_appear_in_same_query!(claims, items, looted, players,);
|
||||||
claims,
|
|
||||||
items,
|
|
||||||
looted,
|
|
||||||
players,
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
<template>
|
<template>
|
||||||
<PlayerView
|
<PlayerView
|
||||||
:id="state.player_id"
|
:id="player_id"
|
||||||
v-slot="{ player, loot, notifications, actions }"
|
v-slot="{ player, loot, notifications, actions, claims }"
|
||||||
>
|
>
|
||||||
<main id="app" class="container">
|
<main id="app" class="container">
|
||||||
<header>
|
<header>
|
||||||
<HeaderBar :app_state="state">
|
<HeaderBar>
|
||||||
<template v-slot:title>
|
<template v-slot:title>
|
||||||
{{ player.name }}
|
{{ player.name }}
|
||||||
</template>
|
</template>
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
</template>
|
</template>
|
||||||
<hr class="navbar-divider">
|
<hr class="navbar-divider">
|
||||||
<div class="navbar-item heading">Changer</div>
|
<div class="navbar-item heading">Changer</div>
|
||||||
<a v-for="(p,i) in state.player_list" :key="i"
|
<a v-for="(p,i) in playerList" :key="i"
|
||||||
@click="setActivePlayer(i)"
|
@click="setActivePlayer(i)"
|
||||||
href="#" class="navbar-item">
|
href="#" class="navbar-item">
|
||||||
{{ p.name }}</a>
|
{{ p.name }}</a>
|
||||||
@@ -57,18 +57,22 @@
|
|||||||
<main class="section">
|
<main class="section">
|
||||||
<template v-if="isAdding">
|
<template v-if="isAdding">
|
||||||
<Loot v-if="playerIsGroup"
|
<Loot v-if="playerIsGroup"
|
||||||
:inventory="state.inventory"
|
:inventory="itemsInventory"
|
||||||
@addItem="item => pending_loot.push(item)"
|
@addItem="item => pending_loot.push(item)"
|
||||||
@confirmAction="addNewLoot"
|
@confirmAction="addNewLoot"
|
||||||
></Loot>
|
></Loot>
|
||||||
<AddingChest
|
<AddingChest
|
||||||
:items="playerIsGroup ? pending_loot : state.inventory"
|
:player="player.id"
|
||||||
|
:claims="claims"
|
||||||
|
:items="playerIsGroup ? pending_loot : itemsInShop"
|
||||||
:perms="playerIsGroup ? {} : { canBuy: true }"
|
:perms="playerIsGroup ? {} : { canBuy: true }"
|
||||||
@buy="(data) => { switchView('player'); actions.buyItems(data); }">
|
@buy="(data) => { switchView('player'); actions.buyItems(data); }">
|
||||||
</AddingChest>
|
</AddingChest>
|
||||||
</template>
|
</template>
|
||||||
<Chest v-else
|
<Chest v-else
|
||||||
:items="showPlayerChest ? loot : state.group_loot"
|
:player="player.id"
|
||||||
|
:claims="claims"
|
||||||
|
:items="showPlayerChest ? loot : groupLoot"
|
||||||
:perms="{
|
:perms="{
|
||||||
canGrab: !(showPlayerChest || playerIsGroup),
|
canGrab: !(showPlayerChest || playerIsGroup),
|
||||||
canSell: showPlayerChest || playerIsGroup
|
canSell: showPlayerChest || playerIsGroup
|
||||||
@@ -88,7 +92,7 @@ import HeaderBar from './components/HeaderBar.vue'
|
|||||||
import Wealth from './components/Wealth.vue'
|
import Wealth from './components/Wealth.vue'
|
||||||
import Chest from './components/Chest.vue'
|
import Chest from './components/Chest.vue'
|
||||||
import Loot from './components/Loot.vue'
|
import Loot from './components/Loot.vue'
|
||||||
import { Api, AppStorage } from './AppStorage'
|
import { api } from './lootalot.js'
|
||||||
|
|
||||||
function getCookie(cname) {
|
function getCookie(cname) {
|
||||||
var name = cname + "=";
|
var name = cname + "=";
|
||||||
@@ -110,10 +114,14 @@ export default {
|
|||||||
name: 'app',
|
name: 'app',
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
state: AppStorage.state,
|
player_id: 0,
|
||||||
|
playerList: [],
|
||||||
activeView: 'group',
|
activeView: 'group',
|
||||||
shopInventory: [{id: 1, name: "Item from shop #1", base_price: 2000}],
|
groupLoot: [],
|
||||||
|
itemsInventory: [],
|
||||||
|
itemsInShop: [{id: 1, name: "Item from shop #1", base_price: 2000}],
|
||||||
pending_loot: [],
|
pending_loot: [],
|
||||||
|
initiated: false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
components: {
|
components: {
|
||||||
@@ -125,21 +133,26 @@ export default {
|
|||||||
Loot,
|
Loot,
|
||||||
},
|
},
|
||||||
created () {
|
created () {
|
||||||
// Initiate with active player set to value found in cookie
|
|
||||||
// or as group by default.
|
|
||||||
const cookie = getCookie("player_id");
|
const cookie = getCookie("player_id");
|
||||||
let playerId;
|
this.player_id = cookie ? Number(cookie) : 0;
|
||||||
if (cookie == "") {
|
Promise.all([
|
||||||
playerId = 0;
|
api.fetch("players/", "GET", null),
|
||||||
} else {
|
api.fetch("players/0/loot", "GET", null),
|
||||||
playerId = Number(cookie);
|
api.fetch("items", "GET", null),
|
||||||
}
|
])
|
||||||
AppStorage.initStorage(playerId);
|
.then(([players, loot, items]) => {
|
||||||
|
this.playerList = players.value;
|
||||||
|
this.groupLoot = loot.value;
|
||||||
|
this.itemsInventory = items.value;
|
||||||
|
})
|
||||||
|
.catch(r => alert("Error ! \n" + r))
|
||||||
|
.then(() => this.initiated = true);
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
setActivePlayer (idx) {
|
setActivePlayer (idx) {
|
||||||
if (idx == 0) this.switchView('group');
|
if (idx == 0) this.switchView('group');
|
||||||
AppStorage.setActivePlayer(idx);
|
this.player_id = Number(idx)
|
||||||
|
document.cookie = `player_id=${idx};`;
|
||||||
},
|
},
|
||||||
switchView (viewId) {
|
switchView (viewId) {
|
||||||
if (!['group', 'player', 'adding'].includes(viewId)) {
|
if (!['group', 'player', 'adding'].includes(viewId)) {
|
||||||
@@ -147,21 +160,19 @@ export default {
|
|||||||
}
|
}
|
||||||
this.activeView = viewId;
|
this.activeView = viewId;
|
||||||
},
|
},
|
||||||
switchPlayerChestVisibility () {
|
|
||||||
AppStorage.switchPlayerChestVisibility();
|
|
||||||
},
|
|
||||||
addNewLoot () {
|
addNewLoot () {
|
||||||
Api.newLoot(this.pending_loot)
|
api.fetch("admin/add-loot", "POST", this.pending_loot)
|
||||||
.then(_ => {
|
.then(() => {
|
||||||
this.pending_loot = []
|
this.pending_loot = []
|
||||||
this.switchView('group');
|
this.switchView('group');
|
||||||
});
|
})
|
||||||
|
.catch(r => alert("Error: " + r));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
showPlayerChest () { return this.activeView == 'player' },
|
showPlayerChest () { return this.activeView == 'player' },
|
||||||
isAdding () { return this.activeView == 'adding' },
|
isAdding () { return this.activeView == 'adding' },
|
||||||
playerIsGroup () { return this.state.player_id == 0 },
|
playerIsGroup () { return this.player_id == 0 },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,175 +0,0 @@
|
|||||||
import Vue from 'vue'
|
|
||||||
|
|
||||||
const API_BASEURL = "http://localhost:8088/api/"
|
|
||||||
const API_ENDPOINT = function (tailString) {
|
|
||||||
return API_BASEURL + tailString;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const Api = {
|
|
||||||
__doFetch (endpoint, method, payload) {
|
|
||||||
return fetch(API_ENDPOINT(endpoint),
|
|
||||||
{
|
|
||||||
method,
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload)
|
|
||||||
})
|
|
||||||
.then(r => r.json())
|
|
||||||
},
|
|
||||||
fetchPlayerList () {
|
|
||||||
return fetch(API_ENDPOINT("players/all"))
|
|
||||||
.then(r => r.json())
|
|
||||||
},
|
|
||||||
fetchInventory () {
|
|
||||||
return fetch(API_ENDPOINT("items"))
|
|
||||||
.then(r => r.json())
|
|
||||||
},
|
|
||||||
fetchClaims () {
|
|
||||||
return fetch(API_ENDPOINT("claims"))
|
|
||||||
.then(r => r.json())
|
|
||||||
},
|
|
||||||
fetchLoot (playerId) {
|
|
||||||
return fetch(API_ENDPOINT("players/loot/" + playerId))
|
|
||||||
.then(r => r.json())
|
|
||||||
},
|
|
||||||
putClaim (player_id, item_id) {
|
|
||||||
const payload = { player_id, item_id };
|
|
||||||
return this.__doFetch("claims", 'PUT', payload);
|
|
||||||
},
|
|
||||||
unClaim (player_id, item_id) {
|
|
||||||
const payload = { player_id, item_id };
|
|
||||||
return this.__doFetch("claims", 'DELETE', payload);
|
|
||||||
},
|
|
||||||
updateWealth (player_id, value_in_gp) {
|
|
||||||
const payload = { player_id, value_in_gp: Number(value_in_gp) };
|
|
||||||
return this.__doFetch("players/update-wealth", 'PUT', payload);
|
|
||||||
},
|
|
||||||
buyItems (player_id, items) {
|
|
||||||
const payload = { player_id, items };
|
|
||||||
return this.__doFetch("players/buy", 'POST', payload);
|
|
||||||
},
|
|
||||||
sellItems (player_id, items) {
|
|
||||||
const payload = { player_id, items };
|
|
||||||
return this.__doFetch("players/sell", 'POST', payload);
|
|
||||||
},
|
|
||||||
newLoot (items) {
|
|
||||||
return this.__doFetch("admin/add-loot", 'POST', items);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
export const AppStorage = {
|
|
||||||
debug: true,
|
|
||||||
state: {
|
|
||||||
player_id: 0,
|
|
||||||
player_list: {},
|
|
||||||
group_loot: [],
|
|
||||||
player_claims: {},
|
|
||||||
inventory: [],
|
|
||||||
initiated: false,
|
|
||||||
show_player_chest: false,
|
|
||||||
},
|
|
||||||
// Initiate the state
|
|
||||||
initStorage (playerId) {
|
|
||||||
if (this.debug) console.log('Initiates with player : ', playerId)
|
|
||||||
this.state.player_id = playerId;
|
|
||||||
// Fetch initial data
|
|
||||||
return Promise
|
|
||||||
.all([
|
|
||||||
Api.fetchPlayerList(),
|
|
||||||
Api.fetchClaims(),
|
|
||||||
Api.fetchInventory(),
|
|
||||||
Api.fetchLoot(0)
|
|
||||||
])
|
|
||||||
.then(data => {
|
|
||||||
const [players, claims, inventory, group_loot] = data;
|
|
||||||
this.__initPlayerList(players);
|
|
||||||
this.__initClaimsStore(claims);
|
|
||||||
Vue.set(this.state, 'group_loot', group_loot);
|
|
||||||
Vue.set(this.state, 'inventory', inventory);
|
|
||||||
})
|
|
||||||
.then(_ => this.state.initiated = true)
|
|
||||||
.catch(e => { alert(e); this.state.initiated = false });
|
|
||||||
},
|
|
||||||
__initClaimsStore(data) {
|
|
||||||
for (var idx in data) {
|
|
||||||
var claimDesc = data[idx];
|
|
||||||
this.state.player_claims[claimDesc.player_id].push(claimDesc.loot_id);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
__initPlayerList(data) {
|
|
||||||
for (var idx in data) {
|
|
||||||
var playerDesc = data[idx];
|
|
||||||
const playerId = Number(playerDesc.id);
|
|
||||||
if (this.debug) console.log("Creates", playerId, playerDesc.name)
|
|
||||||
// Initiate data for a single Player.
|
|
||||||
Vue.set(this.state.player_list, playerId, playerDesc);
|
|
||||||
Vue.set(this.state.player_claims, playerId, []);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// User actions
|
|
||||||
// Sets a new active player by id
|
|
||||||
setActivePlayer (newPlayerId) {
|
|
||||||
if (this.debug) console.log('setActivePlayer to ', newPlayerId)
|
|
||||||
this.state.player_id = Number(newPlayerId)
|
|
||||||
document.cookie = `player_id=${newPlayerId};`;
|
|
||||||
},
|
|
||||||
// Show/Hide player's chest
|
|
||||||
switchPlayerChestVisibility () {
|
|
||||||
if (this.debug) console.log('switchPlayerChestVisibility', !this.state.show_player_chest)
|
|
||||||
this.state.show_player_chest = !this.state.show_player_chest
|
|
||||||
},
|
|
||||||
updatePlayerWealth (goldValue) {
|
|
||||||
return Api.updateWealth(this.state.player_id, goldValue)
|
|
||||||
.then(diff => this.__updatePlayerWealth(diff));
|
|
||||||
},
|
|
||||||
// TODO: Weird private name denotes a conflict
|
|
||||||
__updatePlayerWealth (diff) {
|
|
||||||
if (this.debug) console.log('updatePlayerWealth', diff)
|
|
||||||
this.state.player_list[this.state.player_id].cp += diff[0];
|
|
||||||
this.state.player_list[this.state.player_id].sp += diff[1];
|
|
||||||
this.state.player_list[this.state.player_id].gp += diff[2];
|
|
||||||
this.state.player_list[this.state.player_id].pp += diff[3];
|
|
||||||
},
|
|
||||||
// Put a claim on an item from group chest.
|
|
||||||
putRequest (itemId) {
|
|
||||||
const playerId = this.state.player_id
|
|
||||||
return Api.putClaim(playerId, itemId)
|
|
||||||
.then(done => {
|
|
||||||
// Update cliend-side state
|
|
||||||
this.state.player_claims[playerId].push(itemId);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
buyItems (items) {
|
|
||||||
return Api.buyItems(this.state.player_id, items)
|
|
||||||
.then(([items, diff]) => {
|
|
||||||
this.__updatePlayerWealth(diff)
|
|
||||||
// Add items to the player loot
|
|
||||||
// TODO: needs refactoring because player mutation happens in
|
|
||||||
// 2 different places
|
|
||||||
return items;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
sellItems (items) {
|
|
||||||
return Api.sellItems(this.state.player_id, items)
|
|
||||||
.then(diff => this.__updatePlayerWealth(diff))
|
|
||||||
},
|
|
||||||
// Withdraws a claim.
|
|
||||||
cancelRequest(itemId) {
|
|
||||||
const playerId = this.state.player_id
|
|
||||||
return Api.unClaim(playerId, itemId)
|
|
||||||
.then(_ => {
|
|
||||||
var idx = this.state.player_claims[playerId].indexOf(itemId);
|
|
||||||
if (idx > -1) {
|
|
||||||
this.state.player_claims[playerId].splice(idx, 1);
|
|
||||||
} else {
|
|
||||||
if (this.debug) console.log("cancel a non-existent request")
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
addNewLoot (items) {
|
|
||||||
return Api.newLoot(items);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -47,6 +47,8 @@
|
|||||||
<td>
|
<td>
|
||||||
<Request
|
<Request
|
||||||
v-if="perms.canGrab"
|
v-if="perms.canGrab"
|
||||||
|
:id="player"
|
||||||
|
:claims="claims"
|
||||||
:item="item.id"
|
:item="item.id"
|
||||||
@claim="(data) => $emit('claim', data)"
|
@claim="(data) => $emit('claim', data)"
|
||||||
@unclaim="(data) => $emit('unclaim', data)"
|
@unclaim="(data) => $emit('unclaim', data)"
|
||||||
@@ -68,6 +70,7 @@
|
|||||||
import Request from './Request.vue'
|
import Request from './Request.vue'
|
||||||
import PercentInput from './PercentInput.vue'
|
import PercentInput from './PercentInput.vue'
|
||||||
import Selector from './Selector.vue'
|
import Selector from './Selector.vue'
|
||||||
|
import { api } from '../lootalot.js'
|
||||||
/*
|
/*
|
||||||
The chest displays a collection of items.
|
The chest displays a collection of items.
|
||||||
|
|
||||||
@@ -77,6 +80,10 @@
|
|||||||
*/
|
*/
|
||||||
export default {
|
export default {
|
||||||
props: {
|
props: {
|
||||||
|
player: {
|
||||||
|
type: Number,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
items: {
|
items: {
|
||||||
type: Array,
|
type: Array,
|
||||||
required: true,
|
required: true,
|
||||||
@@ -85,6 +92,10 @@
|
|||||||
type: Object,
|
type: Object,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
|
claims: {
|
||||||
|
type: Object,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
components: {
|
components: {
|
||||||
Request,
|
Request,
|
||||||
|
|||||||
@@ -1,70 +1,94 @@
|
|||||||
import { Api, AppStorage } from '../AppStorage'
|
import { api } from '../lootalot.js'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
props: ["id"],
|
props: ["id"],
|
||||||
data () { return {
|
data () { return {
|
||||||
|
player: {
|
||||||
|
name: "Loading",
|
||||||
|
id: 0,
|
||||||
|
cp: '-', sp: '-', gp: '-', pp: '-',
|
||||||
|
debt: 0,
|
||||||
|
},
|
||||||
notifications: [],
|
notifications: [],
|
||||||
loot: [],
|
loot: [],
|
||||||
|
claims: {},
|
||||||
}},
|
}},
|
||||||
methods: {
|
created () {
|
||||||
updateWealth (value) {
|
api.fetch("claims", "GET", null)
|
||||||
AppStorage.updatePlayerWealth(value)
|
.then(r => {
|
||||||
.then(_ => {if (AppStorage.debug) this.notifications.push("Wealth updated")})
|
for (var idx in r.value) {
|
||||||
.catch(e => {if (AppStorage.debug) console.error("wealthUpdate Error", e)})
|
var claim = r.value[idx];
|
||||||
},
|
if (!(claim.player_id in this.claims)) {
|
||||||
putClaim (itemId) {
|
this.$set(this.claims, claim.player_id, []);
|
||||||
AppStorage.putRequest(itemId)
|
}
|
||||||
.then(_ => { if (AppStorage.debug) this.notifications.push("Claim put")})
|
this.claims[claim.player_id].push(claim.loot_id);
|
||||||
},
|
|
||||||
withdrawClaim (itemId) {
|
|
||||||
AppStorage.cancelRequest(itemId)
|
|
||||||
.then(_ => { if (AppStorage.debug) this.notifications.push("Claim withdrawn")})
|
|
||||||
|
|
||||||
},
|
|
||||||
buyItems(items) {
|
|
||||||
AppStorage.buyItems(items)
|
|
||||||
.then((items) => {
|
|
||||||
this.notifications.push(`Bought ${items.length} items`)
|
|
||||||
this.loot = this.loot.concat(items);
|
|
||||||
})
|
|
||||||
},
|
|
||||||
sellItems (items) {
|
|
||||||
AppStorage.sellItems(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) {
|
|
||||||
this.loot = [];
|
|
||||||
items.map(item => {
|
|
||||||
this.loot.push(item);
|
|
||||||
});
|
});
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
parseUpdate (update) {
|
||||||
|
if (update.Wealth) {
|
||||||
|
var w = update.Wealth;
|
||||||
|
this.player.cp += w.cp;
|
||||||
|
this.player.sp += w.sp;
|
||||||
|
this.player.gp += w.gp;
|
||||||
|
this.player.pp += w.pp;
|
||||||
}
|
}
|
||||||
|
else if (update.ItemAdded) {
|
||||||
|
var i = update.ItemAdded;
|
||||||
|
this.loot.push(i);
|
||||||
|
}
|
||||||
|
else if (update.ItemRemoved) {
|
||||||
|
var i = update.ItemRemoved;
|
||||||
|
this.loot.splice(this.loot.indexOf(i), 1);
|
||||||
|
}
|
||||||
|
else if (update.ClaimAdded) {
|
||||||
|
var c = update.ClaimAdded;
|
||||||
|
this.claims[c.player_id].push(c.loot_id);
|
||||||
|
}
|
||||||
|
else if (update.ClaimRemoved) {
|
||||||
|
var c = update.ClaimRemoved;
|
||||||
|
this.claims[c.player_id].splice(
|
||||||
|
this.claims[c.player_id].indexOf(c.loot_id),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
call (resource, method, payload) {
|
||||||
|
return api.fetch(`players/${this.id}/${resource}`, method, payload)
|
||||||
|
.then(response => {
|
||||||
|
if (response.notification) {
|
||||||
|
this.notifications.push(response.notification)
|
||||||
|
}
|
||||||
|
if (response.errors) {
|
||||||
|
this.notifications.push(response.errors)
|
||||||
|
}
|
||||||
|
if (response.updates) {
|
||||||
|
for (var idx in response.updates) {
|
||||||
|
this.parseUpdate(response.updates[idx]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return response.value;
|
||||||
|
})
|
||||||
|
},
|
||||||
|
updateWealth (value) { this.call("wealth", "PUT", Number(value)) },
|
||||||
|
putClaim (itemId) { this.call("claims", "PUT", itemId) },
|
||||||
|
withdrawClaim (itemId) { this.call("claims", "DELETE", itemId) },
|
||||||
|
buyItems(items) { this.call("loot", "PUT", items) },
|
||||||
|
sellItems (items) { this.call("loot", "DELETE", items) },
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
id: {
|
id: {
|
||||||
immediate: true,
|
immediate: true,
|
||||||
handler: function(newId) {
|
handler: function(newId) {
|
||||||
Api.fetchLoot(newId).then(this.parseLoot);
|
this.call("", "GET", null)
|
||||||
}
|
.then(p => this.player = p)
|
||||||
},
|
this.call("loot", "GET", null)
|
||||||
},
|
.then(l => this.loot = l)
|
||||||
computed: {
|
|
||||||
player () {
|
|
||||||
if (!AppStorage.state.initiated) {
|
|
||||||
return { name: "Loading",
|
|
||||||
id: 0,
|
|
||||||
cp: '-', sp: '-', gp: '-', pp: '-',
|
|
||||||
debt: 0 };
|
|
||||||
} else {
|
|
||||||
return AppStorage.state.player_list[this.id];
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
computed: {},
|
||||||
render () {
|
render () {
|
||||||
return this.$scopedSlots.default({
|
return this.$scopedSlots.default({
|
||||||
player: this.player,
|
player: this.player,
|
||||||
@@ -76,7 +100,8 @@ export default {
|
|||||||
withdrawClaim: this.withdrawClaim,
|
withdrawClaim: this.withdrawClaim,
|
||||||
buyItems: this.buyItems,
|
buyItems: this.buyItems,
|
||||||
sellItems: this.sellItems,
|
sellItems: this.sellItems,
|
||||||
}
|
},
|
||||||
|
claims: this.claims,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
</template>
|
</template>
|
||||||
<button class="button is-primary is-fullwidth"
|
<button class="button is-primary"
|
||||||
@click="putRequest"
|
@click="putRequest"
|
||||||
:disabled="isRequested">
|
:disabled="isRequested">
|
||||||
<span class="icon is-small">
|
<span class="icon is-small">
|
||||||
@@ -25,28 +25,41 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import { AppStorage } from '../AppStorage'
|
|
||||||
export default {
|
export default {
|
||||||
props: ["item"],
|
props: {
|
||||||
data () {
|
// Id of active player
|
||||||
return AppStorage.state;
|
id: {
|
||||||
|
type: Number,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
// Map of all claims
|
||||||
|
claims: {
|
||||||
|
type: Object,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
// Id of item we are bound to
|
||||||
|
item: {
|
||||||
|
type: Number,
|
||||||
|
required: true,
|
||||||
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
// Check if item is requested by active player
|
// Check if item is requested by active player
|
||||||
isRequested () {
|
isRequested () {
|
||||||
const reqs = this.player_claims[this.player_id];
|
if (this.claims[this.id]) {
|
||||||
return reqs.includes(this.item);
|
return this.claims[this.id].includes(this.item);
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
// Check if item is requested by multiple players including active one
|
// Check if item is requested by multiple players including active one
|
||||||
isInConflict () {
|
isInConflict () {
|
||||||
const reqs = this.player_claims;
|
|
||||||
const playerId = this.player_id;
|
|
||||||
var reqByPlayer = false;
|
var reqByPlayer = false;
|
||||||
var reqByOther = false;
|
var reqByOther = false;
|
||||||
for (var key in reqs) {
|
for (var id in this.claims) {
|
||||||
const isReq = reqs[key].includes(this.item);
|
const isReq = this.claims[id].includes(this.item);
|
||||||
if (isReq) {
|
if (isReq) {
|
||||||
if (key == playerId) {
|
if (id == this.id) {
|
||||||
reqByPlayer = true;
|
reqByPlayer = true;
|
||||||
} else {
|
} else {
|
||||||
reqByOther = true;
|
reqByOther = true;
|
||||||
|
|||||||
20
lootalot_front/src/lootalot.js
Normal file
20
lootalot_front/src/lootalot.js
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
const API_BASEURL = "http://localhost:8088/api/"
|
||||||
|
const API_ENDPOINT = function (tailString) {
|
||||||
|
return API_BASEURL + tailString;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
fetch: function(endpoint, method, payload) {
|
||||||
|
var config = {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (payload) {
|
||||||
|
config.body = JSON.stringify(payload);
|
||||||
|
}
|
||||||
|
return fetch(API_ENDPOINT(endpoint), config)
|
||||||
|
.then(r => r.json());
|
||||||
|
}
|
||||||
|
}
|
||||||
184
src/api.rs
Normal file
184
src/api.rs
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
use lootalot_db::{self as db, DbConnection, QueryResult};
|
||||||
|
|
||||||
|
/// Every possible update which can happen during a query
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
pub enum Update {
|
||||||
|
Wealth(db::Wealth),
|
||||||
|
ItemAdded(db::Item),
|
||||||
|
ItemRemoved(db::Item),
|
||||||
|
ClaimAdded(db::Claim),
|
||||||
|
ClaimRemoved(db::Claim),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every value which can be queried
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Value {
|
||||||
|
Player(db::Player),
|
||||||
|
Item(db::Item),
|
||||||
|
Claim(db::Claim),
|
||||||
|
ItemList(Vec<db::Item>),
|
||||||
|
ClaimList(Vec<db::Claim>),
|
||||||
|
PlayerList(Vec<db::Player>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl serde::Serialize for Value {
|
||||||
|
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||||
|
match self {
|
||||||
|
Value::Player(v) => v.serialize(serializer),
|
||||||
|
Value::Item(v) => v.serialize(serializer),
|
||||||
|
Value::Claim(v) => v.serialize(serializer),
|
||||||
|
Value::ItemList(v) => v.serialize(serializer),
|
||||||
|
Value::ClaimList(v) => v.serialize(serializer),
|
||||||
|
Value::PlayerList(v) => v.serialize(serializer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A generic response for all queries
|
||||||
|
#[derive(Serialize, Debug, Default)]
|
||||||
|
pub struct ApiResponse {
|
||||||
|
/// The value requested, if any
|
||||||
|
pub value: Option<Value>,
|
||||||
|
/// A text to notify user, if relevant
|
||||||
|
pub notification: Option<String>,
|
||||||
|
/// A list of updates, if any
|
||||||
|
pub updates: Option<Vec<Update>>,
|
||||||
|
/// A text describing errors, if any
|
||||||
|
pub errors: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiResponse {
|
||||||
|
fn push_update(&mut self, update: Update) {
|
||||||
|
if let Some(v) = self.updates.as_mut() {
|
||||||
|
v.push(update);
|
||||||
|
} else {
|
||||||
|
self.updates = Some(vec![update]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_error<S: Into<String>>(&mut self, error: S) {
|
||||||
|
if let Some(errors) = self.errors.as_mut() {
|
||||||
|
*errors = format!("{}\n{}", errors, error.into());
|
||||||
|
} else {
|
||||||
|
self.errors = Some(error.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_value(&mut self, value: Value) {
|
||||||
|
self.value = Some(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn notify<S: Into<String>>(&mut self, text: S) {
|
||||||
|
self.notification = Some(text.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum ApiError {
|
||||||
|
DieselError(diesel::result::Error),
|
||||||
|
InvalidAction(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every allowed queries on the database
|
||||||
|
pub enum ApiActions {
|
||||||
|
FetchPlayers,
|
||||||
|
FetchInventory,
|
||||||
|
FetchClaims,
|
||||||
|
// Player actions
|
||||||
|
FetchPlayer(i32),
|
||||||
|
FetchLoot(i32),
|
||||||
|
UpdateWealth(i32, f64),
|
||||||
|
BuyItems(i32, Vec<(i32, Option<f64>)>),
|
||||||
|
SellItems(i32, Vec<(i32, Option<f64>)>),
|
||||||
|
ClaimItem(i32, i32),
|
||||||
|
UnclaimItem(i32, i32),
|
||||||
|
// Group actions
|
||||||
|
AddLoot(Vec<db::Item>),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum AdminActions {
|
||||||
|
AddPlayer(String, f64),
|
||||||
|
//AddInventoryItem(pub String, pub i32),
|
||||||
|
ResolveClaims,
|
||||||
|
//SetClaimsTimeout(pub i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn execute(
|
||||||
|
conn: &DbConnection,
|
||||||
|
query: ApiActions,
|
||||||
|
) -> Result<ApiResponse, diesel::result::Error> {
|
||||||
|
let mut response = ApiResponse::default();
|
||||||
|
match query {
|
||||||
|
ApiActions::FetchPlayers => {
|
||||||
|
response.set_value(Value::PlayerList(db::Players(conn).all()?));
|
||||||
|
}
|
||||||
|
ApiActions::FetchInventory => {
|
||||||
|
response.set_value(Value::ItemList(db::Inventory(conn).all()?));
|
||||||
|
}
|
||||||
|
ApiActions::FetchClaims => {
|
||||||
|
response.set_value(Value::ClaimList(db::fetch_claims(conn)?));
|
||||||
|
}
|
||||||
|
ApiActions::FetchPlayer(id) => {
|
||||||
|
response.set_value(Value::Player(db::Players(conn).find(id)?));
|
||||||
|
}
|
||||||
|
ApiActions::FetchLoot(id) => {
|
||||||
|
response.set_value(Value::ItemList(db::LootManager(conn, id).all()?));
|
||||||
|
}
|
||||||
|
ApiActions::UpdateWealth(id, amount) => {
|
||||||
|
response.push_update(Update::Wealth(
|
||||||
|
db::AsPlayer(conn, id).update_wealth(amount)?,
|
||||||
|
));
|
||||||
|
response.notify(format!("Mis à jour ({}po)!", amount));
|
||||||
|
}
|
||||||
|
ApiActions::BuyItems(id, params) => {
|
||||||
|
let mut cumulated_diff: Vec<db::Wealth> = Vec::with_capacity(params.len());
|
||||||
|
let mut added_items: u16 = 0;
|
||||||
|
for (item_id, price_mod) in params.into_iter() {
|
||||||
|
if let Ok((item, diff)) = db::buy_item_from_inventory(conn, id, item_id, price_mod) {
|
||||||
|
cumulated_diff.push(diff);
|
||||||
|
response.push_update(Update::ItemAdded(item));
|
||||||
|
added_items += 1;
|
||||||
|
} else {
|
||||||
|
response.push_error(format!("Error adding {}", item_id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let total_amount = cumulated_diff
|
||||||
|
.into_iter()
|
||||||
|
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
||||||
|
response.notify(format!("{} objets achetés pour {}po", added_items, total_amount.to_gp()));
|
||||||
|
response.push_update(Update::Wealth(total_amount));
|
||||||
|
}
|
||||||
|
ApiActions::SellItems(id, params) => {
|
||||||
|
let mut all_results: Vec<db::Wealth> = Vec::with_capacity(params.len());
|
||||||
|
let mut sold_items: u16 = 0;
|
||||||
|
for (loot_id, price_mod) in params.into_iter() {
|
||||||
|
if let Ok((deleted, diff)) = db::sell_item_transaction(conn, id, loot_id, price_mod) {
|
||||||
|
all_results.push(diff);
|
||||||
|
response.push_update(Update::ItemRemoved(deleted));
|
||||||
|
sold_items += 1;
|
||||||
|
} else {
|
||||||
|
response.push_error(format!("Error selling {}", loot_id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let total_amount = all_results
|
||||||
|
.into_iter()
|
||||||
|
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
||||||
|
response.notify(format!("{} objet(s) vendu(s) pour {} po", sold_items, total_amount.to_gp()));
|
||||||
|
response.push_update(Update::Wealth(total_amount));
|
||||||
|
}
|
||||||
|
ApiActions::ClaimItem(id, item) => {
|
||||||
|
response.push_update(Update::ClaimAdded(
|
||||||
|
db::Claims(conn).add(id, item)?,
|
||||||
|
));
|
||||||
|
response.notify(format!("Pour moi !"));
|
||||||
|
}
|
||||||
|
ApiActions::UnclaimItem(id, item) => {
|
||||||
|
response.push_update(Update::ClaimRemoved(
|
||||||
|
db::Claims(conn).remove(id, item)?,
|
||||||
|
));
|
||||||
|
response.notify(format!("Bof! Finalement non."));
|
||||||
|
}
|
||||||
|
// Group actions
|
||||||
|
ApiActions::AddLoot(items) => {}
|
||||||
|
}
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
@@ -2,9 +2,10 @@ extern crate actix_web;
|
|||||||
extern crate dotenv;
|
extern crate dotenv;
|
||||||
extern crate env_logger;
|
extern crate env_logger;
|
||||||
extern crate lootalot_db;
|
extern crate lootalot_db;
|
||||||
extern crate serde;
|
#[macro_use] extern crate serde;
|
||||||
|
|
||||||
mod server;
|
mod server;
|
||||||
|
mod api;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
std::env::set_var("RUST_LOG", "actix_web=info");
|
std::env::set_var("RUST_LOG", "actix_web=info");
|
||||||
|
|||||||
247
src/server.rs
247
src/server.rs
@@ -1,49 +1,26 @@
|
|||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
use actix_files as fs;
|
use actix_files as fs;
|
||||||
use actix_web::{web, App, Error, HttpResponse, HttpServer};
|
use actix_web::{web, middleware, App, Error, HttpResponse, HttpServer};
|
||||||
use futures::Future;
|
use futures::Future;
|
||||||
use lootalot_db::{DbApi, Pool, QueryResult};
|
|
||||||
use lootalot_db::models::Item;
|
|
||||||
use std::env;
|
use std::env;
|
||||||
use serde::{Serialize, Deserialize};
|
|
||||||
|
|
||||||
type AppPool = web::Data<Pool>;
|
use lootalot_db as db;
|
||||||
|
use crate::api;
|
||||||
|
|
||||||
/// Wraps call to the DbApi and process its result as a async HttpResponse
|
type AppPool = web::Data<db::Pool>;
|
||||||
///
|
type PlayerId = web::Path<i32>;
|
||||||
/// Provides a convenient way to call the api inside a route definition. Given a connection pool,
|
type ItemId = web::Json<i32>;
|
||||||
/// access to the api is granted in a closure. The closure is called in a blocking way and should
|
type ItemListWithMods = web::Json<Vec<(i32, Option<f64>)>>;
|
||||||
/// return a QueryResult.
|
|
||||||
/// If the query succeeds, it's result is returned as JSON data. Otherwise, an InternalServerError
|
/// Wraps call to the database query and convert its result as a async HttpResponse
|
||||||
/// is returned.
|
pub fn db_call(
|
||||||
///
|
|
||||||
/// # Usage
|
|
||||||
/// ```
|
|
||||||
/// (...)
|
|
||||||
/// .route("path/to/",
|
|
||||||
/// move |pool: web::Data<Pool>| {
|
|
||||||
/// // user data can be processed here
|
|
||||||
/// // ...
|
|
||||||
/// db_call(pool, move |api| {
|
|
||||||
/// // ...do what you want with the api
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// )
|
|
||||||
/// ```
|
|
||||||
pub fn db_call<J,Q>(
|
|
||||||
pool: AppPool,
|
pool: AppPool,
|
||||||
query: Q,
|
query: api::ApiActions,
|
||||||
) -> impl Future<Item=HttpResponse, Error=Error>
|
) -> impl Future<Item = HttpResponse, Error = Error>
|
||||||
where J: serde::ser::Serialize + Send + 'static,
|
|
||||||
Q: Fn(DbApi) -> QueryResult<J> + Send + 'static,
|
|
||||||
{
|
{
|
||||||
let conn = pool.get().unwrap();
|
let conn = pool.get().unwrap();
|
||||||
web::block(move || {
|
web::block(move || api::execute(&conn, query)).then(|res| match res {
|
||||||
let api = DbApi::with_conn(&conn);
|
Ok(r) => HttpResponse::Ok().json(r),
|
||||||
query(api)
|
|
||||||
})
|
|
||||||
.then(|res| match res {
|
|
||||||
Ok(players) => HttpResponse::Ok().json(players),
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
dbg!(&e);
|
dbg!(&e);
|
||||||
HttpResponse::InternalServerError().finish()
|
HttpResponse::InternalServerError().finish()
|
||||||
@@ -51,142 +28,94 @@ pub fn db_call<J,Q>(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
fn configure_app(config: &mut web::ServiceConfig) {
|
||||||
struct PlayerClaim {
|
use api::ApiActions as Q;
|
||||||
player_id: i32,
|
config.service(
|
||||||
item_id: i32,
|
web::scope("/api")
|
||||||
|
.service(
|
||||||
|
web::scope("/players")
|
||||||
|
.service(
|
||||||
|
web::resource("/").route(
|
||||||
|
web::get().to_async(|pool| db_call(pool, Q::FetchPlayers)),
|
||||||
|
), //.route(web::post().to_async(endpoints::new_player))
|
||||||
|
) // List of players
|
||||||
|
.service(
|
||||||
|
web::scope("/{player_id}")
|
||||||
|
.route("/", web::get().to_async(|pool, player: PlayerId| {
|
||||||
|
db_call(pool, Q::FetchPlayer(*player))
|
||||||
|
}))
|
||||||
|
.service(
|
||||||
|
web::resource("/claims")
|
||||||
|
//.route(web::get().to_async(endpoints::player_claims))
|
||||||
|
.route(web::put().to_async(
|
||||||
|
|pool, (player, data): (PlayerId, ItemId)| {
|
||||||
|
db_call(pool, Q::ClaimItem(*player, *data))
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.route(web::delete().to_async(
|
||||||
|
|pool, (player, data): (PlayerId, ItemId)| {
|
||||||
|
db_call(
|
||||||
|
pool,
|
||||||
|
Q::UnclaimItem(*player, *data),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
.service(
|
||||||
|
web::resource("/wealth")
|
||||||
|
//.route(web::get().to_async(...))
|
||||||
|
.route(web::put().to_async(
|
||||||
|
|pool, (player, data): (PlayerId, web::Json<f64>)| {
|
||||||
|
db_call(
|
||||||
|
pool,
|
||||||
|
Q::UpdateWealth(*player, *data),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
.service(
|
||||||
|
web::resource("/loot")
|
||||||
|
.route(web::get().to_async(|pool, player: PlayerId| {
|
||||||
|
db_call(pool, Q::FetchLoot(*player))
|
||||||
|
}))
|
||||||
|
.route(web::put().to_async(
|
||||||
|
move |pool, (player, data): (PlayerId, ItemListWithMods)| {
|
||||||
|
db_call(pool, Q::BuyItems(*player, data.into_inner()))
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.route(web::delete().to_async(
|
||||||
|
move |pool, (player, data): (PlayerId, ItemListWithMods)| {
|
||||||
|
db_call(pool, Q::SellItems(*player, data.into_inner()))
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.route("/claims", web::get().to_async(|pool| db_call(pool, Q::FetchClaims)))
|
||||||
|
.route(
|
||||||
|
"/items",
|
||||||
|
web::get()
|
||||||
|
.to_async(move |pool: AppPool| db_call(pool, Q::FetchInventory)),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
pub fn serve() -> std::io::Result<()> {
|
||||||
struct WealthUpdate {
|
|
||||||
player_id: i32,
|
|
||||||
value_in_gp: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
|
||||||
struct NewPlayer {
|
|
||||||
name: String,
|
|
||||||
wealth: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
|
||||||
struct LootUpdate {
|
|
||||||
player_id: i32,
|
|
||||||
items: Vec<(i32, Option<f32>)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn serve() -> std::io::Result<()> {
|
|
||||||
let www_root: String = env::var("WWW_ROOT").expect("WWW_ROOT must be set");
|
let www_root: String = env::var("WWW_ROOT").expect("WWW_ROOT must be set");
|
||||||
|
let pool = db::create_pool();
|
||||||
dbg!(&www_root);
|
dbg!(&www_root);
|
||||||
let pool = lootalot_db::create_pool();
|
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.data(pool.clone())
|
.data(pool.clone())
|
||||||
|
.configure(configure_app)
|
||||||
.wrap(
|
.wrap(
|
||||||
Cors::new()
|
Cors::new()
|
||||||
.allowed_origin("http://localhost:8080")
|
.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),
|
||||||
)
|
)
|
||||||
.service(
|
.wrap(middleware::Logger::default())
|
||||||
web::scope("/api")
|
|
||||||
.route("/items", web::get().to_async(move |pool: AppPool| {
|
|
||||||
db_call(pool, move |api| api.fetch_inventory())
|
|
||||||
}))
|
|
||||||
.service(
|
|
||||||
web::scope("/players")
|
|
||||||
.route(
|
|
||||||
"/all",
|
|
||||||
web::get().to_async(move |pool: AppPool| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.fetch_players())
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/loot/{player_id}",
|
|
||||||
web::get().to_async(move |pool: AppPool, player_id: web::Path<i32>| {
|
|
||||||
db_call(pool, move |api| api.as_player(*player_id).loot())
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/update-wealth",
|
|
||||||
web::put().to_async(move |pool: AppPool, data: web::Json<WealthUpdate>| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.as_player(data.player_id)
|
|
||||||
.update_wealth(data.value_in_gp))
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/buy",
|
|
||||||
web::post().to_async(move |pool: AppPool, data: web::Json<LootUpdate>| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.as_player(data.player_id)
|
|
||||||
.buy(&data.items),
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/sell",
|
|
||||||
web::post().to_async(move |pool: AppPool, data: web::Json<LootUpdate>| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.as_player(data.player_id)
|
|
||||||
.sell(&data.items),
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.service(
|
|
||||||
web::resource("/claims")
|
|
||||||
.route(web::get()
|
|
||||||
.to_async(move |pool: AppPool| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.fetch_claims())
|
|
||||||
}))
|
|
||||||
.route(web::put()
|
|
||||||
.to_async(move |pool: AppPool, data: web::Json<PlayerClaim>| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.as_player(data.player_id)
|
|
||||||
.claim(data.item_id))
|
|
||||||
}))
|
|
||||||
.route(web::delete()
|
|
||||||
.to_async(move |pool: AppPool, data: web::Json<PlayerClaim>| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.as_player(data.player_id)
|
|
||||||
.unclaim(data.item_id))
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
.service(web::scope("/admin")
|
|
||||||
.route(
|
|
||||||
"/resolve-claims",
|
|
||||||
web::get().to_async(move |pool: AppPool| {
|
|
||||||
db_call(pool, move |api| api.as_admin().resolve_claims())
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/add-loot",
|
|
||||||
web::post().to_async(
|
|
||||||
move |pool: AppPool, data: web::Json<Vec<Item>>| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.as_admin()
|
|
||||||
.add_loot(data.to_vec()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/add-player",
|
|
||||||
web::get().to_async(
|
|
||||||
move |pool: AppPool, data: web::Json<NewPlayer>| {
|
|
||||||
db_call(pool, move |api| api
|
|
||||||
.as_admin()
|
|
||||||
.add_player(&data.name, data.wealth),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8088")?
|
.bind("127.0.0.1:8088")?
|
||||||
|
|||||||
Reference in New Issue
Block a user