Skip to content

Добавлена архитектура правил, планов и состояний ухода - #21

Merged
newfatto merged 1 commit into
developfrom
feature/care-rule
Jul 29, 2026
Merged

Добавлена архитектура правил, планов и состояний ухода#21
newfatto merged 1 commit into
developfrom
feature/care-rule

Conversation

@newfatto

Copy link
Copy Markdown
Owner

Что изменено

  • Добавлены CareRule, PlannedEvent, PetCondition для разделения регулярности, плановых задач и активных состояний ухода.
  • Добавлено переходное поле Event.happened_at рядом со старым event_datetime.
  • Добавлены additive migrations 0012-0015.
  • Добавлены dry-run команды подготовки правил, плановых задач и состояний.
  • Расширена команда recalculate_pet_statuses.
  • Добавлено fallback-чтение старой схемы.
  • Регулярность сохраняется в CareRule.
  • Уточнены права суперпользователя для создания сущностей чужого питомца.
  • Уточнены подписи дат в админке и подсказка под полем повторяемости.

Что сохранено

  • Старые поля и история событий не удалялись.
  • Старый Event.event_type, event_datetime, repeat_after_days, no_handling_days остаются совместимыми на переходный период.
  • Production, deploy и main не трогались.

README

Перед merge проверено: обязательная правка README.md сейчас не требуется. README уже описывает повторяющиеся задачи и напоминания на уровне публичной витрины; внутренние детали CareRule, PlannedEvent, PetCondition не выносим, чтобы README не превращался в техническую спецификацию.

Проверки

  • python manage.py makemigrations --check
  • python manage.py check
  • git diff --check
  • isort --check-only
  • python manage.py recalculate_pet_statuses в dry-run
  • pytest --no-cov — 257 passed

Примечание по форматированию

black пока не включался в автоматический цикл Codex в этой Windows-среде из-за зависания процесса после форматирования. Основной контроль закрыт isort, git diff --check, Django checks и pytest.

@newfatto
newfatto marked this pull request as ready for review July 29, 2026 14:07
@newfatto
newfatto merged commit 548334e into develop Jul 29, 2026
2 checks passed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6dd9b01328

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread pets/services.py
Comment on lines +468 to +472
CareRule.objects.filter(
pet=event.pet,
event_type=event_type,
is_active=True,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve separate recurring custom tasks

When a pet has two titled recurring custom events, both resolve to the same catalog EventType (custom), so this lookup returns the first active rule and the second event silently overwrites its interval and start date. Custom events previously recurred independently, so rules need an identity beyond the pet/type pair, such as their originating custom task.

Useful? React with 👍 / 👎.

Comment thread pets/views.py

with transaction.atomic():
response = super().form_valid(form)
sync_care_rule_from_event_repeat(self.object, repeat_after_days)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Allow users to disable an existing recurrence

After the first save, repeat_after_days is cleared from the Event and stored in CareRule, so the next update form renders this field blank. Submitting that blank value calls sync_care_rule_from_event_repeat(..., None), which returns without changing the existing active rule; consequently the normal event UI neither displays the configured interval nor provides a way to clear it, and reminders continue after the user submits an empty recurrence field.

Useful? React with 👍 / 👎.

Comment thread pets/services.py
Comment on lines +265 to +266
if base_dt is None:
base_dt = _get_care_rule_start_datetime(care_rule)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor the selected CareRule calculation mode

For rules configured as last_planned_date or fixed_schedule, the only preceding calculation branch is skipped and this fallback always uses start_date. Once a generated task is completed or skipped, the next generator run therefore recreates a task at the same original timestamp rather than advancing from the previous plan or along the fixed schedule.

Useful? React with 👍 / 👎.

Comment thread users/services.py
if local_next_dt.date() == today:
event_name = event.title.strip() if event.title else "другое событие"
tasks.append(event_name)
tasks.append(task_labels.get(task.event_type_slug, task.event_type_name.lower()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve custom titles in daily reminders

For a recurring custom event represented by a CareRule, task.event_type_name is the catalog name Другое, so this emits a generic “другое” task. The subsequent custom_care_rule_exists check suppresses the legacy loop that used the event's actual title, meaning even a single named reminder such as “Заменить лампу” loses its actionable text after conversion to the new architecture.

Useful? React with 👍 / 👎.

Comment thread pets/services.py
плановых задач и активных состояний нужно передать ``apply_changes=True``.
"""
care_rule_result = backfill_care_rules_from_repeat_events(apply_changes=apply_changes)
planned_event_result = generate_planned_events_from_care_rules(apply_changes=apply_changes)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include newly previewed rules when counting planned tasks

In dry-run mode with only legacy repeating events, the preceding backfill reports candidate CareRule rows but deliberately does not create them, so this planner sees no rules and reports planned_events_to_create == 0. Running the same command with --apply creates both the rules and their planned events, making the command's “will be created” preview materially undercount the changes it will apply.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant