Skip to content
Merged
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
2 changes: 1 addition & 1 deletion legal-api/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "legal-api"
version = "3.1.82"
version = "3.1.83"
description = ""
authors = [
{name = "thor",email = "1042854+thorwolpert@users.noreply.github.com"}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def validate(business: Business, cod: dict) -> Error:
msg += validate_appointment_date(business, cod)
msg += validate_directors_name(cod)
msg += validate_directors_addresses(business, cod)
msg += validate_directors_ids(business, cod)

msg += validate_effective_date(business, cod)

Expand Down Expand Up @@ -234,6 +235,70 @@ def validate_directors_addresses(business: Business, cod: dict) -> list:
return msg


def _as_party_id(value) -> int | None:
"""Return the officer id as an int, or None when it is not an integer or a numeric string."""
if isinstance(value, bool) or not isinstance(value, int | str):
return None
try:
return int(value)
except ValueError:
return None


def validate_directors_ids(business: Business, cod: dict) -> list:
"""Return error messages if an existing director's officer id is missing or invalid.

The filer updates existing directors by officer.id (the party id), so every director that is
not being appointed must carry one that matches a director currently active on the business.

Rules:
- Appointed directors are new and need no officer.id.
- Directors with no actions are unchanged; the filer ignores them, so they are not checked.
- Every other director must have officer.id, as an integer or a string that casts to one.
- That id must belong to a director currently active on the business.
- COLIN-sourced filings carry no party ids; the filer matches those directors by name.
"""
if cod["filing"]["header"].get("source") == Filing.Source.COLIN.value:
return []

msg = []
directors = cod["filing"]["changeOfDirectors"]["directors"]
active_ids = None

for idx, director in enumerate(directors):
actions = director.get("actions") or []
if not actions or "appointed" in actions:
continue

party_id = director.get("officer", {}).get("id")
path = f"/filing/changeOfDirectors/directors/{idx}/officer/id"

if party_id is None:
msg.append({
"error": babel("Director id is required for an existing director."),
"path": path
})
continue

if (party_id := _as_party_id(party_id)) is None:
msg.append({
"error": babel("Director id must be an integer."),
"path": path
})
continue

if active_ids is None:
roles = PartyRole.get_party_roles(business.id, LegislationDatetime.datenow(), DIRECTOR_ROLE_TYPE)
active_ids = {role.party_id for role in roles}
if party_id not in active_ids:
msg.append({
"error": babel("Director id does not match an active director of this business."),
"path": path
})

return msg


def validate_effective_date(business: Business, cod: dict) -> list:
"""Return an error or warning message based on the effective date validation rules.

Expand Down Expand Up @@ -364,10 +429,12 @@ def validate_cod_relationships(business: Business, cod: dict) -> list:
def validate_relationship_actions(cod: dict) -> list:
"""Return error messages if a relationship's explicit actions are inconsistent.

Rules (relationships with no actions are skipped — change semantics are derived):
Rules:
- ADDED implies a new director: no entity identifier is allowed.
- Edit/removal actions require an entity identifier (an existing director).
- ADDED cannot be combined with an edit/removal action.
- With no actions the change is derived: a cessation date without an entity identifier
is a cease with no director to cease.
"""
msg = []
relationships = cod["filing"]["changeOfDirectors"]["relationships"]
Expand All @@ -376,11 +443,16 @@ def validate_relationship_actions(cod: dict) -> list:

for idx, relationship in enumerate(relationships):
actions = set(relationship.get("actions") or [])
identifier = relationship.get("entity", {}).get("identifier")
if not actions:
if not identifier and "ceased" in map_relationship_actions(relationship):
msg.append({
"error": babel("An entity identifier is required to change or cease a director."),
"path": f"/filing/changeOfDirectors/relationships/{idx}/entity/identifier"
})
continue

path = f"/filing/changeOfDirectors/relationships/{idx}/actions"
identifier = relationship.get("entity", {}).get("identifier")
edits = actions & edit_actions

if "ADDED" in actions and edits:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,66 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test Suite for the Change of Director filing validations."""
import copy

from business_common.utils import LegislationDatetime, datetime
from business_model.models import Address, Business, PartyRole
from registry_schemas.example_data import FILING_HEADER
from tests.unit.models import factory_business, factory_party_role

VALID_ADDRESS = {
'streetAddress': '123 A St',
'addressCity': 'Vancouver',
'addressRegion': 'BC',
'addressCountry': 'CA',
'postalCode': 'V5K0A1'
}

DIRECTOR_OFFICER = {
'firstName': 'Joe',
'lastName': 'Swanson',
'middleInitial': 'P',
'partyType': 'person',
'organizationName': ''
}


def setup_business(identifier: str,
founding_date: datetime,
legal_type: str = Business.LegalTypes.COOP.value,
last_cod_date: datetime = None) -> Business:
"""Create a business whose last COD date defaults to its founding date."""
business = factory_business(identifier, founding_date, None, legal_type)
business.last_cod_date = last_cod_date or founding_date
business.save()
return business


def add_director(business: Business, appointment_date: str, cessation_date: str = None) -> int:
"""Add a director role to the business and return the party id."""
role = factory_party_role(
Address.create_address(VALID_ADDRESS),
Address.create_address(VALID_ADDRESS),
DIRECTOR_OFFICER,
appointment_date,
cessation_date,
PartyRole.RoleTypes.DIRECTOR)
business.party_roles.append(role)
business.save()
return role.party_id


def build_cod_filing(identifier: str, cod: dict, now: datetime = None) -> dict:
"""Build a changeOfDirectors filing envelope effective at the start of the given day, as the UI does."""
now = now or datetime.utcnow()
effective_date = LegislationDatetime.as_legislation_timezone(now)
effective_date = effective_date.replace(hour=0, minute=0, second=0, microsecond=0)
effective_date = LegislationDatetime.as_utc_timezone(effective_date)

filing = copy.deepcopy(FILING_HEADER)
filing['filing']['header']['date'] = now.date().isoformat()
filing['filing']['header']['effectiveDate'] = effective_date.isoformat()
filing['filing']['header']['name'] = 'changeOfDirectors'
filing['filing']['business']['identifier'] = identifier
filing['filing']['changeOfDirectors'] = cod
return filing
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.
"""Test Change of Director basic validations."""
import copy
import random
from datetime import timezone
from http import HTTPStatus

Expand All @@ -21,9 +22,9 @@
from freezegun import freeze_time

from business_common.utils import LegislationDatetime, datetime
from business_model.models import Business
from legal_api.services.filings import validate
from tests.unit.services.filings.validations import lists_are_equal
from tests.unit.services.filings.validations.change_of_director import add_director, setup_business
from registry_schemas.example_data import CHANGE_OF_DIRECTORS, FILING_HEADER


Expand Down Expand Up @@ -112,12 +113,10 @@ def test_validate_cod_basic(session, test_name, now,
expected_code, expected_msg):
"""Assert that a basic COD can be validated."""
# setup
identifier = 'CP1234567'
founding_date = now - datedelta.YEAR
business = Business(identifier=identifier,
last_ledger_timestamp=founding_date,
founding_date=founding_date,
last_cod_date=founding_date)
business = setup_business(f'CP{random.randint(1000000, 9999999)}', founding_date)
party_id = add_director(business, founding_date.date().isoformat())
identifier = business.identifier

# convert 'now' to an effective date with 0 time in the legislation timezone, same as the UI does
effective_date = LegislationDatetime.as_legislation_timezone(now)
Expand All @@ -138,6 +137,8 @@ def test_validate_cod_basic(session, test_name, now,

cod['directors'][0]['mailingAddress'] = mailing_address_1
cod['directors'][1]['mailingAddress'] = mailing_address_2
for director in cod['directors']:
director['officer']['id'] = party_id

f['filing']['changeOfDirectors'] = cod

Expand Down Expand Up @@ -258,15 +259,10 @@ def test_validate_whitespace_cod_address_fields(session, test_name,
"""Validate that directors' address fields cannot contain leading or trailing whitespace."""
# setup
now = datetime(2025, 1, 1, tzinfo=timezone.utc)
identifier = "CP7654321"
founding_date = now - datedelta.YEAR

business = Business(
identifier=identifier,
last_ledger_timestamp=founding_date,
founding_date=founding_date,
last_cod_date=founding_date
)
business = setup_business(f'CP{random.randint(1000000, 9999999)}', founding_date)
party_id = add_director(business, founding_date.date().isoformat())
identifier = business.identifier

f = copy.deepcopy(FILING_HEADER)
f["filing"]["header"]["date"] = now.date().isoformat()
Expand All @@ -278,6 +274,8 @@ def test_validate_whitespace_cod_address_fields(session, test_name,

cod['directors'][0]['deliveryAddress'] = delivery_address
cod['directors'][0]['mailingAddress'] = mailing_address
for director in cod['directors']:
director['officer']['id'] = party_id

f['filing']['changeOfDirectors'] = cod

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.
"""Test Change of Director director date validations. See rules in change_of_directors.py."""
import copy
import random
from datetime import timezone
from http import HTTPStatus

Expand All @@ -27,6 +28,7 @@
from legal_api.services.filings.validations.change_of_directors import get_cod_date_bounds
from registry_schemas.example_data import CHANGE_OF_DIRECTORS, FILING_HEADER
from tests.unit.services.filings.validations import lists_are_equal
from tests.unit.services.filings.validations.change_of_director import add_director, setup_business

NOW = datetime(2025, 1, 1, 12, 0, tzinfo=timezone.utc)
FOUNDING_DATE = NOW - datedelta.YEAR
Expand All @@ -35,13 +37,10 @@


def common_setup_cod(identifier: str, actions, cessationDate=None, appointmentDate=None, last_cod_date=LAST_COD_DATE_SAME_AS_FOUNDING):
"""Set up the data for COD director date validation tests."""
business = Business(
identifier=identifier,
last_ledger_timestamp=FOUNDING_DATE,
founding_date=FOUNDING_DATE,
last_cod_date=last_cod_date
)
"""Set up the data for COD director date validation tests: a coop with one active director."""
identifier = f'{identifier[:2]}{random.randint(1000000, 9999999)}'
business = setup_business(identifier, FOUNDING_DATE, last_cod_date=last_cod_date)
party_id = add_director(business, FOUNDING_DATE.date().isoformat())

f = copy.deepcopy(FILING_HEADER)
f['filing']['header']['date'] = NOW.date().isoformat()
Expand All @@ -54,6 +53,9 @@ def common_setup_cod(identifier: str, actions, cessationDate=None, appointmentDa
cod["directors"][0]["cessationDate"] = cessationDate
cod["directors"][0]["appointmentDate"] = appointmentDate or FOUNDING_DATE.date().isoformat()
cod["directors"][1]["appointmentDate"] = FOUNDING_DATE.date().isoformat()
for director in cod["directors"]:
if "appointed" not in director["actions"]:
director["officer"]["id"] = party_id
f['filing']['changeOfDirectors'] = cod

return business, f
Expand Down
Loading