consent.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. modpol.modules = modpol.modules or {}
  2. modpol.modules.consent = {
  3. type = "consent",
  4. }
  5. -- sets consent to its own callback
  6. modpol.modules.consent.__index = modpol.modules.consent
  7. function temp_consent_process()
  8. return {
  9. org_id = nil,
  10. request_id = nil,
  11. total_votes = 0,
  12. majority_to_pass = 0.51,
  13. votes_yes = {},
  14. votes_no = {}
  15. }
  16. end
  17. -- ===============================================
  18. -- function to create a new consent process to resolve a pending process
  19. function modpol.modules.consent:new_process(request_id, org_id)
  20. local process = temp_consent_process()
  21. process.request_id = request_id
  22. process.org_id = org_id
  23. setmetatable(process, modpol.modules.consent)
  24. modpol.ocutil.log('Created new process for request id #' .. request_id)
  25. return process
  26. end
  27. -- ======================================================
  28. -- function for users to vote on a pending request
  29. function modpol.modules.consent:approve(user, decision)
  30. if not modpol.orgs.get_org(self.org_id):has_member(user) then
  31. modpol.ocutil.log('Error in consent:approve -> user not a member of the org')
  32. return
  33. end
  34. if decision then
  35. table.insert(self.votes_yes, user)
  36. modpol.ocutil.log('User ' .. user .. ' voted yes on request #' .. self.request_id)
  37. else
  38. table.insert(self.votes_no, user)
  39. modpol.ocutil.log('User ' .. user .. ' voted no on request #' .. self.request_id)
  40. end
  41. self.total_votes = self.total_votes + 1
  42. self:update_status()
  43. end
  44. -- ===================================================
  45. -- determines whether process has finished and resolves request if it has (unfinished)
  46. function modpol.modules.consent:update_status()
  47. local process_org = modpol.orgs.get_org(self.org_id)
  48. local eligible_voters = process_org:get_member_count()
  49. local votes_needed = math.ceil(self.majority_to_pass * eligible_voters)
  50. if #self.votes_yes >= votes_needed then
  51. modpol.ocutil.log('Request #' .. self.request_id .. ' passes')
  52. process_org:resolve_request(self.request_id, true)
  53. elseif #self.votes_no >= votes_needed then
  54. modpol.ocutil.log('Request #' .. self.request_id .. ' fails to pass')
  55. process_org:resolve_request(self.request_id, false)
  56. else
  57. modpol.ocutil.log('Waiting for more votes...')
  58. end
  59. end