Compare commits
31 Commits
refactor_u
...
4f6970c423
| Author | SHA1 | Date | |
|---|---|---|---|
| 4f6970c423 | |||
| 1ff2429244 | |||
| f1548aedfa | |||
| c99a38a738 | |||
| d6fe5b71f5 | |||
| 47b5d27a0b | |||
| 60b489e8fd | |||
| 2e7afa9bb0 | |||
| 34bb1977a5 | |||
| cb98b97126 | |||
| 6e7a0f6211 | |||
| 6f1a0530d0 | |||
| 8fbca0f7d8 | |||
| 3cfa12570d | |||
| 10d157a9af | |||
| 894f5f8200 | |||
| 3b39428e76 | |||
| a0e4a02e0f | |||
| e56c8df121 | |||
| f1d088596d | |||
| dde7dc3770 | |||
| 15d87e3b47 | |||
| dae7633c11 | |||
| e07b236313 | |||
| fccd9b999b | |||
| 2991a88a30 | |||
| a3eaeed807 | |||
| d280d0f095 | |||
| dbb084b0ec | |||
| 7350d5222c | |||
| 89172177eb |
7
.gitignore
vendored
7
.gitignore
vendored
@@ -1,11 +1,10 @@
|
|||||||
/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,47 +6,21 @@ Un gestionnaire de trésors pour des joueurs de Donjon&Dragons(tm).
|
|||||||
|
|
||||||
## Fonctionnalités prévues
|
## Fonctionnalités prévues
|
||||||
|
|
||||||
* Ajouter des objets "lootés"
|
* Ajouter des objets
|
||||||
|
☐ 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 pour chaque objet ou globale
|
☐ Possibilité d'indiquer une variation du prix de vente globale et/ou pour chaque objet
|
||||||
|
☐ Possibilité d'indiquer des joueurs exclus de la répartition
|
||||||
* Gérer les comptes du groupe et des joueurs
|
* Gérer les comptes du groupe et des joueurs
|
||||||
* Historique des transactions par propriétaire
|
☑ Afficher le solde actuel et la dette envers le groupe
|
||||||
|
☑ 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 ?_
|
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
2255
lootalot_db/res/items.csv
Normal file
2255
lootalot_db/res/items.csv
Normal file
File diff suppressed because it is too large
Load Diff
@@ -4,19 +4,15 @@
|
|||||||
//! This module wraps all needed database operations.
|
//! This module wraps all needed database operations.
|
||||||
//! It exports a public API for integration with various clients (REST Api, CLI, ...)
|
//! It exports a public API for integration with various clients (REST Api, CLI, ...)
|
||||||
extern crate dotenv;
|
extern crate dotenv;
|
||||||
#[macro_use]
|
#[macro_use] extern crate diesel;
|
||||||
extern crate diesel;
|
#[macro_use] extern crate serde_derive;
|
||||||
#[macro_use]
|
|
||||||
extern crate serde_derive;
|
|
||||||
|
|
||||||
use diesel::prelude::*;
|
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};
|
|
||||||
|
|
||||||
/// The connection used
|
/// The connection used
|
||||||
pub type DbConnection = SqliteConnection;
|
pub type DbConnection = SqliteConnection;
|
||||||
@@ -24,39 +20,10 @@ 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>>;
|
/// The result of an action provided by DbApi
|
||||||
/// Return status of an Action
|
pub type ActionResult<R> = Result<R, diesel::result::Error>;
|
||||||
#[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
|
/// A wrapper providing an API over the database
|
||||||
/// It offers a convenient way to deal with connection.
|
/// It offers a convenient way to deal with connection.
|
||||||
///
|
///
|
||||||
@@ -75,7 +42,7 @@ impl<T: Default + serde::Serialize> ActionStatus<T> {
|
|||||||
/// x .sell_loot([players], [excluded_item_ids]) -> Success status (bool, player_share)
|
/// x .sell_loot([players], [excluded_item_ids]) -> Success status (bool, player_share)
|
||||||
/// // Claims should be resolved after a certain delay
|
/// // Claims should be resolved after a certain delay
|
||||||
/// x .set_claims_timeout()
|
/// x .set_claims_timeout()
|
||||||
/// x .resolve_claims()
|
/// v .resolve_claims()
|
||||||
/// v .add_player(player_data)
|
/// v .add_player(player_data)
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
@@ -99,8 +66,10 @@ impl<'q> DbApi<'q> {
|
|||||||
Ok(schema::players::table.load::<models::Player>(self.0)?)
|
Ok(schema::players::table.load::<models::Player>(self.0)?)
|
||||||
}
|
}
|
||||||
/// Fetch the inventory of items
|
/// Fetch the inventory of items
|
||||||
|
///
|
||||||
|
/// TODO: remove limit used for debug
|
||||||
pub fn fetch_inventory(self) -> QueryResult<Vec<models::Item>> {
|
pub fn fetch_inventory(self) -> QueryResult<Vec<models::Item>> {
|
||||||
Ok(schema::items::table.load::<models::Item>(self.0)?)
|
Ok(schema::items::table.limit(100).load::<models::Item>(self.0)?)
|
||||||
}
|
}
|
||||||
/// Fetch all existing claims
|
/// Fetch all existing claims
|
||||||
pub fn fetch_claims(self) -> QueryResult<Vec<models::Claim>> {
|
pub fn fetch_claims(self) -> QueryResult<Vec<models::Claim>> {
|
||||||
@@ -152,98 +121,142 @@ impl<'q> AsPlayer<'q> {
|
|||||||
pub fn loot(self) -> QueryResult<Vec<models::Item>> {
|
pub fn loot(self) -> QueryResult<Vec<models::Item>> {
|
||||||
Ok(models::Item::owned_by(self.id).load(self.conn)?)
|
Ok(models::Item::owned_by(self.id).load(self.conn)?)
|
||||||
}
|
}
|
||||||
/// Buy an item and add it to this player chest
|
/// Buy a batch of items and add them to this player chest
|
||||||
///
|
///
|
||||||
/// TODO: Items should be picked from a custom list
|
/// Items can only be bought from inventory. Hence, the use
|
||||||
|
/// of the entity's id in 'items' table.
|
||||||
///
|
///
|
||||||
/// # Panics
|
/// # Params
|
||||||
|
/// List of (Item's id in inventory, Option<Price modifier>)
|
||||||
///
|
///
|
||||||
/// This currently panics if player wealth fails to be updated, as this is
|
/// # Returns
|
||||||
/// a serious error. TODO: handle deletion of bought item in case of wealth update failure.
|
/// Result containing the difference in coins after operation
|
||||||
pub fn buy<S: Into<String>>(self, name: S, price: i32) -> ActionResult<Option<(i32, i32, i32, i32)>> {
|
pub fn buy<'a>(self, params: &Vec<(i32, Option<f32>)>) -> ActionResult<(Vec<models::Item>, (i32, i32, i32, i32))> {
|
||||||
match transactions::player::Buy.execute(
|
let mut cumulated_diff: Vec<(i32, i32, i32, i32)> = Vec::with_capacity(params.len());
|
||||||
self.conn,
|
let mut added_items: Vec<models::Item> = Vec::with_capacity(params.len());
|
||||||
transactions::player::AddLootParams {
|
for (item_id, price_mod) in params.into_iter() {
|
||||||
player_id: self.id,
|
if let Ok((item, diff)) = self.conn.transaction(|| {
|
||||||
loot_name: name.into(),
|
use schema::looted::dsl::*;
|
||||||
loot_price: price,
|
let item = schema::items::table.find(item_id).first::<models::Item>(self.conn)?;
|
||||||
},
|
let new_item = models::item::NewLoot::to_player(self.id, (&item.name, item.base_price));
|
||||||
) {
|
diesel::insert_into(schema::looted::table)
|
||||||
Ok(res) => Ok(ActionStatus { executed: true, response: Some(res.loot_cost) }),
|
.values(&new_item)
|
||||||
Err(e) => { dbg!(&e); Ok(ActionStatus { executed: false, response: None}) },
|
.execute(self.conn)?;
|
||||||
|
let added_item = models::Item::owned_by(self.id)
|
||||||
|
.order(id.desc())
|
||||||
|
.first(self.conn)?;
|
||||||
|
let sell_price = match price_mod {
|
||||||
|
Some(modifier) => item.base_price as f32 * modifier,
|
||||||
|
None => item.base_price as f32
|
||||||
|
};
|
||||||
|
DbApi::with_conn(self.conn)
|
||||||
|
.as_player(self.id)
|
||||||
|
.update_wealth(-sell_price)
|
||||||
|
.map(|diff| (added_item, diff))
|
||||||
|
}) {
|
||||||
|
cumulated_diff.push(diff);
|
||||||
|
added_items.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Sell an item from this player chest
|
let all_diff = cumulated_diff.into_iter().fold((0,0,0,0), |sum, diff| {
|
||||||
|
(sum.0 + diff.0, sum.1 + diff.1, sum.2 + diff.2, sum.3 + diff.3)
|
||||||
|
});
|
||||||
|
Ok((added_items, all_diff))
|
||||||
|
}
|
||||||
|
/// Sell a set of items from this player chest
|
||||||
///
|
///
|
||||||
/// # Panics
|
/// # Returns
|
||||||
///
|
/// Result containing the difference in coins after operation
|
||||||
/// 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(
|
pub fn sell(
|
||||||
self,
|
self,
|
||||||
loot_id: i32,
|
params: &Vec<(i32, Option<f32>)>,
|
||||||
_price_mod: Option<f32>,
|
) -> ActionResult<(i32, i32, i32, i32)> {
|
||||||
) -> ActionResult<Option<(i32, i32, i32, i32)>> {
|
let mut all_results: Vec<(i32, i32, i32, i32)> = Vec::with_capacity(params.len());
|
||||||
// Check that the item belongs to player
|
for (loot_id, price_mod) in params.into_iter() {
|
||||||
let exists_and_owned: bool =
|
let res = self.conn.transaction(|| {
|
||||||
diesel::select(models::Loot::owns(self.id, loot_id))
|
use schema::looted::dsl::*;
|
||||||
.get_result(self.conn)?;
|
let loot = looted
|
||||||
if !exists_and_owned {
|
.find(loot_id)
|
||||||
return Ok(ActionStatus::nop());
|
.first::<models::Loot>(self.conn)?;
|
||||||
|
if loot.owner != self.id {
|
||||||
|
// If the item does not belong to player,
|
||||||
|
// it can't be what we're looking for
|
||||||
|
return Err(diesel::result::Error::NotFound);
|
||||||
}
|
}
|
||||||
transactions::player::Sell.execute(
|
let mut sell_value = loot.base_price as f32 / 2.0;
|
||||||
self.conn,
|
if let Some(modifier) = price_mod {
|
||||||
transactions::player::LootParams {
|
sell_value *= modifier;
|
||||||
player_id: self.id,
|
}
|
||||||
loot_id,
|
let _deleted = diesel::delete(looted.find(loot_id))
|
||||||
},
|
.execute(self.conn)?;
|
||||||
)
|
DbApi::with_conn(self.conn).as_player(self.id).update_wealth(sell_value)
|
||||||
.map(|res| ActionStatus { executed: true, response: Some(res.loot_cost) })
|
});
|
||||||
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop()) })
|
if let Ok(diff) = res {
|
||||||
|
all_results.push(diff)
|
||||||
|
} else {
|
||||||
|
// TODO: need to find a better way to deal with errors
|
||||||
|
return Err(diesel::result::Error::NotFound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(all_results.into_iter().fold((0,0,0,0), |sum, diff| {
|
||||||
|
(sum.0 + diff.0, sum.1 + diff.1, sum.2 + diff.2, sum.3 + diff.3)
|
||||||
|
}))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds the value in gold to the player's wealth.
|
/// Adds the value in gold to the player's wealth.
|
||||||
///
|
///
|
||||||
/// Value can be negative to substract wealth.
|
/// Value can be negative to substract wealth.
|
||||||
pub fn update_wealth(self, value_in_gp: f32) -> ActionResult<Option<(i32, i32, i32, i32)>> {
|
pub fn update_wealth(self, value_in_gp: f32) -> ActionResult<(i32, i32, i32, i32)> {
|
||||||
transactions::player::UpdateWealth.execute(
|
use schema::players::dsl::*;
|
||||||
self.conn,
|
let current_wealth = players
|
||||||
transactions::player::WealthParams {
|
.find(self.id)
|
||||||
player_id: self.id,
|
.select((cp, sp, gp, pp))
|
||||||
value_in_gp,
|
.first::<models::Wealth>(self.conn)?;
|
||||||
},
|
// TODO: improve thisdiesel dependant transaction
|
||||||
)
|
// should be move inside a WealthUpdate method
|
||||||
.map(|res| ActionStatus { executed: true, response: Some(res) })
|
let updated_wealth = models::Wealth::from_gp(current_wealth.to_gp() + value_in_gp);
|
||||||
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
// Difference in coins that is sent back
|
||||||
|
let (old, new) = (current_wealth.as_tuple(), updated_wealth.as_tuple());
|
||||||
|
let diff = (new.0 - old.0, new.1 - old.1, new.2 - old.2, new.3 - old.3);
|
||||||
|
diesel::update(players)
|
||||||
|
.filter(id.eq(self.id))
|
||||||
|
.set(&updated_wealth)
|
||||||
|
.execute(self.conn)
|
||||||
|
.map(|r| match r {
|
||||||
|
1 => diff,
|
||||||
|
_ => panic!("RuntimeError: UpdateWealth did no changes at all!"),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
/// Put a claim on a specific item
|
/// Put a claim on a specific item
|
||||||
pub fn claim(self, item: i32) -> ActionResult<()> {
|
pub fn claim(self, item: i32) -> ActionResult<()> {
|
||||||
let exists: bool =
|
let exists: bool = diesel::select(models::Loot::exists(item)).get_result(self.conn)?;
|
||||||
diesel::select(models::Loot::exists(item)).get_result(self.conn)?;
|
|
||||||
if !exists {
|
if !exists {
|
||||||
return Ok(ActionStatus::nop());
|
return Err(diesel::result::Error::NotFound);
|
||||||
};
|
};
|
||||||
transactions::player::PutClaim.execute(
|
let claim = models::claim::NewClaim::new(self.id, item);
|
||||||
self.conn,
|
diesel::insert_into(schema::claims::table)
|
||||||
transactions::player::LootParams {
|
.values(&claim)
|
||||||
player_id: self.id,
|
.execute(self.conn)
|
||||||
loot_id: item,
|
.map(|rows_updated| match rows_updated {
|
||||||
},
|
1 => (),
|
||||||
)
|
_ => panic!("RuntimeError: Claim did no change at all!"),
|
||||||
.map(|_| ActionStatus { executed: true, response: () })
|
})
|
||||||
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
|
||||||
}
|
}
|
||||||
/// Withdraw claim
|
/// Withdraw claim
|
||||||
pub fn unclaim(self, item: i32) -> ActionResult<()> {
|
pub fn unclaim(self, item: i32) -> ActionResult<()> {
|
||||||
transactions::player::WithdrawClaim.execute(
|
use schema::claims::dsl::*;
|
||||||
self.conn,
|
diesel::delete(
|
||||||
transactions::player::LootParams {
|
claims
|
||||||
player_id: self.id,
|
.filter(loot_id.eq(item))
|
||||||
loot_id: item,
|
.filter(player_id.eq(self.id)),
|
||||||
},
|
|
||||||
)
|
)
|
||||||
.map(|_| ActionStatus { executed: true, response: () })
|
.execute(self.conn)
|
||||||
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
.and_then(|rows_updated| match rows_updated {
|
||||||
|
1 => Ok(()),
|
||||||
|
0 => Err(diesel::result::Error::NotFound),
|
||||||
|
_ => panic!("RuntimeError: UnclaimItem did not make expected changes"),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,22 +267,32 @@ impl<'q> AsAdmin<'q> {
|
|||||||
/// Adds a player to the database
|
/// Adds a player to the database
|
||||||
///
|
///
|
||||||
/// Takes the player name and starting wealth (in gold value).
|
/// Takes the player name and starting wealth (in gold value).
|
||||||
pub fn add_player(self, name: String, start_wealth: f32) -> ActionResult<()> {
|
pub fn add_player(self, name: &str, start_wealth: f32) -> ActionResult<()> {
|
||||||
diesel::insert_into(schema::players::table)
|
diesel::insert_into(schema::players::table)
|
||||||
.values(&models::player::NewPlayer::create(&name, start_wealth))
|
.values(&models::player::NewPlayer::create(name, start_wealth))
|
||||||
.execute(self.0)
|
.execute(self.0)
|
||||||
.map(ActionStatus::was_updated)
|
.map(|rows_updated| match rows_updated {
|
||||||
|
1 => (),
|
||||||
|
_ => panic!("RuntimeError: AddPlayer did not make expected changes"),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds a list of items to the group loot
|
/// Adds a list of items to the group loot
|
||||||
pub fn add_loot<'a>(self, items: Vec<(&'a str, i32)>) -> ActionResult<()> {
|
///
|
||||||
|
/// This offers complete control other created items, so that unique
|
||||||
|
/// items can be easily added. A user interface shall deal with
|
||||||
|
/// filling theses values for known items in inventory.
|
||||||
|
///
|
||||||
|
/// # Params
|
||||||
|
/// List of (name, base_price) values for the new items
|
||||||
|
pub fn add_loot(self, items: Vec<(&str, i32)>) -> ActionResult<()> {
|
||||||
for item_desc in items.into_iter() {
|
for item_desc in items.into_iter() {
|
||||||
let new_item = models::item::NewLoot::to_group(item_desc);
|
let new_item = models::item::NewLoot::to_group(item_desc);
|
||||||
diesel::insert_into(schema::looted::table)
|
diesel::insert_into(schema::looted::table)
|
||||||
.values(&new_item)
|
.values(&new_item)
|
||||||
.execute(self.0)?;
|
.execute(self.0)?;
|
||||||
}
|
}
|
||||||
Ok(ActionStatus::ok())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve all pending claims and dispatch claimed items.
|
/// Resolve all pending claims and dispatch claimed items.
|
||||||
@@ -283,10 +306,32 @@ impl<'q> AsAdmin<'q> {
|
|||||||
.grouped_by(&loot);
|
.grouped_by(&loot);
|
||||||
// For each claimed item
|
// For each claimed item
|
||||||
let data = loot.into_iter().zip(claims).collect::<Vec<_>>();
|
let data = loot.into_iter().zip(claims).collect::<Vec<_>>();
|
||||||
dbg!(data);
|
dbg!(&data);
|
||||||
// If mutiples claims -> find highest resolve, give to this player
|
|
||||||
// If only one claim -> give to claiming
|
for (loot, claims) in data {
|
||||||
Ok(ActionStatus::nop())
|
match claims.len() {
|
||||||
|
1 => {
|
||||||
|
let claim = claims.get(0).unwrap();
|
||||||
|
let player_id = claim.player_id;
|
||||||
|
self.0.transaction(|| {
|
||||||
|
use schema::looted::dsl::*;
|
||||||
|
diesel::update(looted.find(claim.loot_id))
|
||||||
|
.set(owner_id.eq(player_id))
|
||||||
|
.execute(self.0)?;
|
||||||
|
diesel::delete(schema::claims::table.find(claim.id))
|
||||||
|
.execute(self.0)?;
|
||||||
|
{
|
||||||
|
use schema::players::dsl::*;
|
||||||
|
diesel::update(players.find(player_id))
|
||||||
|
.set(debt.eq(debt + (loot.base_price / 2)))
|
||||||
|
.execute(self.0)
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,7 +361,7 @@ mod tests {
|
|||||||
/// 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 test_group_is_autocreated() {
|
fn global_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);
|
||||||
@@ -328,20 +373,19 @@ mod tests {
|
|||||||
/// 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 test_player_updates_wealth() {
|
fn as_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".to_string(), 403.21)
|
.add_player("PlayerName", 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)
|
||||||
.unwrap()
|
.ok();
|
||||||
.response
|
|
||||||
.unwrap();
|
|
||||||
// Check the returned diff
|
// Check the returned diff
|
||||||
assert_eq!(diff, (-1, -2, -1, -4));
|
assert_eq!(diff, Some((-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
|
||||||
@@ -352,13 +396,12 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_admin_add_player() {
|
fn as_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".to_string(), 403.21)
|
.add_player("PlayerName", 403.21);
|
||||||
.unwrap();
|
assert_eq!(result.is_ok(), true);
|
||||||
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();
|
||||||
@@ -370,56 +413,80 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_admin_resolve_claims() {
|
fn as_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 test_player_claim_item() {
|
fn as_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".to_string(), 0.0)
|
.add_player("Player", 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).unwrap();
|
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||||
assert_eq!(result.executed, true);
|
assert_eq!(result.is_ok(), 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).unwrap();
|
let result = DbApi::with_conn(&conn).as_player(1).claim(2);
|
||||||
assert_eq!(result.executed, false);
|
assert_eq!(result.is_ok(), false);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_player_unclaim_item() {
|
fn as_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".to_string(), 0.0)
|
.add_player("Player", 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).unwrap();
|
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||||
assert_eq!(result.executed, true);
|
assert_eq!(result.is_ok(), true);
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1).unwrap();
|
// Claiming twice is an error
|
||||||
assert_eq!(result.executed, true);
|
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||||
// Check that unclaimed items will not be unclaimed...
|
assert_eq!(result.is_ok(), false);
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1).unwrap();
|
// Unclaiming and item
|
||||||
assert_eq!(result.executed, false);
|
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
||||||
|
assert_eq!(result.is_ok(), true);
|
||||||
|
// Check that not claimed items will not be unclaimed...
|
||||||
|
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
||||||
|
assert_eq!(result.is_ok(), false);
|
||||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||||
assert_eq!(claims.len(), 0);
|
assert_eq!(claims.len(), 0);
|
||||||
}
|
}
|
||||||
@@ -428,20 +495,27 @@ mod tests {
|
|||||||
///
|
///
|
||||||
/// 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 test_buy_sell_simple() {
|
fn as_player_simple_buy_sell() {
|
||||||
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".to_string(), 1000.0)
|
.add_player("Player", 1000.0)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
// Buy an item
|
// Buy an item
|
||||||
let bought = DbApi::with_conn(&conn)
|
let bought = DbApi::with_conn(&conn)
|
||||||
.as_player(1)
|
.as_player(1)
|
||||||
.buy("Sword", 800)
|
.buy(&vec![(1, None)]);
|
||||||
.unwrap();
|
assert_eq!(bought.ok(), Some((0, 0, 0, -8))); // Returns diff of player wealth ?
|
||||||
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();
|
||||||
@@ -450,13 +524,12 @@ mod tests {
|
|||||||
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).sell(&vec![(loot.id, None)]);
|
||||||
.as_player(1)
|
assert_eq!(sold.ok(), Some((0, 0, 0, 4)));
|
||||||
.sell(loot.id, None)
|
|
||||||
.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();
|
||||||
@@ -465,7 +538,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_admin_add_loot() {
|
fn as_admin_add_loot() {
|
||||||
let conn = test_connection();
|
let conn = test_connection();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
0,
|
0,
|
||||||
@@ -474,9 +547,8 @@ mod tests {
|
|||||||
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());
|
||||||
.unwrap();
|
assert_eq!(result.is_ok(), true);
|
||||||
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
|
||||||
|
|||||||
@@ -35,8 +35,8 @@ type OwnedLoot = Filter<looted::table, WithOwner>;
|
|||||||
pub(crate) struct Loot {
|
pub(crate) struct Loot {
|
||||||
id: i32,
|
id: i32,
|
||||||
name: String,
|
name: String,
|
||||||
base_price: i32,
|
pub(crate) base_price: i32,
|
||||||
owner: i32,
|
pub(crate) owner: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Loot {
|
impl Loot {
|
||||||
|
|||||||
@@ -40,4 +40,9 @@ joinable!(claims -> looted (loot_id));
|
|||||||
joinable!(claims -> players (player_id));
|
joinable!(claims -> players (player_id));
|
||||||
joinable!(looted -> players (owner_id));
|
joinable!(looted -> players (owner_id));
|
||||||
|
|
||||||
allow_tables_to_appear_in_same_query!(claims, items, looted, players,);
|
allow_tables_to_appear_in_same_query!(
|
||||||
|
claims,
|
||||||
|
items,
|
||||||
|
looted,
|
||||||
|
players,
|
||||||
|
);
|
||||||
|
|||||||
@@ -1,295 +0,0 @@
|
|||||||
//! 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;
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,6 @@ module.exports = {
|
|||||||
presets: [
|
presets: [
|
||||||
'@vue/app'
|
'@vue/app'
|
||||||
],
|
],
|
||||||
"presets": [["env", { "modules": false }]],
|
|
||||||
"env": {
|
"env": {
|
||||||
"test": {
|
"test": {
|
||||||
"presets": [["env", { "targets": { "node": "current" } }]]
|
"presets": [["env", { "targets": { "node": "current" } }]]
|
||||||
|
|||||||
15047
lootalot_front/package-lock.json
generated
15047
lootalot_front/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -21,6 +21,7 @@
|
|||||||
"@vue/cli-plugin-eslint": "^3.8.0",
|
"@vue/cli-plugin-eslint": "^3.8.0",
|
||||||
"@vue/cli-service": "^3.8.0",
|
"@vue/cli-service": "^3.8.0",
|
||||||
"@vue/test-utils": "^1.0.0-beta.29",
|
"@vue/test-utils": "^1.0.0-beta.29",
|
||||||
|
"babel-core": "^6.26.3",
|
||||||
"babel-eslint": "^10.0.1",
|
"babel-eslint": "^10.0.1",
|
||||||
"babel-jest": "^24.8.0",
|
"babel-jest": "^24.8.0",
|
||||||
"babel-preset-env": "^1.7.0",
|
"babel-preset-env": "^1.7.0",
|
||||||
@@ -61,8 +62,11 @@
|
|||||||
"vue"
|
"vue"
|
||||||
],
|
],
|
||||||
"transform": {
|
"transform": {
|
||||||
".*\\.(vue)$": "vue-jest",
|
"^.*\\.(vue)$": "vue-jest",
|
||||||
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
|
"^.+\\.js$": "babel-jest"
|
||||||
|
},
|
||||||
|
"moduleNameMapper": {
|
||||||
|
"^@/(.*)$": "<rootDir>/src/$1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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="fontawesome/js/all.js"></script>
|
<script defer src="<%= BASE_URL %>fontawesome/js/all.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|||||||
@@ -1,17 +1,95 @@
|
|||||||
<template>
|
<template>
|
||||||
<main id="app" class="section">
|
<PlayerView
|
||||||
<section id="content" class="columns is-desktop">
|
:id="state.player_id"
|
||||||
<Player></Player>
|
v-slot="{ player, loot, notifications, actions }"
|
||||||
<div class="column">
|
>
|
||||||
<Chest :player="0" v-if="state.initiated"></Chest>
|
<main id="app" class="container">
|
||||||
|
<header>
|
||||||
|
<HeaderBar :app_state="state">
|
||||||
|
<template v-slot:title>
|
||||||
|
{{ 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 state.player_list" :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>
|
</div>
|
||||||
</section>
|
</nav>
|
||||||
|
<main class="section">
|
||||||
|
<template v-if="isAdding">
|
||||||
|
<div v-if="playerIsGroup" class="box">
|
||||||
|
<ItemInput v-if="playerIsGroup"
|
||||||
|
:source="state.inventory"
|
||||||
|
@addItem="item => pending_loot.push(item)"
|
||||||
|
></ItemInput>
|
||||||
|
<button>Envoyer</button>
|
||||||
|
</div>
|
||||||
|
<AddingChest
|
||||||
|
:items="playerIsGroup ? pending_loot : state.inventory"
|
||||||
|
:perms="playerIsGroup ? {} : { canBuy: true }"
|
||||||
|
@buy="(data) => { switchView('player'); actions.buyItems(data); }">
|
||||||
|
</AddingChest>
|
||||||
|
</template>
|
||||||
|
<Chest v-else
|
||||||
|
:items="showPlayerChest ? loot : state.group_loot"
|
||||||
|
:perms="{
|
||||||
|
canGrab: !(showPlayerChest || playerIsGroup),
|
||||||
|
canSell: showPlayerChest || playerIsGroup
|
||||||
|
}"
|
||||||
|
@sell="actions.sellItems"
|
||||||
|
@claim="actions.putClaim"
|
||||||
|
@unclaim="actions.withdrawClaim">
|
||||||
|
</Chest>
|
||||||
</main>
|
</main>
|
||||||
|
</main>
|
||||||
|
</PlayerView>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import Player from './components/Player.vue'
|
import PlayerView from './components/PlayerView.js'
|
||||||
|
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 ItemInput from './components/ItemInput.vue'
|
||||||
import { AppStorage } from './AppStorage'
|
import { AppStorage } from './AppStorage'
|
||||||
|
|
||||||
function getCookie(cname) {
|
function getCookie(cname) {
|
||||||
@@ -35,11 +113,18 @@ export default {
|
|||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
state: AppStorage.state,
|
state: AppStorage.state,
|
||||||
|
activeView: 'group',
|
||||||
|
shopInventory: [{id: 1, name: "Item from shop #1", base_price: 2000}],
|
||||||
|
pending_loot: [],
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
components: {
|
components: {
|
||||||
Player,
|
PlayerView,
|
||||||
Chest
|
HeaderBar,
|
||||||
|
'AddingChest': Chest, // Alias to prevent component re-use
|
||||||
|
Chest,
|
||||||
|
Wealth,
|
||||||
|
ItemInput,
|
||||||
},
|
},
|
||||||
created () {
|
created () {
|
||||||
// Initiate with active player set to value found in cookie
|
// Initiate with active player set to value found in cookie
|
||||||
@@ -53,14 +138,29 @@ export default {
|
|||||||
}
|
}
|
||||||
AppStorage.initStorage(playerId);
|
AppStorage.initStorage(playerId);
|
||||||
},
|
},
|
||||||
|
methods: {
|
||||||
|
setActivePlayer (idx) {
|
||||||
|
if (idx == 0) this.switchView('group');
|
||||||
|
AppStorage.setActivePlayer(idx);
|
||||||
|
},
|
||||||
|
switchView (viewId) {
|
||||||
|
if (!['group', 'player', 'adding'].includes(viewId)) {
|
||||||
|
console.error("Not a valid view ID :", viewId);
|
||||||
|
}
|
||||||
|
this.activeView = viewId;
|
||||||
|
},
|
||||||
|
switchPlayerChestVisibility () { AppStorage.switchPlayerChestVisibility(); },
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
showPlayerChest () { return this.activeView == 'player' },
|
||||||
|
isAdding () { return this.activeView == 'adding' },
|
||||||
|
playerIsGroup () { return this.state.player_id == 0 },
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style>
|
<style scoped>
|
||||||
#app {
|
header {
|
||||||
font-family: 'Montserrat', Helvetica, Arial, sans-serif;
|
padding-bottom: 1.5em;
|
||||||
-webkit-font-smoothing: antialiased;
|
|
||||||
-moz-osx-font-smoothing: grayscale;
|
|
||||||
text-align: center;
|
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -5,37 +5,55 @@ const API_ENDPOINT = function (tailString) {
|
|||||||
return API_BASEURL + tailString;
|
return API_BASEURL + tailString;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Api = {
|
export const Api = {
|
||||||
fetchPlayerList () {
|
__doFetch (endpoint, method, payload) {
|
||||||
return fetch(API_ENDPOINT("players"))
|
return fetch(API_ENDPOINT(endpoint),
|
||||||
|
{
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
})
|
||||||
|
.then(r => r.json())
|
||||||
|
},
|
||||||
|
fetchPlayerList () {
|
||||||
|
return fetch(API_ENDPOINT("players/all"))
|
||||||
|
.then(r => r.json())
|
||||||
|
},
|
||||||
|
fetchInventory () {
|
||||||
|
return fetch(API_ENDPOINT("items"))
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.catch(e => console.error("Fetch error ", e));
|
|
||||||
},
|
},
|
||||||
fetchClaims () {
|
fetchClaims () {
|
||||||
return fetch(API_ENDPOINT("claims"))
|
return fetch(API_ENDPOINT("claims"))
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.catch(e => console.error("Fetch error ", e));
|
|
||||||
},
|
},
|
||||||
fetchLoot (playerId) {
|
fetchLoot (playerId) {
|
||||||
return fetch(API_ENDPOINT(playerId + "/loot"))
|
return fetch(API_ENDPOINT("players/loot/" + playerId))
|
||||||
.then(r => r.json())
|
.then(r => r.json())
|
||||||
.catch(e => console.error("Fetch error", e));
|
|
||||||
},
|
},
|
||||||
putClaim (playerId, itemId) {
|
putClaim (player_id, item_id) {
|
||||||
return fetch(API_ENDPOINT(playerId + "/claim/" + itemId))
|
const payload = { player_id, item_id };
|
||||||
.then(r => r.json())
|
return this.__doFetch("claims", 'PUT', payload);
|
||||||
.catch(e => console.error("Fetch error", e));
|
|
||||||
},
|
},
|
||||||
unClaim (playerId, itemId) {
|
unClaim (player_id, item_id) {
|
||||||
return fetch(API_ENDPOINT(playerId + "/unclaim/" + itemId))
|
const payload = { player_id, item_id };
|
||||||
.then(r => r.json())
|
return this.__doFetch("claims", 'DELETE', payload);
|
||||||
.catch(e => console.error("Fetch error", e));
|
},
|
||||||
|
updateWealth (player_id, value_in_gp) {
|
||||||
|
const payload = { player_id, value_in_gp: Number(value_in_gp) };
|
||||||
|
return this.__doFetch("players/update-wealth", 'PUT', payload);
|
||||||
|
},
|
||||||
|
buyItems (player_id, items) {
|
||||||
|
const payload = { player_id, items };
|
||||||
|
return this.__doFetch("players/buy", 'POST', payload);
|
||||||
|
},
|
||||||
|
sellItems (player_id, items) {
|
||||||
|
const payload = { player_id, items };
|
||||||
|
return this.__doFetch("players/sell", 'POST', payload);
|
||||||
|
|
||||||
},
|
},
|
||||||
updateWealth (playerId, goldValue) {
|
|
||||||
return fetch(API_ENDPOINT(playerId + "/update-wealth/" + goldValue))
|
|
||||||
.then(r => r.json())
|
|
||||||
.catch(e => console.error("Fetch error", e));
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -44,8 +62,9 @@ export const AppStorage = {
|
|||||||
state: {
|
state: {
|
||||||
player_id: 0,
|
player_id: 0,
|
||||||
player_list: {},
|
player_list: {},
|
||||||
player_loot: {},
|
group_loot: [],
|
||||||
player_claims: {},
|
player_claims: {},
|
||||||
|
inventory: [],
|
||||||
initiated: false,
|
initiated: false,
|
||||||
show_player_chest: false,
|
show_player_chest: false,
|
||||||
},
|
},
|
||||||
@@ -55,14 +74,21 @@ export const AppStorage = {
|
|||||||
this.state.player_id = playerId;
|
this.state.player_id = playerId;
|
||||||
// Fetch initial data
|
// Fetch initial data
|
||||||
return Promise
|
return Promise
|
||||||
.all([ Api.fetchPlayerList(), Api.fetchClaims(), ])
|
.all([
|
||||||
|
Api.fetchPlayerList(),
|
||||||
|
Api.fetchClaims(),
|
||||||
|
Api.fetchInventory(),
|
||||||
|
Api.fetchLoot(0)
|
||||||
|
])
|
||||||
.then(data => {
|
.then(data => {
|
||||||
const [players, claims] = data;
|
const [players, claims, inventory, group_loot] = data;
|
||||||
this.__initPlayerList(players);
|
this.__initPlayerList(players);
|
||||||
this.__initClaimsStore(claims);
|
this.__initClaimsStore(claims);
|
||||||
});
|
Vue.set(this.state, 'group_loot', group_loot);
|
||||||
// TODO: when __initPlayerList won't use promises
|
Vue.set(this.state, 'inventory', inventory);
|
||||||
//.then(_ => this.state.initiated = true);
|
})
|
||||||
|
.then(_ => this.state.initiated = true)
|
||||||
|
.catch(e => { alert(e); this.state.initiated = false });
|
||||||
},
|
},
|
||||||
__initClaimsStore(data) {
|
__initClaimsStore(data) {
|
||||||
for (var idx in data) {
|
for (var idx in data) {
|
||||||
@@ -77,86 +103,67 @@ export const AppStorage = {
|
|||||||
if (this.debug) console.log("Creates", playerId, playerDesc.name)
|
if (this.debug) console.log("Creates", playerId, playerDesc.name)
|
||||||
// Initiate data for a single Player.
|
// Initiate data for a single Player.
|
||||||
Vue.set(this.state.player_list, playerId, playerDesc);
|
Vue.set(this.state.player_list, playerId, playerDesc);
|
||||||
Vue.set(this.state.player_loot, playerId, []);
|
|
||||||
Vue.set(this.state.player_claims, 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
|
// User actions
|
||||||
// Sets a new active player by id
|
// Sets a new active player by id
|
||||||
setActivePlayer (newPlayerId) {
|
setActivePlayer (newPlayerId) {
|
||||||
if (this.debug) console.log('setActivePlayer to ', newPlayerId)
|
if (this.debug) console.log('setActivePlayer to ', newPlayerId)
|
||||||
this.state.player_id = newPlayerId
|
this.state.player_id = Number(newPlayerId)
|
||||||
document.cookie = `player_id=${newPlayerId};`;
|
document.cookie = `player_id=${newPlayerId};`;
|
||||||
},
|
},
|
||||||
// Show/Hide player's chest
|
// Show/Hide player's chest
|
||||||
switchPlayerChestVisibility () {
|
switchPlayerChestVisibility () {
|
||||||
if (this.debug) console.log('switchPlayerChestVisibility', !this.state.show_player_chest)
|
if (this.debug) console.log('switchPlayerChestVisibility', !this.state.show_player_chest)
|
||||||
this.state.show_player_chest = !this.state.show_player_chest
|
this.state.show_player_chest = !this.state.show_player_chest
|
||||||
},
|
|
||||||
// TODO
|
|
||||||
// get the content of a player Chest, retrieve form cache or fetched
|
|
||||||
// will replace hack that loads *all* chest...
|
|
||||||
getPlayerLoot (playerId) {
|
|
||||||
|
|
||||||
},
|
},
|
||||||
updatePlayerWealth (goldValue) {
|
updatePlayerWealth (goldValue) {
|
||||||
return Api.updateWealth(this.state.player_id, goldValue)
|
return Api.updateWealth(this.state.player_id, goldValue)
|
||||||
.then(done => {
|
.then(diff => this.__updatePlayerWealth(diff));
|
||||||
if (done.executed) {
|
},
|
||||||
// Update player wealth
|
// TODO: Weird private name denotes a conflict
|
||||||
var diff = done.response;
|
__updatePlayerWealth (diff) {
|
||||||
if (this.debug) console.log('updatePlayerWealth', diff)
|
if (this.debug) console.log('updatePlayerWealth', diff)
|
||||||
this.state.player_list[this.state.player_id].cp += diff[0];
|
this.state.player_list[this.state.player_id].cp += diff[0];
|
||||||
this.state.player_list[this.state.player_id].sp += diff[1];
|
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].gp += diff[2];
|
||||||
this.state.player_list[this.state.player_id].pp += diff[3];
|
this.state.player_list[this.state.player_id].pp += diff[3];
|
||||||
}
|
|
||||||
return done.executed;
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
// Put a claim on an item from group chest.
|
// Put a claim on an item from group chest.
|
||||||
putRequest (itemId) {
|
putRequest (itemId) {
|
||||||
const playerId = this.state.player_id
|
const playerId = this.state.player_id
|
||||||
Api.putClaim(playerId, itemId)
|
return Api.putClaim(playerId, itemId)
|
||||||
.then(done => {
|
.then(done => {
|
||||||
if (done.executed) {
|
|
||||||
// Update cliend-side state
|
// Update cliend-side state
|
||||||
this.state.player_claims[playerId].push(itemId);
|
this.state.player_claims[playerId].push(itemId);
|
||||||
} else {
|
|
||||||
if (this.debug) console.log("API responded with 'false'")
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
buyItems (items) {
|
||||||
|
return Api.buyItems(this.state.player_id, items)
|
||||||
|
.then(([items, diff]) => {
|
||||||
|
this.__updatePlayerWealth(diff)
|
||||||
|
// Add items to the player loot
|
||||||
|
// TODO: needs refactoring because player mutation happens in
|
||||||
|
// 2 different places
|
||||||
|
return items;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
sellItems (items) {
|
||||||
|
return Api.sellItems(this.state.player_id, items)
|
||||||
|
.then(diff => this.__updatePlayerWealth(diff))
|
||||||
|
},
|
||||||
// Withdraws a claim.
|
// Withdraws a claim.
|
||||||
cancelRequest(itemId) {
|
cancelRequest(itemId) {
|
||||||
const playerId = this.state.player_id
|
const playerId = this.state.player_id
|
||||||
Api.unClaim(playerId, itemId)
|
return Api.unClaim(playerId, itemId)
|
||||||
.then(done => {
|
.then(_ => {
|
||||||
if (done.executed) {
|
|
||||||
var idx = this.state.player_claims[playerId].indexOf(itemId);
|
var idx = this.state.player_claims[playerId].indexOf(itemId);
|
||||||
if (idx > -1) {
|
if (idx > -1) {
|
||||||
this.state.player_claims[playerId].splice(idx, 1);
|
this.state.player_claims[playerId].splice(idx, 1);
|
||||||
} else {
|
} else {
|
||||||
if (this.debug) console.log("cancel a non-existent request")
|
if (this.debug) console.log("cancel a non-existent request")
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
if (this.debug) console.log("API responded with 'false'")
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,168 +1,155 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="container is-paddingless">
|
<article>
|
||||||
<div v-if="mainControlsDisplayed"
|
<p class="control has-icons-left">
|
||||||
class="columns is-mobile is-vcentered"
|
<input type="text" class="input" v-model="searchText">
|
||||||
>
|
<span class="icon is-small is-left"><i class="fas fa-search"></i></span>
|
||||||
<div class="column is-narrow">
|
</p>
|
||||||
<span class="icon is-large">
|
<table class="table is-fullwidth is-striped">
|
||||||
<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>Objets de {{ player }}</th>
|
<th width="100%">Objets</th>
|
||||||
<th v-if="canGrab"></th>
|
<th>Valeur</th>
|
||||||
<th v-if="canSell">
|
<th>
|
||||||
<div class="buttons is-right">
|
<div v-if="perms.canSell" class="buttons" :class="{'has-addons': is_selling}">
|
||||||
<button class="button"
|
<button class="button"
|
||||||
:class="is_selling ? 'is-danger' : 'is-warning'"
|
:class="is_selling ? 'is-danger' : 'is-warning'"
|
||||||
@click="is_selling = !is_selling"
|
@click="sellSelectedItems"
|
||||||
>
|
>
|
||||||
<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">
|
<p v-if="!is_selling">Vendre</p>
|
||||||
Vendre</p>
|
<p v-else>{{ selected_items.length > 0 ? `${totalSelectedValue} po` : 'Annuler' }}</p>
|
||||||
<p v-else>
|
|
||||||
{{ totalSellValue ? totalSellValue : 'Annuler' }}</p>
|
|
||||||
</button>
|
</button>
|
||||||
<PercentInput v-show="is_selling">
|
<PercentInput v-show="is_selling" v-model="global_mod"></PercentInput>
|
||||||
</PercentInput>
|
</div>
|
||||||
|
<div v-else-if="perms.canBuy">
|
||||||
|
<button class="button is-danger is-fullwidth"
|
||||||
|
:disabled="selected_items.length == 0"
|
||||||
|
@click="buySelectedItems"
|
||||||
|
>Acheter ({{ totalSelectedValue}}po)</button>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="perms.canGrab">
|
||||||
|
<button class="button is-static is-fullwidth">Demander</button>
|
||||||
</div>
|
</div>
|
||||||
</th>
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<template v-for="(item, idx) in content">
|
<template v-for="(item, idx) in shownItems">
|
||||||
<tr :key="`row-${idx}`">
|
<tr :key="`row-${idx}`">
|
||||||
<td>{{item.name}}</td>
|
<td>
|
||||||
<td v-if="canGrab">
|
<strong>{{item.name}}</strong>
|
||||||
<Request :item="item.id"></Request>
|
|
||||||
</td>
|
</td>
|
||||||
<td v-if="canSell">
|
<td>
|
||||||
<div class="field is-grouped is-pulled-right" v-show="is_selling">
|
{{ is_selling ? item.base_price / 2 : item.base_price }}po
|
||||||
<div class="control">
|
</td>
|
||||||
<label class="label">
|
<td>
|
||||||
<input type="checkbox"
|
<Request
|
||||||
id="`item-${idx}`"
|
v-if="perms.canGrab"
|
||||||
:value="item.id"
|
:item="item.id"
|
||||||
v-model="sell_selected">
|
@claim="(data) => $emit('claim', data)"
|
||||||
{{item.base_price / 2}} GP
|
@unclaim="(data) => $emit('unclaim', data)"
|
||||||
</label>
|
></Request>
|
||||||
</div>
|
<Selector
|
||||||
<PercentInput></PercentInput>
|
v-else-if="showSelectors"
|
||||||
</div>
|
:id="item.id"
|
||||||
|
v-model="selected_items"
|
||||||
|
></Selector>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</template>
|
</template>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</article>
|
||||||
</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 Loot from './Loot.vue'
|
import Selector from './Selector.vue'
|
||||||
/*
|
/*
|
||||||
The chest displays the collection of items owned by a player
|
The chest displays a collection of items.
|
||||||
|
|
||||||
TO TEST :
|
A set of permissions is passed as props, to update
|
||||||
- Possible interactions depends on player_id and current chest
|
the possible actions of active user upon these items.
|
||||||
- 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: {
|
items: {
|
||||||
type: Number,
|
type: Array,
|
||||||
required: true,
|
required: true,
|
||||||
default: 0
|
},
|
||||||
}
|
perms: {
|
||||||
|
type: Object,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
components: {
|
components: {
|
||||||
Request,
|
Request,
|
||||||
PercentInput,
|
PercentInput,
|
||||||
Loot,
|
Selector,
|
||||||
},
|
},
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
app_state: AppStorage.state,
|
|
||||||
is_selling: false,
|
is_selling: false,
|
||||||
is_adding: false,
|
selected_items: [],
|
||||||
sell_selected: [],
|
global_mod: 0,
|
||||||
|
searchText: "",
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
fetchLoot () {
|
buySelectedItems () {
|
||||||
|
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: {
|
||||||
content () {
|
shownItems () {
|
||||||
const playerId = this.player;
|
if (this.searchText != "") {
|
||||||
console.log("Refresh chest of", playerId);
|
const searchText = this.searchText.toUpperCase();
|
||||||
return this.app_state.player_loot[playerId];
|
return this.items.filter(item => item.name.toUpperCase().includes(searchText));
|
||||||
},
|
} else {
|
||||||
// Can the active user sell items from this chest ?
|
return this.items;
|
||||||
canSell () {
|
|
||||||
return this.player == this.app_state.player_id;
|
|
||||||
},
|
|
||||||
totalSellValue () {
|
|
||||||
const selected = this.sell_selected;
|
|
||||||
return this.content
|
|
||||||
.filter(item => selected.includes(item.id))
|
|
||||||
.map(item => item.base_price / 2)
|
|
||||||
.reduce((total,value) => total + value, 0);
|
|
||||||
},
|
|
||||||
// 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);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
showSelectors () {
|
||||||
|
return !this.perms.canGrab
|
||||||
|
&& (this.is_selling || this.perms.canBuy);
|
||||||
|
},
|
||||||
|
totalSelectedValue () {
|
||||||
|
var total = this.selected_items
|
||||||
|
.map(([id, mod]) => {
|
||||||
|
const item = this.items.find(item => item.id == id);
|
||||||
|
var price = item.base_price * mod;
|
||||||
|
if (this.is_selling) {
|
||||||
|
price = price / 2;
|
||||||
|
}
|
||||||
|
return price;
|
||||||
|
})
|
||||||
|
.reduce((total,value) => total + value, 0);
|
||||||
|
return (1 + this.global_mod / 100) * total;
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
</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>
|
||||||
|
|||||||
36
lootalot_front/src/components/HeaderBar.vue
Normal file
36
lootalot_front/src/components/HeaderBar.vue
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<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,93 +1,96 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="container is-paddingless">
|
<div class="container is-paddingless">
|
||||||
<div class="field has-addons">
|
<p class="heading">Ajouter un objet</p>
|
||||||
<div class="control is-expanded"
|
<div class="field">
|
||||||
:class="{'is-loading': is_loading }">
|
<label for="item_name" class="label">Nom</label>
|
||||||
|
<div class="control is-expanded" :class="{'is-loading': is_loading }">
|
||||||
<input type="text"
|
<input type="text"
|
||||||
v-model="search"
|
id="item_name"
|
||||||
|
v-model="item.name"
|
||||||
@input="autoCompletion"
|
@input="autoCompletion"
|
||||||
class="input"
|
class="input"
|
||||||
:class="{'is-danger': no_results,
|
autocomplete="on"
|
||||||
'is-warning': auto_open}"
|
></input>
|
||||||
autocomplete="on">
|
</div>
|
||||||
</input>
|
<div class="dropdown" :class="{'is-active': showCompletionFrame}">
|
||||||
|
<div class="dropdown-menu">
|
||||||
|
<div class="dropdown-content">
|
||||||
|
<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">
|
||||||
|
<div class="control">
|
||||||
|
<input type="text"
|
||||||
|
class="input"
|
||||||
|
:class="{'is-danger': item.base_price == ''}"
|
||||||
|
v-model.number="item.base_price"
|
||||||
|
></input>
|
||||||
</div>
|
</div>
|
||||||
<div class="control">
|
<div class="control">
|
||||||
<button class="button is-primary"
|
<button class="button is-primary"
|
||||||
:disabled="no_results"
|
|
||||||
@click="addItem"
|
@click="addItem"
|
||||||
>+</button>
|
>+</button>
|
||||||
</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>
|
</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,
|
||||||
no_results: false,
|
item: {
|
||||||
search: '',
|
name: '',
|
||||||
|
base_price: '',
|
||||||
|
},
|
||||||
results: [],
|
results: [],
|
||||||
auto_open: false,
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
autoCompletion (ev) {
|
autoCompletion () {
|
||||||
// TODO: a lot happens here that
|
// Unset any previous value on input (for every field except item's name)
|
||||||
// need to be clarified
|
this.item.base_price = '';
|
||||||
if (this.search == '') {
|
|
||||||
this.auto_open = false;
|
if (this.item.name == '') {
|
||||||
this.results = [];
|
this.results = [];
|
||||||
this.no_results = false;
|
|
||||||
} else {
|
} else {
|
||||||
this.results = MOCK_ITEMS.filter(item => {
|
this.results = this.source.filter(
|
||||||
return item.name.includes(this.search);
|
item => item.name.toUpperCase().includes(this.item.name.toUpperCase())
|
||||||
});
|
);
|
||||||
// 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.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.search);
|
// TODO: check item is valid
|
||||||
this.search = '';
|
this.$emit("addItem", this.item);
|
||||||
|
this.item = {
|
||||||
|
name: '',
|
||||||
|
base_price: '',
|
||||||
|
};
|
||||||
this.results = [];
|
this.results = [];
|
||||||
this.no_results = false;
|
|
||||||
this.auto_open = false;
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
showCompletionFrame () { return this.results.length > 0 },
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.dropdown, .dropdown-menu { min-width: 100%; margin-top: 0; padding-top: 0;}
|
.dropdown, .dropdown-menu { min-width: 100%; margin-top: 0; padding-top: 0;}
|
||||||
.dropdown { top: -0.75rem; }
|
/*.dropdown { top: -0.75rem; }*/
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,32 +1,29 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="card is-shadowless">
|
<div>
|
||||||
<div class="card-header">
|
<p class="heading has-text-left is-size-5">
|
||||||
<p class="card-header-title">
|
|
||||||
Nouveau loot - {{ looted.length }} objet(s)</p>
|
Nouveau loot - {{ looted.length }} objet(s)</p>
|
||||||
</div>
|
<ItemInput @addItem="onAddItem" :source="inventory"></ItemInput>
|
||||||
<div class="card-content">
|
|
||||||
<ItemInput @addItem="onAddItem"></ItemInput>
|
|
||||||
<p v-for="(item, idx) in looted" :key="idx"
|
<p v-for="(item, idx) in looted" :key="idx"
|
||||||
class="has-text-left is-size-5">
|
class="has-text-left is-size-5">
|
||||||
{{ item }}
|
{{ item.name }} ({{ item.sell_value }}po)
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import ItemInput from './ItemInput.vue'
|
import ItemInput from './ItemInput.vue'
|
||||||
|
// 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},
|
||||||
|
{id: 9, name: "Arc court", sell_value: 10},
|
||||||
|
];
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
components: { ItemInput },
|
components: { ItemInput },
|
||||||
data () { return {
|
data () { return {
|
||||||
looted: [],
|
looted: [],
|
||||||
|
inventory: MOCK_ITEMS,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
<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,15 +1,13 @@
|
|||||||
<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 is-small" type="number" size="3" min=-50 max=50 step=5>
|
<input class="input" :value="value" @input="input" type="number" size="3" min="-50" max=50 step=5>
|
||||||
<span class="icon is-small is-left">
|
<span class="icon 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 is-small is-outlined"
|
<button class="button" @click="switchOpenedState">
|
||||||
@click="is_opened = !is_opened"
|
|
||||||
>
|
|
||||||
<small v-if="!is_opened">Mod.</small>
|
<small v-if="!is_opened">Mod.</small>
|
||||||
<span v-else class="icon"><i class="fas fa-times-circle"></i></span>
|
<span v-else class="icon"><i class="fas fa-times-circle"></i></span>
|
||||||
</button>
|
</button>
|
||||||
@@ -19,10 +17,25 @@
|
|||||||
|
|
||||||
<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>
|
||||||
|
|||||||
@@ -1,165 +0,0 @@
|
|||||||
<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>
|
|
||||||
82
lootalot_front/src/components/PlayerView.js
Normal file
82
lootalot_front/src/components/PlayerView.js
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import { Api, AppStorage } from '../AppStorage'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
props: ["id"],
|
||||||
|
data () { return {
|
||||||
|
notifications: [],
|
||||||
|
loot: [],
|
||||||
|
}},
|
||||||
|
methods: {
|
||||||
|
updateWealth (value) {
|
||||||
|
AppStorage.updatePlayerWealth(value)
|
||||||
|
.then(_ => {if (AppStorage.debug) this.notifications.push("Wealth updated")})
|
||||||
|
.catch(e => {if (AppStorage.debug) console.error("wealthUpdate Error", e)})
|
||||||
|
},
|
||||||
|
putClaim (itemId) {
|
||||||
|
AppStorage.putRequest(itemId)
|
||||||
|
.then(_ => { if (AppStorage.debug) this.notifications.push("Claim put")})
|
||||||
|
},
|
||||||
|
withdrawClaim (itemId) {
|
||||||
|
AppStorage.cancelRequest(itemId)
|
||||||
|
.then(_ => { if (AppStorage.debug) this.notifications.push("Claim withdrawn")})
|
||||||
|
|
||||||
|
},
|
||||||
|
buyItems(items) {
|
||||||
|
AppStorage.buyItems(items)
|
||||||
|
.then((items) => {
|
||||||
|
this.notifications.push(`Bought ${items.length} items`)
|
||||||
|
this.loot = this.loot.concat(items);
|
||||||
|
})
|
||||||
|
},
|
||||||
|
sellItems (items) {
|
||||||
|
AppStorage.sellItems(items)
|
||||||
|
.then(_ => {
|
||||||
|
this.notifications.push(`Sold ${items.length} items`)
|
||||||
|
for (var idx in items) {
|
||||||
|
var to_remove = items[idx][0];
|
||||||
|
this.loot = this.loot.filter((item) => item.id != to_remove);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
parseLoot (items) {
|
||||||
|
this.loot = [];
|
||||||
|
items.map(item => {
|
||||||
|
this.loot.push(item);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
watch: {
|
||||||
|
id: {
|
||||||
|
immediate: true,
|
||||||
|
handler: function(newId) {
|
||||||
|
Api.fetchLoot(newId).then(this.parseLoot);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
player () {
|
||||||
|
if (!AppStorage.state.initiated) {
|
||||||
|
return { name: "Loading",
|
||||||
|
id: 0,
|
||||||
|
cp: '-', sp: '-', gp: '-', pp: '-',
|
||||||
|
debt: 0 };
|
||||||
|
} else {
|
||||||
|
return AppStorage.state.player_list[this.id];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,26 +1,22 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="buttons is-right" >
|
<div class="buttons">
|
||||||
<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">
|
<span class="icon is-small">
|
||||||
<i class="fas fa-hand-peace"></i>
|
<i class="fas fa-hand-peace"></i>
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="button is-danger"
|
<button class="button is-danger"
|
||||||
@click="hardenRequest"
|
@click="hardenRequest">
|
||||||
>
|
|
||||||
<span class="icon is-small">
|
<span class="icon is-small">
|
||||||
<i class="fas fa-hand-middle-finger"></i>
|
<i class="fas fa-hand-middle-finger"></i>
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
</template>
|
</template>
|
||||||
<button class="button is-primary"
|
<button class="button is-primary is-fullwidth"
|
||||||
@click="putRequest"
|
@click="putRequest"
|
||||||
:class="{'is-outlined': isRequested}"
|
:disabled="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>
|
||||||
@@ -33,20 +29,18 @@
|
|||||||
export default {
|
export default {
|
||||||
props: ["item"],
|
props: ["item"],
|
||||||
data () {
|
data () {
|
||||||
return {
|
return AppStorage.state;
|
||||||
state: AppStorage.state,
|
|
||||||
};
|
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
// Check if item is requested by active player
|
// Check if item is requested by active player
|
||||||
isRequested () {
|
isRequested () {
|
||||||
const reqs = this.state.player_claims[this.state.player_id];
|
const reqs = this.player_claims[this.player_id];
|
||||||
return reqs.includes(this.item);
|
return reqs.includes(this.item);
|
||||||
},
|
},
|
||||||
// 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 reqs = this.player_claims;
|
||||||
const playerId = this.state.player_id;
|
const playerId = this.player_id;
|
||||||
var reqByPlayer = false;
|
var reqByPlayer = false;
|
||||||
var reqByOther = false;
|
var reqByOther = false;
|
||||||
for (var key in reqs) {
|
for (var key in reqs) {
|
||||||
@@ -65,11 +59,11 @@
|
|||||||
methods: {
|
methods: {
|
||||||
// The active player claims the item
|
// The active player claims the item
|
||||||
putRequest () {
|
putRequest () {
|
||||||
AppStorage.putRequest(this.item)
|
this.$emit("claim", this.item);
|
||||||
},
|
},
|
||||||
// The active player withdraws his request
|
// The active player withdraws his request
|
||||||
cancelRequest () {
|
cancelRequest () {
|
||||||
AppStorage.cancelRequest(this.item)
|
this.$emit("unclaim", 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
|
||||||
@@ -79,3 +73,7 @@
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.buttons, .button { margin-bottom: 0; }
|
||||||
|
</style>
|
||||||
|
|||||||
57
lootalot_front/src/components/Selector.vue
Normal file
57
lootalot_front/src/components/Selector.vue
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
<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,92 +1,97 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="box is-shadowless">
|
<section class="level is-mobile">
|
||||||
<nav class="columns is-mobile is-multiline is-vcentered">
|
<div class="level-left">
|
||||||
<div class="column">
|
<div class="level-item">
|
||||||
<span class="icon is-large"
|
<span class="icon is-large" @click="editing = !editing">
|
||||||
@click="edit = !edit">
|
|
||||||
<i class="fas fa-2x fa-piggy-bank"></i>
|
<i class="fas fa-2x fa-piggy-bank"></i>
|
||||||
</span>
|
</span>
|
||||||
<p v-if="debt" class="has-text-danger">-{{ debt }}gp </p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="column has-text-info">
|
<template v-if="editing">
|
||||||
|
<div class="level-item">
|
||||||
|
<div class="field has-addons">
|
||||||
|
<p class="control">
|
||||||
|
<input class="input" type="number" step="0.01" v-model="edit_value"></input>
|
||||||
|
</p>
|
||||||
|
<p class="control">
|
||||||
|
<a class="button is-static">po</a>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="level-item">
|
||||||
|
<button class="button is-danger" @click="updateWealth()">
|
||||||
|
Modifier
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<div class="level-item ">
|
||||||
|
<p class="is-size-4">{{ pp }}</p>
|
||||||
<p class="heading">PP</p>
|
<p class="heading">PP</p>
|
||||||
<p class="is-size-4">{{ wealth[3] }}</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="column has-text-warning">
|
<div class="level-item ">
|
||||||
|
<p class="is-size-4">{{ gp }}</p>
|
||||||
<p class="heading">PO</p>
|
<p class="heading">PO</p>
|
||||||
<p class="is-size-4">{{ wealth[2] }}</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="column has-text-grey">
|
<div class="level-item ">
|
||||||
|
<p class="is-size-4 has-text-grey-light">{{ sp }}</p>
|
||||||
<p class="heading">PA</p>
|
<p class="heading">PA</p>
|
||||||
<p class="is-size-4">{{ wealth[1] }}</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="column has-text-grey">
|
<div class="level-item ">
|
||||||
|
<p class="is-size-4 has-text-grey-light">{{ cp }}</p>
|
||||||
<p class="heading">PC</p>
|
<p class="heading">PC</p>
|
||||||
<p class="is-size-4">{{ wealth[0] }}</p>
|
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</template>
|
||||||
<div v-if="edit"> <!-- or v-show ? -->
|
|
||||||
<nav class="columns is-mobile">
|
|
||||||
<div class="column">
|
|
||||||
<NumberInput v-model="edit_value"></NumberInput>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="column is-2">
|
<div class="level-right" v-if="debt">
|
||||||
<button class="button is-outlined is-fullwidth is-danger"
|
<div class="level-item">
|
||||||
@click="updateWealth('minus')">
|
<p class="heading is-size-4 has-text-danger">Dette: {{ debt }}gp </p>
|
||||||
<span class="icon"><i class="fas fa-2x fa-minus"></i></span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="column is-2">
|
|
||||||
<button class="button is-outlined is-primary is-fullwidth"
|
|
||||||
@click="updateWealth('plus')">
|
|
||||||
<span class="icon"><i class="fas fa-2x fa-plus"></i></span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
</div>
|
</div>
|
||||||
</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 {
|
||||||
edit: false,
|
editing: false,
|
||||||
edit_value: 0,
|
edit_value: 0,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
updateWealth (op) {
|
updateWealth () {
|
||||||
var goldValue;
|
this.$emit("update", this.edit_value);
|
||||||
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();
|
this.resetValues();
|
||||||
} else {
|
|
||||||
console.log('correct errors');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
resetValues () {
|
resetValues () {
|
||||||
this.edit = false;
|
this.editing = 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>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ extern crate actix_web;
|
|||||||
extern crate dotenv;
|
extern crate dotenv;
|
||||||
extern crate env_logger;
|
extern crate env_logger;
|
||||||
extern crate lootalot_db;
|
extern crate lootalot_db;
|
||||||
|
extern crate serde;
|
||||||
|
|
||||||
mod server;
|
mod server;
|
||||||
|
|
||||||
|
|||||||
125
src/server.rs
125
src/server.rs
@@ -4,6 +4,7 @@ use actix_web::{web, App, Error, HttpResponse, HttpServer};
|
|||||||
use futures::Future;
|
use futures::Future;
|
||||||
use lootalot_db::{DbApi, Pool, QueryResult};
|
use lootalot_db::{DbApi, Pool, QueryResult};
|
||||||
use std::env;
|
use std::env;
|
||||||
|
use serde::{Serialize, Deserialize};
|
||||||
|
|
||||||
type AppPool = web::Data<Pool>;
|
type AppPool = web::Data<Pool>;
|
||||||
|
|
||||||
@@ -28,13 +29,13 @@ type AppPool = web::Data<Pool>;
|
|||||||
/// }
|
/// }
|
||||||
/// )
|
/// )
|
||||||
/// ```
|
/// ```
|
||||||
pub fn db_call<
|
pub fn db_call<J,Q>(
|
||||||
J: serde::ser::Serialize + Send + 'static,
|
|
||||||
Q: Fn(DbApi) -> QueryResult<J> + Send + 'static,
|
|
||||||
>(
|
|
||||||
pool: AppPool,
|
pool: AppPool,
|
||||||
query: Q,
|
query: Q,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item=HttpResponse, Error=Error>
|
||||||
|
where J: serde::ser::Serialize + Send + 'static,
|
||||||
|
Q: Fn(DbApi) -> QueryResult<J> + Send + 'static,
|
||||||
|
{
|
||||||
let conn = pool.get().unwrap();
|
let conn = pool.get().unwrap();
|
||||||
web::block(move || {
|
web::block(move || {
|
||||||
let api = DbApi::with_conn(&conn);
|
let api = DbApi::with_conn(&conn);
|
||||||
@@ -49,6 +50,30 @@ pub fn db_call<
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
struct PlayerClaim {
|
||||||
|
player_id: i32,
|
||||||
|
item_id: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
struct WealthUpdate {
|
||||||
|
player_id: i32,
|
||||||
|
value_in_gp: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
struct NewPlayer {
|
||||||
|
name: String,
|
||||||
|
wealth: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
struct LootUpdate {
|
||||||
|
player_id: i32,
|
||||||
|
items: Vec<(i32, Option<f32>)>,
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn serve() -> std::io::Result<()> {
|
pub(crate) fn serve() -> std::io::Result<()> {
|
||||||
let www_root: String = env::var("WWW_ROOT").expect("WWW_ROOT must be set");
|
let www_root: String = env::var("WWW_ROOT").expect("WWW_ROOT must be set");
|
||||||
dbg!(&www_root);
|
dbg!(&www_root);
|
||||||
@@ -60,63 +85,95 @@ pub(crate) fn serve() -> std::io::Result<()> {
|
|||||||
.wrap(
|
.wrap(
|
||||||
Cors::new()
|
Cors::new()
|
||||||
.allowed_origin("http://localhost:8080")
|
.allowed_origin("http://localhost:8080")
|
||||||
.allowed_methods(vec!["GET", "POST"])
|
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
||||||
.max_age(3600),
|
.max_age(3600),
|
||||||
)
|
)
|
||||||
.service(
|
.service(
|
||||||
web::scope("/api")
|
web::scope("/api")
|
||||||
|
.route("/items", web::get().to_async(move |pool: AppPool| {
|
||||||
|
db_call(pool, move |api| api.fetch_inventory())
|
||||||
|
}))
|
||||||
|
.service(
|
||||||
|
web::scope("/players")
|
||||||
.route(
|
.route(
|
||||||
"/players",
|
"/all",
|
||||||
web::get().to_async(move |pool: AppPool| {
|
web::get().to_async(move |pool: AppPool| {
|
||||||
db_call(pool, move |api| api.fetch_players())
|
db_call(pool, move |api| api
|
||||||
|
.fetch_players())
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/claims",
|
"/loot/{player_id}",
|
||||||
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>| {
|
web::get().to_async(move |pool: AppPool, player_id: web::Path<i32>| {
|
||||||
db_call(pool, move |api| api.as_player(*player_id).loot())
|
db_call(pool, move |api| api.as_player(*player_id).loot())
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/{player_id}/claim/{item_id}",
|
"/update-wealth",
|
||||||
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, i32)>| {
|
web::put().to_async(move |pool: AppPool, data: web::Json<WealthUpdate>| {
|
||||||
db_call(pool, move |api| api.as_player(data.0).claim(data.1))
|
db_call(pool, move |api| api
|
||||||
|
.as_player(data.player_id)
|
||||||
|
.update_wealth(data.value_in_gp))
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/{player_id}/unclaim/{item_id}",
|
"/buy",
|
||||||
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, i32)>| {
|
web::post().to_async(move |pool: AppPool, data: web::Json<LootUpdate>| {
|
||||||
db_call(pool, move |api| api.as_player(data.0).unclaim(data.1))
|
db_call(pool, move |api| api
|
||||||
|
.as_player(data.player_id)
|
||||||
|
.buy(&data.items),
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/admin/resolve-claims",
|
"/sell",
|
||||||
|
web::post().to_async(move |pool: AppPool, data: web::Json<LootUpdate>| {
|
||||||
|
db_call(pool, move |api| api
|
||||||
|
.as_player(data.player_id)
|
||||||
|
.sell(&data.items),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.service(
|
||||||
|
web::resource("/claims")
|
||||||
|
.route(web::get()
|
||||||
|
.to_async(move |pool: AppPool| {
|
||||||
|
db_call(pool, move |api| api
|
||||||
|
.fetch_claims())
|
||||||
|
}))
|
||||||
|
.route(web::put()
|
||||||
|
.to_async(move |pool: AppPool, data: web::Json<PlayerClaim>| {
|
||||||
|
db_call(pool, move |api| api
|
||||||
|
.as_player(data.player_id)
|
||||||
|
.claim(data.item_id))
|
||||||
|
}))
|
||||||
|
.route(web::delete()
|
||||||
|
.to_async(move |pool: AppPool, data: web::Json<PlayerClaim>| {
|
||||||
|
db_call(pool, move |api| api
|
||||||
|
.as_player(data.player_id)
|
||||||
|
.unclaim(data.item_id))
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
.service(web::scope("/admin")
|
||||||
|
.route(
|
||||||
|
"/resolve-claims",
|
||||||
web::get().to_async(move |pool: AppPool| {
|
web::get().to_async(move |pool: AppPool| {
|
||||||
db_call(pool, move |api| api.as_admin().resolve_claims())
|
db_call(pool, move |api| api.as_admin().resolve_claims())
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/admin/add-player/{name}/{wealth}",
|
"/add-player",
|
||||||
web::get().to_async(
|
web::get().to_async(
|
||||||
move |pool: AppPool, data: web::Path<(String, f32)>| {
|
move |pool: AppPool, data: web::Json<NewPlayer>| {
|
||||||
db_call(pool, move |api| {
|
db_call(pool, move |api| api
|
||||||
api.as_admin().add_player(data.0.clone(), data.1)
|
.as_admin()
|
||||||
})
|
.add_player(&data.name, data.wealth),
|
||||||
|
)
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user