Example #1
0
    def _create_account_event_payload(self,
                                      event_type: str,
                                      include_pay_info: bool = False):
        """Return event payload for account."""
        payload: Dict[str, any] = {
            'specversion': '1.x-wip',
            'type': event_type,
            'source':
            f'https://api.pay.bcregistry.gov.bc.ca/v1/accounts/{self.auth_account_id}',
            'id': f'{self.auth_account_id}',
            'time': f'{datetime.now()}',
            'datacontenttype': 'application/json',
            'data': {
                'accountId': self.auth_account_id,
                'accountName': self.auth_account_name,
                'padTosAcceptedBy': self.pad_tos_accepted_by
            }
        }

        if include_pay_info:
            payload['data']['paymentInfo'] = dict(
                bankInstitutionNumber=self.bank_number,
                bankTransitNumber=self.bank_branch_number,
                bankAccountNumber=mask(self.bank_account_number,
                                       current_app.config['MASK_LEN']),
                paymentStartDate=get_local_formatted_date(
                    self.pad_activation_date))
        return payload
Example #2
0
    def get_receipt_details(filing_data, invoice_identifier, skip_auth_check):
        """Return receipt details."""
        receipt_details: dict = {}
        # invoice number mandatory
        invoice_data = Invoice.find_by_id(invoice_identifier,
                                          skip_auth_check=skip_auth_check)

        is_pending_invoice = invoice_data.payment_method_code in \
            (PaymentMethod.PAD.value, PaymentMethod.EJV.value) and \
            invoice_data.invoice_status_code != InvoiceStatus.PAID.value
        if not is_pending_invoice and not invoice_data.receipts:
            raise BusinessException(Error.INVALID_REQUEST)

        invoice_reference = InvoiceReference.find_completed_reference_by_invoice_id(
            invoice_data.id)

        receipt_details['invoiceNumber'] = invoice_reference.invoice_number
        if invoice_data.payment_method_code == PaymentSystem.INTERNAL.value and invoice_data.routing_slip:
            receipt_details['routingSlipNumber'] = invoice_data.routing_slip
        receipt_details[
            'receiptNumber'] = None if is_pending_invoice else invoice_data.receipts[
                0].receipt_number
        receipt_details['filingIdentifier'] = filing_data.get(
            'filingIdentifier', invoice_data.filing_id)
        receipt_details['bcOnlineAccountNumber'] = invoice_data.bcol_account

        payment_method = PaymentMethodModel.find_by_code(
            invoice_data.payment_method_code)

        receipt_details['paymentMethod'] = payment_method.code
        if invoice_data.payment_method_code != PaymentSystem.INTERNAL.value:
            receipt_details[
                'paymentMethodDescription'] = payment_method.description
        receipt_details['invoice'] = camelcase_dict(invoice_data.asdict(), {})
        # Format date to display in report.
        receipt_details['invoice']['createdOn'] = get_local_formatted_date(
            invoice_data.created_on)
        return receipt_details
