def _create_business(incorporation_body, client_request): """Create a business from an incorporation filing.""" # Check that there is a JSON filing if not incorporation_body: return None, {'message': f'No filing json data in body of post for incorporation'}, \ HTTPStatus.BAD_REQUEST temp_corp_num = incorporation_body['filing']['incorporationApplication']['nameRequest']['nrNumber'] # check authorization if not authorized(temp_corp_num, jwt, action=['edit']): return None, {'message': f'You are not authorized to incorporate for {temp_corp_num}.'}, \ HTTPStatus.UNAUTHORIZED # Ensure there are no current businesses with the NR/random identifier business = Business.find_by_identifier(temp_corp_num) if business: return None, {'message': f'Incorporation filing for {temp_corp_num} already exists'}, \ HTTPStatus.BAD_REQUEST # Create an empty business record, to be updated by the filer business = Business() business.identifier = temp_corp_num business.save() return business, None, (HTTPStatus.CREATED if (client_request.method == 'POST') else HTTPStatus.ACCEPTED)
def delete(identifier, filing_id=None): """Delete a filing from the business.""" if not filing_id: return ({ 'message': _('No filing id provided for:') + identifier }, HTTPStatus.BAD_REQUEST) # check authorization if not authorized(identifier, jwt, action=['edit']): return jsonify({'message': _('You are not authorized to delete a filing for:') + identifier}),\ HTTPStatus.UNAUTHORIZED filing = Business.get_filing_by_id(identifier, filing_id) if not filing: return jsonify({'message': _('Filing Not Found.')}), \ HTTPStatus.NOT_FOUND try: filing.delete() return jsonify({'message': _('Filing deleted.')}), \ HTTPStatus.OK except BusinessException as err: return jsonify({'errors': [ { 'error': err.error }, ]}), err.status_code return {}, HTTPStatus.NOT_IMPLEMENTED
def get_documents(identifier: str, filing_id: int, legal_filing_name: str = None): """Return a JSON object with meta information about the Service.""" # basic checks if not authorized(identifier, jwt, [ 'view', ]): return jsonify(message=get_error_message(ErrorCode.NOT_AUTHORIZED, **{ 'identifier': identifier })), HTTPStatus.UNAUTHORIZED if identifier.startswith('T'): filing_model = FilingModel.get_temp_reg_filing(identifier) business = Business.find_by_internal_id(filing_model.business_id) else: business = Business.find_by_identifier(identifier) if not business and not identifier.startswith('T'): return jsonify(message=get_error_message(ErrorCode.MISSING_BUSINESS, ** {'identifier': identifier })), HTTPStatus.NOT_FOUND if not (filing := Filing.get(identifier, filing_id)): return jsonify(message=get_error_message( ErrorCode.FILING_NOT_FOUND, **{ 'filing_id': filing_id, 'identifier': identifier })), HTTPStatus.NOT_FOUND
def patch(identifier, filing_id=None): """Cancel the payment and resets the filing status to DRAFT.""" if not filing_id: return ({'message': _('No filing id provided for:') + identifier}, HTTPStatus.BAD_REQUEST) # check authorization if not authorized(identifier, jwt, action=['edit']): return jsonify({'message': _('You are not authorized to delete a filing for:') + identifier}), \ HTTPStatus.UNAUTHORIZED filing = Business.get_filing_by_id(identifier, filing_id) if not filing: return jsonify({'message': ('Filing Not Found.')}), \ HTTPStatus.NOT_FOUND try: payment_svc_url = '{}/{}'.format(current_app.config.get('PAYMENT_SVC_URL'), filing.payment_token) token = jwt.get_token_auth_header() headers = {'Authorization': 'Bearer ' + token} rv = requests.delete(url=payment_svc_url, headers=headers, timeout=20.0) if rv.status_code == HTTPStatus.OK or rv.status_code == HTTPStatus.ACCEPTED: filing.reset_filing_to_draft() except (exceptions.ConnectionError, exceptions.Timeout) as err: current_app.logger.error(f'Payment connection failure for {identifier}: filing:{filing.id}', err) return {'message': 'Unable to cancel payment for the filing.'}, HTTPStatus.INTERNAL_SERVER_ERROR except BusinessException as err: return {'message': err.error}, err.status_code return jsonify(filing.json), HTTPStatus.ACCEPTED
def put(identifier, filing_id): # pylint: disable=too-many-return-statements """Modify an incomplete filing for the business.""" # basic checks err_msg, err_code = ListFilingResource._put_basic_checks(identifier, filing_id, request) if err_msg: return jsonify({'errors': [err_msg, ]}), err_code json_input = request.get_json() # check authorization if not authorized(identifier, jwt, action=['edit']): return jsonify({'message': f'You are not authorized to submit a filing for {identifier}.'}), \ HTTPStatus.UNAUTHORIZED draft = (request.args.get('draft', None).lower() == 'true') \ if request.args.get('draft', None) else False only_validate = (request.args.get('only_validate', None).lower() == 'true') \ if request.args.get('only_validate', None) else False # validate filing if not draft: business = Business.find_by_identifier(identifier) err = validate(business, json_input) # err_msg, err_code = ListFilingResource._validate_filing_json(request) if err or only_validate: if err: json_input['errors'] = err.msg return jsonify(json_input), err.code return jsonify(json_input), HTTPStatus.OK # save filing, if it's draft only then bail user = User.get_or_create_user_by_jwt(g.jwt_oidc_token_info) business, filing, err_msg, err_code = ListFilingResource._save_filing(request, identifier, user, filing_id) if err_msg or draft: reply = filing.json if filing else json_input reply['errors'] = [err_msg, ] return jsonify(reply), err_code or \ (HTTPStatus.CREATED if (request.method == 'POST') else HTTPStatus.ACCEPTED) # if filing is from COLIN, place on queue and return if jwt.validate_roles([COLIN_SVC_ROLE]): err_msg, err_code = ListFilingResource._process_colin_filing(identifier, json_input) return jsonify(err_msg), err_code # create invoice ?? if not draft: filing_types = ListFilingResource._get_filing_types(filing.filing_json) err_msg, err_code = ListFilingResource._create_invoice(business, filing, filing_types, jwt) if err_code: reply = filing.json reply['errors'] = [err_msg, ] return jsonify(reply), err_code # all done return jsonify(filing.json),\ (HTTPStatus.CREATED if (request.method == 'POST') else HTTPStatus.ACCEPTED)
def post(identifier, filing_id): """Create a new comment for the filing.""" # basic checks err_msg, err_code = CommentResource._basic_checks( identifier, filing_id, request) if err_msg: return jsonify(err_msg), err_code json_input = request.get_json() # check authorization if not authorized(identifier, jwt, action=['add_comment']): return jsonify({'message': f'You are not authorized to submit a comment for {identifier}.'}), \ HTTPStatus.UNAUTHORIZED # validate comment err = validate(json_input, True) if err: json_input['errors'] = err.msg return jsonify(json_input), err.code # confirm that the filing ID in the URL is the same as in the json if json_input['comment']['filingId'] != filing_id: json_input['errors'] = [ { 'error': 'Invalid filingId in request' }, ] return jsonify(json_input), HTTPStatus.BAD_REQUEST # save comment user = User.get_or_create_user_by_jwt(g.jwt_oidc_token_info) try: comment = Comment() comment.comment = json_input['comment']['comment'] comment.staff_id = user.id comment.filing_id = filing_id comment.timestamp = datetime.datetime.utcnow() comment.save() except BusinessException as err: reply = json_input reply['errors'] = [ { 'error': err.error }, ] return jsonify(reply), err.status_code or \ (HTTPStatus.CREATED if (request.method == 'POST') else HTTPStatus.ACCEPTED) # all done return jsonify(comment.json), HTTPStatus.CREATED
def delete(identifier, filing_id=None): # pylint: disable=too-many-branches """Delete a filing from the business.""" if not filing_id: return ({ 'message': _('No filing id provided for:') + identifier }, HTTPStatus.BAD_REQUEST) # check authorization if not authorized(identifier, jwt, action=['edit']): return jsonify({'message': _('You are not authorized to delete a filing for:') + identifier}),\ HTTPStatus.UNAUTHORIZED if identifier.startswith('T'): filing = Filing.get_temp_reg_filing(identifier, filing_id) else: filing = Business.get_filing_by_id(identifier, filing_id) if not filing: return jsonify({'message': _('Filing Not Found.')}), HTTPStatus.NOT_FOUND if filing.deletion_locked: # should not be deleted return ListFilingResource._create_deletion_locked_response( identifier, filing) try: ListFilingResource._delete_from_minio(filing) filing.delete() except BusinessException as err: return jsonify({'errors': [ { 'error': err.error }, ]}), err.status_code if identifier.startswith('T'): bootstrap = RegistrationBootstrap.find_by_identifier(identifier) if bootstrap: deregister_status = RegistrationBootstrapService.deregister_bootstrap( bootstrap) delete_status = RegistrationBootstrapService.delete_bootstrap( bootstrap) if deregister_status != HTTPStatus.OK or delete_status != HTTPStatus.OK: current_app.logger.error( 'Unable to deregister and delete temp reg:', identifier) return jsonify({'message': _('Filing deleted.')}), HTTPStatus.OK
def _check_authorization(identifier, filing_json: str) -> Tuple[dict, int]: action = ['edit'] filing_type = filing_json['filing']['header'].get('name') if filing_type == 'courtOrder': action = ['court_order'] elif filing_type == 'registrarsNotation': action = ['registrars_notation'] elif filing_type == 'registrarsOrder': action = ['registrars_order'] if not authorized(identifier, jwt, action=action): return jsonify({'message': f'You are not authorized to submit a filing for {identifier}.'}), \ HTTPStatus.UNAUTHORIZED return None, None
def post(identifier): """Create a new comment for the business.""" # basic checks business = Business.find_by_identifier(identifier) err_msg, err_code = BusinessCommentResource._basic_checks( identifier, business, request) if err_msg: return jsonify(err_msg), err_code json_input = request.get_json() # check authorization if not authorized(identifier, jwt, action=['add_comment']): return jsonify({'message': f'You are not authorized to submit a comment for {identifier}.'}), \ HTTPStatus.UNAUTHORIZED # validate comment err = validate(json_input, False) if err: json_input['errors'] = err.msg return jsonify(json_input), err.code # save comment user = User.get_or_create_user_by_jwt(g.jwt_oidc_token_info) try: comment = Comment() comment.comment = json_input['comment']['comment'] comment.staff_id = user.id comment.business_id = business.id comment.timestamp = datetime.datetime.utcnow() comment.save() except BusinessException as err: reply = json_input reply['errors'] = [ { 'error': err.error }, ] return jsonify(reply), err.status_code # all done return jsonify(comment.json), HTTPStatus.CREATED
def put(identifier, filing_id): # pylint: disable=too-many-return-statements """Modify an incomplete filing for the business.""" # basic checks err_msg, err_code = ListFilingResource._put_basic_checks( identifier, filing_id, request) if err_msg: return jsonify({'errors': [ err_msg, ]}), err_code json_input = request.get_json() # check authorization if not authorized(identifier, jwt, action=['edit']): return jsonify({'message': f'You are not authorized to submit a filing for {identifier}.'}), \ HTTPStatus.UNAUTHORIZED # get query params draft = (request.args.get('draft', None).lower() == 'true') \ if request.args.get('draft', None) else False only_validate = (request.args.get('only_validate', None).lower() == 'true') \ if request.args.get('only_validate', None) else False # validate filing if not draft and not ListFilingResource._is_before_epoch_filing( json_input, Business.find_by_identifier(identifier)): if identifier.startswith('T'): business_validate = RegistrationBootstrap.find_by_identifier( identifier) else: business_validate = Business.find_by_identifier(identifier) err = validate(business_validate, json_input) # err_msg, err_code = ListFilingResource._validate_filing_json(request) if err or only_validate: if err: json_input['errors'] = err.msg return jsonify(json_input), err.code return jsonify(json_input), HTTPStatus.OK # save filing, if it's draft only then bail user = User.get_or_create_user_by_jwt(g.jwt_oidc_token_info) try: business, filing, err_msg, err_code = ListFilingResource._save_filing( request, identifier, user, filing_id) if err_msg or draft: reply = filing.json if filing else json_input reply['errors'] = [ err_msg, ] return jsonify(reply), err_code or \ (HTTPStatus.CREATED if (request.method == 'POST') else HTTPStatus.ACCEPTED) except Exception as err: print(err) # complete filing response, response_code = ListFilingResource.complete_filing( business, filing, draft) if response: return response, response_code # all done return jsonify(filing.json),\ (HTTPStatus.CREATED if (request.method == 'POST') else HTTPStatus.ACCEPTED)