Compare commits
139 Commits
0ff303475b
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| a47646bd5f | |||
| 2c87713818 | |||
| b19d56fd9a | |||
| 342a66475d | |||
| 108470c5d1 | |||
| d1a85ed1d0 | |||
| cb8dfa9a2a | |||
| 61a03f1781 | |||
| 9d84a5ac62 | |||
| 988cdc97e2 | |||
| b5010539bb | |||
| 51cc6c4765 | |||
| 1cc9c2eefa | |||
| 4925afbeb5 | |||
| 1afbcff12a | |||
| ee0b7b2b7a | |||
| 089aaf9a6d | |||
| 1f2a940968 | |||
| 8d1344e0b6 | |||
| e9f535ac86 | |||
| 0ac2bce183 | |||
| d880d9528e | |||
| 9ee8cb867c | |||
| df06e2cf4a | |||
| ae991bf4dc | |||
| 40e39d5a65 | |||
| 559ce804a7 | |||
| 9a3744e340 | |||
| dc0874bd12 | |||
| 49dfd8bb14 | |||
| 74ee4a831b | |||
| 05a08ea337 | |||
| edf236ef8c | |||
| ed3ac2abcb | |||
| 2248e25aec | |||
| 24807615f7 | |||
| a552d7beee | |||
| ce04b77a15 | |||
| 622d746446 | |||
| b0441f3402 | |||
| 61c9a4e6d4 | |||
| 3fce1dc7d0 | |||
| 60a6e69f67 | |||
| 08397e7b25 | |||
| ec36403dc3 | |||
| 80585eb1cd | |||
| 185e1403e3 | |||
| 3cc45397da | |||
| 2222422f8a | |||
| 8cfa21eccf | |||
| 8af7790d17 | |||
| 6101aaa9e9 | |||
| 8399ffebf7 | |||
| de4aad5679 | |||
| a05cab9974 | |||
| c72169281d | |||
| b2e319dc15 | |||
| 0df875d6a6 | |||
| 068b2e7169 | |||
| 3a1f8ec4f6 | |||
| 77728cfdc4 | |||
| 70eed30bee | |||
| 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 | |||
| 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 |
8
.gitignore
vendored
8
.gitignore
vendored
@@ -1,8 +1,10 @@
|
||||
/target
|
||||
**/*.rs.bk
|
||||
|
||||
node_modules
|
||||
Cargo.lock
|
||||
**/*.sqlite3
|
||||
**/.env
|
||||
|
||||
package-lock.json
|
||||
fontawesome
|
||||
|
||||
Cargo.lock
|
||||
|
||||
|
||||
14
Cargo.toml
14
Cargo.toml
@@ -4,6 +4,20 @@ version = "0.1.0"
|
||||
authors = ["Artus <artus@landoftheunicorn.ovh>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.*"
|
||||
actix-files = "*"
|
||||
actix-service = "*"
|
||||
actix-identity = "*"
|
||||
lootalot-db = { version = "0.1", path = "./lootalot_db" }
|
||||
dotenv = "*"
|
||||
env_logger = "*"
|
||||
futures = "0.1"
|
||||
diesel = "*"
|
||||
serde = "*"
|
||||
serde_json = "*"
|
||||
actix-cors = "0.1.0"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
"lootalot_db"
|
||||
|
||||
54
README.md
54
README.md
@@ -6,43 +6,21 @@ Un gestionnaire de trésors pour des joueurs de Donjon&Dragons(tm).
|
||||
|
||||
## Fonctionnalités prévues
|
||||
|
||||
* Ajouter des objets "lootés"
|
||||
* Répartir les objets entre les joueurs et le groupe
|
||||
* 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
|
||||
* Gérer les comptes du groupe et des joueurs
|
||||
* Historique des transactions par propriétaire
|
||||
* Ajouter des objets
|
||||
☑ Acheter
|
||||
☐ Ajouter un trésor (objet par objet ou par liste)
|
||||
* 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
|
||||
☑ 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
|
||||
☑ 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
|
||||
|
||||
L'inventaire des objets qui peuvent être lootés.
|
||||
PK: id
|
||||
|
||||
### Propriétaires
|
||||
|
||||
Les joueurs sont des propriétaires d'objet.
|
||||
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
|
||||
```
|
||||
### Propriété
|
||||
|
||||
Table associative entre objets et propriétaires (joueurs ou groupe)
|
||||
L'ajout d'un objet à un propriétaire est un achat. La suppression, une vente.
|
||||
NB: L'historique d'achat est enregistré puis effacé lors de la vente.
|
||||
```
|
||||
PK: id
|
||||
FK: objets_id, proprietaire_id
|
||||
ATTRS: acquired_date, at_value
|
||||
```
|
||||
### Opérations
|
||||
|
||||
_Doit-on garder un historique des opérations ?_
|
||||
|
||||
|
||||
@@ -6,7 +6,11 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
dotenv = "*"
|
||||
diesel_migrations = "*"
|
||||
serde = "*"
|
||||
serde_derive = "*"
|
||||
serde_json = "*"
|
||||
|
||||
[dependencies.diesel]
|
||||
version = "1.0"
|
||||
features = ["sqlite"]
|
||||
version = "1.4"
|
||||
features = ["sqlite", "r2d2"]
|
||||
|
||||
Binary file not shown.
@@ -1,2 +1,3 @@
|
||||
DROP TABLE items;
|
||||
|
||||
DROP TABLE looted;
|
||||
DROP TABLE shop;
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
-- The global inventory of items
|
||||
CREATE TABLE items (
|
||||
id INTEGER PRIMARY KEY,
|
||||
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)
|
||||
);
|
||||
|
||||
-- The items that are available in shop
|
||||
CREATE TABLE shop (
|
||||
id INTEGER PRIMARY KEY NOT NULL,
|
||||
name VARCHAR NOT NULL,
|
||||
base_price INTEGER NOT NULL
|
||||
);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
CREATE TABLE players (
|
||||
id INTEGER PRIMARY KEY,
|
||||
id INTEGER PRIMARY KEY NOT NULL,
|
||||
name VARCHAR NOT NULL,
|
||||
debt INTEGER DEFAULT 0, -- debt to the group in copper pieces
|
||||
cp INTEGER DEFAULT 0,
|
||||
sp INTEGER DEFAULT 0,
|
||||
gp INTEGER DEFAULT 0,
|
||||
pp INTEGER DEFAULT 0
|
||||
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 +0,0 @@
|
||||
DROP TABLE looted;
|
||||
@@ -1,8 +0,0 @@
|
||||
CREATE TABLE looted (
|
||||
id INTEGER PRIMARY KEY,
|
||||
player_id INTEGER NOT NULL,
|
||||
item_id INTEGER NOT NULL,
|
||||
acquired_date DATE DEFAULT NOW,
|
||||
FOREIGN KEY (player_id) REFERENCES players(id),
|
||||
FOREIGN KEY (item_id) REFERENCES items(id)
|
||||
);
|
||||
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)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE notifications;
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE notifications (
|
||||
id INTEGER PRIMARY KEY NOT NULL,
|
||||
player_id INTEGER NOT NULL,
|
||||
text VARCHAR NOT NULL,
|
||||
FOREIGN KEY (player_id) REFERENCES players(id)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE history;
|
||||
8
lootalot_db/migrations/2019-10-27-135235_history/up.sql
Normal file
8
lootalot_db/migrations/2019-10-27-135235_history/up.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE history (
|
||||
id INTEGER PRIMARY KEY NOT NULL,
|
||||
player_id INTEGER NOT NULL,
|
||||
event_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
text VARCHAR NOT NULL,
|
||||
updates VARCHAR,
|
||||
FOREIGN KEY (player_id) REFERENCES players(id)
|
||||
);
|
||||
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
@@ -1,52 +1,472 @@
|
||||
#[macro_use] extern crate diesel;
|
||||
extern crate dotenv;
|
||||
//! 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 dotenv::dotenv;
|
||||
use std::env;
|
||||
use diesel::query_dsl::RunQueryDsl;
|
||||
use diesel::r2d2::{self, ConnectionManager};
|
||||
|
||||
pub fn establish_connection() -> Result<SqliteConnection, String> {
|
||||
dotenv().ok();
|
||||
let database_url =
|
||||
env::var("DATABASE_URL")
|
||||
.expect("DATABASE_URL must be set !");
|
||||
SqliteConnection::establish(&database_url)
|
||||
.map_err(|e| format!("Error connecting to {} : {:?}", database_url, e))
|
||||
}
|
||||
|
||||
pub mod schema;
|
||||
pub mod models;
|
||||
mod schema;
|
||||
|
||||
pub fn list_players() -> Vec<models::Player> {
|
||||
use schema::players::dsl::*;
|
||||
let conn = establish_connection().unwrap();
|
||||
players
|
||||
.load::<models::Player>(&conn)
|
||||
.expect("Error loading players")
|
||||
.collect()
|
||||
pub use models::{
|
||||
claim::{Claim, Claims},
|
||||
history::{Event, UpdateList},
|
||||
item::{Inventory, Shop, Item, LootManager},
|
||||
player::{AsPlayer, Player, Players, Wealth},
|
||||
};
|
||||
|
||||
/// 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 UpdateResult = QueryResult<Update>;
|
||||
|
||||
/// 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.")
|
||||
}
|
||||
|
||||
/// Every possible update which can happen during a query
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub enum Update {
|
||||
Wealth(Wealth),
|
||||
ItemAdded(Item),
|
||||
ItemRemoved(Item),
|
||||
ClaimAdded(Claim),
|
||||
ClaimRemoved(Claim),
|
||||
}
|
||||
|
||||
impl Update {
|
||||
/// Change back what has been updated
|
||||
fn undo(&self, conn: &DbConnection, id: i32) -> UpdateResult {
|
||||
Ok(match self {
|
||||
Update::Wealth(diff) => AsPlayer(conn, id).update_wealth(-diff.to_gp())?,
|
||||
Update::ItemAdded(item) => LootManager(conn, id).find(item.id)?.remove(conn)?,
|
||||
Update::ItemRemoved(item) => LootManager(conn, id).add_from(&item)?,
|
||||
// Unused for now
|
||||
Update::ClaimAdded(claim) => Update::ClaimRemoved(*claim),
|
||||
Update::ClaimRemoved(claim) => Update::ClaimAdded(*claim),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO: use this to wrap update in UpdateResult, allowing unified interface
|
||||
/// whether a query makes multiple updates or just one.
|
||||
enum OneOrMore {
|
||||
One(Update),
|
||||
More(Vec<Update>),
|
||||
}
|
||||
|
||||
/// Every value which can be queried
|
||||
#[derive(Debug)]
|
||||
pub enum Value {
|
||||
Player(Player),
|
||||
Item(Item),
|
||||
Claim(Claim),
|
||||
ItemList(Vec<Item>),
|
||||
ClaimList(Vec<Claim>),
|
||||
PlayerList(Vec<Player>),
|
||||
Notifications(Vec<String>),
|
||||
}
|
||||
|
||||
impl serde::Serialize for Value {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
match self {
|
||||
Value::Player(v) => v.serialize(serializer),
|
||||
Value::Item(v) => v.serialize(serializer),
|
||||
Value::Claim(v) => v.serialize(serializer),
|
||||
Value::ItemList(v) => v.serialize(serializer),
|
||||
Value::ClaimList(v) => v.serialize(serializer),
|
||||
Value::PlayerList(v) => v.serialize(serializer),
|
||||
Value::Notifications(v) => v.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sells a single item inside a transaction
|
||||
///
|
||||
/// # Returns
|
||||
/// The deleted entity and the updated Wealth (as a difference from previous value)
|
||||
pub fn sell_item_transaction(
|
||||
conn: &DbConnection,
|
||||
id: i32,
|
||||
loot_id: i32,
|
||||
price_mod: Option<f64>,
|
||||
) -> QueryResult<(Update, Wealth)> {
|
||||
conn.transaction(|| {
|
||||
let to_delete = LootManager(conn, id).find(loot_id)?;
|
||||
let mut sell_value = to_delete.sell_value() as f64;
|
||||
if let Some(modifier) = price_mod {
|
||||
sell_value *= modifier;
|
||||
}
|
||||
let deleted = to_delete.remove(conn)?;
|
||||
if let Update::Wealth(wealth) = AsPlayer(conn, id).update_wealth(sell_value)? {
|
||||
Ok((deleted, wealth))
|
||||
} else {
|
||||
Err(diesel::result::Error::RollbackTransaction)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Buys a single item, copied from inventory.
|
||||
/// Runs inside a transaction
|
||||
///
|
||||
/// # Returns
|
||||
/// The created entity and the updated Wealth (as a difference from previous value)
|
||||
pub fn buy_item_from_inventory(
|
||||
conn: &DbConnection,
|
||||
id: i32,
|
||||
item_id: i32,
|
||||
price_mod: Option<f64>,
|
||||
) -> QueryResult<(Update, Wealth)> {
|
||||
conn.transaction(|| {
|
||||
// Find item in inventory
|
||||
let item = Inventory(conn).find(item_id)?;
|
||||
let new_item = LootManager(conn, id).add_from(&item)?;
|
||||
let sell_price = match price_mod {
|
||||
Some(modifier) => item.value() * modifier,
|
||||
None => item.value(),
|
||||
};
|
||||
if let Update::Wealth(diff) = AsPlayer(conn, id).update_wealth(-sell_price)? {
|
||||
Ok((new_item, diff))
|
||||
} else {
|
||||
Err(diesel::result::Error::RollbackTransaction)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn buy_item_from_shop(
|
||||
conn: &DbConnection,
|
||||
id: i32,
|
||||
item_id: i32,
|
||||
price_mod: Option<f64>,
|
||||
) -> QueryResult<(Update, Wealth)> {
|
||||
conn.transaction(|| {
|
||||
let shop = Shop(conn);
|
||||
// Find item in inventory
|
||||
let item = shop.get(item_id)?;
|
||||
let new_item = LootManager(conn, id).add_from(&item)?;
|
||||
let _deleted = shop.remove(item_id)?;
|
||||
let sell_price = match price_mod {
|
||||
Some(modifier) => item.value() * modifier,
|
||||
None => item.value(),
|
||||
};
|
||||
if let Update::Wealth(diff) = AsPlayer(conn, id).update_wealth(-sell_price)? {
|
||||
Ok((new_item, diff))
|
||||
} else {
|
||||
Err(diesel::result::Error::RollbackTransaction)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/// Resolve all pending claims and dispatch claimed items.
|
||||
///
|
||||
/// When a player gets an item, it's debt is increased by this item sell value
|
||||
pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
|
||||
let data = models::claim::Claims(conn).grouped_by_item()?;
|
||||
dbg!(&data);
|
||||
conn.transaction(move || {
|
||||
for (item, mut claims) in data {
|
||||
if claims.len() > 1 {
|
||||
// TODO: better sorting mechanism :)
|
||||
claims.sort_by(|a, b| a.resolve.cmp(&b.resolve));
|
||||
}
|
||||
let winner = claims.get(0).expect("Claims should not be empty !");
|
||||
let player_id = winner.player_id;
|
||||
winner.resolve_claim(conn)?;
|
||||
models::player::AsPlayer(conn, player_id).update_debt(item.sell_value() as i32)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Split up and share an certain amount of group money among selected players
|
||||
///
|
||||
/// The group first solve players debts,
|
||||
/// then give what's left.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A Wealth update with the amount of money shared with players
|
||||
pub fn split_and_share(
|
||||
conn: &DbConnection,
|
||||
amount: i32,
|
||||
players: Vec<i32>,
|
||||
) -> UpdateResult {
|
||||
let players = match players.is_empty() {
|
||||
true => Players(conn)
|
||||
.all_except_group()?
|
||||
.iter()
|
||||
.map(|p| p.id)
|
||||
.collect(),
|
||||
false => players
|
||||
};
|
||||
let share = (
|
||||
amount / (players.len() + 1) as i32
|
||||
// +1 share for the group
|
||||
) as f64;
|
||||
conn.transaction(|| {
|
||||
let mut shared_total = 0.0;
|
||||
for id in players {
|
||||
let player = Players(conn).find(id)?;
|
||||
// Take debt into account
|
||||
match share - player.debt as f64 {
|
||||
rest if rest > 0.0 => {
|
||||
AsPlayer(conn, id).update_debt(-player.debt)?;
|
||||
AsPlayer(conn, id).update_wealth(rest)?;
|
||||
AsPlayer(conn, 0).update_wealth(-rest)?;
|
||||
shared_total += rest;
|
||||
}
|
||||
_ => {
|
||||
AsPlayer(conn, id).update_debt(-share as i32)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Update::Wealth(Wealth::from_gp(shared_total)))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[cfg(none)]
|
||||
mod tests_old {
|
||||
use super::*;
|
||||
type TestConnection = DbConnection;
|
||||
|
||||
fn with_db<F>(f: F) -> ()
|
||||
where F: Fn(&SqliteConnection) -> (),
|
||||
{
|
||||
let conn = establish_connection().unwrap();
|
||||
conn.test_transaction::<_,diesel::result::Error,_>(|| {
|
||||
f(&conn);
|
||||
Ok(())
|
||||
});
|
||||
/// Return a connection to a fresh database (stored in memory)
|
||||
fn test_connection() -> TestConnection {
|
||||
let test_conn = DbConnection::establish(":memory:").unwrap();
|
||||
diesel_migrations::run_pending_migrations(&test_conn).unwrap();
|
||||
test_conn
|
||||
}
|
||||
|
||||
/// When migrations are run, a special player with id 0 and name "Groupe"
|
||||
/// must be created.
|
||||
#[test]
|
||||
fn global_group_is_autocreated() {
|
||||
let conn = test_connection();
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
assert_eq!(players.len(), 1);
|
||||
let group = players.get(0).unwrap();
|
||||
assert_eq!(group.id, 0);
|
||||
assert_eq!(group.name, "Groupe".to_string());
|
||||
}
|
||||
|
||||
/// When a player updates wealth, a difference is returned by API.
|
||||
/// Added to the previous amount of coins, it should equal the updated weath.
|
||||
#[test]
|
||||
fn as_player_updates_wealth() {
|
||||
let conn = test_connection();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("PlayerName", 403.21)
|
||||
.unwrap();
|
||||
let diff = DbApi::with_conn(&conn)
|
||||
.as_player(1)
|
||||
.update_wealth(-401.21)
|
||||
.ok();
|
||||
// Check the returned diff
|
||||
assert_eq!(diff, Some((-1, -2, -1, -4)));
|
||||
let diff = diff.unwrap();
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
let player = players.get(1).unwrap();
|
||||
// Check that we can add old value to return diff to get resulting value
|
||||
assert_eq!(
|
||||
(player.cp, player.sp, player.gp, player.pp),
|
||||
(1 + diff.0, 2 + diff.1, 3 + diff.2, 4 + diff.3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_connection() {
|
||||
use crate::establish_connection;
|
||||
let conn = establish_connection();
|
||||
assert_eq!(conn.is_ok(), true);
|
||||
fn as_admin_add_player() {
|
||||
let conn = test_connection();
|
||||
let result = DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("PlayerName", 403.21);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
assert_eq!(players.len(), 2);
|
||||
let new_player = players.get(1).unwrap();
|
||||
assert_eq!(new_player.name, "PlayerName");
|
||||
assert_eq!(
|
||||
(new_player.cp, new_player.sp, new_player.gp, new_player.pp),
|
||||
(1, 2, 3, 4)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_admin_resolve_claims() {
|
||||
let conn = test_connection();
|
||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||
assert_eq!(claims.len(), 0);
|
||||
|
||||
// Add items
|
||||
assert_eq!(
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_loot(vec![("Épée", 40), ("Arc", 40),])
|
||||
.is_ok(),
|
||||
true
|
||||
);
|
||||
// Add players
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player1", 0.0)
|
||||
.unwrap();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player2", 0.0)
|
||||
.unwrap();
|
||||
// Put claims on one different item each
|
||||
DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
||||
DbApi::with_conn(&conn).as_player(2).claim(2).unwrap();
|
||||
let result = DbApi::with_conn(&conn).as_admin().resolve_claims();
|
||||
assert_eq!(result.is_ok(), true);
|
||||
// Check that both players received an item
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
for &i in [1, 2].into_iter() {
|
||||
assert_eq!(
|
||||
DbApi::with_conn(&conn).as_player(i).loot().unwrap().len(),
|
||||
1
|
||||
);
|
||||
let player = players.get(i as usize).unwrap();
|
||||
assert_eq!(player.debt, 20);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_player_claim_item() {
|
||||
let conn = test_connection();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player", 0.0)
|
||||
.unwrap();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_loot(vec![("Épée", 25)])
|
||||
.unwrap();
|
||||
// Claim an existing item
|
||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||
assert_eq!(claims.len(), 1);
|
||||
let claim = claims.get(0).unwrap();
|
||||
assert_eq!(claim.player_id, 1);
|
||||
assert_eq!(claim.loot_id, 1);
|
||||
// Claim an inexistant item
|
||||
let result = DbApi::with_conn(&conn).as_player(1).claim(2);
|
||||
assert_eq!(result.is_ok(), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_player_unclaim_item() {
|
||||
let conn = test_connection();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player", 0.0)
|
||||
.unwrap();
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_loot(vec![("Épée", 25)])
|
||||
.unwrap();
|
||||
// Claim an existing item
|
||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
// Claiming twice is an error
|
||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
||||
assert_eq!(result.is_ok(), false);
|
||||
// Unclaiming and item
|
||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
// Check that not claimed items will not be unclaimed...
|
||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
||||
assert_eq!(result.is_ok(), false);
|
||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
||||
assert_eq!(claims.len(), 0);
|
||||
}
|
||||
|
||||
/// All-in-one checks one a simple buy/sell procedure
|
||||
///
|
||||
/// Checks that player's chest and wealth are updated.
|
||||
/// Checks that items are sold at half their value.
|
||||
/// Checks that a player cannot sell item he does not own.
|
||||
#[test]
|
||||
fn as_player_simple_buy_sell() {
|
||||
let conn = test_connection();
|
||||
// Adds a sword into inventory
|
||||
{
|
||||
use schema::items::dsl::*;
|
||||
diesel::insert_into(items)
|
||||
.values((name.eq("Sword"), base_price.eq(800)))
|
||||
.execute(&conn)
|
||||
.expect("Could not set up items table");
|
||||
}
|
||||
DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_player("Player", 1000.0)
|
||||
.unwrap();
|
||||
// Buy an item
|
||||
let bought = DbApi::with_conn(&conn).as_player(1).buy(&vec![(1, None)]);
|
||||
assert_eq!(bought.ok(), Some((0, 0, 0, -8))); // Returns diff of player wealth ?
|
||||
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
||||
assert_eq!(chest.len(), 1);
|
||||
let loot = chest.get(0).unwrap();
|
||||
assert_eq!(loot.name, "Sword");
|
||||
assert_eq!(loot.base_price, 800);
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
let player = players.get(1).unwrap();
|
||||
assert_eq!(player.pp, 2);
|
||||
// A player cannot sell loot from an other's chest
|
||||
let result = DbApi::with_conn(&conn)
|
||||
.as_player(0)
|
||||
.sell(&vec![(loot.id, None)]);
|
||||
assert_eq!(result.is_ok(), false);
|
||||
// Sell back
|
||||
let sold = DbApi::with_conn(&conn)
|
||||
.as_player(1)
|
||||
.sell(&vec![(loot.id, None)]);
|
||||
assert_eq!(sold.ok(), Some((0, 0, 0, 4)));
|
||||
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
||||
assert_eq!(chest.len(), 0);
|
||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
||||
let player = players.get(1).unwrap();
|
||||
assert_eq!(player.pp, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_admin_add_loot() {
|
||||
let conn = test_connection();
|
||||
assert_eq!(
|
||||
0,
|
||||
DbApi::with_conn(&conn).as_player(0).loot().unwrap().len()
|
||||
);
|
||||
let loot_to_add = vec![("Cape d'invisibilité", 8000), ("Arc long", 25)];
|
||||
let result = DbApi::with_conn(&conn)
|
||||
.as_admin()
|
||||
.add_loot(loot_to_add.clone());
|
||||
assert_eq!(result.is_ok(), true);
|
||||
let looted = DbApi::with_conn(&conn).as_player(0).loot().unwrap();
|
||||
assert_eq!(looted.len(), 2);
|
||||
// NB: Not a problem now, but this adds constraints of items being
|
||||
// created in the same order.
|
||||
for (added, to_add) in looted.into_iter().zip(loot_to_add) {
|
||||
assert_eq!(added.name, to_add.0);
|
||||
assert_eq!(added.base_price, to_add.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
use crate::*;
|
||||
use crate::schema::players;
|
||||
|
||||
#[derive(Queryable)]
|
||||
pub struct Player {
|
||||
id: i32,
|
||||
name: String,
|
||||
debt: i32,
|
||||
cp: i32,
|
||||
sp: i32,
|
||||
gp: i32,
|
||||
pp: i32,
|
||||
}
|
||||
|
||||
#[derive(Insertable)]
|
||||
#[table_name="players"]
|
||||
pub struct NewPlayer<'a> {
|
||||
name: &'a str,
|
||||
cp: i32,
|
||||
sp: i32,
|
||||
gp: i32,
|
||||
pp: i32,
|
||||
}
|
||||
|
||||
impl<'a> NewPlayer<'a> {
|
||||
|
||||
fn new(
|
||||
name: &'a str,
|
||||
wealth: Option<(i32,i32,i32,i32)>,
|
||||
) -> Self {
|
||||
let (cp,sp,gp,pp) = wealth.unwrap_or((0,0,0,0));
|
||||
NewPlayer { name, cp, sp, gp, pp }
|
||||
}
|
||||
|
||||
fn insert(&self) -> Result<(),()> {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::tests;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn new_player_only_with_name() {
|
||||
let n = NewPlayer::new("Féfi", None);
|
||||
assert_eq!(n.name, "Féfi");
|
||||
assert_eq!(n.cp, 0);
|
||||
assert_eq!(n.sp, 0);
|
||||
assert_eq!(n.gp, 0);
|
||||
assert_eq!(n.pp, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_player_with_wealth() {
|
||||
let initial_wealth = (1, 2, 3, 4);
|
||||
let n = NewPlayer::new("Féfi", Some(initial_wealth));
|
||||
assert_eq!(initial_wealth, (n.cp, n.sp, n.gp, n.pp));
|
||||
}
|
||||
}
|
||||
187
lootalot_db/src/models/claim.rs
Normal file
187
lootalot_db/src/models/claim.rs
Normal file
@@ -0,0 +1,187 @@
|
||||
use diesel::prelude::*;
|
||||
|
||||
use crate::{DbConnection, QueryResult, Update, UpdateResult};
|
||||
use crate::models::{self, 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, Deserialize, Clone, Copy, 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,
|
||||
}
|
||||
|
||||
impl Claim {
|
||||
/// Resolves this claim (player wins the item) and deletes it
|
||||
pub fn resolve_claim(&self, conn: &DbConnection) -> QueryResult<()> {
|
||||
let loot: Loot = Loot::find(self.loot_id).first(conn)?;
|
||||
loot.set_owner(self.player_id, conn)?;
|
||||
self.remove(conn)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove(&self, conn: &DbConnection) -> QueryResult<()> {
|
||||
diesel::delete(claims::table.find(self.id)).execute(conn)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Claims<'q>(pub &'q DbConnection);
|
||||
|
||||
impl<'q> Claims<'q> {
|
||||
/// Get all claims from database
|
||||
pub fn all(&self) -> QueryResult<Vec<Claim>> {
|
||||
claims::table.load(self.0)
|
||||
}
|
||||
|
||||
pub fn by_player(&self, id: i32) -> QueryResult<Vec<Claim>> {
|
||||
claims::table.filter(claims::dsl::player_id.eq(id))
|
||||
.load(self.0)
|
||||
}
|
||||
|
||||
/// Finds a single claim by association of player and loot ids.
|
||||
pub fn find(&self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
||||
claims::table
|
||||
.filter(claims::dsl::player_id.eq(player_id))
|
||||
.filter(claims::dsl::loot_id.eq(loot_id))
|
||||
.first(self.0)
|
||||
}
|
||||
|
||||
/// Adds a claim in database and returns it.
|
||||
///
|
||||
/// Will validate that the claimed item exists and is
|
||||
/// actually owned by the group.
|
||||
/// Duplicates are also ignored.
|
||||
pub fn add(self, player_id: i32, loot_id: i32) -> UpdateResult {
|
||||
// We need to validate that the claimed item exists
|
||||
// AND is actually owned by group (id 0)
|
||||
let _item = models::item::LootManager(self.0, 0).find(loot_id)?;
|
||||
// We also check if claims does not already exists
|
||||
if let Ok(_) = self.find(player_id, loot_id) {
|
||||
return Err(diesel::result::Error::RollbackTransaction);
|
||||
}
|
||||
|
||||
let claim = NewClaim::new(player_id, loot_id);
|
||||
diesel::insert_into(claims::table)
|
||||
.values(&claim)
|
||||
.execute(self.0)?;
|
||||
// Return the created claim
|
||||
Ok(
|
||||
Update::ClaimAdded(
|
||||
claims::table
|
||||
.order(claims::dsl::id.desc())
|
||||
.first::<Claim>(self.0)?
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// Removes a claim from database, returning it
|
||||
pub fn remove(self, player_id: i32, loot_id: i32) -> UpdateResult {
|
||||
let claim = self.find(player_id, loot_id)?;
|
||||
claim.remove(self.0)?;
|
||||
Ok(
|
||||
Update::ClaimRemoved(claim)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> {
|
||||
claims::table
|
||||
.filter(claims::dsl::loot_id.eq(loot_id))
|
||||
.load(self.0)
|
||||
}
|
||||
|
||||
pub(crate) fn delete_for_loot(&self, loot_id: i32) -> QueryResult<usize> {
|
||||
diesel::delete(
|
||||
claims::table
|
||||
.filter(claims::dsl::loot_id.eq(loot_id))
|
||||
)
|
||||
.execute(self.0)
|
||||
|
||||
}
|
||||
|
||||
pub(crate) fn grouped_by_item(&self) -> QueryResult<Vec<(models::item::Item, Vec<Claim>)>> {
|
||||
let group_loot: Vec<Loot> = Loot::owned_by(0).load(self.0)?;
|
||||
let claims = claims::table.load(self.0)?.grouped_by(&group_loot);
|
||||
Ok(group_loot
|
||||
.into_iter()
|
||||
.map(|loot| loot.into_item())
|
||||
.zip(claims)
|
||||
.collect::<Vec<_>>())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Insertable, Debug)]
|
||||
#[table_name = "claims"]
|
||||
struct NewClaim {
|
||||
player_id: i32,
|
||||
loot_id: i32,
|
||||
}
|
||||
|
||||
impl NewClaim {
|
||||
fn new(player_id: i32, loot_id: i32) -> Self {
|
||||
Self { player_id, loot_id }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
type TestResult = Result<(), diesel::result::Error>;
|
||||
|
||||
fn test_connection() -> Result<DbConnection, diesel::result::Error> {
|
||||
let conn =
|
||||
DbConnection::establish(":memory:").map_err(|_| diesel::result::Error::NotFound)?;
|
||||
diesel_migrations::run_pending_migrations(&conn)
|
||||
.map_err(|_| diesel::result::Error::NotFound)?;
|
||||
let manager = models::player::Players(&conn);
|
||||
manager.add("Player1", 0.0)?;
|
||||
manager.add("Player2", 0.0)?;
|
||||
crate::LootManager(&conn, 0).add("Epee", 30)?;
|
||||
crate::LootManager(&conn, 1).add("Arc", 20)?;
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_claim() -> TestResult {
|
||||
let conn = test_connection()?;
|
||||
Claims(&conn).add(1, 1)?;
|
||||
assert_eq!(Claims(&conn).all()?.len(), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cannot_duplicate_by_adding() -> TestResult {
|
||||
let conn = test_connection()?;
|
||||
Claims(&conn).add(1, 1)?;
|
||||
let res = Claims(&conn).add(1, 1);
|
||||
assert_eq!(res.is_err(), true);
|
||||
assert_eq!(Claims(&conn).all()?.len(), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_claim() -> TestResult {
|
||||
let conn = test_connection()?;
|
||||
let claim = Claims(&conn).add(1, 1)?;
|
||||
claim.remove(&conn);
|
||||
assert_eq!(Claims(&conn).all()?.len(), 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cannot_only_claim_from_group() -> TestResult {
|
||||
let conn = test_connection()?;
|
||||
let claim = Claims(&conn).add(1, 2);
|
||||
assert_eq!(claim.is_err(), true);
|
||||
assert_eq!(Claims(&conn).all()?.len(), 0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
109
lootalot_db/src/models/history.rs
Normal file
109
lootalot_db/src/models/history.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use serde_json;
|
||||
use diesel::prelude::*;
|
||||
use diesel::sql_types::Text;
|
||||
use diesel::deserialize::FromSql;
|
||||
use diesel::backend::Backend;
|
||||
use crate::schema::history;
|
||||
use crate::{DbConnection, QueryResult, Update};
|
||||
|
||||
#[derive(Debug, FromSqlRow)]
|
||||
pub struct UpdateList(Vec<Update>);
|
||||
|
||||
impl UpdateList {
|
||||
pub fn inner(&self) -> &Vec<Update> {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn into_inner(self) -> Vec<Update> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: decide if updates is really optionnal or not
|
||||
// (like if storing an event without update is usefull ?)
|
||||
|
||||
/// An event in history
|
||||
#[derive(Debug, Queryable)]
|
||||
pub struct Event {
|
||||
id: i32,
|
||||
player_id: i32,
|
||||
event_date: String,
|
||||
text: String,
|
||||
updates: Option<UpdateList>,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn name(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
|
||||
/// TODO: why a move here ??
|
||||
/// Undo all updates in a single transaction
|
||||
pub fn undo(self, conn: &DbConnection) -> QueryResult<UpdateList> {
|
||||
conn.transaction(move || {
|
||||
if let Some(ref updates) = self.updates {
|
||||
let undone = updates.0.iter()
|
||||
// TODO: swallow errors !
|
||||
.filter_map(|u| u.undo(conn, self.player_id).ok())
|
||||
.collect();
|
||||
diesel::delete(history::table.find(self.id)).execute(conn)?;
|
||||
Ok(UpdateList(undone))
|
||||
} else {
|
||||
Ok(UpdateList(vec![]))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<DB: Backend> FromSql<Text, DB> for UpdateList
|
||||
where
|
||||
String: FromSql<Text, DB>,
|
||||
{
|
||||
fn from_sql(bytes: Option<&DB::RawValue>) -> diesel::deserialize::Result<Self> {
|
||||
let repr = String::from_sql(bytes)?;
|
||||
Ok(UpdateList(serde_json::from_str::<Vec<Update>>(&repr)?))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Insertable)]
|
||||
#[table_name = "history"]
|
||||
struct NewEvent<'a> {
|
||||
player_id: i32,
|
||||
text: &'a str,
|
||||
updates: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
/// Insert a new event
|
||||
///
|
||||
/// # Warning
|
||||
/// This actually swallow up conversion errors
|
||||
pub fn insert_event(conn: &DbConnection, id: i32, text: &str, updates: &Vec<Update>) -> QueryResult<Event> {
|
||||
diesel::insert_into(history::table)
|
||||
.values(&NewEvent {
|
||||
player_id: id,
|
||||
text,
|
||||
updates: serde_json::to_string(updates).ok(),
|
||||
})
|
||||
.execute(conn)?;
|
||||
history::table
|
||||
.order(history::dsl::id.desc())
|
||||
.first(conn)
|
||||
}
|
||||
|
||||
pub fn get_last_of_player(conn: &DbConnection, id: i32) -> QueryResult<Event> {
|
||||
history::table
|
||||
.filter(history::dsl::player_id.eq(id))
|
||||
.order(history::dsl::id.desc())
|
||||
.first(conn)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_insert_event_with_updates() {
|
||||
|
||||
}
|
||||
}
|
||||
219
lootalot_db/src/models/item.rs
Normal file
219
lootalot_db/src/models/item.rs
Normal file
@@ -0,0 +1,219 @@
|
||||
use diesel::dsl::{exists, Eq, Filter, Find, Select};
|
||||
use diesel::expression::exists::Exists;
|
||||
use diesel::prelude::*;
|
||||
|
||||
use crate::schema::{items, looted, shop};
|
||||
use crate::{DbConnection, QueryResult, Update, UpdateResult, Claims };
|
||||
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 basic item
|
||||
#[derive(Debug, Queryable, Serialize, Deserialize, Clone)]
|
||||
pub struct Item {
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
base_price: i32,
|
||||
}
|
||||
|
||||
impl Item {
|
||||
/// Returns this item value
|
||||
pub fn value(&self) -> f64 {
|
||||
self.base_price as f64
|
||||
}
|
||||
|
||||
/// Returns this item sell value
|
||||
pub fn sell_value(&self) -> f64 {
|
||||
self.base_price as f64 / 2.0
|
||||
}
|
||||
|
||||
pub fn remove(self, conn: &DbConnection) -> UpdateResult {
|
||||
conn.transaction(
|
||||
|| -> UpdateResult
|
||||
{
|
||||
Claims(conn).delete_for_loot(self.id)?;
|
||||
diesel::delete(looted::table.find(self.id)).execute(conn)?;
|
||||
|
||||
Ok(Update::ItemRemoved(self))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn owned_by(player: i32) -> OwnedBy {
|
||||
Loot::owned_by(player).select(ITEM_COLUMNS)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Inventory<'q>(pub &'q DbConnection);
|
||||
|
||||
impl<'q> Inventory<'q> {
|
||||
/// Get all items from Inventory
|
||||
pub fn all(&self) -> QueryResult<Vec<Item>> {
|
||||
items::table.load::<Item>(self.0)
|
||||
}
|
||||
|
||||
/// Find an item in Inventory
|
||||
pub fn find(&self, item_id: i32) -> QueryResult<Item> {
|
||||
items::table.find(item_id).first::<Item>(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Shop<'q>(pub &'q DbConnection);
|
||||
|
||||
impl<'q> Shop<'q> {
|
||||
pub fn all(&self) -> QueryResult<Vec<Item>> {
|
||||
shop::table.load(self.0)
|
||||
}
|
||||
|
||||
pub fn get(&self, id: i32) -> QueryResult<Item> {
|
||||
shop::table.find(&id).first::<Item>(self.0)
|
||||
}
|
||||
|
||||
pub fn remove(&self, id: i32) -> QueryResult<()> {
|
||||
diesel::delete(
|
||||
shop::table.find(&id)
|
||||
).execute(self.0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn replace_list(&self, items: Vec<Item>) -> QueryResult<()> {
|
||||
self.0.transaction(
|
||||
|| -> QueryResult<()>
|
||||
{
|
||||
// Remove all content
|
||||
diesel::delete(shop::table).execute(self.0)?;
|
||||
// Adds new list
|
||||
for item in &items {
|
||||
let new_item = NewItem {
|
||||
name: &item.name,
|
||||
base_price: item.base_price,
|
||||
};
|
||||
diesel::insert_into(shop::table)
|
||||
.values(&new_item)
|
||||
.execute(self.0)?;
|
||||
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
type WithOwner = Eq<looted::owner_id, i32>;
|
||||
type OwnedLoot = Filter<looted::table, WithOwner>;
|
||||
|
||||
/// Represents an item that has been looted,
|
||||
/// hence has an owner.
|
||||
#[derive(Identifiable, Debug, Queryable)]
|
||||
#[table_name = "looted"]
|
||||
pub(super) struct Loot {
|
||||
id: i32,
|
||||
name: String,
|
||||
base_price: i32,
|
||||
owner: i32,
|
||||
}
|
||||
|
||||
impl Loot {
|
||||
/// A filter on Loot that is owned by given player
|
||||
pub(super) fn owned_by(id: i32) -> OwnedLoot {
|
||||
looted::table.filter(looted::owner_id.eq(id))
|
||||
}
|
||||
|
||||
fn exists(id: i32) -> Exists<Find<looted::table, i32>> {
|
||||
exists(looted::table.find(id))
|
||||
}
|
||||
|
||||
pub(super) fn set_owner(&self, owner: i32, conn: &DbConnection) -> QueryResult<()> {
|
||||
diesel::update(looted::table.find(self.id))
|
||||
.set(looted::dsl::owner_id.eq(owner))
|
||||
.execute(conn)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn into_item(self) -> Item {
|
||||
Item {
|
||||
id: self.id,
|
||||
name: self.name,
|
||||
base_price: self.base_price,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn find(id: i32) -> Find<looted::table, i32> {
|
||||
looted::table.find(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Manager for a *single* player loot
|
||||
pub struct LootManager<'q>(pub &'q DbConnection, pub i32);
|
||||
|
||||
impl<'q> LootManager<'q> {
|
||||
/// All items from this player chest
|
||||
pub fn all(&self) -> QueryResult<Vec<Item>> {
|
||||
Ok(Item::owned_by(self.1).load(self.0)?)
|
||||
}
|
||||
|
||||
/// Finds an item by id
|
||||
///
|
||||
/// Returns a NotFound error if an item is found by it
|
||||
/// does not belong to this player
|
||||
pub fn find(&self, loot_id: i32) -> QueryResult<Item> {
|
||||
Ok(Loot::find(loot_id).first(self.0).and_then(|loot: Loot| {
|
||||
if loot.owner != self.1 {
|
||||
Err(diesel::result::Error::NotFound)
|
||||
} else {
|
||||
Ok(Item {
|
||||
id: loot.id,
|
||||
name: loot.name,
|
||||
base_price: loot.base_price,
|
||||
})
|
||||
}
|
||||
})?)
|
||||
}
|
||||
|
||||
/// The last item added to the chest
|
||||
pub fn last(&self) -> QueryResult<Item> {
|
||||
Ok(Item::owned_by(self.1)
|
||||
.order(looted::dsl::id.desc())
|
||||
.first(self.0)?)
|
||||
}
|
||||
|
||||
pub(crate) fn add<S: Into<String>>(self, name: S, base_price: i32) -> UpdateResult {
|
||||
self.add_from(&Item {
|
||||
id: 0,
|
||||
name: name.into(),
|
||||
base_price,
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds a copy of the given item inside player chest
|
||||
pub fn add_from(self, item: &Item) -> UpdateResult {
|
||||
let new_item = NewLoot {
|
||||
name: &item.name,
|
||||
base_price: item.base_price,
|
||||
owner_id: self.1,
|
||||
};
|
||||
diesel::insert_into(looted::table)
|
||||
.values(&new_item)
|
||||
.execute(self.0)?;
|
||||
Ok(Update::ItemAdded(self.last()?))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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"]
|
||||
struct NewLoot<'a> {
|
||||
name: &'a str,
|
||||
base_price: i32,
|
||||
owner_id: i32,
|
||||
}
|
||||
|
||||
#[derive(Insertable)]
|
||||
#[table_name = "shop"]
|
||||
struct NewItem<'a> {
|
||||
name: &'a str,
|
||||
base_price: i32,
|
||||
}
|
||||
8
lootalot_db/src/models/mod.rs
Normal file
8
lootalot_db/src/models/mod.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
pub mod claim;
|
||||
pub mod item;
|
||||
pub mod player;
|
||||
pub mod history;
|
||||
|
||||
pub use claim::Claim;
|
||||
pub use item::Item;
|
||||
pub use player::{Player, Wealth};
|
||||
126
lootalot_db/src/models/player/mod.rs
Normal file
126
lootalot_db/src/models/player/mod.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
use crate::schema::players;
|
||||
use crate::{DbConnection, QueryResult, Update, UpdateResult};
|
||||
use diesel::prelude::*;
|
||||
|
||||
mod notification;
|
||||
pub mod wealth;
|
||||
pub use wealth::Wealth;
|
||||
|
||||
/// Representation of a player in database
|
||||
#[derive(Identifiable, Queryable, Serialize, Deserialize, Debug)]
|
||||
pub struct Player {
|
||||
/// DB Identitier
|
||||
pub id: i32,
|
||||
/// Full name of the character
|
||||
pub name: String,
|
||||
/// Amount of gold coins owed to the group.
|
||||
/// Taking a looted items will increase the debt by it's sell value
|
||||
pub debt: i32,
|
||||
/// Count of copper pieces
|
||||
pub cp: i32,
|
||||
/// Count of silver pieces
|
||||
pub sp: i32,
|
||||
/// Count of gold pieces
|
||||
pub gp: i32,
|
||||
/// Count of platinum pieces
|
||||
pub pp: i32,
|
||||
}
|
||||
|
||||
/// Manager for players
|
||||
pub struct Players<'q>(pub &'q DbConnection);
|
||||
|
||||
impl<'q> Players<'q> {
|
||||
/// Get all players from database
|
||||
pub fn all(&self) -> QueryResult<Vec<Player>> {
|
||||
players::table.load(self.0)
|
||||
}
|
||||
|
||||
/// Get all non-group players
|
||||
pub fn all_except_group(&self) -> QueryResult<Vec<Player>> {
|
||||
use diesel::dsl::not;
|
||||
players::table.filter(not(players::id.eq(0))).load(self.0)
|
||||
}
|
||||
|
||||
/// Find a player by id
|
||||
pub fn find(&self, id: i32) -> QueryResult<Player> {
|
||||
players::table.find(id).first(self.0)
|
||||
}
|
||||
|
||||
/// Add a new player with name and starting wealth
|
||||
pub fn add(&self, name: &str, wealth: f64) -> QueryResult<Player> {
|
||||
diesel::insert_into(players::table)
|
||||
.values(&NewPlayer::create(name, wealth))
|
||||
.execute(self.0)?;
|
||||
players::table.order(players::dsl::id.desc()).first(self.0)
|
||||
}
|
||||
|
||||
/// Notify all players of an event
|
||||
pub fn notifiy_all(&self, text: &str) -> QueryResult<()> {
|
||||
for id in self.all()?.into_iter().map(|p| p.id) {
|
||||
self.notify(id, text);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Notify a single player of an event
|
||||
pub fn notify(&self, id: i32, text: &str) -> QueryResult<()> {
|
||||
let _ = notification::Notification::add(self.0, id, text)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper for action of a single player
|
||||
pub struct AsPlayer<'q>(pub &'q DbConnection, pub i32);
|
||||
|
||||
impl<'q> AsPlayer<'q> {
|
||||
/// Fetch notifications for this player
|
||||
pub fn notifications(&self) -> QueryResult<Vec<String>> {
|
||||
notification::pop_all_for(self.1, self.0)
|
||||
}
|
||||
/// Updates this player's wealth, returning the difference
|
||||
pub fn update_wealth(&self, value_in_gp: f64) -> UpdateResult {
|
||||
use crate::schema::players::dsl::*;
|
||||
let current_wealth = players
|
||||
.find(self.1)
|
||||
.select((cp, sp, gp, pp))
|
||||
.first::<Wealth>(self.0)?;
|
||||
let updated_wealth = Wealth::from_gp(current_wealth.to_gp() + value_in_gp);
|
||||
diesel::update(players)
|
||||
.filter(id.eq(self.1))
|
||||
.set(&updated_wealth)
|
||||
.execute(self.0)?;
|
||||
Ok(Update::Wealth(updated_wealth - current_wealth))
|
||||
}
|
||||
|
||||
/// Updates this player's debt
|
||||
pub fn update_debt(&self, value_in_gp: i32) -> QueryResult<()> {
|
||||
diesel::update(players::table.find(self.1))
|
||||
.set(players::dsl::debt.eq(players::dsl::debt + value_in_gp))
|
||||
.execute(self.0)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Representation of a new player record
|
||||
#[derive(Insertable)]
|
||||
#[table_name = "players"]
|
||||
struct NewPlayer<'a> {
|
||||
name: &'a str,
|
||||
cp: i32,
|
||||
sp: i32,
|
||||
gp: i32,
|
||||
pp: i32,
|
||||
}
|
||||
|
||||
impl<'a> NewPlayer<'a> {
|
||||
fn create(name: &'a str, wealth_in_gp: f64) -> Self {
|
||||
let (cp, sp, gp, pp) = Wealth::from_gp(wealth_in_gp).as_tuple();
|
||||
Self {
|
||||
name,
|
||||
cp,
|
||||
sp,
|
||||
gp,
|
||||
pp,
|
||||
}
|
||||
}
|
||||
}
|
||||
44
lootalot_db/src/models/player/notification.rs
Normal file
44
lootalot_db/src/models/player/notification.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use diesel::prelude::*;
|
||||
use crate::{
|
||||
DbConnection,
|
||||
schema::notifications,
|
||||
models::player::Player,
|
||||
};
|
||||
|
||||
|
||||
/// Pops all notification for a player, deleting the database entities
|
||||
pub(super) fn pop_all_for(id: i32, conn: &DbConnection) -> QueryResult<Vec<String>> {
|
||||
let select = notifications::table.filter(notifications::dsl::player_id.eq(id));
|
||||
let popped = select.load(conn)?;
|
||||
diesel::delete(select).execute(conn)?;
|
||||
Ok(popped.into_iter().map(|n: Notification| n.text).collect())
|
||||
}
|
||||
|
||||
#[derive(Identifiable, Queryable, Associations, Serialize, Debug)]
|
||||
#[belongs_to(Player)]
|
||||
pub(super) struct Notification {
|
||||
pub id: i32,
|
||||
pub player_id: i32,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Notification {
|
||||
pub(super) fn add<'a, S: Into<&'a str>>(conn: &DbConnection, id: i32, text: S) -> QueryResult<Notification> {
|
||||
diesel::insert_into(notifications::table)
|
||||
.values(&NewNotification {
|
||||
player_id: id,
|
||||
text: text.into(),
|
||||
})
|
||||
.execute(conn)?;
|
||||
notifications::table
|
||||
.order(notifications::dsl::id.desc())
|
||||
.first(conn)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Insertable)]
|
||||
#[table_name="notifications"]
|
||||
struct NewNotification<'a> {
|
||||
player_id: i32,
|
||||
text: &'a str,
|
||||
}
|
||||
157
lootalot_db/src/models/player/wealth.rs
Normal file
157
lootalot_db/src/models/player/wealth.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
use crate::schema::players;
|
||||
|
||||
/// Unpack a floating value of 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: f64) -> (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, Serialize, Deserialize, PartialEq, Copy, Clone, 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: f64) -> 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: 5, sp: 8, cp: 4};
|
||||
/// assert_eq!(wealth.to_gp(), 405.84);
|
||||
/// ```
|
||||
pub fn to_gp(&self) -> f64 {
|
||||
let i = self.pp * 100 + self.gp;
|
||||
let f = (self.sp * 10 + self.cp) as f64 / 100.0;
|
||||
i as f64 + 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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl std::ops::Sub for Wealth {
|
||||
type Output = Self;
|
||||
/// What needs to be added to 'other' so that
|
||||
/// the result equals 'self'
|
||||
fn sub(self, other: Self) -> Self {
|
||||
Wealth::from_gp(self.to_gp() - other.to_gp())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Add for Wealth {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, other: Self) -> Self {
|
||||
Wealth::from_gp(self.to_gp() + other.to_gp())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_unpack_gold_values() {
|
||||
use super::unpack_gold_value;
|
||||
let test_values = [
|
||||
(0.01, (1, 0, 0, 0)),
|
||||
(0.1, (0, 1, 0, 0)),
|
||||
(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)),
|
||||
(141805.9, (0, 9, 5, 1418)),
|
||||
(123141805.9, (0, 9, 5, 1231418)),
|
||||
(-8090.20, (0, -2, -90, -80)),
|
||||
];
|
||||
|
||||
for (tested, expected) in test_values.into_iter() {
|
||||
assert_eq!(unpack_gold_value(*tested), *expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_negative_wealth() {
|
||||
use super::Wealth;
|
||||
|
||||
assert_eq!(
|
||||
Wealth{ cp: 3, sp: 2, gp: 1, pp: 0 } + Wealth{ cp: -8, pp: 0, sp: 0, gp: 0 },
|
||||
Wealth::from_gp(1.23 - 0.08)
|
||||
)
|
||||
|
||||
}
|
||||
#[test]
|
||||
fn test_negative_wealth_inverse() {
|
||||
use super::Wealth;
|
||||
|
||||
assert_eq!(
|
||||
(Wealth{ cp: 3, sp: 2, gp: 1, pp: 0 } + Wealth{ cp: -8, pp: 0, sp: 0, gp: 0 }).to_gp(),
|
||||
1.23 - 0.08
|
||||
)
|
||||
|
||||
}
|
||||
#[test]
|
||||
fn test_diff_adding() {
|
||||
use super::Wealth;
|
||||
|
||||
// Let say we add 0.08 gp
|
||||
// 1.23 + 0.08 gold is 1.31, diff is cp: -2, sp: +1
|
||||
let old = Wealth::from_gp(1.23);
|
||||
let new = Wealth::from_gp(1.31);
|
||||
let diff = new - old;
|
||||
assert_eq!(diff.as_tuple(), (-2, 1, 0, 0));
|
||||
assert_eq!(diff.to_gp(), 0.08);
|
||||
assert_eq!(new - diff, old);
|
||||
|
||||
}
|
||||
#[test]
|
||||
fn test_diff_subbing() {
|
||||
use super::Wealth;
|
||||
|
||||
// Let say we sub 0.08 gp
|
||||
// 1.31 - 0.08 gold is 1.23, diff is cp: +2, sp: -1
|
||||
let old = Wealth::from_gp(1.31);
|
||||
let new = Wealth::from_gp(1.23);
|
||||
let diff = new - old;
|
||||
assert_eq!(diff.as_tuple(), (2, -1, 0, 0));
|
||||
assert_eq!(diff.to_gp(), -0.08);
|
||||
assert_eq!(new - diff, old);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,25 @@
|
||||
table! {
|
||||
claims (id) {
|
||||
id -> Integer,
|
||||
player_id -> Integer,
|
||||
loot_id -> Integer,
|
||||
resolve -> Integer,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
history (id) {
|
||||
id -> Integer,
|
||||
player_id -> Integer,
|
||||
event_date -> Timestamp,
|
||||
text -> Text,
|
||||
updates -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
items (id) {
|
||||
id -> Nullable<Integer>,
|
||||
id -> Integer,
|
||||
name -> Text,
|
||||
base_price -> Integer,
|
||||
}
|
||||
@@ -8,30 +27,53 @@ table! {
|
||||
|
||||
table! {
|
||||
looted (id) {
|
||||
id -> Nullable<Integer>,
|
||||
id -> Integer,
|
||||
name -> Text,
|
||||
base_price -> Integer,
|
||||
owner_id -> Integer,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
notifications (id) {
|
||||
id -> Integer,
|
||||
player_id -> Integer,
|
||||
item_id -> Integer,
|
||||
acquired_date -> Nullable<Date>,
|
||||
text -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
players (id) {
|
||||
id -> Nullable<Integer>,
|
||||
id -> Integer,
|
||||
name -> Text,
|
||||
debt -> Nullable<Integer>,
|
||||
cp -> Nullable<Integer>,
|
||||
sp -> Nullable<Integer>,
|
||||
gp -> Nullable<Integer>,
|
||||
pp -> Nullable<Integer>,
|
||||
debt -> Integer,
|
||||
cp -> Integer,
|
||||
sp -> Integer,
|
||||
gp -> Integer,
|
||||
pp -> Integer,
|
||||
}
|
||||
}
|
||||
|
||||
joinable!(looted -> items (item_id));
|
||||
joinable!(looted -> players (player_id));
|
||||
table! {
|
||||
shop (id) {
|
||||
id -> Integer,
|
||||
name -> Text,
|
||||
base_price -> Integer,
|
||||
}
|
||||
}
|
||||
|
||||
joinable!(claims -> looted (loot_id));
|
||||
joinable!(claims -> players (player_id));
|
||||
joinable!(history -> players (player_id));
|
||||
joinable!(looted -> players (owner_id));
|
||||
joinable!(notifications -> players (player_id));
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
claims,
|
||||
history,
|
||||
items,
|
||||
looted,
|
||||
notifications,
|
||||
players,
|
||||
shop,
|
||||
);
|
||||
|
||||
21
lootalot_front/.gitignore
vendored
21
lootalot_front/.gitignore
vendored
@@ -1,21 +0,0 @@
|
||||
.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?
|
||||
@@ -1,29 +0,0 @@
|
||||
# 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/).
|
||||
@@ -1,5 +0,0 @@
|
||||
module.exports = {
|
||||
presets: [
|
||||
'@vue/app'
|
||||
]
|
||||
}
|
||||
12252
lootalot_front/package-lock.json
generated
12252
lootalot_front/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,51 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
},
|
||||
"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",
|
||||
"babel-eslint": "^10.0.1",
|
||||
"eslint": "^5.16.0",
|
||||
"eslint-plugin-vue": "^5.0.0",
|
||||
"node-sass": "^4.12.0",
|
||||
"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"
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
Before Width: | Height: | Size: 4.2 KiB |
@@ -1,20 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,9 +0,0 @@
|
||||
@charset "utf-8";
|
||||
|
||||
$brown: #757763;
|
||||
|
||||
$primary: $brown;
|
||||
|
||||
$button-padding-horizontal: 1em;
|
||||
|
||||
@import "../node_modules/bulma/bulma.sass";
|
||||
@@ -1,101 +0,0 @@
|
||||
<template>
|
||||
<main id="app" class="section">
|
||||
<section id="content" class="columns is-desktop">
|
||||
<Player></Player>
|
||||
<div class="column">
|
||||
<GroupChest></GroupChest>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import Player from './components/Player.vue'
|
||||
import GroupChest from './components/GroupChest.vue'
|
||||
|
||||
export const store = {
|
||||
debug: true,
|
||||
state: {
|
||||
player_id: 0,
|
||||
player_list: [
|
||||
{id: 0, name: "Groupe", wealth: [0,0,0,0], debt: 0},
|
||||
{id: 1, name: "Lomion", wealth: [0,0,0,0], debt: 0},
|
||||
{id: 4, name: "Oilosse", wealth: [0,0,0,0], debt: 0},
|
||||
{id: 3, name: "Fefi", wealth: [0,0,0,0], debt: 0},
|
||||
],
|
||||
show_player_chest: false,
|
||||
requests: { // TEST: must be initialised with players ids
|
||||
0: [], 1: [], 4: [], 3: []
|
||||
},
|
||||
},
|
||||
setActivePlayer (newPlayerId) {
|
||||
if (this.debug) console.log('setActivePlayer to ', newPlayerId)
|
||||
this.state.player_id = newPlayerId
|
||||
document.cookie = `player_id=${newPlayerId};`;
|
||||
},
|
||||
switchPlayerChestVisibility () {
|
||||
if (this.debug) console.log('switchPlayerChestVisibility', !this.state.show_player_chest)
|
||||
this.state.show_player_chest = !this.state.show_player_chest
|
||||
},
|
||||
putRequest (itemId) {
|
||||
const playerId = this.state.player_id
|
||||
if (this.debug) console.log('newRequest from', playerId, 'on', itemId)
|
||||
this.state.requests[playerId].push(itemId);
|
||||
},
|
||||
cancelRequest(itemId) {
|
||||
const playerId = this.state.player_id
|
||||
if (this.debug) console.log('cancelRequest of', playerId, 'on', itemId)
|
||||
var idx = this.state.requests[playerId].indexOf(itemId);
|
||||
if (idx > -1) {
|
||||
this.state.requests[playerId].splice(idx, 1);
|
||||
} else {
|
||||
if (this.debug) console.log("cancel a non-existent request")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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',
|
||||
components: {
|
||||
Player,
|
||||
GroupChest
|
||||
},
|
||||
created () {
|
||||
const cookie = getCookie("player_id");
|
||||
if (cookie == "") {
|
||||
return;
|
||||
} else {
|
||||
var newPlayerId = Number(cookie);
|
||||
console.log("initiated with id", newPlayerId);
|
||||
store.setActivePlayer(newPlayerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
#app {
|
||||
font-family: 'Avenir', Helvetica, Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
text-align: center;
|
||||
color: #2c3e50;
|
||||
margin-top: 60px;
|
||||
}
|
||||
</style>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 6.7 KiB |
@@ -1,136 +0,0 @@
|
||||
<template>
|
||||
<div class="container">
|
||||
<button v-if="canAdd"
|
||||
class="button is-medium is-info"
|
||||
@click="is_adding = true"
|
||||
v-show="!is_adding">
|
||||
Nouveau loot
|
||||
</button>
|
||||
<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.sell_value}} GP
|
||||
</label>
|
||||
</div>
|
||||
<PercentInput></PercentInput>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { store } from '../App.vue'
|
||||
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: store.state,
|
||||
content: [
|
||||
{id: 10, name: "Épée longue +2 acérée",
|
||||
sell_value: 15000 },
|
||||
{id: 5, name: "Ceinture de force +6",
|
||||
sell_value: 80000 },
|
||||
],
|
||||
is_selling: false,
|
||||
is_adding: false,
|
||||
sell_selected: [],
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
// Can the active user sell items from this chest ?
|
||||
canSell () {
|
||||
return this.player == this.app_state.player_id;
|
||||
},
|
||||
totalSellValue () {
|
||||
const selected = this.sell_selected;
|
||||
var value = this.content
|
||||
.filter(item => selected.includes(item.id))
|
||||
.map(item => item.sell_value)
|
||||
.reduce((total,value) => total + value, 0);
|
||||
|
||||
return value;
|
||||
},
|
||||
// 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);
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.table td, .table th { vertical-align: middle; }
|
||||
</style>
|
||||
@@ -1,22 +0,0 @@
|
||||
<template>
|
||||
<section id="main" class="section">
|
||||
<div id="main-heading" class="notification is-dark is-paddingless 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>
|
||||
<Chest :player="0"></Chest>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import Chest from './Chest.vue'
|
||||
|
||||
export default {
|
||||
components: { Chest },
|
||||
data () { return {}; }
|
||||
}
|
||||
</script>
|
||||
@@ -1,93 +0,0 @@
|
||||
<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>
|
||||
@@ -1,40 +0,0 @@
|
||||
<template>
|
||||
<div class="card">
|
||||
<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">
|
||||
<a class="card-footer-item">Confirmer</a>
|
||||
<a @click="onClose" class="card-footer-item">Annuler</a>
|
||||
</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>
|
||||
@@ -1,28 +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',
|
||||
// Do the conversion if valid
|
||||
this.has_error ? newValue : Number(newValue)
|
||||
);
|
||||
}
|
||||
},
|
||||
}
|
||||
</script>
|
||||
@@ -1,28 +0,0 @@
|
||||
<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>
|
||||
@@ -1,157 +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">{{ 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">
|
||||
<a v-for="(p,i) in 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="player.wealth"
|
||||
:edit="edit_wealth"
|
||||
@updated="edit_wealth = !edit_wealth">
|
||||
</Wealth>
|
||||
<p class="notification is-warning" v-show="!playerIsGroup">Dette : {{ player.debt }}gp</p>
|
||||
</div>
|
||||
<footer class="card-footer">
|
||||
<a @click="switchPlayerChestVisibility" v-show="!playerIsGroup"
|
||||
href="#" class="card-footer-item is-dark">
|
||||
Coffre
|
||||
</a>
|
||||
<a @click="edit_wealth = !edit_wealth" href="#" class="card-footer-item">Argent</a>
|
||||
<a href="#" class="card-footer-item disabled">Historique</a>
|
||||
</footer>
|
||||
</div>
|
||||
<div class="card" v-show="state.show_player_chest" style="margin-top: 1em;">
|
||||
<div class="card-content">
|
||||
<Chest :player="state.player_id"></Chest>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { store } from '../App.vue'
|
||||
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 {
|
||||
state: store.state,
|
||||
show_dropdown: false,
|
||||
edit_wealth: false,
|
||||
handleOutsideClick: null,
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
player () {
|
||||
const id = this.state.player_id;
|
||||
const idx = this.state.player_list.findIndex(p => p.id == id);
|
||||
return this.state.player_list[idx];
|
||||
},
|
||||
name () {
|
||||
return this.player.name;
|
||||
},
|
||||
// Check if the active player is the special 'Group' player
|
||||
playerIsGroup () {
|
||||
return this.state.player_id == 0;
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
switchPlayerChestVisibility () {
|
||||
store.switchPlayerChestVisibility();
|
||||
},
|
||||
hidePlayerChest () {
|
||||
if (this.state.show_player_chest) {
|
||||
this.switchPlayerChestVisibility();
|
||||
}
|
||||
},
|
||||
setActivePlayer (playerIdx) {
|
||||
const newId = this.state.player_list[playerIdx].id;
|
||||
store.setActivePlayer(newId);
|
||||
if (newId == 0) { this.hidePlayerChest() }
|
||||
this.player.name = this.state.player_list[playerIdx].name
|
||||
},
|
||||
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>
|
||||
</style>
|
||||
@@ -1,82 +0,0 @@
|
||||
<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 { store } from '../App.vue'
|
||||
export default {
|
||||
props: ["item"],
|
||||
data () {
|
||||
return {
|
||||
state: store.state,
|
||||
_requested: false, // Dummy state
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
// Check if item is requested by active player
|
||||
isRequested () {
|
||||
const reqs = this.state.requests[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.requests;
|
||||
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 () {
|
||||
store.putRequest(this.item)
|
||||
},
|
||||
// The active player withdraws his request
|
||||
cancelRequest () {
|
||||
store.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>
|
||||
@@ -1,83 +0,0 @@
|
||||
<template>
|
||||
<div class="box is-primary">
|
||||
<span class="icon is-large">
|
||||
<i class="fas fa-2x fa-piggy-bank"></i>
|
||||
</span>
|
||||
<nav class="columns is-mobile is-multiline">
|
||||
<div class="column">
|
||||
<p class="heading">PC</p>
|
||||
<p class="is-size-4">{{ wealth[0] }}</p>
|
||||
</div>
|
||||
<div class="column">
|
||||
<p class="heading">PA</p>
|
||||
<p class="is-size-4">{{ wealth[1] }}</p>
|
||||
</div>
|
||||
<div class="column">
|
||||
<p class="heading">PO</p>
|
||||
<p class="is-size-4">{{ wealth[2] }}</p>
|
||||
</div>
|
||||
<div class="column">
|
||||
<p class="heading">PP</p>
|
||||
<p class="is-size-4">{{ wealth[3] }}</p>
|
||||
</div>
|
||||
</nav>
|
||||
<div v-if="edit"> <!-- or v-show ? -->
|
||||
<nav class="columns is-1 is-variable is-mobile">
|
||||
<template v-for="i in 4">
|
||||
<div :key="`input-col-${i}`" class="column">
|
||||
<NumberInput v-model="edit_values[i - 1]"></NumberInput>
|
||||
</div>
|
||||
</template>
|
||||
</nav>
|
||||
<nav class="columns is-mobile">
|
||||
<div class="column is-4 is-offset-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-4">
|
||||
<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 NumberInput from './NumberInput.vue'
|
||||
export default {
|
||||
components: { NumberInput },
|
||||
props: ["wealth", "edit"],
|
||||
data () {
|
||||
return {
|
||||
edit_values: [0,0,0,0],
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
updateWealth (op) {
|
||||
const values = this.edit_values;
|
||||
// Is it optimal, considering NumberInput already validates numbers ?
|
||||
// Check that all fields are valid numbers
|
||||
const success = values
|
||||
.map(v => !isNaN(v))
|
||||
.reduce(
|
||||
(t,v) => t && v,
|
||||
true);
|
||||
if (success) {
|
||||
console.log('updated', op, values);
|
||||
this.$emit('updated');
|
||||
this.resetValues();
|
||||
} else {
|
||||
console.log('correct errors');
|
||||
}
|
||||
},
|
||||
resetValues () {
|
||||
this.edit_values.fill(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -1,8 +0,0 @@
|
||||
import Vue from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
Vue.config.productionTip = false
|
||||
|
||||
new Vue({
|
||||
render: h => h(App),
|
||||
}).$mount('#app')
|
||||
323
src/api.rs
Normal file
323
src/api.rs
Normal file
@@ -0,0 +1,323 @@
|
||||
use diesel::connection::Connection;
|
||||
use lootalot_db::{self as db, DbConnection, Update, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub type IdList = Vec<i32>;
|
||||
pub type ItemListWithMods = Vec<(i32, Option<f64>)>;
|
||||
pub type ItemList = Vec<db::Item>;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct BuySellParams {
|
||||
pub items: ItemListWithMods,
|
||||
players: Option<IdList>,
|
||||
global_mod: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct NewGroupLoot {
|
||||
source_name: String,
|
||||
// claims_limit_date: String
|
||||
pub items: ItemList,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct NewPlayer {
|
||||
name : String,
|
||||
wealth : f64,
|
||||
}
|
||||
|
||||
/// A generic response for all queries
|
||||
#[derive(Serialize, Debug, Default)]
|
||||
pub struct ApiResponse {
|
||||
/// The value requested, if any
|
||||
pub value: Option<Value>,
|
||||
/// A text to notify user, if relevant
|
||||
pub notification: Option<String>,
|
||||
/// A list of updates, if any
|
||||
pub updates: Option<Vec<Update>>,
|
||||
/// A text describing errors, if any
|
||||
pub errors: Option<String>,
|
||||
}
|
||||
|
||||
impl ApiResponse {
|
||||
fn push_update(&mut self, update: db::Update) {
|
||||
if let Some(v) = self.updates.as_mut() {
|
||||
v.push(update);
|
||||
} else {
|
||||
self.updates = Some(vec![update]);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_error<S: Into<String>>(&mut self, error: S) {
|
||||
if let Some(errors) = self.errors.as_mut() {
|
||||
*errors = format!("{}\n{}", errors, error.into());
|
||||
} else {
|
||||
self.errors = Some(error.into())
|
||||
}
|
||||
}
|
||||
|
||||
fn set_value(&mut self, value: db::Value) {
|
||||
self.value = Some(value);
|
||||
}
|
||||
|
||||
fn notify<S: Into<String>>(&mut self, text: S) {
|
||||
self.notification = Some(text.into());
|
||||
}
|
||||
}
|
||||
|
||||
pub enum ApiError {
|
||||
DieselError(diesel::result::Error),
|
||||
InvalidAction(String),
|
||||
}
|
||||
|
||||
/// Every allowed queries on the database
|
||||
pub enum ApiActions {
|
||||
// Application level
|
||||
FetchPlayers,
|
||||
FetchInventory,
|
||||
FetchShopInventory,
|
||||
FetchClaims,
|
||||
CheckItemList(Vec<String>),
|
||||
// Player level
|
||||
FetchPlayer(i32),
|
||||
FetchPlayerClaims(i32),
|
||||
FetchNotifications(i32),
|
||||
FetchLoot(i32),
|
||||
UpdateWealth(i32, f64),
|
||||
BuyItems(i32, BuySellParams),
|
||||
SellItems(i32, BuySellParams),
|
||||
ClaimItems(i32, IdList),
|
||||
UndoLastAction(i32),
|
||||
// Group level
|
||||
AddLoot(NewGroupLoot),
|
||||
// Admin level
|
||||
RefreshShopInventory(ItemList),
|
||||
AddPlayer(NewPlayer),
|
||||
//AddInventoryItem(pub String, pub i32),
|
||||
//ResolveClaims,
|
||||
//SetClaimsTimeout(pub i32),
|
||||
}
|
||||
|
||||
pub fn execute(
|
||||
conn: &DbConnection,
|
||||
query: ApiActions,
|
||||
) -> Result<ApiResponse, diesel::result::Error> {
|
||||
let mut response = ApiResponse::default();
|
||||
// Return an Option<String> that describes what happened.
|
||||
// If there is some value, store the actions in db so that it can be reversed.
|
||||
let action_text: Option<(i32, &str)> = match query {
|
||||
ApiActions::CheckItemList(names) => {
|
||||
let (items, errors) = {
|
||||
let mut found = Vec::new();
|
||||
let mut errors = String::new();
|
||||
let items = db::Inventory(conn).all()?;
|
||||
for name in &names {
|
||||
if let Some(item) = items.iter().filter(|i| &i.name == name).take(1).next() {
|
||||
found.push(item.clone())
|
||||
} else {
|
||||
errors.push_str(&format!("{},\n", name));
|
||||
}
|
||||
}
|
||||
(found, errors)
|
||||
};
|
||||
|
||||
response.set_value(Value::ItemList(items));
|
||||
response.push_error(errors);
|
||||
dbg!(&names, &response);
|
||||
None
|
||||
}
|
||||
ApiActions::FetchPlayers => {
|
||||
response.set_value(Value::PlayerList(db::Players(conn).all_except_group()?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchInventory => {
|
||||
response.set_value(Value::ItemList(db::Inventory(conn).all()?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchShopInventory => {
|
||||
response.set_value(Value::ItemList(db::Shop(conn).all()?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchClaims => {
|
||||
response.set_value(Value::ClaimList(db::Claims(conn).all()?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchPlayer(id) => {
|
||||
response.set_value(Value::Player(db::Players(conn).find(id)?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchPlayerClaims(id) => {
|
||||
response.set_value(Value::ClaimList(db::Claims(conn).by_player(id)?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchNotifications(id) => {
|
||||
response.set_value(Value::Notifications(
|
||||
db::AsPlayer(conn, id).notifications()?,
|
||||
));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchLoot(id) => {
|
||||
response.set_value(Value::ItemList(db::LootManager(conn, id).all()?));
|
||||
None
|
||||
}
|
||||
ApiActions::UpdateWealth(id, amount) => {
|
||||
response.push_update(db::AsPlayer(conn, id).update_wealth(amount)?);
|
||||
response.notify(format!("Mis à jour ({}po)!", amount));
|
||||
Some((id, "Argent mis à jour"))
|
||||
}
|
||||
ApiActions::BuyItems(id, params) => {
|
||||
// TODO: check that player has enough money !
|
||||
let has_enough_gold = true;
|
||||
|
||||
if has_enough_gold {
|
||||
let mut gains: Vec<db::Wealth> = Vec::with_capacity(params.items.len());
|
||||
for (item_id, price_mod) in params.items.into_iter() {
|
||||
if let Ok((item, diff)) = db::buy_item_from_shop(conn, id, item_id, price_mod) {
|
||||
response.push_update(item);
|
||||
gains.push(diff);
|
||||
} else {
|
||||
response.push_error(format!("Error adding {}", item_id));
|
||||
}
|
||||
}
|
||||
let added_items = gains.len();
|
||||
let total_amount = gains
|
||||
.into_iter()
|
||||
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
||||
response.notify(format!(
|
||||
"{} objets achetés pour {}po",
|
||||
added_items,
|
||||
total_amount.to_gp()
|
||||
));
|
||||
response.push_update(Update::Wealth(total_amount));
|
||||
Some((id, "Achat d'objets"))
|
||||
} else {
|
||||
response.push_error("Vous n'avez pas assez d'argent !");
|
||||
None
|
||||
}
|
||||
}
|
||||
// Behavior differs if player is group or regular.
|
||||
// Group sells item like players then split the total amount among players.
|
||||
ApiActions::SellItems(id, params) => {
|
||||
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
|
||||
let mut gains: Vec<db::Wealth> = Vec::with_capacity(params.items.len());
|
||||
for (loot_id, price_mod) in params.items.iter() {
|
||||
if let Ok((deleted, diff)) =
|
||||
db::sell_item_transaction(conn, id, *loot_id, *price_mod)
|
||||
{
|
||||
response.push_update(deleted);
|
||||
gains.push(diff);
|
||||
} else {
|
||||
response
|
||||
.push_error(format!("Erreur lors de la vente (loot_id : {})", loot_id));
|
||||
}
|
||||
}
|
||||
let sold_items = gains.len();
|
||||
let total_amount = gains
|
||||
.into_iter()
|
||||
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
||||
match id {
|
||||
0 => {
|
||||
let players = params.players.unwrap_or_default();
|
||||
if let Update::Wealth(shared) =
|
||||
db::split_and_share(conn, total_amount.to_gp() as i32, players)?
|
||||
{
|
||||
response.notify(format!(
|
||||
"Les objets ont été vendus, les joueurs ont reçu (au total) {} po",
|
||||
shared.to_gp()
|
||||
));
|
||||
response.push_update(Update::Wealth(total_amount - shared));
|
||||
};
|
||||
}
|
||||
_ => {
|
||||
response.notify(format!(
|
||||
"{} objet(s) vendu(s) pour {} po",
|
||||
sold_items,
|
||||
total_amount.to_gp()
|
||||
));
|
||||
response.push_update(Update::Wealth(total_amount));
|
||||
}
|
||||
}
|
||||
Ok(Some((id, "Vente d'objets")))
|
||||
})?
|
||||
}
|
||||
ApiActions::ClaimItems(id, items) => {
|
||||
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
|
||||
let current_claims: HashSet<i32> = db::Claims(conn)
|
||||
.all()?
|
||||
.iter()
|
||||
.filter(|c| c.player_id == id)
|
||||
.map(|c| c.loot_id)
|
||||
.collect();
|
||||
let new_claims: HashSet<i32> = items.into_iter().collect();
|
||||
// Claims to delete
|
||||
for item in current_claims.difference(&new_claims) {
|
||||
response.push_update(db::Claims(conn).remove(id, *item)?);
|
||||
}
|
||||
// Claims to add
|
||||
for item in new_claims.difference(¤t_claims) {
|
||||
response.push_update(db::Claims(conn).add(id, *item)?);
|
||||
}
|
||||
Ok(None)
|
||||
})?
|
||||
}
|
||||
ApiActions::UndoLastAction(id) => {
|
||||
if let Ok(event) = db::models::history::get_last_of_player(conn, id) {
|
||||
let name = String::from(event.name());
|
||||
for undone in event.undo(conn)?.into_inner().into_iter() {
|
||||
response.push_update(undone);
|
||||
}
|
||||
response.notify(format!("'{}' annulé(e)", name));
|
||||
} else {
|
||||
response.push_error("Aucune action trouvée")
|
||||
};
|
||||
None
|
||||
}
|
||||
// Group actions
|
||||
ApiActions::AddLoot(data) => {
|
||||
let mut added_items = 0;
|
||||
for item in data.items.into_iter() {
|
||||
if let Ok(added) = db::LootManager(conn, 0).add_from(&item) {
|
||||
response.push_update(added);
|
||||
added_items += 1;
|
||||
} else {
|
||||
response.push_error(format!("Error adding {:?}", item));
|
||||
}
|
||||
}
|
||||
response.notify(format!("{} objets lootés !", added_items));
|
||||
// Notify players through persistent notifications
|
||||
if let Err(e) = db::Players(conn)
|
||||
.notifiy_all("De nouveaux objets ont été ajoutés au coffre de groupe !")
|
||||
{
|
||||
response.push_error(format!("Erreur durant la notification : {:?}", e));
|
||||
};
|
||||
Some((0, "Nouveau loot"))
|
||||
}
|
||||
// Admin actions
|
||||
ApiActions::RefreshShopInventory(items) => {
|
||||
db::Shop(conn).replace_list(items)?;
|
||||
response.notify("Inventaire du marchand renouvelé !");
|
||||
None
|
||||
}
|
||||
ApiActions::AddPlayer(data) => {
|
||||
db::Players(conn).add(&data.name, data.wealth)?;
|
||||
response.notify("Joueur ajouté !");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// Store the event if it can be undone.
|
||||
dbg!(&action_text);
|
||||
if let Some((id, text)) = action_text {
|
||||
db::models::history::insert_event(
|
||||
conn,
|
||||
id,
|
||||
text,
|
||||
response
|
||||
.updates
|
||||
.as_ref()
|
||||
.expect("there should be updates in here !"),
|
||||
)?;
|
||||
}
|
||||
// match _action_text -> Save updates in DB
|
||||
Ok(response)
|
||||
}
|
||||
16
src/main.rs
16
src/main.rs
@@ -1,5 +1,19 @@
|
||||
extern crate actix_web;
|
||||
extern crate dotenv;
|
||||
extern crate env_logger;
|
||||
extern crate lootalot_db;
|
||||
#[macro_use] extern crate serde;
|
||||
|
||||
mod server;
|
||||
mod api;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
325
src/server.rs
Normal file
325
src/server.rs
Normal file
@@ -0,0 +1,325 @@
|
||||
use actix_cors::Cors;
|
||||
use actix_files as fs;
|
||||
use actix_identity::{CookieIdentityPolicy, Identity, IdentityService, RequestIdentity};
|
||||
use actix_service::{Service, Transform};
|
||||
use actix_web::{
|
||||
dev::{ServiceRequest, ServiceResponse},
|
||||
http::{header, StatusCode},
|
||||
middleware, web, App, Error, HttpResponse, HttpServer,
|
||||
};
|
||||
use futures::{
|
||||
future::{ok, Either, FutureResult},
|
||||
Future,
|
||||
};
|
||||
use serde_json;
|
||||
use std::env;
|
||||
|
||||
use crate::api;
|
||||
use lootalot_db as db;
|
||||
|
||||
type AppPool = web::Data<db::Pool>;
|
||||
type PlayerId = web::Path<i32>;
|
||||
type ItemId = web::Json<i32>;
|
||||
type IdList = web::Json<api::IdList>;
|
||||
type BuySellParams = web::Json<api::BuySellParams>;
|
||||
type NewGroupLoot = web::Json<api::NewGroupLoot>;
|
||||
|
||||
type MaybeForbidden =
|
||||
actix_web::Either<Box<dyn Future<Item = HttpResponse, Error = Error>>, HttpResponse>;
|
||||
|
||||
/// Wraps call to the database query and convert its result as a async HttpResponse
|
||||
fn db_call(
|
||||
pool: AppPool,
|
||||
query: api::ApiActions,
|
||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||
let conn = pool.get().unwrap();
|
||||
web::block(move || api::execute(&conn, query)).then(|res| match res {
|
||||
Ok(r) => HttpResponse::Ok().json(r),
|
||||
Err(e) => {
|
||||
dbg!(&e);
|
||||
HttpResponse::InternalServerError().finish()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn restricted_to_group(id: i32, params: (AppPool, api::ApiActions)) -> MaybeForbidden {
|
||||
if id != 0 {
|
||||
actix_web::Either::B(HttpResponse::Forbidden().finish())
|
||||
} else {
|
||||
actix_web::Either::A(Box::new(db_call(params.0, params.1)))
|
||||
}
|
||||
}
|
||||
|
||||
struct RestrictedAccess;
|
||||
|
||||
impl<S, B> Transform<S> for RestrictedAccess
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
S::Future: 'static,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Transform = RestrictedAccessMiddleware<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(RestrictedAccessMiddleware { service })
|
||||
}
|
||||
}
|
||||
|
||||
struct RestrictedAccessMiddleware<S> {
|
||||
service: S,
|
||||
}
|
||||
|
||||
impl<S, B> Service for RestrictedAccessMiddleware<S>
|
||||
where
|
||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
S::Future: 'static,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = Error;
|
||||
type Future = Either<S::Future, FutureResult<Self::Response, Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||
let is_logged_in = req.get_identity().is_some();
|
||||
|
||||
if is_logged_in {
|
||||
Either::A(self.service.call(req))
|
||||
} else {
|
||||
Either::B(ok(
|
||||
req.into_response(HttpResponse::Forbidden().finish().into_body())
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn configure_api(config: &mut web::ServiceConfig) {
|
||||
use api::ApiActions as Q;
|
||||
config.service(
|
||||
web::scope("/api")
|
||||
.wrap(RestrictedAccess)
|
||||
.service(
|
||||
web::scope("/players")
|
||||
.service(
|
||||
web::resource("/")
|
||||
.route(web::get().to_async(|pool| db_call(pool, Q::FetchPlayers)))
|
||||
.route(web::post().to_async(
|
||||
|pool, player: web::Json<api::NewPlayer>| {
|
||||
db_call(pool, Q::AddPlayer(player.into_inner()))
|
||||
},
|
||||
)),
|
||||
) // List of players
|
||||
.service(
|
||||
web::scope("/{player_id}")
|
||||
.route(
|
||||
"/",
|
||||
web::get().to_async(|pool, player: PlayerId| {
|
||||
db_call(pool, Q::FetchPlayer(*player))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/notifications",
|
||||
web::get().to_async(|pool, player: PlayerId| {
|
||||
db_call(pool, Q::FetchNotifications(*player))
|
||||
}),
|
||||
)
|
||||
.service(
|
||||
web::resource("/claims")
|
||||
.route(web::get().to_async(|pool, player: PlayerId| {
|
||||
db_call(pool, Q::FetchPlayerClaims(*player))
|
||||
}))
|
||||
.route(web::post().to_async(
|
||||
|pool, (player, data): (PlayerId, IdList)| {
|
||||
db_call(pool, Q::ClaimItems(*player, data.into_inner()))
|
||||
},
|
||||
)),
|
||||
)
|
||||
.service(
|
||||
web::resource("/wealth")
|
||||
//.route(web::get().to_async(...))
|
||||
.route(web::put().to_async(
|
||||
|pool, (player, data): (PlayerId, web::Json<f64>)| {
|
||||
db_call(pool, Q::UpdateWealth(*player, *data))
|
||||
},
|
||||
)),
|
||||
)
|
||||
.service(
|
||||
web::resource("/loot")
|
||||
.route(web::get().to_async(|pool, player: PlayerId| {
|
||||
db_call(pool, Q::FetchLoot(*player))
|
||||
}))
|
||||
.route(web::put().to_async(
|
||||
move |pool, (player, data): (PlayerId, BuySellParams)| {
|
||||
db_call(pool, Q::BuyItems(*player, data.into_inner()))
|
||||
},
|
||||
))
|
||||
.route(web::post().to(
|
||||
move |pool, (player, data): (PlayerId, NewGroupLoot)| {
|
||||
restricted_to_group(
|
||||
*player,
|
||||
(pool, Q::AddLoot(data.into_inner())),
|
||||
)
|
||||
},
|
||||
))
|
||||
.route(web::delete().to_async(
|
||||
move |pool, (player, data): (PlayerId, BuySellParams)| {
|
||||
db_call(pool, Q::SellItems(*player, data.into_inner()))
|
||||
},
|
||||
)),
|
||||
)
|
||||
.service(web::scope("/events").route(
|
||||
"/last",
|
||||
web::delete().to_async(|pool, player: PlayerId| {
|
||||
db_call(pool, Q::UndoLastAction(*player))
|
||||
}),
|
||||
)),
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/claims",
|
||||
web::get().to_async(|pool| db_call(pool, Q::FetchClaims)),
|
||||
)
|
||||
.service(
|
||||
web::resource("/shop")
|
||||
.route(web::get().to_async(|pool| db_call(pool, Q::FetchShopInventory)))
|
||||
.route(
|
||||
web::post().to_async(|pool, items: web::Json<api::ItemList>| {
|
||||
db_call(pool, Q::RefreshShopInventory(items.into_inner()))
|
||||
}),
|
||||
),
|
||||
)
|
||||
.service(
|
||||
web::resource("/items")
|
||||
.route(
|
||||
web::get().to_async(move |pool: AppPool| db_call(pool, Q::FetchInventory)),
|
||||
)
|
||||
.route(web::post().to_async(
|
||||
move |pool: AppPool, items: web::Json<Vec<String>>| {
|
||||
db_call(pool, Q::CheckItemList(items.into_inner()))
|
||||
},
|
||||
)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AuthRequest {
|
||||
key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
enum SessionKind {
|
||||
Player(i32),
|
||||
Admin,
|
||||
}
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn check_key(key: &str, db: HashMap<&str, SessionKind>) -> Option<SessionKind> {
|
||||
db.get(&key).map(Clone::clone)
|
||||
}
|
||||
|
||||
fn login(id: Identity, key: web::Query<AuthRequest>) -> HttpResponse {
|
||||
if let Some(session_kind) = check_key(
|
||||
&key.key.to_string(),
|
||||
[
|
||||
("0", SessionKind::Player(0)),
|
||||
("1", SessionKind::Player(1)),
|
||||
("2", SessionKind::Player(2)),
|
||||
("admin", SessionKind::Admin),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<HashMap<&str, SessionKind>>(),
|
||||
) {
|
||||
id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error"));
|
||||
HttpResponse::build(StatusCode::TEMPORARY_REDIRECT)
|
||||
.header(header::LOCATION, "/")
|
||||
.finish()
|
||||
} else {
|
||||
HttpResponse::Forbidden().finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn logout(id: Identity) -> HttpResponse {
|
||||
id.forget();
|
||||
HttpResponse::build(StatusCode::TEMPORARY_REDIRECT)
|
||||
.header(header::LOCATION, "/")
|
||||
.finish()
|
||||
}
|
||||
|
||||
/// This endpoint shall be called by client,
|
||||
/// at initialization, to retrieve the current
|
||||
/// logging session info.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The player data if a player is logged in
|
||||
/// The admin data if the admin is logged in
|
||||
/// A Forbidden response otherwise
|
||||
fn enter_session(id: Identity, pool: AppPool) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||
let conn = pool.get().unwrap();
|
||||
let logged: SessionKind = id
|
||||
.identity()
|
||||
.map(|s| serde_json::from_str(&s).expect("Deserialize SessionKind error"))
|
||||
// This will fail, fastest way to handle
|
||||
// unlogged case with web::block below
|
||||
.unwrap_or(SessionKind::Player(-1));
|
||||
|
||||
web::block(move || {
|
||||
api::execute(
|
||||
&conn,
|
||||
match logged {
|
||||
SessionKind::Player(id) => api::ApiActions::FetchPlayer(id),
|
||||
SessionKind::Admin => api::ApiActions::FetchPlayers,
|
||||
},
|
||||
)
|
||||
})
|
||||
.then(|res| match res {
|
||||
Ok(r) => HttpResponse::Ok().json(r.value),
|
||||
Err(e) => {
|
||||
dbg!(&e);
|
||||
HttpResponse::Forbidden().finish()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn serve() -> std::io::Result<()> {
|
||||
let domain: String = env::var("DOMAIN").expect("DOMAIN must be set");
|
||||
let pool = db::create_pool();
|
||||
println!("Serving Loot-a-lot on {}", domain);
|
||||
|
||||
let key = [0; 32]; // TODO: Use a real key
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.data(pool.clone())
|
||||
.configure(configure_api)
|
||||
.wrap(
|
||||
Cors::new()
|
||||
.allowed_origin(&domain)
|
||||
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
||||
.max_age(3600),
|
||||
)
|
||||
.wrap(IdentityService::new(
|
||||
CookieIdentityPolicy::new(&key)
|
||||
.name("logged-in")
|
||||
.secure(false),
|
||||
))
|
||||
//.wrap(middleware::Logger::default())
|
||||
.wrap(middleware::Logger::new("%r -> %s (%{User-Agent}i)"))
|
||||
.route("/session", web::get().to_async(enter_session))
|
||||
.route("/login", web::get().to(login))
|
||||
.route("/logout", web::get().to(logout))
|
||||
//.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