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

1088 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-27 22:43 +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_whole_usd: 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": loc_context.localize_currency(self.amount_whole_usd, "USD")}) 

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_whole_usd=data.amount, receipt_url=data.receipt_url) 

564 

565 @classmethod 

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

567 return [ 

568 cls( 

569 user_name="Alice", 

570 amount_whole_usd=25, 

571 receipt_url="https://couchers.org/receipts/123", 

572 ) 

573 ] 

574 

575 

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

577class EmailChangedEmail(EmailBase): 

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

579 

580 new_email: str 

581 

582 @property 

583 def string_key_base(self) -> str: 

584 return "email_change.initiated" 

585 

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

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

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

589 return builder.build() 

590 

591 @classmethod 

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

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

594 

595 @classmethod 

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

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

598 

599 

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

601class EmailChangeConfirmationEmail(EmailBase): 

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

603 

604 old_email: str 

605 confirm_url: str 

606 

607 @property 

608 def string_key_base(self) -> str: 

609 return "email_change.confirmation" 

610 

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

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

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

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

615 return builder.build() 

616 

617 @classmethod 

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

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

620 

621 

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

623class EmailVerifiedEmail(EmailBase): 

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

625 

626 @property 

627 def string_key_base(self) -> str: 

628 return "email_change.verified" 

629 

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

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

632 builder.para(".purpose") 

633 return builder.build() 

634 

635 @classmethod 

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

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

638 

639 

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

641class EventInfo: 

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

643 

644 title: str 

645 start_time: datetime 

646 end_time: datetime 

647 timezone: tzinfo 

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

649 view_url: str 

650 description_markdown: str 

651 

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

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

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

655 start_time_display = loc_context.localize_datetime( 

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

657 ) 

658 end_time_display = loc_context.localize_datetime( 

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

660 ) 

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

662 

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

664 html += "<br>" 

665 html += time_range_display 

666 if self.address: 

667 html += "<br>" 

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

669 

670 return ParaBlock(text=Markup(html)) 

671 

672 def get_description_block(self) -> EmailBlock: 

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

674 

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

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

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

678 

679 @classmethod 

680 def from_proto(cls, event: events_pb2.Event, *, comment_id: int | None = None) -> EventInfo: 

681 return cls( 

682 title=event.title, 

683 start_time=to_aware_datetime(event.start_time), 

684 end_time=to_aware_datetime(event.end_time), 

685 timezone=ZoneInfo(event.timezone), 

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

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

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

689 description_markdown=event.content or "", 

690 ) 

691 

692 @staticmethod 

693 def dummy() -> EventInfo: 

694 return EventInfo( 

695 title="Berlin Meetup", 

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

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

698 timezone=UTC, 

699 address="Alexanderplatz, Berlin", 

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

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

702 ) 

703 

704 

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

706class EventCreatedEmail(EmailBase): 

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

708 

709 inviting_user: UserInfo 

710 event_info: EventInfo 

711 community_name: str | None 

712 community_url: str | None 

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

714 

715 @property 

716 def string_key_base(self) -> str: 

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

718 

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

720 return self._localize( 

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

722 ) 

723 

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

725 return markdown_to_plaintext(self.event_info.description_markdown) 

726 

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

728 builder = self._body_builder(loc_context) 

729 if self.community_name: 

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

731 else: 

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

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

734 builder.user(self.inviting_user) 

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

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

737 return builder.build() 

738 

739 @classmethod 

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

741 has_community = bool(data.in_community.community_id) 

742 community_url = ( 

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

744 if has_community 

745 else None 

746 ) 

747 return cls( 

748 user_name=user_name, 

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

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

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

752 community_url=community_url, 

753 is_invite=is_invite, 

754 ) 

755 

756 @classmethod 

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

758 prototype = cls( 

759 user_name="Alice", 

760 inviting_user=UserInfo.dummy_bob(), 

761 event_info=EventInfo.dummy(), 

762 community_name="Berlin", 

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

764 is_invite=True, 

765 ) 

766 return [ 

767 replace(prototype, is_invite=True), 

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

769 replace(prototype, is_invite=False), 

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

771 ] 

772 

773 

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

775class EventUpdatedEmail(EmailBase): 

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

777 

778 updating_user: UserInfo 

779 event_info: EventInfo 

780 updated_items: list[notification_data_pb2.EventUpdateItem.ValueType] 

781 

782 @property 

783 def string_key_base(self) -> str: 

784 return "events.updated" 

785 

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

787 return self._localize( 

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

789 ) 

790 

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

792 builder = self._body_builder(loc_context) 

793 

794 updated_items_string_keys = list( 

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

796 ) 

797 if updated_items_string_keys: 

798 updated_items_text = loc_context.localize_list( 

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

800 ) 

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

802 else: 

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

804 

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

806 builder.user(self.updating_user) 

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

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

809 return builder.build() 

810 

811 @classmethod 

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

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

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

815 updated_items.extend(data.updated_enum_items) 

816 

817 return cls( 

818 user_name=user_name, 

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

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

821 updated_items=updated_items, 

822 ) 

823 

824 @staticmethod 

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

826 match value: 

827 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_TITLE: 

828 return ".item_names.title" 

829 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_CONTENT: 

830 return ".item_names.content" 

831 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_LOCATION: 

832 return ".item_names.location" 

833 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_START_TIME: 

834 return ".item_names.start_time" 

835 case notification_data_pb2.EventUpdateItem.EVENT_UPDATE_ITEM_END_TIME: 

836 return ".item_names.end_time" 

837 case _: 

838 return None 

839 

840 @classmethod 

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

842 prototype = cls( 

843 user_name="Alice", 

844 updating_user=UserInfo.dummy_bob(), 

845 event_info=EventInfo.dummy(), 

846 updated_items=[], 

847 ) 

848 return [ 

849 replace(prototype, updated_items=[]), 

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

851 ] 

852 

853 

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

855class EventOrganizerInvitedEmail(EmailBase): 

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

857 

858 inviting_user: UserInfo 

859 event_info: EventInfo 

860 

861 @property 

862 def string_key_base(self) -> str: 

863 return "events.organizer_invited" 

864 

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

866 return self._localize( 

867 loc_context, 

868 ".subject", 

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

870 ) 

871 

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

873 builder = self._body_builder(loc_context) 

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

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

876 builder.user(self.inviting_user) 

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

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

879 builder.para(_do_not_reply_request_string_key, epilogue=True) 

880 return builder.build() 

881 

882 @classmethod 

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

884 return cls( 

885 user_name=user_name, 

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

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

888 ) 

889 

890 @classmethod 

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

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

893 

894 

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

896class EventCommentEmail(EmailBase): 

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

898 

899 author: UserInfo 

900 event_info: EventInfo 

901 comment_markdown: str 

902 

903 @property 

904 def string_key_base(self) -> str: 

905 return "events.comment" 

906 

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

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

909 

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

911 return markdown_to_plaintext(self.comment_markdown) 

912 

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

914 builder = self._body_builder(loc_context) 

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

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

917 builder.user(self.author) 

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

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

920 return builder.build() 

921 

922 @classmethod 

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

924 return cls( 

925 user_name=user_name, 

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

927 event_info=EventInfo.from_proto(data.event, comment_id=data.reply.thread_id), 

928 comment_markdown=data.reply.content, 

929 ) 

930 

931 @classmethod 

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

933 return [ 

934 cls( 

935 user_name="Alice", 

936 author=UserInfo.dummy_bob(), 

937 event_info=EventInfo.dummy(), 

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

939 ) 

940 ] 

941 

942 

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

944class EventReminderEmail(EmailBase): 

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

946 

947 event_info: EventInfo 

948 

949 @property 

950 def string_key_base(self) -> str: 

951 return "events.reminder" 

952 

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

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

955 

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

957 builder = self._body_builder(loc_context) 

958 builder.para(".purpose") 

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

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

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

962 return builder.build() 

963 

964 @classmethod 

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

966 return cls( 

967 user_name=user_name, 

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

969 ) 

970 

971 @classmethod 

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

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

974 

975 

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

977class EventCancelledEmail(EmailBase): 

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

979 

980 cancelling_user: UserInfo 

981 event_info: EventInfo 

982 

983 @property 

984 def string_key_base(self) -> str: 

985 return "events.cancel" 

986 

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

988 return self._localize( 

989 loc_context, 

990 ".subject", 

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

992 ) 

993 

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

995 builder = self._body_builder(loc_context) 

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

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

998 builder.user(self.cancelling_user) 

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

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

1001 return builder.build() 

1002 

1003 @classmethod 

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

1005 return cls( 

1006 user_name=user_name, 

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

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

1009 ) 

1010 

1011 @classmethod 

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

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

1014 

1015 

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

1017class EventDeletedEmail(EmailBase): 

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

1019 

1020 event_info: EventInfo 

1021 

1022 @property 

1023 def string_key_base(self) -> str: 

1024 return "events.deleted" 

1025 

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

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

1028 

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

1030 builder = self._body_builder(loc_context) 

1031 builder.para(".purpose") 

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

1033 return builder.build() 

1034 

1035 @classmethod 

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

1037 return cls( 

1038 user_name=user_name, 

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

1040 ) 

1041 

1042 @classmethod 

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

1044 return [ 

1045 cls( 

1046 user_name="Alice", 

1047 event_info=EventInfo.dummy(), 

1048 ) 

1049 ] 

1050 

1051 

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

1053class FriendReferenceReceivedEmail(EmailBase): 

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

1055 

1056 from_user: UserInfo 

1057 text: str 

1058 

1059 @property 

1060 def string_key_base(self) -> str: 

1061 return "references.received.friend" 

1062 

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

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

1065 

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

1067 return self.text 

1068 

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

1070 builder = self._body_builder(loc_context) 

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

1072 builder.user(self.from_user) 

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

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

1075 return builder.build() 

1076 

1077 @classmethod 

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

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

1080 

1081 @classmethod 

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

1083 return [ 

1084 cls( 

1085 user_name="Alice", 

1086 from_user=UserInfo.dummy_bob(), 

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

1088 ) 

1089 ] 

1090 

1091 

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

1093class FriendRequestReceivedEmail(EmailBase): 

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

1095 

1096 befriender: UserInfo 

1097 

1098 @property 

1099 def string_key_base(self) -> str: 

1100 return "friend_requests.received" 

1101 

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

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

1104 

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

1106 builder = self._body_builder(loc_context) 

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

1108 builder.user(self.befriender) 

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

1110 builder.para(".closing") 

1111 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1112 return builder.build() 

1113 

1114 @classmethod 

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

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

1117 

1118 @classmethod 

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

1120 return [ 

1121 cls( 

1122 user_name="Alice", 

1123 befriender=UserInfo.dummy_bob(), 

1124 ) 

1125 ] 

1126 

1127 

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

1129class FriendRequestAcceptedEmail(EmailBase): 

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

1131 

1132 new_friend: UserInfo 

1133 

1134 @property 

1135 def string_key_base(self) -> str: 

1136 return "friend_requests.accepted" 

1137 

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

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

1140 

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

1142 builder = self._body_builder(loc_context) 

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

1144 builder.user(self.new_friend) 

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

1146 builder.para(".closing") 

1147 return builder.build() 

1148 

1149 @classmethod 

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

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

1152 

1153 @classmethod 

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

1155 return [ 

1156 cls( 

1157 user_name="Alice", 

1158 new_friend=UserInfo.dummy_bob(), 

1159 ) 

1160 ] 

1161 

1162 

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

1164class GenderChangedEmail(EmailBase): 

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

1166 

1167 new_gender: str 

1168 

1169 @property 

1170 def string_key_base(self) -> str: 

1171 return "gender_changed" 

1172 

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

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

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

1176 return builder.build() 

1177 

1178 @classmethod 

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

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

1181 

1182 @classmethod 

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

1184 return [ 

1185 cls( 

1186 user_name="Alice", 

1187 new_gender="Male", 

1188 ) 

1189 ] 

1190 

1191 

1192class StayProposalType(Enum): 

1193 request = "request" 

1194 invitation = "invitation" 

1195 

1196 def __str__(self) -> str: 

1197 return self.value 

1198 

1199 @staticmethod 

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

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

1202 

1203 

1204def _stay_proposal_quick_decline_link(host_request: requests_pb2.HostRequest) -> str | None: 

1205 # Requests are unsolicited, so they can be quick declined, 

1206 # but invitations are solicited by a public trip, so they should get a reply. 

1207 return ( 

1208 generate_quick_decline_link(host_request) 

1209 if StayProposalType.from_proto(host_request) == StayProposalType.request 

1210 else None 

1211 ) 

1212 

1213 

1214def _add_stay_proposal_actions( 

1215 builder: EmailBlocksBuilder, 

1216 *, 

1217 proposal_type: StayProposalType, 

1218 view_link: str, 

1219 quick_decline_link: str | None, 

1220) -> None: 

1221 view_text_key = f"stays.generic.{proposal_type}.view_action" 

1222 if quick_decline_link is not None: 

1223 builder.action_pair( 

1224 primary_url=view_link, 

1225 primary_text_key=view_text_key, 

1226 secondary_url=quick_decline_link, 

1227 secondary_text_key="stays.generic.quick_decline_action", 

1228 ) 

1229 else: 

1230 builder.action(view_link, view_text_key) 

