def test_business_relationships_json(session): """Assert that the business model is saved correctly.""" from legal_api.models import Address, Office business = Business(legal_name='legal_name', founding_date=EPOCH_DATETIME, last_ledger_timestamp=EPOCH_DATETIME, identifier='CP1234567', last_modified=EPOCH_DATETIME) office = Office(office_type='registeredOffice') mailing_address = Address(city='Test City', address_type=Address.MAILING, business_id=business.id) office.addresses.append(mailing_address) business.offices.append(office) business.save() assert business.mailing_address.one_or_none() delivery_address = Address(city='Test City', address_type=Address.DELIVERY, business_id=business.id) office.addresses.append(delivery_address) business.save() assert business.delivery_address.one_or_none()
def test_address_save(session): """Assert that the address saves correctly.""" identifier = 'CP1234567' address = Address(city='Test City', street=f'{identifier}-Test Street', postal_code='T3S3T3', country='TA', region='BC', address_type=Address.MAILING) address.save() assert address.id
def create_delivery_address(delivery_json): delivery_address = Address() delivery_address.address_type = Address.DELIVERY delivery_address.city = delivery_json['addressCity'] # delivery_address.country = delivery_json['addressCountry'] delivery_address.country = 'CA' delivery_address.delivery_instructions = delivery_json['deliveryInstructions'] delivery_address.postal_code = delivery_json['postalCode'] # delivery_address.region = delivery_json['addressRegion'] delivery_address.region = 'BC' delivery_address.street = delivery_json['streetAddress'] delivery_address.street_additional = delivery_json['streetAddressAdditional'] return delivery_address
def create_address(address_json: dict, address_type: Address.ADDRESS_TYPES) -> Address: """Create a new address in lear via the model.""" address = Address() address.address_type = address_type address.city = address_json['addressCity'] address.country = pycountry.countries.search_fuzzy( address_json['addressCountry'])[0].alpha_2 address.delivery_instructions = address_json['deliveryInstructions'] address.postal_code = address_json['postalCode'] address.region = address_json['addressRegion'] address.street = address_json['streetAddress'] address.street_additional = address_json['streetAddressAdditional'] return address
def create_address(address_info: Dict, address_type: str) -> Address: """Create an address.""" if not address_info: return Address() address = Address( street=address_info.get('streetAddress'), street_additional=address_info.get('streetAddressAdditional'), city=address_info.get('addressCity'), region=address_info.get('addressRegion'), country=pycountry.countries.search_fuzzy( address_info.get('addressCountry'))[0].alpha_2, postal_code=address_info.get('postalCode'), delivery_instructions=address_info.get('deliveryInstructions'), address_type=address_type) return address
def test_post_valid_ar(session, client, jwt): """Assert that a unpaid filing can be posted.""" from legal_api.models import Address, Filing identifier = 'CP7654321' business = factory_business(identifier) mailing_address = Address(city='Test Mailing City', address_type=Address.MAILING) business.mailing_address.append(mailing_address) business.save() rv = client.post(f'/api/v1/businesses/{identifier}/filings', json=AR_FILING, headers=create_header(jwt, [STAFF_ROLE], identifier)) # check return assert rv.status_code == HTTPStatus.CREATED assert not rv.json.get('errors') assert rv.json['filing']['header']['filingId'] assert rv.json['filing']['header']['paymentToken'] assert rv.json['filing']['header']['paymentToken'] == '153' # check stored filing filing = Filing.get_filing_by_payment_token( rv.json['filing']['header']['paymentToken']) assert filing assert filing.status == Filing.Status.PENDING.value
def create_business_address(business, type): """Create an address.""" from legal_api.models import Address address = Address( city='Test City', street=f'{business.identifier}-Test Street', postal_code='T3S3T3', country='TA', region='BC', ) if type == 'mailing': address.address_type = Address.MAILING business.mailing_address.append(address) else: address.address_type = Address.DELIVERY business.delivery_address.append(address) business.save() return business
def create_business_address(business, type): """Create an address.""" from legal_api.models import Address, Office address = Address( city='Test City', street=f'{business.identifier}-Test Street', postal_code='T3S3T3', country='TA', region='BC', ) if type == 'mailing': address.address_type = Address.MAILING else: address.address_type = Address.DELIVERY office = Office(office_type='registeredOffice') office.addresses.append(address) business.offices.append(office) business.save() return business
def factory_business_mailing_address(business): """Create a business entity.""" address = Address(city='Test City', street=f'{business.identifier}-Test Street', postal_code='T3S3T3', country='TA', region='BC', address_type=Address.MAILING) business.mailing_address.append(address) business.save() return business
def create_director(director): """Create a director.""" from legal_api.models import Address, Director new_address = Address( street=director['deliveryAddress']['streetAddress'], city=director['deliveryAddress']['addressCity'], country='CA', postal_code=director['deliveryAddress']['postalCode'], region=director['deliveryAddress']['addressRegion'], delivery_instructions=director['deliveryAddress'].get( 'deliveryInstructions', '').upper()) new_address.save() new_director = Director( first_name=director['officer'].get('firstName', '').upper(), last_name=director['officer'].get('lastName', '').upper(), middle_initial=director['officer'].get('middleInitial', '').upper(), appointment_date=director['appointmentDate'], cessation_date=None, delivery_address=new_address) new_director.save() return new_director
def add_business_addresses(business, offices_json): for office_type in offices_json: delivery_address = create_delivery_address(offices_json[office_type]['deliveryAddress']) #business.delivery_address.append(delivery_address) mailing_address = None if offices_json[office_type]['mailingAddress'] == None: # clone delivery to mailing mailing_address = copy.deepcopy(delivery_address) else: mailing_address = Address() mailing_json = offices_json[office_type]['mailingAddress'] mailing_address.city = mailing_json['addressCity'] mailing_address.country = pycountry.countries.search_fuzzy( mailing_json['addressCountry'])[0].alpha_2 mailing_address.delivery_instructions = mailing_json['deliveryInstructions'] mailing_address.postal_code = mailing_json['postalCode'] mailing_address.region = mailing_json['addressRegion'] mailing_address.street = mailing_json['streetAddress'] mailing_address.street_additional = mailing_json['streetAddressAdditional'] mailing_address.address_type = Address.MAILING create_office(business, [mailing_address, delivery_address], office_type)
def update_address(address: Address, new_info: dict) -> Address: """Update address with new info.""" address.street = new_info.get('streetAddress') address.street_additional = new_info.get('streetAddressAdditional') address.city = new_info.get('addressCity') address.region = new_info.get('addressRegion') address.country = pycountry.countries.search_fuzzy(new_info.get('addressCountry'))[0].alpha_2 address.postal_code = new_info.get('postalCode') address.delivery_instructions = new_info.get('deliveryInstructions') return address
def test_mailing_address_save_to_business(session): """Assert that the address saves correctly.""" identifier = 'CP1234567' business = factory_business(identifier) address = Address(city='Test City', street=f'{identifier}-Test Street', postal_code='T3S3T3', country='TA', region='BC', address_type=Address.MAILING) business.mailing_address.append(address) business.save() mailing = business.mailing_address.one_or_none() assert mailing.id
def test_address_json(session): """Assert that the address renders our json format correctly.""" identifier = 'CP1234567' address = Address(city='Test City', street=f'{identifier}-Test Street', postal_code='T3S3T3', country='TA', region='BC', address_type=Address.MAILING) address_json = { 'streetAddress': address.street, 'streetAddressAdditional': address.street_additional, 'addressType': address.address_type, 'addressCity': address.city, 'addressRegion': address.region, 'addressCountry': address.country, 'postalCode': address.postal_code, 'deliveryInstructions': address.delivery_instructions } assert address.json == address_json
def _create_invoice(business: Business, # pylint: disable=too-many-locals filing: Filing, filing_types: list, user_jwt: JwtManager, payment_account_id: str = None) \ -> Tuple[int, dict, int]: """Create the invoice for the filing submission. Returns: { int: the paymentToken (id), or None dict: a dict of errors, or None int: the HTTPStatus error code, or None } """ payment_svc_url = current_app.config.get('PAYMENT_SVC_URL') if filing.filing_type == Filing.FILINGS[ 'incorporationApplication'].get('name'): mailing_address = Address.create_address( filing.json['filing']['incorporationApplication']['offices'] ['registeredOffice']['mailingAddress']) corp_type = filing.json['filing']['business'].get( 'legalType', Business.LegalTypes.BCOMP.value) try: business.legal_name = filing.json['filing'][ 'incorporationApplication']['nameRequest']['legalName'] except KeyError: business.legal_name = business.identifier else: mailing_address = business.mailing_address.one_or_none() corp_type = business.legal_type if business.legal_type else \ filing.json['filing']['business'].get('legalType') payload = { 'businessInfo': { 'businessIdentifier': f'{business.identifier}', 'corpType': f'{corp_type}', 'businessName': f'{business.legal_name}', 'contactInfo': { 'city': mailing_address.city, 'postalCode': mailing_address.postal_code, 'province': mailing_address.region, 'addressLine1': mailing_address.street, 'country': mailing_address.country } }, 'filingInfo': { 'filingTypes': filing_types } } folio_number = filing.json['filing']['header'].get('folioNumber', None) if folio_number: payload['filingInfo']['folioNumber'] = folio_number if user_jwt.validate_roles([STAFF_ROLE]) or \ user_jwt.validate_roles([SYSTEM_ROLE]): account_info = {} routing_slip_number = get_str(filing.filing_json, 'filing/header/routingSlipNumber') if routing_slip_number: account_info['routingSlip'] = routing_slip_number bcol_account_number = get_str(filing.filing_json, 'filing/header/bcolAccountNumber') if bcol_account_number: account_info['bcolAccountNumber'] = bcol_account_number dat_number = get_str(filing.filing_json, 'filing/header/datNumber') if dat_number: account_info['datNumber'] = dat_number if account_info: payload['accountInfo'] = account_info try: token = user_jwt.get_token_auth_header() headers = { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' } rv = requests.post(url=payment_svc_url, json=payload, headers=headers, timeout=20.0) except (exceptions.ConnectionError, exceptions.Timeout) as err: current_app.logger.error( f'Payment connection failure for {business.identifier}: filing:{filing.id}', err) return { 'message': 'unable to create invoice for payment.' }, HTTPStatus.PAYMENT_REQUIRED if rv.status_code in (HTTPStatus.OK, HTTPStatus.CREATED): pid = rv.json().get('id') filing.payment_token = pid filing.payment_status_code = rv.json().get('statusCode', '') filing.payment_account = payment_account_id filing.save() return { 'isPaymentActionRequired': rv.json().get('isPaymentActionRequired', False) }, HTTPStatus.CREATED if rv.status_code == HTTPStatus.BAD_REQUEST: # Set payment error type used to retrieve error messages from pay-api error_type = rv.json().get('type') filing.payment_status_code = error_type filing.save() return { 'payment_error_type': error_type, 'message': rv.json().get('detail') }, HTTPStatus.PAYMENT_REQUIRED return { 'message': 'unable to create invoice for payment.' }, HTTPStatus.PAYMENT_REQUIRED
def _create_invoice(business: Business, filing: Filing, filing_types: list, user_jwt: JwtManager) \ -> Tuple[int, dict, int]: """Create the invoice for the filing submission. Returns: { int: the paymentToken (id), or None dict: a dict of errors, or None int: the HTTPStatus error code, or None } """ payment_svc_url = current_app.config.get('PAYMENT_SVC_URL') if filing.filing_type == Filing.FILINGS[ 'incorporationApplication'].get('name'): mailing_address = Address.create_address( filing.json['filing']['incorporationApplication']['offices'] ['registeredOffice']['mailingAddress']) corp_type = filing.json['filing']['incorporationApplication'][ 'nameRequest']['legalType'] else: mailing_address = business.mailing_address.one_or_none() corp_type = business.identifier[:-7] payload = { 'paymentInfo': { 'methodOfPayment': 'CC' }, 'businessInfo': { 'businessIdentifier': f'{business.identifier}', 'corpType': f'{corp_type}', 'businessName': f'{business.legal_name}', 'contactInfo': { 'city': mailing_address.city, 'postalCode': mailing_address.postal_code, 'province': mailing_address.region, 'addressLine1': mailing_address.street, 'country': mailing_address.country } }, 'filingInfo': { 'filingTypes': filing_types } } if user_jwt.validate_roles([STAFF_ROLE]): routing_slip_number = get_str(filing.filing_json, 'filing/header/routingSlipNumber') if routing_slip_number: payload['accountInfo'] = {'routingSlip': routing_slip_number} try: token = user_jwt.get_token_auth_header() headers = { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' } rv = requests.post(url=payment_svc_url, json=payload, headers=headers, timeout=20.0) except (exceptions.ConnectionError, exceptions.Timeout) as err: current_app.logger.error( f'Payment connection failure for {business.identifier}: filing:{filing.id}', err) return { 'message': 'unable to create invoice for payment.' }, HTTPStatus.PAYMENT_REQUIRED if rv.status_code == HTTPStatus.OK or rv.status_code == HTTPStatus.CREATED: pid = rv.json().get('id') filing.payment_token = pid filing.save() return None, None if rv.status_code == HTTPStatus.BAD_REQUEST: return { 'code': rv.json().get('code'), 'message': rv.json().get('message') }, HTTPStatus.PAYMENT_REQUIRED return { 'message': 'unable to create invoice for payment.' }, HTTPStatus.PAYMENT_REQUIRED