Coverage for app / services / statements / store.py: 96%

90 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""Closing a month: writing each workspace's statement once, and keeping it. 

2 

3A month is closed an hour after it ends (``SETTLE``), as the economics export 

4waits for a day: work that began before midnight and was recorded just after 

5belongs to the month it began. Every workspace with a ledger row in the month 

6gets a statement — a project, its organisation or its owner's Personal 

7workspace through the row's stamps — and a parent counts its projects. Runs 

8catch up on any month within ``LOOKBACK_MONTHS`` that has none yet, at most 

9``MAX_PER_RUN`` statements a run, so a first run or one after a long gap 

10does not hold the scheduler's tick. A statement already written is never 

11written again (``uq_spend_statement_month``). 

12""" 

13 

14from __future__ import annotations 

15 

16import logging 

17from dataclasses import dataclass, field 

18from datetime import datetime, timedelta 

19from decimal import Decimal 

20 

21from sqlalchemy.exc import IntegrityError 

22from sqlalchemy.orm import Session 

23 

24from app.db.postgres.models import GovernanceUsage, SpendStatement 

25from app.services import workspace as workspace_service 

26from app.services.workspace import Workspace, WorkspaceKind 

27from app.util.time import aware_utcnow 

28 

29from .build import SCHEMA_VERSION, Month, build, digest 

30 

31logger = logging.getLogger(__name__) 

32 

33#: How long after a month ends its statements are written. 

34SETTLE = timedelta(hours=1) 

35#: How far back a missing statement is still written. 

36LOOKBACK_MONTHS = 12 

37#: Statements written per run. 

38MAX_PER_RUN = 25 

39 

40 

41@dataclass 

42class RunResult: 

43 written: list[str] = field(default_factory=list) 

44 pending: int = 0 

45 

46 

47def due_months(now: datetime, lookback: int = LOOKBACK_MONTHS) -> list[Month]: 

48 """The finished months, settled, within ``lookback``, oldest first.""" 

49 naive = now.replace(tzinfo=None) 

50 month = Month.of(naive).previous() 

51 out: list[Month] = [] 

52 for _ in range(lookback): 

53 if month.end + SETTLE <= naive: 

54 out.append(month) 

55 month = month.previous() 

56 return list(reversed(out)) 

57 

58 

59def workspaces_with_spend(db: Session, month: Month) -> list[str]: 

60 """Every workspace a ledger row of ``month`` belongs to, by key: its 

61 project, its organisation, its owner's Personal workspace.""" 

62 rows = ( 

63 db.query( 

64 GovernanceUsage.owner_project_id, 

65 GovernanceUsage.owner_organisation_id, 

66 GovernanceUsage.workspace_user_id, 

67 ) 

68 .filter( 

69 GovernanceUsage.occurred_at >= month.begin, 

70 GovernanceUsage.occurred_at < month.end, 

71 ) 

72 .distinct() 

73 .all() 

74 ) 

75 keys: set[str] = set() 

76 for project_id, organisation_id, user_id in rows: 

77 if project_id is not None: 

78 keys.add(Workspace(WorkspaceKind.project, project_id).key) 

79 if organisation_id is not None: 

80 keys.add(Workspace(WorkspaceKind.organisation, organisation_id).key) 

81 if user_id is not None: 

82 keys.add(Workspace(WorkspaceKind.personal, user_id).key) 

83 return sorted(keys) 

84 

85 

86def stored(db: Session, ws_key: str, month: Month) -> SpendStatement | None: 

87 return ( 

88 db.query(SpendStatement) 

89 .filter( 

90 SpendStatement.workspace_key == ws_key, 

91 SpendStatement.period_start == month.first_day, 

92 ) 

93 .one_or_none() 

94 ) 

95 

96 

97def _owner_columns(ws: Workspace) -> dict: 

98 """Whose data export holds it: a person's Personal workspace only.""" 

99 return { 

100 "owner_user_id": ws.id if ws.kind is WorkspaceKind.personal else None, 

101 "owner_organisation_id": ws.id 

102 if ws.kind is WorkspaceKind.organisation 

103 else None, 

104 "owner_project_id": ws.id if ws.kind is WorkspaceKind.project else None, 

105 } 

106 

107 

108def close( 

109 db: Session, ws: Workspace, month: Month, *, now: datetime | None = None 

110) -> SpendStatement: 

111 """``ws``'s statement for the finished ``month``: the one already kept, 

112 or computed now and kept. Commits.""" 

113 existing = stored(db, ws.key, month) 

114 if existing is not None: 

115 return existing 

116 now = now or aware_utcnow() 

117 content = build(db, ws, month, now=now, closed=True) 

118 row = SpendStatement( 

119 workspace_key=ws.key, 

120 period_start=month.first_day, 

121 closed_at=now.replace(tzinfo=None), 

122 schema_version=SCHEMA_VERSION, 

123 content=content, 

124 content_sha256=digest(content), 

125 **_owner_columns(ws), 

126 ) 

127 db.add(row) 

128 try: 

129 db.commit() 

130 except IntegrityError: 

131 # Another process closed it first: theirs is the statement. 

132 db.rollback() 

133 existing = stored(db, ws.key, month) 

134 if existing is None: 

135 raise 

136 return existing 

137 return row 

138 

139 

140def run(db: Session, *, now: datetime | None = None) -> RunResult: 

141 """Write every statement that is due and missing, oldest month first, 

142 at most ``MAX_PER_RUN``.""" 

143 now = now or aware_utcnow() 

144 result = RunResult() 

145 for month in due_months(now): 

146 done = { 

147 key 

148 for (key,) in db.query(SpendStatement.workspace_key) 

149 .filter(SpendStatement.period_start == month.first_day) 

150 .all() 

151 } 

152 for key in workspaces_with_spend(db, month): 

153 if key in done: 

154 continue 

155 if len(result.written) >= MAX_PER_RUN: 

156 result.pending += 1 

157 continue 

158 try: 

159 ws = workspace_service.from_key(db, key) 

160 except Exception: 

161 # A project since deleted: nothing left to name it by. 

162 logger.warning( 

163 "Statement for %s %s skipped: no workspace", key, month.key 

164 ) 

165 continue 

166 row = close(db, ws, month, now=now) 

167 result.written.append(f"{key} {month.key}") 

168 _tell(db, ws, month, row) 

169 return result 

170 

171 

172def _tell(db: Session, ws: Workspace, month: Month, row: SpendStatement) -> None: 

173 """Tell those who govern ``ws`` its month's statement is ready.""" 

174 from app.services import notifications 

175 from app.services.budgets.alerts import where 

176 from app.services.rules.actions import usd_text 

177 

178 place = where(db, ws) 

179 spend = (row.content or {}).get("spend") or {} 

180 spent = spend.get("spend_usd") 

181 figure = ( 

182 f"{usd_text(Decimal(str(spent)))} spent" 

183 if spent is not None 

184 else "Spend that could not all be priced" 

185 ) 

186 notifications.notify( 

187 db, 

188 notifications.governors(db, ws), 

189 notifications.Message( 

190 kind=notifications.StatementReady.key, 

191 title=f"{month.label}'s statement is ready", 

192 body=f"{figure} in {place}. Open it to download it as CSV or print it.", 

193 link=f"/user/governance/spend/statements/{month.key}", 

194 workspace=ws, 

195 workspace_name=place, 

196 dedupe_key=f"statement:{ws.key}:{month.key}", 

197 data={"month": month.key, "spend_usd": spent}, 

198 ), 

199 )