works on resolve_claims

This commit is contained in:
2019-10-14 15:27:49 +02:00
parent 0df875d6a6
commit b2e319dc15
4 changed files with 65 additions and 42 deletions

View File

@@ -22,49 +22,65 @@ pub struct Claims<'q>(pub &'q DbConnection);
impl<'q> Claims<'q> {
/// Finds a single claim by id.
/// Finds a single claim by association of player and loot ids.
pub fn find(&self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
Ok(
claims::table
.filter(claims::dsl::player_id.eq(player_id))
.filter(claims::dsl::loot_id.eq(loot_id))
.first(self.0)?
)
.first(self.0)
}
/// Adds a claim in database and returns it
pub fn add(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
// We need to validate that the claimed item exists, and is actually owned by group (id 0)
let exists: bool = diesel::select(Loot::exists(loot_id)).get_result(self.0)?;
if !exists {
return Err(diesel::result::Error::NotFound);
};
// We need to validate that the claimed item exists
// AND is actually owned by group (id 0)
let _item = models::item::LootManager(self.0, 0).find(loot_id)?;
let claim = NewClaim::new(player_id, loot_id);
diesel::insert_into(claims::table)
.values(&claim)
.execute(self.0)?;
// Return the created claim
Ok(claims::table.order(claims::dsl::id.desc()).first::<Claim>(self.0)?)
claims::table
.order(claims::dsl::id.desc())
.first::<Claim>(self.0)
}
/// Removes a claim from database, returning it
pub fn remove(self, req_player_id: i32, req_loot_id: i32) -> QueryResult<Claim> {
let claim = self.find(req_player_id, req_loot_id)?;
pub fn remove(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
let claim = self.find(player_id, loot_id)?;
diesel::delete(claims::table.find(claim.id))
.execute(self.0)?;
Ok(claim)
}
pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> {
claims::table
.filter(claims::dsl::loot_id.eq(loot_id))
.load(self.0)
}
pub(crate) fn grouped_by_loot(&self) -> QueryResult<Vec<(models::item::Loot, Vec<Claim>)>> {
let loot = models::item::Loot::owned_by(0).load(self.0)?;
let claims = claims::table
.load(self.0)?
.grouped_by(&loot);
Ok(
loot.into_iter()
.zip(claims)
.collect::<Vec<_>>()
)
}
}
#[derive(Insertable, Debug)]
#[table_name = "claims"]
pub(crate) struct NewClaim {
struct NewClaim {
player_id: i32,
loot_id: i32,
}
impl NewClaim {
pub(crate) fn new(player_id: i32, loot_id: i32) -> Self {
fn new(player_id: i32, loot_id: i32) -> Self {
Self { player_id, loot_id }
}
}