def test_post_default_statement_settings_daily(session, client, jwt, app): """Assert that the post endpoint works.""" token = jwt.create_jwt(get_claims(), token_header) headers = { 'Authorization': f'Bearer {token}', 'content-type': 'application/json' } rv = client.post('/api/v1/payment-requests', data=json.dumps( get_payment_request(business_identifier='CP0002000')), headers=headers) invoice: Invoice = Invoice.find_by_id(rv.json.get('id')) pay_account: PaymentAccount = PaymentAccount.find_by_id( invoice.payment_account_id) rv = client.get( f'/api/v1/accounts/{pay_account.auth_account_id}/statements/settings', data=json.dumps({}), headers=headers) assert rv.status_code == 200 assert rv.json.get('currentFrequency').get( 'frequency') == StatementFrequency.WEEKLY.value # Set the frequency to Daily and assert daily_frequency = {'frequency': 'DAILY'} rv = client.post( f'/api/v1/accounts/{pay_account.auth_account_id}/statements/settings', data=json.dumps(daily_frequency), headers=headers) assert rv.json.get('frequency') == StatementFrequency.DAILY.value end_date = get_week_start_and_end_date()[1] assert rv.json.get('fromDate') == (end_date + timedelta(days=1)).strftime('%Y-%m-%d') # Set the frequency to Monthly and assert daily_frequency = {'frequency': 'MONTHLY'} rv = client.post( f'/api/v1/accounts/{pay_account.auth_account_id}/statements/settings', data=json.dumps(daily_frequency), headers=headers) end_date = get_first_and_last_dates_of_month(current_local_time().month, current_local_time().year)[1] assert rv.json.get('frequency') == StatementFrequency.MONTHLY.value assert rv.json.get('fromDate') == (end_date + timedelta(days=1)).strftime('%Y-%m-%d') # Get the latest frequency rv = client.get( f'/api/v1/accounts/{pay_account.auth_account_id}/statements/settings', data=json.dumps({}), headers=headers) assert rv.status_code == 200 assert rv.json.get('currentFrequency').get( 'frequency') == StatementFrequency.MONTHLY.value
def test_get_payment_system_url_service_fees(session, public_user_mock): """Assert that the url returned is correct.""" today = current_local_time().strftime(PAYBC_DATE_FORMAT) payment_account = factory_payment_account() payment = factory_payment() payment_account.save() payment.save() invoice = factory_invoice(payment_account) invoice.save() invoice_ref = factory_invoice_reference(invoice.id).save() fee_schedule = FeeSchedule.find_by_filing_type_and_corp_type('CP', 'OTANN') distribution_code = DistributionCodeModel.find_by_active_for_fee_schedule(fee_schedule.fee_schedule_id) distribution_code_svc = DistributionCode() distribution_code_payload = get_distribution_code_payload() # Set service fee distribution distribution_code_payload.update({'serviceFeeDistributionCodeId': distribution_code.distribution_code_id}) # update the existing gl code with new values distribution_code_svc.save_or_update(distribution_code_payload, distribution_code.distribution_code_id) service_fee = 100 line = factory_payment_line_item(invoice.id, fee_schedule_id=fee_schedule.fee_schedule_id, service_fees=service_fee) line.save() direct_pay_service = DirectPayService() payment_response_url = direct_pay_service.get_payment_system_url_for_invoice(invoice, invoice_ref, 'google.com') url_param_dict = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(payment_response_url).query)) assert url_param_dict['trnDate'] == today assert url_param_dict['glDate'] == today assert url_param_dict['description'] == 'Direct_Sale' assert url_param_dict['pbcRefNumber'] == current_app.config.get('PAYBC_DIRECT_PAY_REF_NUMBER') assert url_param_dict['trnNumber'] == generate_transaction_number(invoice.id) assert url_param_dict['trnAmount'] == str(invoice.total) assert url_param_dict['paymentMethod'] == 'CC' assert url_param_dict['redirectUri'] == 'google.com' revenue_str = f"1:{distribution_code_payload['client']}." \ f"{distribution_code_payload['responsibilityCentre']}." \ f"{distribution_code_payload['serviceLine']}." \ f"{distribution_code_payload['stob']}." \ f"{distribution_code_payload['projectCode']}." \ f'000000.0000:10.00' revenue_str_service_fee = f"2:{distribution_code_payload['client']}." \ f"{distribution_code_payload['responsibilityCentre']}." \ f"{distribution_code_payload['serviceLine']}." \ f"{distribution_code_payload['stob']}." \ f"{distribution_code_payload['projectCode']}." \ f'000000.0000:{format(service_fee, DECIMAL_PRECISION)}' assert url_param_dict['revenue'] == f'{revenue_str}|{revenue_str_service_fee}' urlstring = f"trnDate={today}&pbcRefNumber={current_app.config.get('PAYBC_DIRECT_PAY_REF_NUMBER')}&" \ f'glDate={today}&description=Direct_Sale&' \ f'trnNumber={generate_transaction_number(invoice.id)}&' \ f'trnAmount={invoice.total}&' \ f'paymentMethod=CC&' \ f'redirectUri=google.com&' \ f'currency=CAD&' \ f'revenue={revenue_str}|' \ f'{revenue_str_service_fee}' expected_hash_str = HashingService.encode(urlstring) assert expected_hash_str == url_param_dict['hashValue']
def get_payment_system_url_for_invoice(self, invoice: Invoice, inv_ref: InvoiceReference, return_url: str): """Return the payment system url.""" today = current_local_time().strftime(PAYBC_DATE_FORMAT) url_params_dict = { 'trnDate': today, 'pbcRefNumber': current_app.config.get('PAYBC_DIRECT_PAY_REF_NUMBER'), 'glDate': today, 'description': 'Direct_Sale', 'trnNumber': generate_transaction_number(invoice.id), 'trnAmount': invoice.total, 'paymentMethod': PaymentMethod.CC.value, 'redirectUri': return_url, 'currency': 'CAD', 'revenue': DirectPayService._create_revenue_string(invoice) } url_params = urlencode(url_params_dict) # unquote is used below so that unescaped url string can be hashed url_params_dict['hashValue'] = HashingService.encode( unquote_plus(url_params)) encoded_query_params = urlencode( url_params_dict) # encode it again to inlcude the hash paybc_url = current_app.config.get('PAYBC_DIRECT_PAY_PORTAL_URL') current_app.logger.debug( f'PayBC URL for {invoice.id} -> {paybc_url}?{encoded_query_params}' ) return f'{paybc_url}?{encoded_query_params}'
def create_cms(cls, line_items: List[PaymentLineItemModel], cfs_account: CfsAccountModel) -> Dict[str, any]: """Create CM record in CFS.""" current_app.logger.debug('>Creating CMS') access_token: str = CFSService.get_token().json().get('access_token') cfs_base: str = current_app.config.get('CFS_BASE_URL') cms_url = f'{cfs_base}/cfs/parties/{cfs_account.cfs_party}/accs/{cfs_account.cfs_account}' \ f'/sites/{cfs_account.cfs_site}/cms/' current_app.logger.debug('CMS URL %s', cms_url) now = current_local_time() curr_time = now.strftime('%Y-%m-%dT%H:%M:%SZ') cms_payload = dict( batch_source=CFS_CM_BATCH_SOURCE, cust_trx_type=CFS_CMS_TRX_TYPE, transaction_date=curr_time, gl_date=curr_time, comments='', lines=cls._build_lines(line_items, negate=True) ) cms_response = CFSService.post(cms_url, access_token, AuthHeaderType.BEARER, ContentType.JSON, cms_payload) current_app.logger.debug('>Received CMS response') return cms_response.json()
def create_account_invoice(cls, transaction_number: str, line_items: List[PaymentLineItemModel], cfs_account: CfsAccountModel) \ -> Dict[str, any]: """Create CFS Account Invoice.""" now = current_local_time() curr_time = now.strftime('%Y-%m-%dT%H:%M:%SZ') invoice_url = current_app.config.get( 'CFS_BASE_URL') + f'/cfs/parties/{cfs_account.cfs_party}' \ f'/accs/{cfs_account.cfs_account}/sites/{cfs_account.cfs_site}/invs/' invoice_payload = dict( batch_source=CFS_BATCH_SOURCE, cust_trx_type=CFS_CUST_TRX_TYPE, transaction_date=curr_time, transaction_number=generate_transaction_number(transaction_number), gl_date=curr_time, term_name=CFS_TERM_NAME, comments='', lines=cls._build_lines(line_items) ) access_token = CFSService.get_token().json().get('access_token') invoice_response = CFSService.post(invoice_url, access_token, AuthHeaderType.BEARER, ContentType.JSON, invoice_payload) return invoice_response
def _get_end_of(frequency: StatementFrequency): """Return the end of either week or month.""" today = datetime.today() end_date = current_local_time() if frequency == StatementFrequency.WEEKLY.value: end_date = get_week_start_and_end_date()[1] if frequency == StatementFrequency.MONTHLY.value: end_date = get_first_and_last_dates_of_month( today.month, today.year)[1] return end_date
def _calculate_activation_date(): """Find the activation date in local time.Convert it to UTC before returning.""" account_activation_wait_period: int = current_app.config.get( 'PAD_CONFIRMATION_PERIOD_IN_DAYS') date_after_wait_period = current_local_time() + timedelta( days=account_activation_wait_period + 1) # reset the day to the beginning of the day. round_to_full_day = date_after_wait_period.replace(minute=0, hour=0, second=0) utc_time = round_to_full_day.astimezone(timezone.utc) return utc_time
def create_invoice( self, payment_account: PaymentAccount, # pylint: disable=too-many-locals line_items: [PaymentLineItem], invoice: Invoice, **kwargs): """Create Invoice in PayBC.""" current_app.logger.debug('<create_invoice') now = current_local_time() curr_time = now.strftime('%Y-%m-%dT%H:%M:%SZ') invoice_number: str = kwargs.get('invoice_number', None) if invoice_number is None: invoice_number = invoice.id invoice_url = current_app.config.get('CFS_BASE_URL') + '/cfs/parties/{}/accs/{}/sites/{}/invs/' \ .format(payment_account.paybc_party, payment_account.paybc_account, payment_account.paybc_site) # Check if random invoice number needs to be generated transaction_num_suffix = secrets.token_hex(10) \ if current_app.config.get('GENERATE_RANDOM_INVOICE_NUMBER', 'False').lower() == 'true' \ else payment_account.corp_number transaction_number = f'{invoice_number}-{transaction_num_suffix}'.replace( ' ', '') invoice_payload = dict(batch_source=CFS_BATCH_SOURCE, cust_trx_type=CFS_CUST_TRX_TYPE, transaction_date=curr_time, transaction_number=transaction_number[:20], gl_date=curr_time, term_name=CFS_TERM_NAME, comments='', lines=[]) index: int = 0 for line_item in line_items: index = index + 1 invoice_payload['lines'].append({ 'line_number': index, 'line_type': CFS_LINE_TYPE, 'memo_line_name': line_item.fee_distribution.memo_name, 'description': line_item.description, 'attribute1': line_item.description, 'unit_price': line_item.total, 'quantity': 1 }) if line_item.service_fees > 0: index = index + 1 invoice_payload['lines'].append({ 'line_number': index, 'line_type': CFS_LINE_TYPE, 'memo_line_name': line_item.fee_distribution.service_fee_memo_name, 'description': 'Service Fee', 'attribute1': 'Service Fee', 'unit_price': line_item.service_fees, 'quantity': 1 }) access_token = self.__get_token().json().get('access_token') invoice_response = self.post(invoice_url, access_token, AuthHeaderType.BEARER, ContentType.JSON, invoice_payload) invoice_result = { 'invoice_number': invoice_response.json().get('invoice_number', None), 'reference_number': invoice_response.json().get('pbc_ref_number', None) } current_app.logger.debug('>create_invoice') return invoice_result