Coverage for app/backend/src/couchers/email/emails.py: 98%

1083 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-10 09:48 +0000

1""" 

2Defines data models for each email we sent out to users. 

3 

4Email writing style guidelines 

5 

6Subject line: 

7 Single sentence of the form "who did what" (avoid passive voice when possible) 

8 No punctuation*. 

9 Do not quote people, community, group or event names. 

10 No need to refer to "Couchers.org", the sender name already does. 

11 

12Preview line: 

13 Quoted user content (e.g. comment/reference text), otherwise none. 

14 Don't repeat or paraphrase the subject. 

15 

16Purpose line of the body (first paragraph after the greeting): 

17 Usually a single sentence stating the purpose of the email. 

18 Similar or identical to the subject but may include additional info (e.g. dates). 

19 Should be punctuated with a period*, or end with a colon (':') if we then quote user content. 

20 

21Other instructions for body text: 

22 A single purpose line is enough for day-to-day notifications, no need for further prose. 

23 Highlight key pieces of info (names, locations, dates) using <b> tags. 

24 Highlight important passages using <strong> tags. 

25 Provide a link or instructions if the user has follow-up actions. 

26 

27* Some key emails like new accounts might use an exclamation mark (limit to 1) and more personal prose. 

28""" 

29 

30import re 

31from dataclasses import dataclass, replace 

32from datetime import UTC, date, datetime, tzinfo 

33from enum import Enum 

34from typing import Self, assert_never 

35from zoneinfo import ZoneInfo 

36 

37from markupsafe import Markup, escape 

38 

39from couchers import urls 

40from couchers.config import config 

41from couchers.constants import LATEST_RELEASE_BLOG_URL 

42from couchers.email.blocks import ( 

43 ActionBlock, 

44 EmailBase, 

45 EmailBlock, 

46 EmailBlocksBuilder, 

47 ParaBlock, 

48 QuoteBlock, 

49 UserInfo, 

50) 

51from couchers.email.locales import get_emails_i18next 

52from couchers.i18n import LocalizationContext 

53from couchers.i18n.localize import format_phone_number 

54from couchers.markup import html_link, html_mailto_link, markdown_to_plaintext 

55from couchers.notifications.quick_links import generate_quick_decline_link 

56from couchers.proto import events_pb2, messages_pb2, notification_data_pb2, requests_pb2 

57from couchers.utils import now, to_aware_datetime 

58 

59# Common string keys 

60_do_not_reply_request_string_key = "generic.do_not_reply_request" 

61 

62# Specific email definitions 

63 

64 

65@dataclass(kw_only=True, slots=True) 

66class AccountDeletionStartedEmail(EmailBase): 

67 """Sent to a user to confirm their account deletion request.""" 

68 

69 deletion_link: str 

70 

71 @property 

72 def string_key_base(self) -> str: 

73 return "account_deletion.started" 

74 

75 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

76 builder = self._body_builder(loc_context, security_warning=True) 

77 builder.para(".purpose") 

78 builder.action(self.deletion_link, ".confirm_action") 

79 return builder.build() 

80 

81 @classmethod 

82 def from_notification(cls, data: notification_data_pb2.AccountDeletionStart, *, user_name: str) -> Self: 

83 return cls( 

84 user_name=user_name, 

85 deletion_link=urls.delete_account_link(account_deletion_token=data.deletion_token), 

86 ) 

87 

88 @classmethod 

89 def test_instances(cls) -> list[Self]: 

90 return [ 

91 cls( 

92 user_name="Alice", 

93 deletion_link="https://couchers.org/delete-account?token=xxx", 

94 ) 

95 ] 

96 

97 

98@dataclass(kw_only=True, slots=True) 

99class AccountDeletionCompletedEmail(EmailBase): 

100 """Sent to a user after their account has been deleted.""" 

101 

102 undelete_link: str 

103 days: int 

104 

105 @property 

106 def string_key_base(self) -> str: 

107 return "account_deletion.completed" 

108 

109 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

110 builder = self._body_builder(loc_context, security_warning=True) 

111 builder.para(".purpose") 

112 builder.para(".farewell") 

113 builder.para(".recovery_instructions_days", {"count": self.days}) 

114 builder.action(self.undelete_link, ".recover_action") 

115 return builder.build() 

116 

117 @classmethod 

118 def from_notification(cls, data: notification_data_pb2.AccountDeletionComplete, *, user_name: str) -> Self: 

119 return cls( 

120 user_name=user_name, 

121 undelete_link=urls.recover_account_link(account_undelete_token=data.undelete_token), 

122 days=data.undelete_days, 

123 ) 

124 

125 @classmethod 

126 def test_instances(cls) -> list[Self]: 

127 return [ 

128 cls( 

129 user_name="Alice", 

130 undelete_link="https://couchers.org/recover-account?token=xxx", 

131 days=30, 

132 ) 

133 ] 

134 

135 

136@dataclass(kw_only=True, slots=True) 

137class AccountDeletionRecoveredEmail(EmailBase): 

138 """Sent to a user after their account deletion has been cancelled.""" 

139 

140 @property 

141 def string_key_base(self) -> str: 

142 return "account_deletion.recovered" 

143 

144 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

145 builder = self._body_builder(loc_context, security_warning=True) 

146 builder.para(".confirmation") 

147 builder.para(".login_instructions") 

148 builder.action(urls.app_link(), ".login_action") 

149 builder.para(".redelete_instructions") 

150 return builder.build() 

151 

152 @classmethod 

153 def test_instances(cls) -> list[Self]: 

154 return [cls(user_name="Alice")] 

155 

156 

157@dataclass(kw_only=True, slots=True) 

158class ActivenessProbeEmail(EmailBase): 

159 """Sent to a host to check if they are still open to hosting.""" 

160 

161 days_left: int 

162 

163 @property 

164 def string_key_base(self) -> str: 

165 return "activeness_probe" 

166 

167 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

168 builder = self._body_builder(loc_context) 

169 builder.para(".purpose") 

170 builder.para(".instructions_days", {"count": self.days_left}) 

171 builder.action(urls.app_link(), ".login_action") 

172 builder.para(".encouragement") 

173 

174 # Extract major.minor from the version string. "v1.3.18927" -> "1.3" 

175 version = config.VERSION 

176 if version_match := re.search(r"^v?(\d+\.\d+)\b", version): 176 ↛ 177line 176 didn't jump to line 177 because the condition on line 176 was never true

177 version = version_match[1] 

178 

179 builder.para(".latest_release", {"version": version, "blog_url": LATEST_RELEASE_BLOG_URL}) 

180 return builder.build() 

181 

182 @classmethod 

183 def from_notification(cls, data: notification_data_pb2.ActivenessProbe, *, user_name: str) -> Self: 

184 days_left = (to_aware_datetime(data.deadline) - now()).days 

185 return cls(user_name=user_name, days_left=days_left) 

186 

187 @classmethod 

188 def test_instances(cls) -> list[Self]: 

189 return [cls(user_name="Alice", days_left=7)] 

190 

191 

192@dataclass(kw_only=True, slots=True) 

193class APIKeyIssuedEmail(EmailBase): 

194 """Sent to a user to notify them that their API key was issued.""" 

195 

196 api_key: str 

197 expiry: datetime 

198 

199 @property 

200 def string_key_base(self) -> str: 

201 return "api_key_issued" 

202 

203 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

204 builder = self._body_builder(loc_context, security_warning=True) 

205 builder.para(".header") 

206 builder.quote(self.api_key, markdown=False) 

207 # API keys are technical information so show in UTC (string emphasizes this). 

208 builder.para(".expiry2", {"datetime_utc": loc_context.localize_datetime(self.expiry, display_timezone=UTC)}) 

209 builder.para(".usage_warning") 

210 builder.para(".policy_warning", {"terms_url": urls.terms_of_service_url()}) 

211 return builder.build() 

212 

213 @classmethod 

214 def from_notification(cls, data: notification_data_pb2.ApiKeyCreate, *, user_name: str) -> Self: 

215 return cls(user_name=user_name, api_key=data.api_key, expiry=data.expiry.ToDatetime(tzinfo=UTC)) 

216 

217 @classmethod 

218 def test_instances(cls) -> list[Self]: 

219 return [cls(user_name="Alice", api_key="my_api_key_123", expiry=datetime(2099, 12, 31, 23, 59, 59, tzinfo=UTC))] 

220 

221 

222@dataclass(kw_only=True, slots=True) 

223class BadgeChangedEmail(EmailBase): 

224 """Sent to a user to notify them that a badge was added or removed from their profile.""" 

225 

226 badge_name: str 

227 added: bool 

228 

229 @property 

230 def string_key_base(self) -> str: 

231 return "badges.added" if self.added else "badges.removed" 

232 

233 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

234 return self._localize(loc_context, ".subject", {"name": self.badge_name}) 

235 

236 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

237 builder = self._body_builder(loc_context) 

238 builder.para(".purpose", {"name": self.badge_name}) 

239 return builder.build() 

240 

241 @classmethod 

242 def from_notification( 

243 cls, data: notification_data_pb2.BadgeAdd | notification_data_pb2.BadgeRemove, *, user_name: str 

244 ) -> Self: 

245 return cls( 

246 user_name=user_name, badge_name=data.badge_name, added=isinstance(data, notification_data_pb2.BadgeAdd) 

247 ) 

248 

249 @classmethod 

250 def test_instances(cls) -> list[Self]: 

251 prototype = cls(user_name="Alice", badge_name="Founder", added=True) 

252 return [replace(prototype, added=True), replace(prototype, added=False)] 

253 

254 

255@dataclass(kw_only=True, slots=True) 

256class BirthdateChangedEmail(EmailBase): 

257 """Sent to a user to notify them that their birthdate was changed.""" 

258 

259 new_birthdate: date 

260 

261 @property 

262 def string_key_base(self) -> str: 

263 return "birthdate_changed" 

264 

265 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

266 builder = self._body_builder(loc_context, security_warning=True) 

267 builder.para(".purpose", {"date": loc_context.localize_date(self.new_birthdate)}) 

268 return builder.build() 

269 

270 @classmethod 

271 def from_notification(cls, data: notification_data_pb2.BirthdateChange, *, user_name: str) -> Self: 

272 return cls(user_name=user_name, new_birthdate=date.fromisoformat(data.birthdate)) 

273 

274 @classmethod 

275 def test_instances(cls) -> list[Self]: 

276 return [ 

277 cls( 

278 user_name="Alice", 

279 new_birthdate=date(1990, 1, 1), 

280 ) 

281 ] 

282 

283 

284@dataclass(kw_only=True, slots=True) 

