Compare commits
2 Commits
edf236ef8c
...
refactor_u
| Author | SHA1 | Date | |
|---|---|---|---|
| 08f29fc90e | |||
| 4f60df88d7 |
7
.gitignore
vendored
7
.gitignore
vendored
@@ -1,10 +1,11 @@
|
|||||||
/target
|
/target
|
||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
fontawesome
|
||||||
|
package-lock.json
|
||||||
|
|
||||||
Cargo.lock
|
Cargo.lock
|
||||||
**/*.sqlite3
|
**/*.sqlite3
|
||||||
**/.env
|
**/.env
|
||||||
|
|
||||||
package-lock.json
|
|
||||||
fontawesome
|
|
||||||
|
|
||||||
|
|||||||
52
README.md
52
README.md
@@ -6,21 +6,47 @@ 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 "lootés"
|
||||||
☑ Acheter
|
|
||||||
☐ 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
|
|
||||||
☐ Résoudre un conflit
|
|
||||||
☐ 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 pour chaque objet ou globale
|
||||||
☐ 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
|
* Historique des transactions par propriétaire
|
||||||
☑ Mettre à jour facilement
|
|
||||||
* Historique
|
|
||||||
☐ Annuler une action
|
|
||||||
☐ Consulter l'historique des objets 'looté' par le groupe
|
|
||||||
|
|
||||||
|
|
||||||
|
## Base de données
|
||||||
|
|
||||||
|
### Objets (items)
|
||||||
|
|
||||||
|
L'inventaire des objets qui peuvent être lootés.
|
||||||
|
PK: id
|
||||||
|
|
||||||
|
### Objets lootés (looted)
|
||||||
|
|
||||||
|
Les objets actuellement looté.
|
||||||
|
Même schéma que `items` plus une colonne supplémentaire : `owner_id` -> players(id)
|
||||||
|
|
||||||
|
### Joueurs (players)
|
||||||
|
|
||||||
|
Le "groupe" est un propriétaire spécial, avec un ID réservé : 0
|
||||||
|
|
||||||
|
La table conserve l'état actuel des finances du propriétaire. L'attribut `dette` représente la dette envers le groupe.
|
||||||
|
|
||||||
|
```
|
||||||
|
PK: id
|
||||||
|
ATTRS: name, debt (in gp), pp, sp, gp, cp
|
||||||
|
```
|
||||||
|
### Requêtes (claims)
|
||||||
|
|
||||||
|
Table associative entre objets lootés et joueurs.
|
||||||
|
Représente les requêtes des joueurs. La colonne `resolve` permettra d'établir un classement de détermination entre les joueurs.
|
||||||
|
```
|
||||||
|
PK: id
|
||||||
|
FK: loot_id, player_id
|
||||||
|
ATTRS: resolve
|
||||||
|
```
|
||||||
|
|
||||||
|
### Opérations
|
||||||
|
|
||||||
|
_Doit-on garder un historique des opérations ?_
|
||||||
|
|
||||||
|
|||||||
BIN
lootalot_db/db.sqlite3
Normal file
BIN
lootalot_db/db.sqlite3
Normal file
Binary file not shown.
@@ -1 +0,0 @@
|
|||||||
DROP TABLE notifications;
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
CREATE TABLE notifications (
|
|
||||||
id INTEGER PRIMARY KEY NOT NULL,
|
|
||||||
player_id INTEGER NOT NULL,
|
|
||||||
text VARCHAR NOT NULL,
|
|
||||||
FOREIGN KEY (player_id) REFERENCES players(id)
|
|
||||||
);
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -13,14 +13,10 @@ use diesel::prelude::*;
|
|||||||
use diesel::query_dsl::RunQueryDsl;
|
use diesel::query_dsl::RunQueryDsl;
|
||||||
use diesel::r2d2::{self, ConnectionManager};
|
use diesel::r2d2::{self, ConnectionManager};
|
||||||
|
|
||||||
|
mod transactions;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
mod schema;
|
mod schema;
|
||||||
|
use transactions::{DbTransaction};
|
||||||
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;
|
||||||
@@ -28,6 +24,271 @@ pub type DbConnection = SqliteConnection;
|
|||||||
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>;
|
||||||
|
pub type ActionResult<T> = QueryResult<ActionStatus<T>>;
|
||||||
|
/// Return status of an Action
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
pub struct ActionStatus<R: serde::Serialize> {
|
||||||
|
/// Has the action made changes ?
|
||||||
|
pub executed: bool,
|
||||||
|
/// Response payload
|
||||||
|
pub response: R,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActionStatus<()> {
|
||||||
|
pub fn was_updated(updated_lines: usize) -> Self {
|
||||||
|
match updated_lines {
|
||||||
|
1 => Self::ok(),
|
||||||
|
_ => Self::nop(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn ok() -> ActionStatus<()> {
|
||||||
|
Self {
|
||||||
|
executed: true,
|
||||||
|
response: (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Default + serde::Serialize> ActionStatus<T> {
|
||||||
|
pub fn nop() -> ActionStatus<T> {
|
||||||
|
Self {
|
||||||
|
executed: false,
|
||||||
|
response: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 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()
|
||||||
|
/// x .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
|
||||||
|
pub fn fetch_inventory(self) -> QueryResult<Vec<models::Item>> {
|
||||||
|
Ok(schema::items::table.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 an item and add it to this player chest
|
||||||
|
///
|
||||||
|
/// TODO: Items should be picked from a custom list
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// This currently panics if player wealth fails to be updated, as this is
|
||||||
|
/// a serious error. TODO: handle deletion of bought item in case of wealth update failure.
|
||||||
|
pub fn buy<S: Into<String>>(self, name: S, price: i32) -> ActionResult<Option<(i32, i32, i32, i32)>> {
|
||||||
|
match transactions::player::Buy.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::AddLootParams {
|
||||||
|
player_id: self.id,
|
||||||
|
loot_name: name.into(),
|
||||||
|
loot_price: price,
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Ok(res) => Ok(ActionStatus { executed: true, response: Some(res.loot_cost) }),
|
||||||
|
Err(e) => { dbg!(&e); Ok(ActionStatus { executed: false, response: None}) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Sell an item from this player chest
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// This currently panics if player wealth fails to be updated, as this is
|
||||||
|
/// a serious error. TODO: handle restoring of sold item in case of wealth update failure.
|
||||||
|
pub fn sell(
|
||||||
|
self,
|
||||||
|
loot_id: i32,
|
||||||
|
_price_mod: Option<f32>,
|
||||||
|
) -> ActionResult<Option<(i32, i32, i32, i32)>> {
|
||||||
|
// Check that the item belongs to player
|
||||||
|
let exists_and_owned: bool =
|
||||||
|
diesel::select(models::Loot::owns(self.id, loot_id))
|
||||||
|
.get_result(self.conn)?;
|
||||||
|
if !exists_and_owned {
|
||||||
|
return Ok(ActionStatus::nop());
|
||||||
|
}
|
||||||
|
transactions::player::Sell.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::LootParams {
|
||||||
|
player_id: self.id,
|
||||||
|
loot_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|res| ActionStatus { executed: true, response: Some(res.loot_cost) })
|
||||||
|
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop()) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<Option<(i32, i32, i32, i32)>> {
|
||||||
|
transactions::player::UpdateWealth.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::WealthParams {
|
||||||
|
player_id: self.id,
|
||||||
|
value_in_gp,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|res| ActionStatus { executed: true, response: Some(res) })
|
||||||
|
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
||||||
|
}
|
||||||
|
/// 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 Ok(ActionStatus::nop());
|
||||||
|
};
|
||||||
|
transactions::player::PutClaim.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::LootParams {
|
||||||
|
player_id: self.id,
|
||||||
|
loot_id: item,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|_| ActionStatus { executed: true, response: () })
|
||||||
|
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
||||||
|
}
|
||||||
|
/// Withdraw claim
|
||||||
|
pub fn unclaim(self, item: i32) -> ActionResult<()> {
|
||||||
|
transactions::player::WithdrawClaim.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::LootParams {
|
||||||
|
player_id: self.id,
|
||||||
|
loot_id: item,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|_| ActionStatus { executed: true, response: () })
|
||||||
|
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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: String, start_wealth: f32) -> ActionResult<()> {
|
||||||
|
diesel::insert_into(schema::players::table)
|
||||||
|
.values(&models::player::NewPlayer::create(&name, start_wealth))
|
||||||
|
.execute(self.0)
|
||||||
|
.map(ActionStatus::was_updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a list of items to the group loot
|
||||||
|
pub fn add_loot<'a>(self, items: Vec<(&'a str, i32)>) -> ActionResult<()> {
|
||||||
|
for item_desc in items.into_iter() {
|
||||||
|
let new_item = models::item::NewLoot::to_group(item_desc);
|
||||||
|
diesel::insert_into(schema::looted::table)
|
||||||
|
.values(&new_item)
|
||||||
|
.execute(self.0)?;
|
||||||
|
}
|
||||||
|
Ok(ActionStatus::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);
|
||||||
|
// If mutiples claims -> find highest resolve, give to this player
|
||||||
|
// If only one claim -> give to claiming
|
||||||
|
Ok(ActionStatus::nop())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 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)
|
||||||
@@ -40,87 +301,8 @@ pub fn create_pool() -> Pool {
|
|||||||
.expect("Failed to create pool.")
|
.expect("Failed to create pool.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
/// Sells a single item inside a transaction
|
mod tests {
|
||||||
///
|
|
||||||
/// # 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.sell_value() as f64;
|
|
||||||
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.value() as f64 * modifier,
|
|
||||||
None => item.value() 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;
|
||||||
|
|
||||||
@@ -134,7 +316,7 @@ mod tests_old {
|
|||||||
/// When migrations are run, a special player with id 0 and name "Groupe"
|
/// When migrations are run, a special player with id 0 and name "Groupe"
|
||||||
/// must be created.
|
/// must be created.
|
||||||
#[test]
|
#[test]
|
||||||
fn global_group_is_autocreated() {
|
fn test_group_is_autocreated() {
|
||||||
let conn = test_connection();
|
let conn = test_connection();
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
assert_eq!(players.len(), 1);
|
assert_eq!(players.len(), 1);
|
||||||
@@ -146,19 +328,20 @@ mod tests_old {
|
|||||||
/// When a player updates wealth, a difference is returned by API.
|
/// When a player updates wealth, a difference is returned by API.
|
||||||
/// Added to the previous amount of coins, it should equal the updated weath.
|
/// Added to the previous amount of coins, it should equal the updated weath.
|
||||||
#[test]
|
#[test]
|
||||||
fn as_player_updates_wealth() {
|
fn test_player_updates_wealth() {
|
||||||
let conn = test_connection();
|
let conn = test_connection();
|
||||||
DbApi::with_conn(&conn)
|
DbApi::with_conn(&conn)
|
||||||
.as_admin()
|
.as_admin()
|
||||||
.add_player("PlayerName", 403.21)
|
.add_player("PlayerName".to_string(), 403.21)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let diff = DbApi::with_conn(&conn)
|
let diff = DbApi::with_conn(&conn)
|
||||||
.as_player(1)
|
.as_player(1)
|
||||||
.update_wealth(-401.21)
|
.update_wealth(-401.21)
|
||||||
.ok();
|
.unwrap()
|
||||||
|
.response
|
||||||
|
.unwrap();
|
||||||
// Check the returned diff
|
// Check the returned diff
|
||||||
assert_eq!(diff, Some((-1, -2, -1, -4)));
|
assert_eq!(diff, (-1, -2, -1, -4));
|
||||||
let diff = diff.unwrap();
|
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
let player = players.get(1).unwrap();
|
let player = players.get(1).unwrap();
|
||||||
// Check that we can add old value to return diff to get resulting value
|
// Check that we can add old value to return diff to get resulting value
|
||||||
@@ -169,12 +352,13 @@ mod tests_old {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn as_admin_add_player() {
|
fn test_admin_add_player() {
|
||||||
let conn = test_connection();
|
let conn = test_connection();
|
||||||
let result = DbApi::with_conn(&conn)
|
let result = DbApi::with_conn(&conn)
|
||||||
.as_admin()
|
.as_admin()
|
||||||
.add_player("PlayerName", 403.21);
|
.add_player("PlayerName".to_string(), 403.21)
|
||||||
assert_eq!(result.is_ok(), true);
|
.unwrap();
|
||||||
|
assert_eq!(result.executed, true);
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
assert_eq!(players.len(), 2);
|
assert_eq!(players.len(), 2);
|
||||||
let new_player = players.get(1).unwrap();
|
let new_player = players.get(1).unwrap();
|
||||||
@@ -186,92 +370,56 @@ mod tests_old {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn as_admin_resolve_claims() {
|
fn test_admin_resolve_claims() {
|
||||||
let conn = test_connection();
|
let conn = test_connection();
|
||||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||||
assert_eq!(claims.len(), 0);
|
assert_eq!(claims.len(), 0);
|
||||||
|
assert_eq!(true, false); // Failing as test is not complete
|
||||||
// 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]
|
#[test]
|
||||||
fn as_player_claim_item() {
|
fn test_player_claim_item() {
|
||||||
let conn = test_connection();
|
let conn = test_connection();
|
||||||
DbApi::with_conn(&conn)
|
DbApi::with_conn(&conn)
|
||||||
.as_admin()
|
.as_admin()
|
||||||
.add_player("Player", 0.0)
|
.add_player("Player".to_string(), 0.0)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
DbApi::with_conn(&conn)
|
DbApi::with_conn(&conn)
|
||||||
.as_admin()
|
.as_admin()
|
||||||
.add_loot(vec![("Épée", 25)])
|
.add_loot(vec![("Épée", 25)])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
// Claim an existing item
|
// Claim an existing item
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
let result = DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
||||||
assert_eq!(result.is_ok(), true);
|
assert_eq!(result.executed, true);
|
||||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||||
assert_eq!(claims.len(), 1);
|
assert_eq!(claims.len(), 1);
|
||||||
let claim = claims.get(0).unwrap();
|
let claim = claims.get(0).unwrap();
|
||||||
assert_eq!(claim.player_id, 1);
|
assert_eq!(claim.player_id, 1);
|
||||||
assert_eq!(claim.loot_id, 1);
|
assert_eq!(claim.loot_id, 1);
|
||||||
// Claim an inexistant item
|
// Claim an inexistant item
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).claim(2);
|
let result = DbApi::with_conn(&conn).as_player(1).claim(2).unwrap();
|
||||||
assert_eq!(result.is_ok(), false);
|
assert_eq!(result.executed, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn as_player_unclaim_item() {
|
fn test_player_unclaim_item() {
|
||||||
let conn = test_connection();
|
let conn = test_connection();
|
||||||
DbApi::with_conn(&conn)
|
DbApi::with_conn(&conn)
|
||||||
.as_admin()
|
.as_admin()
|
||||||
.add_player("Player", 0.0)
|
.add_player("Player".to_string(), 0.0)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
DbApi::with_conn(&conn)
|
DbApi::with_conn(&conn)
|
||||||
.as_admin()
|
.as_admin()
|
||||||
.add_loot(vec![("Épée", 25)])
|
.add_loot(vec![("Épée", 25)])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
// Claim an existing item
|
// Claim an existing item
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
let result = DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
||||||
assert_eq!(result.is_ok(), true);
|
assert_eq!(result.executed, true);
|
||||||
// Claiming twice is an error
|
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1).unwrap();
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
assert_eq!(result.executed, true);
|
||||||
assert_eq!(result.is_ok(), false);
|
// Check that unclaimed items will not be unclaimed...
|
||||||
// Unclaiming and item
|
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1).unwrap();
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
assert_eq!(result.executed, false);
|
||||||
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();
|
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||||
assert_eq!(claims.len(), 0);
|
assert_eq!(claims.len(), 0);
|
||||||
}
|
}
|
||||||
@@ -280,25 +428,20 @@ mod tests_old {
|
|||||||
///
|
///
|
||||||
/// Checks that player's chest and wealth are updated.
|
/// Checks that player's chest and wealth are updated.
|
||||||
/// Checks that items are sold at half their value.
|
/// Checks that items are sold at half their value.
|
||||||
/// Checks that a player cannot sell item he does not own.
|
|
||||||
#[test]
|
#[test]
|
||||||
fn as_player_simple_buy_sell() {
|
fn test_buy_sell_simple() {
|
||||||
let conn = test_connection();
|
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)
|
DbApi::with_conn(&conn)
|
||||||
.as_admin()
|
.as_admin()
|
||||||
.add_player("Player", 1000.0)
|
.add_player("Player".to_string(), 1000.0)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
// Buy an item
|
// Buy an item
|
||||||
let bought = DbApi::with_conn(&conn).as_player(1).buy(&vec![(1, None)]);
|
let bought = DbApi::with_conn(&conn)
|
||||||
assert_eq!(bought.ok(), Some((0, 0, 0, -8))); // Returns diff of player wealth ?
|
.as_player(1)
|
||||||
|
.buy("Sword", 800)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(bought.executed, true); // Was updated ?
|
||||||
|
assert_eq!(bought.response, 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);
|
||||||
let loot = chest.get(0).unwrap();
|
let loot = chest.get(0).unwrap();
|
||||||
@@ -307,16 +450,13 @@ mod tests_old {
|
|||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
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
|
|
||||||
let result = DbApi::with_conn(&conn)
|
|
||||||
.as_player(0)
|
|
||||||
.sell(&vec![(loot.id, None)]);
|
|
||||||
assert_eq!(result.is_ok(), false);
|
|
||||||
// Sell back
|
// Sell back
|
||||||
let sold = DbApi::with_conn(&conn)
|
let sold = DbApi::with_conn(&conn)
|
||||||
.as_player(1)
|
.as_player(1)
|
||||||
.sell(&vec![(loot.id, None)]);
|
.sell(loot.id, None)
|
||||||
assert_eq!(sold.ok(), Some((0, 0, 0, 4)));
|
.unwrap();
|
||||||
|
assert_eq!(sold.executed, true);
|
||||||
|
assert_eq!(sold.response, 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);
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
@@ -325,7 +465,7 @@ mod tests_old {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn as_admin_add_loot() {
|
fn test_admin_add_loot() {
|
||||||
let conn = test_connection();
|
let conn = test_connection();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
0,
|
0,
|
||||||
@@ -334,8 +474,9 @@ mod tests_old {
|
|||||||
let loot_to_add = vec![("Cape d'invisibilité", 8000), ("Arc long", 25)];
|
let loot_to_add = vec![("Cape d'invisibilité", 8000), ("Arc long", 25)];
|
||||||
let result = DbApi::with_conn(&conn)
|
let result = DbApi::with_conn(&conn)
|
||||||
.as_admin()
|
.as_admin()
|
||||||
.add_loot(loot_to_add.clone());
|
.add_loot(loot_to_add.clone())
|
||||||
assert_eq!(result.is_ok(), true);
|
.unwrap();
|
||||||
|
assert_eq!(result.executed, true);
|
||||||
let looted = DbApi::with_conn(&conn).as_player(0).loot().unwrap();
|
let looted = DbApi::with_conn(&conn).as_player(0).loot().unwrap();
|
||||||
assert_eq!(looted.len(), 2);
|
assert_eq!(looted.len(), 2);
|
||||||
// NB: Not a problem now, but this adds constraints of items being
|
// NB: Not a problem now, but this adds constraints of items being
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
use crate::{DbConnection, QueryResult};
|
use crate::models::item::Loot;
|
||||||
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, Deserialize, Debug)]
|
#[derive(Identifiable, Queryable, Associations, Serialize, Debug)]
|
||||||
#[belongs_to(Loot)]
|
#[belongs_to(Loot)]
|
||||||
pub struct Claim {
|
pub struct Claim {
|
||||||
/// DB Identifier
|
/// DB Identifier
|
||||||
@@ -18,150 +15,15 @@ pub struct Claim {
|
|||||||
pub resolve: i32,
|
pub resolve: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Claim {
|
|
||||||
/// Resolves this claim (player wins the item) and deletes it
|
|
||||||
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> {
|
|
||||||
/// Get all claims from database
|
|
||||||
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.
|
|
||||||
///
|
|
||||||
/// Will validate that the claimed item exists and is
|
|
||||||
/// actually owned by the group.
|
|
||||||
/// Duplicates are also ignored.
|
|
||||||
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"]
|
||||||
struct NewClaim {
|
pub(crate) struct NewClaim {
|
||||||
player_id: i32,
|
player_id: i32,
|
||||||
loot_id: i32,
|
loot_id: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NewClaim {
|
impl NewClaim {
|
||||||
fn new(player_id: i32, loot_id: i32) -> Self {
|
pub(crate) 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("Epee", 30)?;
|
|
||||||
crate::LootManager(&conn, 1).add("Arc", 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,59 +1,38 @@
|
|||||||
|
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 basic item
|
/// Represents a unique item in inventory
|
||||||
#[derive(Debug, Queryable, Serialize, Deserialize, Clone)]
|
///
|
||||||
|
/// 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)]
|
||||||
pub struct Item {
|
pub struct Item {
|
||||||
pub id: i32,
|
pub id: i32,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
base_price: i32,
|
pub base_price: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Item {
|
impl Item {
|
||||||
/// Returns this item value
|
/// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns this item sell value
|
|
||||||
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> {
|
|
||||||
/// Get all items from Inventory
|
|
||||||
pub fn all(&self) -> QueryResult<Vec<Item>> {
|
|
||||||
items::table.load::<Item>(self.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Find an item in Inventory
|
|
||||||
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
|
||||||
/// hence has an owner.
|
#[derive(Identifiable, Debug, Queryable, Serialize)]
|
||||||
#[derive(Identifiable, Debug, Queryable)]
|
|
||||||
#[table_name = "looted"]
|
#[table_name = "looted"]
|
||||||
pub(super) struct Loot {
|
pub(crate) struct Loot {
|
||||||
id: i32,
|
id: i32,
|
||||||
name: String,
|
name: String,
|
||||||
base_price: i32,
|
base_price: i32,
|
||||||
@@ -62,95 +41,21 @@ pub(super) struct Loot {
|
|||||||
|
|
||||||
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(super) fn owned_by(id: i32) -> OwnedLoot {
|
pub(crate) fn owned_by(id: i32) -> OwnedLoot {
|
||||||
looted::table.filter(looted::owner_id.eq(id))
|
looted::table.filter(looted::owner_id.eq(id))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn exists(id: i32) -> Exists<Find<looted::table, i32>> {
|
pub(crate) fn owns(player: i32, item: i32) -> Exists<Find<OwnedLoot, i32>> {
|
||||||
|
exists(Loot::owned_by(player).find(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn exists(id: i32) -> Exists<Find<looted::table, i32>> {
|
||||||
exists(looted::table.find(id))
|
exists(looted::table.find(id))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn set_owner(&self, owner: i32, conn: &DbConnection) -> QueryResult<()> {
|
|
||||||
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 *single* player loot
|
/// Description of an item : (name, value in gold)
|
||||||
pub struct LootManager<'q>(pub &'q DbConnection, pub i32);
|
pub type ItemDesc<'a> = (&'a str, 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
|
|
||||||
///
|
|
||||||
/// Returns a NotFound error if an item is found by it
|
|
||||||
/// does not belong to this player
|
|
||||||
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)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn add<S: Into<String>>(self, name: S, base_price: i32) -> QueryResult<Item> {
|
|
||||||
self.add_from(&Item {
|
|
||||||
id: 0,
|
|
||||||
name: name.into(),
|
|
||||||
base_price,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An item being looted or bought.
|
/// An item being looted or bought.
|
||||||
///
|
///
|
||||||
@@ -158,8 +63,28 @@ impl<'q> LootManager<'q> {
|
|||||||
/// to the id of buying player otherwise.
|
/// to the id of buying player otherwise.
|
||||||
#[derive(Insertable)]
|
#[derive(Insertable)]
|
||||||
#[table_name = "looted"]
|
#[table_name = "looted"]
|
||||||
struct NewLoot<'a> {
|
pub(crate) 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: ItemDesc<'a>) -> Self {
|
||||||
|
Self {
|
||||||
|
name: desc.0,
|
||||||
|
base_price: desc.1,
|
||||||
|
owner_id: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new loot going to a specific player (buy procedure)
|
||||||
|
pub(crate) fn to_player(player: i32, desc: ItemDesc<'a>) -> Self {
|
||||||
|
Self {
|
||||||
|
name: desc.0,
|
||||||
|
base_price: desc.1,
|
||||||
|
owner_id: player,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
pub mod claim;
|
pub(super) mod claim;
|
||||||
pub mod item;
|
pub(super) mod item;
|
||||||
pub mod player;
|
pub(super) 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,6 +1,26 @@
|
|||||||
use crate::schema::players;
|
use crate::schema::players;
|
||||||
|
|
||||||
/// Unpack a floating value of gold pieces to integer
|
/// Representation of a player in database
|
||||||
|
#[derive(Debug, Queryable, Serialize)]
|
||||||
|
pub struct Player {
|
||||||
|
/// DB Identitier
|
||||||
|
pub id: i32,
|
||||||
|
/// Full name of the character
|
||||||
|
pub name: String,
|
||||||
|
/// Amount of gold coins owed to the group.
|
||||||
|
/// Taking a looted items will increase the debt by it's sell value
|
||||||
|
pub debt: i32,
|
||||||
|
/// Count of copper pieces
|
||||||
|
pub cp: i32,
|
||||||
|
/// Count of silver pieces
|
||||||
|
pub sp: i32,
|
||||||
|
/// Count of gold pieces
|
||||||
|
pub gp: i32,
|
||||||
|
/// Count of platinum pieces
|
||||||
|
pub pp: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unpack a floating value in gold pieces to integer
|
||||||
/// values of copper, silver, gold and platinum pieces
|
/// values of copper, silver, gold and platinum pieces
|
||||||
///
|
///
|
||||||
/// # Note
|
/// # Note
|
||||||
@@ -8,7 +28,7 @@ use crate::schema::players;
|
|||||||
/// 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: f64) -> (i32, i32, i32, i32) {
|
fn unpack_gold_value(gold: f32) -> (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;
|
||||||
@@ -22,7 +42,7 @@ fn unpack_gold_value(gold: f64) -> (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, Serialize, Deserialize, Debug)]
|
#[derive(Queryable, AsChangeset, Debug)]
|
||||||
#[table_name = "players"]
|
#[table_name = "players"]
|
||||||
pub struct Wealth {
|
pub struct Wealth {
|
||||||
pub cp: i32,
|
pub cp: i32,
|
||||||
@@ -40,7 +60,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: f64) -> Self {
|
pub fn from_gp(gp: f32) -> 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 }
|
||||||
}
|
}
|
||||||
@@ -49,13 +69,13 @@ impl Wealth {
|
|||||||
/// # Examples
|
/// # Examples
|
||||||
/// ```
|
/// ```
|
||||||
/// # use lootalot_db::models::Wealth;
|
/// # use lootalot_db::models::Wealth;
|
||||||
/// let wealth = Wealth{ pp: 4, gp: 5, sp: 8, cp: 4};
|
/// let wealth = Wealth{ pp: 4, gp: 3, sp: 2, cp: 1};
|
||||||
/// assert_eq!(wealth.to_gp(), 405.84);
|
/// assert_eq!(wealth.to_gp(), 403.21);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn to_gp(&self) -> f64 {
|
pub fn to_gp(&self) -> f32 {
|
||||||
let i = self.pp * 100 + self.gp;
|
let i = self.pp * 100 + self.gp;
|
||||||
let f = (self.sp * 10 + self.cp) as f64 / 100.0;
|
let f = (self.sp * 10 + self.cp) as f32 / 100.0;
|
||||||
i as f64 + f
|
i as f32 + 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) {
|
||||||
@@ -63,30 +83,26 @@ impl Wealth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Representation of a new player record
|
||||||
impl std::ops::Sub for Wealth {
|
#[derive(Insertable)]
|
||||||
type Output = Self;
|
#[table_name = "players"]
|
||||||
/// What needs to be added to 'other' so that
|
pub(crate) struct NewPlayer<'a> {
|
||||||
/// the result equals 'self'
|
name: &'a str,
|
||||||
fn sub(self, other: Self) -> Self {
|
cp: i32,
|
||||||
Wealth {
|
sp: i32,
|
||||||
cp: self.cp - other.cp,
|
gp: i32,
|
||||||
sp: self.sp - other.sp,
|
pp: i32,
|
||||||
gp: self.gp - other.gp,
|
|
||||||
pp: self.pp - other.pp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::ops::Add for Wealth {
|
impl<'a> NewPlayer<'a> {
|
||||||
type Output = Self;
|
pub(crate) fn create(name: &'a str, wealth_in_gp: f32) -> Self {
|
||||||
|
let (cp, sp, gp, pp) = Wealth::from_gp(wealth_in_gp).as_tuple();
|
||||||
fn add(self, other: Self) -> Self {
|
Self {
|
||||||
Wealth {
|
name,
|
||||||
cp: self.cp + other.cp,
|
cp,
|
||||||
sp: self.sp + other.sp,
|
sp,
|
||||||
gp: self.gp + other.gp,
|
gp,
|
||||||
pp: self.pp + other.pp
|
pp,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,16 +114,12 @@ 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)),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
use crate::schema::players;
|
|
||||||
use crate::{DbConnection, QueryResult};
|
|
||||||
use diesel::prelude::*;
|
|
||||||
|
|
||||||
mod notification;
|
|
||||||
pub mod wealth;
|
|
||||||
pub use wealth::Wealth;
|
|
||||||
|
|
||||||
/// Representation of a player in database
|
|
||||||
#[derive(Identifiable, Queryable, Serialize, Deserialize, Debug)]
|
|
||||||
pub struct Player {
|
|
||||||
/// DB Identitier
|
|
||||||
pub id: i32,
|
|
||||||
/// Full name of the character
|
|
||||||
pub name: String,
|
|
||||||
/// Amount of gold coins owed to the group.
|
|
||||||
/// Taking a looted items will increase the debt by it's sell value
|
|
||||||
pub debt: i32,
|
|
||||||
/// Count of copper pieces
|
|
||||||
pub cp: i32,
|
|
||||||
/// Count of silver pieces
|
|
||||||
pub sp: i32,
|
|
||||||
/// Count of gold pieces
|
|
||||||
pub gp: i32,
|
|
||||||
/// Count of platinum pieces
|
|
||||||
pub pp: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Manager for players
|
|
||||||
pub struct Players<'q>(pub &'q DbConnection);
|
|
||||||
|
|
||||||
impl<'q> Players<'q> {
|
|
||||||
/// Get all players from database
|
|
||||||
pub fn all(&self) -> QueryResult<Vec<Player>> {
|
|
||||||
players::table.load(self.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Find a player by id
|
|
||||||
pub fn find(&self, id: i32) -> QueryResult<Player> {
|
|
||||||
players::table.find(id).first(self.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add a new player with name and starting wealth
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Notify all players of an event
|
|
||||||
pub fn notifiy_all(&self, text: &str) -> QueryResult<()> {
|
|
||||||
for id in self.all()?
|
|
||||||
.into_iter()
|
|
||||||
.map(|p| p.id)
|
|
||||||
{
|
|
||||||
self.notify(id, text);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Notify a single player of an event
|
|
||||||
pub fn notify(&self, id: i32, text: &str) -> QueryResult<()> {
|
|
||||||
let _ = notification::Notification::add(self.0, id, text)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wrapper for action of a single player
|
|
||||||
pub struct AsPlayer<'q>(pub &'q DbConnection, pub i32);
|
|
||||||
|
|
||||||
impl<'q> AsPlayer<'q> {
|
|
||||||
/// Fetch notifications for this player
|
|
||||||
pub fn notifications(&self) -> QueryResult<Vec<String>> {
|
|
||||||
notification::pop_all_for(self.1, self.0)
|
|
||||||
}
|
|
||||||
/// Updates this player's wealth, returning the difference
|
|
||||||
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)?;
|
|
||||||
Ok(updated_wealth - current_wealth)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Updates this player's debt
|
|
||||||
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(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Representation of a new player record
|
|
||||||
#[derive(Insertable)]
|
|
||||||
#[table_name = "players"]
|
|
||||||
struct NewPlayer<'a> {
|
|
||||||
name: &'a str,
|
|
||||||
cp: i32,
|
|
||||||
sp: i32,
|
|
||||||
gp: i32,
|
|
||||||
pp: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> NewPlayer<'a> {
|
|
||||||
fn create(name: &'a str, wealth_in_gp: f64) -> Self {
|
|
||||||
let (cp, sp, gp, pp) = Wealth::from_gp(wealth_in_gp).as_tuple();
|
|
||||||
Self {
|
|
||||||
name,
|
|
||||||
cp,
|
|
||||||
sp,
|
|
||||||
gp,
|
|
||||||
pp,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
use diesel::prelude::*;
|
|
||||||
use crate::{
|
|
||||||
DbConnection,
|
|
||||||
schema::notifications,
|
|
||||||
models::player::Player,
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
/// Pops all notification for a player, deleting the database entities
|
|
||||||
pub(super) fn pop_all_for(id: i32, conn: &DbConnection) -> QueryResult<Vec<String>> {
|
|
||||||
let select = notifications::table.filter(notifications::dsl::player_id.eq(id));
|
|
||||||
let popped = select.load(conn)?;
|
|
||||||
diesel::delete(select).execute(conn)?;
|
|
||||||
Ok(popped.into_iter().map(|n: Notification| n.text).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Identifiable, Queryable, Associations, Serialize, Debug)]
|
|
||||||
#[belongs_to(Player)]
|
|
||||||
pub(super) struct Notification {
|
|
||||||
pub id: i32,
|
|
||||||
pub player_id: i32,
|
|
||||||
pub text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Notification {
|
|
||||||
pub(super) fn add<'a, S: Into<&'a str>>(conn: &DbConnection, id: i32, text: S) -> QueryResult<Notification> {
|
|
||||||
diesel::insert_into(notifications::table)
|
|
||||||
.values(&NewNotification {
|
|
||||||
player_id: id,
|
|
||||||
text: text.into(),
|
|
||||||
})
|
|
||||||
.execute(conn)?;
|
|
||||||
notifications::table
|
|
||||||
.order(notifications::dsl::id.desc())
|
|
||||||
.first(conn)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Insertable)]
|
|
||||||
#[table_name="notifications"]
|
|
||||||
struct NewNotification<'a> {
|
|
||||||
player_id: i32,
|
|
||||||
text: &'a str,
|
|
||||||
}
|
|
||||||
@@ -24,14 +24,6 @@ table! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
table! {
|
|
||||||
notifications (id) {
|
|
||||||
id -> Integer,
|
|
||||||
player_id -> Integer,
|
|
||||||
text -> Text,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
table! {
|
table! {
|
||||||
players (id) {
|
players (id) {
|
||||||
id -> Integer,
|
id -> Integer,
|
||||||
@@ -47,12 +39,5 @@ table! {
|
|||||||
joinable!(claims -> looted (loot_id));
|
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));
|
||||||
joinable!(notifications -> players (player_id));
|
|
||||||
|
|
||||||
allow_tables_to_appear_in_same_query!(
|
allow_tables_to_appear_in_same_query!(claims, items, looted, players,);
|
||||||
claims,
|
|
||||||
items,
|
|
||||||
looted,
|
|
||||||
notifications,
|
|
||||||
players,
|
|
||||||
);
|
|
||||||
|
|||||||
295
lootalot_db/src/transactions.rs
Normal file
295
lootalot_db/src/transactions.rs
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
//! TODO:
|
||||||
|
//! Extract actions provided by API into their dedicated module.
|
||||||
|
//! Will allow more flexibilty to combinate them inside API methods.
|
||||||
|
//! Should make it easier to add a new feature : Reverting an action
|
||||||
|
//!
|
||||||
|
use crate::models;
|
||||||
|
use crate::schema;
|
||||||
|
use crate::DbConnection;
|
||||||
|
use diesel::prelude::*;
|
||||||
|
// TODO: revertable actions :
|
||||||
|
// - Buy
|
||||||
|
// - Sell
|
||||||
|
// - UpdateWealth
|
||||||
|
pub type TransactionResult<T> = Result<T, diesel::result::Error>;
|
||||||
|
|
||||||
|
|
||||||
|
pub trait DbTransaction {
|
||||||
|
type Params;
|
||||||
|
type Response: serde::Serialize;
|
||||||
|
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Revertable : DbTransaction {
|
||||||
|
fn revert<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
player_id: i32,
|
||||||
|
params: <Self as DbTransaction>::Response,
|
||||||
|
) -> TransactionResult<<Self as DbTransaction>::Response>;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return status of an Action
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
pub struct ActionStatus<R: serde::Serialize> {
|
||||||
|
/// Has the action made changes ?
|
||||||
|
pub executed: bool,
|
||||||
|
/// Response payload
|
||||||
|
pub response: R,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActionStatus<()> {
|
||||||
|
pub fn was_updated(updated_lines: usize) -> Self {
|
||||||
|
match updated_lines {
|
||||||
|
1 => Self::ok(),
|
||||||
|
_ => Self::nop(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn ok() -> ActionStatus<()> {
|
||||||
|
Self {
|
||||||
|
executed: true,
|
||||||
|
response: (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Default + serde::Serialize> ActionStatus<T> {
|
||||||
|
pub fn nop() -> ActionStatus<T> {
|
||||||
|
Self {
|
||||||
|
executed: false,
|
||||||
|
response: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Or a module ?
|
||||||
|
pub(crate) mod player {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
pub struct AddLootParams {
|
||||||
|
pub player_id: i32,
|
||||||
|
pub loot_name: String,
|
||||||
|
pub loot_price: i32,
|
||||||
|
}
|
||||||
|
pub struct Buy;
|
||||||
|
|
||||||
|
enum LootTransactionKind {
|
||||||
|
Buy,
|
||||||
|
Sell,
|
||||||
|
}
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
pub struct LootTransaction {
|
||||||
|
player_id: i32,
|
||||||
|
loot_id: i32,
|
||||||
|
kind: LootTransactionKind,
|
||||||
|
pub loot_cost: (i32, i32, i32, i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DbTransaction for Buy {
|
||||||
|
type Params = AddLootParams;
|
||||||
|
type Response = LootTransaction;
|
||||||
|
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
let added_item = {
|
||||||
|
let new_item = models::item::NewLoot::to_player(
|
||||||
|
params.player_id,
|
||||||
|
(¶ms.loot_name, params.loot_price),
|
||||||
|
);
|
||||||
|
diesel::insert_into(schema::looted::table)
|
||||||
|
.values(&new_item)
|
||||||
|
.execute(conn)?
|
||||||
|
// TODO: return ID of inserted item
|
||||||
|
};
|
||||||
|
let updated_wealth = UpdateWealth.execute(
|
||||||
|
conn,
|
||||||
|
WealthParams {
|
||||||
|
player_id: params.player_id,
|
||||||
|
value_in_gp: -(params.loot_price as f32),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match (added_item, updated_wealth) {
|
||||||
|
(1, Ok(loot_cost)) => Ok(LootTransaction {
|
||||||
|
kind: LootTransactionKind::Buy,
|
||||||
|
player_id: params.player_id,
|
||||||
|
loot_id: 0, //TODO: find added item ID
|
||||||
|
loot_cost,
|
||||||
|
}),
|
||||||
|
// TODO: Handle other cases
|
||||||
|
_ => panic!()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Revertable for Buy {
|
||||||
|
fn revert<'q>(self, conn: &'q DbConnection, player_id: i32, params: <Self as DbTransaction>::Response)
|
||||||
|
-> TransactionResult<<Self as DbTransaction>::Response> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct LootParams {
|
||||||
|
pub player_id: i32,
|
||||||
|
pub loot_id: i32,
|
||||||
|
}
|
||||||
|
pub struct Sell;
|
||||||
|
impl DbTransaction for Sell {
|
||||||
|
type Params = LootParams;
|
||||||
|
type Response = LootTransaction;
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
use schema::looted::dsl::*;
|
||||||
|
let loot_value = looted
|
||||||
|
.find(params.loot_id)
|
||||||
|
.select(base_price)
|
||||||
|
.first::<i32>(conn)?;
|
||||||
|
let sell_value = (loot_value / 2) as f32;
|
||||||
|
diesel::delete(looted.find(params.loot_id))
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|r| match r {
|
||||||
|
// On deletion, update this player wealth
|
||||||
|
1 => Ok(UpdateWealth
|
||||||
|
.execute(
|
||||||
|
conn,
|
||||||
|
WealthParams {
|
||||||
|
player_id: params.player_id,
|
||||||
|
value_in_gp: sell_value as f32,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap()),
|
||||||
|
_ => Ok(ActionStatus {
|
||||||
|
executed: false,
|
||||||
|
response: None,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PutClaim;
|
||||||
|
impl DbTransaction for PutClaim {
|
||||||
|
type Params = LootParams;
|
||||||
|
type Response = ();
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
let claim = models::claim::NewClaim::new(params.player_id, params.loot_id);
|
||||||
|
diesel::insert_into(schema::claims::table)
|
||||||
|
.values(&claim)
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|_| Ok(()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WithdrawClaim;
|
||||||
|
impl DbTransaction for WithdrawClaim {
|
||||||
|
type Params = LootParams;
|
||||||
|
type Response = ();
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
use schema::claims::dsl::*;
|
||||||
|
diesel::delete(
|
||||||
|
claims
|
||||||
|
.filter(loot_id.eq(params.loot_id))
|
||||||
|
.filter(player_id.eq(params.player_id)),
|
||||||
|
)
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|_| Ok(()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WealthParams {
|
||||||
|
pub player_id: i32,
|
||||||
|
pub value_in_gp: f32,
|
||||||
|
}
|
||||||
|
pub struct UpdateWealth;
|
||||||
|
|
||||||
|
impl DbTransaction for UpdateWealth {
|
||||||
|
type Params = WealthParams;
|
||||||
|
type Response = (i32, i32, i32, i32);
|
||||||
|
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
params: WealthParams,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
use schema::players::dsl::*;
|
||||||
|
let current_wealth = players
|
||||||
|
.find(params.player_id)
|
||||||
|
.select((cp, sp, gp, pp))
|
||||||
|
.first::<models::Wealth>(conn)?;
|
||||||
|
// TODO: improve thisdiesel dependant transaction
|
||||||
|
// should be move inside a WealthUpdate method
|
||||||
|
let updated_wealth =
|
||||||
|
models::Wealth::from_gp(current_wealth.to_gp() + params.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(params.player_id))
|
||||||
|
.set(&updated_wealth)
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|r| match r {
|
||||||
|
1 => Ok(diff),
|
||||||
|
_ => panic!("UpdateWealth made no changes !"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Revertable for UpdateWealth {
|
||||||
|
fn revert<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
player_id: i32,
|
||||||
|
params: <Self as DbTransaction>::Response,
|
||||||
|
) -> TransactionResult<<Self as DbTransaction>::Response> {
|
||||||
|
use schema::players::dsl::*;
|
||||||
|
let cur_wealth = players
|
||||||
|
.find(player_id)
|
||||||
|
.select((cp, sp, gp, pp))
|
||||||
|
.first::<models::Wealth>(conn)?;
|
||||||
|
let reverted_wealth = models::player::Wealth {
|
||||||
|
cp: cur_wealth.cp - params.0,
|
||||||
|
sp: cur_wealth.cp - params.1,
|
||||||
|
gp: cur_wealth.cp - params.2,
|
||||||
|
pp: cur_wealth.cp - params.3,
|
||||||
|
};
|
||||||
|
// Difference in coins that is sent back
|
||||||
|
let diff = ( -params.0, -params.1, -params.2, -params.3);
|
||||||
|
diesel::update(players)
|
||||||
|
.filter(id.eq(params.0))
|
||||||
|
.set(&reverted_wealth)
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|r| match r {
|
||||||
|
1 => Ok(diff),
|
||||||
|
_ => panic!("RevertableWealthUpdate made no changes"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub(crate) mod admin {
|
||||||
|
pub struct AddPlayer;
|
||||||
|
pub struct AddLoot;
|
||||||
|
pub struct SellLoot;
|
||||||
|
pub struct ResolveClaims;
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
> 1%
|
|
||||||
last 2 versions
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
root: true,
|
|
||||||
env: {
|
|
||||||
node: true
|
|
||||||
},
|
|
||||||
'extends': [
|
|
||||||
'plugin:vue/essential',
|
|
||||||
'eslint:recommended'
|
|
||||||
],
|
|
||||||
rules: {
|
|
||||||
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
|
|
||||||
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
|
|
||||||
},
|
|
||||||
parserOptions: {
|
|
||||||
parser: 'babel-eslint'
|
|
||||||
},
|
|
||||||
overrides: [
|
|
||||||
{
|
|
||||||
files: [
|
|
||||||
'**/__tests__/*.{j,t}s?(x)'
|
|
||||||
],
|
|
||||||
env: {
|
|
||||||
mocha: true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,11 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
presets: [
|
presets: [
|
||||||
'@vue/app'
|
'@vue/app'
|
||||||
]
|
],
|
||||||
|
"presets": [["env", { "modules": false }]],
|
||||||
|
"env": {
|
||||||
|
"test": {
|
||||||
|
"presets": [["env", { "targets": { "node": "current" } }]]
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
15047
lootalot_front/package-lock.json
generated
Normal file
15047
lootalot_front/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -3,10 +3,12 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"css-build": "node-sass --omit-source-map-url sass/scroll.scss public/css/scroll.css",
|
||||||
|
"css-watch": "npm run css-build -- --watch",
|
||||||
"serve": "vue-cli-service serve",
|
"serve": "vue-cli-service serve",
|
||||||
"build": "vue-cli-service build",
|
"build": "vue-cli-service build",
|
||||||
"lint": "vue-cli-service lint",
|
"lint": "vue-cli-service lint",
|
||||||
"test:unit": "vue-cli-service test:unit"
|
"test": "jest"
|
||||||
},
|
},
|
||||||
"main": "sass/scroll.scss",
|
"main": "sass/scroll.scss",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -15,15 +17,52 @@
|
|||||||
"vue": "^2.6.10"
|
"vue": "^2.6.10"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vue/cli-plugin-babel": "^3.11.0",
|
"@vue/cli-plugin-babel": "^3.8.0",
|
||||||
"@vue/cli-plugin-eslint": "^3.11.0",
|
"@vue/cli-plugin-eslint": "^3.8.0",
|
||||||
"@vue/cli-plugin-unit-mocha": "^3.11.0",
|
"@vue/cli-service": "^3.8.0",
|
||||||
"@vue/cli-service": "^3.11.0",
|
"@vue/test-utils": "^1.0.0-beta.29",
|
||||||
"@vue/test-utils": "1.0.0-beta.29",
|
|
||||||
"babel-eslint": "^10.0.1",
|
"babel-eslint": "^10.0.1",
|
||||||
"chai": "^4.1.2",
|
"babel-jest": "^24.8.0",
|
||||||
|
"babel-preset-env": "^1.7.0",
|
||||||
"eslint": "^5.16.0",
|
"eslint": "^5.16.0",
|
||||||
"eslint-plugin-vue": "^5.0.0",
|
"eslint-plugin-vue": "^5.0.0",
|
||||||
|
"jest": "^24.8.0",
|
||||||
|
"node-sass": "^4.12.0",
|
||||||
|
"vue-jest": "^3.0.4",
|
||||||
"vue-template-compiler": "^2.6.10"
|
"vue-template-compiler": "^2.6.10"
|
||||||
|
},
|
||||||
|
"eslintConfig": {
|
||||||
|
"root": true,
|
||||||
|
"env": {
|
||||||
|
"node": true
|
||||||
|
},
|
||||||
|
"extends": [
|
||||||
|
"plugin:vue/essential",
|
||||||
|
"eslint:recommended"
|
||||||
|
],
|
||||||
|
"rules": {},
|
||||||
|
"parserOptions": {
|
||||||
|
"parser": "babel-eslint"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"postcss": {
|
||||||
|
"plugins": {
|
||||||
|
"autoprefixer": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"browserslist": [
|
||||||
|
"> 1%",
|
||||||
|
"last 2 versions"
|
||||||
|
],
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"vue"
|
||||||
|
],
|
||||||
|
"transform": {
|
||||||
|
".*\\.(vue)$": "vue-jest",
|
||||||
|
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
plugins: {
|
|
||||||
autoprefixer: {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
||||||
<link rel="stylesheet" href="<%= BASE_URL %>css/scroll.css">
|
<link rel="stylesheet" href="<%= BASE_URL %>css/scroll.css">
|
||||||
<title>Loot-a-Lot !</title>
|
<title>Loot-a-Lot !</title>
|
||||||
<script defer src="<%= BASE_URL %>fontawesome/js/all.js"></script>
|
<script defer src="fontawesome/js/all.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|||||||
@@ -1,98 +1,18 @@
|
|||||||
<template>
|
<template>
|
||||||
<PlayerView
|
<main id="app" class="section">
|
||||||
:id="player_id"
|
<section id="content" class="columns is-desktop">
|
||||||
v-slot="{ player, loot, notifications, actions, claims }"
|
<Player></Player>
|
||||||
>
|
<div class="column">
|
||||||
<main id="app" class="container">
|
<Chest :player="0" v-if="state.initiated"></Chest>
|
||||||
<header>
|
</div>
|
||||||
<HeaderBar>
|
</section>
|
||||||
<template v-slot:title>
|
</main>
|
||||||
{{ player.name }}
|
|
||||||
</template>
|
|
||||||
<template v-slot:links>
|
|
||||||
<a class="navbar-item">History of Loot</a>
|
|
||||||
<template v-if="playerIsGroup">
|
|
||||||
<hr class="navbar-divider">
|
|
||||||
<div class="navbar-item heading">Admin</div>
|
|
||||||
<a class="navbar-item">"Resolve claims"</a>
|
|
||||||
<a class="navbar-item">"Add player"</a>
|
|
||||||
</template>
|
|
||||||
<hr class="navbar-divider">
|
|
||||||
<div class="navbar-item heading">Changer</div>
|
|
||||||
<a v-for="(p,i) in playerList" :key="i"
|
|
||||||
@click="setActivePlayer(i)"
|
|
||||||
href="#" class="navbar-item">
|
|
||||||
{{ p.name }}</a>
|
|
||||||
</template>
|
|
||||||
</HeaderBar>
|
|
||||||
<Wealth
|
|
||||||
:wealth="[player.cp, player.sp, player.gp, player.pp]"
|
|
||||||
:debt="player.debt"
|
|
||||||
@update="actions.updateWealth"
|
|
||||||
></Wealth>
|
|
||||||
<p v-show="notifications.length > 0">{{ notifications }}</p>
|
|
||||||
</header>
|
|
||||||
<nav>
|
|
||||||
<div class="tabs is-centered is-boxed is-medium">
|
|
||||||
<ul>
|
|
||||||
<li :class="{ 'is-active': activeView == 'group' }">
|
|
||||||
<a @click="switchView('group')">
|
|
||||||
Coffre de groupe
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li v-show="!playerIsGroup" :class="{ 'is-active': activeView == 'player' }">
|
|
||||||
<a @click="switchView('player')">
|
|
||||||
Mon coffre
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li :class="{'is-active': activeView == 'adding' }">
|
|
||||||
<a class="has-text-grey-light"
|
|
||||||
@click="switchView('adding')">
|
|
||||||
+ {{ playerIsGroup ? 'Nouveau Loot' : 'Acheter' }}
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
<main class="section">
|
|
||||||
<template v-if="isAdding">
|
|
||||||
<Loot v-if="playerIsGroup"
|
|
||||||
:inventory="itemsInventory"
|
|
||||||
@addItem="item => pending_loot.push(item)"
|
|
||||||
@confirmAction="addNewLoot"
|
|
||||||
></Loot>
|
|
||||||
<AddingChest
|
|
||||||
:player="player.id"
|
|
||||||
:claims="claims"
|
|
||||||
:items="playerIsGroup ? pending_loot : itemsInShop"
|
|
||||||
:perms="playerIsGroup ? {} : { canBuy: true }"
|
|
||||||
@buy="(data) => { switchView('player'); actions.buyItems(data); }">
|
|
||||||
</AddingChest>
|
|
||||||
</template>
|
|
||||||
<Chest v-else
|
|
||||||
:player="player.id"
|
|
||||||
:claims="claims"
|
|
||||||
:items="showPlayerChest ? loot : groupLoot"
|
|
||||||
:perms="{
|
|
||||||
canGrab: !(showPlayerChest || playerIsGroup),
|
|
||||||
canSell: showPlayerChest || playerIsGroup
|
|
||||||
}"
|
|
||||||
@sell="actions.sellItems"
|
|
||||||
@claim="actions.putClaim"
|
|
||||||
@unclaim="actions.withdrawClaim">
|
|
||||||
</Chest>
|
|
||||||
</main>
|
|
||||||
</main>
|
|
||||||
</PlayerView>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import PlayerView from './components/PlayerView.js'
|
import Player from './components/Player.vue'
|
||||||
import HeaderBar from './components/HeaderBar.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 { AppStorage } from './AppStorage'
|
||||||
import { api } from './lootalot.js'
|
|
||||||
|
|
||||||
function getCookie(cname) {
|
function getCookie(cname) {
|
||||||
var name = cname + "=";
|
var name = cname + "=";
|
||||||
@@ -114,74 +34,33 @@ export default {
|
|||||||
name: 'app',
|
name: 'app',
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
player_id: 0,
|
state: AppStorage.state,
|
||||||
playerList: [],
|
|
||||||
activeView: 'group',
|
|
||||||
groupLoot: [],
|
|
||||||
itemsInventory: [],
|
|
||||||
itemsInShop: [{id: 1, name: "Item from shop #1", base_price: 2000}],
|
|
||||||
pending_loot: [],
|
|
||||||
initiated: false,
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
components: {
|
components: {
|
||||||
PlayerView,
|
Player,
|
||||||
HeaderBar,
|
Chest
|
||||||
'AddingChest': Chest, // Alias to prevent component re-use
|
|
||||||
Chest,
|
|
||||||
Wealth,
|
|
||||||
Loot,
|
|
||||||
},
|
},
|
||||||
created () {
|
created () {
|
||||||
const cookie = getCookie("player_id");
|
// Initiate with active player set to value found in cookie
|
||||||
this.player_id = cookie ? Number(cookie) : 0;
|
// or as group by default.
|
||||||
Promise.all([
|
const cookie = getCookie("player_id");
|
||||||
api.fetch("players/", "GET", null),
|
let playerId;
|
||||||
api.fetch("players/0/loot", "GET", null),
|
if (cookie == "") {
|
||||||
api.fetch("items", "GET", null),
|
playerId = 0;
|
||||||
])
|
} else {
|
||||||
.then(([players, loot, items]) => {
|
playerId = Number(cookie);
|
||||||
this.playerList = players.value;
|
|
||||||
this.groupLoot = loot.value;
|
|
||||||
this.itemsInventory = items.value;
|
|
||||||
})
|
|
||||||
.catch(r => alert("Error ! \n" + r))
|
|
||||||
.then(() => this.initiated = true);
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
setActivePlayer (idx) {
|
|
||||||
if (idx == 0) this.switchView('group');
|
|
||||||
this.player_id = Number(idx)
|
|
||||||
document.cookie = `player_id=${idx};`;
|
|
||||||
},
|
|
||||||
switchView (viewId) {
|
|
||||||
if (!['group', 'player', 'adding'].includes(viewId)) {
|
|
||||||
console.error("Not a valid view ID :", viewId);
|
|
||||||
}
|
|
||||||
this.activeView = viewId;
|
|
||||||
},
|
|
||||||
addNewLoot () {
|
|
||||||
api.fetch("players/0/loot", "POST", {
|
|
||||||
source_name: "Dummy name",
|
|
||||||
items: this.pending_loot,
|
|
||||||
})
|
|
||||||
.then(() => {
|
|
||||||
this.pending_loot = []
|
|
||||||
this.switchView('group');
|
|
||||||
})
|
|
||||||
.catch(r => alert("Error: " + r));
|
|
||||||
}
|
}
|
||||||
|
AppStorage.initStorage(playerId);
|
||||||
},
|
},
|
||||||
computed: {
|
|
||||||
showPlayerChest () { return this.activeView == 'player' },
|
|
||||||
isAdding () { return this.activeView == 'adding' },
|
|
||||||
playerIsGroup () { return this.player_id == 0 },
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style>
|
||||||
header {
|
#app {
|
||||||
padding-bottom: 1.5em;
|
font-family: 'Montserrat', Helvetica, Arial, sans-serif;
|
||||||
}
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
163
lootalot_front/src/AppStorage.js
Normal file
163
lootalot_front/src/AppStorage.js
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
import Vue from 'vue'
|
||||||
|
|
||||||
|
const API_BASEURL = "http://localhost:8088/api/"
|
||||||
|
const API_ENDPOINT = function (tailString) {
|
||||||
|
return API_BASEURL + tailString;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Api = {
|
||||||
|
fetchPlayerList () {
|
||||||
|
return fetch(API_ENDPOINT("players"))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error ", e));
|
||||||
|
},
|
||||||
|
fetchClaims () {
|
||||||
|
return fetch(API_ENDPOINT("claims"))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error ", e));
|
||||||
|
},
|
||||||
|
fetchLoot (playerId) {
|
||||||
|
return fetch(API_ENDPOINT(playerId + "/loot"))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error", e));
|
||||||
|
},
|
||||||
|
putClaim (playerId, itemId) {
|
||||||
|
return fetch(API_ENDPOINT(playerId + "/claim/" + itemId))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error", e));
|
||||||
|
},
|
||||||
|
unClaim (playerId, itemId) {
|
||||||
|
return fetch(API_ENDPOINT(playerId + "/unclaim/" + itemId))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error", e));
|
||||||
|
},
|
||||||
|
updateWealth (playerId, goldValue) {
|
||||||
|
return fetch(API_ENDPOINT(playerId + "/update-wealth/" + goldValue))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error", e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
export const AppStorage = {
|
||||||
|
debug: true,
|
||||||
|
state: {
|
||||||
|
player_id: 0,
|
||||||
|
player_list: {},
|
||||||
|
player_loot: {},
|
||||||
|
player_claims: {},
|
||||||
|
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(), ])
|
||||||
|
.then(data => {
|
||||||
|
const [players, claims] = data;
|
||||||
|
this.__initPlayerList(players);
|
||||||
|
this.__initClaimsStore(claims);
|
||||||
|
});
|
||||||
|
// TODO: when __initPlayerList won't use promises
|
||||||
|
//.then(_ => this.state.initiated = true);
|
||||||
|
},
|
||||||
|
__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_loot, playerId, []);
|
||||||
|
Vue.set(this.state.player_claims, playerId, []);
|
||||||
|
}
|
||||||
|
// Hack for now !!
|
||||||
|
// Fetch all players loot and wait to set initiated to true
|
||||||
|
var promises = [];
|
||||||
|
for (var idx in data) {
|
||||||
|
const playerId = data[idx].id;
|
||||||
|
var promise = Api.fetchLoot(playerId)
|
||||||
|
.then(data => data.forEach(
|
||||||
|
item => {
|
||||||
|
if (this.debug) console.log("add looted item", item, playerId)
|
||||||
|
this.state.player_loot[playerId].push(item)
|
||||||
|
}
|
||||||
|
));
|
||||||
|
promises.push(promise);
|
||||||
|
}
|
||||||
|
Promise.all(promises).then(_ => this.state.initiated = true);
|
||||||
|
},
|
||||||
|
// User actions
|
||||||
|
// Sets a new active player by id
|
||||||
|
setActivePlayer (newPlayerId) {
|
||||||
|
if (this.debug) console.log('setActivePlayer to ', newPlayerId)
|
||||||
|
this.state.player_id = 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
|
||||||
|
},
|
||||||
|
// TODO
|
||||||
|
// get the content of a player Chest, retrieve form cache or fetched
|
||||||
|
// will replace hack that loads *all* chest...
|
||||||
|
getPlayerLoot (playerId) {
|
||||||
|
|
||||||
|
},
|
||||||
|
updatePlayerWealth (goldValue) {
|
||||||
|
return Api.updateWealth(this.state.player_id, goldValue)
|
||||||
|
.then(done => {
|
||||||
|
if (done.executed) {
|
||||||
|
// Update player wealth
|
||||||
|
var diff = done.response;
|
||||||
|
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];
|
||||||
|
}
|
||||||
|
return done.executed;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// Put a claim on an item from group chest.
|
||||||
|
putRequest (itemId) {
|
||||||
|
const playerId = this.state.player_id
|
||||||
|
Api.putClaim(playerId, itemId)
|
||||||
|
.then(done => {
|
||||||
|
if (done.executed) {
|
||||||
|
// Update cliend-side state
|
||||||
|
this.state.player_claims[playerId].push(itemId);
|
||||||
|
} else {
|
||||||
|
if (this.debug) console.log("API responded with 'false'")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// Withdraws a claim.
|
||||||
|
cancelRequest(itemId) {
|
||||||
|
const playerId = this.state.player_id
|
||||||
|
Api.unClaim(playerId, itemId)
|
||||||
|
.then(done => {
|
||||||
|
if (done.executed) {
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (this.debug) console.log("API responded with 'false'")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,166 +1,168 @@
|
|||||||
<template>
|
<template>
|
||||||
<article>
|
<div class="container is-paddingless">
|
||||||
<p class="control has-icons-left">
|
<div v-if="mainControlsDisplayed"
|
||||||
<input type="text" class="input" v-model="searchText">
|
class="columns is-mobile is-vcentered"
|
||||||
<span class="icon is-small is-left"><i class="fas fa-search"></i></span>
|
>
|
||||||
</p>
|
<div class="column is-narrow">
|
||||||
<table class="table is-fullwidth is-striped">
|
<span class="icon is-large">
|
||||||
|
<i class="fas fa-2x fa-dragon"></i>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="column has-text-left">
|
||||||
|
<h1 class="title">Coffre de groupe</h1>
|
||||||
|
</div>
|
||||||
|
<div class="column" v-show="canAdd">
|
||||||
|
<div v-show="mainControlsDisplayed" class="buttons is-right">
|
||||||
|
<button v-if="canAdd"
|
||||||
|
class="button is-inverted is-info"
|
||||||
|
@click="is_adding = true"
|
||||||
|
>
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fas fa-box-open"></i>
|
||||||
|
</span>
|
||||||
|
<p>Nouveau loot</p>
|
||||||
|
</button>
|
||||||
|
<button class="button is-inverted is-primary">
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fas fa-coins"></i>
|
||||||
|
</span>
|
||||||
|
<p>Tout vendre</p>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Loot v-if="is_adding" @done="is_adding = false"></Loot>
|
||||||
|
<table v-else class="table is-fullwidth is-striped" >
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th width="100%">Objets</th>
|
<th>Objets de {{ player }}</th>
|
||||||
<th>Valeur</th>
|
<th v-if="canGrab"></th>
|
||||||
<th>
|
<th v-if="canSell">
|
||||||
<div v-if="perms.canSell" class="buttons" :class="{'has-addons': is_selling}">
|
<div class="buttons is-right">
|
||||||
<button class="button"
|
<button class="button"
|
||||||
:class="is_selling ? 'is-danger' : 'is-warning'"
|
:class="is_selling ? 'is-danger' : 'is-warning'"
|
||||||
@click="sellSelectedItems"
|
@click="is_selling = !is_selling"
|
||||||
>
|
>
|
||||||
<span class="icon">
|
<span class="icon">
|
||||||
<i class="fas fa-coins"></i>
|
<i class="fas fa-coins"></i>
|
||||||
</span>
|
</span>
|
||||||
<p v-if="!is_selling">Vendre</p>
|
<p v-if="!is_selling">
|
||||||
<p v-else>{{ selected_items.length > 0 ? `${totalSelectedValue} po` : 'Annuler' }}</p>
|
Vendre</p>
|
||||||
</button>
|
<p v-else>
|
||||||
<PercentInput v-show="is_selling" v-model="global_mod"></PercentInput>
|
{{ totalSellValue ? totalSellValue : 'Annuler' }}</p>
|
||||||
</div>
|
</button>
|
||||||
<div v-else-if="perms.canBuy">
|
<PercentInput v-show="is_selling">
|
||||||
<button class="button is-danger is-fullwidth"
|
</PercentInput>
|
||||||
:disabled="selected_items.length == 0"
|
</div>
|
||||||
@click="buySelectedItems"
|
</th>
|
||||||
>Acheter ({{ totalSelectedValue}}po)</button>
|
|
||||||
</div>
|
|
||||||
<div v-else-if="perms.canGrab">
|
|
||||||
<button class="button is-static is-fullwidth">Demander</button>
|
|
||||||
</div>
|
|
||||||
</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<template v-for="(item, idx) in shownItems">
|
|
||||||
<tr :key="`row-${idx}`">
|
|
||||||
<td>
|
|
||||||
<strong>{{item.name}}</strong>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
{{ is_selling ? item.base_price / 2 : item.base_price }}po
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<Request
|
|
||||||
v-if="perms.canGrab"
|
|
||||||
:id="player"
|
|
||||||
:claims="claims"
|
|
||||||
:item="item.id"
|
|
||||||
@claim="(data) => $emit('claim', data)"
|
|
||||||
@unclaim="(data) => $emit('unclaim', data)"
|
|
||||||
></Request>
|
|
||||||
<Selector
|
|
||||||
v-else-if="showSelectors"
|
|
||||||
:id="item.id"
|
|
||||||
v-model="selected_items"
|
|
||||||
></Selector>
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
</template>
|
</thead>
|
||||||
</tbody>
|
<tbody>
|
||||||
</table>
|
<template v-for="(item, idx) in content">
|
||||||
</article>
|
<tr :key="`row-${idx}`">
|
||||||
|
<td>{{item.name}}</td>
|
||||||
|
<td v-if="canGrab">
|
||||||
|
<Request :item="item.id"></Request>
|
||||||
|
</td>
|
||||||
|
<td v-if="canSell">
|
||||||
|
<div class="field is-grouped is-pulled-right" v-show="is_selling">
|
||||||
|
<div class="control">
|
||||||
|
<label class="label">
|
||||||
|
<input type="checkbox"
|
||||||
|
id="`item-${idx}`"
|
||||||
|
:value="item.id"
|
||||||
|
v-model="sell_selected">
|
||||||
|
{{item.base_price / 2}} GP
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<PercentInput></PercentInput>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</template>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
import { AppStorage } from '../AppStorage'
|
||||||
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 Loot from './Loot.vue'
|
||||||
import { api } from '../lootalot.js'
|
|
||||||
/*
|
/*
|
||||||
The chest displays a collection of items.
|
The chest displays the collection of items owned by a player
|
||||||
|
|
||||||
A set of permissions is passed as props, to update
|
TO TEST :
|
||||||
the possible actions of active user upon these items.
|
- Possible interactions depends on player_id and current chest
|
||||||
|
- Objects are displayed as a table
|
||||||
|
|
||||||
|
Sell workflow :
|
||||||
|
1. Click sell (sell becomes danger)
|
||||||
|
2. Check objects to sell (sell button displays total value)
|
||||||
|
3. Click sell to confirm
|
||||||
*/
|
*/
|
||||||
export default {
|
export default {
|
||||||
props: {
|
props: {
|
||||||
player: {
|
player: {
|
||||||
type: Number,
|
type: Number,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
default: 0
|
||||||
items: {
|
}
|
||||||
type: Array,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
perms: {
|
|
||||||
type: Object,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
claims: {
|
|
||||||
type: Object,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
components: {
|
components: {
|
||||||
Request,
|
Request,
|
||||||
PercentInput,
|
PercentInput,
|
||||||
Selector,
|
Loot,
|
||||||
},
|
},
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
|
app_state: AppStorage.state,
|
||||||
is_selling: false,
|
is_selling: false,
|
||||||
selected_items: [],
|
is_adding: false,
|
||||||
global_mod: 0,
|
sell_selected: [],
|
||||||
searchText: "",
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
buySelectedItems () {
|
fetchLoot () {
|
||||||
this.$emit("buy", this.selected_items);
|
|
||||||
this.selected_items = [];
|
}
|
||||||
},
|
|
||||||
sellSelectedItems () {
|
|
||||||
if (!this.is_selling) {
|
|
||||||
this.is_selling = true;
|
|
||||||
} else {
|
|
||||||
this.is_selling = false;
|
|
||||||
if (this.selected_items.length > 0) {
|
|
||||||
this.$emit("sell", this.selected_items);
|
|
||||||
this.selected_items = [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
shownItems () {
|
content () {
|
||||||
if (this.searchText != "") {
|
const playerId = this.player;
|
||||||
const searchText = this.searchText.toUpperCase();
|
console.log("Refresh chest of", playerId);
|
||||||
return this.items.filter(item => item.name.toUpperCase().includes(searchText));
|
return this.app_state.player_loot[playerId];
|
||||||
} else {
|
|
||||||
return this.items;
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
showSelectors () {
|
// Can the active user sell items from this chest ?
|
||||||
return !this.perms.canGrab
|
canSell () {
|
||||||
&& (this.is_selling || this.perms.canBuy);
|
return this.player == this.app_state.player_id;
|
||||||
},
|
},
|
||||||
totalSelectedValue () {
|
totalSellValue () {
|
||||||
var total = this.selected_items
|
const selected = this.sell_selected;
|
||||||
.map(([id, mod]) => {
|
return this.content
|
||||||
const item = this.items.find(item => item.id == id);
|
.filter(item => selected.includes(item.id))
|
||||||
var price = item.base_price * mod;
|
.map(item => item.base_price / 2)
|
||||||
if (this.is_selling) {
|
|
||||||
price = price / 2;
|
|
||||||
}
|
|
||||||
return price;
|
|
||||||
})
|
|
||||||
.reduce((total,value) => total + value, 0);
|
.reduce((total,value) => total + value, 0);
|
||||||
return (1 + this.global_mod / 100) * total;
|
|
||||||
},
|
},
|
||||||
|
// Can the user grab items from this chest ?
|
||||||
|
canGrab () {
|
||||||
|
return (this.app_state.player_id != 0 // User is not the group
|
||||||
|
&& this.player == 0); // This is the group chest
|
||||||
|
},
|
||||||
|
canAdd () {
|
||||||
|
return (this.app_state.player_id == 0
|
||||||
|
&& this.player == 0);
|
||||||
|
},
|
||||||
|
// The main controls are only displayed on group chest
|
||||||
|
mainControlsDisplayed () {
|
||||||
|
return (this.player == 0
|
||||||
|
&& !this.is_adding);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.table td, .table th { vertical-align: middle; }
|
.table td, .table th { vertical-align: middle; }
|
||||||
.buttons { flex-wrap: nowrap; }
|
|
||||||
label.is-checkbox {
|
|
||||||
background-color: #eee;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
<template>
|
|
||||||
<nav class="navbar is-info">
|
|
||||||
<div class="navbar-brand">
|
|
||||||
<p class="navbar-item is-size-4"><slot name="title">...</slot></p>
|
|
||||||
<a role="button" class="navbar-burger" aria-label="menu" aria-expanded="false"
|
|
||||||
@click="switchMobileVisibility">
|
|
||||||
<span aria-hidden="true"></span>
|
|
||||||
<span aria-hidden="true"></span>
|
|
||||||
<span aria-hidden="true"></span>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
<div id="menu" class="navbar-menu" :class="{'is-active': showOnMobile }">
|
|
||||||
<div class="navbar-end">
|
|
||||||
<div class="navbar-item has-dropdown is-hoverable">
|
|
||||||
<a class="navbar-link">Autres</a>
|
|
||||||
<div class="navbar-dropdown is-right" @click="switchMobileVisibility">
|
|
||||||
<slot name="links">
|
|
||||||
<a class="navbar-item">History of Loot</a>
|
|
||||||
</slot>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
data () { return { showOnMobile: false } },
|
|
||||||
methods: {
|
|
||||||
switchMobileVisibility () {
|
|
||||||
this.showOnMobile = !this.showOnMobile
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,109 +1,93 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="field is-horizontal">
|
<div class="container is-paddingless">
|
||||||
<div class="field-label">
|
<div class="field has-addons">
|
||||||
<label class="label">Nouvel objet</label>
|
<div class="control is-expanded"
|
||||||
</div>
|
:class="{'is-loading': is_loading }">
|
||||||
<div class="field-body">
|
<input type="text"
|
||||||
<div class="field">
|
v-model="search"
|
||||||
<div class="control is-expanded">
|
@input="autoCompletion"
|
||||||
<input type="text"
|
class="input"
|
||||||
name="name"
|
:class="{'is-danger': no_results,
|
||||||
placeholder="Nom de l'objet"
|
'is-warning': auto_open}"
|
||||||
v-model="item.name"
|
autocomplete="on">
|
||||||
@input="autoCompletion"
|
</input>
|
||||||
class="input"
|
</div>
|
||||||
autocomplete="on"
|
<div class="control">
|
||||||
>
|
<button class="button is-primary"
|
||||||
</div>
|
:disabled="no_results"
|
||||||
<div class="dropdown" :class="{'is-active': showCompletionFrame}">
|
@click="addItem"
|
||||||
<div class="dropdown-menu">
|
>+</button>
|
||||||
<div class="dropdown-content">
|
</div>
|
||||||
<a v-for="(result,i) in results"
|
|
||||||
:key="i"
|
|
||||||
@click="setResult(result)"
|
|
||||||
class="dropdown-item"
|
|
||||||
>{{ result.name }}</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="field is-expanded has-addons" v-show="item.name != ''">
|
|
||||||
<p class="control"><a class="button is-static">PO</a></p>
|
|
||||||
<p class="control">
|
|
||||||
<input type="text"
|
|
||||||
name="base_price"
|
|
||||||
placeholder="Prix"
|
|
||||||
class="input"
|
|
||||||
:class="{'is-danger': item.base_price == ''}"
|
|
||||||
v-model.number="item.base_price"
|
|
||||||
>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
|
||||||
<div class="control">
|
|
||||||
<button class="button is-primary"
|
|
||||||
@click="addItem"
|
|
||||||
:disabled="!isItemValid"
|
|
||||||
>Ajouter</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div class="dropdown" :class="{'is-active': auto_open}">
|
||||||
|
<div class="dropdown-menu">
|
||||||
|
<div class="dropdown-content">
|
||||||
|
<a v-for="(result,i) in results" :key="i"
|
||||||
|
@click="setResult(result.name)"
|
||||||
|
class="dropdown-item"
|
||||||
|
>
|
||||||
|
{{ result.name }}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
// List of items for autocomplete
|
||||||
|
const MOCK_ITEMS = [
|
||||||
|
{id: 35, name: "Cape d'invisibilité", sell_value: 30000},
|
||||||
|
{id: 8, name: "Arc long", sell_value: 10},
|
||||||
|
];
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
props: ["source"],
|
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
is_loading: false,
|
is_loading: false,
|
||||||
item: {
|
no_results: false,
|
||||||
id: 0,
|
search: '',
|
||||||
name: '',
|
|
||||||
base_price: '',
|
|
||||||
},
|
|
||||||
results: [],
|
results: [],
|
||||||
|
auto_open: false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
autoCompletion () {
|
autoCompletion (ev) {
|
||||||
// Unset any previous value on input (for every field except item's name)
|
// TODO: a lot happens here that
|
||||||
this.item.base_price = '';
|
// need to be clarified
|
||||||
if (this.item.name == '') {
|
if (this.search == '') {
|
||||||
|
this.auto_open = false;
|
||||||
this.results = [];
|
this.results = [];
|
||||||
|
this.no_results = false;
|
||||||
} else {
|
} else {
|
||||||
this.results = this.source.filter(
|
this.results = MOCK_ITEMS.filter(item => {
|
||||||
item => item.name.toUpperCase().includes(this.item.name.toUpperCase())
|
return item.name.includes(this.search);
|
||||||
);
|
});
|
||||||
|
// Update status
|
||||||
|
if (this.results.length == 0) {
|
||||||
|
this.no_results = true;
|
||||||
|
} else {
|
||||||
|
this.no_results = false;
|
||||||
|
this.auto_open = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
setResult(result) {
|
setResult(result) {
|
||||||
this.item.id = result.id;
|
this.search = result;
|
||||||
this.item.name = result.name;
|
this.auto_open = false;
|
||||||
this.item.base_price = result.base_price;
|
|
||||||
// Clear results to close completionFrame
|
|
||||||
this.results = [];
|
|
||||||
},
|
},
|
||||||
addItem () {
|
addItem () {
|
||||||
this.$emit("addItem", this.item);
|
this.$emit("addItem", this.search);
|
||||||
this.item = {
|
this.search = '';
|
||||||
name: '',
|
|
||||||
base_price: '',
|
|
||||||
};
|
|
||||||
this.results = [];
|
this.results = [];
|
||||||
},
|
this.no_results = false;
|
||||||
|
this.auto_open = false;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
|
||||||
showCompletionFrame () { return this.results.length > 0 },
|
|
||||||
isItemValid () { return this.item.name != '' && this.item.base_price != '' },
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.dropdown, .dropdown-menu {
|
.dropdown, .dropdown-menu { min-width: 100%; margin-top: 0; padding-top: 0;}
|
||||||
min-width: 100%;
|
.dropdown { top: -0.75rem; }
|
||||||
margin-top: 0;
|
|
||||||
padding-top: 0;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,33 +1,40 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="box">
|
<div class="card is-shadowless">
|
||||||
<ItemInput
|
<div class="card-header">
|
||||||
@addItem="onAddItem"
|
<p class="card-header-title">
|
||||||
:source="inventory"
|
Nouveau loot - {{ looted.length }} objet(s)</p>
|
||||||
></ItemInput>
|
</div>
|
||||||
<div class="field is-horizontal">
|
<div class="card-content">
|
||||||
<div class="field-label"><label class="label">ou</label></div>
|
<ItemInput @addItem="onAddItem"></ItemInput>
|
||||||
<div class="field-body">
|
<p v-for="(item, idx) in looted" :key="idx"
|
||||||
<div class="field">
|
class="has-text-left is-size-5">
|
||||||
<div class="control">
|
{{ item }}
|
||||||
<button class="button is-primary">Depuis une liste</button>
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="card-footer">
|
||||||
|
<div class="card-footer-item buttons is-center">
|
||||||
|
<a class="button is-primary">Confirmer</a>
|
||||||
|
<a @click="onClose" class="button is-danger">Annuler</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
<button class="button is-danger" @click="$emit('confirmAction')">Finaliser</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import ItemInput from './ItemInput.vue'
|
import ItemInput from './ItemInput.vue'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
props: ["inventory"],
|
|
||||||
components: { ItemInput },
|
components: { ItemInput },
|
||||||
data () { return {}; },
|
data () { return {
|
||||||
|
looted: [],
|
||||||
|
};
|
||||||
|
},
|
||||||
methods: {
|
methods: {
|
||||||
onAddItem (item) {
|
onAddItem (item) {
|
||||||
this.$emit('addItem', item);
|
this.looted.push(item);
|
||||||
|
},
|
||||||
|
onClose () {
|
||||||
|
this.$emit('done');
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
27
lootalot_front/src/components/NumberInput.vue
Normal file
27
lootalot_front/src/components/NumberInput.vue
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<template>
|
||||||
|
<input type="text"
|
||||||
|
class="input"
|
||||||
|
:class="{'is-danger': has_error}"
|
||||||
|
:value="value"
|
||||||
|
@input="checkError"
|
||||||
|
></input>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
props: ["value"],
|
||||||
|
data () {
|
||||||
|
return { has_error: false};
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
checkError (ev) {
|
||||||
|
const newValue = ev.target.value;
|
||||||
|
this.has_error = isNaN(newValue);
|
||||||
|
this.$emit(
|
||||||
|
'input',
|
||||||
|
this.has_error ? 0 : Number(newValue)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -1,41 +1,28 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="field has-addons">
|
<div class="field has-addons">
|
||||||
<div v-show="is_opened" class="control has-icons-left">
|
<div v-show="is_opened" class="control has-icons-left">
|
||||||
<input class="input" :value="value" @input="input" type="number" size="3" min="-50" max=50 step=5>
|
<input class="input is-small" type="number" size="3" min=-50 max=50 step=5>
|
||||||
<span class="icon is-left">
|
<span class="icon is-small is-left">
|
||||||
<i class="fas fa-percent"></i>
|
<i class="fas fa-percent"></i>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="control">
|
<div class="control">
|
||||||
<button class="button" @click="switchOpenedState">
|
<button class="button is-small is-outlined"
|
||||||
<small v-if="!is_opened">Mod.</small>
|
@click="is_opened = !is_opened"
|
||||||
<span v-else class="icon"><i class="fas fa-times-circle"></i></span>
|
>
|
||||||
</button>
|
<small v-if="!is_opened">Mod.</small>
|
||||||
</div>
|
<span v-else class="icon"><i class="fas fa-times-circle"></i></span>
|
||||||
</div>
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
export default {
|
export default {
|
||||||
props: ["value"],
|
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
is_opened: false,
|
is_opened: false,
|
||||||
};
|
};
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
input (event) { this.$emit("input", event.target.value); },
|
|
||||||
switchOpenedState () {
|
|
||||||
this.is_opened = !this.is_opened;
|
|
||||||
// Reset the modifier in closed state
|
|
||||||
if (!this.is_opened) {
|
|
||||||
this.$emit("input", 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.input { width: 6em; }
|
|
||||||
</style>
|
|
||||||
|
|||||||
165
lootalot_front/src/components/Player.vue
Normal file
165
lootalot_front/src/components/Player.vue
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
<template>
|
||||||
|
<div class="column is-one-third-desktop">
|
||||||
|
<div id="sidebar" class="card">
|
||||||
|
<header id="sidebar-heading" class="card-header">
|
||||||
|
<p class="card-header-title">
|
||||||
|
{{ app_state.initiated ? player.name : "..." }}</p>
|
||||||
|
<div class="dropdown is-right"
|
||||||
|
:class="{ 'is-active': show_dropdown }">
|
||||||
|
<div class="dropdown-trigger" ref="dropdown_btn">
|
||||||
|
<a id="change_player" class="card-header-icon"
|
||||||
|
@click="show_dropdown = !show_dropdown"
|
||||||
|
aria-haspopup="true" aria-controls="dropdown-menu">
|
||||||
|
<span class="icon is-small">
|
||||||
|
<i class="fas fa-exchange-alt"></i>
|
||||||
|
</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<div class="dropdown-menu" id="dropdown-menu" role="menu"
|
||||||
|
v-closable="{ exclude: ['dropdown_btn'], handler: 'closeDropdown', visible: show_dropdown }">
|
||||||
|
<div class="dropdown-content" v-if="app_state.initiated">
|
||||||
|
<a v-for="(p,i) in app_state.player_list" :key="i"
|
||||||
|
@click="setActivePlayer(i)"
|
||||||
|
href="#" class="dropdown-item">
|
||||||
|
{{ p.name }}</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div class="card-content">
|
||||||
|
<Wealth :wealth="wealth" :debt="player.debt"></Wealth>
|
||||||
|
<div class="box is-shadowless" v-show="!playerIsGroup">
|
||||||
|
<div class="columns is-vcentered" @click="switchPlayerChestVisibility">
|
||||||
|
<div class="column is-one-fifth">
|
||||||
|
<span class="icon is-large">
|
||||||
|
<i class="fas fa-2x fa-box"></i>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="column if-four-fifth has-text-left">
|
||||||
|
<p class="is-size-3">Coffre</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Chest :player="app_state.player_id"
|
||||||
|
v-show="app_state.show_player_chest">
|
||||||
|
</Chest>
|
||||||
|
<a href="#" class="button is-link is-fullwidth is-hidden" disabled>Historique</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import { AppStorage } from '../AppStorage'
|
||||||
|
import Chest from './Chest.vue'
|
||||||
|
import Wealth from './Wealth.vue'
|
||||||
|
/*
|
||||||
|
The Player control board.
|
||||||
|
To test :
|
||||||
|
- Player name is displayed
|
||||||
|
- Player's wealth is displayed -> Inside Wealth component
|
||||||
|
- Dropdown:
|
||||||
|
- The first item is the group
|
||||||
|
- Opened by activator
|
||||||
|
- Closed when clicked outside
|
||||||
|
- Click on item does switch active player
|
||||||
|
- Switch player :
|
||||||
|
- Name is updated when player_id is updated
|
||||||
|
- Wealth is updated -> Inside Wealth component
|
||||||
|
- Chest button controls Chest visibility
|
||||||
|
|
||||||
|
*/
|
||||||
|
let handleOutsideClick;
|
||||||
|
export default {
|
||||||
|
components: { Chest, Wealth },
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
app_state: AppStorage.state,
|
||||||
|
show_dropdown: false,
|
||||||
|
edit_wealth: false,
|
||||||
|
handleOutsideClick: null,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
player () {
|
||||||
|
if (!this.app_state.initiated) return {}
|
||||||
|
const idx = this.app_state.player_id;
|
||||||
|
return this.app_state.player_list[idx];
|
||||||
|
},
|
||||||
|
wealth () {
|
||||||
|
if (!this.app_state.initiated) {
|
||||||
|
return ["-", "-", "-", "-"];
|
||||||
|
} else {
|
||||||
|
const cp = this.player.cp
|
||||||
|
const sp = this.player.sp
|
||||||
|
const gp = this.player.gp
|
||||||
|
const pp = this.player.pp
|
||||||
|
return [cp, sp, gp, pp];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// Check if the active player is the special 'Group' player
|
||||||
|
playerIsGroup () {
|
||||||
|
return this.app_state.player_id == 0;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
switchPlayerChestVisibility () {
|
||||||
|
AppStorage.switchPlayerChestVisibility();
|
||||||
|
},
|
||||||
|
hidePlayerChest () {
|
||||||
|
if (this.app_state.show_player_chest) {
|
||||||
|
this.switchPlayerChestVisibility();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
setActivePlayer (playerIdx) {
|
||||||
|
var playerIdx = Number(playerIdx);
|
||||||
|
AppStorage.setActivePlayer(playerIdx);
|
||||||
|
if (playerIdx == 0) { this.hidePlayerChest() }
|
||||||
|
},
|
||||||
|
closeDropdown () {
|
||||||
|
this.show_dropdown = false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
directives: {
|
||||||
|
'closable': {
|
||||||
|
bind: function(el, binding, vnode) {
|
||||||
|
handleOutsideClick = (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
const { exclude, handler } = binding.value;
|
||||||
|
let excludedElClicked = false;
|
||||||
|
exclude.forEach(refName => {
|
||||||
|
if (!excludedElClicked) {
|
||||||
|
const elt = vnode.context.$refs[refName];
|
||||||
|
excludedElClicked = elt.contains(e.target);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!excludedElClicked) {
|
||||||
|
console.log('outsideCloseDropdown');
|
||||||
|
vnode.context[handler]()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
},
|
||||||
|
// Bind custom handler only when dropdown is visible
|
||||||
|
update: function(el, binding, vnode, _) {
|
||||||
|
const { visible } = binding.value;
|
||||||
|
if (visible) {
|
||||||
|
document.addEventListener('click', handleOutsideClick);
|
||||||
|
document.addEventListener('touchstart', handleOutsideClick);
|
||||||
|
} else {
|
||||||
|
document.removeEventListener('click', handleOutsideClick);
|
||||||
|
document.removeEventListener('touchstart', handleOutsideClick);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
unbind: function() { console.log("unbind");
|
||||||
|
document.removeEventListener('click', handleOutsideClick);
|
||||||
|
document.removeEventListener('touchstart', handleOutsideClick);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.fa-exchange-alt.disabled { opacity: 0.4; }
|
||||||
|
</style>
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
import { api } from '../lootalot.js'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
props: ["id"],
|
|
||||||
data () { return {
|
|
||||||
player: {
|
|
||||||
name: "Loading",
|
|
||||||
id: 0,
|
|
||||||
cp: '-', sp: '-', gp: '-', pp: '-',
|
|
||||||
debt: 0,
|
|
||||||
},
|
|
||||||
notifications: [],
|
|
||||||
loot: [],
|
|
||||||
claims: {},
|
|
||||||
}},
|
|
||||||
created () {
|
|
||||||
api.fetch("claims", "GET", null)
|
|
||||||
.then(r => {
|
|
||||||
for (var idx in r.value) {
|
|
||||||
var claim = r.value[idx];
|
|
||||||
if (!(claim.player_id in this.claims)) {
|
|
||||||
this.$set(this.claims, claim.player_id, []);
|
|
||||||
}
|
|
||||||
this.claims[claim.player_id].push(claim.loot_id);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
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: {
|
|
||||||
id: {
|
|
||||||
immediate: true,
|
|
||||||
handler: function(newId) {
|
|
||||||
this.call("", "GET", null)
|
|
||||||
.then(p => this.player = p)
|
|
||||||
this.call("loot", "GET", null)
|
|
||||||
.then(l => this.loot = l)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
computed: {},
|
|
||||||
render () {
|
|
||||||
return this.$scopedSlots.default({
|
|
||||||
player: this.player,
|
|
||||||
loot: this.loot,
|
|
||||||
notifications: this.notifications,
|
|
||||||
actions: {
|
|
||||||
updateWealth: this.updateWealth,
|
|
||||||
putClaim: this.putClaim,
|
|
||||||
withdrawClaim: this.withdrawClaim,
|
|
||||||
buyItems: this.buyItems,
|
|
||||||
sellItems: this.sellItems,
|
|
||||||
},
|
|
||||||
claims: this.claims,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +1,26 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="buttons">
|
<div class="buttons is-right" >
|
||||||
<template v-if="isInConflict">
|
<template v-if="isInConflict">
|
||||||
<button class="button is-success"
|
<button class="button is-success"
|
||||||
@click="cancelRequest">
|
@click="cancelRequest"
|
||||||
<span class="icon is-small">
|
>
|
||||||
<i class="fas fa-hand-peace"></i>
|
<span class="icon is-small">
|
||||||
</span>
|
<i class="fas fa-hand-peace"></i>
|
||||||
</button>
|
</span>
|
||||||
<button class="button is-danger"
|
</button>
|
||||||
@click="hardenRequest">
|
<button class="button is-danger"
|
||||||
<span class="icon is-small">
|
@click="hardenRequest"
|
||||||
<i class="fas fa-hand-middle-finger"></i>
|
>
|
||||||
</span>
|
<span class="icon is-small">
|
||||||
</button>
|
<i class="fas fa-hand-middle-finger"></i>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
</template>
|
</template>
|
||||||
<button class="button is-primary"
|
<button class="button is-primary"
|
||||||
@click="putRequest"
|
@click="putRequest"
|
||||||
:disabled="isRequested">
|
:class="{'is-outlined': isRequested}"
|
||||||
|
:disabled="isRequested"
|
||||||
|
>
|
||||||
<span class="icon is-small">
|
<span class="icon is-small">
|
||||||
<i class="fas fa-praying-hands"></i>
|
<i class="fas fa-praying-hands"></i>
|
||||||
</span>
|
</span>
|
||||||
@@ -25,41 +29,30 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
import { AppStorage } from '../AppStorage'
|
||||||
export default {
|
export default {
|
||||||
props: {
|
props: ["item"],
|
||||||
// Id of active player
|
data () {
|
||||||
id: {
|
return {
|
||||||
type: Number,
|
state: AppStorage.state,
|
||||||
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 () {
|
||||||
if (this.claims[this.id]) {
|
const reqs = this.state.player_claims[this.state.player_id];
|
||||||
return this.claims[this.id].includes(this.item);
|
return reqs.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.state.player_claims;
|
||||||
|
const playerId = this.state.player_id;
|
||||||
var reqByPlayer = false;
|
var reqByPlayer = false;
|
||||||
var reqByOther = false;
|
var reqByOther = false;
|
||||||
for (var id in this.claims) {
|
for (var key in reqs) {
|
||||||
const isReq = this.claims[id].includes(this.item);
|
const isReq = reqs[key].includes(this.item);
|
||||||
if (isReq) {
|
if (isReq) {
|
||||||
if (id == this.id) {
|
if (key == playerId) {
|
||||||
reqByPlayer = true;
|
reqByPlayer = true;
|
||||||
} else {
|
} else {
|
||||||
reqByOther = true;
|
reqByOther = true;
|
||||||
@@ -72,11 +65,11 @@
|
|||||||
methods: {
|
methods: {
|
||||||
// The active player claims the item
|
// The active player claims the item
|
||||||
putRequest () {
|
putRequest () {
|
||||||
this.$emit("claim", this.item);
|
AppStorage.putRequest(this.item)
|
||||||
},
|
},
|
||||||
// The active player withdraws his request
|
// The active player withdraws his request
|
||||||
cancelRequest () {
|
cancelRequest () {
|
||||||
this.$emit("unclaim", this.item);
|
AppStorage.cancelRequest(this.item)
|
||||||
},
|
},
|
||||||
// The active player insist on his claim
|
// The active player insist on his claim
|
||||||
// TODO: Find a simple and fun system to express
|
// TODO: Find a simple and fun system to express
|
||||||
@@ -86,7 +79,3 @@
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.buttons, .button { margin-bottom: 0; }
|
|
||||||
</style>
|
|
||||||
|
|||||||
@@ -1,57 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="buttons has-addons">
|
|
||||||
<label class="button is-fullwidth">
|
|
||||||
<input type="checkbox" class="checkbox" v-model="selected">
|
|
||||||
</label>
|
|
||||||
<PercentInput v-show="selected" v-model.number="mod_value"></PercentInput>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
import PercentInput from './PercentInput.vue'
|
|
||||||
|
|
||||||
/* Selector for a specific item, with an associated price modifier.
|
|
||||||
Acts as checkbox on a v-model, except it populates an array with [value, modifier] instead of value alone
|
|
||||||
*/
|
|
||||||
|
|
||||||
export default {
|
|
||||||
props: ["id", "value"],
|
|
||||||
components: { PercentInput },
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
selected: false,
|
|
||||||
mod_value: 0,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
modifier () {
|
|
||||||
return 1 + this.mod_value / 100;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
selected (newState) {
|
|
||||||
let idx = this._findData();
|
|
||||||
var updated = this.value;
|
|
||||||
if (newState == true && idx == -1) {
|
|
||||||
updated.push([this.id, this.modifier]);
|
|
||||||
} else if (newState == false && idx != -1 ) {
|
|
||||||
updated.splice(idx, 1);
|
|
||||||
}
|
|
||||||
this.$emit('input', updated);
|
|
||||||
},
|
|
||||||
mod_value (newState) {
|
|
||||||
let idx = this._findData();
|
|
||||||
var updated = this.value;
|
|
||||||
if (idx != -1) {
|
|
||||||
updated.splice(idx, 1, [this.id, this.modifier]);
|
|
||||||
this.$emit('input', updated);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
_findData () {
|
|
||||||
return this.value.findIndex(([val,mod]) => this.id == val);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,97 +1,92 @@
|
|||||||
<template>
|
<template>
|
||||||
<section class="level is-mobile">
|
<div class="box is-shadowless">
|
||||||
<div class="level-left">
|
<nav class="columns is-mobile is-multiline is-vcentered">
|
||||||
<div class="level-item">
|
<div class="column">
|
||||||
<span class="icon is-large" @click="editing = !editing">
|
<span class="icon is-large"
|
||||||
<i class="fas fa-2x fa-piggy-bank"></i>
|
@click="edit = !edit">
|
||||||
</span>
|
<i class="fas fa-2x fa-piggy-bank"></i>
|
||||||
</div>
|
</span>
|
||||||
<template v-if="editing">
|
<p v-if="debt" class="has-text-danger">-{{ debt }}gp </p>
|
||||||
<div class="level-item">
|
</div>
|
||||||
<div class="field has-addons">
|
<div class="column has-text-info">
|
||||||
<p class="control">
|
<p class="heading">PP</p>
|
||||||
<input class="input" type="number" step="0.01" v-model="edit_value"></input>
|
<p class="is-size-4">{{ wealth[3] }}</p>
|
||||||
</p>
|
</div>
|
||||||
<p class="control">
|
<div class="column has-text-warning">
|
||||||
<a class="button is-static">po</a>
|
<p class="heading">PO</p>
|
||||||
</p>
|
<p class="is-size-4">{{ wealth[2] }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="column has-text-grey">
|
||||||
|
<p class="heading">PA</p>
|
||||||
|
<p class="is-size-4">{{ wealth[1] }}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div class="column has-text-grey">
|
||||||
<div class="level-item">
|
<p class="heading">PC</p>
|
||||||
<button class="button is-danger" @click="updateWealth()">
|
<p class="is-size-4">{{ wealth[0] }}</p>
|
||||||
Modifier
|
</div>
|
||||||
|
</nav>
|
||||||
|
<div v-if="edit"> <!-- or v-show ? -->
|
||||||
|
<nav class="columns is-mobile">
|
||||||
|
<div class="column">
|
||||||
|
<NumberInput v-model="edit_value"></NumberInput>
|
||||||
|
</div>
|
||||||
|
<div class="column is-2">
|
||||||
|
<button class="button is-outlined is-fullwidth is-danger"
|
||||||
|
@click="updateWealth('minus')">
|
||||||
|
<span class="icon"><i class="fas fa-2x fa-minus"></i></span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
<div class="column is-2">
|
||||||
<template v-else>
|
<button class="button is-outlined is-primary is-fullwidth"
|
||||||
<div class="level-item ">
|
@click="updateWealth('plus')">
|
||||||
<p class="is-size-4">{{ pp }}</p>
|
<span class="icon"><i class="fas fa-2x fa-plus"></i></span>
|
||||||
<p class="heading">PP</p>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="level-item ">
|
</nav>
|
||||||
<p class="is-size-4">{{ gp }}</p>
|
|
||||||
<p class="heading">PO</p>
|
|
||||||
</div>
|
|
||||||
<div class="level-item ">
|
|
||||||
<p class="is-size-4 has-text-grey-light">{{ sp }}</p>
|
|
||||||
<p class="heading">PA</p>
|
|
||||||
</div>
|
|
||||||
<div class="level-item ">
|
|
||||||
<p class="is-size-4 has-text-grey-light">{{ cp }}</p>
|
|
||||||
<p class="heading">PC</p>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="level-right" v-if="debt">
|
</div>
|
||||||
<div class="level-item">
|
|
||||||
<p class="heading is-size-4 has-text-danger">Dette: {{ debt }}gp </p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
import { AppStorage } from '../AppStorage.js'
|
||||||
|
import NumberInput from './NumberInput.vue'
|
||||||
export default {
|
export default {
|
||||||
|
components: { NumberInput },
|
||||||
props: ["wealth", "debt"],
|
props: ["wealth", "debt"],
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
editing: false,
|
edit: false,
|
||||||
edit_value: 0,
|
edit_value: 0,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
updateWealth () {
|
updateWealth (op) {
|
||||||
this.$emit("update", this.edit_value);
|
var goldValue;
|
||||||
this.resetValues();
|
switch (op) {
|
||||||
|
case 'plus':
|
||||||
|
goldValue = this.edit_value;
|
||||||
|
break;
|
||||||
|
case 'minus':
|
||||||
|
goldValue = -this.edit_value;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.log("Error, bad operator !", op);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
AppStorage.updatePlayerWealth(goldValue)
|
||||||
|
.then(done => {
|
||||||
|
if (done) {
|
||||||
|
this.$emit('updated');
|
||||||
|
this.resetValues();
|
||||||
|
} else {
|
||||||
|
console.log('correct errors');
|
||||||
|
}
|
||||||
|
});
|
||||||
},
|
},
|
||||||
resetValues () {
|
resetValues () {
|
||||||
this.editing = false;
|
this.edit = false;
|
||||||
this.edit_value = 0;
|
this.edit_value = 0;
|
||||||
}
|
}
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
pp () {
|
|
||||||
return this.wealth[3];
|
|
||||||
},
|
|
||||||
gp () {
|
|
||||||
const gp = this.wealth[2];
|
|
||||||
if (gp < 10) {
|
|
||||||
return "0" + gp;
|
|
||||||
} else {
|
|
||||||
return gp;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
sp () {
|
|
||||||
return this.wealth[1];
|
|
||||||
},
|
|
||||||
cp () {
|
|
||||||
return this.wealth[0];
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.input { max-width: 9em; }
|
|
||||||
</style>
|
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
env: {
|
|
||||||
mocha: true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
import { expect } from 'chai'
|
|
||||||
import { mount } from '@vue/test-utils'
|
|
||||||
import ItemInput from '@/components/ItemInput.vue'
|
|
||||||
|
|
||||||
const MOCK_SOURCE = [
|
|
||||||
{ id: 1, name: "Épée", base_price: 20 },
|
|
||||||
{ id: 2, name: "Arc", base_price: 30 },
|
|
||||||
]
|
|
||||||
|
|
||||||
const withItemFactory = function (item) {
|
|
||||||
const wrapper = mount(ItemInput, {
|
|
||||||
propsData: {
|
|
||||||
source: MOCK_SOURCE,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
wrapper.setData({ item })
|
|
||||||
return wrapper
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('ItemInput.vue', () => {
|
|
||||||
|
|
||||||
// Tests on validation of the item data
|
|
||||||
it('item with name and price is valid', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: 'Epee',
|
|
||||||
base_price: 200
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('item without data is not valid', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: '',
|
|
||||||
base_price: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('item without price is not valid', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: 'Epee',
|
|
||||||
base_price: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('item without name is not valid', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: '',
|
|
||||||
base_price: 200
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('item price must be a number', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: 'Epee',
|
|
||||||
base_price: 'cheap'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Test on auto-completion
|
|
||||||
it('show completion suggestions on input', () => {
|
|
||||||
const wrapper = withItemFactory({ id: 0, name: '', base_price: '' })
|
|
||||||
const input = wrapper.find({ name: "name" })
|
|
||||||
const suggestionBox = wrapper.find('.dropdown')
|
|
||||||
console.log(input)
|
|
||||||
expect(suggestionBox.classes('is-active')).to.equal(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('hides suggestion box when no suggestions are available', () => {
|
|
||||||
|
|
||||||
})
|
|
||||||
|
|
||||||
it('click on suggestion sets the item', () => {
|
|
||||||
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { expect } from 'chai'
|
|
||||||
import { shallowMount } from '@vue/test-utils'
|
|
||||||
import Wealth from '@/components/Wealth.vue'
|
|
||||||
|
|
||||||
describe('Wealth.vue', () => {
|
|
||||||
it('renders wealth when passed', () => {
|
|
||||||
const wealth = [1, 2, 3, 4]
|
|
||||||
const wrapper = shallowMount(Wealth, {
|
|
||||||
propsData: { wealth }
|
|
||||||
})
|
|
||||||
var divs = wrapper.findAll('div')
|
|
||||||
expect(wrapper.text()).to.include(wealth)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
208
src/api.rs
208
src/api.rs
@@ -1,208 +0,0 @@
|
|||||||
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>),
|
|
||||||
Notifications(Vec<String>),
|
|
||||||
}
|
|
||||||
|
|
||||||
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),
|
|
||||||
Value::Notifications(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),
|
|
||||||
FetchNotifications(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::FetchNotifications(id) => {
|
|
||||||
response.set_value(Value::Notifications(db::AsPlayer(conn, id).notifications()?));
|
|
||||||
}
|
|
||||||
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) => {
|
|
||||||
// TODO: Different procedure for group and other players
|
|
||||||
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) => {
|
|
||||||
let mut added_items = 0;
|
|
||||||
for item in items.into_iter() {
|
|
||||||
if let Ok(added) = db::LootManager(conn, 0).add_from(&item) {
|
|
||||||
response.push_update(Update::ItemAdded(added));
|
|
||||||
added_items += 1;
|
|
||||||
} else {
|
|
||||||
response.push_error(format!("Error adding {:?}", item));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
response.notify(format!("{} objets lootés !", added_items));
|
|
||||||
// Notify players through persistent notifications
|
|
||||||
if let Err(e) = db::Players(conn)
|
|
||||||
.notifiy_all("De nouveaux objets ont été ajoutés au coffre de groupe !")
|
|
||||||
{
|
|
||||||
response.push_error(format!("Erreur durant la notification : {:?}", e));
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
@@ -2,10 +2,8 @@ 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;
|
||||||
#[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");
|
||||||
|
|||||||
205
src/server.rs
205
src/server.rs
@@ -1,32 +1,47 @@
|
|||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
use actix_files as fs;
|
use actix_files as fs;
|
||||||
use actix_web::{web, middleware, App, Error, HttpResponse, HttpServer};
|
use actix_web::{web, App, Error, HttpResponse, HttpServer};
|
||||||
use futures::{Future, IntoFuture};
|
use futures::Future;
|
||||||
|
use lootalot_db::{DbApi, Pool, QueryResult};
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
use lootalot_db as db;
|
type AppPool = web::Data<Pool>;
|
||||||
use crate::api;
|
|
||||||
|
|
||||||
type AppPool = web::Data<db::Pool>;
|
/// Wraps call to the DbApi and process its result as a async HttpResponse
|
||||||
type PlayerId = web::Path<i32>;
|
///
|
||||||
type ItemId = web::Json<i32>;
|
/// Provides a convenient way to call the api inside a route definition. Given a connection pool,
|
||||||
type ItemListWithMods = web::Json<Vec<(i32, Option<f64>)>>;
|
/// access to the api is granted in a closure. The closure is called in a blocking way and should
|
||||||
|
/// return a QueryResult.
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
/// If the query succeeds, it's result is returned as JSON data. Otherwise, an InternalServerError
|
||||||
struct NewGroupLoot {
|
/// is returned.
|
||||||
source_name: String,
|
///
|
||||||
items: Vec<db::Item>,
|
/// # Usage
|
||||||
}
|
/// ```
|
||||||
|
/// (...)
|
||||||
/// Wraps call to the database query and convert its result as a async HttpResponse
|
/// .route("path/to/",
|
||||||
pub fn db_call(
|
/// 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: serde::ser::Serialize + Send + 'static,
|
||||||
|
Q: Fn(DbApi) -> QueryResult<J> + Send + 'static,
|
||||||
|
>(
|
||||||
pool: AppPool,
|
pool: AppPool,
|
||||||
query: api::ApiActions,
|
query: Q,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error>
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
{
|
|
||||||
let conn = pool.get().unwrap();
|
let conn = pool.get().unwrap();
|
||||||
web::block(move || api::execute(&conn, query)).then(|res| match res {
|
web::block(move || {
|
||||||
Ok(r) => HttpResponse::Ok().json(r),
|
let api = DbApi::with_conn(&conn);
|
||||||
|
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()
|
||||||
@@ -34,105 +49,75 @@ pub fn db_call(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_app(config: &mut web::ServiceConfig) {
|
pub(crate) fn serve() -> std::io::Result<()> {
|
||||||
use api::ApiActions as Q;
|
|
||||||
config.service(
|
|
||||||
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))
|
|
||||||
}))
|
|
||||||
.route("/notifications", web::get().to_async(|pool, player: PlayerId| {
|
|
||||||
db_call(pool, Q::FetchNotifications(*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::post().to_async(
|
|
||||||
move |pool, (player, data): (PlayerId, web::Json<NewGroupLoot>)| {
|
|
||||||
match *player {
|
|
||||||
0 => db_call(pool, Q::AddLoot(data.items.clone())),
|
|
||||||
_ => HttpResponse::Forbidden().finish().into_future(),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
))
|
|
||||||
.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)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub 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"])
|
||||||
.max_age(3600),
|
.max_age(3600),
|
||||||
)
|
)
|
||||||
.wrap(middleware::Logger::default())
|
.service(
|
||||||
|
web::scope("/api")
|
||||||
|
.route(
|
||||||
|
"/players",
|
||||||
|
web::get().to_async(move |pool: AppPool| {
|
||||||
|
db_call(pool, move |api| api.fetch_players())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/claims",
|
||||||
|
web::get().to_async(move |pool: AppPool| {
|
||||||
|
db_call(pool, move |api| api.fetch_claims())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/{player_id}/update-wealth/{amount}",
|
||||||
|
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, f32)>| {
|
||||||
|
db_call(pool, move |api| api.as_player(data.0).update_wealth(data.1))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/{player_id}/loot",
|
||||||
|
web::get().to_async(move |pool: AppPool, player_id: web::Path<i32>| {
|
||||||
|
db_call(pool, move |api| api.as_player(*player_id).loot())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/{player_id}/claim/{item_id}",
|
||||||
|
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, i32)>| {
|
||||||
|
db_call(pool, move |api| api.as_player(data.0).claim(data.1))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/{player_id}/unclaim/{item_id}",
|
||||||
|
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, i32)>| {
|
||||||
|
db_call(pool, move |api| api.as_player(data.0).unclaim(data.1))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/admin/resolve-claims",
|
||||||
|
web::get().to_async(move |pool: AppPool| {
|
||||||
|
db_call(pool, move |api| api.as_admin().resolve_claims())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/admin/add-player/{name}/{wealth}",
|
||||||
|
web::get().to_async(
|
||||||
|
move |pool: AppPool, data: web::Path<(String, f32)>| {
|
||||||
|
db_call(pool, move |api| {
|
||||||
|
api.as_admin().add_player(data.0.clone(), data.1)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
.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