Compare commits
32 Commits
edf236ef8c
...
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 |
@@ -7,12 +7,15 @@ edition = "2018"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.*"
|
actix-web = "1.0.*"
|
||||||
actix-files = "*"
|
actix-files = "*"
|
||||||
|
actix-service = "*"
|
||||||
|
actix-identity = "*"
|
||||||
lootalot-db = { version = "0.1", path = "./lootalot_db" }
|
lootalot-db = { version = "0.1", path = "./lootalot_db" }
|
||||||
dotenv = "*"
|
dotenv = "*"
|
||||||
env_logger = "*"
|
env_logger = "*"
|
||||||
futures = "0.1"
|
futures = "0.1"
|
||||||
diesel = "*"
|
diesel = "*"
|
||||||
serde = "*"
|
serde = "*"
|
||||||
|
serde_json = "*"
|
||||||
actix-cors = "0.1.0"
|
actix-cors = "0.1.0"
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ dotenv = "*"
|
|||||||
diesel_migrations = "*"
|
diesel_migrations = "*"
|
||||||
serde = "*"
|
serde = "*"
|
||||||
serde_derive = "*"
|
serde_derive = "*"
|
||||||
|
serde_json = "*"
|
||||||
|
|
||||||
[dependencies.diesel]
|
[dependencies.diesel]
|
||||||
version = "1.4"
|
version = "1.4"
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
DROP TABLE items;
|
DROP TABLE items;
|
||||||
DROP TABLE looted;
|
DROP TABLE looted;
|
||||||
|
DROP TABLE shop;
|
||||||
|
|||||||
@@ -13,3 +13,10 @@ CREATE TABLE looted (
|
|||||||
owner_id INTEGER NOT NULL,
|
owner_id INTEGER NOT NULL,
|
||||||
FOREIGN KEY (owner_id) REFERENCES players(id)
|
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
|
||||||
|
);
|
||||||
|
|||||||
@@ -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)
|
||||||
|
);
|
||||||
@@ -18,8 +18,9 @@ mod schema;
|
|||||||
|
|
||||||
pub use models::{
|
pub use models::{
|
||||||
claim::{Claim, Claims},
|
claim::{Claim, Claims},
|
||||||
item::{Item, LootManager, Inventory},
|
history::{Event, UpdateList},
|
||||||
player::{Player, Wealth, Players, AsPlayer},
|
item::{Inventory, Shop, Item, LootManager},
|
||||||
|
player::{AsPlayer, Player, Players, Wealth},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The connection used
|
/// The connection used
|
||||||
@@ -28,6 +29,7 @@ pub type DbConnection = SqliteConnection;
|
|||||||
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
|
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
|
||||||
/// The result of a query on DB
|
/// The result of a query on DB
|
||||||
pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
||||||
|
pub type UpdateResult = QueryResult<Update>;
|
||||||
|
|
||||||
/// Sets up a connection pool and returns it.
|
/// Sets up a connection pool and returns it.
|
||||||
/// Uses the DATABASE_URL environment variable (must be set)
|
/// Uses the DATABASE_URL environment variable (must be set)
|
||||||
@@ -40,6 +42,62 @@ pub fn create_pool() -> Pool {
|
|||||||
.expect("Failed to create pool.")
|
.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
|
/// Sells a single item inside a transaction
|
||||||
///
|
///
|
||||||
@@ -50,17 +108,19 @@ pub fn sell_item_transaction(
|
|||||||
id: i32,
|
id: i32,
|
||||||
loot_id: i32,
|
loot_id: i32,
|
||||||
price_mod: Option<f64>,
|
price_mod: Option<f64>,
|
||||||
) -> QueryResult<(Item, Wealth)> {
|
) -> QueryResult<(Update, Wealth)> {
|
||||||
conn.transaction(|| {
|
conn.transaction(|| {
|
||||||
let deleted = LootManager(conn, id)
|
let to_delete = LootManager(conn, id).find(loot_id)?;
|
||||||
.remove(loot_id)?;
|
let mut sell_value = to_delete.sell_value() as f64;
|
||||||
let mut sell_value = deleted.sell_value() as f64;
|
|
||||||
if let Some(modifier) = price_mod {
|
if let Some(modifier) = price_mod {
|
||||||
sell_value *= modifier;
|
sell_value *= modifier;
|
||||||
}
|
}
|
||||||
let wealth = AsPlayer(conn, id)
|
let deleted = to_delete.remove(conn)?;
|
||||||
.update_wealth(sell_value)?;
|
if let Update::Wealth(wealth) = AsPlayer(conn, id).update_wealth(sell_value)? {
|
||||||
Ok((deleted, wealth))
|
Ok((deleted, wealth))
|
||||||
|
} else {
|
||||||
|
Err(diesel::result::Error::RollbackTransaction)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,50 +134,114 @@ pub fn buy_item_from_inventory(
|
|||||||
id: i32,
|
id: i32,
|
||||||
item_id: i32,
|
item_id: i32,
|
||||||
price_mod: Option<f64>,
|
price_mod: Option<f64>,
|
||||||
) -> QueryResult<(Item, Wealth)> {
|
) -> QueryResult<(Update, Wealth)> {
|
||||||
conn.transaction(|| {
|
conn.transaction(|| {
|
||||||
// Find item in inventory
|
// Find item in inventory
|
||||||
let item = Inventory(conn).find(item_id)?;
|
let item = Inventory(conn).find(item_id)?;
|
||||||
let new_item = LootManager(conn, id).add_from(&item)?;
|
let new_item = LootManager(conn, id).add_from(&item)?;
|
||||||
let sell_price = match price_mod {
|
let sell_price = match price_mod {
|
||||||
Some(modifier) => item.value() as f64 * modifier,
|
Some(modifier) => item.value() * modifier,
|
||||||
None => item.value() as f64,
|
None => item.value(),
|
||||||
};
|
};
|
||||||
AsPlayer(conn, id)
|
if let Update::Wealth(diff) = AsPlayer(conn, id).update_wealth(-sell_price)? {
|
||||||
.update_wealth(-sell_price)
|
Ok((new_item, diff))
|
||||||
.map(|diff| (new_item, diff))
|
} else {
|
||||||
|
Err(diesel::result::Error::RollbackTransaction)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch all existing claims
|
pub fn buy_item_from_shop(
|
||||||
pub fn fetch_claims(conn: &DbConnection) -> QueryResult<Vec<models::Claim>> {
|
conn: &DbConnection,
|
||||||
schema::claims::table.load::<models::Claim>(conn)
|
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.
|
/// Resolve all pending claims and dispatch claimed items.
|
||||||
///
|
///
|
||||||
/// When a player gets an item, it's debt is increased by this item sell value
|
/// When a player gets an item, it's debt is increased by this item sell value
|
||||||
pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
|
pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
|
||||||
let data = models::claim::Claims(conn).grouped_by_item()?;
|
let data = models::claim::Claims(conn).grouped_by_item()?;
|
||||||
dbg!(&data);
|
dbg!(&data);
|
||||||
|
conn.transaction(move || {
|
||||||
for (item, claims) in data {
|
for (item, mut claims) in data {
|
||||||
match claims.len() {
|
if claims.len() > 1 {
|
||||||
1 => {
|
// TODO: better sorting mechanism :)
|
||||||
let claim = claims.get(0).unwrap();
|
claims.sort_by(|a, b| a.resolve.cmp(&b.resolve));
|
||||||
let player_id = claim.player_id;
|
|
||||||
conn.transaction(|| {
|
|
||||||
claim.resolve_claim(conn)?;
|
|
||||||
//models::item::LootManager(self.0, 0).set_owner(claim.loot_id, claim.player_id)?;
|
|
||||||
models::player::AsPlayer(conn, player_id).update_debt(item.sell_value())
|
|
||||||
})?;
|
|
||||||
}
|
}
|
||||||
_ => (),
|
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(())
|
||||||
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(none)]
|
#[cfg(none)]
|
||||||
mod tests_old {
|
mod tests_old {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use crate::{DbConnection, QueryResult};
|
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
|
||||||
|
use crate::{DbConnection, QueryResult, Update, UpdateResult};
|
||||||
use crate::models::{self, item::Loot};
|
use crate::models::{self, item::Loot};
|
||||||
use crate::schema::claims;
|
use crate::schema::claims;
|
||||||
|
|
||||||
/// A Claim is a request by a single player on an item from group chest.
|
/// A Claim is a request by a single player on an item from group chest.
|
||||||
#[derive(Identifiable, Queryable, Associations, Serialize, Deserialize, Debug)]
|
#[derive(Identifiable, Queryable, Associations, Serialize, Deserialize, Clone, Copy, Debug)]
|
||||||
#[belongs_to(Loot)]
|
#[belongs_to(Loot)]
|
||||||
pub struct Claim {
|
pub struct Claim {
|
||||||
/// DB Identifier
|
/// DB Identifier
|
||||||
@@ -41,6 +41,11 @@ impl<'q> Claims<'q> {
|
|||||||
claims::table.load(self.0)
|
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.
|
/// Finds a single claim by association of player and loot ids.
|
||||||
pub fn find(&self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
pub fn find(&self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
||||||
claims::table
|
claims::table
|
||||||
@@ -54,7 +59,7 @@ impl<'q> Claims<'q> {
|
|||||||
/// Will validate that the claimed item exists and is
|
/// Will validate that the claimed item exists and is
|
||||||
/// actually owned by the group.
|
/// actually owned by the group.
|
||||||
/// Duplicates are also ignored.
|
/// Duplicates are also ignored.
|
||||||
pub fn add(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
pub fn add(self, player_id: i32, loot_id: i32) -> UpdateResult {
|
||||||
// We need to validate that the claimed item exists
|
// We need to validate that the claimed item exists
|
||||||
// AND is actually owned by group (id 0)
|
// AND is actually owned by group (id 0)
|
||||||
let _item = models::item::LootManager(self.0, 0).find(loot_id)?;
|
let _item = models::item::LootManager(self.0, 0).find(loot_id)?;
|
||||||
@@ -68,16 +73,22 @@ impl<'q> Claims<'q> {
|
|||||||
.values(&claim)
|
.values(&claim)
|
||||||
.execute(self.0)?;
|
.execute(self.0)?;
|
||||||
// Return the created claim
|
// Return the created claim
|
||||||
claims::table
|
Ok(
|
||||||
.order(claims::dsl::id.desc())
|
Update::ClaimAdded(
|
||||||
.first::<Claim>(self.0)
|
claims::table
|
||||||
|
.order(claims::dsl::id.desc())
|
||||||
|
.first::<Claim>(self.0)?
|
||||||
|
)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes a claim from database, returning it
|
/// Removes a claim from database, returning it
|
||||||
pub fn remove(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
pub fn remove(self, player_id: i32, loot_id: i32) -> UpdateResult {
|
||||||
let claim = self.find(player_id, loot_id)?;
|
let claim = self.find(player_id, loot_id)?;
|
||||||
claim.remove(self.0)?;
|
claim.remove(self.0)?;
|
||||||
Ok(claim)
|
Ok(
|
||||||
|
Update::ClaimRemoved(claim)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> {
|
pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> {
|
||||||
@@ -86,6 +97,15 @@ impl<'q> Claims<'q> {
|
|||||||
.load(self.0)
|
.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>)>> {
|
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 group_loot: Vec<Loot> = Loot::owned_by(0).load(self.0)?;
|
||||||
let claims = claims::table.load(self.0)?.grouped_by(&group_loot);
|
let claims = claims::table.load(self.0)?.grouped_by(&group_loot);
|
||||||
|
|||||||
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() {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,8 +2,8 @@ use diesel::dsl::{exists, Eq, Filter, Find, Select};
|
|||||||
use diesel::expression::exists::Exists;
|
use diesel::expression::exists::Exists;
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
|
||||||
use crate::schema::{items, looted};
|
use crate::schema::{items, looted, shop};
|
||||||
use crate::{DbConnection, QueryResult};
|
use crate::{DbConnection, QueryResult, Update, UpdateResult, Claims };
|
||||||
type ItemColumns = (looted::id, looted::name, looted::base_price);
|
type ItemColumns = (looted::id, looted::name, looted::base_price);
|
||||||
const ITEM_COLUMNS: ItemColumns = (looted::id, looted::name, looted::base_price);
|
const ITEM_COLUMNS: ItemColumns = (looted::id, looted::name, looted::base_price);
|
||||||
type OwnedBy = Select<OwnedLoot, ItemColumns>;
|
type OwnedBy = Select<OwnedLoot, ItemColumns>;
|
||||||
@@ -18,13 +18,25 @@ pub struct Item {
|
|||||||
|
|
||||||
impl Item {
|
impl Item {
|
||||||
/// Returns this item value
|
/// Returns this item value
|
||||||
pub fn value(&self) -> i32 {
|
pub fn value(&self) -> f64 {
|
||||||
self.base_price
|
self.base_price as f64
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns this item sell value
|
/// Returns this item sell value
|
||||||
pub fn sell_value(&self) -> i32 {
|
pub fn sell_value(&self) -> f64 {
|
||||||
self.base_price / 2
|
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 {
|
fn owned_by(player: i32) -> OwnedBy {
|
||||||
@@ -46,6 +58,47 @@ impl<'q> Inventory<'q> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 WithOwner = Eq<looted::owner_id, i32>;
|
||||||
type OwnedLoot = Filter<looted::table, WithOwner>;
|
type OwnedLoot = Filter<looted::table, WithOwner>;
|
||||||
|
|
||||||
@@ -124,7 +177,7 @@ impl<'q> LootManager<'q> {
|
|||||||
.first(self.0)?)
|
.first(self.0)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn add<S: Into<String>>(self, name: S, base_price: i32) -> QueryResult<Item> {
|
pub(crate) fn add<S: Into<String>>(self, name: S, base_price: i32) -> UpdateResult {
|
||||||
self.add_from(&Item {
|
self.add_from(&Item {
|
||||||
id: 0,
|
id: 0,
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
@@ -133,7 +186,7 @@ impl<'q> LootManager<'q> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Adds a copy of the given item inside player chest
|
/// Adds a copy of the given item inside player chest
|
||||||
pub fn add_from(self, item: &Item) -> QueryResult<Item> {
|
pub fn add_from(self, item: &Item) -> UpdateResult {
|
||||||
let new_item = NewLoot {
|
let new_item = NewLoot {
|
||||||
name: &item.name,
|
name: &item.name,
|
||||||
base_price: item.base_price,
|
base_price: item.base_price,
|
||||||
@@ -142,13 +195,7 @@ impl<'q> LootManager<'q> {
|
|||||||
diesel::insert_into(looted::table)
|
diesel::insert_into(looted::table)
|
||||||
.values(&new_item)
|
.values(&new_item)
|
||||||
.execute(self.0)?;
|
.execute(self.0)?;
|
||||||
self.last()
|
Ok(Update::ItemAdded(self.last()?))
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove(self, item_id: i32) -> QueryResult<Item> {
|
|
||||||
let deleted = self.find(item_id)?;
|
|
||||||
diesel::delete(looted::table.find(deleted.id)).execute(self.0)?;
|
|
||||||
Ok(deleted)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,3 +210,10 @@ struct NewLoot<'a> {
|
|||||||
base_price: i32,
|
base_price: i32,
|
||||||
owner_id: i32,
|
owner_id: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Insertable)]
|
||||||
|
#[table_name = "shop"]
|
||||||
|
struct NewItem<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
base_price: i32,
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
pub mod claim;
|
pub mod claim;
|
||||||
pub mod item;
|
pub mod item;
|
||||||
pub mod player;
|
pub mod player;
|
||||||
|
pub mod history;
|
||||||
|
|
||||||
pub use claim::Claim;
|
pub use claim::Claim;
|
||||||
pub use item::Item;
|
pub use item::Item;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::schema::players;
|
use crate::schema::players;
|
||||||
use crate::{DbConnection, QueryResult};
|
use crate::{DbConnection, QueryResult, Update, UpdateResult};
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
|
||||||
mod notification;
|
mod notification;
|
||||||
@@ -35,6 +35,12 @@ impl<'q> Players<'q> {
|
|||||||
players::table.load(self.0)
|
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
|
/// Find a player by id
|
||||||
pub fn find(&self, id: i32) -> QueryResult<Player> {
|
pub fn find(&self, id: i32) -> QueryResult<Player> {
|
||||||
players::table.find(id).first(self.0)
|
players::table.find(id).first(self.0)
|
||||||
@@ -50,10 +56,7 @@ impl<'q> Players<'q> {
|
|||||||
|
|
||||||
/// Notify all players of an event
|
/// Notify all players of an event
|
||||||
pub fn notifiy_all(&self, text: &str) -> QueryResult<()> {
|
pub fn notifiy_all(&self, text: &str) -> QueryResult<()> {
|
||||||
for id in self.all()?
|
for id in self.all()?.into_iter().map(|p| p.id) {
|
||||||
.into_iter()
|
|
||||||
.map(|p| p.id)
|
|
||||||
{
|
|
||||||
self.notify(id, text);
|
self.notify(id, text);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -75,7 +78,7 @@ impl<'q> AsPlayer<'q> {
|
|||||||
notification::pop_all_for(self.1, self.0)
|
notification::pop_all_for(self.1, self.0)
|
||||||
}
|
}
|
||||||
/// Updates this player's wealth, returning the difference
|
/// Updates this player's wealth, returning the difference
|
||||||
pub fn update_wealth(&self, value_in_gp: f64) -> QueryResult<Wealth> {
|
pub fn update_wealth(&self, value_in_gp: f64) -> UpdateResult {
|
||||||
use crate::schema::players::dsl::*;
|
use crate::schema::players::dsl::*;
|
||||||
let current_wealth = players
|
let current_wealth = players
|
||||||
.find(self.1)
|
.find(self.1)
|
||||||
@@ -86,7 +89,7 @@ impl<'q> AsPlayer<'q> {
|
|||||||
.filter(id.eq(self.1))
|
.filter(id.eq(self.1))
|
||||||
.set(&updated_wealth)
|
.set(&updated_wealth)
|
||||||
.execute(self.0)?;
|
.execute(self.0)?;
|
||||||
Ok(updated_wealth - current_wealth)
|
Ok(Update::Wealth(updated_wealth - current_wealth))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Updates this player's debt
|
/// Updates this player's debt
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ fn unpack_gold_value(gold: f64) -> (i32, i32, i32, i32) {
|
|||||||
///
|
///
|
||||||
/// Values are held as individual pieces counts.
|
/// Values are held as individual pieces counts.
|
||||||
/// Allows conversion from and to a floating amount of gold pieces.
|
/// Allows conversion from and to a floating amount of gold pieces.
|
||||||
#[derive(Queryable, AsChangeset, Serialize, Deserialize, Debug)]
|
#[derive(Queryable, AsChangeset, Serialize, Deserialize, PartialEq, Copy, Clone, Debug)]
|
||||||
#[table_name = "players"]
|
#[table_name = "players"]
|
||||||
pub struct Wealth {
|
pub struct Wealth {
|
||||||
pub cp: i32,
|
pub cp: i32,
|
||||||
@@ -69,12 +69,7 @@ impl std::ops::Sub for Wealth {
|
|||||||
/// What needs to be added to 'other' so that
|
/// What needs to be added to 'other' so that
|
||||||
/// the result equals 'self'
|
/// the result equals 'self'
|
||||||
fn sub(self, other: Self) -> Self {
|
fn sub(self, other: Self) -> Self {
|
||||||
Wealth {
|
Wealth::from_gp(self.to_gp() - other.to_gp())
|
||||||
cp: self.cp - other.cp,
|
|
||||||
sp: self.sp - other.sp,
|
|
||||||
gp: self.gp - other.gp,
|
|
||||||
pp: self.pp - other.pp,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,12 +77,7 @@ impl std::ops::Add for Wealth {
|
|||||||
type Output = Self;
|
type Output = Self;
|
||||||
|
|
||||||
fn add(self, other: Self) -> Self {
|
fn add(self, other: Self) -> Self {
|
||||||
Wealth {
|
Wealth::from_gp(self.to_gp() + other.to_gp())
|
||||||
cp: self.cp + other.cp,
|
|
||||||
sp: self.sp + other.sp,
|
|
||||||
gp: self.gp + other.gp,
|
|
||||||
pp: self.pp + other.pp
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,4 +106,52 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,16 @@ table! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
history (id) {
|
||||||
|
id -> Integer,
|
||||||
|
player_id -> Integer,
|
||||||
|
event_date -> Timestamp,
|
||||||
|
text -> Text,
|
||||||
|
updates -> Nullable<Text>,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
table! {
|
table! {
|
||||||
items (id) {
|
items (id) {
|
||||||
id -> Integer,
|
id -> Integer,
|
||||||
@@ -44,15 +54,26 @@ table! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
table! {
|
||||||
|
shop (id) {
|
||||||
|
id -> Integer,
|
||||||
|
name -> Text,
|
||||||
|
base_price -> Integer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
joinable!(claims -> looted (loot_id));
|
joinable!(claims -> looted (loot_id));
|
||||||
joinable!(claims -> players (player_id));
|
joinable!(claims -> players (player_id));
|
||||||
|
joinable!(history -> players (player_id));
|
||||||
joinable!(looted -> players (owner_id));
|
joinable!(looted -> players (owner_id));
|
||||||
joinable!(notifications -> players (player_id));
|
joinable!(notifications -> players (player_id));
|
||||||
|
|
||||||
allow_tables_to_appear_in_same_query!(
|
allow_tables_to_appear_in_same_query!(
|
||||||
claims,
|
claims,
|
||||||
|
history,
|
||||||
items,
|
items,
|
||||||
looted,
|
looted,
|
||||||
notifications,
|
notifications,
|
||||||
players,
|
players,
|
||||||
|
shop,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
> 1%
|
|
||||||
last 2 versions
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
root: true,
|
|
||||||
env: {
|
|
||||||
node: true
|
|
||||||
},
|
|
||||||
'extends': [
|
|
||||||
'plugin:vue/essential',
|
|
||||||
'eslint:recommended'
|
|
||||||
],
|
|
||||||
rules: {
|
|
||||||
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
|
|
||||||
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
|
|
||||||
},
|
|
||||||
parserOptions: {
|
|
||||||
parser: 'babel-eslint'
|
|
||||||
},
|
|
||||||
overrides: [
|
|
||||||
{
|
|
||||||
files: [
|
|
||||||
'**/__tests__/*.{j,t}s?(x)'
|
|
||||||
],
|
|
||||||
env: {
|
|
||||||
mocha: true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
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'
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "lootalot_front",
|
|
||||||
"version": "0.1.0",
|
|
||||||
"private": true,
|
|
||||||
"scripts": {
|
|
||||||
"serve": "vue-cli-service serve",
|
|
||||||
"build": "vue-cli-service build",
|
|
||||||
"lint": "vue-cli-service lint",
|
|
||||||
"test:unit": "vue-cli-service test:unit"
|
|
||||||
},
|
|
||||||
"main": "sass/scroll.scss",
|
|
||||||
"dependencies": {
|
|
||||||
"bulma": "^0.7.5",
|
|
||||||
"core-js": "^2.6.5",
|
|
||||||
"vue": "^2.6.10"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@vue/cli-plugin-babel": "^3.11.0",
|
|
||||||
"@vue/cli-plugin-eslint": "^3.11.0",
|
|
||||||
"@vue/cli-plugin-unit-mocha": "^3.11.0",
|
|
||||||
"@vue/cli-service": "^3.11.0",
|
|
||||||
"@vue/test-utils": "1.0.0-beta.29",
|
|
||||||
"babel-eslint": "^10.0.1",
|
|
||||||
"chai": "^4.1.2",
|
|
||||||
"eslint": "^5.16.0",
|
|
||||||
"eslint-plugin-vue": "^5.0.0",
|
|
||||||
"vue-template-compiler": "^2.6.10"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
plugins: {
|
|
||||||
autoprefixer: {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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="<%= BASE_URL %>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,21 +0,0 @@
|
|||||||
@charset "utf-8";
|
|
||||||
|
|
||||||
$brown: #757763;
|
|
||||||
$beige: #C9AD6A;
|
|
||||||
$beige-light: #E0E5C1;
|
|
||||||
$beige-lighter: #EEE5CE;
|
|
||||||
$red: #B7321B;
|
|
||||||
$dark-red: #58180D;
|
|
||||||
$yellow-light: #FCF2C5;
|
|
||||||
|
|
||||||
$link: $brown;
|
|
||||||
$primary: $brown;
|
|
||||||
$info: $beige;
|
|
||||||
$danger: $red;
|
|
||||||
|
|
||||||
$table-cell-border: 1px solid $dark-red;
|
|
||||||
$table-striped-row-even-background-color: $yellow-light;
|
|
||||||
|
|
||||||
$button-padding-horizontal: 1em;
|
|
||||||
|
|
||||||
@import "../node_modules/bulma/bulma.sass";
|
|
||||||
@@ -1,187 +0,0 @@
|
|||||||
<template>
|
|
||||||
<PlayerView
|
|
||||||
:id="player_id"
|
|
||||||
v-slot="{ player, loot, notifications, actions, claims }"
|
|
||||||
>
|
|
||||||
<main id="app" class="container">
|
|
||||||
<header>
|
|
||||||
<HeaderBar>
|
|
||||||
<template v-slot:title>
|
|
||||||
{{ player.name }}
|
|
||||||
</template>
|
|
||||||
<template v-slot:links>
|
|
||||||
<a class="navbar-item">History of Loot</a>
|
|
||||||
<template v-if="playerIsGroup">
|
|
||||||
<hr class="navbar-divider">
|
|
||||||
<div class="navbar-item heading">Admin</div>
|
|
||||||
<a class="navbar-item">"Resolve claims"</a>
|
|
||||||
<a class="navbar-item">"Add player"</a>
|
|
||||||
</template>
|
|
||||||
<hr class="navbar-divider">
|
|
||||||
<div class="navbar-item heading">Changer</div>
|
|
||||||
<a v-for="(p,i) in playerList" :key="i"
|
|
||||||
@click="setActivePlayer(i)"
|
|
||||||
href="#" class="navbar-item">
|
|
||||||
{{ p.name }}</a>
|
|
||||||
</template>
|
|
||||||
</HeaderBar>
|
|
||||||
<Wealth
|
|
||||||
:wealth="[player.cp, player.sp, player.gp, player.pp]"
|
|
||||||
:debt="player.debt"
|
|
||||||
@update="actions.updateWealth"
|
|
||||||
></Wealth>
|
|
||||||
<p v-show="notifications.length > 0">{{ notifications }}</p>
|
|
||||||
</header>
|
|
||||||
<nav>
|
|
||||||
<div class="tabs is-centered is-boxed is-medium">
|
|
||||||
<ul>
|
|
||||||
<li :class="{ 'is-active': activeView == 'group' }">
|
|
||||||
<a @click="switchView('group')">
|
|
||||||
Coffre de groupe
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li v-show="!playerIsGroup" :class="{ 'is-active': activeView == 'player' }">
|
|
||||||
<a @click="switchView('player')">
|
|
||||||
Mon coffre
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li :class="{'is-active': activeView == 'adding' }">
|
|
||||||
<a class="has-text-grey-light"
|
|
||||||
@click="switchView('adding')">
|
|
||||||
+ {{ playerIsGroup ? 'Nouveau Loot' : 'Acheter' }}
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
<main class="section">
|
|
||||||
<template v-if="isAdding">
|
|
||||||
<Loot v-if="playerIsGroup"
|
|
||||||
:inventory="itemsInventory"
|
|
||||||
@addItem="item => pending_loot.push(item)"
|
|
||||||
@confirmAction="addNewLoot"
|
|
||||||
></Loot>
|
|
||||||
<AddingChest
|
|
||||||
:player="player.id"
|
|
||||||
:claims="claims"
|
|
||||||
:items="playerIsGroup ? pending_loot : itemsInShop"
|
|
||||||
:perms="playerIsGroup ? {} : { canBuy: true }"
|
|
||||||
@buy="(data) => { switchView('player'); actions.buyItems(data); }">
|
|
||||||
</AddingChest>
|
|
||||||
</template>
|
|
||||||
<Chest v-else
|
|
||||||
:player="player.id"
|
|
||||||
:claims="claims"
|
|
||||||
:items="showPlayerChest ? loot : groupLoot"
|
|
||||||
:perms="{
|
|
||||||
canGrab: !(showPlayerChest || playerIsGroup),
|
|
||||||
canSell: showPlayerChest || playerIsGroup
|
|
||||||
}"
|
|
||||||
@sell="actions.sellItems"
|
|
||||||
@claim="actions.putClaim"
|
|
||||||
@unclaim="actions.withdrawClaim">
|
|
||||||
</Chest>
|
|
||||||
</main>
|
|
||||||
</main>
|
|
||||||
</PlayerView>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
import PlayerView from './components/PlayerView.js'
|
|
||||||
import HeaderBar from './components/HeaderBar.vue'
|
|
||||||
import Wealth from './components/Wealth.vue'
|
|
||||||
import Chest from './components/Chest.vue'
|
|
||||||
import Loot from './components/Loot.vue'
|
|
||||||
import { api } from './lootalot.js'
|
|
||||||
|
|
||||||
function getCookie(cname) {
|
|
||||||
var name = cname + "=";
|
|
||||||
var decodedCookie = decodeURIComponent(document.cookie);
|
|
||||||
var ca = decodedCookie.split(';');
|
|
||||||
for(var i = 0; i <ca.length; i++) {
|
|
||||||
var c = ca[i];
|
|
||||||
while (c.charAt(0) == ' ') {
|
|
||||||
c = c.substring(1);
|
|
||||||
}
|
|
||||||
if (c.indexOf(name) == 0) {
|
|
||||||
return c.substring(name.length, c.length);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'app',
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
player_id: 0,
|
|
||||||
playerList: [],
|
|
||||||
activeView: 'group',
|
|
||||||
groupLoot: [],
|
|
||||||
itemsInventory: [],
|
|
||||||
itemsInShop: [{id: 1, name: "Item from shop #1", base_price: 2000}],
|
|
||||||
pending_loot: [],
|
|
||||||
initiated: false,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
components: {
|
|
||||||
PlayerView,
|
|
||||||
HeaderBar,
|
|
||||||
'AddingChest': Chest, // Alias to prevent component re-use
|
|
||||||
Chest,
|
|
||||||
Wealth,
|
|
||||||
Loot,
|
|
||||||
},
|
|
||||||
created () {
|
|
||||||
const cookie = getCookie("player_id");
|
|
||||||
this.player_id = cookie ? Number(cookie) : 0;
|
|
||||||
Promise.all([
|
|
||||||
api.fetch("players/", "GET", null),
|
|
||||||
api.fetch("players/0/loot", "GET", null),
|
|
||||||
api.fetch("items", "GET", null),
|
|
||||||
])
|
|
||||||
.then(([players, loot, items]) => {
|
|
||||||
this.playerList = players.value;
|
|
||||||
this.groupLoot = loot.value;
|
|
||||||
this.itemsInventory = items.value;
|
|
||||||
})
|
|
||||||
.catch(r => alert("Error ! \n" + r))
|
|
||||||
.then(() => this.initiated = true);
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
setActivePlayer (idx) {
|
|
||||||
if (idx == 0) this.switchView('group');
|
|
||||||
this.player_id = Number(idx)
|
|
||||||
document.cookie = `player_id=${idx};`;
|
|
||||||
},
|
|
||||||
switchView (viewId) {
|
|
||||||
if (!['group', 'player', 'adding'].includes(viewId)) {
|
|
||||||
console.error("Not a valid view ID :", viewId);
|
|
||||||
}
|
|
||||||
this.activeView = viewId;
|
|
||||||
},
|
|
||||||
addNewLoot () {
|
|
||||||
api.fetch("players/0/loot", "POST", {
|
|
||||||
source_name: "Dummy name",
|
|
||||||
items: this.pending_loot,
|
|
||||||
})
|
|
||||||
.then(() => {
|
|
||||||
this.pending_loot = []
|
|
||||||
this.switchView('group');
|
|
||||||
})
|
|
||||||
.catch(r => alert("Error: " + r));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
showPlayerChest () { return this.activeView == 'player' },
|
|
||||||
isAdding () { return this.activeView == 'adding' },
|
|
||||||
playerIsGroup () { return this.player_id == 0 },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
header {
|
|
||||||
padding-bottom: 1.5em;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 6.7 KiB |
@@ -1,166 +0,0 @@
|
|||||||
<template>
|
|
||||||
<article>
|
|
||||||
<p class="control has-icons-left">
|
|
||||||
<input type="text" class="input" v-model="searchText">
|
|
||||||
<span class="icon is-small is-left"><i class="fas fa-search"></i></span>
|
|
||||||
</p>
|
|
||||||
<table class="table is-fullwidth is-striped">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th width="100%">Objets</th>
|
|
||||||
<th>Valeur</th>
|
|
||||||
<th>
|
|
||||||
<div v-if="perms.canSell" class="buttons" :class="{'has-addons': is_selling}">
|
|
||||||
<button class="button"
|
|
||||||
:class="is_selling ? 'is-danger' : 'is-warning'"
|
|
||||||
@click="sellSelectedItems"
|
|
||||||
>
|
|
||||||
<span class="icon">
|
|
||||||
<i class="fas fa-coins"></i>
|
|
||||||
</span>
|
|
||||||
<p v-if="!is_selling">Vendre</p>
|
|
||||||
<p v-else>{{ selected_items.length > 0 ? `${totalSelectedValue} po` : 'Annuler' }}</p>
|
|
||||||
</button>
|
|
||||||
<PercentInput v-show="is_selling" v-model="global_mod"></PercentInput>
|
|
||||||
</div>
|
|
||||||
<div v-else-if="perms.canBuy">
|
|
||||||
<button class="button is-danger is-fullwidth"
|
|
||||||
:disabled="selected_items.length == 0"
|
|
||||||
@click="buySelectedItems"
|
|
||||||
>Acheter ({{ totalSelectedValue}}po)</button>
|
|
||||||
</div>
|
|
||||||
<div v-else-if="perms.canGrab">
|
|
||||||
<button class="button is-static is-fullwidth">Demander</button>
|
|
||||||
</div>
|
|
||||||
</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<template v-for="(item, idx) in shownItems">
|
|
||||||
<tr :key="`row-${idx}`">
|
|
||||||
<td>
|
|
||||||
<strong>{{item.name}}</strong>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
{{ is_selling ? item.base_price / 2 : item.base_price }}po
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<Request
|
|
||||||
v-if="perms.canGrab"
|
|
||||||
:id="player"
|
|
||||||
:claims="claims"
|
|
||||||
:item="item.id"
|
|
||||||
@claim="(data) => $emit('claim', data)"
|
|
||||||
@unclaim="(data) => $emit('unclaim', data)"
|
|
||||||
></Request>
|
|
||||||
<Selector
|
|
||||||
v-else-if="showSelectors"
|
|
||||||
:id="item.id"
|
|
||||||
v-model="selected_items"
|
|
||||||
></Selector>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</template>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</article>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
import Request from './Request.vue'
|
|
||||||
import PercentInput from './PercentInput.vue'
|
|
||||||
import Selector from './Selector.vue'
|
|
||||||
import { api } from '../lootalot.js'
|
|
||||||
/*
|
|
||||||
The chest displays a collection of items.
|
|
||||||
|
|
||||||
A set of permissions is passed as props, to update
|
|
||||||
the possible actions of active user upon these items.
|
|
||||||
|
|
||||||
*/
|
|
||||||
export default {
|
|
||||||
props: {
|
|
||||||
player: {
|
|
||||||
type: Number,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
items: {
|
|
||||||
type: Array,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
perms: {
|
|
||||||
type: Object,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
claims: {
|
|
||||||
type: Object,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
components: {
|
|
||||||
Request,
|
|
||||||
PercentInput,
|
|
||||||
Selector,
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
is_selling: false,
|
|
||||||
selected_items: [],
|
|
||||||
global_mod: 0,
|
|
||||||
searchText: "",
|
|
||||||
};
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
buySelectedItems () {
|
|
||||||
this.$emit("buy", this.selected_items);
|
|
||||||
this.selected_items = [];
|
|
||||||
},
|
|
||||||
sellSelectedItems () {
|
|
||||||
if (!this.is_selling) {
|
|
||||||
this.is_selling = true;
|
|
||||||
} else {
|
|
||||||
this.is_selling = false;
|
|
||||||
if (this.selected_items.length > 0) {
|
|
||||||
this.$emit("sell", this.selected_items);
|
|
||||||
this.selected_items = [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
shownItems () {
|
|
||||||
if (this.searchText != "") {
|
|
||||||
const searchText = this.searchText.toUpperCase();
|
|
||||||
return this.items.filter(item => item.name.toUpperCase().includes(searchText));
|
|
||||||
} else {
|
|
||||||
return this.items;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
showSelectors () {
|
|
||||||
return !this.perms.canGrab
|
|
||||||
&& (this.is_selling || this.perms.canBuy);
|
|
||||||
},
|
|
||||||
totalSelectedValue () {
|
|
||||||
var total = this.selected_items
|
|
||||||
.map(([id, mod]) => {
|
|
||||||
const item = this.items.find(item => item.id == id);
|
|
||||||
var price = item.base_price * mod;
|
|
||||||
if (this.is_selling) {
|
|
||||||
price = price / 2;
|
|
||||||
}
|
|
||||||
return price;
|
|
||||||
})
|
|
||||||
.reduce((total,value) => total + value, 0);
|
|
||||||
return (1 + this.global_mod / 100) * total;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.table td, .table th { vertical-align: middle; }
|
|
||||||
.buttons { flex-wrap: nowrap; }
|
|
||||||
label.is-checkbox {
|
|
||||||
background-color: #eee;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
<template>
|
|
||||||
<nav class="navbar is-info">
|
|
||||||
<div class="navbar-brand">
|
|
||||||
<p class="navbar-item is-size-4"><slot name="title">...</slot></p>
|
|
||||||
<a role="button" class="navbar-burger" aria-label="menu" aria-expanded="false"
|
|
||||||
@click="switchMobileVisibility">
|
|
||||||
<span aria-hidden="true"></span>
|
|
||||||
<span aria-hidden="true"></span>
|
|
||||||
<span aria-hidden="true"></span>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
<div id="menu" class="navbar-menu" :class="{'is-active': showOnMobile }">
|
|
||||||
<div class="navbar-end">
|
|
||||||
<div class="navbar-item has-dropdown is-hoverable">
|
|
||||||
<a class="navbar-link">Autres</a>
|
|
||||||
<div class="navbar-dropdown is-right" @click="switchMobileVisibility">
|
|
||||||
<slot name="links">
|
|
||||||
<a class="navbar-item">History of Loot</a>
|
|
||||||
</slot>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
data () { return { showOnMobile: false } },
|
|
||||||
methods: {
|
|
||||||
switchMobileVisibility () {
|
|
||||||
this.showOnMobile = !this.showOnMobile
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="field is-horizontal">
|
|
||||||
<div class="field-label">
|
|
||||||
<label class="label">Nouvel objet</label>
|
|
||||||
</div>
|
|
||||||
<div class="field-body">
|
|
||||||
<div class="field">
|
|
||||||
<div class="control is-expanded">
|
|
||||||
<input type="text"
|
|
||||||
name="name"
|
|
||||||
placeholder="Nom de l'objet"
|
|
||||||
v-model="item.name"
|
|
||||||
@input="autoCompletion"
|
|
||||||
class="input"
|
|
||||||
autocomplete="on"
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
<div class="dropdown" :class="{'is-active': showCompletionFrame}">
|
|
||||||
<div class="dropdown-menu">
|
|
||||||
<div class="dropdown-content">
|
|
||||||
<a v-for="(result,i) in results"
|
|
||||||
:key="i"
|
|
||||||
@click="setResult(result)"
|
|
||||||
class="dropdown-item"
|
|
||||||
>{{ result.name }}</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="field is-expanded has-addons" v-show="item.name != ''">
|
|
||||||
<p class="control"><a class="button is-static">PO</a></p>
|
|
||||||
<p class="control">
|
|
||||||
<input type="text"
|
|
||||||
name="base_price"
|
|
||||||
placeholder="Prix"
|
|
||||||
class="input"
|
|
||||||
:class="{'is-danger': item.base_price == ''}"
|
|
||||||
v-model.number="item.base_price"
|
|
||||||
>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
|
||||||
<div class="control">
|
|
||||||
<button class="button is-primary"
|
|
||||||
@click="addItem"
|
|
||||||
:disabled="!isItemValid"
|
|
||||||
>Ajouter</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
props: ["source"],
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
is_loading: false,
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: '',
|
|
||||||
base_price: '',
|
|
||||||
},
|
|
||||||
results: [],
|
|
||||||
};
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
autoCompletion () {
|
|
||||||
// Unset any previous value on input (for every field except item's name)
|
|
||||||
this.item.base_price = '';
|
|
||||||
if (this.item.name == '') {
|
|
||||||
this.results = [];
|
|
||||||
} else {
|
|
||||||
this.results = this.source.filter(
|
|
||||||
item => item.name.toUpperCase().includes(this.item.name.toUpperCase())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
setResult(result) {
|
|
||||||
this.item.id = result.id;
|
|
||||||
this.item.name = result.name;
|
|
||||||
this.item.base_price = result.base_price;
|
|
||||||
// Clear results to close completionFrame
|
|
||||||
this.results = [];
|
|
||||||
},
|
|
||||||
addItem () {
|
|
||||||
this.$emit("addItem", this.item);
|
|
||||||
this.item = {
|
|
||||||
name: '',
|
|
||||||
base_price: '',
|
|
||||||
};
|
|
||||||
this.results = [];
|
|
||||||
},
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
showCompletionFrame () { return this.results.length > 0 },
|
|
||||||
isItemValid () { return this.item.name != '' && this.item.base_price != '' },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.dropdown, .dropdown-menu {
|
|
||||||
min-width: 100%;
|
|
||||||
margin-top: 0;
|
|
||||||
padding-top: 0;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="box">
|
|
||||||
<ItemInput
|
|
||||||
@addItem="onAddItem"
|
|
||||||
:source="inventory"
|
|
||||||
></ItemInput>
|
|
||||||
<div class="field is-horizontal">
|
|
||||||
<div class="field-label"><label class="label">ou</label></div>
|
|
||||||
<div class="field-body">
|
|
||||||
<div class="field">
|
|
||||||
<div class="control">
|
|
||||||
<button class="button is-primary">Depuis une liste</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button class="button is-danger" @click="$emit('confirmAction')">Finaliser</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
import ItemInput from './ItemInput.vue'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
props: ["inventory"],
|
|
||||||
components: { ItemInput },
|
|
||||||
data () { return {}; },
|
|
||||||
methods: {
|
|
||||||
onAddItem (item) {
|
|
||||||
this.$emit('addItem', item);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="field has-addons">
|
|
||||||
<div v-show="is_opened" class="control has-icons-left">
|
|
||||||
<input class="input" :value="value" @input="input" type="number" size="3" min="-50" max=50 step=5>
|
|
||||||
<span class="icon is-left">
|
|
||||||
<i class="fas fa-percent"></i>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="control">
|
|
||||||
<button class="button" @click="switchOpenedState">
|
|
||||||
<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 {
|
|
||||||
props: ["value"],
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
is_opened: false,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
input (event) { this.$emit("input", event.target.value); },
|
|
||||||
switchOpenedState () {
|
|
||||||
this.is_opened = !this.is_opened;
|
|
||||||
// Reset the modifier in closed state
|
|
||||||
if (!this.is_opened) {
|
|
||||||
this.$emit("input", 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.input { width: 6em; }
|
|
||||||
</style>
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
import { api } from '../lootalot.js'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
props: ["id"],
|
|
||||||
data () { return {
|
|
||||||
player: {
|
|
||||||
name: "Loading",
|
|
||||||
id: 0,
|
|
||||||
cp: '-', sp: '-', gp: '-', pp: '-',
|
|
||||||
debt: 0,
|
|
||||||
},
|
|
||||||
notifications: [],
|
|
||||||
loot: [],
|
|
||||||
claims: {},
|
|
||||||
}},
|
|
||||||
created () {
|
|
||||||
api.fetch("claims", "GET", null)
|
|
||||||
.then(r => {
|
|
||||||
for (var idx in r.value) {
|
|
||||||
var claim = r.value[idx];
|
|
||||||
if (!(claim.player_id in this.claims)) {
|
|
||||||
this.$set(this.claims, claim.player_id, []);
|
|
||||||
}
|
|
||||||
this.claims[claim.player_id].push(claim.loot_id);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
parseUpdate (update) {
|
|
||||||
if (update.Wealth) {
|
|
||||||
var w = update.Wealth;
|
|
||||||
this.player.cp += w.cp;
|
|
||||||
this.player.sp += w.sp;
|
|
||||||
this.player.gp += w.gp;
|
|
||||||
this.player.pp += w.pp;
|
|
||||||
}
|
|
||||||
else if (update.ItemAdded) {
|
|
||||||
var i = update.ItemAdded;
|
|
||||||
this.loot.push(i);
|
|
||||||
}
|
|
||||||
else if (update.ItemRemoved) {
|
|
||||||
var i = update.ItemRemoved;
|
|
||||||
this.loot.splice(this.loot.indexOf(i), 1);
|
|
||||||
}
|
|
||||||
else if (update.ClaimAdded) {
|
|
||||||
var c = update.ClaimAdded;
|
|
||||||
this.claims[c.player_id].push(c.loot_id);
|
|
||||||
}
|
|
||||||
else if (update.ClaimRemoved) {
|
|
||||||
var c = update.ClaimRemoved;
|
|
||||||
this.claims[c.player_id].splice(
|
|
||||||
this.claims[c.player_id].indexOf(c.loot_id),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
call (resource, method, payload) {
|
|
||||||
return api.fetch(`players/${this.id}/${resource}`, method, payload)
|
|
||||||
.then(response => {
|
|
||||||
if (response.notification) {
|
|
||||||
this.notifications.push(response.notification)
|
|
||||||
}
|
|
||||||
if (response.errors) {
|
|
||||||
this.notifications.push(response.errors)
|
|
||||||
}
|
|
||||||
if (response.updates) {
|
|
||||||
for (var idx in response.updates) {
|
|
||||||
this.parseUpdate(response.updates[idx]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return response.value;
|
|
||||||
})
|
|
||||||
},
|
|
||||||
updateWealth (value) { this.call("wealth", "PUT", Number(value)) },
|
|
||||||
putClaim (itemId) { this.call("claims", "PUT", itemId) },
|
|
||||||
withdrawClaim (itemId) { this.call("claims", "DELETE", itemId) },
|
|
||||||
buyItems(items) { this.call("loot", "PUT", items) },
|
|
||||||
sellItems (items) { this.call("loot", "DELETE", items) },
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
id: {
|
|
||||||
immediate: true,
|
|
||||||
handler: function(newId) {
|
|
||||||
this.call("", "GET", null)
|
|
||||||
.then(p => this.player = p)
|
|
||||||
this.call("loot", "GET", null)
|
|
||||||
.then(l => this.loot = l)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
computed: {},
|
|
||||||
render () {
|
|
||||||
return this.$scopedSlots.default({
|
|
||||||
player: this.player,
|
|
||||||
loot: this.loot,
|
|
||||||
notifications: this.notifications,
|
|
||||||
actions: {
|
|
||||||
updateWealth: this.updateWealth,
|
|
||||||
putClaim: this.putClaim,
|
|
||||||
withdrawClaim: this.withdrawClaim,
|
|
||||||
buyItems: this.buyItems,
|
|
||||||
sellItems: this.sellItems,
|
|
||||||
},
|
|
||||||
claims: this.claims,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="buttons">
|
|
||||||
<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"
|
|
||||||
:disabled="isRequested">
|
|
||||||
<span class="icon is-small">
|
|
||||||
<i class="fas fa-praying-hands"></i>
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
props: {
|
|
||||||
// Id of active player
|
|
||||||
id: {
|
|
||||||
type: Number,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
// Map of all claims
|
|
||||||
claims: {
|
|
||||||
type: Object,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
// Id of item we are bound to
|
|
||||||
item: {
|
|
||||||
type: Number,
|
|
||||||
required: true,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
// Check if item is requested by active player
|
|
||||||
isRequested () {
|
|
||||||
if (this.claims[this.id]) {
|
|
||||||
return this.claims[this.id].includes(this.item);
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// Check if item is requested by multiple players including active one
|
|
||||||
isInConflict () {
|
|
||||||
var reqByPlayer = false;
|
|
||||||
var reqByOther = false;
|
|
||||||
for (var id in this.claims) {
|
|
||||||
const isReq = this.claims[id].includes(this.item);
|
|
||||||
if (isReq) {
|
|
||||||
if (id == this.id) {
|
|
||||||
reqByPlayer = true;
|
|
||||||
} else {
|
|
||||||
reqByOther = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return reqByPlayer && reqByOther;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
// The active player claims the item
|
|
||||||
putRequest () {
|
|
||||||
this.$emit("claim", this.item);
|
|
||||||
},
|
|
||||||
// The active player withdraws his request
|
|
||||||
cancelRequest () {
|
|
||||||
this.$emit("unclaim", 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>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.buttons, .button { margin-bottom: 0; }
|
|
||||||
</style>
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="buttons has-addons">
|
|
||||||
<label class="button is-fullwidth">
|
|
||||||
<input type="checkbox" class="checkbox" v-model="selected">
|
|
||||||
</label>
|
|
||||||
<PercentInput v-show="selected" v-model.number="mod_value"></PercentInput>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
import PercentInput from './PercentInput.vue'
|
|
||||||
|
|
||||||
/* Selector for a specific item, with an associated price modifier.
|
|
||||||
Acts as checkbox on a v-model, except it populates an array with [value, modifier] instead of value alone
|
|
||||||
*/
|
|
||||||
|
|
||||||
export default {
|
|
||||||
props: ["id", "value"],
|
|
||||||
components: { PercentInput },
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
selected: false,
|
|
||||||
mod_value: 0,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
modifier () {
|
|
||||||
return 1 + this.mod_value / 100;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
selected (newState) {
|
|
||||||
let idx = this._findData();
|
|
||||||
var updated = this.value;
|
|
||||||
if (newState == true && idx == -1) {
|
|
||||||
updated.push([this.id, this.modifier]);
|
|
||||||
} else if (newState == false && idx != -1 ) {
|
|
||||||
updated.splice(idx, 1);
|
|
||||||
}
|
|
||||||
this.$emit('input', updated);
|
|
||||||
},
|
|
||||||
mod_value (newState) {
|
|
||||||
let idx = this._findData();
|
|
||||||
var updated = this.value;
|
|
||||||
if (idx != -1) {
|
|
||||||
updated.splice(idx, 1, [this.id, this.modifier]);
|
|
||||||
this.$emit('input', updated);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
_findData () {
|
|
||||||
return this.value.findIndex(([val,mod]) => this.id == val);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
<template>
|
|
||||||
<section class="level is-mobile">
|
|
||||||
<div class="level-left">
|
|
||||||
<div class="level-item">
|
|
||||||
<span class="icon is-large" @click="editing = !editing">
|
|
||||||
<i class="fas fa-2x fa-piggy-bank"></i>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<template v-if="editing">
|
|
||||||
<div class="level-item">
|
|
||||||
<div class="field has-addons">
|
|
||||||
<p class="control">
|
|
||||||
<input class="input" type="number" step="0.01" v-model="edit_value"></input>
|
|
||||||
</p>
|
|
||||||
<p class="control">
|
|
||||||
<a class="button is-static">po</a>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="level-item">
|
|
||||||
<button class="button is-danger" @click="updateWealth()">
|
|
||||||
Modifier
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
<template v-else>
|
|
||||||
<div class="level-item ">
|
|
||||||
<p class="is-size-4">{{ pp }}</p>
|
|
||||||
<p class="heading">PP</p>
|
|
||||||
</div>
|
|
||||||
<div class="level-item ">
|
|
||||||
<p class="is-size-4">{{ gp }}</p>
|
|
||||||
<p class="heading">PO</p>
|
|
||||||
</div>
|
|
||||||
<div class="level-item ">
|
|
||||||
<p class="is-size-4 has-text-grey-light">{{ sp }}</p>
|
|
||||||
<p class="heading">PA</p>
|
|
||||||
</div>
|
|
||||||
<div class="level-item ">
|
|
||||||
<p class="is-size-4 has-text-grey-light">{{ cp }}</p>
|
|
||||||
<p class="heading">PC</p>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
<div class="level-right" v-if="debt">
|
|
||||||
<div class="level-item">
|
|
||||||
<p class="heading is-size-4 has-text-danger">Dette: {{ debt }}gp </p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
props: ["wealth", "debt"],
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
editing: false,
|
|
||||||
edit_value: 0,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
updateWealth () {
|
|
||||||
this.$emit("update", this.edit_value);
|
|
||||||
this.resetValues();
|
|
||||||
},
|
|
||||||
resetValues () {
|
|
||||||
this.editing = false;
|
|
||||||
this.edit_value = 0;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
pp () {
|
|
||||||
return this.wealth[3];
|
|
||||||
},
|
|
||||||
gp () {
|
|
||||||
const gp = this.wealth[2];
|
|
||||||
if (gp < 10) {
|
|
||||||
return "0" + gp;
|
|
||||||
} else {
|
|
||||||
return gp;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
sp () {
|
|
||||||
return this.wealth[1];
|
|
||||||
},
|
|
||||||
cp () {
|
|
||||||
return this.wealth[0];
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.input { max-width: 9em; }
|
|
||||||
</style>
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
const API_BASEURL = "http://localhost:8088/api/"
|
|
||||||
const API_ENDPOINT = function (tailString) {
|
|
||||||
return API_BASEURL + tailString;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const api = {
|
|
||||||
fetch: function(endpoint, method, payload) {
|
|
||||||
var config = {
|
|
||||||
method,
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
if (payload) {
|
|
||||||
config.body = JSON.stringify(payload);
|
|
||||||
}
|
|
||||||
return fetch(API_ENDPOINT(endpoint), config)
|
|
||||||
.then(r => r.json());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import Vue from 'vue'
|
|
||||||
import App from './App.vue'
|
|
||||||
|
|
||||||
Vue.config.productionTip = false
|
|
||||||
|
|
||||||
new Vue({
|
|
||||||
render: h => h(App),
|
|
||||||
}).$mount('#app')
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
env: {
|
|
||||||
mocha: true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
import { expect } from 'chai'
|
|
||||||
import { mount } from '@vue/test-utils'
|
|
||||||
import ItemInput from '@/components/ItemInput.vue'
|
|
||||||
|
|
||||||
const MOCK_SOURCE = [
|
|
||||||
{ id: 1, name: "Épée", base_price: 20 },
|
|
||||||
{ id: 2, name: "Arc", base_price: 30 },
|
|
||||||
]
|
|
||||||
|
|
||||||
const withItemFactory = function (item) {
|
|
||||||
const wrapper = mount(ItemInput, {
|
|
||||||
propsData: {
|
|
||||||
source: MOCK_SOURCE,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
wrapper.setData({ item })
|
|
||||||
return wrapper
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('ItemInput.vue', () => {
|
|
||||||
|
|
||||||
// Tests on validation of the item data
|
|
||||||
it('item with name and price is valid', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: 'Epee',
|
|
||||||
base_price: 200
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('item without data is not valid', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: '',
|
|
||||||
base_price: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('item without price is not valid', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: 'Epee',
|
|
||||||
base_price: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('item without name is not valid', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: '',
|
|
||||||
base_price: 200
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('item price must be a number', () => {
|
|
||||||
const localItem = {
|
|
||||||
item: {
|
|
||||||
id: 0,
|
|
||||||
name: 'Epee',
|
|
||||||
base_price: 'cheap'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(ItemInput.computed.isItemValid.call(localItem)).to.equal(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Test on auto-completion
|
|
||||||
it('show completion suggestions on input', () => {
|
|
||||||
const wrapper = withItemFactory({ id: 0, name: '', base_price: '' })
|
|
||||||
const input = wrapper.find({ name: "name" })
|
|
||||||
const suggestionBox = wrapper.find('.dropdown')
|
|
||||||
console.log(input)
|
|
||||||
expect(suggestionBox.classes('is-active')).to.equal(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('hides suggestion box when no suggestions are available', () => {
|
|
||||||
|
|
||||||
})
|
|
||||||
|
|
||||||
it('click on suggestion sets the item', () => {
|
|
||||||
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { expect } from 'chai'
|
|
||||||
import { shallowMount } from '@vue/test-utils'
|
|
||||||
import Wealth from '@/components/Wealth.vue'
|
|
||||||
|
|
||||||
describe('Wealth.vue', () => {
|
|
||||||
it('renders wealth when passed', () => {
|
|
||||||
const wealth = [1, 2, 3, 4]
|
|
||||||
const wrapper = shallowMount(Wealth, {
|
|
||||||
propsData: { wealth }
|
|
||||||
})
|
|
||||||
var divs = wrapper.findAll('div')
|
|
||||||
expect(wrapper.text()).to.include(wealth)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
301
src/api.rs
301
src/api.rs
@@ -1,39 +1,29 @@
|
|||||||
use lootalot_db::{self as db, DbConnection, QueryResult};
|
use diesel::connection::Connection;
|
||||||
|
use lootalot_db::{self as db, DbConnection, Update, Value};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
/// Every possible update which can happen during a query
|
pub type IdList = Vec<i32>;
|
||||||
#[derive(Serialize, Debug)]
|
pub type ItemListWithMods = Vec<(i32, Option<f64>)>;
|
||||||
pub enum Update {
|
pub type ItemList = Vec<db::Item>;
|
||||||
Wealth(db::Wealth),
|
|
||||||
ItemAdded(db::Item),
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
ItemRemoved(db::Item),
|
pub struct BuySellParams {
|
||||||
ClaimAdded(db::Claim),
|
pub items: ItemListWithMods,
|
||||||
ClaimRemoved(db::Claim),
|
players: Option<IdList>,
|
||||||
|
global_mod: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every value which can be queried
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
#[derive(Debug)]
|
pub struct NewGroupLoot {
|
||||||
pub enum Value {
|
source_name: String,
|
||||||
Player(db::Player),
|
// claims_limit_date: String
|
||||||
Item(db::Item),
|
pub items: ItemList,
|
||||||
Claim(db::Claim),
|
|
||||||
ItemList(Vec<db::Item>),
|
|
||||||
ClaimList(Vec<db::Claim>),
|
|
||||||
PlayerList(Vec<db::Player>),
|
|
||||||
Notifications(Vec<String>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl serde::Serialize for Value {
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
pub struct NewPlayer {
|
||||||
match self {
|
name : String,
|
||||||
Value::Player(v) => v.serialize(serializer),
|
wealth : f64,
|
||||||
Value::Item(v) => v.serialize(serializer),
|
|
||||||
Value::Claim(v) => v.serialize(serializer),
|
|
||||||
Value::ItemList(v) => v.serialize(serializer),
|
|
||||||
Value::ClaimList(v) => v.serialize(serializer),
|
|
||||||
Value::PlayerList(v) => v.serialize(serializer),
|
|
||||||
Value::Notifications(v) => v.serialize(serializer),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A generic response for all queries
|
/// A generic response for all queries
|
||||||
@@ -50,7 +40,7 @@ pub struct ApiResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ApiResponse {
|
impl ApiResponse {
|
||||||
fn push_update(&mut self, update: Update) {
|
fn push_update(&mut self, update: db::Update) {
|
||||||
if let Some(v) = self.updates.as_mut() {
|
if let Some(v) = self.updates.as_mut() {
|
||||||
v.push(update);
|
v.push(update);
|
||||||
} else {
|
} else {
|
||||||
@@ -66,7 +56,7 @@ impl ApiResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_value(&mut self, value: Value) {
|
fn set_value(&mut self, value: db::Value) {
|
||||||
self.value = Some(value);
|
self.value = Some(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,26 +72,29 @@ pub enum ApiError {
|
|||||||
|
|
||||||
/// Every allowed queries on the database
|
/// Every allowed queries on the database
|
||||||
pub enum ApiActions {
|
pub enum ApiActions {
|
||||||
|
// Application level
|
||||||
FetchPlayers,
|
FetchPlayers,
|
||||||
FetchInventory,
|
FetchInventory,
|
||||||
|
FetchShopInventory,
|
||||||
FetchClaims,
|
FetchClaims,
|
||||||
// Player actions
|
CheckItemList(Vec<String>),
|
||||||
|
// Player level
|
||||||
FetchPlayer(i32),
|
FetchPlayer(i32),
|
||||||
|
FetchPlayerClaims(i32),
|
||||||
FetchNotifications(i32),
|
FetchNotifications(i32),
|
||||||
FetchLoot(i32),
|
FetchLoot(i32),
|
||||||
UpdateWealth(i32, f64),
|
UpdateWealth(i32, f64),
|
||||||
BuyItems(i32, Vec<(i32, Option<f64>)>),
|
BuyItems(i32, BuySellParams),
|
||||||
SellItems(i32, Vec<(i32, Option<f64>)>),
|
SellItems(i32, BuySellParams),
|
||||||
ClaimItem(i32, i32),
|
ClaimItems(i32, IdList),
|
||||||
UnclaimItem(i32, i32),
|
UndoLastAction(i32),
|
||||||
// Group actions
|
// Group level
|
||||||
AddLoot(Vec<db::Item>),
|
AddLoot(NewGroupLoot),
|
||||||
}
|
// Admin level
|
||||||
|
RefreshShopInventory(ItemList),
|
||||||
pub enum AdminActions {
|
AddPlayer(NewPlayer),
|
||||||
AddPlayer(String, f64),
|
|
||||||
//AddInventoryItem(pub String, pub i32),
|
//AddInventoryItem(pub String, pub i32),
|
||||||
ResolveClaims,
|
//ResolveClaims,
|
||||||
//SetClaimsTimeout(pub i32),
|
//SetClaimsTimeout(pub i32),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,87 +103,182 @@ pub fn execute(
|
|||||||
query: ApiActions,
|
query: ApiActions,
|
||||||
) -> Result<ApiResponse, diesel::result::Error> {
|
) -> Result<ApiResponse, diesel::result::Error> {
|
||||||
let mut response = ApiResponse::default();
|
let mut response = ApiResponse::default();
|
||||||
match query {
|
// 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 => {
|
ApiActions::FetchPlayers => {
|
||||||
response.set_value(Value::PlayerList(db::Players(conn).all()?));
|
response.set_value(Value::PlayerList(db::Players(conn).all_except_group()?));
|
||||||
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchInventory => {
|
ApiActions::FetchInventory => {
|
||||||
response.set_value(Value::ItemList(db::Inventory(conn).all()?));
|
response.set_value(Value::ItemList(db::Inventory(conn).all()?));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
ApiActions::FetchShopInventory => {
|
||||||
|
response.set_value(Value::ItemList(db::Shop(conn).all()?));
|
||||||
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchClaims => {
|
ApiActions::FetchClaims => {
|
||||||
response.set_value(Value::ClaimList(db::fetch_claims(conn)?));
|
response.set_value(Value::ClaimList(db::Claims(conn).all()?));
|
||||||
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchPlayer(id) => {
|
ApiActions::FetchPlayer(id) => {
|
||||||
response.set_value(Value::Player(db::Players(conn).find(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) => {
|
ApiActions::FetchNotifications(id) => {
|
||||||
response.set_value(Value::Notifications(db::AsPlayer(conn, id).notifications()?));
|
response.set_value(Value::Notifications(
|
||||||
|
db::AsPlayer(conn, id).notifications()?,
|
||||||
|
));
|
||||||
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchLoot(id) => {
|
ApiActions::FetchLoot(id) => {
|
||||||
response.set_value(Value::ItemList(db::LootManager(conn, id).all()?));
|
response.set_value(Value::ItemList(db::LootManager(conn, id).all()?));
|
||||||
|
None
|
||||||
}
|
}
|
||||||
ApiActions::UpdateWealth(id, amount) => {
|
ApiActions::UpdateWealth(id, amount) => {
|
||||||
response.push_update(Update::Wealth(
|
response.push_update(db::AsPlayer(conn, id).update_wealth(amount)?);
|
||||||
db::AsPlayer(conn, id).update_wealth(amount)?,
|
|
||||||
));
|
|
||||||
response.notify(format!("Mis à jour ({}po)!", amount));
|
response.notify(format!("Mis à jour ({}po)!", amount));
|
||||||
|
Some((id, "Argent mis à jour"))
|
||||||
}
|
}
|
||||||
ApiActions::BuyItems(id, params) => {
|
ApiActions::BuyItems(id, params) => {
|
||||||
let mut cumulated_diff: Vec<db::Wealth> = Vec::with_capacity(params.len());
|
// TODO: check that player has enough money !
|
||||||
let mut added_items: u16 = 0;
|
let has_enough_gold = true;
|
||||||
for (item_id, price_mod) in params.into_iter() {
|
|
||||||
if let Ok((item, diff)) = db::buy_item_from_inventory(conn, id, item_id, price_mod) {
|
if has_enough_gold {
|
||||||
cumulated_diff.push(diff);
|
let mut gains: Vec<db::Wealth> = Vec::with_capacity(params.items.len());
|
||||||
response.push_update(Update::ItemAdded(item));
|
for (item_id, price_mod) in params.items.into_iter() {
|
||||||
added_items += 1;
|
if let Ok((item, diff)) = db::buy_item_from_shop(conn, id, item_id, price_mod) {
|
||||||
} else {
|
response.push_update(item);
|
||||||
response.push_error(format!("Error adding {}", item_id));
|
gains.push(diff);
|
||||||
|
} else {
|
||||||
|
response.push_error(format!("Error adding {}", item_id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
let added_items = gains.len();
|
||||||
let total_amount = cumulated_diff
|
let total_amount = gains
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
.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.notify(format!(
|
||||||
response.push_update(Update::Wealth(total_amount));
|
"{} 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) => {
|
ApiActions::SellItems(id, params) => {
|
||||||
// TODO: Different procedure for group and other players
|
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
|
||||||
let mut all_results: Vec<db::Wealth> = Vec::with_capacity(params.len());
|
let mut gains: Vec<db::Wealth> = Vec::with_capacity(params.items.len());
|
||||||
let mut sold_items: u16 = 0;
|
for (loot_id, price_mod) in params.items.iter() {
|
||||||
for (loot_id, price_mod) in params.into_iter() {
|
if let Ok((deleted, diff)) =
|
||||||
if let Ok((deleted, diff)) = db::sell_item_transaction(conn, id, loot_id, price_mod) {
|
db::sell_item_transaction(conn, id, *loot_id, *price_mod)
|
||||||
all_results.push(diff);
|
{
|
||||||
response.push_update(Update::ItemRemoved(deleted));
|
response.push_update(deleted);
|
||||||
sold_items += 1;
|
gains.push(diff);
|
||||||
} else {
|
} else {
|
||||||
response.push_error(format!("Error selling {}", loot_id));
|
response
|
||||||
|
.push_error(format!("Erreur lors de la vente (loot_id : {})", loot_id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
let sold_items = gains.len();
|
||||||
let total_amount = all_results
|
let total_amount = gains
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
||||||
response.notify(format!("{} objet(s) vendu(s) pour {} po", sold_items, total_amount.to_gp()));
|
match id {
|
||||||
response.push_update(Update::Wealth(total_amount));
|
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::ClaimItem(id, item) => {
|
ApiActions::ClaimItems(id, items) => {
|
||||||
response.push_update(Update::ClaimAdded(
|
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
|
||||||
db::Claims(conn).add(id, item)?,
|
let current_claims: HashSet<i32> = db::Claims(conn)
|
||||||
));
|
.all()?
|
||||||
response.notify(format!("Pour moi !"));
|
.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::UnclaimItem(id, item) => {
|
ApiActions::UndoLastAction(id) => {
|
||||||
response.push_update(Update::ClaimRemoved(
|
if let Ok(event) = db::models::history::get_last_of_player(conn, id) {
|
||||||
db::Claims(conn).remove(id, item)?,
|
let name = String::from(event.name());
|
||||||
));
|
for undone in event.undo(conn)?.into_inner().into_iter() {
|
||||||
response.notify(format!("Bof! Finalement non."));
|
response.push_update(undone);
|
||||||
|
}
|
||||||
|
response.notify(format!("'{}' annulé(e)", name));
|
||||||
|
} else {
|
||||||
|
response.push_error("Aucune action trouvée")
|
||||||
|
};
|
||||||
|
None
|
||||||
}
|
}
|
||||||
// Group actions
|
// Group actions
|
||||||
ApiActions::AddLoot(items) => {
|
ApiActions::AddLoot(data) => {
|
||||||
let mut added_items = 0;
|
let mut added_items = 0;
|
||||||
for item in items.into_iter() {
|
for item in data.items.into_iter() {
|
||||||
if let Ok(added) = db::LootManager(conn, 0).add_from(&item) {
|
if let Ok(added) = db::LootManager(conn, 0).add_from(&item) {
|
||||||
response.push_update(Update::ItemAdded(added));
|
response.push_update(added);
|
||||||
added_items += 1;
|
added_items += 1;
|
||||||
} else {
|
} else {
|
||||||
response.push_error(format!("Error adding {:?}", item));
|
response.push_error(format!("Error adding {:?}", item));
|
||||||
}
|
}
|
||||||
@@ -202,7 +290,34 @@ pub fn execute(
|
|||||||
{
|
{
|
||||||
response.push_error(format!("Erreur durant la notification : {:?}", e));
|
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)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|||||||
299
src/server.rs
299
src/server.rs
@@ -1,29 +1,37 @@
|
|||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
use actix_files as fs;
|
use actix_files as fs;
|
||||||
use actix_web::{web, middleware, App, Error, HttpResponse, HttpServer};
|
use actix_identity::{CookieIdentityPolicy, Identity, IdentityService, RequestIdentity};
|
||||||
use futures::{Future, IntoFuture};
|
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 std::env;
|
||||||
|
|
||||||
use lootalot_db as db;
|
|
||||||
use crate::api;
|
use crate::api;
|
||||||
|
use lootalot_db as db;
|
||||||
|
|
||||||
type AppPool = web::Data<db::Pool>;
|
type AppPool = web::Data<db::Pool>;
|
||||||
type PlayerId = web::Path<i32>;
|
type PlayerId = web::Path<i32>;
|
||||||
type ItemId = web::Json<i32>;
|
type ItemId = web::Json<i32>;
|
||||||
type ItemListWithMods = web::Json<Vec<(i32, Option<f64>)>>;
|
type IdList = web::Json<api::IdList>;
|
||||||
|
type BuySellParams = web::Json<api::BuySellParams>;
|
||||||
|
type NewGroupLoot = web::Json<api::NewGroupLoot>;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
type MaybeForbidden =
|
||||||
struct NewGroupLoot {
|
actix_web::Either<Box<dyn Future<Item = HttpResponse, Error = Error>>, HttpResponse>;
|
||||||
source_name: String,
|
|
||||||
items: Vec<db::Item>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wraps call to the database query and convert its result as a async HttpResponse
|
/// Wraps call to the database query and convert its result as a async HttpResponse
|
||||||
pub fn db_call(
|
fn db_call(
|
||||||
pool: AppPool,
|
pool: AppPool,
|
||||||
query: api::ApiActions,
|
query: api::ApiActions,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error>
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
{
|
|
||||||
let conn = pool.get().unwrap();
|
let conn = pool.get().unwrap();
|
||||||
web::block(move || api::execute(&conn, query)).then(|res| match res {
|
web::block(move || api::execute(&conn, query)).then(|res| match res {
|
||||||
Ok(r) => HttpResponse::Ok().json(r),
|
Ok(r) => HttpResponse::Ok().json(r),
|
||||||
@@ -34,39 +42,102 @@ pub fn db_call(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_app(config: &mut web::ServiceConfig) {
|
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;
|
use api::ApiActions as Q;
|
||||||
config.service(
|
config.service(
|
||||||
web::scope("/api")
|
web::scope("/api")
|
||||||
|
.wrap(RestrictedAccess)
|
||||||
.service(
|
.service(
|
||||||
web::scope("/players")
|
web::scope("/players")
|
||||||
.service(
|
.service(
|
||||||
web::resource("/").route(
|
web::resource("/")
|
||||||
web::get().to_async(|pool| db_call(pool, Q::FetchPlayers)),
|
.route(web::get().to_async(|pool| db_call(pool, Q::FetchPlayers)))
|
||||||
), //.route(web::post().to_async(endpoints::new_player))
|
.route(web::post().to_async(
|
||||||
|
|pool, player: web::Json<api::NewPlayer>| {
|
||||||
|
db_call(pool, Q::AddPlayer(player.into_inner()))
|
||||||
|
},
|
||||||
|
)),
|
||||||
) // List of players
|
) // List of players
|
||||||
.service(
|
.service(
|
||||||
web::scope("/{player_id}")
|
web::scope("/{player_id}")
|
||||||
.route("/", web::get().to_async(|pool, player: PlayerId| {
|
.route(
|
||||||
db_call(pool, Q::FetchPlayer(*player))
|
"/",
|
||||||
}))
|
web::get().to_async(|pool, player: PlayerId| {
|
||||||
.route("/notifications", web::get().to_async(|pool, player: PlayerId| {
|
db_call(pool, Q::FetchPlayer(*player))
|
||||||
db_call(pool, Q::FetchNotifications(*player))
|
}),
|
||||||
}))
|
)
|
||||||
|
.route(
|
||||||
|
"/notifications",
|
||||||
|
web::get().to_async(|pool, player: PlayerId| {
|
||||||
|
db_call(pool, Q::FetchNotifications(*player))
|
||||||
|
}),
|
||||||
|
)
|
||||||
.service(
|
.service(
|
||||||
web::resource("/claims")
|
web::resource("/claims")
|
||||||
//.route(web::get().to_async(endpoints::player_claims))
|
.route(web::get().to_async(|pool, player: PlayerId| {
|
||||||
.route(web::put().to_async(
|
db_call(pool, Q::FetchPlayerClaims(*player))
|
||||||
|pool, (player, data): (PlayerId, ItemId)| {
|
}))
|
||||||
db_call(pool, Q::ClaimItem(*player, *data))
|
.route(web::post().to_async(
|
||||||
},
|
|pool, (player, data): (PlayerId, IdList)| {
|
||||||
))
|
db_call(pool, Q::ClaimItems(*player, data.into_inner()))
|
||||||
.route(web::delete().to_async(
|
|
||||||
|pool, (player, data): (PlayerId, ItemId)| {
|
|
||||||
db_call(
|
|
||||||
pool,
|
|
||||||
Q::UnclaimItem(*player, *data),
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
@@ -75,10 +146,7 @@ fn configure_app(config: &mut web::ServiceConfig) {
|
|||||||
//.route(web::get().to_async(...))
|
//.route(web::get().to_async(...))
|
||||||
.route(web::put().to_async(
|
.route(web::put().to_async(
|
||||||
|pool, (player, data): (PlayerId, web::Json<f64>)| {
|
|pool, (player, data): (PlayerId, web::Json<f64>)| {
|
||||||
db_call(
|
db_call(pool, Q::UpdateWealth(*player, *data))
|
||||||
pool,
|
|
||||||
Q::UpdateWealth(*player, *data),
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
@@ -88,52 +156,169 @@ fn configure_app(config: &mut web::ServiceConfig) {
|
|||||||
db_call(pool, Q::FetchLoot(*player))
|
db_call(pool, Q::FetchLoot(*player))
|
||||||
}))
|
}))
|
||||||
.route(web::put().to_async(
|
.route(web::put().to_async(
|
||||||
move |pool, (player, data): (PlayerId, ItemListWithMods)| {
|
move |pool, (player, data): (PlayerId, BuySellParams)| {
|
||||||
db_call(pool, Q::BuyItems(*player, data.into_inner()))
|
db_call(pool, Q::BuyItems(*player, data.into_inner()))
|
||||||
},
|
},
|
||||||
))
|
))
|
||||||
.route(web::post().to_async(
|
.route(web::post().to(
|
||||||
move |pool, (player, data): (PlayerId, web::Json<NewGroupLoot>)| {
|
move |pool, (player, data): (PlayerId, NewGroupLoot)| {
|
||||||
match *player {
|
restricted_to_group(
|
||||||
0 => db_call(pool, Q::AddLoot(data.items.clone())),
|
*player,
|
||||||
_ => HttpResponse::Forbidden().finish().into_future(),
|
(pool, Q::AddLoot(data.into_inner())),
|
||||||
}
|
)
|
||||||
},
|
},
|
||||||
))
|
))
|
||||||
.route(web::delete().to_async(
|
.route(web::delete().to_async(
|
||||||
move |pool, (player, data): (PlayerId, ItemListWithMods)| {
|
move |pool, (player, data): (PlayerId, BuySellParams)| {
|
||||||
db_call(pool, Q::SellItems(*player, data.into_inner()))
|
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)))
|
|
||||||
.route(
|
.route(
|
||||||
"/items",
|
"/claims",
|
||||||
web::get()
|
web::get().to_async(|pool| db_call(pool, Q::FetchClaims)),
|
||||||
.to_async(move |pool: AppPool| db_call(pool, Q::FetchInventory)),
|
)
|
||||||
|
.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<()> {
|
pub fn serve() -> std::io::Result<()> {
|
||||||
let www_root: String = env::var("WWW_ROOT").expect("WWW_ROOT must be set");
|
let domain: String = env::var("DOMAIN").expect("DOMAIN must be set");
|
||||||
let pool = db::create_pool();
|
let pool = db::create_pool();
|
||||||
dbg!(&www_root);
|
println!("Serving Loot-a-lot on {}", domain);
|
||||||
|
|
||||||
|
let key = [0; 32]; // TODO: Use a real key
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.data(pool.clone())
|
.data(pool.clone())
|
||||||
.configure(configure_app)
|
.configure(configure_api)
|
||||||
.wrap(
|
.wrap(
|
||||||
Cors::new()
|
Cors::new()
|
||||||
.allowed_origin("http://localhost:8080")
|
.allowed_origin(&domain)
|
||||||
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
||||||
.max_age(3600),
|
.max_age(3600),
|
||||||
)
|
)
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(IdentityService::new(
|
||||||
.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
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")?
|
.bind("127.0.0.1:8088")?
|
||||||
.run()
|
.run()
|
||||||
|
|||||||
Reference in New Issue
Block a user