Repository navigation
feat(renewals): enforce the renewal window and share its rule across the API and apps (REGBACKLOG-391) #1964
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
base: main
Are you sure you want to change the base?
Changes from all commits
4040626
634b69a
4c8ec4e
8c72fa2
6009210
fc30e73
e2b3e0a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -81,6 +81,7 @@ | |
| APPLICATION_UNPAID_STATES, | ||
| ) | ||
| from strr_api.services.examiner_note_service import ExaminerNoteNotAllowedException, ExaminerNoteService | ||
| from strr_api.utils.renewal_window import RenewalWindow | ||
| from strr_api.validators.DocumentUploadValidator import limit_document_upload_size, validate_document_upload | ||
| from strr_api.validators.RegistrationRequestValidator import validate_request | ||
|
|
||
|
|
@@ -132,7 +133,11 @@ def create_application(application_number: Optional[str] = None): | |
| 200: | ||
| description: Application created or updated; JSON body is serialized application. | ||
| 400: | ||
| description: Validation or business rule failure (e.g. missing registrationId for renewal). | ||
| description: > | ||
| Validation or business rule failure (e.g. missing registrationId for renewal, or a renewal created | ||
| or submitted before its renewal period starts, errorCode RENEWAL_WINDOW_NOT_OPEN, where a new renewal is | ||
| refused even as a draft; or a renewal created or submitted after its renewal period ends, errorCode | ||
| RENEWAL_WINDOW_CLOSED, likewise even as a draft). | ||
| 401: | ||
| description: Unauthorized. | ||
| 404: | ||
|
|
@@ -186,7 +191,9 @@ def create_application(application_number: Optional[str] = None): | |
| http_status=HTTPStatus.BAD_REQUEST, | ||
| ) | ||
|
|
||
| if request.method == "PUT" and existing_registration_id != registration_id: | ||
| # An existing application must already be a renewal of this registration, whether it's saved by PUT or | ||
| # POST; otherwise a regular draft could be turned into a renewal past the window and in-progress checks | ||
| if application is not None and existing_registration_id != registration_id: | ||
| return error_response( | ||
| message=ErrorMessage.REGISTRATION_ID_MISMATCH.value, | ||
| http_status=HTTPStatus.BAD_REQUEST, | ||
|
|
@@ -204,6 +211,23 @@ def create_application(application_number: Optional[str] = None): | |
| http_status=HTTPStatus.BAD_REQUEST, | ||
| ) | ||
|
|
||
| renewal_window = RenewalWindow.for_registration(registration) | ||
| # A new renewal can't be started before its window opens, even as a draft; an existing draft can't be | ||
| # submitted before then either | ||
| if renewal_window.is_not_yet_open and (application is None or not is_draft): | ||
| return error_response( | ||
| message=ErrorMessage.RENEWAL_WINDOW_NOT_OPEN.value, | ||
| http_status=HTTPStatus.BAD_REQUEST, | ||
| error_code="RENEWAL_WINDOW_NOT_OPEN", | ||
| ) | ||
| # The same applies after the window closes | ||
| if renewal_window.is_closed and (application is None or not is_draft): | ||
| return error_response( | ||
| message=ErrorMessage.RENEWAL_WINDOW_CLOSED.value, | ||
| http_status=HTTPStatus.BAD_REQUEST, | ||
| error_code="RENEWAL_WINDOW_CLOSED", | ||
| ) | ||
|
|
||
| if application is None: | ||
|
Collaborator
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. can we run the duplicate check when submitting a draft too? a draft can still create an invoice while another renewal is in progress. we'd need to skip the current draft in that check.
Collaborator
Author
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. Good point. Yes, a renewal draft skipped the check when it was submitted, so it could get an invoice while another renewal was in progress. That's how H353013514 paid for two renewals on 2026-06-14, both from drafts started before the check went live (June 2026). I checked Production: 52 registrations have a renewal draft beside another unfinished renewal (38 beside PAYMENT_DUE, 14 beside another DRAFT). All were created before the check went live on 2026-06-01, but any of them could still be submitted and paid. The check now also runs when a renewal draft is submitted, leaving out the draft itself. Saving a draft still isn't checked, since that doesn't create an invoice. The web apps already show the right message for a 409 RENEWAL_ALREADY_IN_PROGRESS on submit. test_draft_is_submitted_only_while_no_other_renewal_is_in_progress covers it. I put this in #1969 rather than #1964, since #1969 already changes this check. |
||
| terminal_status_values = tuple(s.value for s in APPLICATION_TERMINAL_STATES) | ||
| conflicting = ApplicationModel.find_non_terminal_renewal_for_payment_account( | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -39,11 +39,9 @@ | |||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| import logging | ||||||||||||||||||||||||||||||||||
| import traceback | ||||||||||||||||||||||||||||||||||
| from datetime import datetime, timedelta | ||||||||||||||||||||||||||||||||||
| from http import HTTPStatus | ||||||||||||||||||||||||||||||||||
| from io import BytesIO | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| from dateutil.relativedelta import relativedelta | ||||||||||||||||||||||||||||||||||
| from flasgger import swag_from | ||||||||||||||||||||||||||||||||||
| from flask import Blueprint, current_app, g, jsonify, request, send_file | ||||||||||||||||||||||||||||||||||
| from flask_cors import cross_origin | ||||||||||||||||||||||||||||||||||
|
|
@@ -83,18 +81,13 @@ | |||||||||||||||||||||||||||||||||
| REGISTRATION_STATES_STAFF_ACTION, | ||||||||||||||||||||||||||||||||||
| REGISTRATION_STATES_STAFF_ASSIGNABLE, | ||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||
| from strr_api.utils.renewal_window import RenewalWindow | ||||||||||||||||||||||||||||||||||
| from strr_api.utils.user_context import UserContext | ||||||||||||||||||||||||||||||||||
| from strr_api.validators.DocumentUploadValidator import limit_document_upload_size, validate_document_upload | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| logger = logging.getLogger("api") | ||||||||||||||||||||||||||||||||||
| bp = Blueprint("registrations", __name__) | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| # Days before expiry when renewal todos should appear | ||||||||||||||||||||||||||||||||||
| DAYS_BEFORE_EXPIRY_BY_TYPE = { | ||||||||||||||||||||||||||||||||||
| RegistrationType.STRATA_HOTEL.value: 60, | ||||||||||||||||||||||||||||||||||
| RegistrationType.HOST.value: 40, | ||||||||||||||||||||||||||||||||||
| RegistrationType.PLATFORM.value: 40, | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| VALID_REGISTRATION_SORT_FIELDS = ["id", "registration_number", "start_date", "expiry_date", "status"] | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
|
|
@@ -706,22 +699,13 @@ def get_todos(registration_id): | |||||||||||||||||||||||||||||||||
| raise AuthException() | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| todos = [] | ||||||||||||||||||||||||||||||||||
| renewal_window = RenewalWindow.for_registration(registration) | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| if registration.noc_status == RegistrationNocStatus.NOC_PENDING: | ||||||||||||||||||||||||||||||||||
| todos.append({"task": {"type": "NOC_PENDING"}}) | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| if registration.status in [RegistrationStatus.ACTIVE, RegistrationStatus.EXPIRED]: | ||||||||||||||||||||||||||||||||||
| # Get the current time in UTC | ||||||||||||||||||||||||||||||||||
| current_time_utc = datetime.utcnow() | ||||||||||||||||||||||||||||||||||
| registration_expiry_datetime = registration.expiry_date | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| # Window in which todos should appear | ||||||||||||||||||||||||||||||||||
| days_before_expiry = DAYS_BEFORE_EXPIRY_BY_TYPE.get(registration.registration_type, 40) | ||||||||||||||||||||||||||||||||||
| threshold_datetime_start = registration_expiry_datetime - timedelta(days=days_before_expiry) | ||||||||||||||||||||||||||||||||||
| threshold_datetime_end = registration_expiry_datetime + relativedelta(years=3) | ||||||||||||||||||||||||||||||||||
| recent_submission_threshold = current_time_utc - relativedelta(years=1) + timedelta(days=days_before_expiry) | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| if threshold_datetime_start.date() <= current_time_utc.date() <= threshold_datetime_end.date(): | ||||||||||||||||||||||||||||||||||
| if renewal_window.is_open: | ||||||||||||||||||||||||||||||||||
| renewal_application = ( | ||||||||||||||||||||||||||||||||||
| Application.query.filter( | ||||||||||||||||||||||||||||||||||
| Application.registration_id == registration.id, | ||||||||||||||||||||||||||||||||||
|
|
@@ -736,25 +720,15 @@ def get_todos(registration_id): | |||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| if renewal_application: | ||||||||||||||||||||||||||||||||||
| if renewal_application.status == Application.Status.PAYMENT_DUE.value: | ||||||||||||||||||||||||||||||||||
| todos.append( | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| "task": { | ||||||||||||||||||||||||||||||||||
| "type": "REGISTRATION_RENEWAL_PAYMENT_PENDING", | ||||||||||||||||||||||||||||||||||
| "detail": renewal_application.application_number, | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||
| else: | ||||||||||||||||||||||||||||||||||
| todos.append( | ||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||
| "task": { | ||||||||||||||||||||||||||||||||||
| "type": "REGISTRATION_RENEWAL_DRAFT", | ||||||||||||||||||||||||||||||||||
| "detail": renewal_application.application_number, | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||
| is_payment_due = renewal_application.status == Application.Status.PAYMENT_DUE.value | ||||||||||||||||||||||||||||||||||
| todo_type = ( | ||||||||||||||||||||||||||||||||||
| "REGISTRATION_RENEWAL_PAYMENT_PENDING" if is_payment_due else "REGISTRATION_RENEWAL_DRAFT" | ||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||
| todos.append({"task": {"type": todo_type, "detail": renewal_application.application_number}}) | ||||||||||||||||||||||||||||||||||
| else: | ||||||||||||||||||||||||||||||||||
| # Renew is hidden once a renewal has been submitted in this window. A declined renewal doesn't | ||||||||||||||||||||||||||||||||||
| # count, so the host can renew again; create_application's 409 check also accepts a new renewal | ||||||||||||||||||||||||||||||||||
| # after a declined one, because APPLICATION_TERMINAL_STATES includes both declined statuses. | ||||||||||||||||||||||||||||||||||
| submitted_renewal_application = ( | ||||||||||||||||||||||||||||||||||
| Application.query.filter( | ||||||||||||||||||||||||||||||||||
| Application.registration_id == registration.id, | ||||||||||||||||||||||||||||||||||
|
|
@@ -763,9 +737,11 @@ def get_todos(registration_id): | |||||||||||||||||||||||||||||||||
| [ | ||||||||||||||||||||||||||||||||||
| Application.Status.DRAFT.value, | ||||||||||||||||||||||||||||||||||
| Application.Status.PAYMENT_DUE.value, | ||||||||||||||||||||||||||||||||||
| Application.Status.DECLINED.value, | ||||||||||||||||||||||||||||||||||
| Application.Status.PROVISIONALLY_DECLINED.value, | ||||||||||||||||||||||||||||||||||
| ] | ||||||||||||||||||||||||||||||||||
| ), | ||||||||||||||||||||||||||||||||||
| Application.application_date >= recent_submission_threshold, | ||||||||||||||||||||||||||||||||||
| Application.application_date >= renewal_window.start_utc, | ||||||||||||||||||||||||||||||||||
|
Collaborator
Author
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. Copilot's fix would make things worse. What a query found in Production:
Almost all of these are Why that matters.
This bug is already on main. It doesn't depend on #1964: Renew is offered, then fails with "renewal already in progress". It starts affecting about 90 hosts this month, and thousands from February.
Collaborator
Author
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.
Looking into it turned up a larger problem: the 409 check treated PROVISIONAL_REVIEW ("Approved – Provisional") as still in progress, even though that status has already extended the registration. Without a fix, those hosts couldn't renew in their next window. #1969 fixes both. |
||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||
| .order_by(Application.application_date.desc()) | ||||||||||||||||||||||||||||||||||
| .first() | ||||||||||||||||||||||||||||||||||
|
|
@@ -774,7 +750,13 @@ def get_todos(registration_id): | |||||||||||||||||||||||||||||||||
| if not submitted_renewal_application: | ||||||||||||||||||||||||||||||||||
| todos.append({"task": {"type": "REGISTRATION_RENEWAL"}}) | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| return {"todos": todos}, HTTPStatus.OK | ||||||||||||||||||||||||||||||||||
| return { | ||||||||||||||||||||||||||||||||||
| "todos": todos, | ||||||||||||||||||||||||||||||||||
| "renewalWindow": { | ||||||||||||||||||||||||||||||||||
| "startDate": renewal_window.start_date.isoformat(), | ||||||||||||||||||||||||||||||||||
| "hasStarted": not renewal_window.is_not_yet_open, | ||||||||||||||||||||||||||||||||||
|
Comment on lines
+755
to
+757
|
||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||
| }, HTTPStatus.OK | ||||||||||||||||||||||||||||||||||
| except AuthException as auth_exception: | ||||||||||||||||||||||||||||||||||
| return exception_response(auth_exception) | ||||||||||||||||||||||||||||||||||
| except Exception as exception: | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| # Copyright © 2024 Province of British Columbia | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """Renewal window rules. | ||
|
|
||
| Registration dates are stored as UTC. The renewal window opens at the beginning of the day, Vancouver time. | ||
| """ | ||
|
|
||
| from dataclasses import dataclass | ||
| from datetime import date, datetime, time, timedelta, timezone | ||
| from zoneinfo import ZoneInfo | ||
|
|
||
| from dateutil.relativedelta import relativedelta | ||
|
|
||
| from strr_api.enums.enum import RegistrationType | ||
| from strr_api.utils.date_util import DateUtil | ||
|
|
||
| DEFAULT_DAYS_BEFORE_EXPIRY = 40 | ||
| DAYS_BEFORE_EXPIRY_BY_TYPE = { | ||
| RegistrationType.STRATA_HOTEL.value: 60, | ||
| RegistrationType.HOST.value: 40, | ||
| RegistrationType.PLATFORM.value: 40, | ||
| } | ||
| YEARS_AFTER_EXPIRY = 3 | ||
|
|
||
|
|
||
| def get_days_before_expiry(registration_type: str | RegistrationType) -> int: | ||
| """Return how many days before expiry the renewal window opens for the registration type.""" | ||
| type_value = registration_type.value if isinstance(registration_type, RegistrationType) else registration_type | ||
| return DAYS_BEFORE_EXPIRY_BY_TYPE.get(type_value, DEFAULT_DAYS_BEFORE_EXPIRY) | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class RenewalWindow: | ||
| """Renewal window of a registration. The dates are Vancouver calendar dates, and the end date is inclusive.""" | ||
|
|
||
| start_date: date | ||
| end_date: date | ||
|
|
||
| @classmethod | ||
| def for_registration(cls, registration) -> "RenewalWindow": | ||
| """Return the renewal window for the registration.""" | ||
| expiry = registration.expiry_date | ||
| if expiry.tzinfo is None: | ||
| expiry = expiry.replace(tzinfo=timezone.utc) | ||
| expiry_date = DateUtil.as_legislation_timezone(expiry).date() | ||
| return cls( | ||
| start_date=expiry_date - timedelta(days=get_days_before_expiry(registration.registration_type)), | ||
| end_date=expiry_date + relativedelta(years=YEARS_AFTER_EXPIRY), | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _beginning_of_day_utc(day: date) -> datetime: | ||
| """Return the UTC instant at which the given Vancouver date begins.""" | ||
| tz = ZoneInfo(DateUtil.LEGISLATIVE_TIMEZONE) | ||
| return datetime.combine(day, time.min, tzinfo=tz).astimezone(timezone.utc) | ||
|
|
||
| @property | ||
| def start_utc(self) -> datetime: | ||
| """Return the instant the window opens.""" | ||
| return self._beginning_of_day_utc(self.start_date) | ||
|
|
||
| @property | ||
| def end_utc(self) -> datetime: | ||
| """Return the instant the window closes (exclusive).""" | ||
| return self._beginning_of_day_utc(self.end_date + timedelta(days=1)) | ||
|
|
||
| @property | ||
| def is_not_yet_open(self) -> bool: | ||
| """Return True if the window has not opened yet.""" | ||
| return datetime.now(timezone.utc) < self.start_utc | ||
|
|
||
| @property | ||
| def is_closed(self) -> bool: | ||
| """Return True if the window has ended.""" | ||
| return datetime.now(timezone.utc) >= self.end_utc | ||
|
|
||
| @property | ||
| def is_open(self) -> bool: | ||
| """Return True if now is within the window.""" | ||
| return not self.is_not_yet_open and not self.is_closed |
Uh oh!
There was an error while loading. Please reload this page.