Compare commits
4 Commits
dc0874bd12
...
ae991bf4dc
| Author | SHA1 | Date | |
|---|---|---|---|
| ae991bf4dc | |||
| 40e39d5a65 | |||
| 559ce804a7 | |||
| 9a3744e340 |
@@ -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)
|
||||
);
|
||||
@@ -41,6 +41,42 @@ pub fn create_pool() -> Pool {
|
||||
}
|
||||
|
||||
|
||||
/// Every possible update which can happen during a query
|
||||
#[derive(Serialize, Debug)]
|
||||
pub enum Update {
|
||||
Wealth(Wealth),
|
||||
ItemAdded(Item),
|
||||
ItemRemoved(Item),
|
||||
ClaimAdded(Claim),
|
||||
ClaimRemoved(Claim),
|
||||
}
|
||||
|
||||
/// Every value which can be queried
|
||||
#[derive(Debug)]
|
||||
pub enum Value {
|
||||
Player(Player),
|
||||
Item(Item),
|
||||
Claim(Claim),
|
||||
ItemList(Vec<Item>),
|
||||
ClaimList(Vec<Claim>),
|
||||
PlayerList(Vec<Player>),
|
||||
Notifications(Vec<String>),
|
||||
}
|
||||
|
||||
impl serde::Serialize for Value {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
match self {
|
||||
Value::Player(v) => v.serialize(serializer),
|
||||
Value::Item(v) => v.serialize(serializer),
|
||||
Value::Claim(v) => v.serialize(serializer),
|
||||
Value::ItemList(v) => v.serialize(serializer),
|
||||
Value::ClaimList(v) => v.serialize(serializer),
|
||||
Value::PlayerList(v) => v.serialize(serializer),
|
||||
Value::Notifications(v) => v.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sells a single item inside a transaction
|
||||
///
|
||||
/// # Returns
|
||||
@@ -100,22 +136,20 @@ pub fn fetch_claims(conn: &DbConnection) -> QueryResult<Vec<models::Claim>> {
|
||||
pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
|
||||
let data = models::claim::Claims(conn).grouped_by_item()?;
|
||||
dbg!(&data);
|
||||
|
||||
for (item, claims) in data {
|
||||
match claims.len() {
|
||||
1 => {
|
||||
let claim = claims.get(0).unwrap();
|
||||
let player_id = claim.player_id;
|
||||
conn.transaction(|| {
|
||||
claim.resolve_claim(conn)?;
|
||||
//models::item::LootManager(self.0, 0).set_owner(claim.loot_id, claim.player_id)?;
|
||||
models::player::AsPlayer(conn, player_id).update_debt(item.sell_value())
|
||||
})?;
|
||||
}
|
||||
_ => (),
|
||||
conn.transaction(move || {
|
||||
for (item, mut claims) in data {
|
||||
if claims.len() > 1 {
|
||||
// TODO: better sorting mechanism :)
|
||||
claims.sort_by(|a,b| a.resolve.cmp(&b.resolve));
|
||||
}
|
||||
let winner = claims.get(0).expect("Claims should not be empty !");
|
||||
let player_id = winner.player_id;
|
||||
winner.resolve_claim(conn)?;
|
||||
models::player::AsPlayer(conn, player_id)
|
||||
.update_debt(item.sell_value())?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Split up and share group money among selected players
|
||||
@@ -125,8 +159,18 @@ pub fn split_and_share(conn: &DbConnection, amount: i32, players: Vec<i32>) -> Q
|
||||
) as f64;
|
||||
conn.transaction(|| {
|
||||
for p in players.into_iter() {
|
||||
AsPlayer(conn, p).update_wealth(share)?;
|
||||
AsPlayer(conn, 0).update_wealth(-share)?;
|
||||
let player = Players(conn).find(p)?;
|
||||
// Take debt into account
|
||||
match share - player.debt as f64 {
|
||||
rest if rest > 0.0 => {
|
||||
AsPlayer(conn, p).update_debt(-player.debt)?;
|
||||
AsPlayer(conn, p).update_wealth(rest)?;
|
||||
AsPlayer(conn, 0).update_wealth(-rest)?;
|
||||
},
|
||||
_ => {
|
||||
AsPlayer(conn, p).update_debt(-share as i32)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Wealth::from_gp(share))
|
||||
})
|
||||
|
||||
42
lootalot_db/src/models/history.rs
Normal file
42
lootalot_db/src/models/history.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use diesel::prelude::*;
|
||||
use crate::schema::history;
|
||||
use crate::{DbConnection, QueryResult};
|
||||
|
||||
/// An event in history
|
||||
#[derive(Debug, Queryable)]
|
||||
pub struct Event {
|
||||
id: i32,
|
||||
player_id: i32,
|
||||
event_date: String,
|
||||
text: String,
|
||||
updates: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Insertable)]
|
||||
#[table_name = "history"]
|
||||
struct NewEvent<'a> {
|
||||
player_id: i32,
|
||||
text: &'a str,
|
||||
updates: &'a str,
|
||||
}
|
||||
|
||||
/// Insert a new event
|
||||
pub fn insert_event(conn: &DbConnection, id: i32, text: &str, updates: &str) -> QueryResult<Event> {
|
||||
diesel::insert_into(history::table)
|
||||
.values(&NewEvent{
|
||||
player_id: id,
|
||||
text,
|
||||
updates,
|
||||
})
|
||||
.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)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod claim;
|
||||
pub mod item;
|
||||
pub mod player;
|
||||
pub mod history;
|
||||
|
||||
pub use claim::Claim;
|
||||
pub use item::Item;
|
||||
|
||||
@@ -7,6 +7,16 @@ table! {
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
history (id) {
|
||||
id -> Integer,
|
||||
player_id -> Integer,
|
||||
event_date -> Timestamp,
|
||||
text -> Text,
|
||||
updates -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
items (id) {
|
||||
id -> Integer,
|
||||
@@ -46,11 +56,13 @@ table! {
|
||||
|
||||
joinable!(claims -> looted (loot_id));
|
||||
joinable!(claims -> players (player_id));
|
||||
joinable!(history -> players (player_id));
|
||||
joinable!(looted -> players (owner_id));
|
||||
joinable!(notifications -> players (player_id));
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
claims,
|
||||
history,
|
||||
items,
|
||||
looted,
|
||||
notifications,
|
||||
|
||||
130
src/api.rs
130
src/api.rs
@@ -1,5 +1,4 @@
|
||||
use diesel::prelude::*;
|
||||
use lootalot_db::{self as db, DbConnection, QueryResult};
|
||||
use lootalot_db::{self as db, DbConnection, Update, Value};
|
||||
|
||||
pub type ItemListWithMods = Vec<(i32, Option<f64>)>;
|
||||
|
||||
@@ -10,42 +9,6 @@ pub struct SellParams {
|
||||
global_mod: Option<f64>,
|
||||
}
|
||||
|
||||
/// Every possible update which can happen during a query
|
||||
#[derive(Serialize, Debug)]
|
||||
pub enum Update {
|
||||
Wealth(db::Wealth),
|
||||
ItemAdded(db::Item),
|
||||
ItemRemoved(db::Item),
|
||||
ClaimAdded(db::Claim),
|
||||
ClaimRemoved(db::Claim),
|
||||
}
|
||||
|
||||
/// Every value which can be queried
|
||||
#[derive(Debug)]
|
||||
pub enum Value {
|
||||
Player(db::Player),
|
||||
Item(db::Item),
|
||||
Claim(db::Claim),
|
||||
ItemList(Vec<db::Item>),
|
||||
ClaimList(Vec<db::Claim>),
|
||||
PlayerList(Vec<db::Player>),
|
||||
Notifications(Vec<String>),
|
||||
}
|
||||
|
||||
impl serde::Serialize for Value {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
match self {
|
||||
Value::Player(v) => v.serialize(serializer),
|
||||
Value::Item(v) => v.serialize(serializer),
|
||||
Value::Claim(v) => v.serialize(serializer),
|
||||
Value::ItemList(v) => v.serialize(serializer),
|
||||
Value::ClaimList(v) => v.serialize(serializer),
|
||||
Value::PlayerList(v) => v.serialize(serializer),
|
||||
Value::Notifications(v) => v.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generic response for all queries
|
||||
#[derive(Serialize, Debug, Default)]
|
||||
pub struct ApiResponse {
|
||||
@@ -60,7 +23,7 @@ pub struct 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() {
|
||||
v.push(update);
|
||||
} else {
|
||||
@@ -76,7 +39,7 @@ impl ApiResponse {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_value(&mut self, value: Value) {
|
||||
fn set_value(&mut self, value: db::Value) {
|
||||
self.value = Some(value);
|
||||
}
|
||||
|
||||
@@ -122,25 +85,47 @@ pub fn execute(
|
||||
let mut response = ApiResponse::default();
|
||||
// TODO: 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: () = match query {
|
||||
ApiActions::FetchPlayers => response.set_value(Value::PlayerList(db::Players(conn).all()?)),
|
||||
ApiActions::FetchInventory => response.set_value(Value::ItemList(db::Inventory(conn).all()?)),
|
||||
ApiActions::FetchClaims => response.set_value(Value::ClaimList(db::fetch_claims(conn)?)),
|
||||
ApiActions::FetchPlayer(id) => response.set_value(Value::Player(db::Players(conn).find(id)?)),
|
||||
ApiActions::FetchNotifications(id) => response.set_value(Value::Notifications(db::AsPlayer(conn, id).notifications()?)),
|
||||
ApiActions::FetchLoot(id) => response.set_value(Value::ItemList(db::LootManager(conn, id).all()?)),
|
||||
let action_text: Option<&str> = match query {
|
||||
ApiActions::FetchPlayers => {
|
||||
response.set_value(Value::PlayerList(db::Players(conn).all()?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchInventory => {
|
||||
response.set_value(Value::ItemList(db::Inventory(conn).all()?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchClaims => {
|
||||
response.set_value(Value::ClaimList(db::fetch_claims(conn)?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchPlayer(id) => {
|
||||
response.set_value(Value::Player(db::Players(conn).find(id)?));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchNotifications(id) => {
|
||||
response.set_value(Value::Notifications(
|
||||
db::AsPlayer(conn, id).notifications()?,
|
||||
));
|
||||
None
|
||||
}
|
||||
ApiActions::FetchLoot(id) => {
|
||||
response.set_value(Value::ItemList(db::LootManager(conn, id).all()?));
|
||||
None
|
||||
}
|
||||
ApiActions::UpdateWealth(id, amount) => {
|
||||
response.push_update(Update::Wealth(
|
||||
db::AsPlayer(conn, id).update_wealth(amount)?,
|
||||
));
|
||||
response.notify(format!("Mis à jour ({}po)!", amount));
|
||||
Some("Argent mis à jour")
|
||||
}
|
||||
ApiActions::BuyItems(id, params) => {
|
||||
// TODO: check that player has enough money !
|
||||
let mut cumulated_diff: Vec<db::Wealth> = Vec::with_capacity(params.len());
|
||||
let mut added_items: u16 = 0;
|
||||
for (item_id, price_mod) in params.into_iter() {
|
||||
if let Ok((item, diff)) = db::buy_item_from_inventory(conn, id, item_id, price_mod) {
|
||||
if let Ok((item, diff)) = db::buy_item_from_inventory(conn, id, item_id, price_mod)
|
||||
{
|
||||
cumulated_diff.push(diff);
|
||||
response.push_update(Update::ItemAdded(item));
|
||||
added_items += 1;
|
||||
@@ -151,8 +136,13 @@ pub fn execute(
|
||||
let total_amount = cumulated_diff
|
||||
.into_iter()
|
||||
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
||||
response.notify(format!("{} objets achetés pour {}po", added_items, total_amount.to_gp()));
|
||||
response.notify(format!(
|
||||
"{} objets achetés pour {}po",
|
||||
added_items,
|
||||
total_amount.to_gp()
|
||||
));
|
||||
response.push_update(Update::Wealth(total_amount));
|
||||
Some("Achat d'objets")
|
||||
}
|
||||
// Behavior differs if player is group or regular.
|
||||
// Group sells item like players then split the total amount among players.
|
||||
@@ -160,7 +150,9 @@ pub fn execute(
|
||||
let mut all_results: Vec<db::Wealth> = Vec::with_capacity(params.items.len());
|
||||
let mut sold_items: u16 = 0;
|
||||
for (loot_id, price_mod) in params.items.iter() {
|
||||
if let Ok((deleted, diff)) = db::sell_item_transaction(conn, id, *loot_id, *price_mod) {
|
||||
if let Ok((deleted, diff)) =
|
||||
db::sell_item_transaction(conn, id, *loot_id, *price_mod)
|
||||
{
|
||||
all_results.push(diff);
|
||||
response.push_update(Update::ItemRemoved(deleted));
|
||||
sold_items += 1;
|
||||
@@ -173,27 +165,37 @@ pub fn execute(
|
||||
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
||||
match id {
|
||||
0 => {
|
||||
let share = db::split_and_share(conn, total_amount.to_gp() as i32, params.players.expect("Should not be None"))?;
|
||||
response.notify(format!("Les objets ont été vendus, chaque joueur a reçu {} po", share.to_gp()));
|
||||
let share = db::split_and_share(
|
||||
conn,
|
||||
total_amount.to_gp() as i32,
|
||||
params.players.expect("Should not be None"),
|
||||
)?;
|
||||
response.notify(format!(
|
||||
"Les objets ont été vendus, chaque joueur a reçu {} po",
|
||||
share.to_gp()
|
||||
));
|
||||
response.push_update(Update::Wealth(share));
|
||||
},
|
||||
}
|
||||
_ => {
|
||||
response.notify(format!("{} objet(s) vendu(s) pour {} po", sold_items, total_amount.to_gp()));
|
||||
response.notify(format!(
|
||||
"{} objet(s) vendu(s) pour {} po",
|
||||
sold_items,
|
||||
total_amount.to_gp()
|
||||
));
|
||||
response.push_update(Update::Wealth(total_amount));
|
||||
}
|
||||
}
|
||||
Some("Vente d'objets")
|
||||
}
|
||||
ApiActions::ClaimItem(id, item) => {
|
||||
response.push_update(Update::ClaimAdded(
|
||||
db::Claims(conn).add(id, item)?,
|
||||
));
|
||||
response.push_update(Update::ClaimAdded(db::Claims(conn).add(id, item)?));
|
||||
response.notify(format!("Pour moi !"));
|
||||
None
|
||||
}
|
||||
ApiActions::UnclaimItem(id, item) => {
|
||||
response.push_update(Update::ClaimRemoved(
|
||||
db::Claims(conn).remove(id, item)?,
|
||||
));
|
||||
response.push_update(Update::ClaimRemoved(db::Claims(conn).remove(id, item)?));
|
||||
response.notify(format!("Bof! Finalement non."));
|
||||
None
|
||||
}
|
||||
// Group actions
|
||||
ApiActions::AddLoot(items) => {
|
||||
@@ -213,17 +215,17 @@ pub fn execute(
|
||||
{
|
||||
response.push_error(format!("Erreur durant la notification : {:?}", e));
|
||||
};
|
||||
Some("Nouveau loot")
|
||||
}
|
||||
};
|
||||
|
||||
// match _action_text -> Save updates in DB
|
||||
dbg!(&action_text);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Reverts the last action stored for player
|
||||
fn revert_last_action(
|
||||
conn: &DbConnection,
|
||||
id: i32,
|
||||
) -> Result<ApiResponse, diesel::result::Error> {
|
||||
fn revert_last_action(conn: &DbConnection, id: i32) -> Result<ApiResponse, diesel::result::Error> {
|
||||
let mut response = ApiResponse::default();
|
||||
// 1. Load the last action
|
||||
// 2. Iterate trought updates and reverse them (in a single transaction)
|
||||
|
||||
Reference in New Issue
Block a user