/** * Copyright since 2026 Mifos Initiative * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import { expect, test, Page } from '@playwright/test'; // WEB-1496. Deterministic synthetic HTTP fixtures only: the browser never reaches a live backend. Error // envelopes match Fineract's ApiGlobalErrorResponse and the Savings Plugin teller-context rule codes; // backend behaviour itself is proven by the Savings Plugin HTTP integration tests. test.use({ storageState: { cookies: [], origins: [] }, timezoneId: 'UTC', locale: 'en-US' }); const BUSINESS_DATE = '2026-12-01'; const PAGE = '/#/organization/base-teller/credit-payments'; const ADMIN = ['ALL_FUNCTIONS']; const TELLER = [ 'READ_BASE_TELLER_CREDIT_PAYMENT', 'CREATE_BASE_TELLER_CREDIT_PAYMENT', 'REPRINT_BASE_TELLER_CREDIT_PAYMENT', 'REPAYMENT_LOAN' ]; const context = { businessDate: BUSINESS_DATE, officeId: 1, tellerId: 21, cashierId: 34, denominations: [ { identifier: 'SYN-USD-20', currencyCode: 'USD', value: 20, type: 'BANKNOTE' }, { identifier: 'SYN-USD-10', currencyCode: 'USD', value: 10, type: 'BANKNOTE' } ], banks: [{ id: 4, code: 'SYN', name: 'Synthetic Bank' }], paymentTypes: [ { id: 5, name: 'Synthetic Cash', isCashPayment: true }, { id: 6, name: 'Synthetic Check', isCashPayment: false } ] }; const customer = { clientId: 7, accountNo: 'C-SYN-7', displayName: 'Ada Synthetic', officeId: 1, officeName: 'Head Office', status: 'Active' }; const loan = { id: 8, accountNo: 'L-SYN-8', clientId: 7, clientName: 'Ada Synthetic', officeId: 1, status: 'Active', payable: true, currencyCode: 'USD', principalOutstanding: 80, interestOutstanding: 10, feeOutstanding: 5, penaltyOutstanding: 0, totalOutstanding: 95, principalOverdue: 0, interestOverdue: 0, feeOverdue: 0, penaltyOverdue: 0, totalOverdue: 0, repaymentSchedule: { periods: [] }, transactions: [] }; function domainRule(code: string, message: string) { return { status: 403, json: { developerMessage: 'Request was understood but caused a domain rule violation.', httpStatusCode: '403', defaultUserMessage: 'Errors contain reason for domain rule violation.', userMessageGlobalisationCode: 'validation.msg.domain.rule.violation', errors: [ { developerMessage: message, defaultUserMessage: message, userMessageGlobalisationCode: `error.msg.base.teller.credit.payment.${code}`, parameterName: 'id', args: [] } ] } }; } const RECORDED_FAILURE = domainRule( 'cashier.context.required', 'Authenticated user must be linked to staff and office.' ); interface Scenario { permissions: string[]; context: { status: number; json: unknown }; } let scenario: Scenario; let contextReads: number; let payments: { path: string; body: Record }[]; let unexpectedWrites: string[]; async function open(page: Page): Promise { await page.addInitScript((permissions: string[]) => { sessionStorage.setItem( 'mifosXCredentials', JSON.stringify({ authenticated: true, base64EncodedAuthenticationKey: 'synthetic-key', permissions, roles: [], userId: 1496, username: 'synthetic-teller', officeId: 1, officeName: 'Head Office', shouldRenewPassword: false }) ); localStorage.setItem('mifosXLanguage', JSON.stringify({ name: 'English', code: 'en' })); }, scenario.permissions); await page.clock.setFixedTime(new Date(`${BUSINESS_DATE}T12:00:00Z`)); await page.goto(PAGE); await expect(page.getByRole('heading', { name: 'Cash and Check Credit Payments' }).first()).toBeVisible(); } test.beforeEach(async ({ page }) => { scenario = { permissions: ADMIN, context: { status: 200, json: context } }; contextReads = 0; payments = []; unexpectedWrites = []; await page.context().addInitScript((date: string) => { localStorage.setItem('mifosXServerURL', location.origin); localStorage.setItem('mifosXServerDate', date); }, BUSINESS_DATE); await page.context().route('**/assets/env.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'window.env = { productionModeEnableRBAC: true, productionMode: true };' }) ); await page.context().route('**/fineract-provider/**', async (route) => { const request = route.request(); const path = new URL(request.url()).pathname; const api = path.replace(/^.*\/v2\/base-teller\/credit-payments/, ''); if (path.endsWith('/v2/base-teller/credit-payments/context')) { contextReads++; await route.fulfill(scenario.context); } else if (path.endsWith('/v2/base-teller/credit-payments/customers') && request.method() === 'GET') { await route.fulfill({ json: [customer] }); } else if (api === '/customers/7/loans') { await route.fulfill({ json: [loan] }); } else if (api === '/loans/8') { await route.fulfill({ json: loan }); } else if (api === '/preview' && request.method() === 'POST') { const body = request.postDataJSON(); payments.push({ path: api, body }); const amount = Number(body.amount); const tendered = body.paymentMethod === 'CASH' ? 20 : amount; await route.fulfill({ json: { loanId: 8, paymentMethod: body.paymentMethod, checkClassification: body.check?.classification, currencyCode: 'USD', businessDate: BUSINESS_DATE, paymentAmount: amount, tenderAmount: tendered, changeAmount: tendered - amount, principalOutstanding: 80, interestOutstanding: 10, feeOutstanding: 5, penaltyOutstanding: 0, denominations: body.denominations ?? [], postsRepaymentOnConfirmation: body.paymentMethod === 'CASH', nativeRepaymentTemplate: { principalPortion: amount, interestPortion: 0 } } }); } else if (api === '' && request.method() === 'POST') { const body = request.postDataJSON(); payments.push({ path: api, body }); await route.fulfill({ json: { id: 91, receiptNumber: 'CP-SYN-91', status: 'COMPLETED', paymentMethod: 'CASH', clientId: 7, clientName: 'Ada Synthetic', loanId: 8, loanAccountNo: 'L-SYN-8', amount: Number(body.amount), tenderAmount: 20, changeAmount: 20 - Number(body.amount), currencyCode: 'USD', paymentTypeId: 5, businessDate: BUSINESS_DATE, operatorId: 1496, operatorName: 'synthetic-teller', officeId: 1, tellerId: 21, cashierId: 34, loanTransactionId: 501, createdOnUtc: `${BUSINESS_DATE}T12:00:00Z`, denominations: body.denominations } }); } else if (request.method() !== 'GET') { unexpectedWrites.push(`${request.method()} ${path}`); await route.fulfill({ status: 405, json: { errors: [] } }); } else if (path.includes('/configurations')) { await route.fulfill({ json: { enabled: false, value: 0 } }); } else if (path.includes('/actuator/')) { await route.fulfill({ json: { status: 'UP' } }); } else { await route.fulfill({ json: [] }); } }); }); test.afterEach(() => { // Configuration recovery must never create, assign or post anything by itself. expect(unexpectedWrites).toEqual([]); }); async function reachPaymentDetails(page: Page): Promise { const screen = page.locator('.credit-payment'); await screen.getByRole('textbox', { name: 'Customer Search' }).fill('Ada'); await screen.getByRole('button', { name: 'Search' }).click(); await screen.getByRole('option', { name: /Ada Synthetic/ }).click(); await screen.getByRole('button', { name: 'Next' }).click(); await screen.getByRole('option', { name: /L-SYN-8/ }).click(); await screen.getByRole('button', { name: 'Next' }).click(); await expect(screen.getByRole('textbox', { name: 'Amount' })).toBeVisible(); } test('the recorded staff and office failure shows recovery steps, and Retry Configuration restores the workflow', async ({ page }) => { scenario.context = RECORDED_FAILURE; await open(page); const recovery = page.locator('.configuration-recovery'); await expect(recovery.getByRole('alert')).toContainText('User is not linked to staff and office'); await expect(recovery).toContainText('must be linked to a staff member and to an office'); await expect(recovery).toContainText('No payment can be processed until this configuration is corrected.'); await expect(recovery.getByRole('link', { name: 'Users' })).toHaveAttribute('href', '#/appusers'); await expect(recovery.getByRole('link', { name: 'Manage Employees' })).toHaveAttribute( 'href', '#/organization/employees' ); // One specific message: no raw backend text in a snackbar or banner, no generic fallback, no stepper. await expect(page.getByText('Authenticated user must be linked to staff and office.')).toHaveCount(0); await expect(page.getByText('Teller configuration could not be loaded')).toHaveCount(0); await expect(page.locator('mat-stepper')).toHaveCount(0); await expect(page.getByRole('button', { name: 'Confirm and Submit' })).toHaveCount(0); // An administrator corrects the user in User administration; the backend now returns a context. scenario.context = { status: 200, json: context }; await recovery.getByRole('button', { name: 'Retry Configuration' }).click(); await expect(recovery).toHaveCount(0); const summary = page.locator('.context-summary'); await expect(summary).toContainText(`Business Date: ${BUSINESS_DATE}`); await expect(summary).toContainText('Teller: 21'); await expect(summary).toContainText('Cashier: 34'); await expect(page.getByRole('textbox', { name: 'Customer Search' })).toBeVisible(); expect(contextReads).toBe(2); }); test('a teller without administration permissions is told to contact an administrator', async ({ page }) => { scenario.permissions = TELLER; scenario.context = domainRule('cashier.not.allocated', 'Authenticated user has no active cashier allocation.'); await open(page); const recovery = page.locator('.configuration-recovery'); await expect(recovery.getByRole('alert')).toContainText('No active cashier assignment'); await expect(recovery).toContainText('valid for the current business date and shift'); await expect(recovery).toContainText('You cannot change this configuration. Ask your administrator'); await expect(recovery.getByRole('link')).toHaveCount(0); await expect(page.getByRole('link', { name: 'Teller / Cashier Management' })).toHaveCount(0); await expect(recovery.getByRole('button', { name: 'Retry Configuration' })).toBeVisible(); }); test('an administrator is offered teller management for a missing cashier assignment', async ({ page }) => { scenario.context = domainRule('cashier.not.allocated', 'Authenticated user has no active cashier allocation.'); await open(page); await expect( page.locator('.configuration-recovery').getByRole('link', { name: 'Teller / Cashier Management' }) ).toHaveAttribute('href', '#/organization/tellers'); }); test('a permission failure is not presented as retryable', async ({ page }) => { scenario.permissions = TELLER; scenario.context = { status: 403, json: { httpStatusCode: '403', defaultUserMessage: 'Insufficient privileges to perform this action.', userMessageGlobalisationCode: 'error.msg.not.authorized', errors: [ { defaultUserMessage: 'User has no authority to: READ_BASE_TELLER_CREDIT_PAYMENT', userMessageGlobalisationCode: 'error.msg.not.authorized', parameterName: 'id', args: [] } ] } }; await open(page); const recovery = page.locator('.configuration-recovery'); await expect(recovery.getByRole('alert')).toContainText('Access denied'); await expect(recovery).toContainText('Retrying will not change this'); await expect(recovery.getByRole('button')).toHaveCount(0); await expect(page.getByText('User has no authority to')).toHaveCount(0); }); test('the restored workflow previews, confirms and receipts a cash payment', async ({ page }) => { scenario.permissions = TELLER; await open(page); await reachPaymentDetails(page); await page.getByRole('textbox', { name: 'Amount' }).fill('15'); await page.getByRole('spinbutton', { name: 'Quantity' }).first().fill('1'); await page.getByRole('button', { name: 'Preview Payment' }).click(); await expect(page.locator('.authoritative-summary')).toContainText('15 USD'); await page.getByRole('button', { name: 'Confirm and Submit' }).click(); await expect(page.getByRole('heading', { name: 'Credit Payment Receipt' })).toBeVisible(); await expect(page.locator('.receipt')).toContainText('CP-SYN-91'); expect(payments.map((payment) => payment.path)).toEqual([ '/preview', '' ]); expect(payments[1].body).toMatchObject({ clientId: 7, loanId: 8, paymentMethod: 'CASH', amount: '15', paymentTypeId: 5, transactionDate: BUSINESS_DATE, denominations: [ { denominationId: 'SYN-USD-20', value: '20', quantity: 1 }, { denominationId: 'SYN-USD-10', value: '10', quantity: 0 } ] }); expect(payments[1].body.idempotencyKey).toEqual(expect.any(String)); }); test('the restored workflow previews a check payment', async ({ page }) => { scenario.permissions = TELLER; await open(page); await reachPaymentDetails(page); await page.getByRole('radio', { name: 'Check' }).click(); await page.getByRole('textbox', { name: 'Amount' }).fill('25'); await page.getByRole('combobox', { name: 'Bank' }).click(); await page.getByRole('option', { name: 'Synthetic Bank (SYN)' }).click(); await page.getByRole('textbox', { name: 'Check Type' }).fill('PERSONAL'); await page.getByRole('textbox', { name: 'Check Number' }).fill('149600'); await page.getByRole('button', { name: 'Preview Payment' }).click(); await expect(page.locator('.authoritative-summary')).toContainText('25 USD'); await expect(page.getByText('Synthetic Bank', { exact: true })).toBeVisible(); expect(payments).toHaveLength(1); expect(payments[0].body).toMatchObject({ paymentMethod: 'CHECK', paymentTypeId: 6, check: { bankId: 4, checkType: 'PERSONAL', checkNumber: '149600', classification: 'SUBJECT_TO_COLLECTION' } }); }); test('cash stays available when no active check bank is configured', async ({ page }) => { scenario.permissions = TELLER; scenario.context = { status: 200, json: { ...context, banks: [] } }; await open(page); await reachPaymentDetails(page); await expect(page.getByText('Check payments are unavailable because no active bank is configured.')).toBeVisible(); await expect(page.getByRole('radio', { name: 'Check' })).toBeDisabled(); await page.getByRole('textbox', { name: 'Amount' }).fill('20'); await page.getByRole('spinbutton', { name: 'Quantity' }).first().fill('1'); await page.getByRole('button', { name: 'Preview Payment' }).click(); await expect(page.locator('.authoritative-summary')).toContainText('20 USD'); });