:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(review-hog): route the repository and project settings views through the facade (#115707)
Julian Bezbb1106474334
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex e2edee511451..ed83afed4d5f 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -211,6 +211,9 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.replay_vision.backend.api.vision_alerts.VisionAlertViewSet","products.review_hog.backend.presentation.views.blind_spots.ReviewBlindSpotsConfigViewSet","products.review_hog.backend.presentation.views.perspectives.ReviewPerspectiveConfigViewSet",+ "products.review_hog.backend.presentation.views.repositories.ReviewInstallationClaimViewSet",+ "products.review_hog.backend.presentation.views.repositories.ReviewRepositoryChoiceViewSet",+ "products.review_hog.backend.presentation.views.repositories.ReviewRepositoryViewSet","products.review_hog.backend.presentation.views.resolution.ReviewResolutionConfigViewSet","products.review_hog.backend.presentation.views.reviews.ReviewRecentReviewsViewSet","products.review_hog.backend.presentation.views.validators.ReviewValidatorConfigViewSet",diff --git a/products/review_hog/backend/automatic_review_rules.py b/products/review_hog/backend/automatic_review_rules.pyindex b3e4795b4c53..66985dcbe3ae 100644--- a/products/review_hog/backend/automatic_review_rules.py+++ b/products/review_hog/backend/automatic_review_rules.py@@ -22,6 +22,8 @@ from django.db import modelsfrom posthog.dataclasses import frozen+from products.review_hog.backend.facade.contracts import AutomaticReviewDecision+from products.review_hog.backend.facade.enums import AutomaticReviewReason, ReviewUserRepositoryChoiceModefrom products.review_hog.backend.models import (AutomaticFlashFor,ReviewProjectSettings,@@ -33,25 +35,6 @@ from products.review_hog.backend.models import (from products.review_hog.backend.ownership import RepositoryReffrom products.review_hog.backend.preferences import DefaultReviewMode--class AutomaticReviewReason(models.TextChoices):- OWN_REPOSITORY_CHOICE = "own_repository_choice", "Own choice for this repository"- OWN_DEFAULT = "own_default", "Own default"- REPOSITORY_EVERYONE = "repository_everyone", "The repository exception reviews everyone"- REPOSITORY_EXCEPTED = "repository_excepted", "Excepted by the repository exception"- REPOSITORY_LISTED = "repository_listed", "Listed by the repository exception"- REPOSITORY_NOT_LISTED = "repository_not_listed", "Not listed by the repository exception"- REPOSITORY_OPT_IN = "repository_opt_in", "The repository exception reviews only people who opt in"- PROJECT_EVERYONE = "project_everyone", "The project reviews everyone"- PROJECT_EXCEPTED = "project_excepted", "Excepted by the project"- PROJECT_LISTED = "project_listed", "Listed by the project"- PROJECT_NOT_LISTED = "project_not_listed", "Not listed by the project"- PROJECT_OPT_IN = "project_opt_in", "The project reviews only people who opt in"- BOT_REVIEWED = "bot_reviewed", "The project reviews bot pull requests"- BOT_SKIPPED = "bot_skipped", "The project does not review bot pull requests"- NOT_IN_PROJECT = "not_in_project", "This project does not review the repository"--_RULE_REASONS: dict[tuple[bool, str], AutomaticReviewReason] = {(True, "everyone"): AutomaticReviewReason.REPOSITORY_EVERYONE,(True, "excepted"): AutomaticReviewReason.REPOSITORY_EXCEPTED,@@ -71,19 +54,13 @@ def is_bot_login(github_login: str) -> bool:return github_login.lower().endswith("[bot]")-@frozen-class AutomaticReviewDecision:- flash: bool- reason: AutomaticReviewReason--@frozenclass AuthorChoice:# None when the GitHub author maps to no PostHog user.user_id: int | Noneis_bot: booldefault_mode: DefaultReviewMode- repository_choice: ReviewUserRepositoryChoice.Mode | None+ repository_choice: ReviewUserRepositoryChoiceMode | None@frozendiff --git a/products/review_hog/backend/facade/api.py b/products/review_hog/backend/facade/api.pyindex 262f8cd3b974..be5488720af3 100644--- a/products/review_hog/backend/facade/api.py+++ b/products/review_hog/backend/facade/api.py@@ -5,19 +5,62 @@ module: they go in their own facade submodule."""import logging-from collections.abc import Mapping+from collections.abc import Mapping, Sequence+from uuid import UUIDfrom posthog.models.scoping.manager import resolve_effective_team_id+from posthog.models.team import Team+from posthog.models.user import User+from products.review_hog.backend.activity_logging import installation_account_name+from products.review_hog.backend.automatic_review_rules import load_peoplefrom products.review_hog.backend.facade.contracts import (+ UNSET,+ RepositoryNotFoundError,+ ReviewInstallationClaimInfo,+ ReviewInstallationInfo,ReviewProjectPreferenceDefaults,+ ReviewProjectSettingsInfo,+ ReviewRepositoryChoiceInfo,+ ReviewRepositoryChoiceOutcome,+ ReviewRepositoryException,+ ReviewRepositoryOverviewEntry,+ ReviewRepositoryOverviewPage,+ ReviewRepositoryPersonEntry,+ ReviewRepositorySettings,+ ReviewRepositoryWriteOutcome,ReviewSkill,ReviewSkillChoice,ReviewUserPreferences,+ ReviewUserRef,+ Unset,)-from products.review_hog.backend.facade.enums import ReviewSkillKind-from products.review_hog.backend.models import ReviewUserSettings+from products.review_hog.backend.facade.enums import (+ AutomaticFlashFor,+ RepositoryOverviewView,+ ReviewInstallationClaimScope,+ ReviewProjectSettingsBotPullRequests,+ ReviewRepositoryPersonKind,+ ReviewSkillKind,+ ReviewUserRepositoryChoiceMode,+)+from products.review_hog.backend.models import (+ ReviewInstallationClaim,+ ReviewProjectSettings,+ ReviewRepository,+ ReviewRepositoryPerson,+ ReviewUserRepositoryChoice,+ ReviewUserSettings,+)+from products.review_hog.backend.ownership import RepositoryReffrom products.review_hog.backend.preferences import ReviewPreferences+from products.review_hog.backend.repository_settings import (+ InstallationSummary,+ OverviewEntry,+ ProjectRepositories,+ RepositoryChoices,+ RepositoryOverview,+)from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_authoringfrom products.review_hog.backend.skill_configs import ReviewSkillMenufrom products.stamphog.backend.facade.api import has_reviewable_repo_config@@ -106,3 +149,304 @@ def update_review_user_preferences(team_id: int, user_id: int, changes: Mapping[# but not the create kwargs, and mismatched ids mean a never-matching get plus 500s on re-read.team_id = resolve_effective_team_id(team_id)return _user_preferences(team_id, ReviewUserSettings.save_preference_changes(team_id, user_id, changes))+++# Repository settings. Each function takes the root project id: the views resolve it once, because+# their permission checks need it too.+++def _user_ref(user: User | None) -> ReviewUserRef | None:+ if user is None:+ return None+ return ReviewUserRef(+ id=user.id,+ uuid=user.uuid,+ distinct_id=user.distinct_id,+ first_name=user.first_name,+ last_name=user.last_name,+ email=user.email,+ is_email_verified=user.is_email_verified,+ hedgehog_config=user.hedgehog_config,+ role_at_organization=user.role_at_organization,+ )+++def _person_entry(person: ReviewRepositoryPerson) -> ReviewRepositoryPersonEntry:+ user = _user_ref(person.user)+ assert user is not None+ return ReviewRepositoryPersonEntry(id=person.id, user=user, kind=ReviewRepositoryPersonKind(person.kind))+++def _person_entries(people: Sequence[ReviewRepositoryPerson]) -> list[ReviewRepositoryPersonEntry]:+ return [_person_entry(person) for person in people]+++def _repository_settings(+ row: ReviewRepository, people: Mapping[UUID | None, Sequence[ReviewRepositoryPerson]]+) -> ReviewRepositorySettings:+ return ReviewRepositorySettings(+ id=row.id,+ installation_id=row.installation_id,+ github_repo_id=row.github_repo_id,+ full_name=row.full_name,+ selected=row.selected,+ flash_for=AutomaticFlashFor(row.flash_for) if row.flash_for is not None else None,+ people=_person_entries(people.get(row.id, [])),+ created_by=_user_ref(row.created_by),+ created_at=row.created_at,+ )+++def _claim_info(claim: ReviewInstallationClaim) -> ReviewInstallationClaimInfo:+ return ReviewInstallationClaimInfo(+ id=claim.id,+ installation_id=claim.installation_id,+ scope=ReviewInstallationClaimScope(claim.scope),+ account_name=installation_account_name(claim.installation_id),+ created_by=_user_ref(claim.created_by),+ created_at=claim.created_at,+ )+++def _installation_info(summary: InstallationSummary) -> ReviewInstallationInfo:+ return ReviewInstallationInfo(+ installation_id=summary.installation_id,+ account_name=summary.account_name,+ connected_by=_user_ref(summary.connected_by),+ claim_id=summary.claim.id if summary.claim is not None else None,+ scope=ReviewInstallationClaimScope(summary.claim.scope) if summary.claim is not None else None,+ all_taken_by=summary.all_taken_by,+ )+++def _choice_info(choice: ReviewUserRepositoryChoice) -> ReviewRepositoryChoiceInfo:+ return ReviewRepositoryChoiceInfo(+ id=choice.id,+ installation_id=choice.installation_id,+ github_repo_id=choice.github_repo_id,+ full_name=choice.full_name,+ mode=ReviewUserRepositoryChoiceMode(choice.mode),+ )+++def _overview_entry(entry: OverviewEntry) -> ReviewRepositoryOverviewEntry:+ repository = entry.repository+ exception = None+ if repository is not None and repository.flash_for is not None:+ exception = ReviewRepositoryException(+ flash_for=AutomaticFlashFor(repository.flash_for), people=_person_entries(entry.exception_people)+ )+ return ReviewRepositoryOverviewEntry(+ full_name=entry.full_name,+ github_repo_id=entry.github_repo_id,+ owner=entry.owner,+ owner_project=entry.owner_project,+ in_project=entry.in_project,+ selected=entry.selected,+ repository_id=repository.id if repository is not None else None,+ exception=exception,+ my_choice=ReviewUserRepositoryChoiceMode(entry.my_choice.mode) if entry.my_choice is not None else None,+ my_choice_id=entry.my_choice.id if entry.my_choice is not None else None,+ my_result=entry.my_result,+ inherited_result=entry.inherited_result,+ repository_result=entry.repository_result,+ )+++def _project_repositories(team_id: int, user_id: int) -> ProjectRepositories:+ return ProjectRepositories(Team.objects.get(id=team_id), User.objects.get(id=user_id))+++def _repository_choices(team_id: int, user_id: int) -> RepositoryChoices:+ return RepositoryChoices(Team.objects.get(id=team_id), User.objects.get(id=user_id))+++def list_review_repositories(team_id: int, user_id: int) -> list[ReviewRepositorySettings]:+ """The repositories the project has settings for, oldest first."""+ rows = _project_repositories(team_id, user_id).repositories()+ people = load_people(team_id, [row.id for row in rows])+ return [_repository_settings(row, people) for row in rows]+++def get_review_repository(team_id: int, user_id: int, repository_id: UUID) -> ReviewRepositorySettings | None:+ row = _project_repositories(team_id, user_id).repository(repository_id)+ if row is None:+ return None+ return _repository_settings(row, load_people(team_id, [row.id]))+++def save_review_repository(+ team_id: int,+ user_id: int,+ *,+ installation_id: str,+ full_name: str,+ github_repo_id: int | None,+ selected: bool | None,+ flash_for: AutomaticFlashFor | None | Unset = UNSET,+) -> ReviewRepositoryWriteOutcome:+ """Include or remove a repository, or set or clear its exception. Omitted fields keep their value.++ Raises `OwnershipConflict` when another project holds the repository, and `RepositorySettingsError`+ when the rules forbid the write.+ """+ ref = RepositoryRef(installation_id=installation_id, github_repo_id=github_repo_id, full_name=full_name)+ result = _project_repositories(team_id, user_id).save_repository(ref, selected=selected, flash_for=flash_for)+ repository = None+ if result.repository is not None:+ repository = _repository_settings(result.repository, load_people(team_id, [result.repository.id]))+ return ReviewRepositoryWriteOutcome(repository=repository, taken_from=result.taken_from)+++def delete_review_repository(team_id: int, user_id: int, repository_id: UUID) -> bool:+ """Remove the repository's settings and its lists. False when the project has no such repository."""+ return _project_repositories(team_id, user_id).delete_repository(repository_id)+++def add_review_repository_person(+ team_id: int, user_id: int, repository_id: UUID | None, *, person_user_id: int, kind: ReviewRepositoryPersonKind+) -> bool:+ """Add a person to a list of a repository exception, or of the project rule when `repository_id` is None.++ True when added, False when the person was already on the list. Raises `PersonNotActiveMemberError`, and+ `RepositoryNotFoundError` when the project has no such repository.+ """+ repositories = _project_repositories(team_id, user_id)+ repository = None+ if repository_id is not None:+ repository = repositories.repository(repository_id)+ if repository is None:+ raise RepositoryNotFoundError(f"The project has no repository settings {repository_id}.")+ repositories.check_active_member(person_user_id)+ if repository is None:+ # The row exists first, so the activity log has an item to attach the list change to.+ ReviewProjectSettings.ensure(team_id)+ return repositories.add_person(repository, user_id=person_user_id, kind=kind)+++def remove_review_repository_person(team_id: int, user_id: int, repository_id: UUID | None, person_id: UUID) -> bool:+ """Remove one entry from a list of a repository exception, or of the project rule when `repository_id` is None.++ False when the list has no such entry.+ """+ return _project_repositories(team_id, user_id).remove_person(repository_id, person_id)+++def list_review_installation_claims(team_id: int, user_id: int) -> list[ReviewInstallationClaimInfo]:+ return [_claim_info(claim) for claim in _project_repositories(team_id, user_id).claims()]+++def get_review_installation_claim(team_id: int, user_id: int, claim_id: UUID) -> ReviewInstallationClaimInfo | None:+ claim = _project_repositories(team_id, user_id).claim(claim_id)+ return _claim_info(claim) if claim is not None else None+++def create_review_installation_claim(+ team_id: int, user_id: int, installation_id: str, scope: ReviewInstallationClaimScope+) -> ReviewInstallationClaimInfo:+ """Raises `OwnershipConflict` when another project takes all repositories, and `RepositorySettingsError`."""+ return _claim_info(_project_repositories(team_id, user_id).create_claim(installation_id, scope))+++def update_review_installation_claim(+ team_id: int, user_id: int, claim_id: UUID, scope: ReviewInstallationClaimScope+) -> ReviewInstallationClaimInfo | None:+ """None when the project has no such claim. Raises `OwnershipConflict`."""+ repositories = _project_repositories(team_id, user_id)+ claim = repositories.claim(claim_id)+ if claim is None:+ return None+ return _claim_info(repositories.update_claim(claim, scope))+++def delete_review_installation_claim(team_id: int, user_id: int, claim_id: UUID) -> bool:+ """Remove the claim and the project's repository settings there. False when there is no such claim."""+ repositories = _project_repositories(team_id, user_id)+ claim = repositories.claim(claim_id)+ if claim is None:+ return False+ repositories.delete_claim(claim)+ return True+++def list_review_repository_choices(team_id: int, user_id: int) -> list[ReviewRepositoryChoiceInfo]:+ """The user's own repository choices in the project, by repository name."""+ return [_choice_info(choice) for choice in _repository_choices(team_id, user_id).choices()]+++def save_review_repository_choice(+ team_id: int,+ user_id: int,+ *,+ installation_id: str,+ full_name: str,+ github_repo_id: int | None,+ mode: ReviewUserRepositoryChoiceMode,+) -> ReviewRepositoryChoiceOutcome:+ """Set the user's own choice for one repository. A value equal to the inherited one clears it.++ Raises `RepositorySettingsError` when the project does not review the repository.+ """+ ref = RepositoryRef(installation_id=installation_id, github_repo_id=github_repo_id, full_name=full_name)+ choice, decision = _repository_choices(team_id, user_id).save(ref, mode)+ return ReviewRepositoryChoiceOutcome(+ choice=_choice_info(choice) if choice is not None else None, my_result=decision+ )+++def delete_review_repository_choice(team_id: int, user_id: int, choice_id: UUID) -> bool:+ """Clear one of the user's own choices. False when the user has no such choice."""+ return _repository_choices(team_id, user_id).delete(choice_id)+++def get_review_project_settings(team_id: int, user_id: int) -> ReviewProjectSettingsInfo:+ """The project rule, its Full review defaults and people lists, and the connected installations."""+ row = ReviewProjectSettings.load(team_id)+ defaults = row.defaults+ return ReviewProjectSettingsInfo(+ flash_for=AutomaticFlashFor(row.flash_for),+ bot_prs=ReviewProjectSettingsBotPullRequests(row.bot_prs),+ urgency_threshold=defaults.urgency_threshold,+ celebrate_clean_reviews=defaults.celebrate_clean_reviews,+ people=_person_entries(load_people(team_id, [])[None]),+ installations=[+ _installation_info(summary) for summary in _project_repositories(team_id, user_id).installations()+ ],+ )+++def update_review_project_settings(team_id: int, changes: Mapping[str, object]) -> None:+ """Apply `changes` to the project rule. Omitted keys keep their value.++ Raises `InvalidPreference` for an invalid Full review default.+ """+ ReviewProjectSettings.save_changes(team_id, changes)+++def get_review_repository_overview(+ team_id: int,+ user_id: int,+ installation_id: str,+ *,+ search: str,+ view: RepositoryOverviewView,+ offset: int,+ limit: int,+) -> ReviewRepositoryOverviewPage:+ """One page of the repositories the installation can see, with this project's settings and the user's.++ Raises `RepositorySettingsError` when the project has no connection for the installation, and+ `GitHubRepositoryListError` when GitHub does not return the repository list.+ """+ repositories = _project_repositories(team_id, user_id)+ listed = repositories.installation_repositories(installation_id, search)+ overview = RepositoryOverview(repositories.team, repositories.user, installation_id, listed)+ entries, total = overview.page(listed, view=view, offset=offset, limit=limit)+ claim = repositories.claim_for(installation_id)+ return ReviewRepositoryOverviewPage(+ installation_id=installation_id,+ claim_scope=ReviewInstallationClaimScope(claim.scope) if claim is not None else None,+ entries=[_overview_entry(entry) for entry in entries],+ total=total,+ my_choices_unlike_default=overview.choices_unlike_default(),+ )diff --git a/products/review_hog/backend/facade/contracts.py b/products/review_hog/backend/facade/contracts.pyindex 300d700824c0..d84252113e87 100644--- a/products/review_hog/backend/facade/contracts.py+++ b/products/review_hog/backend/facade/contracts.py@@ -1,15 +1,24 @@"""What PostHog Review hands to other products and to its own views. No Django here."""-from collections.abc import Mapping+from collections.abc import Mapping, Sequence+from datetime import datetime+from uuid import UUIDfrom posthog.dataclasses import frozenfrom products.review_hog.backend.facade.enums import (+ AutomaticFlashFor,+ AutomaticReviewReason,DefaultReviewMode,PreferenceSource,PRReviewRequestStatus,+ RepositoryOwnerKind,ResolveSkipReason,+ ReviewInstallationClaimScope,+ ReviewProjectSettingsBotPullRequests,+ ReviewRepositoryPersonKind,ReviewRequestRefusal,+ ReviewUserRepositoryChoiceMode,UrgencyThreshold,)@@ -105,3 +114,192 @@ class ReviewUserPreferences:sources: Mapping[str, PreferenceSource]project_defaults: ReviewProjectPreferenceDefaultsstamphog_connected: bool+++class InvalidPreference(ValueError):+ def __init__(self, key: str, message: str) -> None:+ super().__init__(message)+ self.key = key+++class Unset:+ """Marks a field the request did not mention, because None is a valid value."""+++UNSET = Unset()+++class RepositorySettingsError(Exception):+ """A write the rules do not allow. The API answers 400 with the message."""+++class GitHubRepositoryListError(Exception):+ """GitHub did not return the repository list of an installation. The API answers 502."""+++class RepositoryNotFoundError(LookupError):+ """The project has no settings for the repository."""+++class PersonNotActiveMemberError(Exception):+ """The user to add to a people list is not an active member of the project's organization."""+++@frozen+class ProjectRef:+ """Another project, named only inside its own organization."""++ team_id: int+ name: str | None++ @property+ def label(self) -> str:+ return f"the {self.name} project" if self.name else "a project in another organization"+++class OwnershipConflict(Exception):+ """Another project already holds what this write asks for. The API answers 409."""++ def __init__(self, message: str, project: ProjectRef | None) -> None:+ super().__init__(message)+ self.project = project+++@frozen+class AutomaticReviewDecision:+ flash: bool+ reason: AutomaticReviewReason+++@frozen+class ReviewUserRef:+ """The fields of a user that the core `UserBasicSerializer` reads."""++ id: int+ uuid: UUID+ distinct_id: str | None+ first_name: str+ last_name: str+ email: str+ is_email_verified: bool | None+ hedgehog_config: Mapping[str, object] | None+ role_at_organization: str | None+++@frozen+class ReviewRepositoryPersonEntry:+ """A person on one of the two lists of the project rule or of a repository exception."""++ id: UUID+ user: ReviewUserRef+ kind: ReviewRepositoryPersonKind+++@frozen+class ReviewRepositorySettings:+ """A repository this project has settings for, with the people on its exception's lists."""++ id: UUID+ installation_id: str+ github_repo_id: int | None+ full_name: str+ selected: bool+ flash_for: AutomaticFlashFor | None+ people: Sequence[ReviewRepositoryPersonEntry]+ created_by: ReviewUserRef | None+ created_at: datetime+++@frozen+class ReviewRepositoryWriteOutcome:+ # None when the write left nothing to store, so the row was deleted.+ repository: ReviewRepositorySettings | None+ # The project that took all repositories of the installation, when this write took one from it.+ taken_from: ProjectRef | None+++@frozen+class ReviewInstallationClaimInfo:+ id: UUID+ installation_id: str+ scope: ReviewInstallationClaimScope+ account_name: str+ created_by: ReviewUserRef | None+ created_at: datetime+++@frozen+class ReviewInstallationInfo:+ """A GitHub installation connected to the project, and which of its repositories the project reviews."""++ installation_id: str+ account_name: str+ connected_by: ReviewUserRef | None+ claim_id: UUID | None+ scope: ReviewInstallationClaimScope | None+ all_taken_by: ProjectRef | None+++@frozen+class ReviewRepositoryChoiceInfo:+ """A user's own automatic review choice for their pull requests in one repository."""++ id: UUID+ installation_id: str+ github_repo_id: int | None+ full_name: str+ mode: ReviewUserRepositoryChoiceMode+++@frozen+class ReviewRepositoryChoiceOutcome:+ # None when the value equals the inherited one, so no choice is stored.+ choice: ReviewRepositoryChoiceInfo | None+ my_result: AutomaticReviewDecision+++@frozen+class ReviewProjectSettingsInfo:+ """The project rule, its Full review defaults, its people lists, and the connected installations."""++ flash_for: AutomaticFlashFor+ bot_prs: ReviewProjectSettingsBotPullRequests+ urgency_threshold: UrgencyThreshold+ celebrate_clean_reviews: bool+ people: Sequence[ReviewRepositoryPersonEntry]+ installations: Sequence[ReviewInstallationInfo]+++@frozen+class ReviewRepositoryException:+ flash_for: AutomaticFlashFor+ people: Sequence[ReviewRepositoryPersonEntry]+++@frozen+class ReviewRepositoryOverviewEntry:+ """One repository of an installation, joined with this project's settings and the viewer's."""++ full_name: str+ github_repo_id: int | None+ owner: RepositoryOwnerKind+ owner_project: ProjectRef | None+ in_project: bool+ selected: bool+ repository_id: UUID | None+ exception: ReviewRepositoryException | None+ my_choice: ReviewUserRepositoryChoiceMode | None+ my_choice_id: UUID | None+ my_result: AutomaticReviewDecision+ inherited_result: AutomaticReviewDecision+ repository_result: AutomaticReviewDecision+++@frozen+class ReviewRepositoryOverviewPage:+ installation_id: str+ claim_scope: ReviewInstallationClaimScope | None+ entries: Sequence[ReviewRepositoryOverviewEntry]+ # Entries that match the search and the view, on every page.+ total: int+ my_choices_unlike_default: intdiff --git a/products/review_hog/backend/facade/enums.py b/products/review_hog/backend/facade/enums.pyindex b4275b01df4e..8ec5e6f37091 100644--- a/products/review_hog/backend/facade/enums.py+++ b/products/review_hog/backend/facade/enums.py@@ -62,3 +62,62 @@ class ReviewSkillKind(StrEnum):VALIDATION = "validation"BLIND_SPOTS = "blind_spots"RESOLUTION = "resolution"+++class AutomaticFlashFor(LabeledStrEnum):+ """Who gets automatic Flash reviews under a project rule or a repository exception."""++ EVERYONE = "everyone", "Automatic Flash for everyone"+ LISTED = "listed", "Automatic Flash for these people"+ OFF = "off", "Automatic Flash opt-in only"+++class ReviewProjectSettingsBotPullRequests(LabeledStrEnum):+ SKIP = "skip", "Not reviewed"+ RUN = "run", "Automatic Flash"+++class ReviewInstallationClaimScope(LabeledStrEnum):+ ALL = "all", "All repositories"+ SELECTED = "selected", "Only selected repositories"+++class ReviewRepositoryPersonKind(LabeledStrEnum):+ LISTED = "listed", "Listed"+ EXCEPTED = "excepted", "Excepted"+++class ReviewUserRepositoryChoiceMode(LabeledStrEnum):+ FLASH = "flash", "Flash"+ OFF = "off", "Off"+++class AutomaticReviewReason(LabeledStrEnum):+ OWN_REPOSITORY_CHOICE = "own_repository_choice", "Own choice for this repository"+ OWN_DEFAULT = "own_default", "Own default"+ REPOSITORY_EVERYONE = "repository_everyone", "The repository exception reviews everyone"+ REPOSITORY_EXCEPTED = "repository_excepted", "Excepted by the repository exception"+ REPOSITORY_LISTED = "repository_listed", "Listed by the repository exception"+ REPOSITORY_NOT_LISTED = "repository_not_listed", "Not listed by the repository exception"+ REPOSITORY_OPT_IN = "repository_opt_in", "The repository exception reviews only people who opt in"+ PROJECT_EVERYONE = "project_everyone", "The project reviews everyone"+ PROJECT_EXCEPTED = "project_excepted", "Excepted by the project"+ PROJECT_LISTED = "project_listed", "Listed by the project"+ PROJECT_NOT_LISTED = "project_not_listed", "Not listed by the project"+ PROJECT_OPT_IN = "project_opt_in", "The project reviews only people who opt in"+ BOT_REVIEWED = "bot_reviewed", "The project reviews bot pull requests"+ BOT_SKIPPED = "bot_skipped", "The project does not review bot pull requests"+ NOT_IN_PROJECT = "not_in_project", "This project does not review the repository"+++class RepositoryOwnerKind(LabeledStrEnum):+ THIS_PROJECT = "this_project", "This project"+ OTHER_PROJECT = "other_project", "Another project"+ NONE = "none", "No project"+++class RepositoryOverviewView(LabeledStrEnum):+ ALL = "all", "All repositories"+ IN_PROJECT = "in_project", "In this project"+ EXCEPTIONS = "exceptions", "With exceptions"+ MINE = "mine", "My choices"diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.pyindex 4197c7e9c8e5..0e401e96a567 100644--- a/products/review_hog/backend/models.py+++ b/products/review_hog/backend/models.py@@ -8,6 +8,13 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDModel+from products.review_hog.backend.facade.enums import (+ AutomaticFlashFor,+ ReviewInstallationClaimScope,+ ReviewProjectSettingsBotPullRequests,+ ReviewRepositoryPersonKind,+ ReviewUserRepositoryChoiceMode,+)from products.review_hog.backend.preferences import ReviewPreferences, ReviewProjectDefaults, UrgencyThresholdfrom products.review_hog.backend.reviewer.artefact_content import (ArtefactContentValidationError,@@ -392,14 +399,6 @@ class ReviewSkillConfig(UUIDModel, TeamScopedRootMixin):]-class AutomaticFlashFor(models.TextChoices):- """Who gets automatic Flash reviews under a project rule or a repository exception."""-- EVERYONE = "everyone", "Automatic Flash for everyone"- LISTED = "listed", "Automatic Flash for these people"- OFF = "off", "Automatic Flash opt-in only"--class ReviewProjectSettings(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):"""A project's ReviewHog rule: who gets automatic Flash, bot pull requests, and Full defaults.@@ -409,21 +408,19 @@ class ReviewProjectSettings(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):repository."""- class BotPullRequests(models.TextChoices):- SKIP = "skip", "Not reviewed"- RUN = "run", "Automatic Flash"+ BotPullRequests = ReviewProjectSettingsBotPullRequeststeam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)flash_for = models.CharField(max_length=20,choices=AutomaticFlashFor.choices,- default=AutomaticFlashFor.OFF,+ default=AutomaticFlashFor.OFF.value,db_default=AutomaticFlashFor.OFF.value,)bot_prs = models.CharField(max_length=10,choices=BotPullRequests.choices,- default=BotPullRequests.SKIP,+ default=BotPullRequests.SKIP.value,db_default=BotPullRequests.SKIP.value,)# Project defaults for the Full review preferences (see `preferences.PROJECT_DEFAULT_FIELDS`).@@ -442,6 +439,29 @@ class ReviewProjectSettings(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):row = cls.objects.for_team(team_id).first()return row if row is not None else cls(team_id=team_id)+ @classmethod+ def ensure(cls, team_id: int) -> "ReviewProjectSettings":+ """The project's row, created with the defaults when none exists."""+ row, _created = cls.objects.for_team(team_id, canonical=True).get_or_create(team_id=team_id)+ return row++ @classmethod+ def save_changes(cls, team_id: int, changes: Mapping[str, object]) -> None:+ """Apply `changes` to the project rule and its Full review defaults. Omitted keys keep their value.++ Raises `InvalidPreference` for an invalid Full review default.+ """+ with transaction.atomic():+ row = cls.objects.for_team(team_id).select_for_update().get(id=cls.ensure(team_id).id)+ for field in ("flash_for", "bot_prs"):+ if field in changes:+ setattr(row, field, changes[field])+ preference_changes = {+ key: changes[key] for key in ("urgency_threshold", "celebrate_clean_reviews") if key in changes+ }+ row.preferences = row.defaults.with_changes(preference_changes)+ row.save()+@propertydef defaults(self) -> ReviewProjectDefaults:return ReviewProjectDefaults.resolve(self.preferences)@@ -551,9 +571,7 @@ class ReviewInstallationClaim(ModelActivityMixin, UUIDModel, TeamScopedRootMixinactivity_logging_on_delete = True- class Scope(models.TextChoices):- ALL = "all", "All repositories"- SELECTED = "selected", "Only selected repositories"+ Scope = ReviewInstallationClaimScopeteam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)# The GitHub App installation id, as `Integration.integration_id` stores it.@@ -628,9 +646,7 @@ class ReviewRepositoryPerson(ModelActivityMixin, UUIDModel, TeamScopedRootMixin)activity_logging_on_delete = True- class Kind(models.TextChoices):- LISTED = "listed", "Listed"- EXCEPTED = "excepted", "Excepted"+ Kind = ReviewRepositoryPersonKindteam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)repository = models.ForeignKey(ReviewRepository, on_delete=models.CASCADE, related_name="+", null=True, blank=True)@@ -661,9 +677,7 @@ class ReviewUserRepositoryChoice(UUIDModel, TeamScopedRootMixin):stored but has no effect. No row means the user's default applies, so there is no "follow" value."""- class Mode(models.TextChoices):- FLASH = "flash", "Flash"- OFF = "off", "Off"+ Mode = ReviewUserRepositoryChoiceModeteam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)diff --git a/products/review_hog/backend/preferences.py b/products/review_hog/backend/preferences.pyindex 924941f7720f..e984f7d3d7b9 100644--- a/products/review_hog/backend/preferences.py+++ b/products/review_hog/backend/preferences.py@@ -14,17 +14,12 @@ from typing import castfrom posthog.dataclasses import frozen+from products.review_hog.backend.facade.contracts import InvalidPreferencefrom products.review_hog.backend.facade.enums import DefaultReviewMode, PreferenceSource, UrgencyThresholdPreferenceValue = str | bool-class InvalidPreference(ValueError):- def __init__(self, key: str, message: str) -> None:- super().__init__(message)- self.key = key--@frozenclass PreferenceField:key: strdiff --git a/products/review_hog/backend/presentation/views/project_settings.py b/products/review_hog/backend/presentation/views/project_settings.pyindex 2bc5967266ff..b590c8d02fdf 100644--- a/products/review_hog/backend/presentation/views/project_settings.py+++ b/products/review_hog/backend/presentation/views/project_settings.py@@ -1,7 +1,5 @@-import logging-from typing import Any, cast--from django.db import transaction+from typing import Any+from uuid import UUIDfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import serializers, status, viewsets@@ -9,20 +7,32 @@ from rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.egress.limiter.policies import Priority-from posthog.models.integration import GitHubIntegration, Integration-from posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermission-from products.review_hog.backend.automatic_review_rules import load_people-from products.review_hog.backend.models import (+from products.review_hog.backend.facade.api import (+ add_review_repository_person,+ get_review_project_settings,+ get_review_repository_overview,+ remove_review_repository_person,+ update_review_project_settings,+)+from products.review_hog.backend.facade.contracts import (+ GitHubRepositoryListError,+ InvalidPreference,+ PersonNotActiveMemberError,+ RepositorySettingsError,+ ReviewRepositoryOverviewEntry,+)+from products.review_hog.backend.facade.enums import (AutomaticFlashFor,- ReviewInstallationClaim,- ReviewProjectSettings,- ReviewRepositoryPerson,- ReviewUserRepositoryChoice,+ RepositoryOverviewView,+ RepositoryOwnerKind,+ ReviewInstallationClaimScope,+ ReviewProjectSettingsBotPullRequests,+ ReviewRepositoryPersonKind,+ ReviewUserRepositoryChoiceMode,+ UrgencyThreshold,)-from products.review_hog.backend.preferences import InvalidPreference, UrgencyThresholdfrom products.review_hog.backend.presentation.views.repositories import (UUID_PATH_PATTERN,AutomaticReviewDecisionSerializer,@@ -33,19 +43,13 @@ from products.review_hog.backend.presentation.views.repositories import (ReviewProjectRefSerializer,ReviewRepositoryPersonRequestSerializer,ReviewRepositoryPersonSerializer,- check_active_member,+ bad_request_response,decision_data,installation_data,+ no_such_list_entry_response,+ not_active_member_error,project_ref_data,)-from products.review_hog.backend.repository_settings import (- OverviewEntry,- RepositoryOverview,- RepositoryOverviewView,- RepositoryOwnerKind,-)--logger = logging.getLogger(__name__)class ReviewProjectSettingsSerializer(serializers.Serializer):@@ -57,7 +61,7 @@ class ReviewProjectSettingsSerializer(serializers.Serializer):"default). A repository exception or a person's own choice wins over it.",)bot_prs = serializers.ChoiceField(- choices=ReviewProjectSettings.BotPullRequests.choices,+ choices=ReviewProjectSettingsBotPullRequests.choices,required=False,help_text="Pull requests from bots, and from authors who are not project members, in every repository ""this project reviews: 'skip' (not reviewed, the default) or 'run' (an automatic Standard review that runs as the "@@ -134,7 +138,7 @@ class ReviewRepositoryOverviewEntrySerializer(serializers.Serializer):allow_null=True, help_text="This project's repository exception. Null when the repository follows the project.")my_choice = serializers.ChoiceField(- choices=ReviewUserRepositoryChoice.Mode.choices,+ choices=ReviewUserRepositoryChoiceMode.choices,allow_null=True,help_text="The requesting user's own choice for this repository: 'flash', 'off', or null.",)@@ -155,7 +159,7 @@ class ReviewRepositoryOverviewEntrySerializer(serializers.Serializer):class ReviewRepositoryOverviewSerializer(serializers.Serializer):installation_id = serializers.CharField(help_text="The listed GitHub App installation.")claim_scope = serializers.ChoiceField(- choices=ReviewInstallationClaim.Scope.choices,+ choices=ReviewInstallationClaimScope.choices,allow_null=True,help_text="This project's claim on the installation: 'all', 'selected', or null.",)@@ -169,15 +173,14 @@ class ReviewRepositoryOverviewSerializer(serializers.Serializer):)-def _entry_data(entry: OverviewEntry) -> dict[str, Any]:- repository = entry.repository+def _entry_data(entry: ReviewRepositoryOverviewEntry) -> dict[str, Any]:exception = None- if repository is not None and repository.flash_for is not None:+ if entry.exception is not None:exception = {- "flash_for": repository.flash_for,+ "flash_for": entry.exception.flash_for,# Model rows: the response serializer renders them, and a pre-rendered row would reach the# nested user serializer as a dict.- "people": list(entry.exception_people),+ "people": list(entry.exception.people),}return {"full_name": entry.full_name,@@ -186,10 +189,10 @@ def _entry_data(entry: OverviewEntry) -> dict[str, Any]:"owner_project": project_ref_data(entry.owner_project),"in_project": entry.in_project,"selected": entry.selected,- "repository_id": repository.id if repository is not None else None,+ "repository_id": entry.repository_id,"exception": exception,- "my_choice": entry.my_choice.mode if entry.my_choice is not None else None,- "my_choice_id": entry.my_choice.id if entry.my_choice is not None else None,+ "my_choice": entry.my_choice,+ "my_choice_id": entry.my_choice_id,"my_result": decision_data(entry.my_result),"inherited_result": decision_data(entry.inherited_result),"repository_result": decision_data(entry.repository_result),@@ -206,30 +209,21 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generiscope_object = "review_hog"permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]posthog_feature_flag = "review-hog"- # Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.- queryset = ReviewProjectSettings.objects.unscoped()serializer_class = ReviewProjectSettingsSerializerdef _settings_response(self, response_status: int = status.HTTP_200_OK) -> Response:- team_id = self.effective_team_id- row = ReviewProjectSettings.load(team_id)- defaults = row.defaults+ settings = get_review_project_settings(self.effective_team_id, self.acting_user_id)data = {- "flash_for": row.flash_for,- "bot_prs": row.bot_prs,- "urgency_threshold": defaults.urgency_threshold,- "celebrate_clean_reviews": defaults.celebrate_clean_reviews,- "people": load_people(team_id, [])[None],- "installations": [installation_data(summary) for summary in self.project_repositories().installations()],+ "flash_for": settings.flash_for,+ "bot_prs": settings.bot_prs,+ "urgency_threshold": settings.urgency_threshold,+ "celebrate_clean_reviews": settings.celebrate_clean_reviews,+ "people": settings.people,+ "installations": [installation_data(installation) for installation in settings.installations],"can_edit": self.is_effective_team_admin(),}return Response(ReviewProjectSettingsSerializer(data).data, status=response_status)- def _settings_row(self) -> ReviewProjectSettings:- team_id = self.effective_team_id- row, _created = ReviewProjectSettings.objects.for_team(team_id, canonical=True).get_or_create(team_id=team_id)- return row-@extend_schema(methods=["GET"],responses={200: OpenApiResponse(response=ReviewProjectSettingsSerializer)},@@ -253,22 +247,10 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generiif request.method == "PATCH":serializer = ReviewProjectSettingsSerializer(data=request.data, partial=True)serializer.is_valid(raise_exception=True)- data = serializer.validated_data- with transaction.atomic():- row = (- ReviewProjectSettings.objects.for_team(self.effective_team_id)- .select_for_update()- .get(id=self._settings_row().id)- )- for field in ("flash_for", "bot_prs"):- if field in data:- setattr(row, field, data[field])- changes = {key: data[key] for key in ("urgency_threshold", "celebrate_clean_reviews") if key in data}- try:- row.preferences = row.defaults.with_changes(changes)- except InvalidPreference as error:- raise serializers.ValidationError({error.key: str(error)})- row.save()+ try:+ update_review_project_settings(self.effective_team_id, serializer.validated_data)+ except InvalidPreference as error:+ raise serializers.ValidationError({error.key: str(error)})return self._settings_response()@extend_schema(@@ -285,11 +267,16 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generidef add_project_person(self, request: Request, **kwargs: Any) -> Response:serializer = ReviewRepositoryPersonRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)- user_id: int = serializer.validated_data["user_id"]- check_active_member(self.team, user_id)- # The row exists first, so the activity log has an item to attach the list change to.- self._settings_row()- created = self.project_repositories().add_person(None, user_id=user_id, kind=serializer.validated_data["kind"])+ try:+ created = add_review_repository_person(+ self.effective_team_id,+ self.acting_user_id,+ None,+ person_user_id=serializer.validated_data["user_id"],+ kind=ReviewRepositoryPersonKind(serializer.validated_data["kind"]),+ )+ except PersonNotActiveMemberError as error:+ raise not_active_member_error(error)return self._settings_response(status.HTTP_201_CREATED if created else status.HTTP_200_OK)@extend_schema(@@ -308,16 +295,8 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generirequired_scopes=["review_hog:write"],)def remove_project_person(self, request: Request, person_id: str, **kwargs: Any) -> Response:- person = (- ReviewRepositoryPerson.objects.for_team(self.effective_team_id, canonical=True)- .filter(repository__isnull=True, id=person_id)- .first()- )- if person is None:- return Response(- {"error": "No such list entry.", "conflicting_project": None}, status=status.HTTP_404_NOT_FOUND- )- person.delete()+ if not remove_review_repository_person(self.effective_team_id, self.acting_user_id, None, UUID(person_id)):+ return no_such_list_entry_response()return self._settings_response()@extend_schema(@@ -336,49 +315,29 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generidef repository_overview(self, request: Request, **kwargs: Any) -> Response:query = ReviewRepositoryOverviewQuerySerializer(data=request.query_params)query.is_valid(raise_exception=True)- installation_id: str = query.validated_data["installation_id"]- integration = Integration.objects.filter(- team_id=self.effective_team_id, kind="github", integration_id=installation_id- ).first()- if integration is None:- return Response(- {"error": "This project has no GitHub connection for that installation.", "conflicting_project": None},- status=status.HTTP_400_BAD_REQUEST,- )+ offset: int = query.validated_data["offset"]try:- repositories = GitHubIntegration(- integration, source="review_hog", priority=Priority.NORMAL- ).list_all_cached_repositories()- except Exception:- # The list refreshes from GitHub when the cache is cold, and GitHub can fail or rate limit.- logger.warning("review_hog_repository_overview_list_failed", exc_info=True)- return Response(- {"error": "GitHub did not return the repository list. Try again shortly.", "conflicting_project": None},- status=status.HTTP_502_BAD_GATEWAY,+ page = get_review_repository_overview(+ self.effective_team_id,+ self.acting_user_id,+ query.validated_data["installation_id"],+ search=query.validated_data["search"],+ view=RepositoryOverviewView(query.validated_data["view"]),+ offset=offset,+ limit=query.validated_data["limit"],)- search = query.validated_data["search"].strip().casefold()- if search:- repositories = [- repository for repository in repositories if search in str(repository["full_name"]).casefold()- ]- overview = RepositoryOverview(self.effective_team, cast(User, request.user), installation_id, repositories)- offset: int = query.validated_data["offset"]- entries, total = overview.page(- repositories, view=query.validated_data["view"], offset=offset, limit=query.validated_data["limit"]- )- has_more = offset + len(entries) < total- claim = (- ReviewInstallationClaim.objects.for_team(self.effective_team_id)- .filter(installation_id=installation_id)- .first()- )+ except RepositorySettingsError as error:+ return bad_request_response(error)+ except GitHubRepositoryListError as error:+ return Response({"error": str(error), "conflicting_project": None}, status=status.HTTP_502_BAD_GATEWAY)+ has_more = offset + len(page.entries) < page.totaldata = {- "installation_id": installation_id,- "claim_scope": claim.scope if claim is not None else None,- "results": [_entry_data(entry) for entry in entries],- "total": total,+ "installation_id": page.installation_id,+ "claim_scope": page.claim_scope,+ "results": [_entry_data(entry) for entry in page.entries],+ "total": page.total,"has_more": has_more,- "next_offset": offset + len(entries) if has_more else None,- "my_choices_unlike_default": overview.choices_unlike_default(),+ "next_offset": offset + len(page.entries) if has_more else None,+ "my_choices_unlike_default": page.my_choices_unlike_default,}return Response(ReviewRepositoryOverviewSerializer(data).data)diff --git a/products/review_hog/backend/presentation/views/repositories.py b/products/review_hog/backend/presentation/views/repositories.pyindex b2c41a8458cf..060f85b605ef 100644--- a/products/review_hog/backend/presentation/views/repositories.py+++ b/products/review_hog/backend/presentation/views/repositories.py@@ -1,8 +1,8 @@import refrom typing import Any, cast+from uuid import UUID-from django.db.models import QuerySet-+from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import (OpenApiParameter,OpenApiResponse,@@ -10,9 +10,9 @@ from drf_spectacular.utils import (extend_schema_field,extend_schema_view,)-from rest_framework import mixins, serializers, status, viewsets+from rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action-from rest_framework.exceptions import ValidationError+from rest_framework.exceptions import NotFound, ValidationErrorfrom rest_framework.permissions import SAFE_METHODS, BasePermissionfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -22,33 +22,43 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.scoping.manager import resolve_effective_team_idfrom posthog.models.team import Team-from posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids-from products.review_hog.backend.activity_logging import installation_account_name-from products.review_hog.backend.automatic_review_rules import (- AutomaticReviewDecision,- AutomaticReviewReason,- load_people,+from products.review_hog.backend.facade.api import (+ add_review_repository_person,+ create_review_installation_claim,+ delete_review_installation_claim,+ delete_review_repository,+ delete_review_repository_choice,+ get_review_installation_claim,+ get_review_repository,+ list_review_installation_claims,+ list_review_repositories,+ list_review_repository_choices,+ remove_review_repository_person,+ save_review_repository,+ save_review_repository_choice,+ update_review_installation_claim,)-from products.review_hog.backend.models import (- AutomaticFlashFor,- ReviewInstallationClaim,- ReviewRepository,- ReviewRepositoryPerson,- ReviewUserRepositoryChoice,-)-from products.review_hog.backend.ownership import RepositoryRef-from products.review_hog.backend.repository_settings import (+from products.review_hog.backend.facade.contracts import (UNSET,- InstallationSummary,+ AutomaticReviewDecision,OwnershipConflict,+ PersonNotActiveMemberError,ProjectRef,- ProjectRepositories,- RepositoryChoices,+ RepositoryNotFoundError,RepositorySettingsError,+ ReviewInstallationInfo,+ ReviewRepositorySettings,Unset,)+from products.review_hog.backend.facade.enums import (+ AutomaticFlashFor,+ AutomaticReviewReason,+ ReviewInstallationClaimScope,+ ReviewRepositoryPersonKind,+ ReviewUserRepositoryChoiceMode,+)# GitHub owners and repository names use letters, digits, '-', '_' and '.'._FULL_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")@@ -79,12 +89,29 @@ def bad_request_response(error: RepositorySettingsError) -> Response:return Response({"error": str(error), "conflicting_project": None}, status=status.HTTP_400_BAD_REQUEST)-def check_active_member(team: Team, user_id: int) -> None:- is_member = OrganizationMembership.objects.filter(- organization_id=team.organization_id, user_id=user_id, user__is_active=True- ).exists()- if not is_member:- raise ValidationError({"user_id": "This user is not an active member of the organization."})+def not_active_member_error(error: PersonNotActiveMemberError) -> ValidationError:+ return ValidationError({"user_id": str(error)})+++def no_such_list_entry_response() -> Response:+ return Response({"error": "No such list entry.", "conflicting_project": None}, status=status.HTTP_404_NOT_FOUND)+++def path_uuid(value: str) -> UUID:+ """The UUID of a detail URL. Any other value names no object, so the answer is 404."""+ try:+ return UUID(value)+ except ValueError:+ raise NotFound()+++def uuid_path_parameter(object_name: str) -> OpenApiParameter:+ return OpenApiParameter(+ "id",+ OpenApiTypes.UUID,+ OpenApiParameter.PATH,+ description=f"A UUID string identifying this {object_name}.",+ )def decision_data(decision: AutomaticReviewDecision) -> dict[str, Any]:@@ -107,25 +134,21 @@ class ReviewHogSettingsErrorSerializer(serializers.Serializer):)-class ReviewRepositoryPersonSerializer(serializers.ModelSerializer):+class ReviewRepositoryPersonSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Id of this list entry. Use it to remove the person.")user = UserBasicSerializer(read_only=True, help_text="The project member on the list.")kind = serializers.ChoiceField(- choices=ReviewRepositoryPerson.Kind.choices,+ choices=ReviewRepositoryPersonKind.choices,read_only=True,help_text="Which list: 'listed' (gets automatic reviews when the rule reviews only listed people) or ""'excepted' (skipped when the rule reviews everyone).",)- class Meta:- model = ReviewRepositoryPerson- fields = ["id", "user", "kind"]-class ReviewRepositoryPersonRequestSerializer(serializers.Serializer):user_id = serializers.IntegerField(help_text="Id of the project member to add. Must be an active member.")kind = serializers.ChoiceField(- choices=ReviewRepositoryPerson.Kind.choices,+ choices=ReviewRepositoryPersonKind.choices,help_text="Which list to add the person to: 'listed' or 'excepted'.",)@@ -142,7 +165,7 @@ class AutomaticReviewDecisionSerializer(serializers.Serializer):)-class ReviewRepositorySerializer(serializers.ModelSerializer):+class ReviewRepositorySerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Id of the repository entry.")installation_id = serializers.CharField(read_only=True, help_text="The GitHub App installation that sees it.")github_repo_id = serializers.IntegerField(@@ -167,26 +190,9 @@ class ReviewRepositorySerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="Who added the repository.")created_at = serializers.DateTimeField(read_only=True, help_text="When the repository was added.")- class Meta:- model = ReviewRepository- fields = [- "id",- "installation_id",- "github_repo_id",- "full_name",- "selected",- "flash_for",- "people",- "created_by",- "created_at",- ]-@extend_schema_field(ReviewRepositoryPersonSerializer(many=True))- def get_people(self, instance: ReviewRepository) -> list[dict]:- people = self.context.get("people")- if people is None:- people = load_people(instance.team_id, [instance.id])- return [dict(ReviewRepositoryPersonSerializer(person).data) for person in people.get(instance.id, [])]+ def get_people(self, instance: ReviewRepositorySettings) -> list[dict]:+ return [dict(ReviewRepositoryPersonSerializer(person).data) for person in instance.people]class ReviewRepositoryWriteSerializer(serializers.Serializer):@@ -241,7 +247,7 @@ class ReviewInstallationSerializer(serializers.Serializer):allow_null=True, help_text="Id of this project's claim. Null when the project reviews nothing there.")scope = serializers.ChoiceField(- choices=ReviewInstallationClaim.Scope.choices,+ choices=ReviewInstallationClaimScope.choices,allow_null=True,help_text="Which repositories this project reviews: 'all' (every repository no other project selected, ""including future ones), 'selected' (only the selected ones), or null (none).",@@ -252,22 +258,22 @@ class ReviewInstallationSerializer(serializers.Serializer):)-def installation_data(summary: InstallationSummary) -> dict[str, Any]:+def installation_data(installation: ReviewInstallationInfo) -> dict[str, Any]:return {- "installation_id": summary.installation_id,- "account_name": summary.account_name,- "connected_by": summary.connected_by,- "claim_id": summary.claim.id if summary.claim is not None else None,- "scope": summary.claim.scope if summary.claim is not None else None,- "all_taken_by_project": project_ref_data(summary.all_taken_by),+ "installation_id": installation.installation_id,+ "account_name": installation.account_name,+ "connected_by": installation.connected_by,+ "claim_id": installation.claim_id,+ "scope": installation.scope,+ "all_taken_by_project": project_ref_data(installation.all_taken_by),}-class ReviewInstallationClaimSerializer(serializers.ModelSerializer):+class ReviewInstallationClaimSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Id of the claim.")installation_id = serializers.CharField(read_only=True, help_text="The GitHub App installation id.")scope = serializers.ChoiceField(- choices=ReviewInstallationClaim.Scope.choices,+ choices=ReviewInstallationClaimScope.choices,read_only=True,help_text="'all' (every repository no other project selected, including future ones) or 'selected'.",)@@ -277,19 +283,15 @@ class ReviewInstallationClaimSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="Who made the claim.")created_at = serializers.DateTimeField(read_only=True, help_text="When the claim was made.")- class Meta:- model = ReviewInstallationClaim- fields = ["id", "installation_id", "scope", "account_name", "created_by", "created_at"]-@extend_schema_field(serializers.CharField())- def get_account_name(self, instance: ReviewInstallationClaim) -> str:- return installation_account_name(instance.installation_id)+ def get_account_name(self, instance: Any) -> str:+ return instance.account_nameclass ReviewInstallationClaimCreateSerializer(serializers.Serializer):installation_id = serializers.CharField(max_length=64, help_text="The GitHub App installation id.")scope = serializers.ChoiceField(- choices=ReviewInstallationClaim.Scope.choices,+ choices=ReviewInstallationClaimScope.choices,help_text="'all' reviews every repository of the installation that no other project selected. ""At most one project per installation can choose it. 'selected' reviews only selected repositories.",)@@ -297,34 +299,30 @@ class ReviewInstallationClaimCreateSerializer(serializers.Serializer):class ReviewInstallationClaimUpdateSerializer(serializers.Serializer):scope = serializers.ChoiceField(- choices=ReviewInstallationClaim.Scope.choices,+ choices=ReviewInstallationClaimScope.choices,help_text="'all' or 'selected'. Switching to 'selected' removes the exceptions of the repositories that ""leave the project.",)-class ReviewRepositoryChoiceSerializer(serializers.ModelSerializer):+class ReviewRepositoryChoiceSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Id of the choice. Use it to clear the choice.")installation_id = serializers.CharField(read_only=True, help_text="The GitHub App installation.")github_repo_id = serializers.IntegerField(read_only=True, allow_null=True, help_text="GitHub's repository id.")full_name = serializers.CharField(read_only=True, help_text="GitHub repository in 'owner/name' form.")mode = serializers.ChoiceField(- choices=ReviewUserRepositoryChoice.Mode.choices,+ choices=ReviewUserRepositoryChoiceMode.choices,read_only=True,help_text="'flash' or 'off' for the user's own pull requests in this repository.",)- class Meta:- model = ReviewUserRepositoryChoice- fields = ["id", "installation_id", "github_repo_id", "full_name", "mode"]-class ReviewRepositoryChoiceWriteSerializer(serializers.Serializer):installation_id = serializers.CharField(max_length=64, help_text="The GitHub App installation.")full_name = serializers.CharField(max_length=200, help_text="GitHub repository in 'owner/name' form.")github_repo_id = serializers.IntegerField(required=False, min_value=1, help_text="GitHub's repository id.")mode = serializers.ChoiceField(- choices=ReviewUserRepositoryChoice.Mode.choices,+ choices=ReviewUserRepositoryChoiceMode.choices,help_text="The requesting user's own automatic review for their pull requests in this repository: ""'flash' or 'off'. A value equal to what the user inherits clears the choice instead.",)@@ -354,22 +352,22 @@ class ReviewHogProjectViewSetMixin(TeamAndOrgViewSetMixin):team_id = self.effective_team_idreturn self.team if self.team.id == team_id else Team.objects.get(id=team_id)+ @property+ def acting_user_id(self) -> int:+ return cast(int, self.request.user.id)+def is_effective_team_admin(self) -> bool:level = self.user_permissions.team(self.effective_team).effective_membership_levelreturn level is not None and level >= OrganizationMembership.Level.ADMIN- def project_repositories(self) -> ProjectRepositories:- return ProjectRepositories(self.effective_team, cast(User, self.request.user))--class EffectiveTeamStrictManagementPermission(BasePermission):- """Members read, admins write, both checked on the root project that the writes change.+class EffectiveTeamMemberPermission(BasePermission):+ """Members only, checked on the root project that holds the rows.- An environment URL resolves to its parent project, and a user can be admin of the environment- but only a member of the parent.+ An environment URL resolves to its parent project, and the default checks cover only the URL project."""- message = "You don't have sufficient permissions in the project."+ message = "You don't have access to the project."def has_permission(self, request: Request, view: Any) -> bool:if not isinstance(view, ReviewHogProjectViewSetMixin):@@ -379,26 +377,32 @@ class EffectiveTeamStrictManagementPermission(BasePermission):scoped_teams = get_authenticator_scoped_team_ids(request.successful_authenticator)if scoped_teams is not None and view.effective_team_id not in scoped_teams:return False- if request.method in SAFE_METHODS:- return view.user_permissions.team(view.effective_team).effective_membership_level is not None- return view.is_effective_team_admin()+ return view.user_permissions.team(view.effective_team).effective_membership_level is not None+++class EffectiveTeamStrictManagementPermission(EffectiveTeamMemberPermission):+ """Members read, admins write, both checked on the root project that the writes change.++ A user can be admin of the environment but only a member of the parent.+ """++ message = "You don't have sufficient permissions in the project."++ def has_permission(self, request: Request, view: Any) -> bool:+ if not super().has_permission(request, view):+ return False+ return request.method in SAFE_METHODS or view.is_effective_team_admin()-# `list` keeps the inherited method, because overriding it marks the viewset as a custom list for-# the pagination contract check. Its schema comes from the serializer and the class docstring.@extend_schema_view(destroy=extend_schema(summary="Remove a repository's settings",description="Remove the repository from this project and clear its exception and lists. With an 'all ""repositories' claim the repository stays in the project and follows the project rule.",+ parameters=[uuid_path_parameter("review repository")],),)-class ReviewRepositoryViewSet(- ReviewHogProjectViewSetMixin,- mixins.ListModelMixin,- mixins.DestroyModelMixin,- viewsets.GenericViewSet,-):+class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericViewSet):"""The repositories this project has settings for: selected repositories and repository exceptions.Project members can read them. Only project admins can change them, and every change goes to the@@ -408,27 +412,29 @@ class ReviewRepositoryViewSet(scope_object = "review_hog"permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]posthog_feature_flag = "review-hog"- # Unscoped only to satisfy the router/introspection; `safely_get_queryset` scopes every read.- queryset = ReviewRepository.objects.unscoped()serializer_class = ReviewRepositorySerializerpagination_class = None- def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:- return (- ReviewRepository.objects.for_team(self.effective_team_id, canonical=True)- .select_related("created_by")- .order_by("created_at")- )+ def _repository_or_404(self) -> ReviewRepositorySettings:+ repository_id = path_uuid(self.kwargs["pk"])+ repository = get_review_repository(self.effective_team_id, self.acting_user_id, repository_id)+ if repository is None:+ raise NotFound()+ return repository- def get_serializer_context(self) -> dict:- context = super().get_serializer_context()- team_id = self.effective_team_id- repository_ids = ReviewRepository.objects.for_team(team_id, canonical=True).values_list("id", flat=True)- context["people"] = load_people(team_id, repository_ids)- return context+ def _repository_response(self, repository_id: UUID, response_status: int = status.HTTP_200_OK) -> Response:+ repository = get_review_repository(self.effective_team_id, self.acting_user_id, repository_id)+ return Response(ReviewRepositorySerializer(repository).data, status=response_status)- def _repository_response(self, repository: ReviewRepository, response_status: int = status.HTTP_200_OK) -> Response:- return Response(self.get_serializer(repository).data, status=response_status)+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ repositories = list_review_repositories(self.effective_team_id, self.acting_user_id)+ return Response(ReviewRepositorySerializer(repositories, many=True).data)++ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ repository_id = path_uuid(self.kwargs["pk"])+ if not delete_review_repository(self.effective_team_id, self.acting_user_id, repository_id):+ raise NotFound()+ return Response(status=status.HTTP_204_NO_CONTENT)@extend_schema(request=ReviewRepositoryWriteSerializer,@@ -449,27 +455,30 @@ class ReviewRepositoryViewSet(serializer = ReviewRepositoryWriteSerializer(data=request.data)serializer.is_valid(raise_exception=True)data = serializer.validated_data- ref = RepositoryRef(- installation_id=data["installation_id"],- github_repo_id=data.get("github_repo_id"),- full_name=data["full_name"],- )- flash_for: str | None | Unset = data["flash_for"] if "flash_for" in data else UNSET+ flash_for: AutomaticFlashFor | None | Unset = UNSET+ if "flash_for" in data:+ flash_for = AutomaticFlashFor(data["flash_for"]) if data["flash_for"] is not None else Nonetry:- result = self.project_repositories().save_repository(- ref, selected=data.get("selected"), flash_for=flash_for+ result = save_review_repository(+ self.effective_team_id,+ self.acting_user_id,+ installation_id=data["installation_id"],+ full_name=data["full_name"],+ github_repo_id=data.get("github_repo_id"),+ selected=data.get("selected"),+ flash_for=flash_for,)except OwnershipConflict as error:return conflict_response(error)except RepositorySettingsError as error:return bad_request_response(error)response = ReviewRepositoryWriteResponseSerializer(- {"repository": result.repository, "taken_from_project": project_ref_data(result.taken_from)},- context=self.get_serializer_context(),+ {"repository": result.repository, "taken_from_project": project_ref_data(result.taken_from)})return Response(response.data)@extend_schema(+ parameters=[uuid_path_parameter("review repository")],request=ReviewRepositoryPersonRequestSerializer,responses={200: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was already on it."),@@ -481,18 +490,28 @@ class ReviewRepositoryViewSet()@action(detail=True, methods=["POST"], url_path="people", required_scopes=["review_hog:write"])def add_person(self, request: Request, **kwargs: Any) -> Response:- repository = self.get_object()+ repository = self._repository_or_404()serializer = ReviewRepositoryPersonRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)- user_id: int = serializer.validated_data["user_id"]- check_active_member(self.team, user_id)- created = self.project_repositories().add_person(- repository, user_id=user_id, kind=serializer.validated_data["kind"]- )- return self._repository_response(repository, status.HTTP_201_CREATED if created else status.HTTP_200_OK)+ try:+ created = add_review_repository_person(+ self.effective_team_id,+ self.acting_user_id,+ repository.id,+ person_user_id=serializer.validated_data["user_id"],+ kind=ReviewRepositoryPersonKind(serializer.validated_data["kind"]),+ )+ except PersonNotActiveMemberError as error:+ raise not_active_member_error(error)+ except RepositoryNotFoundError:+ raise NotFound()+ return self._repository_response(repository.id, status.HTTP_201_CREATED if created else status.HTTP_200_OK)@extend_schema(- parameters=[OpenApiParameter("person_id", str, OpenApiParameter.PATH, description="Id of the list entry.")],+ parameters=[+ uuid_path_parameter("review repository"),+ OpenApiParameter("person_id", str, OpenApiParameter.PATH, description="Id of the list entry."),+ ],responses={200: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was removed."),404: OpenApiResponse(response=ReviewHogSettingsErrorSerializer, description="No such list entry."),@@ -507,25 +526,15 @@ class ReviewRepositoryViewSet(required_scopes=["review_hog:write"],)def remove_person(self, request: Request, person_id: str, **kwargs: Any) -> Response:- repository = self.get_object()- person = (- ReviewRepositoryPerson.objects.for_team(repository.team_id, canonical=True)- .filter(repository=repository, id=person_id)- .first()- )- if person is None:- return Response(- {"error": "No such list entry.", "conflicting_project": None}, status=status.HTTP_404_NOT_FOUND- )- person.delete()- return self._repository_response(repository)+ repository = self._repository_or_404()+ if not remove_review_repository_person(+ self.effective_team_id, self.acting_user_id, repository.id, UUID(person_id)+ ):+ return no_such_list_entry_response()+ return self._repository_response(repository.id)-class ReviewInstallationClaimViewSet(- ReviewHogProjectViewSetMixin,- mixins.ListModelMixin,- viewsets.GenericViewSet,-):+class ReviewInstallationClaimViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericViewSet):"""Which repositories of each connected GitHub installation this project reviews.Project members can read the claims. Only project admins can change them, and every change goes@@ -536,16 +545,18 @@ class ReviewInstallationClaimViewSet(scope_object = "review_hog"permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]posthog_feature_flag = "review-hog"- queryset = ReviewInstallationClaim.objects.unscoped()serializer_class = ReviewInstallationClaimSerializerpagination_class = None- def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:- return (- ReviewInstallationClaim.objects.for_team(self.effective_team_id, canonical=True)- .select_related("created_by")- .order_by("created_at")- )+ def _claim_id_or_404(self) -> UUID:+ claim_id = path_uuid(self.kwargs["pk"])+ if get_review_installation_claim(self.effective_team_id, self.acting_user_id, claim_id) is None:+ raise NotFound()+ return claim_id++ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ claims = list_review_installation_claims(self.effective_team_id, self.acting_user_id)+ return Response(ReviewInstallationClaimSerializer(claims, many=True).data)@extend_schema(request=ReviewInstallationClaimCreateSerializer,@@ -564,16 +575,20 @@ class ReviewInstallationClaimViewSet(serializer = ReviewInstallationClaimCreateSerializer(data=request.data)serializer.is_valid(raise_exception=True)try:- claim = self.project_repositories().create_claim(- serializer.validated_data["installation_id"], serializer.validated_data["scope"]+ claim = create_review_installation_claim(+ self.effective_team_id,+ self.acting_user_id,+ serializer.validated_data["installation_id"],+ ReviewInstallationClaimScope(serializer.validated_data["scope"]),)except OwnershipConflict as error:return conflict_response(error)except RepositorySettingsError as error:return bad_request_response(error)- return Response(self.get_serializer(claim).data, status=status.HTTP_201_CREATED)+ return Response(ReviewInstallationClaimSerializer(claim).data, status=status.HTTP_201_CREATED)@extend_schema(+ parameters=[uuid_path_parameter("review installation claim")],request=ReviewInstallationClaimUpdateSerializer,responses={200: OpenApiResponse(response=ReviewInstallationClaimSerializer, description="The claim was changed."),@@ -587,16 +602,24 @@ class ReviewInstallationClaimViewSet("removes the exceptions of the repositories that leave this project. Personal choices stay.",)def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:- claim = self.get_object()+ claim_id = self._claim_id_or_404()serializer = ReviewInstallationClaimUpdateSerializer(data=request.data)serializer.is_valid(raise_exception=True)try:- claim = self.project_repositories().update_claim(claim, serializer.validated_data["scope"])+ claim = update_review_installation_claim(+ self.effective_team_id,+ self.acting_user_id,+ claim_id,+ ReviewInstallationClaimScope(serializer.validated_data["scope"]),+ )except OwnershipConflict as error:return conflict_response(error)- return Response(self.get_serializer(claim).data)+ if claim is None:+ raise NotFound()+ return Response(ReviewInstallationClaimSerializer(claim).data)@extend_schema(+ parameters=[uuid_path_parameter("review installation claim")],responses={204: OpenApiResponse(description="The claim and this project's repository settings there are gone.")},@@ -605,7 +628,9 @@ class ReviewInstallationClaimViewSet("repositories and exceptions there are removed too. Personal choices stay.",)def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:- self.project_repositories().delete_claim(self.get_object())+ claim_id = path_uuid(self.kwargs["pk"])+ if not delete_review_installation_claim(self.effective_team_id, self.acting_user_id, claim_id):+ raise NotFound()return Response(status=status.HTTP_204_NO_CONTENT)@@ -613,14 +638,10 @@ class ReviewInstallationClaimViewSet(destroy=extend_schema(summary="Clear my choice for a repository",description="Clear the requesting user's own choice for one repository, so their default applies again.",+ parameters=[uuid_path_parameter("review user repository choice")],),)-class ReviewRepositoryChoiceViewSet(- ReviewHogProjectViewSetMixin,- mixins.ListModelMixin,- mixins.DestroyModelMixin,- viewsets.GenericViewSet,-):+class ReviewRepositoryChoiceViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericViewSet):"""The requesting user's own automatic review choices for repositories of this project.Any project member can manage their own choices. A choice stores only what differs from what the@@ -628,18 +649,20 @@ class ReviewRepositoryChoiceViewSet("""scope_object = "review_hog"- permission_classes = [PostHogFeatureFlagPermission]+ permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamMemberPermission]posthog_feature_flag = "review-hog"- queryset = ReviewUserRepositoryChoice.objects.unscoped()serializer_class = ReviewRepositoryChoiceSerializerpagination_class = None- def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:- return (- ReviewUserRepositoryChoice.objects.for_team(self.effective_team_id, canonical=True)- .filter(user_id=cast(User, self.request.user).id)- .order_by("full_name")- )+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ choices = list_review_repository_choices(self.effective_team_id, self.acting_user_id)+ return Response(ReviewRepositoryChoiceSerializer(choices, many=True).data)++ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ choice_id = path_uuid(self.kwargs["pk"])+ if not delete_review_repository_choice(self.effective_team_id, self.acting_user_id, choice_id):+ raise NotFound()+ return Response(status=status.HTTP_204_NO_CONTENT)@extend_schema(request=ReviewRepositoryChoiceWriteSerializer,@@ -657,16 +680,18 @@ class ReviewRepositoryChoiceViewSet(serializer = ReviewRepositoryChoiceWriteSerializer(data=request.data)serializer.is_valid(raise_exception=True)data = serializer.validated_data- ref = RepositoryRef(- installation_id=data["installation_id"],- github_repo_id=data.get("github_repo_id"),- full_name=data["full_name"],- )try:- choice, decision = RepositoryChoices(self.effective_team, cast(User, request.user)).save(ref, data["mode"])+ result = save_review_repository_choice(+ self.effective_team_id,+ self.acting_user_id,+ installation_id=data["installation_id"],+ full_name=data["full_name"],+ github_repo_id=data.get("github_repo_id"),+ mode=ReviewUserRepositoryChoiceMode(data["mode"]),+ )except RepositorySettingsError as error:return bad_request_response(error)response = ReviewRepositoryChoiceWriteResponseSerializer(- {"choice": choice, "my_result": decision_data(decision)}+ {"choice": result.choice, "my_result": decision_data(result.my_result)})return Response(response.data)diff --git a/products/review_hog/backend/repository_settings.py b/products/review_hog/backend/repository_settings.pyindex 35bb4f2abe72..3756d02d9bd4 100644--- a/products/review_hog/backend/repository_settings.py+++ b/products/review_hog/backend/repository_settings.py@@ -9,23 +9,34 @@ import loggingfrom collections.abc import Mapping, Sequencefrom dataclasses import replacefrom typing import Any+from uuid import UUID-from django.db import IntegrityError, models, transaction+from django.db import IntegrityError, transactionfrom posthog.dataclasses import frozenfrom posthog.egress.limiter.policies import Priorityfrom posthog.models.integration import GitHubIntegration, Integration+from posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom products.review_hog.backend.activity_logging import log_repository_takenfrom products.review_hog.backend.automatic_review_rules import (AuthorPreferences,- AutomaticReviewDecision,- AutomaticReviewReason,ProjectRuleContext,load_author_preferences,)+from products.review_hog.backend.facade.contracts import (+ UNSET,+ AutomaticReviewDecision,+ GitHubRepositoryListError,+ OwnershipConflict,+ PersonNotActiveMemberError,+ ProjectRef,+ RepositorySettingsError,+ Unset,+)+from products.review_hog.backend.facade.enums import AutomaticReviewReason, RepositoryOverviewView, RepositoryOwnerKindfrom products.review_hog.backend.models import (ReviewInstallationClaim,ReviewRepository,@@ -38,41 +49,11 @@ from products.review_hog.backend.preferences import DefaultReviewModelogger = logging.getLogger(__name__)-class Unset:- """Marks a field the request did not mention, because None is a valid value."""---UNSET = Unset()---class RepositorySettingsError(Exception):- """A write the rules do not allow. The API answers 400 with the message."""---@frozen-class ProjectRef:- """Another project, named only inside its own organization."""-- team_id: int- name: str | None-- @classmethod- def load(cls, team_id: int, *, viewer_organization_id: Any) -> "ProjectRef":- team = Team.objects.filter(id=team_id).values("name", "organization_id").first() or {}- same_organization = team.get("organization_id") == viewer_organization_id- return cls(team_id=team_id, name=team.get("name") if same_organization else None)-- @property- def label(self) -> str:- return f"the {self.name} project" if self.name else "a project in another organization"---class OwnershipConflict(Exception):- """Another project already holds what this write asks for. The API answers 409."""-- def __init__(self, message: str, project: ProjectRef | None) -> None:- super().__init__(message)- self.project = project+def load_project_ref(team_id: int, *, viewer_organization_id: Any) -> ProjectRef:+ """Another project, with its name only when it is in the viewer's organization."""+ team = Team.objects.filter(id=team_id).values("name", "organization_id").first() or {}+ same_organization = team.get("organization_id") == viewer_organization_id+ return ProjectRef(team_id=team_id, name=team.get("name") if same_organization else None)@frozen@@ -101,7 +82,7 @@ class ProjectRepositories:self.user = userdef _project(self, team_id: int) -> ProjectRef:- return ProjectRef.load(team_id, viewer_organization_id=self.team.organization_id)+ return load_project_ref(team_id, viewer_organization_id=self.team.organization_id)def integrations(self) -> list[Integration]:return list(@@ -114,6 +95,69 @@ class ProjectRepositories:raise RepositorySettingsError("This project has no GitHub connection for that installation.")return integration+ def installation_repositories(self, installation_id: str, search: str) -> Sequence[Mapping[str, Any]]:+ """The repositories the installation can see, from the cache, whose name contains `search`."""+ integration = self.integration_for(installation_id)+ try:+ repositories = GitHubIntegration(+ integration, source="review_hog", priority=Priority.NORMAL+ ).list_all_cached_repositories()+ except Exception:+ # The list refreshes from GitHub when the cache is cold, and GitHub can fail or rate limit.+ logger.warning("review_hog_repository_overview_list_failed", exc_info=True)+ raise GitHubRepositoryListError("GitHub did not return the repository list. Try again shortly.")+ search = search.strip().casefold()+ if search:+ repositories = [+ repository for repository in repositories if search in str(repository["full_name"]).casefold()+ ]+ return repositories++ def check_active_member(self, user_id: int) -> None:+ is_member = OrganizationMembership.objects.filter(+ organization_id=self.team.organization_id, user_id=user_id, user__is_active=True+ ).exists()+ if not is_member:+ raise PersonNotActiveMemberError("This user is not an active member of the organization.")++ def repositories(self) -> list[ReviewRepository]:+ return list(+ ReviewRepository.objects.for_team(self.team_id, canonical=True)+ .select_related("created_by")+ .order_by("created_at")+ )++ def repository(self, repository_id: UUID) -> ReviewRepository | None:+ return (+ ReviewRepository.objects.for_team(self.team_id, canonical=True)+ .select_related("created_by")+ .filter(id=repository_id)+ .first()+ )++ def delete_repository(self, repository_id: UUID) -> bool:+ """Delete one repository row and its lists. False when the project has no such row."""+ row = self.repository(repository_id)+ if row is None:+ return False+ row.delete()+ return True++ def claims(self) -> list[ReviewInstallationClaim]:+ return list(+ ReviewInstallationClaim.objects.for_team(self.team_id, canonical=True)+ .select_related("created_by")+ .order_by("created_at")+ )++ def claim(self, claim_id: UUID) -> ReviewInstallationClaim | None:+ return (+ ReviewInstallationClaim.objects.for_team(self.team_id, canonical=True)+ .select_related("created_by")+ .filter(id=claim_id)+ .first()+ )+def verified_ref(self, ref: RepositoryRef) -> RepositoryRef:"""The repository as the installation reports it. A client cannot store a pair GitHub does not know."""integration = self.integration_for(ref.installation_id)@@ -296,18 +340,21 @@ class ProjectRepositories:)return created+ def remove_person(self, repository_id: UUID | None, person_id: UUID) -> bool:+ """Remove one entry from a list of the project rule (no repository) or of an exception.-class RepositoryOwnerKind(models.TextChoices):- THIS_PROJECT = "this_project", "This project"- OTHER_PROJECT = "other_project", "Another project"- NONE = "none", "No project"---class RepositoryOverviewView(models.TextChoices):- ALL = "all", "All repositories"- IN_PROJECT = "in_project", "In this project"- EXCEPTIONS = "exceptions", "With exceptions"- MINE = "mine", "My choices"+ False when the list has no such entry.+ """+ people = ReviewRepositoryPerson.objects.for_team(self.team_id, canonical=True)+ if repository_id is None:+ people = people.filter(repository__isnull=True)+ else:+ people = people.filter(repository_id=repository_id)+ person = people.filter(id=person_id).first()+ if person is None:+ return False+ person.delete()+ return True@frozen@@ -348,7 +395,7 @@ class RepositoryOverview:def _project(self, team_id: int) -> ProjectRef:if team_id not in self._projects:- self._projects[team_id] = ProjectRef.load(team_id, viewer_organization_id=self.team.organization_id)+ self._projects[team_id] = load_project_ref(team_id, viewer_organization_id=self.team.organization_id)return self._projects[team_id]def entry(self, repository: Mapping[str, Any]) -> OverviewEntry:@@ -428,6 +475,25 @@ class RepositoryChoices:self.team = teamself.user = user+ def choices(self) -> list[ReviewUserRepositoryChoice]:+ return list(+ ReviewUserRepositoryChoice.objects.for_team(self.team.id, canonical=True)+ .filter(user_id=self.user.id)+ .order_by("full_name")+ )++ def delete(self, choice_id: UUID) -> bool:+ """Clear one of the person's choices. False when the person has no such choice."""+ choice = (+ ReviewUserRepositoryChoice.objects.for_team(self.team.id, canonical=True)+ .filter(user_id=self.user.id, id=choice_id)+ .first()+ )+ if choice is None:+ return False+ choice.delete()+ return True+def save(self, ref: RepositoryRef, mode: str) -> tuple[ReviewUserRepositoryChoice | None, AutomaticReviewDecision]:ProjectRepositories(self.team, self.user).integration_for(ref.installation_id)owner = RepositoryOwnership.find(ref)diff --git a/products/review_hog/backend/tests/test_automatic_review_rules.py b/products/review_hog/backend/tests/test_automatic_review_rules.pyindex 7c92e16fdbca..0d7a0a3cc3a2 100644--- a/products/review_hog/backend/tests/test_automatic_review_rules.py+++ b/products/review_hog/backend/tests/test_automatic_review_rules.py@@ -9,6 +9,7 @@ from products.review_hog.backend.automatic_review_rules import (AutomaticReviewRule,FlashRule,)+from products.review_hog.backend.facade.enums import ReviewUserRepositoryChoiceModefrom products.review_hog.backend.models import AutomaticFlashFor, ReviewUserRepositoryChoicefrom products.review_hog.backend.preferences import DefaultReviewMode@@ -129,7 +130,7 @@ class TestAutomaticReviewRule(SimpleTestCase):automatic_rule: AutomaticReviewRule,user_id: int,default_mode: DefaultReviewMode,- repository_choice: ReviewUserRepositoryChoice.Mode | None,+ repository_choice: ReviewUserRepositoryChoiceMode | None,flash: bool,reason: AutomaticReviewReason,) -> None:diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.pyindex 22ab8483f35e..a156cafd8068 100644--- a/products/review_hog/backend/tests/test_repositories_api.py+++ b/products/review_hog/backend/tests/test_repositories_api.py@@ -106,13 +106,13 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):@parameterized.expand([- ("environment_only", False, (403, 403, 403, 403, 403)),- ("environment_and_parent", True, (200, 200, 200, 200, 200)),+ ("environment_only", False, (403, 403, 403, 403, 403, 403)),+ ("environment_and_parent", True, (200, 200, 200, 200, 200, 200)),])@patch("products.review_hog.backend.pr_status.probe_workflow", return_value=WorkflowProbe.NOT_RUNNING)def test_a_project_scoped_key_needs_the_parent_project(- self, _name: str, include_parent: bool, expected: tuple[int, int, int, int, int], _probe: MagicMock+ self, _name: str, include_parent: bool, expected: tuple[int, int, int, int, int, int], _probe: MagicMock) -> None:environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Staging")value = generate_random_token_personal()@@ -133,6 +133,7 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):self._url("reviews/pr_status/", environment), {"pr_url": "https://github.com/PostHog/posthog/pull/5"})table = self.client.get(self._url("reviews/table/", environment))+ choices = self.client.get(self._url("repository_choices/", environment))assert (read.status_code,@@ -140,6 +141,7 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):reviews.status_code,pr_status.status_code,table.status_code,+ choices.status_code,) == expecteddef test_project_rule_stores_only_what_differs_and_is_logged(self) -> None:diff --git a/pyproject.toml b/pyproject.tomlindex b28865a20dfb..77b55ff2cbbc 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -644,15 +644,6 @@ ignore_imports = ["products.mcp_store.backend.presentation.views -> products.mcp_store.backend.tools","products.notifications.backend.presentation.views -> products.notifications.backend.cache","products.notifications.backend.presentation.views -> products.notifications.backend.models",- "products.review_hog.backend.presentation.views.project_settings -> products.review_hog.backend.automatic_review_rules",- "products.review_hog.backend.presentation.views.project_settings -> products.review_hog.backend.models",- "products.review_hog.backend.presentation.views.project_settings -> products.review_hog.backend.preferences",- "products.review_hog.backend.presentation.views.project_settings -> products.review_hog.backend.repository_settings",- "products.review_hog.backend.presentation.views.repositories -> products.review_hog.backend.activity_logging",- "products.review_hog.backend.presentation.views.repositories -> products.review_hog.backend.automatic_review_rules",- "products.review_hog.backend.presentation.views.repositories -> products.review_hog.backend.models",- "products.review_hog.backend.presentation.views.repositories -> products.review_hog.backend.ownership",- "products.review_hog.backend.presentation.views.repositories -> products.review_hog.backend.repository_settings","products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.models","products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.pr_status","products.review_hog.backend.presentation.views.reviews -> products.review_hog.backend.preferences",