-
Notifications
You must be signed in to change notification settings - Fork 1
256764: Implement unique field management for households and individu… #356
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
arsen-vs
wants to merge
8
commits into
develop
Choose a base branch
from
feature/256764-Unique-per-programme-fields
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
14501fa
256764: Implement unique field management for households and individu…
f16e066
Enhance Program model data checks and testing
e637427
Refactor Program model and enhance testing for unique field management
8145cbd
Enhance unique value archiving in orchestration and improve test cove…
2053a9a
Add MagicMock import for enhanced testing in test_program.py
9aa5bde
Add mock_program fixture to enhance testing capabilities in test_prog…
065c149
Enhance testing for unique value management in Program and validation…
8b26d8e
Enhance validation logic for household members and add new test case …
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,13 +7,86 @@ | |
| from constance import config | ||
| from django.db.models import Model, QuerySet, Prefetch | ||
| from django.db.models.query import prefetch_related_objects | ||
| from django.utils import timezone | ||
|
|
||
| from country_workspace.context import batch_ctx | ||
| from country_workspace.models import AsyncJob, Household, Individual, Program | ||
| from country_workspace.state import state | ||
| from country_workspace.utils.imports import validate_alien_fields | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
| UNIQUE_VALIDATION_ERROR = "Value must be unique within the programme." | ||
| ARCHIVED_UNIQUE_VALIDATION_ERROR = "Value must be unique and cannot match previously pushed records." | ||
|
|
||
|
|
||
| def _normalize_unique_value(value: object) -> str | None: | ||
| normalized = str(value).strip() if value is not None else "" | ||
| return normalized or None | ||
|
|
||
|
|
||
| def _append_unique_error(obj: Model, field_name: str, message: str) -> None: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Each call to _append_unique_error issues an individual UPDATE query to db. Can we use bulk_update instead? |
||
| errors = dict(getattr(obj, "errors", {}) or {}) | ||
| current = errors.get(field_name) or [] | ||
| if not isinstance(current, list): | ||
| current = [str(current)] | ||
| if message in current: | ||
| return | ||
| current.append(message) | ||
| errors[field_name] = current | ||
| obj.errors = errors | ||
| obj.last_checked = timezone.now() | ||
| obj.save(update_fields=["errors", "last_checked"]) | ||
|
|
||
|
|
||
| def _append_household_member_invalid_error(obj: Model) -> None: | ||
| errors = dict(getattr(obj, "errors", {}) or {}) | ||
| details = errors.get("dct") or [] | ||
| if not isinstance(details, list): | ||
| details = [str(details)] | ||
| marker = "Some members did not validate" | ||
| if marker in details: | ||
| return | ||
| details.append(marker) | ||
| errors["dct"] = details | ||
| obj.errors = errors | ||
| obj.last_checked = timezone.now() | ||
| obj.save(update_fields=["errors", "last_checked"]) | ||
|
|
||
|
|
||
| class UniqueValidationState: | ||
| def __init__(self, *, field_name: str, archived_values: set[str]) -> None: | ||
| self.field_name = field_name | ||
| self.archived_values = archived_values | ||
| self.seen_by_value: dict[str, Model] = {} | ||
|
|
||
| def validate(self, obj: Model) -> set[int]: | ||
| invalid_pks: set[int] = set() | ||
| flex_fields = getattr(obj, "flex_fields", {}) or {} | ||
| value = _normalize_unique_value(flex_fields.get(self.field_name)) | ||
| if not value: | ||
| return invalid_pks | ||
|
|
||
| if value in self.archived_values: | ||
| _append_unique_error(obj, self.field_name, ARCHIVED_UNIQUE_VALIDATION_ERROR) | ||
| invalid_pks.add(obj.pk) | ||
| return invalid_pks | ||
|
|
||
| if previous := self.seen_by_value.get(value): | ||
| _append_unique_error(previous, self.field_name, UNIQUE_VALIDATION_ERROR) | ||
| _append_unique_error(obj, self.field_name, UNIQUE_VALIDATION_ERROR) | ||
| invalid_pks.add(previous.pk) | ||
| invalid_pks.add(obj.pk) | ||
| return invalid_pks | ||
|
|
||
| self.seen_by_value[value] = obj | ||
| return invalid_pks | ||
|
|
||
|
|
||
| def _build_unique_state(program: Program, model: type[Model]) -> UniqueValidationState | None: | ||
| if not (field_name := program.get_unique_field_for(model)): | ||
| return None | ||
| archived_values = {value for value in program.get_removed_unique_values_for(model) if value} | ||
| return UniqueValidationState(field_name=field_name, archived_values=archived_values) | ||
|
|
||
|
|
||
| def validate_queryset(queryset: QuerySet[Model], chunk_size: int = 2000, **kwargs: Any) -> dict[str, int]: | ||
|
|
@@ -27,7 +100,9 @@ def validate_queryset(queryset: QuerySet[Model], chunk_size: int = 2000, **kwarg | |
| return {"valid": valid, "invalid": invalid} | ||
|
|
||
| with state.set(tenant=first.country_office, program=first.program): | ||
| unique_state = _build_unique_state(first.program, queryset.model) | ||
| if issubclass(queryset.model, Household): | ||
| individual_unique_state = _build_unique_state(first.program, Individual) | ||
| # Reverse-FK prefetch for Household.members; include forward FKs for Individuals | ||
| prefetch_members = Prefetch( | ||
| "members", | ||
|
|
@@ -39,11 +114,17 @@ def validate_queryset(queryset: QuerySet[Model], chunk_size: int = 2000, **kwarg | |
| for chunk in batched(it, chunk_size): | ||
| # Populate members for all objects in this batch (no N+1 on members access). | ||
| prefetch_related_objects(chunk, prefetch_members) | ||
| dv, di = _validate_and_count(chunk) | ||
| dv, di = _validate_and_count( | ||
| chunk, | ||
| unique_state=unique_state, | ||
| member_unique_state=individual_unique_state, | ||
| ) | ||
| valid, invalid = valid + dv, invalid + di | ||
| else: # Individual | ||
| # Just stream. | ||
| dv, di = _validate_and_count(queryset.iterator(chunk_size=chunk_size)) # stream rows from DB | ||
| dv, di = _validate_and_count( | ||
| queryset.iterator(chunk_size=chunk_size), unique_state=unique_state | ||
| ) # stream rows from DB | ||
| valid, invalid = valid + dv, invalid + di | ||
|
|
||
| except Exception as e: # pragma: no cover | ||
|
|
@@ -53,21 +134,46 @@ def validate_queryset(queryset: QuerySet[Model], chunk_size: int = 2000, **kwarg | |
| return {"valid": valid, "invalid": invalid} | ||
|
|
||
|
|
||
| def _validate_and_count(objs: Iterable[Model]) -> tuple[int, int]: | ||
| valid = invalid = 0 | ||
| def _validate_and_count( # noqa: C901 | ||
| objs: Iterable[Model], | ||
| unique_state: UniqueValidationState | None = None, | ||
| member_unique_state: UniqueValidationState | None = None, | ||
| ) -> tuple[int, int]: | ||
| total = 0 | ||
| invalid_pks: set[int] = set() | ||
| member_household_by_member_pk: dict[int, int] = {} | ||
| aliens_checked = False | ||
|
|
||
| for obj in objs: | ||
| total += 1 | ||
| if not aliens_checked: | ||
| validate_alien_fields(obj) | ||
| aliens_checked = True | ||
|
|
||
| with batch_ctx(obj.batch_id): | ||
| if obj.validate_with_checker(): | ||
| valid += 1 | ||
| else: | ||
| invalid += 1 | ||
|
|
||
| if not obj.validate_with_checker(): | ||
| invalid_pks.add(obj.pk) | ||
| if unique_state: | ||
| invalid_pks |= unique_state.validate(obj) | ||
| if member_unique_state and isinstance(obj, Household): | ||
| member_invalid = False | ||
| for member in obj.members.all(): | ||
| member_household_by_member_pk[member.pk] = obj.pk | ||
| invalid_member_pks = member_unique_state.validate(member) | ||
| if not invalid_member_pks: | ||
| continue | ||
|
|
||
| member_invalid = True | ||
| for member_pk in invalid_member_pks: | ||
| if household_pk := member_household_by_member_pk.get(member_pk): | ||
| invalid_pks.add(household_pk) | ||
|
|
||
| if member_invalid: | ||
| invalid_pks.add(obj.pk) | ||
| _append_household_member_invalid_error(obj) | ||
|
|
||
| invalid = len(invalid_pks) | ||
| valid = total - invalid | ||
| return valid, invalid | ||
|
|
||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not in the beginning of module?