Skip to content

Introduce sowing_period, refactor period parsing, update admin/bot texts and add migrations#18

Merged
capcom6 merged 3 commits into
masterfrom
codex/add-planting-period-for-crops
Mar 10, 2026
Merged

Introduce sowing_period, refactor period parsing, update admin/bot texts and add migrations#18
capcom6 merged 3 commits into
masterfrom
codex/add-planting-period-for-crops

Conversation

@capcom6

@capcom6 capcom6 commented Feb 28, 2026

Copy link
Copy Markdown
Contributor

Motivation

  • Add explicit sowing_period alongside existing planting_period to model separate semantics for sowing vs transplanting.
  • Keep period format/validation consistent and make parsing more robust and reusable across models and admin.
  • Surface the new field in admin views and ensure user-facing bot text correctly references transplanting readiness.

Description

  • Added AGENTS.md with contributor notes about project structure, domain semantics, and developer checks.
  • Introduced sowing_period CharField on PlantType and PlantVariety with the same regex validation as planting_period, and extracted the regex into PLANTING_PERIOD_REGEX in backend/catalogs/models.py.
  • Refactored period parsing in backend/diary/models.py by adding a static helper _parse_period and separate sowing_period/parsed_sowing_period properties while preserving planting_period and parsed_planting_period, and improved logging to include period_name and plant_id.
  • Updated admin interfaces: PlantTypeAdmin and PlantVarietyAdmin now include sowing_period in fields and list_display, and PlantAdmin shows sowing_period and planting_period columns with display helpers.
  • Adjusted bot text in backend/bot/bot.py for the /planting command to clarify transplanting readiness and changed the label from "Planned planting period" to "Planned transplanting period".
  • Added two Django migrations in backend/catalogs/migrations/0005_alter_planting_period_labels.py and 0006_add_sowing_period_and_restore_planting_period.py to alter verbose names/validators and add sowing_period fields.

Testing

  • Compiled changed Python files with python -m compileall which completed without syntax errors.
  • Ran python backend/manage.py makemigrations --check to confirm migrations are in place and it reported no additional model changes.
  • Executed python backend/manage.py test and the test suite passed.

Codex Task

Summary by CodeRabbit

  • New Features

    • Added sowing period tracking for plant types and varieties in the catalog.
    • Improved date range filtering for plant availability with enhanced year-boundary handling.
  • Bug Fixes

    • Fixed date filtering logic to properly validate both start and end dates.
    • Enhanced period parsing for accurate handling of date ranges crossing year boundaries.
  • Chores

    • Updated UI terminology from "planting" to "transplanting" in the planting flow.
    • Added database migration to support sowing period fields.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Feb 28, 2026

Copy link
Copy Markdown

Walkthrough

The changes add a new sowing_period field to plant catalog models with corresponding admin interface updates. Period parsing logic is refactored to handle year-wrapping scenarios with improved error logging. Bot filtering logic now checks both start and end dates, and display terminology shifts from "planting" to "transplanting" in the bot's planting flow.

Changes

Cohort / File(s) Summary
Model Field Addition
backend/catalogs/models.py
Introduces PLANTING_PERIOD_REGEX constant and adds sowing_period field to PlantType and PlantVariety models; updates existing planting_period validators to use the centralized regex.
Admin Display Configuration
backend/catalogs/admin.py, backend/diary/admin.py
Adds sowing_period to PlantTypeAdmin and PlantVarietyAdmin field and list_display tuples; adds planting_period display method to PlantAdmin.
Period Parsing Refactoring
backend/diary/models.py
Extracts period parsing logic into static method _parse_period with improved error handling; restores planting_period and parsed_planting_period as public properties with year-wrapping support for periods spanning year boundaries.
Bot Logic Updates
backend/bot/bot.py
Updates planting flow filtering to check both start_date and end_date boundaries; changes display text from "planting" to "transplanting"; updates initial message label.
Database Migration
backend/catalogs/migrations/0005_...
Adds sowing_period CharField with RegexValidator to planttype and plantvariety tables via Django migration.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately summarizes the main changes: introducing sowing_period, refactoring period parsing, updating admin/bot texts, and adding migrations. All these elements are directly reflected in the changeset across multiple files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-planting-period-for-crops

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/bot/bot.py (1)

147-173: ⚠️ Potential issue | 🟡 Minor

Header wording does not match readiness logic

The message says plants are “ready for transplanting”, but current filtering still includes future windows (when start_date > now). Either tighten the filter to “ready now” or soften the header to “upcoming transplanting periods”.

