Coverage for app/backend/src/couchers/helpers/references.py: 100%
10 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-23 04:10 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-23 04:10 +0000
1from typing import Any
3from sqlalchemy import select
4from sqlalchemy.orm import aliased
5from sqlalchemy.sql import Select, exists, func, or_
7from couchers.models import HostRequest, Reference, ReferenceType
10def where_references_not_hidden_by_reciprocity[T: tuple[Any, ...]](statement: Select[T]) -> Select[T]:
11 """
12 Filters out references that are still hidden by the reciprocal-reference rule.
14 A host/surf reference stays hidden until either the recipient has written their
15 reciprocal reference or the 2-week window to write one has closed; friend
16 references are always visible.
18 Apply this to any query that selects from Reference. Both the reference list
19 (ListReferences) and the reference count (get_num_references) must use it,
20 otherwise the count includes references the list hides, leaking the existence
21 of a still-hidden reference.
22 """
23 other_reference = aliased(Reference)
24 reciprocal_written = exists(
25 select(other_reference.id)
26 .where(other_reference.host_request_id == Reference.host_request_id)
27 .where(other_reference.from_user_id == Reference.to_user_id)
28 .where(other_reference.reference_type != ReferenceType.friend)
29 )
30 window_closed = exists(
31 select(HostRequest.conversation_id)
32 .where(HostRequest.conversation_id == Reference.host_request_id)
33 .where(HostRequest.end_time_to_write_reference < func.now())
34 )
35 return statement.where(
36 or_(
37 Reference.reference_type == ReferenceType.friend,
38 reciprocal_written,
39 window_closed,
40 )
41 )