1231 

1232 

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

1234class StayProposalReceivedEmail(EmailBase): 

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

1236 

1237 proposal_type: StayProposalType 

1238 initiator: UserInfo 

1239 from_date: date 

1240 to_date: date 

1241 text: str 

1242 view_link: str 

1243 quick_decline_link: str | None 

1244 

1245 @property 

1246 def string_key_base(self) -> str: 

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

1248 

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

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

1251 

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

1253 return self.text 

1254 

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

1256 builder = self._body_builder(loc_context) 

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

1258 builder.user( 

1259 self.initiator, 

1260 "stays.generic.date_range", 

1261 { 

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

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

1264 }, 

1265 ) 

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

1267 _add_stay_proposal_actions( 

1268 builder, 

1269 proposal_type=self.proposal_type, 

1270 view_link=self.view_link, 

1271 quick_decline_link=self.quick_decline_link, 

1272 ) 

1273 builder.para(".respond_encouragement") 

1274 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1275 return builder.build() 

1276 

1277 @classmethod 

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

1279 return cls( 

1280 user_name, 

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

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

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

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

1285 text=data.text, 

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

1287 quick_decline_link=_stay_proposal_quick_decline_link(data.host_request), 

1288 ) 

1289 

1290 @classmethod 

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

1292 prototype = cls( 

1293 user_name="Alice", 

1294 proposal_type=StayProposalType.request, 

1295 initiator=UserInfo.dummy_bob(), 

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

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

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

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

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

1301 ) 

1302 return [prototype, replace(prototype, proposal_type=StayProposalType.invitation, quick_decline_link=None)] 

1303 

1304 

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

1306class StayProposalReminderEmail(EmailBase): 

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

1308 

1309 proposal_type: StayProposalType 

1310 initiator: UserInfo 

1311 from_date: date 

1312 to_date: date 

1313 view_link: str 

1314 quick_decline_link: str | None 

1315 

1316 @property 

1317 def string_key_base(self) -> str: 

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

1319 

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

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

1322 

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

1324 builder = self._body_builder(loc_context) 

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

1326 builder.user( 

1327 self.initiator, 

1328 "stays.generic.date_range", 

1329 { 

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

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

1332 }, 

1333 ) 

1334 _add_stay_proposal_actions( 

1335 builder, 

1336 proposal_type=self.proposal_type, 

1337 view_link=self.view_link, 

1338 quick_decline_link=self.quick_decline_link, 

1339 ) 

1340 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1341 return builder.build() 

1342 

1343 @classmethod 

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

1345 return cls( 

1346 user_name, 

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

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

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

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

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

1352 quick_decline_link=_stay_proposal_quick_decline_link(data.host_request), 

1353 ) 

1354 

1355 @classmethod 

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

1357 prototype = cls( 

1358 user_name="Alice", 

1359 proposal_type=StayProposalType.request, 

1360 initiator=UserInfo.dummy_bob(), 

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

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

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

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

1365 ) 

1366 return [prototype, replace(prototype, proposal_type=StayProposalType.invitation, quick_decline_link=None)] 

1367 

1368 

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

1370class StayMessageEmail(EmailBase): 

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

1372 

1373 proposal_type: StayProposalType 

1374 counterparty: UserInfo 

1375 counterparty_is_initiator: bool 

1376 from_date: date 

1377 to_date: date 

1378 text: str 

1379 view_link: str 

1380 

1381 @property 

1382 def string_key_base(self) -> str: 

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

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

1385 

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

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

1388 

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

1390 return self.text 

1391 

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

1393 builder = self._body_builder(loc_context) 

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

1395 builder.user( 

1396 self.counterparty, 

1397 "stays.generic.date_range", 

1398 { 

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

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

1401 }, 

1402 ) 

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

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

1405 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1406 return builder.build() 

1407 

1408 @classmethod 

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

1410 return cls( 

1411 user_name, 

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

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

1414 counterparty_is_initiator=data.counterparty_is_initiator, 

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

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

1417 text=data.text, 

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

1419 ) 

1420 

1421 @classmethod 

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

1423 prototype = cls( 

1424 user_name="Alice", 

1425 proposal_type=StayProposalType.request, 

1426 counterparty=UserInfo.dummy_bob(), 

1427 counterparty_is_initiator=False, 

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

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

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

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

1432 ) 

1433 return [ 

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

1435 for counterparty_is_initiator in [False, True] 

1436 for proposal_type in StayProposalType 

1437 ] 

1438 

1439 

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

