We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
members page does not reflect available take from account balance
when a balance is available, the members page of a team does not reflect that members will be paid from the team balance.
![balance](https://cloud.githubusercontent.com/assets/1970586/3528854/761a8492-0793-11e4-8f7a-d51c5ae9808f.png)

members page does not reflect available take from account balance
when a balance is available, the members page of a team does not reflect that members will be paid from the team balance.
![balance](https://cloud.githubusercontent.com/assets/1970586/3528854/761a8492-0793-11e4-8f7a-d51c5ae9808f.png)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `gittip/models/_mixin_team.py`
Content:
```
1 """Teams on Gittip are plural participants with members.
2 """
3 from collections import OrderedDict
4 from decimal import Decimal
5 
6 from aspen.utils import typecheck
7 
8 
9 class MemberLimitReached(Exception): pass
10 
11 class StubParticipantAdded(Exception): pass
12 
13 class MixinTeam(object):
14     """This class provides methods for working with a Participant as a Team.
15 
16     :param Participant participant: the underlying :py:class:`~gittip.participant.Participant` object for this team
17 
18     """
19 
20     # XXX These were all written with the ORM and need to be converted.
21 
22     def __init__(self, participant):
23         self.participant = participant
24 
25     def show_as_team(self, user):
26         """Return a boolean, whether to show this participant as a team.
27         """
28         if not self.IS_PLURAL:
29             return False
30         if user.ADMIN:
31             return True
32         if not self.get_takes():
33             if self == user.participant:
34                 return True
35             return False
36         return True
37 
38     def add_member(self, member):
39         """Add a member to this team.
40         """
41         assert self.IS_PLURAL
42         if len(self.get_takes()) == 149:
43             raise MemberLimitReached
44         if not member.is_claimed:
45             raise StubParticipantAdded
46         self.__set_take_for(member, Decimal('0.01'), self)
47 
48     def remove_member(self, member):
49         """Remove a member from this team.
50         """
51         assert self.IS_PLURAL
52         self.__set_take_for(member, Decimal('0.00'), self)
53 
54     def remove_all_members(self, cursor=None):
55         (cursor or self.db).run("""
56             INSERT INTO takes (ctime, member, team, amount, recorder) (
57                 SELECT ctime, member, %(username)s, 0.00, %(username)s
58                   FROM current_takes
59                  WHERE team=%(username)s
60                    AND amount > 0
61             );
62         """, dict(username=self.username))
63 
64     def member_of(self, team):
65         """Given a Participant object, return a boolean.
66         """
67         assert team.IS_PLURAL
68         for take in team.get_takes():
69             if take['member'] == self.username:
70                 return True
71         return False
72 
73     def get_take_last_week_for(self, member):
74         """What did the user actually take most recently? Used in throttling.
75         """
76         assert self.IS_PLURAL
77         membername = member.username if hasattr(member, 'username') \
78                                                         else member['username']
79         return self.db.one("""
80 
81             SELECT amount
82               FROM transfers
83              WHERE tipper=%s AND tippee=%s AND context='take'
84                AND timestamp >
85                 (SELECT ts_start FROM paydays ORDER BY ts_start DESC LIMIT 1)
86           ORDER BY timestamp DESC LIMIT 1
87 
88         """, (self.username, membername), default=Decimal('0.00'))
89 
90     def get_take_for(self, member):
91         """Return a Decimal representation of the take for this member, or 0.
92         """
93         assert self.IS_PLURAL
94         return self.db.one( "SELECT amount FROM current_takes "
95                             "WHERE member=%s AND team=%s"
96                           , (member.username, self.username)
97                           , default=Decimal('0.00')
98                            )
99 
100     def compute_max_this_week(self, last_week):
101         """2x last week's take, but at least a dollar.
102         """
103         return max(last_week * Decimal('2'), Decimal('1.00'))
104 
105     def set_take_for(self, member, take, recorder):
106         """Sets member's take from the team pool.
107         """
108         assert self.IS_PLURAL
109 
110         # lazy import to avoid circular import
111         from gittip.security.user import User
112         from gittip.models.participant import Participant
113 
114         typecheck( member, Participant
115                  , take, Decimal
116                  , recorder, (Participant, User)
117                   )
118 
119         last_week = self.get_take_last_week_for(member)
120         max_this_week = self.compute_max_this_week(last_week)
121         if take > max_this_week:
122             take = max_this_week
123 
124         self.__set_take_for(member, take, recorder)
125         return take
126 
127     def __set_take_for(self, member, amount, recorder):
128         assert self.IS_PLURAL
129         # XXX Factored out for testing purposes only! :O Use .set_take_for.
130         with self.db.get_cursor() as cursor:
131             # Lock to avoid race conditions
132             cursor.run("LOCK TABLE takes IN EXCLUSIVE MODE")
133             # Compute the current takes
134             old_takes = self.compute_actual_takes(cursor)
135             # Insert the new take
136             cursor.run("""
137 
138                 INSERT INTO takes (ctime, member, team, amount, recorder)
139                  VALUES ( COALESCE (( SELECT ctime
140                                         FROM takes
141                                        WHERE member=%(member)s
142                                          AND team=%(team)s
143                                        LIMIT 1
144                                      ), CURRENT_TIMESTAMP)
145                         , %(member)s
146                         , %(team)s
147                         , %(amount)s
148                         , %(recorder)s
149                          )
150 
151             """, dict(member=member.username, team=self.username, amount=amount,
152                       recorder=recorder.username))
153             # Compute the new takes
154             new_takes = self.compute_actual_takes(cursor)
155             # Update receiving amounts in the participants table
156             self.update_taking(old_takes, new_takes, cursor, member)
157 
158     def update_taking(self, old_takes, new_takes, cursor=None, member=None):
159         """Update `taking` amounts based on the difference between `old_takes`
160         and `new_takes`.
161         """
162         for username in set(old_takes.keys()).union(new_takes.keys()):
163             if username == self.username:
164                 continue
165             old = old_takes.get(username, {}).get('actual_amount', Decimal(0))
166             new = new_takes.get(username, {}).get('actual_amount', Decimal(0))
167             diff = new - old
168             if diff != 0:
169                 r = (self.db or cursor).one("""
170                     UPDATE participants
171                        SET taking = (taking + %(diff)s)
172                          , receiving = (receiving + %(diff)s)
173                      WHERE username=%(username)s
174                  RETURNING taking, receiving
175                 """, dict(username=username, diff=diff))
176                 if member and username == member.username:
177                     member.set_attributes(**r._asdict())
178 
179     def get_takes(self, for_payday=False, cursor=None):
180         """Return a list of member takes for a team.
181 
182         This is implemented parallel to Participant.get_tips_and_total. See
183         over there for an explanation of for_payday.
184 
185         """
186         assert self.IS_PLURAL
187 
188         args = dict(team=self.username)
189 
190         if for_payday:
191             args['ts_start'] = for_payday
192 
193             # Get the takes for this team, as they were before ts_start,
194             # filtering out the ones we've already transferred (in case payday
195             # is interrupted and restarted).
196 
197             TAKES = """\
198 
199                 SELECT * FROM (
200                      SELECT DISTINCT ON (member) t.*
201                        FROM takes t
202                        JOIN participants p ON p.username = member
203                       WHERE team=%(team)s
204                         AND mtime < %(ts_start)s
205                         AND p.is_suspicious IS NOT true
206                         AND ( SELECT id
207                                 FROM transfers
208                                WHERE tipper=t.team
209                                  AND tippee=t.member
210                                  AND context='take'
211                                  AND timestamp >= %(ts_start)s
212                              ) IS NULL
213                    ORDER BY member, mtime DESC
214                 ) AS foo
215                 ORDER BY ctime DESC
216 
217             """
218         else:
219             TAKES = """\
220 
221                 SELECT member, amount, ctime, mtime
222                   FROM current_takes
223                  WHERE team=%(team)s
224               ORDER BY ctime DESC
225 
226             """
227 
228         records = (cursor or self.db).all(TAKES, args)
229         return [r._asdict() for r in records]
230 
231     def get_team_take(self, cursor=None):
232         """Return a single take for a team, the team itself's take.
233         """
234         assert self.IS_PLURAL
235         TAKE = "SELECT sum(amount) FROM current_takes WHERE team=%s"
236         total_take = (cursor or self.db).one(TAKE, (self.username,), default=0)
237         team_take = max(self.receiving - total_take, 0)
238         membership = { "ctime": None
239                      , "mtime": None
240                      , "member": self.username
241                      , "amount": team_take
242                       }
243         return membership
244 
245     def compute_actual_takes(self, cursor=None):
246         """Get the takes, compute the actual amounts, and return an OrderedDict.
247         """
248         actual_takes = OrderedDict()
249         nominal_takes = self.get_takes(cursor=cursor)
250         nominal_takes.append(self.get_team_take(cursor=cursor))
251         budget = balance = self.receiving
252         for take in nominal_takes:
253             nominal_amount = take['nominal_amount'] = take.pop('amount')
254             actual_amount = take['actual_amount'] = min(nominal_amount, balance)
255             balance -= actual_amount
256             take['balance'] = balance
257             take['percentage'] = (actual_amount / budget) if budget > 0 else 0
258             actual_takes[take['member']] = take
259         return actual_takes
260 
261     def get_members(self, current_participant):
262         """Return a list of member dicts.
263         """
264         assert self.IS_PLURAL
265         takes = self.compute_actual_takes()
266         members = []
267         for take in takes.values():
268             member = {}
269             member['username'] = take['member']
270             member['take'] = take['nominal_amount']
271             member['balance'] = take['balance']
272             member['percentage'] = take['percentage']
273 
274             member['removal_allowed'] = current_participant == self
275             member['editing_allowed'] = False
276             member['is_current_user'] = False
277             if current_participant is not None:
278                 if member['username'] == current_participant.username:
279                     member['is_current_user'] = True
280                     if take['ctime'] is not None:
281                         # current user, but not the team itself
282                         member['editing_allowed']= True
283 
284             member['last_week'] = last_week = self.get_take_last_week_for(member)
285             member['max_this_week'] = self.compute_max_this_week(last_week)
286             members.append(member)
287         return members
288
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/gittip/models/_mixin_team.py b/gittip/models/_mixin_team.py
--- a/gittip/models/_mixin_team.py
+++ b/gittip/models/_mixin_team.py
@@ -248,11 +248,12 @@
         actual_takes = OrderedDict()
         nominal_takes = self.get_takes(cursor=cursor)
         nominal_takes.append(self.get_team_take(cursor=cursor))
-        budget = balance = self.receiving
+        budget = balance = self.balance + self.receiving
         for take in nominal_takes:
             nominal_amount = take['nominal_amount'] = take.pop('amount')
             actual_amount = take['actual_amount'] = min(nominal_amount, balance)
-            balance -= actual_amount
+            if take['member'] != self.username:
+                balance -= actual_amount
             take['balance'] = balance
             take['percentage'] = (actual_amount / budget) if budget > 0 else 0
             actual_takes[take['member']] = take

{"golden_diff": "diff --git a/gittip/models/_mixin_team.py b/gittip/models/_mixin_team.py\n--- a/gittip/models/_mixin_team.py\n+++ b/gittip/models/_mixin_team.py\n@@ -248,11 +248,12 @@\n         actual_takes = OrderedDict()\n         nominal_takes = self.get_takes(cursor=cursor)\n         nominal_takes.append(self.get_team_take(cursor=cursor))\n-        budget = balance = self.receiving\n+        budget = balance = self.balance + self.receiving\n         for take in nominal_takes:\n             nominal_amount = take['nominal_amount'] = take.pop('amount')\n             actual_amount = take['actual_amount'] = min(nominal_amount, balance)\n-            balance -= actual_amount\n+            if take['member'] != self.username:\n+                balance -= actual_amount\n             take['balance'] = balance\n             take['percentage'] = (actual_amount / budget) if budget > 0 else 0\n             actual_takes[take['member']] = take\n", "issue": "members page does not reflect available take from account balance\nwhen a balance is available, the members page of a team does not reflect that members will be paid from the team balance.\n![balance](https://cloud.githubusercontent.com/assets/1970586/3528854/761a8492-0793-11e4-8f7a-d51c5ae9808f.png)\n\nmembers page does not reflect available take from account balance\nwhen a balance is available, the members page of a team does not reflect that members will be paid from the team balance.\n![balance](https://cloud.githubusercontent.com/assets/1970586/3528854/761a8492-0793-11e4-8f7a-d51c5ae9808f.png)\n\n", "before_files": [{"content": "\"\"\"Teams on Gittip are plural participants with members.\n\"\"\"\nfrom collections import OrderedDict\nfrom decimal import Decimal\n\nfrom aspen.utils import typecheck\n\n\nclass MemberLimitReached(Exception): pass\n\nclass StubParticipantAdded(Exception): pass\n\nclass MixinTeam(object):\n    \"\"\"This class provides methods for working with a Participant as a Team.\n\n    :param Participant participant: the underlying :py:class:`~gittip.participant.Participant` object for this team\n\n    \"\"\"\n\n    # XXX These were all written with the ORM and need to be converted.\n\n    def __init__(self, participant):\n        self.participant = participant\n\n    def show_as_team(self, user):\n        \"\"\"Return a boolean, whether to show this participant as a team.\n        \"\"\"\n        if not self.IS_PLURAL:\n            return False\n        if user.ADMIN:\n            return True\n        if not self.get_takes():\n            if self == user.participant:\n                return True\n            return False\n        return True\n\n    def add_member(self, member):\n        \"\"\"Add a member to this team.\n        \"\"\"\n        assert self.IS_PLURAL\n        if len(self.get_takes()) == 149:\n            raise MemberLimitReached\n        if not member.is_claimed:\n            raise StubParticipantAdded\n        self.__set_take_for(member, Decimal('0.01'), self)\n\n    def remove_member(self, member):\n        \"\"\"Remove a member from this team.\n        \"\"\"\n        assert self.IS_PLURAL\n        self.__set_take_for(member, Decimal('0.00'), self)\n\n    def remove_all_members(self, cursor=None):\n        (cursor or self.db).run(\"\"\"\n            INSERT INTO takes (ctime, member, team, amount, recorder) (\n                SELECT ctime, member, %(username)s, 0.00, %(username)s\n                  FROM current_takes\n                 WHERE team=%(username)s\n                   AND amount > 0\n            );\n        \"\"\", dict(username=self.username))\n\n    def member_of(self, team):\n        \"\"\"Given a Participant object, return a boolean.\n        \"\"\"\n        assert team.IS_PLURAL\n        for take in team.get_takes():\n            if take['member'] == self.username:\n                return True\n        return False\n\n    def get_take_last_week_for(self, member):\n        \"\"\"What did the user actually take most recently? Used in throttling.\n        \"\"\"\n        assert self.IS_PLURAL\n        membername = member.username if hasattr(member, 'username') \\\n                                                        else member['username']\n        return self.db.one(\"\"\"\n\n            SELECT amount\n              FROM transfers\n             WHERE tipper=%s AND tippee=%s AND context='take'\n               AND timestamp >\n                (SELECT ts_start FROM paydays ORDER BY ts_start DESC LIMIT 1)\n          ORDER BY timestamp DESC LIMIT 1\n\n        \"\"\", (self.username, membername), default=Decimal('0.00'))\n\n    def get_take_for(self, member):\n        \"\"\"Return a Decimal representation of the take for this member, or 0.\n        \"\"\"\n        assert self.IS_PLURAL\n        return self.db.one( \"SELECT amount FROM current_takes \"\n                            \"WHERE member=%s AND team=%s\"\n                          , (member.username, self.username)\n                          , default=Decimal('0.00')\n                           )\n\n    def compute_max_this_week(self, last_week):\n        \"\"\"2x last week's take, but at least a dollar.\n        \"\"\"\n        return max(last_week * Decimal('2'), Decimal('1.00'))\n\n    def set_take_for(self, member, take, recorder):\n        \"\"\"Sets member's take from the team pool.\n        \"\"\"\n        assert self.IS_PLURAL\n\n        # lazy import to avoid circular import\n        from gittip.security.user import User\n        from gittip.models.participant import Participant\n\n        typecheck( member, Participant\n                 , take, Decimal\n                 , recorder, (Participant, User)\n                  )\n\n        last_week = self.get_take_last_week_for(member)\n        max_this_week = self.compute_max_this_week(last_week)\n        if take > max_this_week:\n            take = max_this_week\n\n        self.__set_take_for(member, take, recorder)\n        return take\n\n    def __set_take_for(self, member, amount, recorder):\n        assert self.IS_PLURAL\n        # XXX Factored out for testing purposes only! :O Use .set_take_for.\n        with self.db.get_cursor() as cursor:\n            # Lock to avoid race conditions\n            cursor.run(\"LOCK TABLE takes IN EXCLUSIVE MODE\")\n            # Compute the current takes\n            old_takes = self.compute_actual_takes(cursor)\n            # Insert the new take\n            cursor.run(\"\"\"\n\n                INSERT INTO takes (ctime, member, team, amount, recorder)\n                 VALUES ( COALESCE (( SELECT ctime\n                                        FROM takes\n                                       WHERE member=%(member)s\n                                         AND team=%(team)s\n                                       LIMIT 1\n                                     ), CURRENT_TIMESTAMP)\n                        , %(member)s\n                        , %(team)s\n                        , %(amount)s\n                        , %(recorder)s\n                         )\n\n            \"\"\", dict(member=member.username, team=self.username, amount=amount,\n                      recorder=recorder.username))\n            # Compute the new takes\n            new_takes = self.compute_actual_takes(cursor)\n            # Update receiving amounts in the participants table\n            self.update_taking(old_takes, new_takes, cursor, member)\n\n    def update_taking(self, old_takes, new_takes, cursor=None, member=None):\n        \"\"\"Update `taking` amounts based on the difference between `old_takes`\n        and `new_takes`.\n        \"\"\"\n        for username in set(old_takes.keys()).union(new_takes.keys()):\n            if username == self.username:\n                continue\n            old = old_takes.get(username, {}).get('actual_amount', Decimal(0))\n            new = new_takes.get(username, {}).get('actual_amount', Decimal(0))\n            diff = new - old\n            if diff != 0:\n                r = (self.db or cursor).one(\"\"\"\n                    UPDATE participants\n                       SET taking = (taking + %(diff)s)\n                         , receiving = (receiving + %(diff)s)\n                     WHERE username=%(username)s\n                 RETURNING taking, receiving\n                \"\"\", dict(username=username, diff=diff))\n                if member and username == member.username:\n                    member.set_attributes(**r._asdict())\n\n    def get_takes(self, for_payday=False, cursor=None):\n        \"\"\"Return a list of member takes for a team.\n\n        This is implemented parallel to Participant.get_tips_and_total. See\n        over there for an explanation of for_payday.\n\n        \"\"\"\n        assert self.IS_PLURAL\n\n        args = dict(team=self.username)\n\n        if for_payday:\n            args['ts_start'] = for_payday\n\n            # Get the takes for this team, as they were before ts_start,\n            # filtering out the ones we've already transferred (in case payday\n            # is interrupted and restarted).\n\n            TAKES = \"\"\"\\\n\n                SELECT * FROM (\n                     SELECT DISTINCT ON (member) t.*\n                       FROM takes t\n                       JOIN participants p ON p.username = member\n                      WHERE team=%(team)s\n                        AND mtime < %(ts_start)s\n                        AND p.is_suspicious IS NOT true\n                        AND ( SELECT id\n                                FROM transfers\n                               WHERE tipper=t.team\n                                 AND tippee=t.member\n                                 AND context='take'\n                                 AND timestamp >= %(ts_start)s\n                             ) IS NULL\n                   ORDER BY member, mtime DESC\n                ) AS foo\n                ORDER BY ctime DESC\n\n            \"\"\"\n        else:\n            TAKES = \"\"\"\\\n\n                SELECT member, amount, ctime, mtime\n                  FROM current_takes\n                 WHERE team=%(team)s\n              ORDER BY ctime DESC\n\n            \"\"\"\n\n        records = (cursor or self.db).all(TAKES, args)\n        return [r._asdict() for r in records]\n\n    def get_team_take(self, cursor=None):\n        \"\"\"Return a single take for a team, the team itself's take.\n        \"\"\"\n        assert self.IS_PLURAL\n        TAKE = \"SELECT sum(amount) FROM current_takes WHERE team=%s\"\n        total_take = (cursor or self.db).one(TAKE, (self.username,), default=0)\n        team_take = max(self.receiving - total_take, 0)\n        membership = { \"ctime\": None\n                     , \"mtime\": None\n                     , \"member\": self.username\n                     , \"amount\": team_take\n                      }\n        return membership\n\n    def compute_actual_takes(self, cursor=None):\n        \"\"\"Get the takes, compute the actual amounts, and return an OrderedDict.\n        \"\"\"\n        actual_takes = OrderedDict()\n        nominal_takes = self.get_takes(cursor=cursor)\n        nominal_takes.append(self.get_team_take(cursor=cursor))\n        budget = balance = self.receiving\n        for take in nominal_takes:\n            nominal_amount = take['nominal_amount'] = take.pop('amount')\n            actual_amount = take['actual_amount'] = min(nominal_amount, balance)\n            balance -= actual_amount\n            take['balance'] = balance\n            take['percentage'] = (actual_amount / budget) if budget > 0 else 0\n            actual_takes[take['member']] = take\n        return actual_takes\n\n    def get_members(self, current_participant):\n        \"\"\"Return a list of member dicts.\n        \"\"\"\n        assert self.IS_PLURAL\n        takes = self.compute_actual_takes()\n        members = []\n        for take in takes.values():\n            member = {}\n            member['username'] = take['member']\n            member['take'] = take['nominal_amount']\n            member['balance'] = take['balance']\n            member['percentage'] = take['percentage']\n\n            member['removal_allowed'] = current_participant == self\n            member['editing_allowed'] = False\n            member['is_current_user'] = False\n            if current_participant is not None:\n                if member['username'] == current_participant.username:\n                    member['is_current_user'] = True\n                    if take['ctime'] is not None:\n                        # current user, but not the team itself\n                        member['editing_allowed']= True\n\n            member['last_week'] = last_week = self.get_take_last_week_for(member)\n            member['max_this_week'] = self.compute_max_this_week(last_week)\n            members.append(member)\n        return members\n", "path": "gittip/models/_mixin_team.py"}], "after_files": [{"content": "\"\"\"Teams on Gittip are plural participants with members.\n\"\"\"\nfrom collections import OrderedDict\nfrom decimal import Decimal\n\nfrom aspen.utils import typecheck\n\n\nclass MemberLimitReached(Exception): pass\n\nclass StubParticipantAdded(Exception): pass\n\nclass MixinTeam(object):\n    \"\"\"This class provides methods for working with a Participant as a Team.\n\n    :param Participant participant: the underlying :py:class:`~gittip.participant.Participant` object for this team\n\n    \"\"\"\n\n    # XXX These were all written with the ORM and need to be converted.\n\n    def __init__(self, participant):\n        self.participant = participant\n\n    def show_as_team(self, user):\n        \"\"\"Return a boolean, whether to show this participant as a team.\n        \"\"\"\n        if not self.IS_PLURAL:\n            return False\n        if user.ADMIN:\n            return True\n        if not self.get_takes():\n            if self == user.participant:\n                return True\n            return False\n        return True\n\n    def add_member(self, member):\n        \"\"\"Add a member to this team.\n        \"\"\"\n        assert self.IS_PLURAL\n        if len(self.get_takes()) == 149:\n            raise MemberLimitReached\n        if not member.is_claimed:\n            raise StubParticipantAdded\n        self.__set_take_for(member, Decimal('0.01'), self)\n\n    def remove_member(self, member):\n        \"\"\"Remove a member from this team.\n        \"\"\"\n        assert self.IS_PLURAL\n        self.__set_take_for(member, Decimal('0.00'), self)\n\n    def remove_all_members(self, cursor=None):\n        (cursor or self.db).run(\"\"\"\n            INSERT INTO takes (ctime, member, team, amount, recorder) (\n                SELECT ctime, member, %(username)s, 0.00, %(username)s\n                  FROM current_takes\n                 WHERE team=%(username)s\n                   AND amount > 0\n            );\n        \"\"\", dict(username=self.username))\n\n    def member_of(self, team):\n        \"\"\"Given a Participant object, return a boolean.\n        \"\"\"\n        assert team.IS_PLURAL\n        for take in team.get_takes():\n            if take['member'] == self.username:\n                return True\n        return False\n\n    def get_take_last_week_for(self, member):\n        \"\"\"What did the user actually take most recently? Used in throttling.\n        \"\"\"\n        assert self.IS_PLURAL\n        membername = member.username if hasattr(member, 'username') \\\n                                                        else member['username']\n        return self.db.one(\"\"\"\n\n            SELECT amount\n              FROM transfers\n             WHERE tipper=%s AND tippee=%s AND context='take'\n               AND timestamp >\n                (SELECT ts_start FROM paydays ORDER BY ts_start DESC LIMIT 1)\n          ORDER BY timestamp DESC LIMIT 1\n\n        \"\"\", (self.username, membername), default=Decimal('0.00'))\n\n    def get_take_for(self, member):\n        \"\"\"Return a Decimal representation of the take for this member, or 0.\n        \"\"\"\n        assert self.IS_PLURAL\n        return self.db.one( \"SELECT amount FROM current_takes \"\n                            \"WHERE member=%s AND team=%s\"\n                          , (member.username, self.username)\n                          , default=Decimal('0.00')\n                           )\n\n    def compute_max_this_week(self, last_week):\n        \"\"\"2x last week's take, but at least a dollar.\n        \"\"\"\n        return max(last_week * Decimal('2'), Decimal('1.00'))\n\n    def set_take_for(self, member, take, recorder):\n        \"\"\"Sets member's take from the team pool.\n        \"\"\"\n        assert self.IS_PLURAL\n\n        # lazy import to avoid circular import\n        from gittip.security.user import User\n        from gittip.models.participant import Participant\n\n        typecheck( member, Participant\n                 , take, Decimal\n                 , recorder, (Participant, User)\n                  )\n\n        last_week = self.get_take_last_week_for(member)\n        max_this_week = self.compute_max_this_week(last_week)\n        if take > max_this_week:\n            take = max_this_week\n\n        self.__set_take_for(member, take, recorder)\n        return take\n\n    def __set_take_for(self, member, amount, recorder):\n        assert self.IS_PLURAL\n        # XXX Factored out for testing purposes only! :O Use .set_take_for.\n        with self.db.get_cursor() as cursor:\n            # Lock to avoid race conditions\n            cursor.run(\"LOCK TABLE takes IN EXCLUSIVE MODE\")\n            # Compute the current takes\n            old_takes = self.compute_actual_takes(cursor)\n            # Insert the new take\n            cursor.run(\"\"\"\n\n                INSERT INTO takes (ctime, member, team, amount, recorder)\n                 VALUES ( COALESCE (( SELECT ctime\n                                        FROM takes\n                                       WHERE member=%(member)s\n                                         AND team=%(team)s\n                                       LIMIT 1\n                                     ), CURRENT_TIMESTAMP)\n                        , %(member)s\n                        , %(team)s\n                        , %(amount)s\n                        , %(recorder)s\n                         )\n\n            \"\"\", dict(member=member.username, team=self.username, amount=amount,\n                      recorder=recorder.username))\n            # Compute the new takes\n            new_takes = self.compute_actual_takes(cursor)\n            # Update receiving amounts in the participants table\n            self.update_taking(old_takes, new_takes, cursor, member)\n\n    def update_taking(self, old_takes, new_takes, cursor=None, member=None):\n        \"\"\"Update `taking` amounts based on the difference between `old_takes`\n        and `new_takes`.\n        \"\"\"\n        for username in set(old_takes.keys()).union(new_takes.keys()):\n            if username == self.username:\n                continue\n            old = old_takes.get(username, {}).get('actual_amount', Decimal(0))\n            new = new_takes.get(username, {}).get('actual_amount', Decimal(0))\n            diff = new - old\n            if diff != 0:\n                r = (self.db or cursor).one(\"\"\"\n                    UPDATE participants\n                       SET taking = (taking + %(diff)s)\n                         , receiving = (receiving + %(diff)s)\n                     WHERE username=%(username)s\n                 RETURNING taking, receiving\n                \"\"\", dict(username=username, diff=diff))\n                if member and username == member.username:\n                    member.set_attributes(**r._asdict())\n\n    def get_takes(self, for_payday=False, cursor=None):\n        \"\"\"Return a list of member takes for a team.\n\n        This is implemented parallel to Participant.get_tips_and_total. See\n        over there for an explanation of for_payday.\n\n        \"\"\"\n        assert self.IS_PLURAL\n\n        args = dict(team=self.username)\n\n        if for_payday:\n            args['ts_start'] = for_payday\n\n            # Get the takes for this team, as they were before ts_start,\n            # filtering out the ones we've already transferred (in case payday\n            # is interrupted and restarted).\n\n            TAKES = \"\"\"\\\n\n                SELECT * FROM (\n                     SELECT DISTINCT ON (member) t.*\n                       FROM takes t\n                       JOIN participants p ON p.username = member\n                      WHERE team=%(team)s\n                        AND mtime < %(ts_start)s\n                        AND p.is_suspicious IS NOT true\n                        AND ( SELECT id\n                                FROM transfers\n                               WHERE tipper=t.team\n                                 AND tippee=t.member\n                                 AND context='take'\n                                 AND timestamp >= %(ts_start)s\n                             ) IS NULL\n                   ORDER BY member, mtime DESC\n                ) AS foo\n                ORDER BY ctime DESC\n\n            \"\"\"\n        else:\n            TAKES = \"\"\"\\\n\n                SELECT member, amount, ctime, mtime\n                  FROM current_takes\n                 WHERE team=%(team)s\n              ORDER BY ctime DESC\n\n            \"\"\"\n\n        records = (cursor or self.db).all(TAKES, args)\n        return [r._asdict() for r in records]\n\n    def get_team_take(self, cursor=None):\n        \"\"\"Return a single take for a team, the team itself's take.\n        \"\"\"\n        assert self.IS_PLURAL\n        TAKE = \"SELECT sum(amount) FROM current_takes WHERE team=%s\"\n        total_take = (cursor or self.db).one(TAKE, (self.username,), default=0)\n        team_take = max(self.receiving - total_take, 0)\n        membership = { \"ctime\": None\n                     , \"mtime\": None\n                     , \"member\": self.username\n                     , \"amount\": team_take\n                      }\n        return membership\n\n    def compute_actual_takes(self, cursor=None):\n        \"\"\"Get the takes, compute the actual amounts, and return an OrderedDict.\n        \"\"\"\n        actual_takes = OrderedDict()\n        nominal_takes = self.get_takes(cursor=cursor)\n        nominal_takes.append(self.get_team_take(cursor=cursor))\n        budget = balance = self.balance + self.receiving\n        for take in nominal_takes:\n            nominal_amount = take['nominal_amount'] = take.pop('amount')\n            actual_amount = take['actual_amount'] = min(nominal_amount, balance)\n            if take['member'] != self.username:\n                balance -= actual_amount\n            take['balance'] = balance\n            take['percentage'] = (actual_amount / budget) if budget > 0 else 0\n            actual_takes[take['member']] = take\n        return actual_takes\n\n    def get_members(self, current_participant):\n        \"\"\"Return a list of member dicts.\n        \"\"\"\n        assert self.IS_PLURAL\n        takes = self.compute_actual_takes()\n        members = []\n        for take in takes.values():\n            member = {}\n            member['username'] = take['member']\n            member['take'] = take['nominal_amount']\n            member['balance'] = take['balance']\n            member['percentage'] = take['percentage']\n\n            member['removal_allowed'] = current_participant == self\n            member['editing_allowed'] = False\n            member['is_current_user'] = False\n            if current_participant is not None:\n                if member['username'] == current_participant.username:\n                    member['is_current_user'] = True\n                    if take['ctime'] is not None:\n                        # current user, but not the team itself\n                        member['editing_allowed']= True\n\n            member['last_week'] = last_week = self.get_take_last_week_for(member)\n            member['max_this_week'] = self.compute_max_this_week(last_week)\n            members.append(member)\n        return members\n", "path": "gittip/models/_mixin_team.py"}]}