Compare commits
75 Commits
c483f29096
...
refactor_u
| Author | SHA1 | Date | |
|---|---|---|---|
| 08f29fc90e | |||
| 4f60df88d7 | |||
| 51a3d00d03 | |||
| 0636829fdd | |||
| 143d9bb5aa | |||
| 21369535e8 | |||
| 441b7f5ad6 | |||
| 4b55964786 | |||
| caabad3982 | |||
| 96f8e36c97 | |||
| 58f39ae5d0 | |||
| 5d54d40bec | |||
| caa8d3fad6 | |||
| e08cd64743 | |||
| bc65dfcd78 | |||
| 63c14b4a54 | |||
| b4692a7a4e | |||
| 5f0e6624e0 | |||
| 503ebf7b6b | |||
| 4e28eb4159 | |||
| b8968aebbd | |||
| c95c13bf18 | |||
| 5a792edb20 | |||
| 36c8f24fdc | |||
| 9acedd4119 | |||
| 5f598aff24 | |||
| f6ee865088 | |||
| 5379ad236f | |||
| 99404543b3 | |||
| a77fce417c | |||
| f5e495734f | |||
| 23adaa3e79 | |||
| 3d612f33d7 | |||
| 966cafb9d9 | |||
| 0f77a16a8c | |||
| 472e24a62c | |||
| 48f71e048e | |||
| 396989f3dd | |||
| f589751f8c | |||
| ed6a6a4a3f | |||
| f00105aaa5 | |||
| f619f7229b | |||
| 9b3df58a08 | |||
| ef9124cc74 | |||
| d9b629116c | |||
| 3b1ad574cd | |||
| f50765b5ad | |||
| 192c214b6b | |||
| 0ff303475b | |||
| fddb5409b4 | |||
| b345faa517 | |||
| aa23fd7077 | |||
| be5d719068 | |||
| d1f2f55c88 | |||
| 50b00cb626 | |||
| 89547c52e5 | |||
| a058357815 | |||
| dc7a0da95d | |||
| 0e71776f4f | |||
| 109a01a368 | |||
| 93e839e40e | |||
| 5a3c628e8e | |||
| a1a270f5f0 | |||
| d257ffc775 | |||
| 3deda52df4 | |||
| 6843fc92cf | |||
| 2efed539fb | |||
| 3232710a4c | |||
| a57ffdb6c6 | |||
| eeb297215a | |||
| 022b97520f | |||
| feef8146d2 | |||
| 4454bd245c | |||
| ba1792ef55 | |||
| dc978fc87f |
11
.gitignore
vendored
11
.gitignore
vendored
@@ -1,2 +1,11 @@
|
|||||||
/target
|
/target
|
||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
fontawesome
|
||||||
|
package-lock.json
|
||||||
|
|
||||||
|
Cargo.lock
|
||||||
|
**/*.sqlite3
|
||||||
|
**/.env
|
||||||
|
|
||||||
|
|||||||
14
Cargo.toml
14
Cargo.toml
@@ -5,3 +5,17 @@ authors = ["Artus <artus@landoftheunicorn.ovh>"]
|
|||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
actix-web = "1.0.*"
|
||||||
|
actix-files = "*"
|
||||||
|
lootalot-db = { version = "0.1", path = "./lootalot_db" }
|
||||||
|
dotenv = "*"
|
||||||
|
env_logger = "*"
|
||||||
|
futures = "0.1"
|
||||||
|
diesel = "*"
|
||||||
|
serde = "*"
|
||||||
|
actix-cors = "0.1.0"
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
members = [
|
||||||
|
"lootalot_db"
|
||||||
|
]
|
||||||
|
|||||||
22
README.md
22
README.md
@@ -16,14 +16,18 @@ Un gestionnaire de trésors pour des joueurs de Donjon&Dragons(tm).
|
|||||||
|
|
||||||
## Base de données
|
## Base de données
|
||||||
|
|
||||||
### Objets
|
### Objets (items)
|
||||||
|
|
||||||
L'inventaire des objets qui peuvent être lootés.
|
L'inventaire des objets qui peuvent être lootés.
|
||||||
PK: id
|
PK: id
|
||||||
|
|
||||||
### Propriétaires
|
### 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)
|
||||||
|
|
||||||
Les joueurs sont des propriétaires d'objet.
|
|
||||||
Le "groupe" est un propriétaire spécial, avec un ID réservé : 0
|
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.
|
La table conserve l'état actuel des finances du propriétaire. L'attribut `dette` représente la dette envers le groupe.
|
||||||
@@ -32,16 +36,16 @@ La table conserve l'état actuel des finances du propriétaire. L'attribut `dett
|
|||||||
PK: id
|
PK: id
|
||||||
ATTRS: name, debt (in gp), pp, sp, gp, cp
|
ATTRS: name, debt (in gp), pp, sp, gp, cp
|
||||||
```
|
```
|
||||||
### Propriété
|
### Requêtes (claims)
|
||||||
|
|
||||||
Table associative entre objets et propriétaires (joueurs ou groupe)
|
Table associative entre objets lootés et joueurs.
|
||||||
L'ajout d'un objet à un propriétaire est un achat. La suppression, une vente.
|
Représente les requêtes des joueurs. La colonne `resolve` permettra d'établir un classement de détermination entre les joueurs.
|
||||||
NB: L'historique d'achat est enregistré puis effacé lors de la vente.
|
|
||||||
```
|
```
|
||||||
PK: id
|
PK: id
|
||||||
FK: objets_id, proprietaire_id
|
FK: loot_id, player_id
|
||||||
ATTRS: acquired_date, at_value
|
ATTRS: resolve
|
||||||
```
|
```
|
||||||
|
|
||||||
### Opérations
|
### Opérations
|
||||||
|
|
||||||
_Doit-on garder un historique des opérations ?_
|
_Doit-on garder un historique des opérations ?_
|
||||||
|
|||||||
15
lootalot_db/Cargo.toml
Normal file
15
lootalot_db/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
[package]
|
||||||
|
name = "lootalot-db"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Artus <artus@landoftheunicorn.ovh>"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
dotenv = "*"
|
||||||
|
diesel_migrations = "*"
|
||||||
|
serde = "*"
|
||||||
|
serde_derive = "*"
|
||||||
|
|
||||||
|
[dependencies.diesel]
|
||||||
|
version = "1.4"
|
||||||
|
features = ["sqlite", "r2d2"]
|
||||||
BIN
lootalot_db/db.sqlite3
Normal file
BIN
lootalot_db/db.sqlite3
Normal file
Binary file not shown.
5
lootalot_db/diesel.toml
Normal file
5
lootalot_db/diesel.toml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
# For documentation on how to configure this file,
|
||||||
|
# see diesel.rs/guides/configuring-diesel-cli
|
||||||
|
|
||||||
|
[print_schema]
|
||||||
|
file = "src/schema.rs"
|
||||||
0
lootalot_db/migrations/.gitkeep
Normal file
0
lootalot_db/migrations/.gitkeep
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
DROP TABLE items;
|
||||||
|
DROP TABLE looted;
|
||||||
|
|
||||||
15
lootalot_db/migrations/2019-06-10-123922_create_items/up.sql
Normal file
15
lootalot_db/migrations/2019-06-10-123922_create_items/up.sql
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
-- The global inventory of items
|
||||||
|
CREATE TABLE items (
|
||||||
|
id INTEGER PRIMARY KEY NOT NULL,
|
||||||
|
name VARCHAR NOT NULL,
|
||||||
|
base_price INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- The items that have been looted
|
||||||
|
CREATE TABLE looted (
|
||||||
|
id INTEGER PRIMARY KEY NOT NULL,
|
||||||
|
name VARCHAR NOT NULL,
|
||||||
|
base_price INTEGER NOT NULL,
|
||||||
|
owner_id INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (owner_id) REFERENCES players(id)
|
||||||
|
);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE players;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
CREATE TABLE players (
|
||||||
|
id INTEGER PRIMARY KEY NOT NULL,
|
||||||
|
name VARCHAR NOT NULL,
|
||||||
|
debt INTEGER DEFAULT 0 NOT NULL, -- debt to the group in copper pieces
|
||||||
|
cp INTEGER DEFAULT 0 NOT NULL,
|
||||||
|
sp INTEGER DEFAULT 0 NOT NULL,
|
||||||
|
gp INTEGER DEFAULT 0 NOT NULL,
|
||||||
|
pp INTEGER DEFAULT 0 NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO players (id, name) VALUES (0, 'Groupe');
|
||||||
1
lootalot_db/migrations/2019-06-21-113950_claims/down.sql
Normal file
1
lootalot_db/migrations/2019-06-21-113950_claims/down.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE claims;
|
||||||
8
lootalot_db/migrations/2019-06-21-113950_claims/up.sql
Normal file
8
lootalot_db/migrations/2019-06-21-113950_claims/up.sql
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE claims (
|
||||||
|
id INTEGER PRIMARY KEY NOT NULL,
|
||||||
|
player_id INTEGER NOT NULL,
|
||||||
|
loot_id INTEGER NOT NULL,
|
||||||
|
resolve INTEGER NOT NULL DEFAULT 0,
|
||||||
|
FOREIGN KEY (player_id) REFERENCES players(id),
|
||||||
|
FOREIGN KEY (loot_id) REFERENCES looted(id)
|
||||||
|
);
|
||||||
489
lootalot_db/src/lib.rs
Normal file
489
lootalot_db/src/lib.rs
Normal file
@@ -0,0 +1,489 @@
|
|||||||
|
//! Loot-a-lot Database module
|
||||||
|
//!
|
||||||
|
//! # Description
|
||||||
|
//! This module wraps all needed database operations.
|
||||||
|
//! It exports a public API for integration with various clients (REST Api, CLI, ...)
|
||||||
|
extern crate dotenv;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate diesel;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate serde_derive;
|
||||||
|
|
||||||
|
use diesel::prelude::*;
|
||||||
|
use diesel::query_dsl::RunQueryDsl;
|
||||||
|
use diesel::r2d2::{self, ConnectionManager};
|
||||||
|
|
||||||
|
mod transactions;
|
||||||
|
pub mod models;
|
||||||
|
mod schema;
|
||||||
|
use transactions::{DbTransaction};
|
||||||
|
|
||||||
|
/// The connection used
|
||||||
|
pub type DbConnection = SqliteConnection;
|
||||||
|
/// A pool of connections
|
||||||
|
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
|
||||||
|
/// The result of a query on DB
|
||||||
|
pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
||||||
|
pub type ActionResult<T> = QueryResult<ActionStatus<T>>;
|
||||||
|
/// Return status of an Action
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
pub struct ActionStatus<R: serde::Serialize> {
|
||||||
|
/// Has the action made changes ?
|
||||||
|
pub executed: bool,
|
||||||
|
/// Response payload
|
||||||
|
pub response: R,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActionStatus<()> {
|
||||||
|
pub fn was_updated(updated_lines: usize) -> Self {
|
||||||
|
match updated_lines {
|
||||||
|
1 => Self::ok(),
|
||||||
|
_ => Self::nop(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn ok() -> ActionStatus<()> {
|
||||||
|
Self {
|
||||||
|
executed: true,
|
||||||
|
response: (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Default + serde::Serialize> ActionStatus<T> {
|
||||||
|
pub fn nop() -> ActionStatus<T> {
|
||||||
|
Self {
|
||||||
|
executed: false,
|
||||||
|
response: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// A wrapper providing an API over the database
|
||||||
|
/// It offers a convenient way to deal with connection.
|
||||||
|
///
|
||||||
|
/// # Note
|
||||||
|
/// All methods consumes the DbApi, so that only one action
|
||||||
|
/// can be performed using a single instance.
|
||||||
|
///
|
||||||
|
/// # Todo list
|
||||||
|
/// ```text
|
||||||
|
/// v .as_player()
|
||||||
|
/// // Needs an action's history (one entry only should be enough)
|
||||||
|
/// x .undo_last_action() -> Success status
|
||||||
|
/// v .as_admin()
|
||||||
|
/// // When adding loot, an identifier should be used to build some kind of history
|
||||||
|
/// vx .add_loot(identifier, [items_desc]) -> Success status
|
||||||
|
/// x .sell_loot([players], [excluded_item_ids]) -> Success status (bool, player_share)
|
||||||
|
/// // Claims should be resolved after a certain delay
|
||||||
|
/// x .set_claims_timeout()
|
||||||
|
/// x .resolve_claims()
|
||||||
|
/// v .add_player(player_data)
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
pub struct DbApi<'q>(&'q DbConnection);
|
||||||
|
|
||||||
|
impl<'q> DbApi<'q> {
|
||||||
|
/// Returns a DbApi using the user given connection
|
||||||
|
///
|
||||||
|
/// # Usage
|
||||||
|
/// ```
|
||||||
|
/// use lootalot_db::{DbConnection, DbApi};
|
||||||
|
/// # use diesel::connection::Connection;
|
||||||
|
/// let conn = DbConnection::establish(":memory:").unwrap();
|
||||||
|
/// let api = DbApi::with_conn(&conn);
|
||||||
|
/// ```
|
||||||
|
pub fn with_conn(conn: &'q DbConnection) -> Self {
|
||||||
|
Self(conn)
|
||||||
|
}
|
||||||
|
/// Fetch the list of all players
|
||||||
|
pub fn fetch_players(self) -> QueryResult<Vec<models::Player>> {
|
||||||
|
Ok(schema::players::table.load::<models::Player>(self.0)?)
|
||||||
|
}
|
||||||
|
/// Fetch the inventory of items
|
||||||
|
pub fn fetch_inventory(self) -> QueryResult<Vec<models::Item>> {
|
||||||
|
Ok(schema::items::table.load::<models::Item>(self.0)?)
|
||||||
|
}
|
||||||
|
/// Fetch all existing claims
|
||||||
|
pub fn fetch_claims(self) -> QueryResult<Vec<models::Claim>> {
|
||||||
|
Ok(schema::claims::table.load::<models::Claim>(self.0)?)
|
||||||
|
}
|
||||||
|
/// Wrapper for acting as a specific player
|
||||||
|
///
|
||||||
|
/// # Usage
|
||||||
|
/// ```
|
||||||
|
/// # use lootalot_db::{DbConnection, DbApi};
|
||||||
|
/// # use diesel::connection::Connection;
|
||||||
|
/// # let conn = DbConnection::establish(":memory:").unwrap();
|
||||||
|
/// # let api = DbApi::with_conn(&conn);
|
||||||
|
/// let player_id: i32 = 1; // Id that references player in DB
|
||||||
|
/// let player = api.as_player(player_id);
|
||||||
|
/// ```
|
||||||
|
pub fn as_player(self, id: i32) -> AsPlayer<'q> {
|
||||||
|
AsPlayer { id, conn: self.0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wrapper for acting as the admin
|
||||||
|
pub fn as_admin(self) -> AsAdmin<'q> {
|
||||||
|
AsAdmin(self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A wrapper for interactions of players with the database.
|
||||||
|
/// Possible actions are exposed as methods
|
||||||
|
pub struct AsPlayer<'q> {
|
||||||
|
id: i32,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'q> AsPlayer<'q> {
|
||||||
|
/// Fetch the content of a player's chest
|
||||||
|
///
|
||||||
|
/// # Usage
|
||||||
|
/// ```
|
||||||
|
/// # extern crate diesel_migrations;
|
||||||
|
/// # use lootalot_db::{DbConnection, DbApi};
|
||||||
|
/// # use diesel::connection::Connection;
|
||||||
|
/// # let conn = DbConnection::establish(":memory:").unwrap();
|
||||||
|
/// # diesel_migrations::run_pending_migrations(&conn).unwrap();
|
||||||
|
/// # let api = DbApi::with_conn(&conn);
|
||||||
|
/// // Get loot of player with id of 1
|
||||||
|
/// let loot = api.as_player(1).loot().unwrap();
|
||||||
|
/// assert_eq!(format!("{:?}", loot), "[]".to_string());
|
||||||
|
/// ```
|
||||||
|
pub fn loot(self) -> QueryResult<Vec<models::Item>> {
|
||||||
|
Ok(models::Item::owned_by(self.id).load(self.conn)?)
|
||||||
|
}
|
||||||
|
/// Buy an item and add it to this player chest
|
||||||
|
///
|
||||||
|
/// TODO: Items should be picked from a custom list
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// This currently panics if player wealth fails to be updated, as this is
|
||||||
|
/// a serious error. TODO: handle deletion of bought item in case of wealth update failure.
|
||||||
|
pub fn buy<S: Into<String>>(self, name: S, price: i32) -> ActionResult<Option<(i32, i32, i32, i32)>> {
|
||||||
|
match transactions::player::Buy.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::AddLootParams {
|
||||||
|
player_id: self.id,
|
||||||
|
loot_name: name.into(),
|
||||||
|
loot_price: price,
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Ok(res) => Ok(ActionStatus { executed: true, response: Some(res.loot_cost) }),
|
||||||
|
Err(e) => { dbg!(&e); Ok(ActionStatus { executed: false, response: None}) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Sell an item from this player chest
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// This currently panics if player wealth fails to be updated, as this is
|
||||||
|
/// a serious error. TODO: handle restoring of sold item in case of wealth update failure.
|
||||||
|
pub fn sell(
|
||||||
|
self,
|
||||||
|
loot_id: i32,
|
||||||
|
_price_mod: Option<f32>,
|
||||||
|
) -> ActionResult<Option<(i32, i32, i32, i32)>> {
|
||||||
|
// Check that the item belongs to player
|
||||||
|
let exists_and_owned: bool =
|
||||||
|
diesel::select(models::Loot::owns(self.id, loot_id))
|
||||||
|
.get_result(self.conn)?;
|
||||||
|
if !exists_and_owned {
|
||||||
|
return Ok(ActionStatus::nop());
|
||||||
|
}
|
||||||
|
transactions::player::Sell.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::LootParams {
|
||||||
|
player_id: self.id,
|
||||||
|
loot_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|res| ActionStatus { executed: true, response: Some(res.loot_cost) })
|
||||||
|
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop()) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds the value in gold to the player's wealth.
|
||||||
|
///
|
||||||
|
/// Value can be negative to substract wealth.
|
||||||
|
pub fn update_wealth(self, value_in_gp: f32) -> ActionResult<Option<(i32, i32, i32, i32)>> {
|
||||||
|
transactions::player::UpdateWealth.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::WealthParams {
|
||||||
|
player_id: self.id,
|
||||||
|
value_in_gp,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|res| ActionStatus { executed: true, response: Some(res) })
|
||||||
|
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
||||||
|
}
|
||||||
|
/// Put a claim on a specific item
|
||||||
|
pub fn claim(self, item: i32) -> ActionResult<()> {
|
||||||
|
let exists: bool =
|
||||||
|
diesel::select(models::Loot::exists(item)).get_result(self.conn)?;
|
||||||
|
if !exists {
|
||||||
|
return Ok(ActionStatus::nop());
|
||||||
|
};
|
||||||
|
transactions::player::PutClaim.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::LootParams {
|
||||||
|
player_id: self.id,
|
||||||
|
loot_id: item,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|_| ActionStatus { executed: true, response: () })
|
||||||
|
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
||||||
|
}
|
||||||
|
/// Withdraw claim
|
||||||
|
pub fn unclaim(self, item: i32) -> ActionResult<()> {
|
||||||
|
transactions::player::WithdrawClaim.execute(
|
||||||
|
self.conn,
|
||||||
|
transactions::player::LootParams {
|
||||||
|
player_id: self.id,
|
||||||
|
loot_id: item,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map(|_| ActionStatus { executed: true, response: () })
|
||||||
|
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wrapper for interactions of admins with the DB.
|
||||||
|
pub struct AsAdmin<'q>(&'q DbConnection);
|
||||||
|
|
||||||
|
impl<'q> AsAdmin<'q> {
|
||||||
|
/// Adds a player to the database
|
||||||
|
///
|
||||||
|
/// Takes the player name and starting wealth (in gold value).
|
||||||
|
pub fn add_player(self, name: String, start_wealth: f32) -> ActionResult<()> {
|
||||||
|
diesel::insert_into(schema::players::table)
|
||||||
|
.values(&models::player::NewPlayer::create(&name, start_wealth))
|
||||||
|
.execute(self.0)
|
||||||
|
.map(ActionStatus::was_updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a list of items to the group loot
|
||||||
|
pub fn add_loot<'a>(self, items: Vec<(&'a str, i32)>) -> ActionResult<()> {
|
||||||
|
for item_desc in items.into_iter() {
|
||||||
|
let new_item = models::item::NewLoot::to_group(item_desc);
|
||||||
|
diesel::insert_into(schema::looted::table)
|
||||||
|
.values(&new_item)
|
||||||
|
.execute(self.0)?;
|
||||||
|
}
|
||||||
|
Ok(ActionStatus::ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve all pending claims and dispatch claimed items.
|
||||||
|
///
|
||||||
|
/// When a player gets an item, it's debt is increased by this item sell value
|
||||||
|
pub fn resolve_claims(self) -> ActionResult<()> {
|
||||||
|
// Fetch all claims, grouped by items.
|
||||||
|
let loot = models::Loot::owned_by(0).load(self.0)?;
|
||||||
|
let claims = schema::claims::table
|
||||||
|
.load::<models::Claim>(self.0)?
|
||||||
|
.grouped_by(&loot);
|
||||||
|
// For each claimed item
|
||||||
|
let data = loot.into_iter().zip(claims).collect::<Vec<_>>();
|
||||||
|
dbg!(data);
|
||||||
|
// If mutiples claims -> find highest resolve, give to this player
|
||||||
|
// If only one claim -> give to claiming
|
||||||
|
Ok(ActionStatus::nop())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets up a connection pool and returns it.
|
||||||
|
/// Uses the DATABASE_URL environment variable (must be set)
|
||||||
|
pub fn create_pool() -> Pool {
|
||||||
|
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
|
||||||
|
dbg!(&connspec);
|
||||||
|
let manager = ConnectionManager::<DbConnection>::new(connspec);
|
||||||
|
r2d2::Pool::builder()
|
||||||
|
.build(manager)
|
||||||
|
.expect("Failed to create pool.")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
type TestConnection = DbConnection;
|
||||||
|
|
||||||
|
/// Return a connection to a fresh database (stored in memory)
|
||||||
|
fn test_connection() -> TestConnection {
|
||||||
|
let test_conn = DbConnection::establish(":memory:").unwrap();
|
||||||
|
diesel_migrations::run_pending_migrations(&test_conn).unwrap();
|
||||||
|
test_conn
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When migrations are run, a special player with id 0 and name "Groupe"
|
||||||
|
/// must be created.
|
||||||
|
#[test]
|
||||||
|
fn test_group_is_autocreated() {
|
||||||
|
let conn = test_connection();
|
||||||
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
|
assert_eq!(players.len(), 1);
|
||||||
|
let group = players.get(0).unwrap();
|
||||||
|
assert_eq!(group.id, 0);
|
||||||
|
assert_eq!(group.name, "Groupe".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When a player updates wealth, a difference is returned by API.
|
||||||
|
/// Added to the previous amount of coins, it should equal the updated weath.
|
||||||
|
#[test]
|
||||||
|
fn test_player_updates_wealth() {
|
||||||
|
let conn = test_connection();
|
||||||
|
DbApi::with_conn(&conn)
|
||||||
|
.as_admin()
|
||||||
|
.add_player("PlayerName".to_string(), 403.21)
|
||||||
|
.unwrap();
|
||||||
|
let diff = DbApi::with_conn(&conn)
|
||||||
|
.as_player(1)
|
||||||
|
.update_wealth(-401.21)
|
||||||
|
.unwrap()
|
||||||
|
.response
|
||||||
|
.unwrap();
|
||||||
|
// Check the returned diff
|
||||||
|
assert_eq!(diff, (-1, -2, -1, -4));
|
||||||
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
|
let player = players.get(1).unwrap();
|
||||||
|
// Check that we can add old value to return diff to get resulting value
|
||||||
|
assert_eq!(
|
||||||
|
(player.cp, player.sp, player.gp, player.pp),
|
||||||
|
(1 + diff.0, 2 + diff.1, 3 + diff.2, 4 + diff.3)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_admin_add_player() {
|
||||||
|
let conn = test_connection();
|
||||||
|
let result = DbApi::with_conn(&conn)
|
||||||
|
.as_admin()
|
||||||
|
.add_player("PlayerName".to_string(), 403.21)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(result.executed, true);
|
||||||
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
|
assert_eq!(players.len(), 2);
|
||||||
|
let new_player = players.get(1).unwrap();
|
||||||
|
assert_eq!(new_player.name, "PlayerName");
|
||||||
|
assert_eq!(
|
||||||
|
(new_player.cp, new_player.sp, new_player.gp, new_player.pp),
|
||||||
|
(1, 2, 3, 4)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_admin_resolve_claims() {
|
||||||
|
let conn = test_connection();
|
||||||
|
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||||
|
assert_eq!(claims.len(), 0);
|
||||||
|
assert_eq!(true, false); // Failing as test is not complete
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_player_claim_item() {
|
||||||
|
let conn = test_connection();
|
||||||
|
DbApi::with_conn(&conn)
|
||||||
|
.as_admin()
|
||||||
|
.add_player("Player".to_string(), 0.0)
|
||||||
|
.unwrap();
|
||||||
|
DbApi::with_conn(&conn)
|
||||||
|
.as_admin()
|
||||||
|
.add_loot(vec![("Épée", 25)])
|
||||||
|
.unwrap();
|
||||||
|
// Claim an existing item
|
||||||
|
let result = DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
||||||
|
assert_eq!(result.executed, true);
|
||||||
|
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||||
|
assert_eq!(claims.len(), 1);
|
||||||
|
let claim = claims.get(0).unwrap();
|
||||||
|
assert_eq!(claim.player_id, 1);
|
||||||
|
assert_eq!(claim.loot_id, 1);
|
||||||
|
// Claim an inexistant item
|
||||||
|
let result = DbApi::with_conn(&conn).as_player(1).claim(2).unwrap();
|
||||||
|
assert_eq!(result.executed, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_player_unclaim_item() {
|
||||||
|
let conn = test_connection();
|
||||||
|
DbApi::with_conn(&conn)
|
||||||
|
.as_admin()
|
||||||
|
.add_player("Player".to_string(), 0.0)
|
||||||
|
.unwrap();
|
||||||
|
DbApi::with_conn(&conn)
|
||||||
|
.as_admin()
|
||||||
|
.add_loot(vec![("Épée", 25)])
|
||||||
|
.unwrap();
|
||||||
|
// Claim an existing item
|
||||||
|
let result = DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
||||||
|
assert_eq!(result.executed, true);
|
||||||
|
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1).unwrap();
|
||||||
|
assert_eq!(result.executed, true);
|
||||||
|
// Check that unclaimed items will not be unclaimed...
|
||||||
|
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1).unwrap();
|
||||||
|
assert_eq!(result.executed, false);
|
||||||
|
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||||
|
assert_eq!(claims.len(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All-in-one checks one a simple buy/sell procedure
|
||||||
|
///
|
||||||
|
/// Checks that player's chest and wealth are updated.
|
||||||
|
/// Checks that items are sold at half their value.
|
||||||
|
#[test]
|
||||||
|
fn test_buy_sell_simple() {
|
||||||
|
let conn = test_connection();
|
||||||
|
DbApi::with_conn(&conn)
|
||||||
|
.as_admin()
|
||||||
|
.add_player("Player".to_string(), 1000.0)
|
||||||
|
.unwrap();
|
||||||
|
// Buy an item
|
||||||
|
let bought = DbApi::with_conn(&conn)
|
||||||
|
.as_player(1)
|
||||||
|
.buy("Sword", 800)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(bought.executed, true); // Was updated ?
|
||||||
|
assert_eq!(bought.response, Some((0, 0, 0, -8))); // Returns diff of player wealth ?
|
||||||
|
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
||||||
|
assert_eq!(chest.len(), 1);
|
||||||
|
let loot = chest.get(0).unwrap();
|
||||||
|
assert_eq!(loot.name, "Sword");
|
||||||
|
assert_eq!(loot.base_price, 800);
|
||||||
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
|
let player = players.get(1).unwrap();
|
||||||
|
assert_eq!(player.pp, 2);
|
||||||
|
// Sell back
|
||||||
|
let sold = DbApi::with_conn(&conn)
|
||||||
|
.as_player(1)
|
||||||
|
.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();
|
||||||
|
assert_eq!(chest.len(), 0);
|
||||||
|
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||||
|
let player = players.get(1).unwrap();
|
||||||
|
assert_eq!(player.pp, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_admin_add_loot() {
|
||||||
|
let conn = test_connection();
|
||||||
|
assert_eq!(
|
||||||
|
0,
|
||||||
|
DbApi::with_conn(&conn).as_player(0).loot().unwrap().len()
|
||||||
|
);
|
||||||
|
let loot_to_add = vec![("Cape d'invisibilité", 8000), ("Arc long", 25)];
|
||||||
|
let result = DbApi::with_conn(&conn)
|
||||||
|
.as_admin()
|
||||||
|
.add_loot(loot_to_add.clone())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(result.executed, true);
|
||||||
|
let looted = DbApi::with_conn(&conn).as_player(0).loot().unwrap();
|
||||||
|
assert_eq!(looted.len(), 2);
|
||||||
|
// NB: Not a problem now, but this adds constraints of items being
|
||||||
|
// created in the same order.
|
||||||
|
for (added, to_add) in looted.into_iter().zip(loot_to_add) {
|
||||||
|
assert_eq!(added.name, to_add.0);
|
||||||
|
assert_eq!(added.base_price, to_add.1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
29
lootalot_db/src/models/claim.rs
Normal file
29
lootalot_db/src/models/claim.rs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
use crate::models::item::Loot;
|
||||||
|
use crate::schema::claims;
|
||||||
|
|
||||||
|
/// A Claim is a request by a single player on an item from group chest.
|
||||||
|
#[derive(Identifiable, Queryable, Associations, Serialize, Debug)]
|
||||||
|
#[belongs_to(Loot)]
|
||||||
|
pub struct Claim {
|
||||||
|
/// DB Identifier
|
||||||
|
pub id: i32,
|
||||||
|
/// ID that references the player making this claim
|
||||||
|
pub player_id: i32,
|
||||||
|
/// ID that references the loot claimed
|
||||||
|
pub loot_id: i32,
|
||||||
|
/// WIP: How bad the player wants this item
|
||||||
|
pub resolve: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Insertable, Debug)]
|
||||||
|
#[table_name = "claims"]
|
||||||
|
pub(crate) struct NewClaim {
|
||||||
|
player_id: i32,
|
||||||
|
loot_id: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NewClaim {
|
||||||
|
pub(crate) fn new(player_id: i32, loot_id: i32) -> Self {
|
||||||
|
Self { player_id, loot_id }
|
||||||
|
}
|
||||||
|
}
|
||||||
90
lootalot_db/src/models/item.rs
Normal file
90
lootalot_db/src/models/item.rs
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
use crate::schema::looted;
|
||||||
|
use diesel::dsl::{exists, Eq, Filter, Find, Select};
|
||||||
|
use diesel::expression::exists::Exists;
|
||||||
|
use diesel::prelude::*;
|
||||||
|
|
||||||
|
type ItemColumns = (looted::id, looted::name, looted::base_price);
|
||||||
|
const ITEM_COLUMNS: ItemColumns = (looted::id, looted::name, looted::base_price);
|
||||||
|
type OwnedBy = Select<OwnedLoot, ItemColumns>;
|
||||||
|
|
||||||
|
/// Represents a unique item in inventory
|
||||||
|
///
|
||||||
|
/// It is also used as a public representation of Loot, since owner
|
||||||
|
/// information is implicit.
|
||||||
|
/// Or maybe this is a little too confusing ??
|
||||||
|
#[derive(Debug, Queryable, Serialize)]
|
||||||
|
pub struct Item {
|
||||||
|
pub id: i32,
|
||||||
|
pub name: String,
|
||||||
|
pub base_price: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Item {
|
||||||
|
/// Public proxy for Loot::owned_by that selects only Item fields
|
||||||
|
pub fn owned_by(player: i32) -> OwnedBy {
|
||||||
|
Loot::owned_by(player).select(ITEM_COLUMNS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type WithOwner = Eq<looted::owner_id, i32>;
|
||||||
|
type OwnedLoot = Filter<looted::table, WithOwner>;
|
||||||
|
|
||||||
|
/// Represents an item that has been looted
|
||||||
|
#[derive(Identifiable, Debug, Queryable, Serialize)]
|
||||||
|
#[table_name = "looted"]
|
||||||
|
pub(crate) struct Loot {
|
||||||
|
id: i32,
|
||||||
|
name: String,
|
||||||
|
base_price: i32,
|
||||||
|
owner: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Loot {
|
||||||
|
/// A filter on Loot that is owned by given player
|
||||||
|
pub(crate) fn owned_by(id: i32) -> OwnedLoot {
|
||||||
|
looted::table.filter(looted::owner_id.eq(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn owns(player: i32, item: i32) -> Exists<Find<OwnedLoot, i32>> {
|
||||||
|
exists(Loot::owned_by(player).find(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn exists(id: i32) -> Exists<Find<looted::table, i32>> {
|
||||||
|
exists(looted::table.find(id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Description of an item : (name, value in gold)
|
||||||
|
pub type ItemDesc<'a> = (&'a str, i32);
|
||||||
|
|
||||||
|
/// An item being looted or bought.
|
||||||
|
///
|
||||||
|
/// The owner is set to 0 in case of looting,
|
||||||
|
/// to the id of buying player otherwise.
|
||||||
|
#[derive(Insertable)]
|
||||||
|
#[table_name = "looted"]
|
||||||
|
pub(crate) struct NewLoot<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
base_price: i32,
|
||||||
|
owner_id: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> NewLoot<'a> {
|
||||||
|
/// A new loot going to the group (loot procedure)
|
||||||
|
pub(crate) fn to_group(desc: ItemDesc<'a>) -> Self {
|
||||||
|
Self {
|
||||||
|
name: desc.0,
|
||||||
|
base_price: desc.1,
|
||||||
|
owner_id: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new loot going to a specific player (buy procedure)
|
||||||
|
pub(crate) fn to_player(player: i32, desc: ItemDesc<'a>) -> Self {
|
||||||
|
Self {
|
||||||
|
name: desc.0,
|
||||||
|
base_price: desc.1,
|
||||||
|
owner_id: player,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
8
lootalot_db/src/models/mod.rs
Normal file
8
lootalot_db/src/models/mod.rs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
pub(super) mod claim;
|
||||||
|
pub(super) mod item;
|
||||||
|
pub(super) mod player;
|
||||||
|
|
||||||
|
pub use claim::Claim;
|
||||||
|
pub use item::Item;
|
||||||
|
pub(crate) use item::Loot;
|
||||||
|
pub use player::{Player, Wealth};
|
||||||
131
lootalot_db/src/models/player.rs
Normal file
131
lootalot_db/src/models/player.rs
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
use crate::schema::players;
|
||||||
|
|
||||||
|
/// Representation of a player in database
|
||||||
|
#[derive(Debug, Queryable, Serialize)]
|
||||||
|
pub struct Player {
|
||||||
|
/// DB Identitier
|
||||||
|
pub id: i32,
|
||||||
|
/// Full name of the character
|
||||||
|
pub name: String,
|
||||||
|
/// Amount of gold coins owed to the group.
|
||||||
|
/// Taking a looted items will increase the debt by it's sell value
|
||||||
|
pub debt: i32,
|
||||||
|
/// Count of copper pieces
|
||||||
|
pub cp: i32,
|
||||||
|
/// Count of silver pieces
|
||||||
|
pub sp: i32,
|
||||||
|
/// Count of gold pieces
|
||||||
|
pub gp: i32,
|
||||||
|
/// Count of platinum pieces
|
||||||
|
pub pp: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unpack a floating value in gold pieces to integer
|
||||||
|
/// values of copper, silver, gold and platinum pieces
|
||||||
|
///
|
||||||
|
/// # Note
|
||||||
|
///
|
||||||
|
/// The conversion is slightly different than standard rules :
|
||||||
|
/// ``` 1pp = 100gp = 1000sp = 10000 cp ```
|
||||||
|
///
|
||||||
|
fn unpack_gold_value(gold: f32) -> (i32, i32, i32, i32) {
|
||||||
|
let rest = (gold.fract() * 100.0).round() as i32;
|
||||||
|
let gold = gold.trunc() as i32;
|
||||||
|
let pp = gold / 100;
|
||||||
|
let gp = gold % 100;
|
||||||
|
let sp = rest / 10;
|
||||||
|
let cp = rest % 10;
|
||||||
|
(cp, sp, gp, pp)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// State of a player's wealth
|
||||||
|
///
|
||||||
|
/// Values are held as individual pieces counts.
|
||||||
|
/// Allows conversion from and to a floating amount of gold pieces.
|
||||||
|
#[derive(Queryable, AsChangeset, Debug)]
|
||||||
|
#[table_name = "players"]
|
||||||
|
pub struct Wealth {
|
||||||
|
pub cp: i32,
|
||||||
|
pub sp: i32,
|
||||||
|
pub gp: i32,
|
||||||
|
pub pp: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Wealth {
|
||||||
|
/// Unpack individual pieces counts from gold value
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// # use lootalot_db::models::Wealth;
|
||||||
|
/// let wealth = Wealth::from_gp(403.21);
|
||||||
|
/// assert_eq!(wealth.as_tuple(), (1, 2, 3, 4));
|
||||||
|
/// ```
|
||||||
|
pub fn from_gp(gp: f32) -> Self {
|
||||||
|
let (cp, sp, gp, pp) = unpack_gold_value(gp);
|
||||||
|
Self { cp, sp, gp, pp }
|
||||||
|
}
|
||||||
|
/// Convert total value to a floating value in gold pieces
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// # use lootalot_db::models::Wealth;
|
||||||
|
/// let wealth = Wealth{ pp: 4, gp: 3, sp: 2, cp: 1};
|
||||||
|
/// assert_eq!(wealth.to_gp(), 403.21);
|
||||||
|
/// ```
|
||||||
|
pub fn to_gp(&self) -> f32 {
|
||||||
|
let i = self.pp * 100 + self.gp;
|
||||||
|
let f = (self.sp * 10 + self.cp) as f32 / 100.0;
|
||||||
|
i as f32 + f
|
||||||
|
}
|
||||||
|
/// Pack the counts inside a tuple, from lower to higher coin value.
|
||||||
|
pub fn as_tuple(&self) -> (i32, i32, i32, i32) {
|
||||||
|
(self.cp, self.sp, self.gp, self.pp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Representation of a new player record
|
||||||
|
#[derive(Insertable)]
|
||||||
|
#[table_name = "players"]
|
||||||
|
pub(crate) struct NewPlayer<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
cp: i32,
|
||||||
|
sp: i32,
|
||||||
|
gp: i32,
|
||||||
|
pp: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> NewPlayer<'a> {
|
||||||
|
pub(crate) fn create(name: &'a str, wealth_in_gp: f32) -> Self {
|
||||||
|
let (cp, sp, gp, pp) = Wealth::from_gp(wealth_in_gp).as_tuple();
|
||||||
|
Self {
|
||||||
|
name,
|
||||||
|
cp,
|
||||||
|
sp,
|
||||||
|
gp,
|
||||||
|
pp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_unpack_gold_values() {
|
||||||
|
use super::unpack_gold_value;
|
||||||
|
let test_values = [
|
||||||
|
(1.0, (0, 0, 1, 0)),
|
||||||
|
(1.23, (3, 2, 1, 0)),
|
||||||
|
(1.03, (3, 0, 1, 0)),
|
||||||
|
(100.23, (3, 2, 0, 1)),
|
||||||
|
(-100.23, (-3, -2, -0, -1)),
|
||||||
|
(10189.23, (3, 2, 89, 101)),
|
||||||
|
(-8090.20, (0, -2, -90, -80)),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (tested, expected) in test_values.into_iter() {
|
||||||
|
assert_eq!(unpack_gold_value(*tested), *expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
43
lootalot_db/src/schema.rs
Normal file
43
lootalot_db/src/schema.rs
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
table! {
|
||||||
|
claims (id) {
|
||||||
|
id -> Integer,
|
||||||
|
player_id -> Integer,
|
||||||
|
loot_id -> Integer,
|
||||||
|
resolve -> Integer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
items (id) {
|
||||||
|
id -> Integer,
|
||||||
|
name -> Text,
|
||||||
|
base_price -> Integer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
looted (id) {
|
||||||
|
id -> Integer,
|
||||||
|
name -> Text,
|
||||||
|
base_price -> Integer,
|
||||||
|
owner_id -> Integer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
players (id) {
|
||||||
|
id -> Integer,
|
||||||
|
name -> Text,
|
||||||
|
debt -> Integer,
|
||||||
|
cp -> Integer,
|
||||||
|
sp -> Integer,
|
||||||
|
gp -> Integer,
|
||||||
|
pp -> Integer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
joinable!(claims -> looted (loot_id));
|
||||||
|
joinable!(claims -> players (player_id));
|
||||||
|
joinable!(looted -> players (owner_id));
|
||||||
|
|
||||||
|
allow_tables_to_appear_in_same_query!(claims, items, looted, players,);
|
||||||
295
lootalot_db/src/transactions.rs
Normal file
295
lootalot_db/src/transactions.rs
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
//! TODO:
|
||||||
|
//! Extract actions provided by API into their dedicated module.
|
||||||
|
//! Will allow more flexibilty to combinate them inside API methods.
|
||||||
|
//! Should make it easier to add a new feature : Reverting an action
|
||||||
|
//!
|
||||||
|
use crate::models;
|
||||||
|
use crate::schema;
|
||||||
|
use crate::DbConnection;
|
||||||
|
use diesel::prelude::*;
|
||||||
|
// TODO: revertable actions :
|
||||||
|
// - Buy
|
||||||
|
// - Sell
|
||||||
|
// - UpdateWealth
|
||||||
|
pub type TransactionResult<T> = Result<T, diesel::result::Error>;
|
||||||
|
|
||||||
|
|
||||||
|
pub trait DbTransaction {
|
||||||
|
type Params;
|
||||||
|
type Response: serde::Serialize;
|
||||||
|
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Revertable : DbTransaction {
|
||||||
|
fn revert<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
player_id: i32,
|
||||||
|
params: <Self as DbTransaction>::Response,
|
||||||
|
) -> TransactionResult<<Self as DbTransaction>::Response>;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return status of an Action
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
pub struct ActionStatus<R: serde::Serialize> {
|
||||||
|
/// Has the action made changes ?
|
||||||
|
pub executed: bool,
|
||||||
|
/// Response payload
|
||||||
|
pub response: R,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActionStatus<()> {
|
||||||
|
pub fn was_updated(updated_lines: usize) -> Self {
|
||||||
|
match updated_lines {
|
||||||
|
1 => Self::ok(),
|
||||||
|
_ => Self::nop(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn ok() -> ActionStatus<()> {
|
||||||
|
Self {
|
||||||
|
executed: true,
|
||||||
|
response: (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Default + serde::Serialize> ActionStatus<T> {
|
||||||
|
pub fn nop() -> ActionStatus<T> {
|
||||||
|
Self {
|
||||||
|
executed: false,
|
||||||
|
response: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Or a module ?
|
||||||
|
pub(crate) mod player {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
pub struct AddLootParams {
|
||||||
|
pub player_id: i32,
|
||||||
|
pub loot_name: String,
|
||||||
|
pub loot_price: i32,
|
||||||
|
}
|
||||||
|
pub struct Buy;
|
||||||
|
|
||||||
|
enum LootTransactionKind {
|
||||||
|
Buy,
|
||||||
|
Sell,
|
||||||
|
}
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
pub struct LootTransaction {
|
||||||
|
player_id: i32,
|
||||||
|
loot_id: i32,
|
||||||
|
kind: LootTransactionKind,
|
||||||
|
pub loot_cost: (i32, i32, i32, i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DbTransaction for Buy {
|
||||||
|
type Params = AddLootParams;
|
||||||
|
type Response = LootTransaction;
|
||||||
|
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
let added_item = {
|
||||||
|
let new_item = models::item::NewLoot::to_player(
|
||||||
|
params.player_id,
|
||||||
|
(¶ms.loot_name, params.loot_price),
|
||||||
|
);
|
||||||
|
diesel::insert_into(schema::looted::table)
|
||||||
|
.values(&new_item)
|
||||||
|
.execute(conn)?
|
||||||
|
// TODO: return ID of inserted item
|
||||||
|
};
|
||||||
|
let updated_wealth = UpdateWealth.execute(
|
||||||
|
conn,
|
||||||
|
WealthParams {
|
||||||
|
player_id: params.player_id,
|
||||||
|
value_in_gp: -(params.loot_price as f32),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match (added_item, updated_wealth) {
|
||||||
|
(1, Ok(loot_cost)) => Ok(LootTransaction {
|
||||||
|
kind: LootTransactionKind::Buy,
|
||||||
|
player_id: params.player_id,
|
||||||
|
loot_id: 0, //TODO: find added item ID
|
||||||
|
loot_cost,
|
||||||
|
}),
|
||||||
|
// TODO: Handle other cases
|
||||||
|
_ => panic!()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Revertable for Buy {
|
||||||
|
fn revert<'q>(self, conn: &'q DbConnection, player_id: i32, params: <Self as DbTransaction>::Response)
|
||||||
|
-> TransactionResult<<Self as DbTransaction>::Response> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct LootParams {
|
||||||
|
pub player_id: i32,
|
||||||
|
pub loot_id: i32,
|
||||||
|
}
|
||||||
|
pub struct Sell;
|
||||||
|
impl DbTransaction for Sell {
|
||||||
|
type Params = LootParams;
|
||||||
|
type Response = LootTransaction;
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
use schema::looted::dsl::*;
|
||||||
|
let loot_value = looted
|
||||||
|
.find(params.loot_id)
|
||||||
|
.select(base_price)
|
||||||
|
.first::<i32>(conn)?;
|
||||||
|
let sell_value = (loot_value / 2) as f32;
|
||||||
|
diesel::delete(looted.find(params.loot_id))
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|r| match r {
|
||||||
|
// On deletion, update this player wealth
|
||||||
|
1 => Ok(UpdateWealth
|
||||||
|
.execute(
|
||||||
|
conn,
|
||||||
|
WealthParams {
|
||||||
|
player_id: params.player_id,
|
||||||
|
value_in_gp: sell_value as f32,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap()),
|
||||||
|
_ => Ok(ActionStatus {
|
||||||
|
executed: false,
|
||||||
|
response: None,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PutClaim;
|
||||||
|
impl DbTransaction for PutClaim {
|
||||||
|
type Params = LootParams;
|
||||||
|
type Response = ();
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
let claim = models::claim::NewClaim::new(params.player_id, params.loot_id);
|
||||||
|
diesel::insert_into(schema::claims::table)
|
||||||
|
.values(&claim)
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|_| Ok(()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WithdrawClaim;
|
||||||
|
impl DbTransaction for WithdrawClaim {
|
||||||
|
type Params = LootParams;
|
||||||
|
type Response = ();
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &DbConnection,
|
||||||
|
params: Self::Params,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
use schema::claims::dsl::*;
|
||||||
|
diesel::delete(
|
||||||
|
claims
|
||||||
|
.filter(loot_id.eq(params.loot_id))
|
||||||
|
.filter(player_id.eq(params.player_id)),
|
||||||
|
)
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|_| Ok(()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WealthParams {
|
||||||
|
pub player_id: i32,
|
||||||
|
pub value_in_gp: f32,
|
||||||
|
}
|
||||||
|
pub struct UpdateWealth;
|
||||||
|
|
||||||
|
impl DbTransaction for UpdateWealth {
|
||||||
|
type Params = WealthParams;
|
||||||
|
type Response = (i32, i32, i32, i32);
|
||||||
|
|
||||||
|
fn execute<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
params: WealthParams,
|
||||||
|
) -> TransactionResult<Self::Response> {
|
||||||
|
use schema::players::dsl::*;
|
||||||
|
let current_wealth = players
|
||||||
|
.find(params.player_id)
|
||||||
|
.select((cp, sp, gp, pp))
|
||||||
|
.first::<models::Wealth>(conn)?;
|
||||||
|
// TODO: improve thisdiesel dependant transaction
|
||||||
|
// should be move inside a WealthUpdate method
|
||||||
|
let updated_wealth =
|
||||||
|
models::Wealth::from_gp(current_wealth.to_gp() + params.value_in_gp);
|
||||||
|
// Difference in coins that is sent back
|
||||||
|
let (old, new) = (current_wealth.as_tuple(), updated_wealth.as_tuple());
|
||||||
|
let diff = (new.0 - old.0, new.1 - old.1, new.2 - old.2, new.3 - old.3);
|
||||||
|
diesel::update(players)
|
||||||
|
.filter(id.eq(params.player_id))
|
||||||
|
.set(&updated_wealth)
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|r| match r {
|
||||||
|
1 => Ok(diff),
|
||||||
|
_ => panic!("UpdateWealth made no changes !"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Revertable for UpdateWealth {
|
||||||
|
fn revert<'q>(
|
||||||
|
self,
|
||||||
|
conn: &'q DbConnection,
|
||||||
|
player_id: i32,
|
||||||
|
params: <Self as DbTransaction>::Response,
|
||||||
|
) -> TransactionResult<<Self as DbTransaction>::Response> {
|
||||||
|
use schema::players::dsl::*;
|
||||||
|
let cur_wealth = players
|
||||||
|
.find(player_id)
|
||||||
|
.select((cp, sp, gp, pp))
|
||||||
|
.first::<models::Wealth>(conn)?;
|
||||||
|
let reverted_wealth = models::player::Wealth {
|
||||||
|
cp: cur_wealth.cp - params.0,
|
||||||
|
sp: cur_wealth.cp - params.1,
|
||||||
|
gp: cur_wealth.cp - params.2,
|
||||||
|
pp: cur_wealth.cp - params.3,
|
||||||
|
};
|
||||||
|
// Difference in coins that is sent back
|
||||||
|
let diff = ( -params.0, -params.1, -params.2, -params.3);
|
||||||
|
diesel::update(players)
|
||||||
|
.filter(id.eq(params.0))
|
||||||
|
.set(&reverted_wealth)
|
||||||
|
.execute(conn)
|
||||||
|
.and_then(|r| match r {
|
||||||
|
1 => Ok(diff),
|
||||||
|
_ => panic!("RevertableWealthUpdate made no changes"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub(crate) mod admin {
|
||||||
|
pub struct AddPlayer;
|
||||||
|
pub struct AddLoot;
|
||||||
|
pub struct SellLoot;
|
||||||
|
pub struct ResolveClaims;
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
21
lootalot_front/.gitignore
vendored
Normal file
21
lootalot_front/.gitignore
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
.DS_Store
|
||||||
|
node_modules
|
||||||
|
/dist
|
||||||
|
|
||||||
|
# local env files
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# Log files
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
29
lootalot_front/README.md
Normal file
29
lootalot_front/README.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# lootalot_front
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
```
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compiles and hot-reloads for development
|
||||||
|
```
|
||||||
|
npm run serve
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compiles and minifies for production
|
||||||
|
```
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Run your tests
|
||||||
|
```
|
||||||
|
npm run test
|
||||||
|
```
|
||||||
|
|
||||||
|
### Lints and fixes files
|
||||||
|
```
|
||||||
|
npm run lint
|
||||||
|
```
|
||||||
|
|
||||||
|
### Customize configuration
|
||||||
|
See [Configuration Reference](https://cli.vuejs.org/config/).
|
||||||
11
lootalot_front/babel.config.js
Normal file
11
lootalot_front/babel.config.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
module.exports = {
|
||||||
|
presets: [
|
||||||
|
'@vue/app'
|
||||||
|
],
|
||||||
|
"presets": [["env", { "modules": false }]],
|
||||||
|
"env": {
|
||||||
|
"test": {
|
||||||
|
"presets": [["env", { "targets": { "node": "current" } }]]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
15047
lootalot_front/package-lock.json
generated
Normal file
15047
lootalot_front/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
68
lootalot_front/package.json
Normal file
68
lootalot_front/package.json
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
{
|
||||||
|
"name": "lootalot_front",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"css-build": "node-sass --omit-source-map-url sass/scroll.scss public/css/scroll.css",
|
||||||
|
"css-watch": "npm run css-build -- --watch",
|
||||||
|
"serve": "vue-cli-service serve",
|
||||||
|
"build": "vue-cli-service build",
|
||||||
|
"lint": "vue-cli-service lint",
|
||||||
|
"test": "jest"
|
||||||
|
},
|
||||||
|
"main": "sass/scroll.scss",
|
||||||
|
"dependencies": {
|
||||||
|
"bulma": "^0.7.5",
|
||||||
|
"core-js": "^2.6.5",
|
||||||
|
"vue": "^2.6.10"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vue/cli-plugin-babel": "^3.8.0",
|
||||||
|
"@vue/cli-plugin-eslint": "^3.8.0",
|
||||||
|
"@vue/cli-service": "^3.8.0",
|
||||||
|
"@vue/test-utils": "^1.0.0-beta.29",
|
||||||
|
"babel-eslint": "^10.0.1",
|
||||||
|
"babel-jest": "^24.8.0",
|
||||||
|
"babel-preset-env": "^1.7.0",
|
||||||
|
"eslint": "^5.16.0",
|
||||||
|
"eslint-plugin-vue": "^5.0.0",
|
||||||
|
"jest": "^24.8.0",
|
||||||
|
"node-sass": "^4.12.0",
|
||||||
|
"vue-jest": "^3.0.4",
|
||||||
|
"vue-template-compiler": "^2.6.10"
|
||||||
|
},
|
||||||
|
"eslintConfig": {
|
||||||
|
"root": true,
|
||||||
|
"env": {
|
||||||
|
"node": true
|
||||||
|
},
|
||||||
|
"extends": [
|
||||||
|
"plugin:vue/essential",
|
||||||
|
"eslint:recommended"
|
||||||
|
],
|
||||||
|
"rules": {},
|
||||||
|
"parserOptions": {
|
||||||
|
"parser": "babel-eslint"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"postcss": {
|
||||||
|
"plugins": {
|
||||||
|
"autoprefixer": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"browserslist": [
|
||||||
|
"> 1%",
|
||||||
|
"last 2 versions"
|
||||||
|
],
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"vue"
|
||||||
|
],
|
||||||
|
"transform": {
|
||||||
|
".*\\.(vue)$": "vue-jest",
|
||||||
|
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6957
lootalot_front/public/css/scroll.css
Normal file
6957
lootalot_front/public/css/scroll.css
Normal file
File diff suppressed because it is too large
Load Diff
BIN
lootalot_front/public/favicon.ico
Normal file
BIN
lootalot_front/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
20
lootalot_front/public/index.html
Normal file
20
lootalot_front/public/index.html
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<!DOCTYPE HTML>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||||
|
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
||||||
|
<link rel="stylesheet" href="<%= BASE_URL %>css/scroll.css">
|
||||||
|
<title>Loot-a-Lot !</title>
|
||||||
|
<script defer src="fontawesome/js/all.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<!-- built files will be auto injected -->
|
||||||
|
<noscript>
|
||||||
|
<strong>We're sorry but lootalot_front doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
|
||||||
|
</noscript>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
21
lootalot_front/sass/scroll.scss
Normal file
21
lootalot_front/sass/scroll.scss
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
@charset "utf-8";
|
||||||
|
|
||||||
|
$brown: #757763;
|
||||||
|
$beige: #C9AD6A;
|
||||||
|
$beige-light: #E0E5C1;
|
||||||
|
$beige-lighter: #EEE5CE;
|
||||||
|
$red: #B7321B;
|
||||||
|
$dark-red: #58180D;
|
||||||
|
$yellow-light: #FCF2C5;
|
||||||
|
|
||||||
|
$link: $brown;
|
||||||
|
$primary: $brown;
|
||||||
|
$info: $beige;
|
||||||
|
$danger: $red;
|
||||||
|
|
||||||
|
$table-cell-border: 1px solid $dark-red;
|
||||||
|
$table-striped-row-even-background-color: $yellow-light;
|
||||||
|
|
||||||
|
$button-padding-horizontal: 1em;
|
||||||
|
|
||||||
|
@import "../node_modules/bulma/bulma.sass";
|
||||||
66
lootalot_front/src/App.vue
Normal file
66
lootalot_front/src/App.vue
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
<template>
|
||||||
|
<main id="app" class="section">
|
||||||
|
<section id="content" class="columns is-desktop">
|
||||||
|
<Player></Player>
|
||||||
|
<div class="column">
|
||||||
|
<Chest :player="0" v-if="state.initiated"></Chest>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import Player from './components/Player.vue'
|
||||||
|
import Chest from './components/Chest.vue'
|
||||||
|
import { AppStorage } from './AppStorage'
|
||||||
|
|
||||||
|
function getCookie(cname) {
|
||||||
|
var name = cname + "=";
|
||||||
|
var decodedCookie = decodeURIComponent(document.cookie);
|
||||||
|
var ca = decodedCookie.split(';');
|
||||||
|
for(var i = 0; i <ca.length; i++) {
|
||||||
|
var c = ca[i];
|
||||||
|
while (c.charAt(0) == ' ') {
|
||||||
|
c = c.substring(1);
|
||||||
|
}
|
||||||
|
if (c.indexOf(name) == 0) {
|
||||||
|
return c.substring(name.length, c.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: 'app',
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
state: AppStorage.state,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
components: {
|
||||||
|
Player,
|
||||||
|
Chest
|
||||||
|
},
|
||||||
|
created () {
|
||||||
|
// Initiate with active player set to value found in cookie
|
||||||
|
// or as group by default.
|
||||||
|
const cookie = getCookie("player_id");
|
||||||
|
let playerId;
|
||||||
|
if (cookie == "") {
|
||||||
|
playerId = 0;
|
||||||
|
} else {
|
||||||
|
playerId = Number(cookie);
|
||||||
|
}
|
||||||
|
AppStorage.initStorage(playerId);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
#app {
|
||||||
|
font-family: 'Montserrat', Helvetica, Arial, sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
163
lootalot_front/src/AppStorage.js
Normal file
163
lootalot_front/src/AppStorage.js
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
import Vue from 'vue'
|
||||||
|
|
||||||
|
const API_BASEURL = "http://localhost:8088/api/"
|
||||||
|
const API_ENDPOINT = function (tailString) {
|
||||||
|
return API_BASEURL + tailString;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Api = {
|
||||||
|
fetchPlayerList () {
|
||||||
|
return fetch(API_ENDPOINT("players"))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error ", e));
|
||||||
|
},
|
||||||
|
fetchClaims () {
|
||||||
|
return fetch(API_ENDPOINT("claims"))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error ", e));
|
||||||
|
},
|
||||||
|
fetchLoot (playerId) {
|
||||||
|
return fetch(API_ENDPOINT(playerId + "/loot"))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error", e));
|
||||||
|
},
|
||||||
|
putClaim (playerId, itemId) {
|
||||||
|
return fetch(API_ENDPOINT(playerId + "/claim/" + itemId))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error", e));
|
||||||
|
},
|
||||||
|
unClaim (playerId, itemId) {
|
||||||
|
return fetch(API_ENDPOINT(playerId + "/unclaim/" + itemId))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error", e));
|
||||||
|
},
|
||||||
|
updateWealth (playerId, goldValue) {
|
||||||
|
return fetch(API_ENDPOINT(playerId + "/update-wealth/" + goldValue))
|
||||||
|
.then(r => r.json())
|
||||||
|
.catch(e => console.error("Fetch error", e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
export const AppStorage = {
|
||||||
|
debug: true,
|
||||||
|
state: {
|
||||||
|
player_id: 0,
|
||||||
|
player_list: {},
|
||||||
|
player_loot: {},
|
||||||
|
player_claims: {},
|
||||||
|
initiated: false,
|
||||||
|
show_player_chest: false,
|
||||||
|
},
|
||||||
|
// Initiate the state
|
||||||
|
initStorage (playerId) {
|
||||||
|
if (this.debug) console.log('Initiates with player : ', playerId)
|
||||||
|
this.state.player_id = playerId;
|
||||||
|
// Fetch initial data
|
||||||
|
return Promise
|
||||||
|
.all([ Api.fetchPlayerList(), Api.fetchClaims(), ])
|
||||||
|
.then(data => {
|
||||||
|
const [players, claims] = data;
|
||||||
|
this.__initPlayerList(players);
|
||||||
|
this.__initClaimsStore(claims);
|
||||||
|
});
|
||||||
|
// TODO: when __initPlayerList won't use promises
|
||||||
|
//.then(_ => this.state.initiated = true);
|
||||||
|
},
|
||||||
|
__initClaimsStore(data) {
|
||||||
|
for (var idx in data) {
|
||||||
|
var claimDesc = data[idx];
|
||||||
|
this.state.player_claims[claimDesc.player_id].push(claimDesc.loot_id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
__initPlayerList(data) {
|
||||||
|
for (var idx in data) {
|
||||||
|
var playerDesc = data[idx];
|
||||||
|
const playerId = Number(playerDesc.id);
|
||||||
|
if (this.debug) console.log("Creates", playerId, playerDesc.name)
|
||||||
|
// Initiate data for a single Player.
|
||||||
|
Vue.set(this.state.player_list, playerId, playerDesc);
|
||||||
|
Vue.set(this.state.player_loot, playerId, []);
|
||||||
|
Vue.set(this.state.player_claims, playerId, []);
|
||||||
|
}
|
||||||
|
// Hack for now !!
|
||||||
|
// Fetch all players loot and wait to set initiated to true
|
||||||
|
var promises = [];
|
||||||
|
for (var idx in data) {
|
||||||
|
const playerId = data[idx].id;
|
||||||
|
var promise = Api.fetchLoot(playerId)
|
||||||
|
.then(data => data.forEach(
|
||||||
|
item => {
|
||||||
|
if (this.debug) console.log("add looted item", item, playerId)
|
||||||
|
this.state.player_loot[playerId].push(item)
|
||||||
|
}
|
||||||
|
));
|
||||||
|
promises.push(promise);
|
||||||
|
}
|
||||||
|
Promise.all(promises).then(_ => this.state.initiated = true);
|
||||||
|
},
|
||||||
|
// User actions
|
||||||
|
// Sets a new active player by id
|
||||||
|
setActivePlayer (newPlayerId) {
|
||||||
|
if (this.debug) console.log('setActivePlayer to ', newPlayerId)
|
||||||
|
this.state.player_id = newPlayerId
|
||||||
|
document.cookie = `player_id=${newPlayerId};`;
|
||||||
|
},
|
||||||
|
// Show/Hide player's chest
|
||||||
|
switchPlayerChestVisibility () {
|
||||||
|
if (this.debug) console.log('switchPlayerChestVisibility', !this.state.show_player_chest)
|
||||||
|
this.state.show_player_chest = !this.state.show_player_chest
|
||||||
|
},
|
||||||
|
// TODO
|
||||||
|
// get the content of a player Chest, retrieve form cache or fetched
|
||||||
|
// will replace hack that loads *all* chest...
|
||||||
|
getPlayerLoot (playerId) {
|
||||||
|
|
||||||
|
},
|
||||||
|
updatePlayerWealth (goldValue) {
|
||||||
|
return Api.updateWealth(this.state.player_id, goldValue)
|
||||||
|
.then(done => {
|
||||||
|
if (done.executed) {
|
||||||
|
// Update player wealth
|
||||||
|
var diff = done.response;
|
||||||
|
if (this.debug) console.log('updatePlayerWealth', diff)
|
||||||
|
this.state.player_list[this.state.player_id].cp += diff[0];
|
||||||
|
this.state.player_list[this.state.player_id].sp += diff[1];
|
||||||
|
this.state.player_list[this.state.player_id].gp += diff[2];
|
||||||
|
this.state.player_list[this.state.player_id].pp += diff[3];
|
||||||
|
}
|
||||||
|
return done.executed;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// Put a claim on an item from group chest.
|
||||||
|
putRequest (itemId) {
|
||||||
|
const playerId = this.state.player_id
|
||||||
|
Api.putClaim(playerId, itemId)
|
||||||
|
.then(done => {
|
||||||
|
if (done.executed) {
|
||||||
|
// Update cliend-side state
|
||||||
|
this.state.player_claims[playerId].push(itemId);
|
||||||
|
} else {
|
||||||
|
if (this.debug) console.log("API responded with 'false'")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// Withdraws a claim.
|
||||||
|
cancelRequest(itemId) {
|
||||||
|
const playerId = this.state.player_id
|
||||||
|
Api.unClaim(playerId, itemId)
|
||||||
|
.then(done => {
|
||||||
|
if (done.executed) {
|
||||||
|
var idx = this.state.player_claims[playerId].indexOf(itemId);
|
||||||
|
if (idx > -1) {
|
||||||
|
this.state.player_claims[playerId].splice(idx, 1);
|
||||||
|
} else {
|
||||||
|
if (this.debug) console.log("cancel a non-existent request")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (this.debug) console.log("API responded with 'false'")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
BIN
lootalot_front/src/assets/logo.png
Normal file
BIN
lootalot_front/src/assets/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.7 KiB |
168
lootalot_front/src/components/Chest.vue
Normal file
168
lootalot_front/src/components/Chest.vue
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
<template>
|
||||||
|
<div class="container is-paddingless">
|
||||||
|
<div v-if="mainControlsDisplayed"
|
||||||
|
class="columns is-mobile is-vcentered"
|
||||||
|
>
|
||||||
|
<div class="column is-narrow">
|
||||||
|
<span class="icon is-large">
|
||||||
|
<i class="fas fa-2x fa-dragon"></i>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="column has-text-left">
|
||||||
|
<h1 class="title">Coffre de groupe</h1>
|
||||||
|
</div>
|
||||||
|
<div class="column" v-show="canAdd">
|
||||||
|
<div v-show="mainControlsDisplayed" class="buttons is-right">
|
||||||
|
<button v-if="canAdd"
|
||||||
|
class="button is-inverted is-info"
|
||||||
|
@click="is_adding = true"
|
||||||
|
>
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fas fa-box-open"></i>
|
||||||
|
</span>
|
||||||
|
<p>Nouveau loot</p>
|
||||||
|
</button>
|
||||||
|
<button class="button is-inverted is-primary">
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fas fa-coins"></i>
|
||||||
|
</span>
|
||||||
|
<p>Tout vendre</p>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Loot v-if="is_adding" @done="is_adding = false"></Loot>
|
||||||
|
<table v-else class="table is-fullwidth is-striped" >
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Objets de {{ player }}</th>
|
||||||
|
<th v-if="canGrab"></th>
|
||||||
|
<th v-if="canSell">
|
||||||
|
<div class="buttons is-right">
|
||||||
|
<button class="button"
|
||||||
|
:class="is_selling ? 'is-danger' : 'is-warning'"
|
||||||
|
@click="is_selling = !is_selling"
|
||||||
|
>
|
||||||
|
<span class="icon">
|
||||||
|
<i class="fas fa-coins"></i>
|
||||||
|
</span>
|
||||||
|
<p v-if="!is_selling">
|
||||||
|
Vendre</p>
|
||||||
|
<p v-else>
|
||||||
|
{{ totalSellValue ? totalSellValue : 'Annuler' }}</p>
|
||||||
|
</button>
|
||||||
|
<PercentInput v-show="is_selling">
|
||||||
|
</PercentInput>
|
||||||
|
</div>
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<template v-for="(item, idx) in content">
|
||||||
|
<tr :key="`row-${idx}`">
|
||||||
|
<td>{{item.name}}</td>
|
||||||
|
<td v-if="canGrab">
|
||||||
|
<Request :item="item.id"></Request>
|
||||||
|
</td>
|
||||||
|
<td v-if="canSell">
|
||||||
|
<div class="field is-grouped is-pulled-right" v-show="is_selling">
|
||||||
|
<div class="control">
|
||||||
|
<label class="label">
|
||||||
|
<input type="checkbox"
|
||||||
|
id="`item-${idx}`"
|
||||||
|
:value="item.id"
|
||||||
|
v-model="sell_selected">
|
||||||
|
{{item.base_price / 2}} GP
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<PercentInput></PercentInput>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</template>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import { AppStorage } from '../AppStorage'
|
||||||
|
import Request from './Request.vue'
|
||||||
|
import PercentInput from './PercentInput.vue'
|
||||||
|
import Loot from './Loot.vue'
|
||||||
|
/*
|
||||||
|
The chest displays the collection of items owned by a player
|
||||||
|
|
||||||
|
TO TEST :
|
||||||
|
- Possible interactions depends on player_id and current chest
|
||||||
|
- Objects are displayed as a table
|
||||||
|
|
||||||
|
Sell workflow :
|
||||||
|
1. Click sell (sell becomes danger)
|
||||||
|
2. Check objects to sell (sell button displays total value)
|
||||||
|
3. Click sell to confirm
|
||||||
|
*/
|
||||||
|
export default {
|
||||||
|
props: {
|
||||||
|
player: {
|
||||||
|
type: Number,
|
||||||
|
required: true,
|
||||||
|
default: 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
components: {
|
||||||
|
Request,
|
||||||
|
PercentInput,
|
||||||
|
Loot,
|
||||||
|
},
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
app_state: AppStorage.state,
|
||||||
|
is_selling: false,
|
||||||
|
is_adding: false,
|
||||||
|
sell_selected: [],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
fetchLoot () {
|
||||||
|
|
||||||
|
}
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
content () {
|
||||||
|
const playerId = this.player;
|
||||||
|
console.log("Refresh chest of", playerId);
|
||||||
|
return this.app_state.player_loot[playerId];
|
||||||
|
},
|
||||||
|
// Can the active user sell items from this chest ?
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.table td, .table th { vertical-align: middle; }
|
||||||
|
</style>
|
||||||
93
lootalot_front/src/components/ItemInput.vue
Normal file
93
lootalot_front/src/components/ItemInput.vue
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
<template>
|
||||||
|
<div class="container is-paddingless">
|
||||||
|
<div class="field has-addons">
|
||||||
|
<div class="control is-expanded"
|
||||||
|
:class="{'is-loading': is_loading }">
|
||||||
|
<input type="text"
|
||||||
|
v-model="search"
|
||||||
|
@input="autoCompletion"
|
||||||
|
class="input"
|
||||||
|
:class="{'is-danger': no_results,
|
||||||
|
'is-warning': auto_open}"
|
||||||
|
autocomplete="on">
|
||||||
|
</input>
|
||||||
|
</div>
|
||||||
|
<div class="control">
|
||||||
|
<button class="button is-primary"
|
||||||
|
:disabled="no_results"
|
||||||
|
@click="addItem"
|
||||||
|
>+</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="dropdown" :class="{'is-active': auto_open}">
|
||||||
|
<div class="dropdown-menu">
|
||||||
|
<div class="dropdown-content">
|
||||||
|
<a v-for="(result,i) in results" :key="i"
|
||||||
|
@click="setResult(result.name)"
|
||||||
|
class="dropdown-item"
|
||||||
|
>
|
||||||
|
{{ result.name }}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<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 {
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
is_loading: false,
|
||||||
|
no_results: false,
|
||||||
|
search: '',
|
||||||
|
results: [],
|
||||||
|
auto_open: false,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
autoCompletion (ev) {
|
||||||
|
// TODO: a lot happens here that
|
||||||
|
// need to be clarified
|
||||||
|
if (this.search == '') {
|
||||||
|
this.auto_open = false;
|
||||||
|
this.results = [];
|
||||||
|
this.no_results = false;
|
||||||
|
} else {
|
||||||
|
this.results = MOCK_ITEMS.filter(item => {
|
||||||
|
return item.name.includes(this.search);
|
||||||
|
});
|
||||||
|
// Update status
|
||||||
|
if (this.results.length == 0) {
|
||||||
|
this.no_results = true;
|
||||||
|
} else {
|
||||||
|
this.no_results = false;
|
||||||
|
this.auto_open = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
setResult(result) {
|
||||||
|
this.search = result;
|
||||||
|
this.auto_open = false;
|
||||||
|
},
|
||||||
|
addItem () {
|
||||||
|
this.$emit("addItem", this.search);
|
||||||
|
this.search = '';
|
||||||
|
this.results = [];
|
||||||
|
this.no_results = false;
|
||||||
|
this.auto_open = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.dropdown, .dropdown-menu { min-width: 100%; margin-top: 0; padding-top: 0;}
|
||||||
|
.dropdown { top: -0.75rem; }
|
||||||
|
</style>
|
||||||
42
lootalot_front/src/components/Loot.vue
Normal file
42
lootalot_front/src/components/Loot.vue
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
<template>
|
||||||
|
<div class="card is-shadowless">
|
||||||
|
<div class="card-header">
|
||||||
|
<p class="card-header-title">
|
||||||
|
Nouveau loot - {{ looted.length }} objet(s)</p>
|
||||||
|
</div>
|
||||||
|
<div class="card-content">
|
||||||
|
<ItemInput @addItem="onAddItem"></ItemInput>
|
||||||
|
<p v-for="(item, idx) in looted" :key="idx"
|
||||||
|
class="has-text-left is-size-5">
|
||||||
|
{{ item }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="card-footer">
|
||||||
|
<div class="card-footer-item buttons is-center">
|
||||||
|
<a class="button is-primary">Confirmer</a>
|
||||||
|
<a @click="onClose" class="button is-danger">Annuler</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import ItemInput from './ItemInput.vue'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
components: { ItemInput },
|
||||||
|
data () { return {
|
||||||
|
looted: [],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
onAddItem (item) {
|
||||||
|
this.looted.push(item);
|
||||||
|
},
|
||||||
|
onClose () {
|
||||||
|
this.$emit('done');
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
</script>
|
||||||
27
lootalot_front/src/components/NumberInput.vue
Normal file
27
lootalot_front/src/components/NumberInput.vue
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<template>
|
||||||
|
<input type="text"
|
||||||
|
class="input"
|
||||||
|
:class="{'is-danger': has_error}"
|
||||||
|
:value="value"
|
||||||
|
@input="checkError"
|
||||||
|
></input>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
props: ["value"],
|
||||||
|
data () {
|
||||||
|
return { has_error: false};
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
checkError (ev) {
|
||||||
|
const newValue = ev.target.value;
|
||||||
|
this.has_error = isNaN(newValue);
|
||||||
|
this.$emit(
|
||||||
|
'input',
|
||||||
|
this.has_error ? 0 : Number(newValue)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
28
lootalot_front/src/components/PercentInput.vue
Normal file
28
lootalot_front/src/components/PercentInput.vue
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<template>
|
||||||
|
<div class="field has-addons">
|
||||||
|
<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>
|
||||||
|
<span class="icon is-small is-left">
|
||||||
|
<i class="fas fa-percent"></i>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="control">
|
||||||
|
<button class="button is-small is-outlined"
|
||||||
|
@click="is_opened = !is_opened"
|
||||||
|
>
|
||||||
|
<small v-if="!is_opened">Mod.</small>
|
||||||
|
<span v-else class="icon"><i class="fas fa-times-circle"></i></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
is_opened: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
165
lootalot_front/src/components/Player.vue
Normal file
165
lootalot_front/src/components/Player.vue
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
<template>
|
||||||
|
<div class="column is-one-third-desktop">
|
||||||
|
<div id="sidebar" class="card">
|
||||||
|
<header id="sidebar-heading" class="card-header">
|
||||||
|
<p class="card-header-title">
|
||||||
|
{{ app_state.initiated ? player.name : "..." }}</p>
|
||||||
|
<div class="dropdown is-right"
|
||||||
|
:class="{ 'is-active': show_dropdown }">
|
||||||
|
<div class="dropdown-trigger" ref="dropdown_btn">
|
||||||
|
<a id="change_player" class="card-header-icon"
|
||||||
|
@click="show_dropdown = !show_dropdown"
|
||||||
|
aria-haspopup="true" aria-controls="dropdown-menu">
|
||||||
|
<span class="icon is-small">
|
||||||
|
<i class="fas fa-exchange-alt"></i>
|
||||||
|
</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<div class="dropdown-menu" id="dropdown-menu" role="menu"
|
||||||
|
v-closable="{ exclude: ['dropdown_btn'], handler: 'closeDropdown', visible: show_dropdown }">
|
||||||
|
<div class="dropdown-content" v-if="app_state.initiated">
|
||||||
|
<a v-for="(p,i) in app_state.player_list" :key="i"
|
||||||
|
@click="setActivePlayer(i)"
|
||||||
|
href="#" class="dropdown-item">
|
||||||
|
{{ p.name }}</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div class="card-content">
|
||||||
|
<Wealth :wealth="wealth" :debt="player.debt"></Wealth>
|
||||||
|
<div class="box is-shadowless" v-show="!playerIsGroup">
|
||||||
|
<div class="columns is-vcentered" @click="switchPlayerChestVisibility">
|
||||||
|
<div class="column is-one-fifth">
|
||||||
|
<span class="icon is-large">
|
||||||
|
<i class="fas fa-2x fa-box"></i>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="column if-four-fifth has-text-left">
|
||||||
|
<p class="is-size-3">Coffre</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Chest :player="app_state.player_id"
|
||||||
|
v-show="app_state.show_player_chest">
|
||||||
|
</Chest>
|
||||||
|
<a href="#" class="button is-link is-fullwidth is-hidden" disabled>Historique</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import { AppStorage } from '../AppStorage'
|
||||||
|
import Chest from './Chest.vue'
|
||||||
|
import Wealth from './Wealth.vue'
|
||||||
|
/*
|
||||||
|
The Player control board.
|
||||||
|
To test :
|
||||||
|
- Player name is displayed
|
||||||
|
- Player's wealth is displayed -> Inside Wealth component
|
||||||
|
- Dropdown:
|
||||||
|
- The first item is the group
|
||||||
|
- Opened by activator
|
||||||
|
- Closed when clicked outside
|
||||||
|
- Click on item does switch active player
|
||||||
|
- Switch player :
|
||||||
|
- Name is updated when player_id is updated
|
||||||
|
- Wealth is updated -> Inside Wealth component
|
||||||
|
- Chest button controls Chest visibility
|
||||||
|
|
||||||
|
*/
|
||||||
|
let handleOutsideClick;
|
||||||
|
export default {
|
||||||
|
components: { Chest, Wealth },
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
app_state: AppStorage.state,
|
||||||
|
show_dropdown: false,
|
||||||
|
edit_wealth: false,
|
||||||
|
handleOutsideClick: null,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
player () {
|
||||||
|
if (!this.app_state.initiated) return {}
|
||||||
|
const idx = this.app_state.player_id;
|
||||||
|
return this.app_state.player_list[idx];
|
||||||
|
},
|
||||||
|
wealth () {
|
||||||
|
if (!this.app_state.initiated) {
|
||||||
|
return ["-", "-", "-", "-"];
|
||||||
|
} else {
|
||||||
|
const cp = this.player.cp
|
||||||
|
const sp = this.player.sp
|
||||||
|
const gp = this.player.gp
|
||||||
|
const pp = this.player.pp
|
||||||
|
return [cp, sp, gp, pp];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// Check if the active player is the special 'Group' player
|
||||||
|
playerIsGroup () {
|
||||||
|
return this.app_state.player_id == 0;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
switchPlayerChestVisibility () {
|
||||||
|
AppStorage.switchPlayerChestVisibility();
|
||||||
|
},
|
||||||
|
hidePlayerChest () {
|
||||||
|
if (this.app_state.show_player_chest) {
|
||||||
|
this.switchPlayerChestVisibility();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
setActivePlayer (playerIdx) {
|
||||||
|
var playerIdx = Number(playerIdx);
|
||||||
|
AppStorage.setActivePlayer(playerIdx);
|
||||||
|
if (playerIdx == 0) { this.hidePlayerChest() }
|
||||||
|
},
|
||||||
|
closeDropdown () {
|
||||||
|
this.show_dropdown = false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
directives: {
|
||||||
|
'closable': {
|
||||||
|
bind: function(el, binding, vnode) {
|
||||||
|
handleOutsideClick = (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
const { exclude, handler } = binding.value;
|
||||||
|
let excludedElClicked = false;
|
||||||
|
exclude.forEach(refName => {
|
||||||
|
if (!excludedElClicked) {
|
||||||
|
const elt = vnode.context.$refs[refName];
|
||||||
|
excludedElClicked = elt.contains(e.target);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!excludedElClicked) {
|
||||||
|
console.log('outsideCloseDropdown');
|
||||||
|
vnode.context[handler]()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
},
|
||||||
|
// Bind custom handler only when dropdown is visible
|
||||||
|
update: function(el, binding, vnode, _) {
|
||||||
|
const { visible } = binding.value;
|
||||||
|
if (visible) {
|
||||||
|
document.addEventListener('click', handleOutsideClick);
|
||||||
|
document.addEventListener('touchstart', handleOutsideClick);
|
||||||
|
} else {
|
||||||
|
document.removeEventListener('click', handleOutsideClick);
|
||||||
|
document.removeEventListener('touchstart', handleOutsideClick);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
unbind: function() { console.log("unbind");
|
||||||
|
document.removeEventListener('click', handleOutsideClick);
|
||||||
|
document.removeEventListener('touchstart', handleOutsideClick);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.fa-exchange-alt.disabled { opacity: 0.4; }
|
||||||
|
</style>
|
||||||
81
lootalot_front/src/components/Request.vue
Normal file
81
lootalot_front/src/components/Request.vue
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
<template>
|
||||||
|
<div class="buttons is-right" >
|
||||||
|
<template v-if="isInConflict">
|
||||||
|
<button class="button is-success"
|
||||||
|
@click="cancelRequest"
|
||||||
|
>
|
||||||
|
<span class="icon is-small">
|
||||||
|
<i class="fas fa-hand-peace"></i>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<button class="button is-danger"
|
||||||
|
@click="hardenRequest"
|
||||||
|
>
|
||||||
|
<span class="icon is-small">
|
||||||
|
<i class="fas fa-hand-middle-finger"></i>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
<button class="button is-primary"
|
||||||
|
@click="putRequest"
|
||||||
|
:class="{'is-outlined': isRequested}"
|
||||||
|
:disabled="isRequested"
|
||||||
|
>
|
||||||
|
<span class="icon is-small">
|
||||||
|
<i class="fas fa-praying-hands"></i>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import { AppStorage } from '../AppStorage'
|
||||||
|
export default {
|
||||||
|
props: ["item"],
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
state: AppStorage.state,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
// Check if item is requested by active player
|
||||||
|
isRequested () {
|
||||||
|
const reqs = this.state.player_claims[this.state.player_id];
|
||||||
|
return reqs.includes(this.item);
|
||||||
|
},
|
||||||
|
// Check if item is requested by multiple players including active one
|
||||||
|
isInConflict () {
|
||||||
|
const reqs = this.state.player_claims;
|
||||||
|
const playerId = this.state.player_id;
|
||||||
|
var reqByPlayer = false;
|
||||||
|
var reqByOther = false;
|
||||||
|
for (var key in reqs) {
|
||||||
|
const isReq = reqs[key].includes(this.item);
|
||||||
|
if (isReq) {
|
||||||
|
if (key == playerId) {
|
||||||
|
reqByPlayer = true;
|
||||||
|
} else {
|
||||||
|
reqByOther = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return reqByPlayer && reqByOther;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
// The active player claims the item
|
||||||
|
putRequest () {
|
||||||
|
AppStorage.putRequest(this.item)
|
||||||
|
},
|
||||||
|
// The active player withdraws his request
|
||||||
|
cancelRequest () {
|
||||||
|
AppStorage.cancelRequest(this.item)
|
||||||
|
},
|
||||||
|
// The active player insist on his claim
|
||||||
|
// TODO: Find a simple and fun system to express
|
||||||
|
// how much each player want an item
|
||||||
|
hardenRequest () {
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
92
lootalot_front/src/components/Wealth.vue
Normal file
92
lootalot_front/src/components/Wealth.vue
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
<template>
|
||||||
|
<div class="box is-shadowless">
|
||||||
|
<nav class="columns is-mobile is-multiline is-vcentered">
|
||||||
|
<div class="column">
|
||||||
|
<span class="icon is-large"
|
||||||
|
@click="edit = !edit">
|
||||||
|
<i class="fas fa-2x fa-piggy-bank"></i>
|
||||||
|
</span>
|
||||||
|
<p v-if="debt" class="has-text-danger">-{{ debt }}gp </p>
|
||||||
|
</div>
|
||||||
|
<div class="column has-text-info">
|
||||||
|
<p class="heading">PP</p>
|
||||||
|
<p class="is-size-4">{{ wealth[3] }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="column has-text-warning">
|
||||||
|
<p class="heading">PO</p>
|
||||||
|
<p class="is-size-4">{{ wealth[2] }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="column has-text-grey">
|
||||||
|
<p class="heading">PA</p>
|
||||||
|
<p class="is-size-4">{{ wealth[1] }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="column has-text-grey">
|
||||||
|
<p class="heading">PC</p>
|
||||||
|
<p class="is-size-4">{{ wealth[0] }}</p>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<div v-if="edit"> <!-- or v-show ? -->
|
||||||
|
<nav class="columns is-mobile">
|
||||||
|
<div class="column">
|
||||||
|
<NumberInput v-model="edit_value"></NumberInput>
|
||||||
|
</div>
|
||||||
|
<div class="column is-2">
|
||||||
|
<button class="button is-outlined is-fullwidth is-danger"
|
||||||
|
@click="updateWealth('minus')">
|
||||||
|
<span class="icon"><i class="fas fa-2x fa-minus"></i></span>
|
||||||
|
</button>
|
||||||
|
</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>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import { AppStorage } from '../AppStorage.js'
|
||||||
|
import NumberInput from './NumberInput.vue'
|
||||||
|
export default {
|
||||||
|
components: { NumberInput },
|
||||||
|
props: ["wealth", "debt"],
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
edit: false,
|
||||||
|
edit_value: 0,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
updateWealth (op) {
|
||||||
|
var goldValue;
|
||||||
|
switch (op) {
|
||||||
|
case 'plus':
|
||||||
|
goldValue = this.edit_value;
|
||||||
|
break;
|
||||||
|
case 'minus':
|
||||||
|
goldValue = -this.edit_value;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.log("Error, bad operator !", op);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
AppStorage.updatePlayerWealth(goldValue)
|
||||||
|
.then(done => {
|
||||||
|
if (done) {
|
||||||
|
this.$emit('updated');
|
||||||
|
this.resetValues();
|
||||||
|
} else {
|
||||||
|
console.log('correct errors');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
resetValues () {
|
||||||
|
this.edit = false;
|
||||||
|
this.edit_value = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
8
lootalot_front/src/main.js
Normal file
8
lootalot_front/src/main.js
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import Vue from 'vue'
|
||||||
|
import App from './App.vue'
|
||||||
|
|
||||||
|
Vue.config.productionTip = false
|
||||||
|
|
||||||
|
new Vue({
|
||||||
|
render: h => h(App),
|
||||||
|
}).$mount('#app')
|
||||||
16
src/main.rs
16
src/main.rs
@@ -1,3 +1,17 @@
|
|||||||
|
extern crate actix_web;
|
||||||
|
extern crate dotenv;
|
||||||
|
extern crate env_logger;
|
||||||
|
extern crate lootalot_db;
|
||||||
|
|
||||||
|
mod server;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("Hello, world!");
|
std::env::set_var("RUST_LOG", "actix_web=info");
|
||||||
|
env_logger::init();
|
||||||
|
dotenv::dotenv().ok();
|
||||||
|
// TODO: Build a cli app with complete support of DbApi
|
||||||
|
// Server is started with 'serve' subcommand
|
||||||
|
// $ lootalot serve
|
||||||
|
// Start the server.
|
||||||
|
server::serve().ok();
|
||||||
}
|
}
|
||||||
|
|||||||
125
src/server.rs
Normal file
125
src/server.rs
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
use actix_cors::Cors;
|
||||||
|
use actix_files as fs;
|
||||||
|
use actix_web::{web, App, Error, HttpResponse, HttpServer};
|
||||||
|
use futures::Future;
|
||||||
|
use lootalot_db::{DbApi, Pool, QueryResult};
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
type AppPool = web::Data<Pool>;
|
||||||
|
|
||||||
|
/// Wraps call to the DbApi and process its result as a async HttpResponse
|
||||||
|
///
|
||||||
|
/// Provides a convenient way to call the api inside a route definition. Given a connection pool,
|
||||||
|
/// access to the api is granted in a closure. The closure is called in a blocking way and should
|
||||||
|
/// return a QueryResult.
|
||||||
|
/// If the query succeeds, it's result is returned as JSON data. Otherwise, an InternalServerError
|
||||||
|
/// is returned.
|
||||||
|
///
|
||||||
|
/// # Usage
|
||||||
|
/// ```
|
||||||
|
/// (...)
|
||||||
|
/// .route("path/to/",
|
||||||
|
/// move |pool: web::Data<Pool>| {
|
||||||
|
/// // user data can be processed here
|
||||||
|
/// // ...
|
||||||
|
/// db_call(pool, move |api| {
|
||||||
|
/// // ...do what you want with the api
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// )
|
||||||
|
/// ```
|
||||||
|
pub fn db_call<
|
||||||
|
J: serde::ser::Serialize + Send + 'static,
|
||||||
|
Q: Fn(DbApi) -> QueryResult<J> + Send + 'static,
|
||||||
|
>(
|
||||||
|
pool: AppPool,
|
||||||
|
query: Q,
|
||||||
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
|
let conn = pool.get().unwrap();
|
||||||
|
web::block(move || {
|
||||||
|
let api = DbApi::with_conn(&conn);
|
||||||
|
query(api)
|
||||||
|
})
|
||||||
|
.then(|res| match res {
|
||||||
|
Ok(players) => HttpResponse::Ok().json(players),
|
||||||
|
Err(e) => {
|
||||||
|
dbg!(&e);
|
||||||
|
HttpResponse::InternalServerError().finish()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn serve() -> std::io::Result<()> {
|
||||||
|
let www_root: String = env::var("WWW_ROOT").expect("WWW_ROOT must be set");
|
||||||
|
dbg!(&www_root);
|
||||||
|
let pool = lootalot_db::create_pool();
|
||||||
|
|
||||||
|
HttpServer::new(move || {
|
||||||
|
App::new()
|
||||||
|
.data(pool.clone())
|
||||||
|
.wrap(
|
||||||
|
Cors::new()
|
||||||
|
.allowed_origin("http://localhost:8080")
|
||||||
|
.allowed_methods(vec!["GET", "POST"])
|
||||||
|
.max_age(3600),
|
||||||
|
)
|
||||||
|
.service(
|
||||||
|
web::scope("/api")
|
||||||
|
.route(
|
||||||
|
"/players",
|
||||||
|
web::get().to_async(move |pool: AppPool| {
|
||||||
|
db_call(pool, move |api| api.fetch_players())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/claims",
|
||||||
|
web::get().to_async(move |pool: AppPool| {
|
||||||
|
db_call(pool, move |api| api.fetch_claims())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/{player_id}/update-wealth/{amount}",
|
||||||
|
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, f32)>| {
|
||||||
|
db_call(pool, move |api| api.as_player(data.0).update_wealth(data.1))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/{player_id}/loot",
|
||||||
|
web::get().to_async(move |pool: AppPool, player_id: web::Path<i32>| {
|
||||||
|
db_call(pool, move |api| api.as_player(*player_id).loot())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/{player_id}/claim/{item_id}",
|
||||||
|
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, i32)>| {
|
||||||
|
db_call(pool, move |api| api.as_player(data.0).claim(data.1))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/{player_id}/unclaim/{item_id}",
|
||||||
|
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, i32)>| {
|
||||||
|
db_call(pool, move |api| api.as_player(data.0).unclaim(data.1))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/admin/resolve-claims",
|
||||||
|
web::get().to_async(move |pool: AppPool| {
|
||||||
|
db_call(pool, move |api| api.as_admin().resolve_claims())
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/admin/add-player/{name}/{wealth}",
|
||||||
|
web::get().to_async(
|
||||||
|
move |pool: AppPool, data: web::Path<(String, f32)>| {
|
||||||
|
db_call(pool, move |api| {
|
||||||
|
api.as_admin().add_player(data.0.clone(), data.1)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
||||||
|
})
|
||||||
|
.bind("127.0.0.1:8088")?
|
||||||
|
.run()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user