Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions docs/oas/registration-query.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ paths:
registrationType: HOST
status: ACTIVE
startDate: '2026-01-15T00:00:00Z'
expiryDate: '2027-01-15T00:00:00Z'
expiryDate: '2027-01-14T23:59:59Z'
updatedDate: '2026-09-07T18:42:11.203000Z'
cancelledDate: null
primaryContact:
Expand Down Expand Up @@ -189,7 +189,7 @@ paths:
registrationType: PLATFORM
status: ACTIVE
startDate: '2026-02-01T00:00:00Z'
expiryDate: '2027-02-01T00:00:00Z'
expiryDate: '2027-01-31T23:59:59Z'
updatedDate: '2026-09-08T10:15:30.123000Z'
cancelledDate: null
businessDetails:
Expand Down Expand Up @@ -240,7 +240,7 @@ paths:
registrationType: STRATA_HOTEL
status: ACTIVE
startDate: '2026-03-01T00:00:00Z'
expiryDate: '2027-03-01T00:00:00Z'
expiryDate: '2027-02-28T23:59:59Z'
updatedDate: '2026-09-09T14:22:45.542000Z'
cancelledDate: null
businessDetails:
Expand Down Expand Up @@ -482,8 +482,11 @@ components:
expiryDate:
type: string
format: date-time
description: Expiry timestamp of the registration.
example: '2027-01-15T00:00:00Z'
description: >-
End of the registration's expiry day, as stored: 23:59:59 UTC on the expiry date (4:59:59 pm
Pacific). Compare dates, not times. To tell whether a registration is valid, use `status`: it
stays ACTIVE until the registration is marked EXPIRED, after the expiry day has ended.
example: '2027-01-14T23:59:59Z'
updatedDate:
type: string
format: date-time
Expand Down Expand Up @@ -890,8 +893,11 @@ components:
expiryDate:
type: string
format: date-time
description: Expiry timestamp of the registration.
example: '2027-02-01T00:00:00Z'
description: >-
End of the registration's expiry day, as stored: 23:59:59 UTC on the expiry date (4:59:59 pm
Pacific). Compare dates, not times. To tell whether a registration is valid, use `status`: it
stays ACTIVE until the registration is marked EXPIRED, after the expiry day has ended.
example: '2027-01-31T23:59:59Z'
updatedDate:
type: string
format: date-time
Expand Down Expand Up @@ -1032,8 +1038,11 @@ components:
expiryDate:
type: string
format: date-time
description: Expiry timestamp of the registration.
example: '2027-03-01T00:00:00Z'
description: >-
End of the registration's expiry day, as stored: 23:59:59 UTC on the expiry date (4:59:59 pm
Pacific). Compare dates, not times. To tell whether a registration is valid, use `status`: it
stays ACTIVE until the registration is marked EXPIRED, after the expiry day has ended.
example: '2027-02-28T23:59:59Z'
updatedDate:
type: string
format: date-time
Expand Down
2 changes: 1 addition & 1 deletion queue_services/strr-email/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "strr-email"
version = "1.2.8"
version = "1.2.9"
description = "BC Registries - strr-email"
authors = []
license = "BSD-3-Clause"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from pathlib import Path
import re
import traceback
from typing import Any
from urllib.parse import urlencode
from zoneinfo import ZoneInfo

Expand Down
2 changes: 1 addition & 1 deletion strr-api/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "strr-api"
version = "0.3.48"
version = "0.3.49"
description = ""
authors = ["thorwolpert <thor@wolpert.ca>"]
license = "BSD 3-Clause"
Expand Down
2 changes: 2 additions & 0 deletions strr-api/src/strr_api/enums/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ class ErrorMessage(Enum):
"Continue with your existing renewal application, or wait until it reaches a final decision."
)
RENEWAL_APPLICATION_NO_REGISTRATION_ID = "Renewal application does not have a linked registration id."
RENEWAL_WINDOW_NOT_OPEN = "The renewal period for this registration has not started yet."
RENEWAL_WINDOW_CLOSED = "The renewal period for this registration has ended."
EXAMINER_NOTE_TEXT_REQUIRED = "Note text is required."
EXAMINER_NOTE_TEXT_TOO_LONG = "Note text exceeds maximum length."
EXAMINER_NOTE_APPLICATION_REGISTERED = (
Expand Down
28 changes: 26 additions & 2 deletions strr-api/src/strr_api/resources/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -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",
)
Comment thread
Copilot marked this conversation as resolved.
Resolved

if application is None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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(
Expand Down
60 changes: 21 additions & 39 deletions strr-api/src/strr_api/resources/registrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"]


Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,

@severinbeauvais severinbeauvais Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The 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:

Renewal status Registration Window open now Renewals Registrations
PROVISIONAL_REVIEW ACTIVE no 12,112 11,976
PROVISIONAL_REVIEW_NOC_EXPIRED ACTIVE no 8 8
NOC_EXPIRED ACTIVE no 1 1

Almost all of these are PROVISIONAL_REVIEW, which the app shows hosts as "Approved – Provisional". The auto-approval sets it on a renewal when it renews the registration provisionally (provisional_extension_applied), and staff may review it later. So these renewals are effectively approved. They're submitted "before the window" only because the renewal moved the expiry, and with it the window, a year ahead. None was in a genuinely pending status, such as PAID, FULL_REVIEW or ADDITIONAL_INFO_REQUESTED.

Why that matters. APPLICATION_TERMINAL_STATES doesn't include PROVISIONAL_REVIEW, so the 409 check treats these renewals as still in progress. When their next windows open, it will refuse to start a new renewal. Their windows open soon:

Next window opens Registrations
Dec 2026 90
Jan 2027 668
Feb 2027 1,954
Mar 2027 5,470
Apr 2027 onward about 3,800

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.
Copilot's fix would hide Renew from all of them, which is consistent with the 409 check but worse: they couldn't renew at all, and nothing would tell them why.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

/todos only looked at renewals submitted in the current window, while the 409 check blocks on any renewal that isn't finished, whenever it was submitted. So /todos could offer Renew to a host whose submission would then get a 409.

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. /todos and the 409 check now share one set of status lists, and a provisionally approved renewal, including its NOC statuses, counts as approved. #1969 merges into this feature branch, so this PR will include it.

)
.order_by(Application.application_date.desc())
.first()
Expand All @@ -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:
Expand Down
91 changes: 91 additions & 0 deletions strr-api/src/strr_api/utils/renewal_window.py
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
7 changes: 7 additions & 0 deletions strr-api/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@

from strr_api import db as _db
from strr_api.config import Testing
from strr_api.utils.renewal_window import RenewalWindow


@contextmanager
Expand Down Expand Up @@ -139,3 +140,9 @@ def remove(self):
transaction.rollback()
connection.close()
_db.session = original_session_lookup


@pytest.fixture
def renewal_window_open(monkeypatch):
"""Let renewals be submitted regardless of the registration expiry date."""
monkeypatch.setattr(RenewalWindow, "is_not_yet_open", property(lambda self: False))
Loading
Loading