1441class StayMissedMessagesEmail(EmailBase): 

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

1443 

1444 proposal_type: StayProposalType 

1445 counterparty: UserInfo 

1446 counterparty_is_initiator: bool 

1447 from_date: date 

1448 to_date: date 

1449 view_link: str 

1450 

1451 @property 

1452 def string_key_base(self) -> str: 

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

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

1455 

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

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

1458 

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

1460 builder = self._body_builder(loc_context) 

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

1462 builder.user( 

1463 self.counterparty, 

1464 "stays.generic.date_range", 

1465 { 

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

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

1468 }, 

1469 ) 

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

1471 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1472 return builder.build() 

1473 

1474 @classmethod 

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

1476 return cls( 

1477 user_name, 

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

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

1480 counterparty_is_initiator=data.counterparty_is_initiator, 

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

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

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

1484 ) 

1485 

1486 @classmethod 

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

1488 prototype = cls( 

1489 user_name="Alice", 

1490 proposal_type=StayProposalType.request, 

1491 counterparty=UserInfo.dummy_bob(), 

1492 counterparty_is_initiator=False, 

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

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

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

1496 ) 

1497 return [ 

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

1499 for counterparty_is_initiator in [False, True] 

1500 for proposal_type in StayProposalType 

1501 ] 

1502 

1503 

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

1505class StayStatusChangedEmail(EmailBase): 

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

1507 

1508 proposal_type: StayProposalType 

1509 counterparty: UserInfo 

1510 from_date: date 

1511 to_date: date 

1512 new_status: messages_pb2.HostRequestStatus.ValueType 

1513 view_link: str 

1514 

1515 @property 

1516 def string_key_base(self) -> str: 

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

1518 match self.new_status: 

1519 case messages_pb2.HOST_REQUEST_STATUS_ACCEPTED: 

1520 return f"{base_key}.accepted_by_recipient" 

1521 case messages_pb2.HOST_REQUEST_STATUS_REJECTED: 

1522 return f"{base_key}.declined_by_recipient" 

1523 case messages_pb2.HOST_REQUEST_STATUS_CONFIRMED: 

1524 return f"{base_key}.confirmed_by_initiator" 

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

1526 return f"{base_key}.cancelled_by_initiator" 

1527 case _: 

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

1529 

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

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

1532 

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

1534 builder = self._body_builder(loc_context) 

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

1536 builder.user( 

1537 self.counterparty, 

1538 "stays.generic.date_range", 

1539 { 

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

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

1542 }, 

1543 ) 

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

1545 builder.para(_do_not_reply_request_string_key, epilogue=True) 

1546 return builder.build() 

1547 

1548 @classmethod 

1549 def from_notification( 

1550 cls, 

1551 data: notification_data_pb2.StayAccept 

1552 | notification_data_pb2.StayReject 

1553 | notification_data_pb2.StayConfirm 

1554 | notification_data_pb2.StayCancel, 

1555 *, 

1556 user_name: str, 

1557 ) -> Self: 

1558 counterparty: UserInfo 

1559 new_status: messages_pb2.HostRequestStatus.ValueType 

1560 match data: 

1561 case notification_data_pb2.StayAccept(): 

1562 counterparty = UserInfo.from_proto(data.recipient) 

1563 new_status = messages_pb2.HostRequestStatus.HOST_REQUEST_STATUS_ACCEPTED 

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

1565 counterparty = UserInfo.from_proto(data.recipient) 

1566 new_status = messages_pb2.HostRequestStatus.HOST_REQUEST_STATUS_REJECTED 

1567 case notification_data_pb2.StayConfirm(): 

1568 counterparty = UserInfo.from_proto(data.initiator) 

1569 new_status = messages_pb2.HostRequestStatus.HOST_REQUEST_STATUS_CONFIRMED 

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

1571 counterparty = UserInfo.from_proto(data.initiator) 

1572 new_status = messages_pb2.HostRequestStatus.HOST_REQUEST_STATUS_CANCELLED 

1573 case _: 

1574 # Enable mypy's exhaustiveness checking 

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

1576 

1577 return cls( 

1578 user_name, 

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

1580 counterparty=counterparty, 

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

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

1583 new_status=new_status, 

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

1585 ) 

1586 

1587 @classmethod 

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

1589 prototype = cls( 

1590 user_name="Alice", 

1591 proposal_type=StayProposalType.request, 

1592 counterparty=UserInfo.dummy_bob(), 

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

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

1595 new_status=messages_pb2.HOST_REQUEST_STATUS_ACCEPTED, 

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

1597 ) 

1598 return [ 

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

1600 for new_status in [ 

1601 messages_pb2.HOST_REQUEST_STATUS_ACCEPTED, 

1602 messages_pb2.HOST_REQUEST_STATUS_REJECTED, 

1603 messages_pb2.HOST_REQUEST_STATUS_CONFIRMED, 

1604 messages_pb2.HOST_REQUEST_STATUS_CANCELLED, 

1605 ] 

1606 for proposal_type in StayProposalType 

1607 ] 

1608 

1609 

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

1611class StayReferenceReceivedEmail(EmailBase): 

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

1613 

1614 from_user: UserInfo 

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

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

1617 leave_reference_url: str 

1618 

1619 @property 

1620 def string_key_base(self) -> str: 

1621 return "references.received" 

1622 

1623 @property 

1624 def string_role_subkey(self) -> str: 

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

1626 

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

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

1629 

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

1631 return self.text 

1632 

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

1634 builder = self._body_builder(loc_context) 

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

1636 builder.user(self.from_user) 

1637 if self.text: 

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

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

1640 else: 

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

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

1643 return builder.build() 

1644 

1645 @classmethod 

1646 def from_notification( 

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

1648 ) -> Self: 

1649 return cls( 

1650 user_name=user_name, 

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

1652 text=data.text or None, 

1653 surfed=surfed, 

1654 leave_reference_url=urls.leave_reference_link( 

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

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

1657 host_request_id=str(data.host_request_id), 

1658 ), 

1659 ) 

1660 

1661 @classmethod 

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

1663 prototype = cls( 

1664 user_name="Alice", 

1665 from_user=UserInfo.dummy_bob(), 

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

1667 surfed=True, 

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

1669 ) 

1670 return [ 

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

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

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

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

1675 ] 

1676 

1677 

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

1679class StayReferenceReminderEmail(EmailBase): 

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

1681 

1682 counterparty: UserInfo 

1683 days_left: int 

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

1685 leave_reference_url: str 

1686 

1687 @property 

1688 def string_key_base(self) -> str: 

1689 return "references.reminder" 

1690 

1691 @property 

1692 def string_role_subkey(self) -> str: 

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

1694 

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

1696 return self._localize( 

1697 loc_context, 

1698 ".subject_days", 

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

1700 ) 

1701 

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

1703 builder = self._body_builder(loc_context) 

1704 builder.para( 

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

1706 ) 

1707 builder.user(self.counterparty) 

1708 builder.action( 

1709 self.leave_reference_url, 

1710 "references.write_action", 

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

1712 ) 

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

1714 builder.para(".visibility_note") 

1715 return builder.build() 

1716 

1717 @classmethod 

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

1719 return cls( 

1720 user_name=user_name, 

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

1722 days_left=data.days_left, 

1723 surfed=surfed, 

1724 leave_reference_url=urls.leave_reference_link( 

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

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

1727 host_request_id=str(data.host_request_id), 

1728 ), 

1729 ) 

1730 

1731 @classmethod 

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

1733 prototype = cls( 

1734 user_name="Alice", 

1735 counterparty=UserInfo.dummy_bob(), 

1736 days_left=7, 

1737 surfed=True, 

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

1739 ) 

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

1741 

1742 

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

1744class ModeratorNoteEmail(EmailBase): 

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

1746 

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

1748 markdown_text: str | None 

1749 

1750 @property 

1751 def string_key_base(self) -> str: 

1752 return "moderator_note" 

1753 

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

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

1756 

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

1758 builder = self._body_builder(loc_context) 

1759 if self.markdown_text: 

1760 builder.para(".purpose_with_note") 

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

1762 builder.para(".acknowledge_request") 

1763 builder.para(".reply_instructions") 

1764 else: 

1765 builder.para(".purpose") 

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

1767 # letting them use the platform. 

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

1769 return builder.build() 

1770 

1771 @classmethod 

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

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

1774 

1775 @classmethod 

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

1777 return [ 

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

1779 cls( 

1780 user_name="Alice", 

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

1782 ), 

1783 ] 

1784 

1785 

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

1787class NewBlogPostEmail(EmailBase): 

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

1789 

1790 title: str 

1791 blurb: str 

1792 url: str 

1793 

1794 @property 

1795 def string_key_base(self) -> str: 

1796 return "new_blog_post" 

1797 

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

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

1800 

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

1802 return self.blurb 

1803 

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

1805 builder = self._body_builder(loc_context) 

1806 builder.para(".purpose") 

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

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

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

1810 return builder.build() 

1811 

1812 @classmethod 

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

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

1815 

1816 @classmethod 

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

1818 return [ 

1819 cls( 

1820 user_name="Alice", 

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

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

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

1824 ) 

1825 ] 

1826 

1827 

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

1829class OnboardingReminderEmail(EmailBase): 

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

1831 

1832 initial: bool 

1833 

1834 @property 

1835 def string_key_base(self) -> str: 

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

1837 

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

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

1840 if self.initial: 

1841 self._build_body_initial(builder) 

1842 else: 

1843 self._build_body_followup(builder) 

1844 return builder.build() 

1845 

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

1847 builder.para(".welcome") 

1848 builder.para(".early_user_role") 

1849 builder.para(".complete_profile_request") 

1850 builder.para(".profile_importance") 

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

1852 builder.para(".share_request") 

1853 builder.para( 

1854 "generic.closing_lines.aapeli", 

1855 { 

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

1857 }, 

1858 ) 

1859 

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

1861 builder.para(".intro") 

1862 builder.para(".request") 

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

1864 builder.para("generic.thanks") 

1865 builder.para( 

1866 "generic.closing_lines.emily", 

1867 { 

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

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

1870 }, 

1871 ) 

1872 

1873 @classmethod 

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

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

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

1877 

1878 

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

1880class PasswordChangedEmail(EmailBase): 

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

1882 

1883 @property 

1884 def string_key_base(self) -> str: 

1885 return "password_changed" 

1886 

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

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

1889 builder.para(".purpose") 

1890 return builder.build() 

1891 

1892 @classmethod 

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

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

1895 

1896 

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

1898class PasswordResetCompletedEmail(EmailBase): 

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

1900 

1901 @property 

1902 def string_key_base(self) -> str: 

1903 return "password_reset.completed" 

1904 

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

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

1907 builder.para(".purpose") 

1908 return builder.build() 

1909 

1910 @classmethod 

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

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

1913 

1914 

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

1916class PasswordResetStartedEmail(EmailBase): 

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

1918 

1919 password_reset_link: str 

1920 

1921 @property 

1922 def string_key_base(self) -> str: 

1923 return "password_reset.started" 

1924 

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

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

1927 builder.para(".purpose") 

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

1929 return builder.build() 

1930 

1931 @classmethod 

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

1933 return cls( 

1934 user_name=user_name, 

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

1936 ) 

1937 

1938 @classmethod 

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

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

1941 

1942 

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

1944class PhoneNumberChangeEmail(EmailBase): 

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

1946 

1947 new_phone_number: str 

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

1949 

1950 @property 

1951 def string_key_base(self) -> str: 

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

1953 

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

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

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

1957 return builder.build() 

1958 

1959 @classmethod 

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

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

1962 

1963 @classmethod 

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

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

1966 

1967 @classmethod 

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

1969 prototype = cls( 

1970 user_name="Alice", 

1971 new_phone_number="+12223334444", 

1972 completed=False, 

1973 ) 

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

1975 

1976 

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

1978class PostalVerificationFailedEmail(EmailBase): 

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

1980 

1981 reason: notification_data_pb2.PostalVerificationFailReason.ValueType 

1982 

1983 @property 

1984 def string_key_base(self) -> str: 

1985 return "postal_verification.failed" 

1986 

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

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

1989 match self.reason: 

1990 case notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_CODE_EXPIRED: 

1991 purpose_string_key = ".purpose.code_expired" 

1992 case notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_TOO_MANY_ATTEMPTS: 

1993 purpose_string_key = ".purpose.too_many_attempts" 

1994 case _: 

1995 purpose_string_key = ".purpose.default" 

1996 builder.para(purpose_string_key) 

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

1998 return builder.build() 

1999 

2000 @classmethod 

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

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

2003 

2004 @classmethod 

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

2006 prototype = cls( 

2007 user_name="Alice", 

2008 reason=notification_data_pb2.POSTAL_VERIFICATION_FAIL_REASON_CODE_EXPIRED, 

2009 ) 

2010 return [ 

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

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

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

2014 ] 

2015 

2016 

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

2018class PostalVerificationPostcardSentEmail(EmailBase): 

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

2020 

2021 city: str 

2022 country: str 

2023 

2024 @property 

2025 def string_key_base(self) -> str: 

2026 return "postal_verification.postcard_sent" 

2027 

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

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

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

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

2032 return builder.build() 

2033 

2034 @classmethod 

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

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

2037 

2038 @classmethod 

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

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

2041 