Suggested fix (ready-now behavior)
-    answer = _("Your plants ready for transplanting:") + "\n"
+    answer = _("Your plants ready for transplanting:") + "\n"
@@
-        if end_date < now:
+        if now < start_date or end_date < now:
             continue
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/bot/bot.py` around lines 147 - 173, The header "Your plants ready for
transplanting" conflicts with the loop which includes future windows; update the
logic in bot.py so the header and filtering match: either (A) tighten the filter
to only include plants whose parsed_planting_period contains today (i.e.
parsed_planting_period -> start_date and end_date and require start_date <= now
<= end_date before setting plants_found and appending to answer) or (B) change
the header text in the answer variable to something like "Your upcoming
transplanting periods" to reflect that future windows are listed; locate symbols
parsed_planting_period, start_date, end_date, now, the plants iteration and the
answer string to apply the change.
🧹 Nitpick comments (1)
backend/diary/models.py (1)

152-186: Typo: romanian_months should be roman_months.

The dictionary maps Roman numerals (I, II, III, etc.) to integers. "Romanian" refers to the country/language, while "Roman" refers to the numeral system.

✏️ Suggested fix
-        romanian_months = {
+        roman_months = {
             "I": 1,
             "II": 2,
             "III": 3,
             "IV": 4,
             "V": 5,
             "VI": 6,
             "VII": 7,
             "VIII": 8,
             "IX": 9,
             "X": 10,
             "XI": 11,
             "XII": 12,
         }
 
         try:
             start_str, end_str = period.split("-")
             start_day, start_month = start_str.split(".")
             end_day, end_month = end_str.split(".")
 
             today = date.today()
-            start_date = date(today.year, romanian_months[start_month], int(start_day))
-            end_date = date(today.year, romanian_months[end_month], int(end_day))
+            start_date = date(today.year, roman_months[start_month], int(start_day))
+            end_date = date(today.year, roman_months[end_month], int(end_day))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/diary/models.py` around lines 152 - 186, Rename the incorrect
variable name romanian_months to roman_months inside the _parse_period static
method and update any references within that function (e.g., where
romanian_months[start_month] and romanian_months[end_month] are used) so the
dictionary name matches the Roman numeral mapping; ensure no other semantics
change and run tests to confirm no remaining references to the old name.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@backend/bot/bot.py`:
- Around line 147-173: The header "Your plants ready for transplanting"
conflicts with the loop which includes future windows; update the logic in
bot.py so the header and filtering match: either (A) tighten the filter to only
include plants whose parsed_planting_period contains today (i.e.
parsed_planting_period -> start_date and end_date and require start_date <= now
<= end_date before setting plants_found and appending to answer) or (B) change
the header text in the answer variable to something like "Your upcoming
transplanting periods" to reflect that future windows are listed; locate symbols
parsed_planting_period, start_date, end_date, now, the plants iteration and the
answer string to apply the change.

---

Nitpick comments:
In `@backend/diary/models.py`:
- Around line 152-186: Rename the incorrect variable name romanian_months to
roman_months inside the _parse_period static method and update any references
within that function (e.g., where romanian_months[start_month] and
romanian_months[end_month] are used) so the dictionary name matches the Roman
numeral mapping; ensure no other semantics change and run tests to confirm no
remaining references to the old name.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3554c12 and d3ebd1c.

📒 Files selected for processing (8)
  • AGENTS.md
  • backend/bot/bot.py
  • backend/catalogs/admin.py
  • backend/catalogs/migrations/0005_alter_planting_period_labels.py
  • backend/catalogs/migrations/0006_add_sowing_period_and_restore_planting_period.py
  • backend/catalogs/models.py
  • backend/diary/admin.py
  • backend/diary/models.py

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
backend/diary/models.py (1)

183-183: Make parse-failure logs more diagnosable.

The warning currently omits the invalid period value and exception details, which makes production troubleshooting harder.

🛠️ Proposed improvement
-        except (ValueError, KeyError):
-            logger.warning("Failed to parse %s for plant %s", period_name, plant_id)
+        except (ValueError, KeyError) as exc:
+            logger.warning(
+                "Failed to parse %s for plant %s: value=%r error=%s",
+                period_name,
+                plant_id,
+                period,
+                exc,
+            )
             return None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/diary/models.py` at line 183, The log in the parse failure
(logger.warning("Failed to parse %s for plant %s", period_name, plant_id)) omits
the invalid period value and exception details; update the error logging in the
parse path that references period_name and plant_id to capture the exception
(e.g., as e) and include both the offending period value and the exception info
in the log message (or use logger.exception / exc_info=True) so the log shows
period, plant_id, and exception traceback for diagnosability.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/diary/models.py`:
- Around line 178-181: The start_date and end_date are being built using the
same year, which fails for ranges that cross year boundaries (e.g., start_date
from November and end_date in February); after computing start_date and end_date
(using roman_months, start_month, end_month, start_day, end_day), check if
end_date < start_date and if so adjust end_date to the next calendar year
(increment its year by 1) so the returned tuple is always a forward-facing
range.

---

Nitpick comments:
In `@backend/diary/models.py`:
- Line 183: The log in the parse failure (logger.warning("Failed to parse %s for
plant %s", period_name, plant_id)) omits the invalid period value and exception
details; update the error logging in the parse path that references period_name
and plant_id to capture the exception (e.g., as e) and include both the
offending period value and the exception info in the log message (or use
logger.exception / exc_info=True) so the log shows period, plant_id, and
exception traceback for diagnosability.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d3ebd1c and f32bbc1.

📒 Files selected for processing (2)
  • backend/bot/bot.py
  • backend/diary/models.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/bot/bot.py

Comment thread backend/diary/models.py Outdated

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/diary/models.py`:
- Around line 183-187: The start_date is always built with today.year which
mis-anchors wrapped ranges spanning year boundaries; change the logic so when
the range wraps (i.e., (end_month_i, end_day_i) < (start_month_i, start_day_i))
you set end_year = today.year and start_year = end_year - 1, otherwise set
start_year = today.year; then construct start_date = date(start_year,
start_month_i, start_day_i) and end_date = date(end_year, end_month_i,
end_day_i). This updates the variables referenced (start_date, end_date,
end_year, start_month_i, start_day_i, end_month_i, end_day_i) to correctly
anchor cross-year periods.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f32bbc1 and ff8237e.

📒 Files selected for processing (1)
  • backend/diary/models.py

Comment thread backend/diary/models.py Outdated
@capcom6 capcom6 force-pushed the codex/add-planting-period-for-crops branch from 0543834 to 0624b83 Compare March 3, 2026 01:26

@coderabbitai coderabbitai 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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/bot/bot.py`:
- Around line 167-175: The fallback message is misleading because the date
filter (now < start_date or end_date < now) can make plants_found False even
when the user has plants; update the fallback logic that builds answer (uses
variables plants_found, now, start_date, end_date and appends plant.name and
planting_period) to return a message indicating no plants are currently within
the transplanting window (e.g., "You don't have any plants ready for
transplanting right now.") and ensure you use the translation function _() for
the new message so localization remains consistent.

In `@backend/catalogs/models.py`:
- Line 6: The PLANTING_PERIOD_REGEX only enforces format but allows impossible
combinations (e.g., 31.II); add a parser-backed validator that runs after the
regex: implement a function (e.g., validate_planting_period) that parses the two
dates from the string using the same Roman-month tokens as in
PLANTING_PERIOD_REGEX, map Roman numerals to month numbers, validate day bounds
against each month's actual max days (account for February 28/29 if needed or
assume non-leap for schedule domain), ensure the start date is <= end date, and
raise ValidationError when invalid; wire this validator into the model/field
that uses PLANTING_PERIOD_REGEX so impossible month/day combos are rejected
before runtime parsing.

In `@backend/diary/models.py`:
- Around line 177-196: Replace non-timezone-aware date.today() calls with
Django's timezone.localdate(): add "from django.utils import timezone" import
and change the two usages shown — the earlier date.today().strftime(...) and the
later today = date.today() used to compute start_year/end_year and
start_date/end_date — to use timezone.localdate() (keep the same .strftime and
tuple comparisons logic); ensure roman_months, start_date and end_date logic
remains unchanged.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0543834 and 0624b83.

📒 Files selected for processing (6)
  • backend/bot/bot.py
  • backend/catalogs/admin.py
  • backend/catalogs/migrations/0005_planttype_sowing_period_plantvariety_sowing_period.py
  • backend/catalogs/models.py
  • backend/diary/admin.py
  • backend/diary/models.py

Comment thread backend/bot/bot.py Outdated
Comment thread backend/catalogs/models.py
Comment thread backend/diary/models.py Outdated
@capcom6 capcom6 force-pushed the codex/add-planting-period-for-crops branch 3 times, most recently from 30fd70f to 6996294 Compare March 5, 2026 01:44
@capcom6 capcom6 added the ready label Mar 5, 2026
@capcom6 capcom6 force-pushed the codex/add-planting-period-for-crops branch from 6996294 to fd1b660 Compare March 7, 2026 23:34
@capcom6 capcom6 merged commit e46ec61 into master Mar 10, 2026
6 checks passed
@capcom6 capcom6 deleted the codex/add-planting-period-for-crops branch March 10, 2026 02:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant