Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion playwright.investment.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { defineConfig, devices } from '@playwright/test';
/** Deterministic UI tests use synthetic HTTP fixtures; the live spec opts into local Fineract. */
export default defineConfig({
testDir: './playwright/tests',
testMatch: /investment-products(?:\.live)?\.spec\.ts/,
testMatch: /investment-(?:products|simulator)(?:\.live)?\.spec\.ts/,
timeout: 60000,
workers: 1,
retries: 0,
Expand Down
142 changes: 142 additions & 0 deletions playwright/fixtures/investment-simulator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/**
* Copyright since 2025 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 { Page, Route } from '@playwright/test';
import { investmentBackend } from './investment-products';
import {
parseInvestmentJson,
serializeInvestmentJson
} from '../../src/app/products/investment-products/investment-json';
import {
capitalizingConfigurationFixture,
cedeConfigurationFixture,
noteConfigurationFixture,
partialResultFixture,
simulationHistoryFixture,
simulationResultFixture,
simulationTemplateFixture
} from '../../src/app/products/investment-products/investment-simulator/investment-simulator.fixtures';
import { rateFixture } from '../../src/app/products/investment-products/investment-product.fixtures';
import { SimulationRequest } from '../../src/app/products/investment-products/investment-simulator/investment-simulator.models';

/**
* Synthetic BE-03, customer and Main Account contracts layered over the FE-01 investment fixture.
* Responses are deterministic display data, never evidence of backend financial correctness.
*/
export async function simulatorBackend(page: Page) {
const base = await investmentBackend(page);
const state = {
simulationUnavailable: false,
/** Next POST status to return instead of a result, e.g. 502 for an uncertain outcome. */
failNext: 0,
/** Resolve to release a held simulation response. */
hold: null as Promise<void> | null,
balance: '50000.00' as string | null,
/** Client IDs with a linked Main Account. */
mainAccountClients: new Set([7]),
requests: [] as SimulationRequest[],
writes: [] as { method: string; path: string }[]
};
const configurations: Record<number, unknown> = {
41: noteConfigurationFixture,
42: cedeConfigurationFixture,
44: capitalizingConfigurationFixture
};
const effectiveRate = { ...rateFixture, version: 3, status: 'APPROVED_EFFECTIVE', effectiveDate: '2026-11-19' };
const client = (id: number) => ({
id,
accountNo: `00000000${id}`,
displayName: id === 7 ? 'Synthetic Customer Seven' : 'Synthetic Customer Eight',
status: { id: 300, code: 'clientStatusType.active', value: 'Active' },
active: true,
officeId: 1,
officeName: 'Synthetic office',
groups: [],
legalForm: { id: 1 },
timeline: { activatedOnDate: [
2026,
1,
1
] }
});
const json = (route: Route, body: unknown, status = 200) =>
route.fulfill({ status, contentType: 'application/json', body: serializeInvestmentJson(body) });
const raw = (route: Route, body: string, status = 200) =>
route.fulfill({ status, contentType: 'application/json', body });

await page.route('**/fineract-provider/**', async (route) => {
const request = route.request();
const path = new URL(request.url()).pathname.split('/api/v1')[1] ?? '';
if (request.method() !== 'GET') state.writes.push({ method: request.method(), path });
const simulations = '/investment-products/simulations';
if (path.startsWith(simulations)) {
if (state.simulationUnavailable) return raw(route, '{}', 404);
if (path === simulations + '/template') return json(route, simulationTemplateFixture);
if (path === simulations + '/history') return json(route, simulationHistoryFixture);
if (path === simulations && request.method() === 'POST') {
const body = parseInvestmentJson<SimulationRequest>(request.postData()!);
state.requests.push(body);
if (state.hold) await state.hold;
if (state.failNext) {
const status = state.failNext;
state.failNext = 0;
return raw(route, '{"errors":[]}', status);
}
const type = body.productId === 42 ? 'CEDE' : 'PROMISSORY_NOTE';
const result = body.requestedReinvestmentCount > 0 ? partialResultFixture(body) : simulationResultFixture(body);
return json(route, { ...result, investmentType: type });
}
if (/^\/investment-products\/simulations\/[0-9a-f-]{36}$/.test(path))
return json(route, simulationResultFixture(undefined, { createdAtUtc: '2026-11-18T09:00:00Z' }));
}
if (path === '/fixeddepositproducts')
return json(route, [
{ id: 41, name: 'Synthetic Investment', currency: { code: 'USD' } },
{ id: 42, name: 'Synthetic CEDE', currency: { code: 'USD' } },
{ id: 43, name: 'Synthetic unconfigured native product', currency: { code: 'USD' } },
{ id: 44, name: 'Synthetic capitalizing note', currency: { code: 'USD' } }
]);
const configuration = /^\/investment-products\/configuration\/(\d+)$/.exec(path);
if (configuration && configurations[Number(configuration[1])])
return json(route, configurations[Number(configuration[1])]);
if (/^\/investment-products\/(41|42|44)\/rates$/.test(path)) return json(route, effectiveRate);
const clientPath = /^\/clients\/(\d+)$/.exec(path);
if (clientPath) return json(route, client(Number(clientPath[1])));
if (/^\/clients\/\d+\/images/.test(path)) return raw(route, '{}', 404);
const main = /^\/savings\/account-relationships\/clients\/(\d+)\/main$/.exec(path);
if (main) {
const id = Number(main[1]);
return json(route, {
clientId: id,
relationships: state.mainAccountClients.has(id)
? [
{
clientId: id,
savingsAccountId: 18,
savingsProductId: 4,
policyVersion: 1,
nativeStatus: 300,
active: true
}
]
: []
});
}
if (path === '/savingsaccounts/18') {
if (state.balance == null) return raw(route, '{}', 503);
return raw(
route,
`{"id":18,"clientId":7,"accountNo":"000000018","savingsProductId":4,"savingsProductName":"Synthetic Main",` +
`"currency":{"code":"USD","decimalPlaces":2},"status":{"id":300},` +
`"summary":{"accountBalance":${state.balance},"totalInterestPosted":0}}`
);
}
return route.fallback();
});
return Object.assign(state, { base });
}
129 changes: 129 additions & 0 deletions playwright/tests/investment-simulator.live.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/**
* Copyright since 2025 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 { test, expect, type Request } from '@playwright/test';
import fs from 'fs';

/**
* Explicit opt-in against a local Fineract with savings-plugin BE-01/02/03 deployed. Use only a
* disposable tenant with a synthetic customer and a product that has a validated policy and an
* effective published rate. Simulations are audit-only; no account or financial write is issued.
*/
const tenant = process.env.INVESTMENT_LIVE_TENANT ?? 'default';
const productId = Number(process.env.INVESTMENT_SIMULATOR_PRODUCT_ID);
const clientId = Number(process.env.INVESTMENT_SIMULATOR_CLIENT_ID);
const amount = process.env.INVESTMENT_SIMULATOR_AMOUNT ?? '1000';
const termDays = process.env.INVESTMENT_SIMULATOR_TERM_DAYS ?? '90';

test.describe('Investment Simulator — live local Fineract', () => {
test.skip(
process.env.INVESTMENT_SIMULATOR_LIVE !== '1' || !productId || !clientId,
'Requires local BE-03 plus INVESTMENT_SIMULATOR_PRODUCT_ID and INVESTMENT_SIMULATOR_CLIENT_ID.'
);
test('simulates through the real proxy without financial writes', async ({ page, request }) => {
const headers = { 'Fineract-Platform-TenantId': tenant };
const authentication = await request.post('/fineract-provider/api/v1/authentication', {
headers,
data: { username: process.env.E2E_USERNAME ?? 'mifos', password: process.env.E2E_PASSWORD ?? 'password' }
});
expect(authentication.status()).toBe(200);
const credentials = await authentication.json();
const auth = { ...headers, Authorization: 'Basic ' + credentials.base64EncodedAuthenticationKey };
const template = await request.get('/fineract-provider/api/v1/investment-products/simulations/template', {
headers: auth
});
expect(template.status(), 'BE-03 simulation template must be deployed').toBe(200);
const products: { id: number; name: string }[] = await (
await request.get('/fineract-provider/api/v1/fixeddepositproducts', { headers: auth })
).json();
const product = products.find((item) => item.id === productId);
expect(product).toBeDefined();

await page.addInitScript(
({ credentials, tenant }) => {
localStorage.setItem('mifosXCredentials', JSON.stringify({ ...credentials, rememberMe: true }));
localStorage.setItem('mifosXServerURL', location.origin);
localStorage.setItem('mifosXTenantIdentifier', tenant);
localStorage.setItem('mifosXLanguage', JSON.stringify({ name: 'English', code: 'en' }));
},
{ credentials, tenant }
);
// Record every backend request when it is issued, so writes that fail without a response are still caught.
type NetworkEntry = { method: string; path: string; status: number | null; failure: string | null };
const network: NetworkEntry[] = [];
const entries = new Map<Request, NetworkEntry>();
page.on('request', (request) => {
Comment thread
AnvayKharb marked this conversation as resolved.
Resolved
const path = new URL(request.url()).pathname;
if (!path.startsWith('/fineract-provider/') || path.endsWith('/authentication')) return;
const entry: NetworkEntry = { method: request.method(), path, status: null, failure: null };
entries.set(request, entry);
network.push(entry);
});
page.on('response', (response) => {
const entry = entries.get(response.request());
if (entry) entry.status = response.status();
});
page.on('requestfailed', (request) => {
const entry = entries.get(request);
if (entry) entry.failure = request.failure()?.errorText ?? 'failed';
});
// Unexpected backend writes are aborted in the browser, so they never reach the live proxy.
const blocked: { method: string; path: string }[] = [];
await page.route('**/fineract-provider/**', async (route) => {
const request = route.request();
const path = new URL(request.url()).pathname;
const write = !/^(GET|HEAD|OPTIONS)$/.test(request.method());
const allowed =
path.endsWith('/authentication') ||
(request.method() === 'POST' && path === '/fineract-provider/api/v1/investment-products/simulations');
if (!write || allowed) return route.continue();
blocked.push({ method: request.method(), path });
return route.abort('blockedbyclient');
});
await page.goto(`/#/clients/${clientId}/investment-simulator`);
await page.getByRole('radio', { name: product!.name }).check();
await page
.getByRole('tabpanel', { name: /Select Product/ })
.getByRole('button', { name: 'Next' })
.click();
await page.getByLabel(/^Investment Amount/).fill(amount);
await page
.getByRole('tabpanel', { name: /Investment Amount/ })
.getByRole('button', { name: 'Next' })
.click();
const term = page.getByLabel(/^Investment Term \(days\)/);
if ((await term.evaluate((element) => element.tagName)) === 'INPUT') await term.fill(termDays);
else {
await term.click();
await page.getByRole('option', { name: `${termDays} days`, exact: true }).click();
}
await page
.getByRole('tabpanel', { name: /Investment Term/ })
.getByRole('button', { name: 'Next' })
.click();
await page
.getByRole('tabpanel', { name: /Investment Options/ })
.getByRole('button', { name: 'Next' })
.click();
const simulated = page.waitForResponse(
(response) =>
response.url().endsWith('/investment-products/simulations') && response.request().method() === 'POST'
);
await page.getByRole('button', { name: /^(Simulate|Simulate Without Funds)$/ }).click();
expect((await simulated).status()).toBe(200);
await expect(page.getByRole('heading', { name: 'Investment Projection' })).toBeVisible();
fs.mkdirSync('test-results/investment-simulator', { recursive: true });
await page.screenshot({ path: 'test-results/investment-simulator/live-result.png', fullPage: true });
fs.writeFileSync('test-results/investment-simulator/live-network.json', JSON.stringify(network, null, 2));
expect(blocked, 'backend writes other than the simulation POST').toEqual([]);
const writes = network.filter((entry) => !/^(GET|HEAD|OPTIONS)$/.test(entry.method));
expect(writes.map(({ method, path }) => ({ method, path }))).toEqual([
{ method: 'POST', path: '/fineract-provider/api/v1/investment-products/simulations' }
]);
});
});
Loading
Loading