285class ChatMessageReceivedEmail(EmailBase): 

286 """Sent to a user when they receive a new chat message.""" 

287 

288 group_chat_title: str | None # None if direct message 

289 author: UserInfo 

290 text: str 

291 view_url: str 

292 

293 @property 

294 def string_key_base(self) -> str: 

295 return f"chat_messages.received.{'direct' if self.group_chat_title is None else 'group'}" 

296 

297 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

298 return self._localize( 

299 loc_context, ".subject", {"author": self.author.name, "group": self.group_chat_title or ""} 

300 ) 

301 

302 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

303 return self.text 

304 

305 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

306 builder = self._body_builder(loc_context) 

307 builder.para(".purpose", {"author": self.author.name, "group": self.group_chat_title or ""}) 

308 builder.user(self.author) 

309 builder.quote(self.text, markdown=False) 

310 builder.action(self.view_url, ".view_action") 

311 return builder.build() 

312 

313 @classmethod 

314 def from_notification(cls, data: notification_data_pb2.ChatMessage, *, user_name: str) -> Self: 

315 return cls( 

316 user_name, 

317 author=UserInfo.from_proto(data.author), 

318 text=data.text, 

319 group_chat_title=data.group_chat_title or None, 

320 view_url=urls.chat_link(chat_id=data.group_chat_id), 

321 ) 

322 

323 @classmethod 

324 def test_instances(cls) -> list[Self]: 

325 prototype = cls( 

326 user_name="Alice", 

327 group_chat_title=None, 

328 author=UserInfo.dummy_bob(), 

329 text="Hi Alice!", 

330 view_url="https://couchers.org/messages/chats/123", 

331 ) 

332 return [ 

333 replace(prototype, group_chat_title=None), 

334 replace(prototype, group_chat_title="Best friends"), 

335 ] 

336 

337 

338@dataclass(kw_only=True, slots=True) 

339class ChatMessagesMissedEmail(EmailBase): 

340 """Sent to a user after they've missed new chat messages.""" 

341 

342 @dataclass(kw_only=True, slots=True) 

343 class Entry: 

344 """Entry for each chat with missed messages.""" 

345 

346 group_chat_title: str | None # None if direct message 

347 missed_count: int 

348 latest_message_author: UserInfo 

349 latest_message_text: str 

350 view_url: str 

351 

352 entries: list[Entry] 

353 

354 @property 

355 def string_key_base(self) -> str: 

356 return "chat_messages.missed" 

357 

358 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

359 return self._localize(loc_context, ".subject") 

360 

361 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

362 if len(self.entries) != 1: 

363 return None 

364 return self.entries[0].latest_message_text 

365 

366 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

367 builder = self._body_builder(loc_context) 

368 builder.para(".purpose") 

369 for entry in self.entries: 

370 if entry.group_chat_title is None: 

371 builder.para(".count_in_dm", {"count": entry.missed_count, "author": entry.latest_message_author.name}) 

372 else: 

373 builder.para(".count_in_group", {"count": entry.missed_count, "group": entry.group_chat_title}) 

374 builder.user(entry.latest_message_author) 

375 builder.quote(entry.latest_message_text, markdown=False) 

376 builder.action(entry.view_url, ".view_action") 

377 return builder.build() 

378 

379 @classmethod 

380 def from_notification(cls, data: notification_data_pb2.ChatMissedMessages, *, user_name: str) -> Self: 

381 missed_entries = [ 

382 cls.Entry( 

383 group_chat_title=message.group_chat_title or None, 

384 missed_count=message.unseen_count, 

385 latest_message_author=UserInfo.from_proto(message.author), 

386 latest_message_text=message.text, 

387 view_url=urls.chat_link(chat_id=message.group_chat_id), 

388 ) 

389 for message in data.messages 

390 ] 

391 

392 return cls(user_name, entries=missed_entries) 

393 

394 @classmethod 

395 def test_instances(cls) -> list[Self]: 

396 entry_prototype = ChatMessagesMissedEmail.Entry( 

397 group_chat_title=None, 

398 missed_count=1, 

399 latest_message_author=UserInfo.dummy_bob(), 

400 latest_message_text="Hello!", 

401 view_url="https://couchers.org/messages/chats/123", 

402 ) 

403 return [ 

404 cls( 

405 user_name="Alice", 

406 entries=[ 

407 replace(entry_prototype, group_chat_title=None), 

408 replace(entry_prototype, group_chat_title="Best friends"), 

409 ], 

410 ) 

411 ] 

412 

413 

414@dataclass(kw_only=True, slots=True) 

415class DiscussionCreatedEmail(EmailBase): 

416 """Sent to a user when a new discussion is created in a community they follow.""" 

417 

418 author: UserInfo 

419 title: str 

420 parent_context: str # Community or group name 

421 markdown_text: str 

422 view_link: str 

423 

424 @property 

425 def string_key_base(self) -> str: 

426 return "discussions.created" 

427 

428 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

429 return self._localize(loc_context, ".subject", {"author": self.author.name, "title": self.title}) 

430 

431 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

432 return markdown_to_plaintext(self.markdown_text) 

433 

434 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

435 builder = self._body_builder(loc_context) 

436 builder.para( 

437 ".purpose", 

438 { 

439 "author": self.author.name, 

440 "parent_context": self.parent_context, 

441 }, 

442 ) 

443 builder.user(self.author) 

444 builder.block(ParaBlock(text=Markup(f"<b>{escape(self.title)}</b>"))) 

445 builder.quote(self.markdown_text, markdown=True) 

446 builder.action(self.view_link, ".view_action") 

447 return builder.build() 

448 

449 @classmethod 

450 def from_notification(cls, data: notification_data_pb2.DiscussionCreate, *, user_name: str) -> Self: 

451 discussion = data.discussion 

452 return cls( 

453 user_name=user_name, 

454 author=UserInfo.from_proto(data.author), 

455 title=discussion.title, 

456 parent_context=discussion.owner_title, 

457 markdown_text=discussion.content, 

458 view_link=urls.discussion_link(discussion_id=discussion.discussion_id, slug=discussion.slug), 

459 ) 

460 

461 @classmethod 

462 def test_instances(cls) -> list[Self]: 

463 return [ 

464 cls( 

465 user_name="Alice", 

466 author=UserInfo.dummy_bob(), 

467 title="Best hiking trails near Berlin", 

468 parent_context="Berlin", 

469 markdown_text="I've been exploring the area and found some **great** spots...", 

470 view_link="https://couchers.org/discussions/123", 

471 ) 

472 ] 

473 

474 

475@dataclass(kw_only=True, slots=True) 

476class DiscussionCommentEmail(EmailBase): 

477 """Sent to a user when someone comments on a discussion they follow.""" 

478 

479 author: UserInfo 

480 discussion_title: str 

481 discussion_parent_context: str # Community or group name 

482 markdown_text: str 

483 view_link: str 

484 

485 @property 

486 def string_key_base(self) -> str: 

487 return "discussions.comment" 

488 

489 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

490 return self._localize( 

491 loc_context, ".subject", {"author": self.author.name, "discussion_title": self.discussion_title} 

492 ) 

493 

494 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

495 return markdown_to_plaintext(self.markdown_text) 

496 

497 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

498 builder = self._body_builder(loc_context) 

499 builder.para( 

500 ".purpose", 

501 { 

502 "author": self.author.name, 

503 "discussion_title": self.discussion_title, 

504 "parent_context": self.discussion_parent_context, 

505 }, 

506 ) 

507 builder.user(self.author) 

508 builder.quote(self.markdown_text, markdown=True) 

509 builder.action(self.view_link, ".view_action") 

510 return builder.build() 

511 

512 @classmethod 

513 def from_notification(cls, data: notification_data_pb2.DiscussionComment, *, user_name: str) -> Self: 

514 discussion = data.discussion 

515 return cls( 

516 user_name=user_name, 

517 author=UserInfo.from_proto(data.author), 

518 discussion_title=discussion.title, 

519 discussion_parent_context=discussion.owner_title, 

520 markdown_text=data.reply.content, 

521 view_link=urls.discussion_link(discussion_id=discussion.discussion_id, slug=discussion.slug), 

522 ) 

523 

524 @classmethod 

525 def test_instances(cls) -> list[Self]: 

526 return [ 

527 cls( 

528 user_name="Alice", 

529 author=UserInfo.dummy_bob(), 

530 discussion_title="Best hiking trails near Berlin", 

531 discussion_parent_context="Berlin", 

532 markdown_text="Great recommendations, I also **love** the Grünewald forest!", 

533 view_link="https://couchers.org/discussions/123", 

534 ) 

535 ] 

536 

537 

538@dataclass(kw_only=True, slots=True) 

539class DonationReceivedEmail(EmailBase): 

540 """Sent to a user to thank them for a donation.""" 

541 

542 amount: int 

543 receipt_url: str 

544 

545 @property 

546 def string_key_base(self) -> str: 

547 return "donation_received" 

548 

549 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

550 builder = self._body_builder(loc_context, default_closing=False) 

551 builder.para(".purpose", {"amount_with_currency": f"${self.amount}"}) 

552 builder.para(".contribution_impact") 

553 builder.para(".invoice_receipt_info") 

554 builder.action(self.receipt_url, ".download_invoice") 

555 builder.para(".tax_acknowledgment") 

556 builder.para(".questions_contact", {"email_link": html_mailto_link("donations@couchers.org")}) 

557 builder.para("generic.thanks") 

558 builder.para("generic.closing_lines.founders") 

559 return builder.build() 

560 

561 @classmethod 

562 def from_notification(cls, data: notification_data_pb2.DonationReceived, *, user_name: str) -> Self: 

563 return cls(user_name=user_name, amount=data.amount, receipt_url=data.receipt_url) 

564 

565 @classmethod 

566 def test_instances(cls) -> list[Self]: 

567 return [cls(user_name="Alice", amount=25, receipt_url="https://couchers.org/receipts/123")] 

568 

569 

570@dataclass(kw_only=True, slots=True) 

571class EmailChangedEmail(EmailBase): 

572 """Sent to a user to notify them that their email address was changed.""" 

573 

574 new_email: str 

575 

576 @property 

577 def string_key_base(self) -> str: 

578 return "email_change.initiated" 

579 

580 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

581 builder = self._body_builder(loc_context, security_warning=True) 

582 builder.para(".purpose", {"email_address": self.new_email}) 

583 return builder.build() 

584 

585 @classmethod 

586 def from_notification(cls, data: notification_data_pb2.EmailAddressChange, *, user_name: str) -> Self: 

587 return cls(user_name=user_name, new_email=data.new_email) 

588 

589 @classmethod 