Example #3
0
    def create_invoice_pdf(identifier: int, **kwargs) -> Tuple:
        """Find invoice by id."""
        invoice_dao: InvoiceModel = InvoiceModel.find_by_id(identifier)

        if not invoice_dao:
            raise BusinessException(Error.INVALID_INVOICE_ID)

        payment_account: PaymentAccountModel = PaymentAccountModel.find_by_id(
            invoice_dao.payment_account_id)
        cfs_account: CfsAccountModel = CfsAccountModel.find_by_id(
            invoice_dao.cfs_account_id)
        org_response = OAuthService.get(
            current_app.config.get('AUTH_API_ENDPOINT') +
            f'orgs/{payment_account.auth_account_id}',
            kwargs['user'].bearer_token, AuthHeaderType.BEARER,
            ContentType.JSON).json()
        org_contact_response = OAuthService.get(
            current_app.config.get('AUTH_API_ENDPOINT') +
            f'orgs/{payment_account.auth_account_id}/contacts',
            kwargs['user'].bearer_token, AuthHeaderType.BEARER,
            ContentType.JSON).json()

        org_contact = org_contact_response.get(
            'contacts')[0] if org_contact_response.get('contacts',
                                                       None) else {}

        invoice_number: str = invoice_dao.references[0].invoice_number if invoice_dao.references \
            else generate_transaction_number(invoice_dao.id)

        filing_types: List[Dict[str, str]] = []
        for line_item in invoice_dao.payment_line_items:
            business_identifier = invoice_dao.business_identifier \
                if not invoice_dao.business_identifier.startswith('T') \
                else ''
            filing_types.append({
                'folioNumber':
                invoice_dao.folio_number,
                'description':
                line_item.description,
                'businessIdentifier':
                business_identifier,
                'createdOn':
                get_local_formatted_date(invoice_dao.created_on),
                'filingTypeCode':
                line_item.fee_schedule.filing_type_code,
                'fee':
                line_item.total,
                'gst':
                line_item.gst,
                'serviceFees':
                line_item.service_fees,
                'total':
                line_item.total + line_item.service_fees
            })

        template_vars: Dict[str, any] = {
            'invoiceNumber': invoice_number,
            'createdOn': get_local_formatted_date(invoice_dao.created_on),
            'accountNumber': cfs_account.cfs_account if cfs_account else None,
            'total': invoice_dao.total,
            'gst': 0,
            'serviceFees': invoice_dao.service_fees,
            'fees': invoice_dao.total - invoice_dao.service_fees,
            'filingTypes': filing_types,
            'accountContact': {
                'name': org_response.get('name'),
                'city': org_contact.get('city', None),
                'country': org_contact.get('country', None),
                'postalCode': org_contact.get('postalCode', None),
                'region': org_contact.get('region', None),
                'street': org_contact.get('street', None),
                'streetAdditional': org_contact.get('streetAdditional', None)
            }
        }

        invoice_pdf_dict = {
            'templateName': 'invoice',
            'reportName': invoice_number,
            'templateVars': template_vars
        }
        current_app.logger.info('Invoice PDF Dict %s', invoice_pdf_dict)

        pdf_response = OAuthService.post(
            current_app.config.get('REPORT_API_BASE_URL'),
            kwargs['user'].bearer_token, AuthHeaderType.BEARER,
            ContentType.JSON, invoice_pdf_dict)
        current_app.logger.debug('<OAuthService responded to receipt.py')

        return pdf_response, invoice_pdf_dict.get('reportName')
Example #4
0
    def generate_payment_report(content_type, report_name, results,
                                template_name, **kwargs):  # pylint: disable=too-many-locals
        """Prepare data and generate payment report by calling report api."""
        labels = [
            'Transaction', 'Transaction Details', 'Folio Number',
            'Initiated By', 'Date', 'Purchase Amount', 'GST', 'Statutory Fee',
            'BCOL Fee', 'Status', 'Corp Number'
        ]

        # Use the status_code_description instead of status_code.
        invoice_status_codes = CodeService.find_code_values_by_type(
            Code.INVOICE_STATUS.value)
        for invoice in results.get('items', None):
            filtered_codes = [
                cd for cd in invoice_status_codes['codes']
                if cd['code'] == invoice['status_code']
            ]
            if filtered_codes:
                invoice['status_code'] = filtered_codes[0]['description']

        if content_type == ContentType.CSV.value:
            template_vars = {
                'columns': labels,
                'values': Payment._prepare_csv_data(results)
            }
        else:
            total_stat_fees = 0
            total_service_fees = 0
            total = 0
            total_paid = 0

            invoices = results.get('items', None)
            for invoice in invoices:
                total += invoice.get('total', 0)
                total_stat_fees += invoice.get('total', 0) - invoice.get(
                    'service_fees', 0)

                total_service_fees += invoice.get('service_fees', 0)
                total_paid += invoice.get('paid', 0)

                # Format date to local
                invoice['created_on'] = get_local_formatted_date(
                    parser.parse(invoice['created_on']))

            account_info = None
            if kwargs.get('auth', None):
                account_id = kwargs.get('auth')['account']['id']
                contact_url = current_app.config.get(
                    'AUTH_API_ENDPOINT') + f'orgs/{account_id}/contacts'
                contact = OAuthService.get(
                    endpoint=contact_url,
                    token=kwargs['user'].bearer_token,
                    auth_header_type=AuthHeaderType.BEARER,
                    content_type=ContentType.JSON).json()

                account_info = kwargs.get('auth').get('account')
                account_info['contact'] = contact['contacts'][
                    0]  # Get the first one from the list

            template_vars = {
                'invoices': results.get('items', None),
                'total': {
                    'statutoryFees': total_stat_fees,
                    'serviceFees': total_service_fees,
                    'fees': total,
                    'paid': total_paid,
                    'due': total - total_paid
                },
                'account': account_info,
                'statement': kwargs.get('statement')
            }

        report_payload = {
            'reportName': report_name,
            'templateName': template_name,
            'templateVars': template_vars,
            'populatePageNumber': True
        }

        report_response = OAuthService.post(
            endpoint=current_app.config.get('REPORT_API_BASE_URL'),
            token=kwargs['user'].bearer_token,
            auth_header_type=AuthHeaderType.BEARER,
            content_type=ContentType.JSON,
            additional_headers={'Accept': content_type},
            data=report_payload)
        return report_response