Add history entry and fix bug when completing task (#54)
The reward wasn't properly being distributed to all users Reviewed-on: #54
This commit was merged in pull request #54.
This commit is contained in:
@@ -341,10 +341,22 @@ func (db *Db) CompleteTask(taskId int) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add the history entry
|
||||
err = tx.Query("insert into history (user_id, timestamp, amount) values (?, ?, ?)").
|
||||
Bind(userId, time.Now().Unix(), reward).
|
||||
Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Calculate the sums of all weights
|
||||
var sumOfWeights float64
|
||||
err = tx.Query("select sum(weight) from allowances where user_id = ? and weight > 0").Bind(userId).ScanSingle(&sumOfWeights)
|
||||
sumOfWeights += userWeight
|
||||
|
||||
remainingReward := reward
|
||||
|
||||
// Distribute the reward to the allowances
|
||||
for allowanceRow := range tx.Query("select id, weight from allowances where user_id = ? and weight > 0").Bind(userId).Range(&err) {
|
||||
var allowanceId int
|
||||
var allowanceWeight float64
|
||||
@@ -354,19 +366,19 @@ func (db *Db) CompleteTask(taskId int) error {
|
||||
}
|
||||
|
||||
// Calculate the amount to add to the allowance
|
||||
amount := int((allowanceWeight / sumOfWeights) * float64(reward))
|
||||
amount := int((allowanceWeight / sumOfWeights) * float64(remainingReward))
|
||||
sumOfWeights -= allowanceWeight
|
||||
err = tx.Query("update allowances set balance = balance + ? where id = ? and user_id = ?").
|
||||
Bind(amount, allowanceId, userId).Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reward -= amount
|
||||
remainingReward -= amount
|
||||
}
|
||||
|
||||
// Add the remaining reward to the user
|
||||
err = tx.Query("update users set balance = balance + ? where id = ?").
|
||||
Bind(reward, userId).Exec()
|
||||
Bind(remainingReward, userId).Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user