590 def test_instances(cls) -> list[Self]: 

591 return [cls(user_name="Alice", new_email="alice@example.com")] 

592 

593 

594@dataclass(kw_only=True, slots=True) 

595class EmailChangeConfirmationEmail(EmailBase): 

596 """Sent to a user to confirm their new email address.""" 

597 

598 old_email: str 

599 confirm_url: str 

600 

601 @property 

602 def string_key_base(self) -> str: 

603 return "email_change.confirmation" 

604 

605 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

606 builder = self._body_builder(loc_context, security_warning=True) 

607 builder.para(".purpose", {"old_email": self.old_email}) 

608 builder.action(self.confirm_url, ".confirm_action") 

609 return builder.build() 

610 

611 @classmethod 

612 def test_instances(cls) -> list[Self]: 

613 return [cls(user_name="Alice", old_email="alice@example.com", confirm_url="https://example.com")] 

614 

615 

616@dataclass(kw_only=True, slots=True) 

617class EmailVerifiedEmail(EmailBase): 

618 """Sent to a user to notify them that their new email address has been verified.""" 

619 

620 @property 

621 def string_key_base(self) -> str: 

622 return "email_change.verified" 

623 

624 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

625 builder = self._body_builder(loc_context, security_warning=True) 

626 builder.para(".purpose") 

627 return builder.build() 

628 

629 @classmethod 

630 def test_instances(cls) -> list[Self]: 

631 return [cls(user_name="Alice")] 

632 

633 

634@dataclass(kw_only=True, slots=True) 

635class EventInfo: 

636 """Common display fields for an event, extracted from its proto representation.""" 

637 

638 title: str 

639 start_time: datetime 

640 end_time: datetime 

641 timezone: tzinfo 

642 address: str | None # The None case handles legacy online events 

643 view_url: str 

644 description_markdown: str 

645 

646 def get_details_block(self, loc_context: LocalizationContext) -> EmailBlock: 

647 # TODO(#8695): Support localized time ranges 

648 # Event start/end date-times are always shown in the timezone at its location, not the user's. 

649 start_time_display = loc_context.localize_datetime( 

650 self.start_time, display_timezone=self.timezone, with_year=False, with_day_of_week=True 

651 ) 

652 end_time_display = loc_context.localize_datetime( 

653 self.end_time, display_timezone=self.timezone, with_year=False, with_day_of_week=True 

654 ) 

655 time_range_display = f"{start_time_display} - {end_time_display}" 

656 

657 html = f"<b>{escape(self.title)}</b>" 

658 html += "<br>" 

659 html += time_range_display 

660 if self.address: 

661 html += "<br>" 

662 html += f"<i>{escape(self.address)}</i>" 

663 

664 return ParaBlock(text=Markup(html)) 

665 

666 def get_description_block(self) -> EmailBlock: 

667 return QuoteBlock(text=Markup(self.description_markdown), markdown=True) 

668 

669 def get_view_action_block(self, loc_context: LocalizationContext) -> EmailBlock: 

670 view_action_text = loc_context.localize_string("events.generic.view_action", i18next=get_emails_i18next()) 

671 return ActionBlock(text=view_action_text, target_url=self.view_url) 

672 

673 @classmethod 

674 def from_proto(cls, event: events_pb2.Event) -> EventInfo: 

675 return cls( 

676 title=event.title, 

677 start_time=to_aware_datetime(event.start_time), 

678 end_time=to_aware_datetime(event.end_time), 

679 timezone=ZoneInfo(event.timezone), 

680 # Backcompat (2026-06): We might still have queued notifications referencing events with online_information. 

681 address=(event.location.address or None) if event.HasField("location") else None, 

682 view_url=urls.event_link(occurrence_id=event.event_id, slug=event.slug), 

683 description_markdown=event.content or "", 

684 ) 

685 

686 @staticmethod 

687 def dummy() -> EventInfo: 

688 return EventInfo( 

689 title="Berlin Meetup", 

690 start_time=datetime(2025, 7, 15, 18, 0, 0, tzinfo=UTC), 

691 end_time=datetime(2025, 7, 15, 21, 0, 0, tzinfo=UTC), 

692 timezone=UTC, 

693 address="Alexanderplatz, Berlin", 

694 view_url="https://couchers.org/events/123/berlin-community-meetup", 

695 description_markdown="Come join us for our monthly meetup!", 

696 ) 

697 

698 

699@dataclass(kw_only=True, slots=True) 

700class EventCreatedEmail(EmailBase): 

701 """Sent when a user is invited to an event (create_approved) or a new event is created (create_any).""" 

702 

703 inviting_user: UserInfo 

704 event_info: EventInfo 

705 community_name: str | None 

706 community_url: str | None 

707 is_invite: bool # True = create_approved (invitation), False = create_any 

708 

709 @property 

710 def string_key_base(self) -> str: 

711 return f"events.created.{'invitation' if self.is_invite else 'notification'}" 

712 

713 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

714 return self._localize( 

715 loc_context, ".subject", {"user": self.inviting_user.name, "title": self.event_info.title} 

716 ) 

717 

718 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

719 return markdown_to_plaintext(self.event_info.description_markdown) 

720 

721 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

722 builder = self._body_builder(loc_context) 

723 if self.community_name: 

724 builder.para(".purpose_with_community", {"user": self.inviting_user.name, "community": self.community_name}) 

725 else: 

726 builder.para(".purpose_no_community", {"user": self.inviting_user.name}) 

727 builder.block(self.event_info.get_details_block(loc_context)) 

728 builder.user(self.inviting_user) 

729 builder.block(self.event_info.get_description_block()) 

730 builder.block(self.event_info.get_view_action_block(loc_context)) 

731 return builder.build() 

732 

733 @classmethod 

734 def from_notification(cls, data: notification_data_pb2.EventCreate, *, user_name: str, is_invite: bool) -> Self: 

735 has_community = bool(data.in_community.community_id) 

736 community_url = ( 

737 urls.community_link(node_id=data.in_community.community_id, slug=data.in_community.slug) 

738 if has_community 

739 else None 

740 ) 

741 return cls( 

742 user_name=user_name, 

743 inviting_user=UserInfo.from_proto(data.inviting_user), 

744 event_info=EventInfo.from_proto(data.event), 

745 community_name=data.in_community.name if has_community else None, 

746 community_url=community_url, 

747 is_invite=is_invite, 

748 ) 

749 

750 @classmethod 

751 def test_instances(cls) -> list[Self]: 

752 prototype = cls( 

753 user_name="Alice", 

754 inviting_user=UserInfo.dummy_bob(), 

755 event_info=EventInfo.dummy(), 

756 community_name="Berlin", 

757 community_url="https://couchers.org/community/1/berlin-community", 

758 is_invite=True, 

759 ) 

760 return [ 

761 replace(prototype, is_invite=True), 

762 replace(prototype, is_invite=True, community_name=None, community_url=None), 

763 replace(prototype, is_invite=False), 

764 replace(prototype, is_invite=False, community_name=None, community_url=None), 

765 ] 

766 

767 

768@dataclass(kw_only=True, slots=True) 

769class EventUpdatedEmail(EmailBase): 

770 """Sent to subscribers when an event is updated.""" 

771 

772 updating_user: UserInfo 

773 event_info: EventInfo 

774 updated_items: list[notification_data_pb2.EventUpdateItem.ValueType] 

775 

776 @property 

777 def string_key_base(self) -> str: 

778 return "events.updated" 

779 

780 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

781 return self._localize( 

782 loc_context, ".subject", {"user": self.updating_user.name, "title": self.event_info.title} 

783 ) 

784 

785 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

786 builder = self._body_builder(loc_context) 

787 

788 updated_items_string_keys = list( 

789 filter(None, (type(self)._updated_item_to_string_key(i) for i in self.updated_items)) 

790 ) 

791 if updated_items_string_keys: 

792 updated_items_text = loc_context.localize_list( 

793 [self._localize(loc_context, key) for key in updated_items_string_keys] 

794 ) 

795 builder.para(".purpose_with_items", {"user": self.updating_user.name, "items_list": updated_items_text}) 

796 else: 

797 builder.para(".purpose_generic", {"user": self.updating_user.name}) 

798 

799 builder.block(self.event_info.get_details_block(loc_context)) 

800 builder.user(self.updating_user) 

801 builder.block(self.event_info.get_description_block()) 

802 builder.block(self.event_info.get_view_action_block(loc_context)) 

803 return builder.build() 

804 

805 @classmethod 

806 def from_notification(cls, data: notification_data_pb2.EventUpdate, *, user_name: str) -> Self: 

807 updated_items: list[notification_data_pb2.EventUpdateItem.ValueType] = [] 

808 if data.updated_enum_items: 808 ↛ 811line 808 didn't jump to line 811 because the condition on line 808 was always true

809 updated_items.extend(data.updated_enum_items) 

810 

811 return cls( 

812 user_name=user_name, 

813 updating_user=UserInfo.from_proto(data.updating_user), 

814 event_info=EventInfo.from_proto(data.event), 

815 updated_items=updated_items, 

816 ) 

817 

818 @staticmethod 

819 def _updated_item_to_string_key(value: notification_data_pb2.EventUpdateItem.ValueType) -> str | None: 

820 match value: 

821 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_TITLE: 

822 return ".item_names.title" 

823 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_CONTENT: 

824 return ".item_names.content" 

825 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_LOCATION: 

826 return ".item_names.location" 

827 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_START_TIME: 

828 return ".item_names.start_time" 

829 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_END_TIME: 

830 return ".item_names.end_time" 

831 case _: 

832 return None 

833 

834 @classmethod 

835 def test_instances(cls) -> list[Self]: 

836 prototype = cls( 

837 user_name="Alice", 

838 updating_user=UserInfo.dummy_bob(), 

839 event_info=EventInfo.dummy(), 

840 updated_items=[], 

841 ) 

842 return [ 

843 replace(prototype, updated_items=[]), 

844 replace(prototype, updated_items=notification_data_pb2.EventUpdateItem.values()), 

845 ] 

846 

847 

848@dataclass(kw_only=True, slots=True) 

849class EventOrganizerInvitedEmail(EmailBase): 

850 """Sent when a user is invited to co-organize an event.""" 

851 

852 inviting_user: UserInfo 

853 event_info: EventInfo 

854 

855 @property 

856 def string_key_base(self) -> str: 

857 return "events.organizer_invited" 

858 

859 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

860 return self._localize( 

861 loc_context, 

862 ".subject", 

863 {"user": self.inviting_user.name, "title": self.event_info.title}, 

864 ) 

865 

866 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

867 builder = self._body_builder(loc_context) 

