Skip to content
This repository has been archived by the owner on Feb 8, 2018. It is now read-only.

Commit

Permalink
Simplify takes logic by adding available_today
Browse files Browse the repository at this point in the history
  • Loading branch information
rohitpaulk committed Aug 31, 2016
1 parent 0ed1d31 commit 51af227
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
2 changes: 2 additions & 0 deletions gratipay/billing/payday.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,8 @@ def process_takes(cursor, ts_start):
log("Processing takes.")
cursor.run("""
UPDATE payday_teams SET available_today = LEAST(available, balance);
INSERT INTO payday_takes
SELECT team_id, participant_id, amount
FROM ( SELECT DISTINCT ON (team_id, participant_id)
Expand Down
25 changes: 10 additions & 15 deletions sql/payday.sql
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ CREATE TABLE payday_teams AS
SELECT t.id
, slug
, owner
, available
, available -- The maximum amount that can be distributed to members (ever)
, 0::numeric(35, 2) AS balance
, 0::numeric(35, 2) AS available_today -- The maximum amount that can be distributed to members in this payday
, false AS is_drained
FROM teams t
JOIN participants p
Expand Down Expand Up @@ -208,34 +209,28 @@ CREATE TRIGGER process_payment_instruction BEFORE UPDATE OF is_funded ON payday_

-- Create a trigger to process distributions based on takes

CREATE OR REPLACE FUNCTION process_distribution() RETURNS trigger AS $$
CREATE OR REPLACE FUNCTION process_take() RETURNS trigger AS $$
DECLARE
amount numeric(35,2);
balance_ numeric(35,2);
available_ numeric(35,2);
available_today_ numeric(35,2);
BEGIN
amount := NEW.amount;

balance_ := (SELECT balance FROM payday_teams WHERE id = NEW.team_id);
IF balance_ < amount THEN
amount := balance_;
END IF;

available_ := (SELECT available FROM payday_teams WHERE id = NEW.team_id);
IF available_ < amount THEN
amount := available_;
available_today_ := (SELECT available_today FROM payday_teams WHERE id = NEW.team_id);
IF amount > available_today_ THEN
amount := available_today_;
END IF;

IF amount > 0 THEN
UPDATE payday_teams SET available = (available - amount) WHERE id = NEW.team_id;
UPDATE payday_teams SET available_today = (available_today - amount) WHERE id = NEW.team_id;
EXECUTE pay(NEW.participant_id, NEW.team_id, amount, 'to-participant');
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER process_takes AFTER INSERT ON payday_takes
FOR EACH ROW EXECUTE PROCEDURE process_distribution();
CREATE TRIGGER process_take AFTER INSERT ON payday_takes
FOR EACH ROW EXECUTE PROCEDURE process_take();


-- Create a trigger to process draws
Expand Down

0 comments on commit 51af227

Please sign in to comment.