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
18 changes: 9 additions & 9 deletions legal-api/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion legal-api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ dependencies = [
"blinker (==1.4)",
"pyjwt (==2.8.0)",

"registry_schemas @ git+https://github.com/bcgov/business-schemas.git@2.18.60#egg=registry_schemas",
"registry_schemas @ git+https://github.com/bcgov/business-schemas.git@2.18.62#egg=registry_schemas",
"sql-versioning @ git+https://github.com/bcgov/lear.git@main#subdirectory=python/common/sql-versioning",
"gcp-queue @ git+https://github.com/bcgov/sbc-connect-common.git@main#subdirectory=python/gcp-queue",
"structured-logging @ git+https://github.com/bcgov/sbc-connect-common.git@main#subdirectory=python/structured-logging"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@

from legal_api.errors import Error
from legal_api.models import Business, PartyRole
from legal_api.services.filings.validations.common_validations import validate_offices_addresses, validate_relationships
from legal_api.services.filings.validations.common_validations import validate_offices, validate_relationships


def validate(business: Business, filing_json: dict) -> Optional[Error]:
Expand All @@ -58,7 +58,9 @@ def validate(business: Business, filing_json: dict) -> Optional[Error]:
))

if filing_json["filing"][filing_type].get("offices"):
msg.extend(validate_offices_addresses(filing_json, filing_type))
allowed_offices = ["liquidationRecordsOffice"] if filing_sub_type in ["intentToLiquidate", "changeAddressLiquidator"] else []
required_offices = ["liquidationRecordsOffice"] if filing_sub_type in ["intentToLiquidate"] else []
msg.extend(validate_offices(filing_json, filing_type, allowed_offices, required_offices, False))

if msg:
return Error(HTTPStatus.BAD_REQUEST, msg)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ def validate_relationships( # noqa: PLR0913
if identifier and not allow_edits:
msg.append({"error": "Relationship edits are not allowed in this filing.", "path": f"{party_path}/{index}/entity"})
elif identifier and identifier not in party_ids:
msg.append({"error": "Relationship with this identifier does not exist.", "path": f"{party_path}/{index}/entity/identifier"})
msg.append({"error": "Relationship with this identifier is not valid for this filing.", "path": f"{party_path}/{index}/entity/identifier"})
elif not identifier and not allow_new:
msg.append({"error": "New Relationships are not allowed in this filing.", "path": f"{party_path}/{index}/entity"})

Expand Down Expand Up @@ -668,8 +668,28 @@ def validate_foreign_jurisdiction(foreign_jurisdiction: dict,
return msg


def validate_offices(filing_json: dict, filing_type: str, allowed_types: list[str], required_types: list[str], bc_req: bool) -> list:
"""Validate offices."""
msg = []
offices_dict: dict = filing_json["filing"][filing_type]["offices"]
offices_path = f"/filing/{filing_type}/offices"
for key, value in offices_dict.items():
if key not in allowed_types:
msg.append({"error": f"Invalid office {key}. Only {allowed_types} are allowed.",
"path": f"/filing/{filing_type}/offices"})
else:

msg.extend(validate_addresses(value, f"{offices_path}/{key}", bc_req))

if missing_types := [office_type for office_type in required_types if office_type not in offices_dict]:
msg.append({"error": f"Missing required offices {missing_types}.",
"path": f"/filing/{filing_type}/offices"})
return msg


def validate_offices_addresses(filing_json: dict, filing_type: str) -> list:
"""Validate optional fields in office addresses."""
# FUTURE: Update validations using this to use validate_offices instead
msg = []
offices_dict = filing_json["filing"][filing_type]["offices"]
offices_path = f"/filing/{filing_type}/offices"
Expand All @@ -690,7 +710,8 @@ def validate_parties_addresses(filing_json: dict, filing_type: str, key: str = "

def validate_addresses(
addresses: dict,
addresses_path: str
addresses_path: str,
delivery_bc_req = False
) -> list:
"""Validate optional fields in addresses."""
msg = []
Expand All @@ -710,6 +731,23 @@ def validate_addresses(
"error": _(f"{field} cannot start or end with whitespace."),
"path": f"{address_type_path}/{field}"
})

if delivery_bc_req and address_type == Address.JSON_DELIVERY:
region = address.get("addressRegion")
country = address["addressCountry"]

if region != "BC":
msg.append({"error": "Address Region must be 'BC'.",
"path": addresses_path})

try:
country = pycountry.countries.search_fuzzy(country)[0].alpha_2
if country != "CA":
raise LookupError
except LookupError:
msg.append({"error": "Address Country must be 'CA'.",
"path": addresses_path})

return msg


Expand Down
74 changes: 74 additions & 0 deletions legal-api/src/legal_api/services/filings/validations/transition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Copyright © 2025 Province of British Columbia
#
# Licensed under the BSD 3 Clause License, (the "License");
# you may not use this file except in compliance with the License.
# The template for the license can be found here
# https://opensource.org/license/bsd-3-clause/
#
# Redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Validation for the Post Restoration Transition Application filing."""
from http import HTTPStatus
from typing import Optional

from legal_api.errors import Error
from legal_api.models import Business, PartyRole
from legal_api.services.filings.validations.common_validations import (
validate_offices,
validate_relationships,
validate_share_structure,
)


def validate(business: Business, filing_json: dict) -> Optional[Error]:
"""Validate the Post Restoration Transition Application filing."""
filing_type = "transition"

msg = []

msg.extend(validate_relationships(business,
filing_json,
filing_type,
PartyRole.RoleTypes.DIRECTOR,
False,
True))

office_types = ["registeredOffice", "recordsOffice"]
msg.extend(validate_offices(filing_json,
filing_type,
office_types,
office_types,
True))

err = validate_share_structure(filing_json, filing_type, business.legal_type)
if err:
msg.extend(err)

if msg:
return Error(HTTPStatus.BAD_REQUEST, msg)

return None
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
from .restoration import validate as restoration_validate
from .schemas import validate_against_schema
from .special_resolution import validate as special_resolution_validate
from .transition import validate as transition_validate
from .transparency_register import validate as transparency_register_validate


Expand Down Expand Up @@ -229,6 +230,9 @@ def validate(business: Business, # noqa: PLR0915, PLR0912, PLR0911

elif k == Filing.FILINGS["putBackOff"].get("name"):
err = put_back_off_validate(business, filing_json)

elif k == Filing.FILINGS["transition"].get("name"):
err = transition_validate(business, filing_json)

elif k == Filing.FILINGS["transparencyRegister"].get("name"):
err = transparency_register_validate(filing_json) # pylint: disable=assignment-from-none
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@
from unittest.mock import patch

from legal_api.errors import Error
from legal_api.models.party import Party
from legal_api.models.party_role import PartyRole
from legal_api.models import Business, Party, PartyRole
from legal_api.services import flags
from legal_api.services.permissions import PermissionService
import pytest
Expand Down Expand Up @@ -53,6 +52,7 @@
validate_certified_by,
validate_court_order,
validate_email,
validate_offices,
validate_offices_addresses,
validate_parties_addresses,
validate_party_name,
Expand Down Expand Up @@ -102,6 +102,41 @@
'addressCountry': 'CA'
}

VALID_ADDRESS_BC = {
'streetAddress': 'Valid street',
'streetAddressAdditional': 'Suite 200',
'addressCity': 'Vancouver',
'addressRegion': 'BC',
'postalCode': 'V6B 1A1',
'addressCountry': 'CA'
}

VALID_ADDRESS_ON = {
'streetAddress': '88 Hawthorne',
'addressCity': 'Ottawa',
'addressRegion': 'ON',
'postalCode': 'K1N 3H9',
'addressCountry': 'CA'
}

VALID_ADDRESS_EX_CA = {
'streetAddress': 'Somewhere in the US',
'addressCity': 'New York',
'addressRegion': 'NY',
'postalCode': '10001-1234',
'addressCountry': 'US'
}

VALID_OFFICE = {
'deliveryAddress': VALID_ADDRESS_BC,
'mailingAddress': VALID_ADDRESS_ON,
}

VALID_OFFICE_EX_CA = {
'deliveryAddress': VALID_ADDRESS_EX_CA,
'mailingAddress': VALID_ADDRESS_EX_CA,
}

WHITESPACE_VALIDATED_ADDRESS_FIELDS = (
'streetAddress',
'addressCity',
Expand All @@ -110,6 +145,76 @@
)


@pytest.mark.parametrize('test_name, allowed_types, required_types, bc_req, filing_office_data, expected_errs', [
('no_office_allowed_required_success', [], [], False, {}, []),
('no_office_allowed_required_fail',
[],
[],
False,
{'recordsOffice': VALID_OFFICE},
[{'error': 'Invalid office recordsOffice. Only [] are allowed.', 'path': '/filing/transition/offices'}]),
('office_required_success',
['registeredOffice'],
['registeredOffice'],
False,
{'registeredOffice': VALID_OFFICE},
[]),
('office_required_fail',
[],
['registeredOffice'],
False,
{},
[{'error': "Missing required offices ['registeredOffice'].", 'path': '/filing/transition/offices'}]),
('multiple_office_allowed_success',
['registeredOffice', 'recordsOffice'],
['registeredOffice'],
False,
{'registeredOffice': VALID_OFFICE, 'recordsOffice': VALID_OFFICE},
[]),
('multiple_office_allowed_fail',
['registeredOffice', 'recordsOffice'],
['registeredOffice'],
False,
{'registeredOffice': VALID_OFFICE, 'recordsOffice': VALID_OFFICE, 'liquidationRecordsOffice': VALID_OFFICE},
[{'error': "Invalid office liquidationRecordsOffice. Only ['registeredOffice', 'recordsOffice'] are allowed.", 'path': '/filing/transition/offices'}]),
('multiple_office_required_success',
['registeredOffice', 'recordsOffice'],
['registeredOffice', 'recordsOffice'],
False,
{'registeredOffice': VALID_OFFICE, 'recordsOffice': VALID_OFFICE},
[]),
('multiple_office_required_fail',
['registeredOffice', 'recordsOffice'],
['registeredOffice', 'recordsOffice'],
False,
{'registeredOffice': VALID_OFFICE},
[{'error': "Missing required offices ['recordsOffice'].", 'path': '/filing/transition/offices'}]),
('office_bc_req_success',
['registeredOffice', 'recordsOffice'],
['registeredOffice'],
True,
{'registeredOffice': VALID_OFFICE},
[]),
('office_bc_req_fail',
['registeredOffice', 'recordsOffice'],
['registeredOffice'],
True,
{'registeredOffice': VALID_OFFICE_EX_CA},
[{'error': "Address Region must be 'BC'.", 'path': '/filing/transition/offices/registeredOffice'},
{'error': "Address Country must be 'CA'.", 'path': '/filing/transition/offices/registeredOffice'}]),
])
def test_validate_offices(session, test_name, allowed_types, required_types, bc_req, filing_office_data, expected_errs):
"""Test offices can be validated as expected."""
filing = copy.deepcopy(FILING_HEADER)
# NOTE: filing type could be anything for the purposes of this test
filing_type = 'transition'
filing['filing']['header']['name'] = filing_type
filing['filing'][filing_type] = {'offices': copy.deepcopy(filing_office_data)}

errs = validate_offices(filing, filing_type, allowed_types, required_types, bc_req)
assert errs == expected_errs


@pytest.mark.parametrize('filing_type, filing_data, office_type', [
('amaglamationApplication', AMALGAMATION_APPLICATION, 'registeredOffice'),
('changeOfAddress', CHANGE_OF_ADDRESS, 'registeredOffice'),
Expand Down
Loading