868 builder.para(".purpose", {"user": self.inviting_user.name, "title": self.event_info.title}) 

869 builder.block(self.event_info.get_details_block(loc_context)) 

870 builder.user(self.inviting_user) 

871 builder.block(self.event_info.get_description_block()) 

872 builder.block(self.event_info.get_view_action_block(loc_context)) 

873 builder.para(_do_not_reply_request_string_key, epilogue=True) 

874 return builder.build() 

875 

876 @classmethod 

877 def from_notification(cls, data: notification_data_pb2.EventInviteOrganizer, *, user_name: str) -> Self: 

878 return cls( 

879 user_name=user_name, 

880 inviting_user=UserInfo.from_proto(data.inviting_user), 

881 event_info=EventInfo.from_proto(data.event), 

882 ) 

883 

884 @classmethod 

885 def test_instances(cls) -> list[Self]: 

886 return [cls(user_name="Alice", inviting_user=UserInfo.dummy_bob(), event_info=EventInfo.dummy())] 

887 

888 

889@dataclass(kw_only=True, slots=True) 

890class EventCommentEmail(EmailBase): 

891 """Sent to subscribers when someone comments on an event.""" 

892 

893 author: UserInfo 

894 event_info: EventInfo 

895 comment_markdown: str 

896 

897 @property 

898 def string_key_base(self) -> str: 

899 return "events.comment" 

900 

901 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

902 return self._localize(loc_context, ".subject", {"author": self.author.name, "title": self.event_info.title}) 

903 

904 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

905 return markdown_to_plaintext(self.comment_markdown) 

906 

907 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

908 builder = self._body_builder(loc_context) 

909 builder.para(".purpose", {"author": self.author.name}) 

910 builder.block(self.event_info.get_details_block(loc_context)) 

911 builder.user(self.author) 

912 builder.quote(self.comment_markdown, markdown=True) 

913 builder.block(self.event_info.get_view_action_block(loc_context)) 

914 return builder.build() 

915 

916 @classmethod 

917 def from_notification(cls, data: notification_data_pb2.EventComment, *, user_name: str) -> Self: 

918 return cls( 

919 user_name=user_name, 

920 author=UserInfo.from_proto(data.author), 

921 event_info=EventInfo.from_proto(data.event), 

922 comment_markdown=data.reply.content, 

923 ) 

924 

925 @classmethod 

926 def test_instances(cls) -> list[Self]: 

927 return [ 

928 cls( 

929 user_name="Alice", 

930 author=UserInfo.dummy_bob(), 

931 event_info=EventInfo.dummy(), 

932 comment_markdown="Looking forward to it, see you all there!", 

933 ) 

934 ] 

935 

936 

937@dataclass(kw_only=True, slots=True) 

938class EventReminderEmail(EmailBase): 

939 """Sent to subscribers as a reminder that an event starts soon.""" 

940 

941 event_info: EventInfo 

942 

943 @property 

944 def string_key_base(self) -> str: 

945 return "events.reminder" 

946 

947 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

948 return self._localize(loc_context, ".subject", {"title": self.event_info.title}) 

949 

950 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

951 builder = self._body_builder(loc_context) 

952 builder.para(".purpose") 

953 builder.block(self.event_info.get_details_block(loc_context)) 

954 builder.block(self.event_info.get_description_block()) 

955 builder.block(self.event_info.get_view_action_block(loc_context)) 

956 return builder.build() 

957 

958 @classmethod 

959 def from_notification(cls, data: notification_data_pb2.EventReminder, *, user_name: str) -> Self: 

960 return cls( 

961 user_name=user_name, 

962 event_info=EventInfo.from_proto(data.event), 

963 ) 

964 

965 @classmethod 

966 def test_instances(cls) -> list[Self]: 

967 return [cls(user_name="Alice", event_info=EventInfo.dummy())] 

968 

969 

970@dataclass(kw_only=True, slots=True) 

971class EventCancelledEmail(EmailBase): 

972 """Sent to subscribers when an event is cancelled.""" 

973 

974 cancelling_user: UserInfo 

975 event_info: EventInfo 

976 

977 @property 

978 def string_key_base(self) -> str: 

979 return "events.cancel" 

980 

981 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

982 return self._localize( 

983 loc_context, 

984 ".subject", 

985 {"user": self.cancelling_user.name, "title": self.event_info.title}, 

986 ) 

987 

988 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

989 builder = self._body_builder(loc_context) 

990 builder.para(".purpose", {"user": self.cancelling_user.name}) 

991 builder.block(self.event_info.get_details_block(loc_context)) 

992 builder.user(self.cancelling_user) 

993 builder.quote(self.event_info.description_markdown, markdown=True) 

994 builder.block(self.event_info.get_view_action_block(loc_context)) 

995 return builder.build() 

996 

997 @classmethod 

998 def from_notification(cls, data: notification_data_pb2.EventCancel, *, user_name: str) -> Self: 

999 return cls( 

1000 user_name=user_name, 

1001 cancelling_user=UserInfo.from_proto(data.cancelling_user), 

1002 event_info=EventInfo.from_proto(data.event), 

1003 ) 

1004 

1005 @classmethod 

1006 def test_instances(cls) -> list[Self]: 

1007 return [cls(user_name="Alice", cancelling_user=UserInfo.dummy_bob(), event_info=EventInfo.dummy())] 

1008 

1009 

1010@dataclass(kw_only=True, slots=True) 

1011class EventDeletedEmail(EmailBase): 

1012 """Sent to subscribers when a moderator deletes an event.""" 

1013 

1014 event_info: EventInfo 

1015 

1016 @property 

1017 def string_key_base(self) -> str: 

1018 return "events.deleted" 

1019 

1020 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1021 return self._localize(loc_context, ".subject", {"title": self.event_info.title}) 

1022 

1023 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1024 builder = self._body_builder(loc_context) 

1025 builder.para(".purpose") 

1026 builder.block(self.event_info.get_details_block(loc_context)) 

1027 return builder.build() 

1028 

1029 @classmethod 

1030 def from_notification(cls, data: notification_data_pb2.EventDelete, *, user_name: str) -> Self: 

1031 return cls( 

1032 user_name=user_name, 

1033 event_info=EventInfo.from_proto(data.event), 

1034 ) 

1035 

1036 @classmethod 

1037 def test_instances(cls) -> list[Self]: 

1038 return [ 

1039 cls( 

1040 user_name="Alice", 

1041 event_info=EventInfo.dummy(), 

1042 ) 

1043 ] 

1044 

1045 

1046@dataclass(kw_only=True, slots=True) 

1047class FriendReferenceReceivedEmail(EmailBase): 

1048 """Sent to a user when they receive a friend reference.""" 

1049 

1050 from_user: UserInfo 

1051 text: str 

1052 

1053 @property 

1054 def string_key_base(self) -> str: 

1055 return "references.received.friend" 

1056 

1057 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1058 return self._localize(loc_context, ".subject", {"name": self.from_user.name}) 

1059 

1060 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

1061 return self.text 

1062 

1063 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1064 builder = self._body_builder(loc_context) 

1065 builder.para(".purpose", {"name": self.from_user.name}) 

1066 builder.user(self.from_user) 

1067 builder.quote(self.text, markdown=False) 

1068 builder.action(urls.profile_references_link(), "references.received.view_action") 

1069 return builder.build() 

1070 

1071 @classmethod 

1072 def from_notification(cls, data: notification_data_pb2.ReferenceReceiveFriend, *, user_name: str) -> Self: 

1073 return cls(user_name=user_name, from_user=UserInfo.from_proto(data.from_user), text=data.text) 

1074 

1075 @classmethod 

1076 def test_instances(cls) -> list[Self]: 

1077 return [ 

1078 cls( 

1079 user_name="Alice", 

1080 from_user=UserInfo.dummy_bob(), 

1081 text="Alice is a wonderful person and a great travel companion!", 

1082 ) 

1083 ] 

1084 

1085 

1086@dataclass(kw_only=True, slots=True) 

1087class FriendRequestReceivedEmail(EmailBase): 

1088 """Sent to a user when they receive a friend request.""" 

1089 

1090 befriender: UserInfo 

1091 

1092 @property 

1093 def string_key_base(self) -> str: 

1094 return "friend_requests.received" 

1095 

1096 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1097 return self._localize(loc_context, ".subject", {"name": self.befriender.name}) 

1098 

1099 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1100 builder = self._body_builder(loc_context) 

1101 builder.para(".purpose", {"name": self.befriender.name}) 

1102 builder.user(self.befriender) 

1103 builder.action(urls.friend_requests_link(), ".view_action") 

1104 builder.para(".closing") 

1105 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1106 return builder.build() 

1107 

1108 @classmethod 

1109 def from_notification(cls, data: notification_data_pb2.FriendRequestCreate, *, user_name: str) -> Self: 

1110 return cls(user_name=user_name, befriender=UserInfo.from_proto(data.other_user)) 

1111 

1112 @classmethod 

1113 def test_instances(cls) -> list[Self]: 

1114 return [ 

1115 cls( 

1116 user_name="Alice", 

1117 befriender=UserInfo.dummy_bob(), 

1118 ) 

1119 ] 

1120 

1121 

1122@dataclass(kw_only=True, slots=True) 

1123class FriendRequestAcceptedEmail(EmailBase): 

1124 """Sent to a user when their friend request is accepted.""" 

1125 

1126 new_friend: UserInfo 

1127 

1128 @property 

1129 def string_key_base(self) -> str: 

1130 return "friend_requests.accepted" 

1131 

1132 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1133 return self._localize(loc_context, ".subject", {"name": self.new_friend.name}) 

1134 

1135 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1136 builder = self._body_builder(loc_context) 

1137 builder.para(".purpose", {"name": self.new_friend.name}) 

1138 builder.user(self.new_friend) 

1139 builder.action(self.new_friend.profile_url, ".view_action") 

1140 builder.para(".closing") 

1141 return builder.build() 

1142 

1143 @classmethod 

1144 def from_notification(cls, data: notification_data_pb2.FriendRequestAccept, *, user_name: str) -> Self: 

1145 return cls(user_name=user_name, new_friend=UserInfo.from_proto(data.other_user)) 

1146 

1147 @classmethod 

1148 def test_instances(cls) -> list[Self]: 

1149 return [ 

1150 cls( 

1151 user_name="Alice", 

1152 new_friend=UserInfo.dummy_bob(), 

1153 ) 

1154 ] 

1155 

1156 

1157@dataclass(kw_only=True, slots=True) 

1158class GenderChangedEmail(EmailBase): 

1159 """Sent to a user to notify them that their gender was changed.""" 

1160 

1161 new_gender: str 

1162 

1163 @property 

1164 def string_key_base(self) -> str: 

1165 return "gender_changed" 

1166 

1167 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1168 builder = self._body_builder(loc_context, security_warning=True) 

1169 builder.para(".purpose", {"gender": self.new_gender}) 

1170 return builder.build() 

1171 

1172 @classmethod 

1173 def from_notification(cls, data: notification_data_pb2.GenderChange, *, user_name: str) -> Self: 

1174 return cls(user_name=user_name, new_gender=data.gender) 

1175 

1176 @classmethod 

1177 def test_instances(cls) -> list[Self]: 

1178 return [ 

1179 cls( 

1180 user_name="Alice", 

1181 new_gender="Male", 

1182 ) 

1183 ] 

1184 

1185 

1186class StayProposalType(Enum): 

1187 request = "request" 

1188 invitation = "invitation" 

1189 

1190 def __str__(self) -> str: 

1191 return self.value 

1192 

1193 @staticmethod 

1194 def from_proto(data: requests_pb2.HostRequest) -> StayProposalType: 

1195 return StayProposalType.invitation if data.public_trip_id else StayProposalType.request 

1196 

1197 

1198@dataclass(kw_only=True, slots=True) 

1199class StayProposalReceivedEmail(EmailBase): 

1200 """Sent to the recipient of a stay proposal.""" 

1201 

1202 proposal_type: StayProposalType 

1203 initiator: UserInfo 

1204 from_date: date 

1205 to_date: date 

1206 text: str 

1207 view_link: str 

1208 quick_decline_link: str 

1209 

1210 @property 

1211 def string_key_base(self) -> str: 

1212 return f"stays.created.{self.proposal_type}" 

1213 

1214 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1215 return self._localize(loc_context, ".subject", {"initiator": self.initiator.name}) 

1216 

1217 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

1218 return self.text 

1219 

1220 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1221 builder = self._body_builder(loc_context) 

1222 builder.para(".purpose", {"initiator": self.initiator.name}) 

1223 builder.user( 

1224 self.initiator, 

1225 "stays.generic.date_range", 

1226 { 

1227 "from_date": _localize_stay_date(self.from_date, loc_context), 

1228 "to_date": _localize_stay_date(self.to_date, loc_context), 

1229 }, 

1230 ) 

1231 builder.quote(self.text, markdown=False) 

1232 builder.action(self.view_link, f"stays.generic.{self.proposal_type}.view_action") 

1233 builder.action(self.quick_decline_link, "stays.generic.quick_decline_action") 

1234 builder.para(".respond_encouragement") 

1235 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1236 return builder.build() 

1237 

1238 @classmethod 

1239 def from_notification(cls, data: notification_data_pb2.StayCreate, *, user_name: str) -> Self: 

1240 return cls( 

1241 user_name, 

1242 proposal_type=StayProposalType.from_proto(data.host_request), 

1243 initiator=UserInfo.from_proto(data.initiator), 

1244 from_date=date.fromisoformat(data.host_request.from_date), 

1245 to_date=date.fromisoformat(data.host_request.to_date), 

1246 text=data.text, 

1247 view_link=urls.host_request(host_request_id=data.host_request.host_request_id), 

1248 quick_decline_link=generate_quick_decline_link(data.host_request), 

1249 ) 

1250 

1251 @classmethod 

1252 def test_instances(cls) -> list[Self]: 

1253 prototype = cls( 

1254 user_name="Alice", 

1255 proposal_type=StayProposalType.request, 

1256 initiator=UserInfo.dummy_bob(), 

1257 from_date=date(2025, 6, 1), 

1258 to_date=date(2025, 6, 7), 

1259 text="Hey, I'd love to stay for a few nights!", 

1260 view_link="https://couchers.org/requests/123", 

1261 quick_decline_link="https://couchers.org/requests/123/decline?token=xxx", 

1262 ) 

1263 return [replace(prototype, proposal_type=proposal_type) for proposal_type in StayProposalType] 

1264 

1265 

1266@dataclass(kw_only=True, slots=True) 

1267class StayProposalReminderEmail(EmailBase): 

1268 """Sent to a the recipient of a pending stay proposal as a reminder to respond.""" 

1269 

1270 proposal_type: StayProposalType 

1271 initiator: UserInfo 

1272 from_date: date 

1273 to_date: date 

1274 view_link: str 

1275 quick_decline_link: str 

1276 

1277 @property 

1278 def string_key_base(self) -> str: 

1279 return f"stays.reminder.{self.proposal_type}" 

1280 

1281 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1282 return self._localize(loc_context, ".subject", {"initiator": self.initiator.name}) 

1283 

1284 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1285 builder = self._body_builder(loc_context) 

1286 builder.para(".purpose", {"initiator": self.initiator.name}) 

1287 builder.user( 

1288 self.initiator, 

1289 "stays.generic.date_range", 

1290 { 

1291 "from_date": _localize_stay_date(self.from_date, loc_context), 

1292 "to_date": _localize_stay_date(self.to_date, loc_context), 

1293 }, 

1294 ) 

1295 builder.action(self.view_link, f"stays.generic.{self.proposal_type}.view_action") 

1296 builder.action(self.quick_decline_link, "stays.generic.quick_decline_action") 

1297 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1298 return builder.build() 

1299 

1300 @classmethod 

1301 def from_notification(cls, data: notification_data_pb2.StayReminder, *, user_name: str) -> Self: 

1302 return cls( 

1303 user_name, 

1304 proposal_type=StayProposalType.from_proto(data.host_request), 

1305 initiator=UserInfo.from_proto(data.initiator), 

1306 from_date=date.fromisoformat(data.host_request.from_date), 

1307 to_date=date.fromisoformat(data.host_request.to_date), 

1308 view_link=urls.host_request(host_request_id=data.host_request.host_request_id), 

1309 quick_decline_link=generate_quick_decline_link(data.host_request), 

1310 ) 

1311 

1312 @classmethod 

1313 def test_instances(cls) -> list[Self]: 

1314 prototype = cls( 

1315 user_name="Alice", 

1316 proposal_type=StayProposalType.request, 

1317 initiator=UserInfo.dummy_bob(), 

1318 from_date=date(2025, 6, 1), 

1319 to_date=date(2025, 6, 7), 

1320 view_link="https://couchers.org/requests/123", 

1321 quick_decline_link="https://couchers.org/requests/123/decline?token=xxx", 

1322 ) 

1323 return [replace(prototype, proposal_type=proposal_type) for proposal_type in StayProposalType] 

1324 

1325 

1326@dataclass(kw_only=True, slots=True) 

1327class StayMessageEmail(EmailBase): 

1328 """Sent when the counterparty sends a message in a stay.""" 

1329 

1330 proposal_type: StayProposalType 

1331 counterparty: UserInfo 

1332 counterparty_is_initiator: bool 

1333 from_date: date 

1334 to_date: date 

1335 text: str 

1336 view_link: str 

1337 

1338 @property 

1339 def string_key_base(self) -> str: 

1340 variant = "from_initiator" if self.counterparty_is_initiator else "from_recipient" 

1341 return f"stays.message.{self.proposal_type}.{variant}" 

1342 

1343 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1344 return self._localize(loc_context, ".subject", {"counterparty": self.counterparty.name}) 

1345 

1346 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

1347 return self.text 

1348 

1349 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1350 builder = self._body_builder(loc_context) 

1351 builder.para(".purpose", {"counterparty": self.counterparty.name}) 

1352 builder.user( 

1353 self.counterparty, 

1354 "stays.generic.date_range", 

1355 { 

1356 "from_date": _localize_stay_date(self.from_date, loc_context), 

1357 "to_date": _localize_stay_date(self.to_date, loc_context), 

1358 }, 

1359 ) 

1360 builder.quote(self.text, markdown=False) 

1361 builder.action(self.view_link, f"stays.generic.{self.proposal_type}.view_action") 

1362 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1363 return builder.build() 

1364 

1365 @classmethod 

1366 def from_notification(cls, data: notification_data_pb2.StayMessage, *, user_name: str) -> Self: 

1367 return cls( 

1368 user_name, 

1369 proposal_type=StayProposalType.from_proto(data.host_request), 

1370 counterparty=UserInfo.from_proto(data.counterparty), 

1371 counterparty_is_initiator=data.counterparty_is_initiator, 

1372 from_date=date.fromisoformat(data.host_request.from_date), 

1373 to_date=date.fromisoformat(data.host_request.to_date), 

1374 text=data.text, 

1375 view_link=urls.host_request(host_request_id=data.host_request.host_request_id), 

1376 ) 

1377 

1378 @classmethod 

1379 def test_instances(cls) -> list[Self]: 

1380 prototype = cls( 

1381 user_name="Alice", 

1382 proposal_type=StayProposalType.request, 

1383 counterparty=UserInfo.dummy_bob(), 

1384 counterparty_is_initiator=False, 

1385 from_date=date(2025, 6, 1), 

1386 to_date=date(2025, 6, 7), 

1387 text="Looking forward to it, see you soon!", 

1388 view_link="https://couchers.org/requests/123", 

1389 ) 

1390 return [ 

1391 replace(prototype, proposal_type=proposal_type, counterparty_is_initiator=counterparty_is_initiator) 

1392 for counterparty_is_initiator in [False, True] 

1393 for proposal_type in StayProposalType 

1394 ] 

1395 

1396 

1397@dataclass(kw_only=True, slots=True) 

1398class StayMissedMessagesEmail(EmailBase): 

1399 """Sent as a digest when a user has missed messages in a stay.""" 

1400 

1401 proposal_type: StayProposalType 

1402 counterparty: UserInfo 

1403 counterparty_is_initiator: bool 

1404 from_date: date 

1405 to_date: date 

1406 view_link: str 

1407 

1408 @property 

1409 def string_key_base(self) -> str: 

1410 variant = "from_initiator" if self.counterparty_is_initiator else "from_recipient" 

1411 return f"stays.missed_messages.{self.proposal_type}.{variant}" 

1412 

1413 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1414 return self._localize(loc_context, ".subject", {"counterparty": self.counterparty.name}) 

1415 

1416 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1417 builder = self._body_builder(loc_context) 

1418 builder.para(".purpose", {"counterparty": self.counterparty.name}) 

1419 builder.user( 

1420 self.counterparty, 

1421 "stays.generic.date_range", 

1422 { 

1423 "from_date": _localize_stay_date(self.from_date, loc_context), 

1424 "to_date": _localize_stay_date(self.to_date, loc_context), 

1425 }, 

1426 ) 

1427 builder.action(self.view_link, f"stays.generic.{self.proposal_type}.view_action") 

1428 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1429 return builder.build() 

1430 

1431 @classmethod 

1432 def from_notification(cls, data: notification_data_pb2.StayMissedMessages, *, user_name: str) -> Self: 

1433 return cls( 

1434 user_name, 

1435 proposal_type=StayProposalType.from_proto(data.host_request), 

1436 counterparty=UserInfo.from_proto(data.counterparty), 

1437 counterparty_is_initiator=data.counterparty_is_initiator, 

1438 from_date=date.fromisoformat(data.host_request.from_date), 

1439 to_date=date.fromisoformat(data.host_request.to_date), 

1440 view_link=urls.host_request(host_request_id=data.host_request.host_request_id), 

1441 ) 

1442 

1443 @classmethod 

1444 def test_instances(cls) -> list[Self]: 

1445 prototype = cls( 

1446 user_name="Alice", 

1447 proposal_type=StayProposalType.request, 

1448 counterparty=UserInfo.dummy_bob(), 

1449 counterparty_is_initiator=False, 

1450 from_date=date(2025, 6, 1), 

1451 to_date=date(2025, 6, 7), 

1452 view_link="https://couchers.org/requests/123", 

1453 ) 

1454 return [ 

1455 replace(prototype, proposal_type=proposal_type, counterparty_is_initiator=counterparty_is_initiator) 

1456 for counterparty_is_initiator in [False, True] 

1457 for proposal_type in StayProposalType 

1458 ] 

1459 

1460 

1461@dataclass(kw_only=True, slots=True) 

1462class StayStatusChangedEmail(EmailBase): 

1463 """Sent when the counterparty accepts, declines, confirms or cancels a stay.""" 

1464 

1465 proposal_type: StayProposalType 

1466 counterparty: UserInfo 

1467 from_date: date 

1468 to_date: date 

1469 new_status: messages_pb2.HostRequestStatus.ValueType 

1470 view_link: str 

1471 

1472 @property 

1473 def string_key_base(self) -> str: 

1474 base_key = f"stays.status_changed.{self.proposal_type}" 

1475 match self.new_status: 

1476 case messages_pb2.HOST_REQUEST_STATUS_ACCEPTED: 

1477 return f"{base_key}.accepted_by_recipient" 

1478 case messages_pb2.HOST_REQUEST_STATUS_REJECTED: 

1479 return f"{base_key}.declined_by_recipient" 

1480 case messages_pb2.HOST_REQUEST_STATUS_CONFIRMED: 

1481 return f"{base_key}.confirmed_by_initiator" 

1482 case messages_pb2.HOST_REQUEST_STATUS_CANCELLED: 1482 ↛ 1484line 1482 didn't jump to line 1484 because the pattern on line 1482 always matched

1483 return f"{base_key}.cancelled_by_initiator" 

1484 case _: 

1485 raise ValueError(f"Unexpected host request status: {self.new_status}") 

1486 

1487 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1488 return self._localize(loc_context, ".subject", {"counterparty": self.counterparty.name}) 

1489 

1490 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1491 builder = self._body_builder(loc_context) 

1492 builder.para(".purpose", {"counterparty": self.counterparty.name}) 

1493 builder.user( 

1494 self.counterparty, 

1495 "stays.generic.date_range", 

1496 { 

1497 "from_date": _localize_stay_date(self.from_date, loc_context), 

1498 "to_date": _localize_stay_date(self.to_date, loc_context), 

1499 }, 

1500 ) 

1501 builder.action(self.view_link, f"stays.generic.{self.proposal_type}.view_action") 

1502 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1503 return builder.build() 

1504 

1505 @classmethod 

1506 def from_notification( 

1507 cls, 

1508 data: notification_data_pb2.StayAccept 

1509 | notification_data_pb2.StayReject 

1510 | notification_data_pb2.StayConfirm 

1511 | notification_data_pb2.StayCancel, 

1512 *, 

1513 user_name: str, 

1514 ) -> Self: 

1515 counterparty: UserInfo 

1516 new_status: messages_pb2.HostRequestStatus.ValueType 

1517 match data: 

1518 case notification_data_pb2.StayAccept(): 

1519 counterparty = UserInfo.from_proto(data.recipient) 

1520 new_status = messages_pb2.HostRequestStatus.HOST_REQUEST_STATUS_ACCEPTED 

1521 case notification_data_pb2.StayReject(): 1521 ↛ 1522line 1521 didn't jump to line 1522 because the pattern on line 1521 never matched

1522 counterparty = UserInfo.from_proto(data.recipient) 

1523 new_status = messages_pb2.HostRequestStatus.HOST_REQUEST_STATUS_REJECTED 

1524 case notification_data_pb2.StayConfirm(): 

1525 counterparty = UserInfo.from_proto(data.initiator) 

1526 new_status = messages_pb2.HostRequestStatus.HOST_REQUEST_STATUS_CONFIRMED 

1527 case notification_data_pb2.StayCancel(): 1527 ↛ 1530line 1527 didn't jump to line 1530 because the pattern on line 1527 always matched

1528 counterparty = UserInfo.from_proto(data.initiator) 

1529 new_status = messages_pb2.HostRequestStatus.HOST_REQUEST_STATUS_CANCELLED 

1530 case _: 

1531 # Enable mypy's exhaustiveness checking 

1532 assert_never("Unexpected host request status changed notification data type.") 

1533 

1534 return cls( 

1535 user_name, 

1536 proposal_type=StayProposalType.from_proto(data.host_request), 

1537 counterparty=counterparty, 

1538 from_date=date.fromisoformat(data.host_request.from_date), 

1539 to_date=date.fromisoformat(data.host_request.to_date), 

1540 new_status=new_status, 

1541 view_link=urls.host_request(host_request_id=data.host_request.host_request_id), 

1542 ) 

1543 

1544 @classmethod 

1545 def test_instances(cls) -> list[Self]: 

1546 prototype = cls( 

1547 user_name="Alice", 

1548 proposal_type=StayProposalType.request, 

1549 counterparty=UserInfo.dummy_bob(), 

1550 from_date=date(2025, 6, 1), 

1551 to_date=date(2025, 6, 7), 

1552 new_status=messages_pb2.HOST_REQUEST_STATUS_ACCEPTED, 

1553 view_link="https://couchers.org/requests/123", 

1554 ) 

1555 return [ 

1556 replace(prototype, proposal_type=proposal_type, new_status=new_status) 

1557 for new_status in [ 

1558 messages_pb2.HOST_REQUEST_STATUS_ACCEPTED, 

1559 messages_pb2.HOST_REQUEST_STATUS_REJECTED, 

1560 messages_pb2.HOST_REQUEST_STATUS_CONFIRMED, 

1561 messages_pb2.HOST_REQUEST_STATUS_CANCELLED, 

1562 ] 

1563 for proposal_type in StayProposalType 

1564 ] 

1565 

1566 

1567@dataclass(kw_only=True, slots=True) 

1568class StayReferenceReceivedEmail(EmailBase): 

1569 """Sent to a user when they receive a reference from a past host or surfer.""" 

1570 

1571 from_user: UserInfo 

1572 text: str | None # None if hidden because receiver hasn't written their reference yet. 

1573 surfed: bool # True if I was the surfer, False if I was the host 

1574 leave_reference_url: str 

1575 

1576 @property 

1577 def string_key_base(self) -> str: 

1578 return "references.received" 

1579 

1580 @property 

1581 def string_role_subkey(self) -> str: 

1582 return "surfed" if self.surfed else "hosted" 

1583 

1584 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1585 return self._localize(loc_context, ".subject", {"name": self.from_user.name}) 

1586 

1587 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

1588 return self.text 

1589 

1590 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1591 builder = self._body_builder(loc_context) 

1592 builder.para(f".{self.string_role_subkey}.purpose", {"name": self.from_user.name}) 

1593 builder.user(self.from_user) 

1594 if self.text: 

1595 builder.quote(self.text, markdown=False) 

1596 builder.action(urls.profile_references_link(), ".view_action") 

1597 else: 

1598 builder.para(f".{self.string_role_subkey}.reciprocate_encouragement", {"name": self.from_user.name}) 

1599 builder.action(self.leave_reference_url, "references.write_action", {"name": self.from_user.name}) 

1600 return builder.build() 

1601 

1602 @classmethod 

1603 def from_notification( 

1604 cls, data: notification_data_pb2.ReferenceReceiveStay, *, user_name: str, surfed: bool 

1605 ) -> Self: 

1606 return cls( 

1607 user_name=user_name, 

1608 from_user=UserInfo.from_proto(data.from_user), 

1609 text=data.text or None, 

1610 surfed=surfed, 

1611 leave_reference_url=urls.leave_reference_link( 

1612 reference_type="surfed" if surfed else "hosted", 

1613 to_user_id=str(data.from_user.user_id), 

1614 host_request_id=str(data.host_request_id), 

1615 ), 

1616 ) 

1617 

1618 @classmethod 

1619 def test_instances(cls) -> list[Self]: 

1620 prototype = cls( 

1621 user_name="Alice", 

1622 from_user=UserInfo.dummy_bob(), 

1623 text="Alice was a fantastic guest!", 

1624 surfed=True, 

1625 leave_reference_url="https://couchers.org/leave-reference/123", 

1626 ) 

1627 return [ 

1628 replace(prototype, surfed=True, text="Alice was a fantastic guest!"), 

1629 replace(prototype, surfed=True, text=None), 

1630 replace(prototype, surfed=False, text="Bob was a wonderful host!"), 

1631 replace(prototype, surfed=False, text=None), 

1632 ] 

1633 

1634 

1635@dataclass(kw_only=True, slots=True) 

1636class StayReferenceReminderEmail(EmailBase): 

1637 """Sent as a reminder to write a reference after a stay.""" 

1638 

1639 counterparty: UserInfo 

1640 days_left: int 

1641 surfed: bool # True if I was the surfer, False if I was the host 

1642 leave_reference_url: str 

1643 

1644 @property 

1645 def string_key_base(self) -> str: 

1646 return "references.reminder" 

1647 

1648 @property 

1649 def string_role_subkey(self) -> str: 

1650 return "surfed" if self.surfed else "hosted" 

1651 

1652 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1653 return self._localize( 

1654 loc_context, 

1655 ".subject_days", 

1656 {"name": self.counterparty.name, "count": self.days_left}, 

1657 ) 

1658 

1659 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1660 builder = self._body_builder(loc_context) 

1661 builder.para( 

1662 f".{self.string_role_subkey}.purpose_days", {"name": self.counterparty.name, "count": self.days_left} 

1663 ) 

1664 builder.user(self.counterparty) 

1665 builder.action( 

1666 self.leave_reference_url, 

1667 "references.write_action", 

1668 {"name": self.counterparty.name}, 

1669 ) 

1670 builder.para(".no_meeting_note", {"name": self.counterparty.name}) 

1671 builder.para(".visibility_note") 

1672 return builder.build() 

1673 

1674 @classmethod 

1675 def from_notification(cls, data: notification_data_pb2.ReferenceReminder, *, user_name: str, surfed: bool) -> Self: 

1676 return cls( 

1677 user_name=user_name, 

1678 counterparty=UserInfo.from_proto(data.other_user), 

1679 days_left=data.days_left, 

1680 surfed=surfed, 

1681 leave_reference_url=urls.leave_reference_link( 

1682 reference_type="surfed" if surfed else "hosted", 

1683 to_user_id=str(data.other_user.user_id), 

1684 host_request_id=str(data.host_request_id), 

1685 ), 

1686 ) 

1687 

1688 @classmethod 

1689 def test_instances(cls) -> list[Self]: 

1690 prototype = cls( 

1691 user_name="Alice", 

1692 counterparty=UserInfo.dummy_bob(), 

1693 days_left=7, 

1694 surfed=True, 

1695 leave_reference_url="https://couchers.org/leave-reference/123", 

1696 ) 

1697 return [replace(prototype, surfed=True), replace(prototype, surfed=False)] 

1698 

1699 

1700@dataclass(kw_only=True, slots=True) 

1701class ModeratorNoteEmail(EmailBase): 

1702 """Sent to a user to notify them they have received a moderator note.""" 

1703 

1704 # The note's text, only set if the moderator chose to include it in the email. 

1705 markdown_text: str | None 

1706 

1707 @property 

1708 def string_key_base(self) -> str: 

1709 return "moderator_note" 

1710 

1711 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

1712 return markdown_to_plaintext(self.markdown_text) if self.markdown_text else None 

1713 

1714 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1715 builder = self._body_builder(loc_context) 

1716 if self.markdown_text: 

1717 builder.para(".purpose_with_note") 

1718 builder.quote(self.markdown_text, markdown=True) 

1719 builder.para(".acknowledge_request") 

1720 builder.para(".reply_instructions") 

1721 else: 

1722 builder.para(".purpose") 

1723 # Users with moderator notes are "jailed": any URL will show the note before 

1724 # letting them use the platform. 

1725 builder.action(urls.dashboard_link(), ".view_action") 

1726 return builder.build() 

1727 

1728 @classmethod 

1729 def from_notification(cls, data: notification_data_pb2.ModNoteCreate, *, user_name: str) -> Self: 

1730 return cls(user_name=user_name, markdown_text=data.markdown_text or None) 

1731 

1732 @classmethod 

1733 def test_instances(cls) -> list[Self]: 

1734 return [ 

1735 cls(user_name="Alice", markdown_text=None), 

1736 cls( 

1737 user_name="Alice", 

1738 markdown_text="Please **add** a profile photo so that your hosts can recognise you.", 

1739 ), 

1740 ] 

1741 

1742 

1743@dataclass(kw_only=True, slots=True) 

1744class NewBlogPostEmail(EmailBase): 

1745 """Sent to notify users of a new blog post.""" 

1746 

1747 title: str 

1748 blurb: str 

1749 url: str 

1750 

1751 @property 

1752 def string_key_base(self) -> str: 

1753 return "new_blog_post" 

1754 

1755 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

1756 return self._localize(loc_context, ".subject", {"title": self.title}) 

1757 

1758 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

1759 return self.blurb 

1760 

1761 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1762 builder = self._body_builder(loc_context) 

1763 builder.para(".purpose") 

1764 builder.block(ParaBlock(text=Markup(f"<b>{escape(self.title)}</b>"))) 

1765 builder.quote(self.blurb, markdown=False) 

1766 builder.action(self.url, ".read_action") 

1767 return builder.build() 

1768 

1769 @classmethod 

1770 def from_notification(cls, data: notification_data_pb2.GeneralNewBlogPost, *, user_name: str) -> Self: 

1771 return cls(user_name=user_name, title=data.title, blurb=data.blurb, url=data.url) 

1772 

1773 @classmethod 

1774 def test_instances(cls) -> list[Self]: 

1775 return [ 

1776 cls( 

1777 user_name="Alice", 

1778 title="Exciting new features on Couchers.org", 

1779 blurb="We've launched some great new features including improved messaging and event discovery.", 

1780 url="https://couchers.org/blog/2025/01/01/new-features", 

1781 ) 

1782 ] 

1783 

1784 

1785@dataclass(kw_only=True, slots=True) 

1786class OnboardingReminderEmail(EmailBase): 

1787 """Onboarding email sent to new users; initial=True for the first email, False for the second.""" 

1788 

1789 initial: bool 

1790 

1791 @property 

1792 def string_key_base(self) -> str: 

1793 return f"onboarding_reminder.{'initial' if self.initial else 'follow_up'}" 

1794 

1795 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1796 builder = self._body_builder(loc_context, default_closing=False) 

1797 if self.initial: 

1798 self._build_body_initial(builder) 

1799 else: 

1800 self._build_body_followup(builder) 

1801 return builder.build() 

1802 

1803 def _build_body_initial(self, builder: EmailBlocksBuilder) -> None: 

1804 builder.para(".welcome") 

1805 builder.para(".early_user_role") 

1806 builder.para(".complete_profile_request") 

1807 builder.para(".profile_importance") 

1808 builder.action(urls.edit_profile_link(), "onboarding_reminder.complete_profile_action") 

1809 builder.para(".share_request") 

1810 builder.para( 

1811 "generic.closing_lines.aapeli", 

1812 { 

1813 "profile_link": html_link("https://couchers.org/user/aapeli"), 

1814 }, 

1815 ) 

1816 

1817 def _build_body_followup(self, builder: EmailBlocksBuilder) -> None: 

1818 builder.para(".intro") 

1819 builder.para(".request") 

1820 builder.action(urls.edit_profile_link(), "onboarding_reminder.complete_profile_action") 

1821 builder.para("generic.thanks") 

1822 builder.para( 

1823 "generic.closing_lines.emily", 

1824 { 

1825 "email_link": html_mailto_link("community@couchers.org"), 

1826 "profile_link": html_link("https://couchers.org/user/emily"), 

1827 }, 

1828 ) 

1829 

1830 @classmethod 

1831 def test_instances(cls) -> list[Self]: 

1832 prototype = cls(user_name="Alice", initial=True) 

1833 return [replace(prototype, initial=True), replace(prototype, initial=False)] 

1834 

1835 

1836@dataclass(kw_only=True, slots=True) 

1837class PasswordChangedEmail(EmailBase): 

1838 """Sent to a user to notify them that their login password was changed.""" 

1839 

1840 @property 

1841 def string_key_base(self) -> str: 

1842 return "password_changed" 

1843 

1844 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1845 builder = self._body_builder(loc_context, security_warning=True) 

1846 builder.para(".purpose") 

1847 return builder.build() 

1848 

1849 @classmethod 

1850 def test_instances(cls) -> list[Self]: 

1851 return [cls(user_name="Alice")] 

1852 

1853 

1854@dataclass(kw_only=True, slots=True) 

1855class PasswordResetCompletedEmail(EmailBase): 

1856 """Sent to a user to confirm their password was successfully reset.""" 

1857 

1858 @property 

1859 def string_key_base(self) -> str: 

1860 return "password_reset.completed" 

1861 

1862 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1863 builder = self._body_builder(loc_context, security_warning=True) 

1864 builder.para(".purpose") 

1865 return builder.build() 

1866 

1867 @classmethod 

1868 def test_instances(cls) -> list[Self]: 

1869 return [cls(user_name="Alice")] 

1870 

1871 

1872@dataclass(kw_only=True, slots=True) 

1873class PasswordResetStartedEmail(EmailBase): 

1874 """Sent to a user with a link to complete their password reset.""" 

1875 

1876 password_reset_link: str 

1877 

1878 @property 

1879 def string_key_base(self) -> str: 

1880 return "password_reset.started" 

1881 

1882 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1883 builder = self._body_builder(loc_context, security_warning=True) 

1884 builder.para(".purpose") 

1885 builder.action(self.password_reset_link, ".reset_action") 

1886 return builder.build() 

1887 

1888 @classmethod 

1889 def from_notification(cls, data: notification_data_pb2.PasswordResetStart, *, user_name: str) -> Self: 

1890 return cls( 

1891 user_name=user_name, 

1892 password_reset_link=urls.password_reset_link(password_reset_token=data.password_reset_token), 

1893 ) 

1894 

1895 @classmethod 

1896 def test_instances(cls) -> list[Self]: 

1897 return [cls(user_name="Alice", password_reset_link="https://couchers.org/reset-password")] 

1898 

1899 

1900@dataclass(kw_only=True, slots=True) 

1901class PhoneNumberChangeEmail(EmailBase): 

1902 """Sent to a user to notify them that their phone number verification status was changed.""" 

1903 

1904 new_phone_number: str 

1905 completed: bool # False = started, True = completed 

1906 

1907 @property 

1908 def string_key_base(self) -> str: 

1909 return "phone_number_verification.verified" if self.completed else "phone_number_verification.started" 

1910 

1911 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1912 builder = self._body_builder(loc_context, security_warning=True) 

1913 builder.para(".purpose", {"phone_number": format_phone_number(self.new_phone_number)}) 

1914 return builder.build() 

1915 

1916 @classmethod 

1917 def from_change_notification(cls, data: notification_data_pb2.PhoneNumberChange, *, user_name: str) -> Self: 

1918 return cls(user_name=user_name, new_phone_number=data.phone, completed=False) 

1919 

1920 @classmethod 

1921 def from_verify_notification(cls, data: notification_data_pb2.PhoneNumberVerify, *, user_name: str) -> Self: 

1922 return cls(user_name=user_name, new_phone_number=data.phone, completed=True) 

1923 

1924 @classmethod 

1925 def test_instances(cls) -> list[Self]: 

1926 prototype = cls( 

1927 user_name="Alice", 

1928 new_phone_number="+12223334444", 

1929 completed=False, 

1930 ) 

1931 return [replace(prototype, completed=False), replace(prototype, completed=True)] 

1932 

1933 

1934@dataclass(kw_only=True, slots=True) 

1935class PostalVerificationFailedEmail(EmailBase): 

1936 """Sent to a user when their postal verification attempt has failed.""" 

1937 

1938 reason: notification_data_pb2.PostalVerificationFailReason.ValueType 

1939 

1940 @property 

1941 def string_key_base(self) -> str: 

1942 return "postal_verification.failed" 

1943 

1944 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1945 builder = self._body_builder(loc_context, security_warning=True) 

1946 match self.reason: 

1947 case notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_CODE_EXPIRED: 

1948 purpose_string_key = ".purpose.code_expired" 

1949 case notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_TOO_MANY_ATTEMPTS: 

1950 purpose_string_key = ".purpose.too_many_attempts" 

1951 case _: 

1952 purpose_string_key = ".purpose.default" 

1953 builder.para(purpose_string_key) 

1954 builder.action(urls.account_settings_link(), ".restart_action") 

1955 return builder.build() 

1956 

1957 @classmethod 

1958 def from_notification(cls, data: notification_data_pb2.PostalVerificationFailed, *, user_name: str) -> Self: 

1959 return cls(user_name=user_name, reason=data.reason) 

1960 

1961 @classmethod 

1962 def test_instances(cls) -> list[Self]: 

1963 prototype = cls( 

1964 user_name="Alice", 

1965 reason=notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_CODE_EXPIRED, 

1966 ) 

1967 return [ 

1968 replace(prototype, reason=notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_CODE_EXPIRED), 

1969 replace(prototype, reason=notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_TOO_MANY_ATTEMPTS), 

1970 replace(prototype, reason=notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_UNKNOWN), 

1971 ] 

1972 

1973 

1974@dataclass(kw_only=True, slots=True) 

1975class PostalVerificationPostcardSentEmail(EmailBase): 

1976 """Sent to a user to notify them that their verification postcard has been sent.""" 

1977 

1978 city: str 

1979 country: str 

1980 

1981 @property 

1982 def string_key_base(self) -> str: 

1983 return "postal_verification.postcard_sent" 

1984 

1985 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

1986 builder = self._body_builder(loc_context, security_warning=True) 

1987 builder.para(".purpose", {"city": self.city, "country": self.country}) 

1988 builder.action(urls.dashboard_link(), ".enter_code_action") 

1989 return builder.build() 

1990 

1991 @classmethod 

1992 def from_notification(cls, data: notification_data_pb2.PostalVerificationPostcardSent, *, user_name: str) -> Self: 

1993 return cls(user_name=user_name, city=data.city, country=data.country) 

1994 

1995 @classmethod 

1996 def test_instances(cls) -> list[Self]: 

1997 return [cls(user_name="Alice", city="New York", country="United States")] 

1998 

1999 

2000@dataclass(kw_only=True, slots=True) 

2001class PostalVerificationSucceededEmail(EmailBase): 

2002 """Sent to a user when their postal verification has succeeded.""" 

2003 

2004 @property 

2005 def string_key_base(self) -> str: 

2006 return "postal_verification.succeeded" 

2007 

2008 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

2009 builder = self._body_builder(loc_context, security_warning=True) 

2010 builder.para(".purpose") 

2011 return builder.build() 

2012 

2013 @classmethod 

2014 def test_instances(cls) -> list[Self]: 

2015 return [cls(user_name="Alice")] 

2016 

2017 

2018@dataclass(kw_only=True, slots=True) 

2019class SignupVerifyEmail(EmailBase): 

2020 """Sent to a user to verify their email address.""" 

2021 

2022 verify_url: str 

2023 

2024 @property 

2025 def string_key_base(self) -> str: 

2026 return "signup.verify" 

2027 

2028 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

2029 return self._localize(loc_context, "signup.subject") 

2030 

2031 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

2032 builder = self._body_builder(loc_context) 

2033 builder.para(".thanks") 

2034 builder.para(".instructions") 

2035 builder.action(self.verify_url, ".confirm_action") 

2036 builder.para("signup.closing") 

2037 return builder.build() 

2038 

2039 @classmethod 

2040 def test_instances(cls) -> list[Self]: 

2041 return [cls(user_name="Alice", verify_url="https://example.com")] 

2042 

2043 

2044@dataclass(kw_only=True, slots=True) 

2045class SignupContinueEmail(EmailBase): 

2046 """Sent to a user to ask them to continue the signup process.""" 

2047 

2048 continue_url: str 

2049 

2050 @property 

2051 def string_key_base(self) -> str: 

2052 return "signup.continue" 

2053 

2054 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

2055 return self._localize(loc_context, "signup.subject") 

2056 

2057 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

2058 builder = self._body_builder(loc_context) 

2059 builder.para(".purpose") 

2060 builder.action(self.continue_url, ".continue_action") 

2061 builder.para("signup.closing") 

2062 builder.para(".ignore_if_unexpected") 

2063 return builder.build() 

2064 

2065 @classmethod 

2066 def test_instances(cls) -> list[Self]: 

2067 return [cls(user_name="Alice", continue_url="https://example.com")] 

2068 

2069 

2070@dataclass(kw_only=True, slots=True) 

2071class StrongVerificationFailedEmail(EmailBase): 

2072 """Sent to a user when their strong verification attempt has failed.""" 

2073 

2074 reason: notification_data_pb2.SVFailReason.ValueType 

2075 

2076 @property 

2077 def string_key_base(self) -> str: 

2078 return "strong_verification.failed" 

2079 

2080 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

2081 builder = self._body_builder(loc_context, security_warning=True) 

2082 match self.reason: 

2083 case notification_data_pb2.SV_FAIL_REASON_WRONG_BIRTHDATE_OR_GENDER: 

2084 purpose_string_key = ".purpose.wrong_birthdate_or_gender" 

2085 case notification_data_pb2.SV_FAIL_REASON_NOT_A_PASSPORT: 

2086 purpose_string_key = ".purpose.not_a_passport" 

2087 case notification_data_pb2.SV_FAIL_REASON_DUPLICATE: 2087 ↛ 2089line 2087 didn't jump to line 2089 because the pattern on line 2087 always matched

2088 purpose_string_key = ".purpose.duplicate" 

2089 case _: 

2090 raise Exception("Shouldn't get here") 

2091 builder.para(purpose_string_key) 

2092 builder.action(urls.strong_verification_url(), ".restart_action") 

2093 return builder.build() 

2094 

2095 @classmethod 

2096 def from_notification(cls, data: notification_data_pb2.VerificationSVFail, *, user_name: str) -> Self: 

2097 return cls(user_name=user_name, reason=data.reason) 

2098 

2099 @classmethod 

2100 def test_instances(cls) -> list[Self]: 

2101 prototype = cls( 

2102 user_name="Alice", 

2103 reason=notification_data_pb2.SV_FAIL_REASON_NOT_A_PASSPORT, 

2104 ) 

2105 return [ 

2106 replace(prototype, reason=notification_data_pb2.SV_FAIL_REASON_WRONG_BIRTHDATE_OR_GENDER), 

2107 replace(prototype, reason=notification_data_pb2.SV_FAIL_REASON_NOT_A_PASSPORT), 

2108 replace(prototype, reason=notification_data_pb2.SV_FAIL_REASON_DUPLICATE), 

2109 ] 

2110 

2111 

2112@dataclass(kw_only=True, slots=True) 

2113class StrongVerificationSucceededEmail(EmailBase): 

2114 """Sent to a user when their strong verification has succeeded.""" 

2115 

2116 @property 

2117 def string_key_base(self) -> str: 

2118 return "strong_verification.succeeded" 

2119 

2120 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

2121 builder = self._body_builder(loc_context, security_warning=True) 

2122 builder.para(".purpose") 

2123 builder.para(".thanks_message") 

2124 builder.para(".cost_explanation") 

2125 builder.para(".donation_request") 

2126 donate_link = urls.donation_url() + "?utm_source=strong-verification-email" 

2127 builder.action(donate_link, ".donate_action") 

2128 return builder.build() 

2129 

2130 @classmethod 

2131 def test_instances(cls) -> list[Self]: 

2132 return [cls(user_name="Alice")] 

2133 

2134 

2135@dataclass(kw_only=True, slots=True) 

2136class ThreadReplyEmail(EmailBase): 

2137 """Sent to a user when someone replies in a comment thread they participated in.""" 

2138 

2139 author: UserInfo 

2140 parent_context: str # Title of the event or discussion being replied in 

2141 markdown_text: str 

2142 view_link: str 

2143 

2144 @property 

2145 def string_key_base(self) -> str: 

2146 return "thread_reply" 

2147 

2148 def get_subject_line(self, loc_context: LocalizationContext) -> str: 

2149 return self._localize( 

2150 loc_context, ".subject", {"author": self.author.name, "parent_context": self.parent_context} 

2151 ) 

2152 

2153 def get_preview_line(self, loc_context: LocalizationContext) -> str | None: 

2154 return markdown_to_plaintext(self.markdown_text) 

2155 

2156 def get_body_blocks(self, loc_context: LocalizationContext) -> list[EmailBlock]: 

2157 builder = self._body_builder(loc_context) 

2158 builder.para(".purpose", {"author": self.author.name, "parent_context": self.parent_context}) 

2159 builder.user(self.author) 

2160 builder.quote(self.markdown_text, markdown=True) 

2161 builder.action(self.view_link, ".view_action") 

2162 return builder.build() 

2163 

2164 @classmethod 

2165 def from_notification(cls, data: notification_data_pb2.ThreadReply, *, user_name: str) -> Self: 

2166 parent = data.WhichOneof("reply_parent") 

2167 if parent == "event": 

2168 parent_context = data.event.title 

2169 view_link = urls.event_link(occurrence_id=data.event.event_id, slug=data.event.slug) 

2170 elif parent == "discussion": 2170 ↛ 2174line 2170 didn't jump to line 2174 because the condition on line 2170 was always true

2171 parent_context = data.discussion.title 

2172 view_link = urls.discussion_link(discussion_id=data.discussion.discussion_id, slug=data.discussion.slug) 

2173 else: 

2174 raise Exception("Can only do replies to events and discussions") 

2175 return cls( 

2176 user_name=user_name, 

2177 author=UserInfo.from_proto(data.author), 

2178 parent_context=parent_context, 

2179 markdown_text=data.reply.content, 

2180 view_link=view_link, 

2181 ) 

2182 

2183 @classmethod 

2184 def test_instances(cls) -> list[Self]: 

2185 return [ 

2186 cls( 

2187 user_name="Alice", 

2188 author=UserInfo.dummy_bob(), 

2189 parent_context="Best hiking trails near Berlin", 

2190 markdown_text="I agree, the Grünewald is **amazing**!", 

2191 view_link="https://couchers.org/discussions/123", 

2192 ) 

2193 ] 

2194 

2195 

2196def _localize_stay_date(value: date, loc_context: LocalizationContext) -> str: 

2197 return loc_context.localize_date(value, with_year=False, with_day_of_week=True)