2042 

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

2044class PostalVerificationSucceededEmail(EmailBase): 

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

2046 

2047 @property 

2048 def string_key_base(self) -> str: 

2049 return "postal_verification.succeeded" 

2050 

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

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

2053 builder.para(".purpose") 

2054 return builder.build() 

2055 

2056 @classmethod 

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

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

2059 

2060 

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

2062class SignupVerifyEmail(EmailBase): 

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

2064 

2065 verify_url: str 

2066 

2067 @property 

2068 def string_key_base(self) -> str: 

2069 return "signup.verify" 

2070 

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

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

2073 

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

2075 builder = self._body_builder(loc_context) 

2076 builder.para(".thanks") 

2077 builder.para(".instructions") 

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

2079 builder.para("signup.closing") 

2080 return builder.build() 

2081 

2082 @classmethod 

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

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

2085 

2086 

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

2088class SignupContinueEmail(EmailBase): 

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

2090 

2091 continue_url: str 

2092 

2093 @property 

2094 def string_key_base(self) -> str: 

2095 return "signup.continue" 

2096 

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

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

2099 

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

2101 builder = self._body_builder(loc_context) 

2102 builder.para(".purpose") 

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

2104 builder.para("signup.closing") 

2105 builder.para(".ignore_if_unexpected") 

2106 return builder.build() 

2107 

2108 @classmethod 

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

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

2111 

2112 

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

2114class StrongVerificationFailedEmail(EmailBase): 

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

2116 

2117 reason: notification_data_pb2.SVFailReason.ValueType 

2118 

2119 @property 

2120 def string_key_base(self) -> str: 

2121 return "strong_verification.failed" 

2122 

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

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

2125 match self.reason: 

2126 case notification_data_pb2.SV_FAIL_REASON_WRONG_BIRTHDATE_OR_GENDER: 

2127 purpose_string_key = ".purpose.wrong_birthdate_or_gender" 

2128 case notification_data_pb2.SV_FAIL_REASON_NOT_A_PASSPORT: 

2129 purpose_string_key = ".purpose.not_a_passport" 

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

2131 purpose_string_key = ".purpose.duplicate" 

2132 case _: 

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

2134 builder.para(purpose_string_key) 

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

2136 return builder.build() 

2137 

2138 @classmethod 

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

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

2141 

2142 @classmethod 

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

2144 prototype = cls( 

2145 user_name="Alice", 

2146 reason=notification_data_pb2.SV_FAIL_REASON_NOT_A_PASSPORT, 

2147 ) 

2148 return [ 

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

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

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

2152 ] 

2153 

2154 

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

2156class StrongVerificationSucceededEmail(EmailBase): 

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

2158 

2159 @property 

2160 def string_key_base(self) -> str: 

2161 return "strong_verification.succeeded" 

2162 

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

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

2165 builder.para(".purpose") 

2166 builder.para(".thanks_message") 

2167 builder.para(".cost_explanation") 

2168 builder.para(".donation_request") 

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

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

2171 return builder.build() 

2172 

2173 @classmethod 

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

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

2176 

2177 

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

2179class ThreadReplyEmail(EmailBase): 

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

2181 

2182 author: UserInfo 

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

2184 markdown_text: str 

2185 view_link: str 

2186 

2187 @property 

2188 def string_key_base(self) -> str: 

2189 return "thread_reply" 

2190 

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

2192 return self._localize( 

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

2194 ) 

2195 

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

2197 return markdown_to_plaintext(self.markdown_text) 

2198 

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

2200 builder = self._body_builder(loc_context) 

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

2202 builder.user(self.author) 

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

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

2205 return builder.build() 

2206 

2207 @classmethod 

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

2209 parent = data.WhichOneof("reply_parent") 

2210 if parent == "event": 

2211 parent_context = data.event.title 

2212 view_link = urls.event_link( 

2213 occurrence_id=data.event.event_id, slug=data.event.slug, comment_id=data.reply.thread_id 

2214 ) 

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

2216 parent_context = data.discussion.title 

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

2218 else: 

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

2220 return cls( 

2221 user_name=user_name, 

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

2223 parent_context=parent_context, 

2224 markdown_text=data.reply.content, 

2225 view_link=view_link, 

2226 ) 

2227 

2228 @classmethod 

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

2230 return [ 

2231 cls( 

2232 user_name="Alice", 

2233 author=UserInfo.dummy_bob(), 

2234 parent_context="Best hiking trails near Berlin", 

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

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

2237 ) 

2238 ] 

2239 

2240 

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

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