Ejemplo n.º 1
0
def call(request_method,
         resource,
         expected_status_code,
         user,
         headers=None,
         data=None,
         params=None):
    url = "{}".format(resource)
    if headers is None:
        headers = {}

    headers['accept'] = "application/json"

    headers['token'] = auth.get_token(
        username=user.get('user').get('name'),
        password=user.get('user').get('password'),
        force_refresh=False)

    response = request_method(url, params=params, headers=headers, data=data)

    if response.status_code == 401:
        # Retry with a new token
        headers['token'] = auth.get_token(username=user.username,
                                          password=user.password,
                                          force_refresh=False)
        response = request_method(url,
                                  params=params,
                                  headers=headers,
                                  data=data)

    message = "Got status code: {}, expected: {}, response body: {}".format(
        response.status_code, expected_status_code, response.text)
    assert response.status_code == expected_status_code, message

    return response
Ejemplo n.º 2
0
    def create_accounts(cls):  # pylint: disable=too-many-locals
        """Find all pending accounts to be created in CFS.

        Steps:
        1. Find all pending CFS accounts.
        2. Create CFS accounts.
        3. Publish a message to the queue if successful.
        """
        # Pass payment method if offline account creation has be restricted based on payment method.
        pending_accounts: List[
            CfsAccountModel] = CfsAccountModel.find_all_pending_accounts()
        current_app.logger.info(
            f'Found {len(pending_accounts)} CFS Accounts to be created.')
        if len(pending_accounts) == 0:
            return

        auth_token = get_token()

        for pending_account in pending_accounts:
            # Find the payment account and create the pay system instance.
            pay_account: PaymentAccountModel = PaymentAccountModel.find_by_id(
                pending_account.account_id)
            if pay_account.payment_method in (PaymentMethod.CASH.value,
                                              PaymentMethod.CHEQUE.value):
                routing_slip.create_cfs_account(pending_account, pay_account)
            else:
                cls._create_cfs_account(pending_account, pay_account,
                                        auth_token)
Ejemplo n.º 3
0
def login(data: UsuarioLogin):
    user = usuario_service.find_by_email(data.email)

    if user and auth.check_password(data.password, user.password):
        return auth.get_token({
            'id': user.id,
            'email': user.email,
            'nome': user.name,
            'level': user.grupo_usuario
        })
    else:
        return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED,
                            content="Email ou senha incorretos")
Ejemplo n.º 4
0
class StatementNotificationTask:  # pylint:disable=too-few-public-methods
    """Task to send statement notifications."""
    @classmethod
    def send_notifications(cls):
        """Send Notifications.

        Steps:
        1. Get all statements with Notification status as PENDING
        2. Start processing each statements
        2. Set status as processing so that if there is one more job , it wont be fetched
        3. Trigger mail
        4. Check status and update back
        """
        statements_with_pending_notifications = StatementModel.find_all_statements_by_notification_status(
            (NotificationStatus.PENDING.value, ))
        if statement_len := len(statements_with_pending_notifications) < 1:
            current_app.logger.info(
                'No Statements with Pending notifications Found!')
            return

        current_app.logger.info(
            f'{statement_len} Statements with Pending notifications Found!')
        token = get_token()

        params = {
            'logo_url':
            f"{current_app.config.get('AUTH_WEB_URL')}/{current_app.config.get('REGISTRIES_LOGO_IMAGE_NAME')}",
            'url': f"{current_app.config.get('AUTH_WEB_URL')}"
        }
        template = ENV.get_template('statement_notification.html')
        for statement in statements_with_pending_notifications:
            statement.notification_status_code = NotificationStatus.PROCESSING.value
            statement.notification_date = datetime.now()
            statement.commit()
            payment_account = PaymentAccountModel.find_by_id(
                statement.payment_account_id)
            recipients = StatementRecipientsModel.find_all_recipients_for_payment_id(
                statement.payment_account_id)
            if len(recipients) < 1:
                current_app.logger.info(
                    f'No recipients found for statement: '
                    f'{statement.payment_account_id}.Skipping sending')
                statement.notification_status_code = NotificationStatus.SKIP.value
                statement.notification_date = datetime.now()
                statement.commit()
                continue

            to_emails = ','.join(
                [str(recipient.email) for recipient in recipients])
            current_app.logger.info(f'Recipients email Ids:{to_emails}')
            params['org_name'] = payment_account.auth_account_name
            params['frequency'] = statement.frequency.lower()
            # logic changed https://github.com/bcgov/entity/issues/4809
            # params.update({'url': params['url'].replace('orgId', payment_account.auth_account_id)})
            try:
                notify_response = cls.send_email(token, to_emails,
                                                 template.render(params))
            except Exception as e:  # pylint:disable=broad-except
                current_app.logger.error('<notification failed')
                current_app.logger.error(e)
                notify_response = False

            if not notify_response:
                current_app.logger.error('<notification failed')
                statement.notification_status_code = NotificationStatus.FAILED.value
                statement.notification_date = datetime.now()
                statement.commit()
            else:
                statement.notification_status_code = NotificationStatus.SUCCESS.value
                statement.notification_date = datetime.now()
                statement.commit()
        2. Start processing each statements
        2. Set status as processing so that if there is one more job , it wont be fetched
        3. Trigger mail
        4. Check status and update back
        """
        statements_with_pending_notifications = StatementModel.find_all_statements_by_notification_status(
            (NotificationStatus.PENDING.value, ))
        if statement_len := len(statements_with_pending_notifications) < 1:
            current_app.logger.info(
                'No Statements with Pending notifications Found!')
            return
        else:
            current_app.logger.info(
                f'{statement_len} Statements with Pending notifications Found!'
            )
        token = get_token()

        params = {
            'logo_url':
            f"{current_app.config.get('AUTH_WEB_URL')}/{current_app.config.get('REGISTRIES_LOGO_IMAGE_NAME')}",
            'url':
            f"{current_app.config.get('AUTH_WEB_URL')}/{current_app.config.get('AUTH_WEB_STATEMENT_URL')}"
        }
        template = ENV.get_template('statement_notification.html')
        for statement in statements_with_pending_notifications:
            statement.notification_status_code = NotificationStatus.PROCESSING.value
            statement.notification_date = datetime.now()
            statement.commit()
            payment_account = PaymentAccountModel.find_by_id(
                statement.payment_account_id)
            recipients = StatementRecipientsModel.find_all_recipients_for_payment_id(
Ejemplo n.º 6
0
    def create_accounts(cls):  # pylint: disable=too-many-locals
        """Find all pending accounts to be created in CFS.

        Steps:
        1. Find all pending CFS accounts.
        2. Create CFS accounts.
        3. Publish a message to the queue if successful.
        """
        # Pass payment method if offline account creation has be restricted based on payment method.
        pending_accounts: List[
            CfsAccountModel] = CfsAccountModel.find_all_pending_accounts()
        current_app.logger.info(
            f'Found {len(pending_accounts)} CFS Accounts to be created.')
        if len(pending_accounts) == 0:
            return

        auth_token = get_token()

        for pending_account in pending_accounts:
            # Find the payment account and create the pay system instance.
            pay_account: PaymentAccountModel = PaymentAccountModel.find_by_id(
                pending_account.account_id)

            # If PAD Account creation in CFS is paused, then just continue
            # TODO Remove once PAD account bugs are fixed and stable on CAS side.
            if current_app.config.get('CFS_STOP_PAD_ACCOUNT_CREATION') and \
                    pay_account.payment_method == PaymentMethod.PAD.value:
                current_app.logger.info(
                    'Continuing to next record as CFS PAD account creation is stopped.'
                )
                continue

            current_app.logger.info(
                f'Creating pay system instance for {pay_account.payment_method} for account {pay_account.id}.'
            )

            account_contact = cls._get_account_contact(
                auth_token, pay_account.auth_account_id)

            contact_info: Dict[str, str] = {
                'city': account_contact.get('city'),
                'postalCode': account_contact.get('postalCode'),
                'province': account_contact.get('region'),
                'addressLine1': account_contact.get('street'),
                'country': account_contact.get('country')
            }

            payment_info: Dict[str, any] = {
                'bankInstitutionNumber': pending_account.bank_number,
                'bankTransitNumber': pending_account.bank_branch_number,
                'bankAccountNumber': pending_account.bank_account_number,
            }

            account_name = pay_account.auth_account_name
            # For an existing CFS Account, call update.. This is to handle PAD update when CFS is offline
            try:
                if pending_account.cfs_account and pending_account.cfs_party and pending_account.cfs_site:
                    # This means, PAD account details have changed. So update banking details for this CFS account
                    bank_details = CFSService.update_bank_details(
                        name=account_name,
                        party_number=pending_account.cfs_party,
                        account_number=pending_account.cfs_account,
                        site_number=pending_account.cfs_site,
                        payment_info=payment_info)
                    pending_account.payment_instrument_number = bank_details.get(
                        'payment_instrument_number', None)
                else:  # It's a new account, now create
                    # If the account have banking information, then create a PAD account else a regular account.
                    if pending_account.bank_number and pending_account.bank_branch_number \
                            and pending_account.bank_account_number:
                        cfs_account_details = CFSService.create_cfs_account(
                            name=account_name,
                            contact_info=contact_info,
                            payment_info=payment_info,
                            receipt_method=RECEIPT_METHOD_PAD_DAILY)
                    else:
                        cfs_account_details = CFSService.create_cfs_account(
                            name=account_name,
                            contact_info=contact_info,
                            receipt_method=None)

                    pending_account.payment_instrument_number = cfs_account_details.get(
                        'payment_instrument_number', None)
                    pending_account.cfs_account = cfs_account_details.get(
                        'account_number')
                    pending_account.cfs_site = cfs_account_details.get(
                        'site_number')
                    pending_account.cfs_party = cfs_account_details.get(
                        'party_number')

            except Exception as e:  # NOQA # pylint: disable=broad-except
                # publish to mailer queue.
                mailer.publish_mailer_events('PadSetupFailed', pay_account)
                capture_message(
                    f'Error on creating CFS Account: account id={pay_account.id}, '
                    f'auth account : {pay_account.auth_account_id}, ERROR : {str(e)}',
                    level='error')
                current_app.logger.error(e)
                pending_account.rollback()
                # pending_account.status = CfsAccountStatus.INACTIVE.value
                # pending_account.save()
                continue

            # If the account has an activation time set ,
            # before that it shud be set to the  PENDING_PAD_ACTIVATION status.
            is_account_in_pad_confirmation_period = pay_account.pad_activation_date is not None and \
                pay_account.pad_activation_date > datetime.today()
            pending_account.status = CfsAccountStatus.PENDING_PAD_ACTIVATION.value if \
                is_account_in_pad_confirmation_period else CfsAccountStatus.ACTIVE.value
            pending_account.save()