chore(web): merge protected session mvp updates

This commit is contained in:
José René White Enciso 2026-03-08 17:18:35 -06:00
commit aa9ac91617
9 changed files with 517 additions and 52 deletions

View File

@ -4,6 +4,18 @@
- Frontend data access flows through `src/api/*` adapter modules.
- The UI does not access DAL or internal services directly.
- Route shell and protected sections are session-aware via Thalos session endpoints.
- Runtime base URLs:
## Runtime Base URLs
- `API_BASE_URL` for business BFF calls.
- `THALOS_AUTH_BASE_URL` for session login/refresh/logout/me.
## Protected Workflow Endpoints
- `GET /api/pos/transactions/summary?contextId=...`
- `POST /api/pos/transactions/payments`
## UI Workflow Coverage
- POS summary lookup
- POS payment capture

View File

@ -14,9 +14,9 @@ npm run test:ci
## Coverage Scope
- `src/api/client.test.ts`: runtime-config precedence and fallback behavior
- `src/api/dashboardApi.test.ts`: endpoint path/query contract generation
- `src/App.test.tsx`: render baseline and mocked load flow
- `src/api/client.test.ts`: runtime-config precedence and fallback behavior.
- `src/api/dashboardApi.test.ts`: endpoint path/query composition and payload mapping.
- `src/App.test.tsx`: protected-route render and workflow trigger behavior.
## Notes

View File

@ -1,31 +1,66 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('./api/dashboardApi', () => ({
loadDashboard: vi.fn()
vi.mock('./api/sessionApi', () => ({
getSessionMe: vi.fn(),
loginSession: vi.fn(),
refreshSession: vi.fn(),
logoutSession: vi.fn()
}));
import { loadDashboard } from './api/dashboardApi';
vi.mock('./api/dashboardApi', () => ({
loadDashboard: vi.fn(),
capturePosPayment: vi.fn()
}));
import { capturePosPayment, loadDashboard } from './api/dashboardApi';
import { getSessionMe } from './api/sessionApi';
import App from './App';
describe('App', () => {
it('renders baseline page', () => {
describe('POS Transactions App', () => {
beforeEach(() => {
vi.mocked(loadDashboard).mockReset();
vi.mocked(capturePosPayment).mockReset();
vi.mocked(getSessionMe).mockReset();
});
it('loads transaction summary for authenticated users', async () => {
vi.mocked(getSessionMe).mockResolvedValue({
isAuthenticated: true,
subjectId: 'demo-user',
tenantId: 'demo-tenant',
provider: 0
});
vi.mocked(loadDashboard).mockResolvedValue({ contextId: 'demo-context', summary: 'summary' });
render(<App />);
expect(screen.getByRole('heading', { name: 'POS Transactions Web' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Load' })).toBeInTheDocument();
await waitFor(() => expect(screen.getByRole('button', { name: 'Load Summary' })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: 'Load Summary' }));
await waitFor(() => expect(loadDashboard).toHaveBeenCalledWith('demo-context'));
});
it('captures payment from action route', async () => {
vi.mocked(getSessionMe).mockResolvedValue({
isAuthenticated: true,
subjectId: 'demo-user',
tenantId: 'demo-tenant',
provider: 0
});
vi.mocked(capturePosPayment).mockResolvedValue({
contextId: 'demo-context',
transactionId: 'POS-9001',
succeeded: true,
summary: 'captured'
});
it('loads dashboard data when user clicks load', async () => {
vi.mocked(loadDashboard).mockResolvedValue({ summary: 'ok' });
render(<App />);
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'ctx stage28' } });
fireEvent.click(screen.getByRole('button', { name: 'Load' }));
await waitFor(() => expect(screen.getByRole('button', { name: 'Capture Payment' })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: 'Capture Payment' }));
fireEvent.click(screen.getByRole('button', { name: 'Capture Payment Now' }));
await waitFor(() => {
expect(loadDashboard).toHaveBeenCalledWith('ctx stage28');
expect(screen.getByText(/summary/)).toBeInTheDocument();
});
await waitFor(() => expect(capturePosPayment).toHaveBeenCalledTimes(1));
});
});

View File

@ -1,41 +1,267 @@
import { useState } from 'react';
import { loadDashboard } from './api/dashboardApi';
import {
capturePosPayment,
loadDashboard,
type CapturePosPaymentRequest,
type CapturePosPaymentResponse,
type PosTransactionSummaryResponse
} from './api/dashboardApi';
import { SessionProvider, useSessionContext } from './auth/sessionContext';
import type { IdentityProvider } from './api/sessionApi';
type RouteKey = 'overview' | 'actions';
function App() {
return (
<SessionProvider>
<PosTransactionsShell />
</SessionProvider>
);
}
function PosTransactionsShell() {
const session = useSessionContext();
const [route, setRoute] = useState<RouteKey>('overview');
const [contextId, setContextId] = useState('demo-context');
const [payload, setPayload] = useState<unknown>(null);
const [summaryPayload, setSummaryPayload] = useState<PosTransactionSummaryResponse | null>(null);
const [paymentRequest, setPaymentRequest] = useState<CapturePosPaymentRequest>({
contextId: 'demo-context',
transactionId: 'POS-9001',
amount: 25.5,
currency: 'USD',
paymentMethod: 'card'
});
const [paymentResponse, setPaymentResponse] = useState<CapturePosPaymentResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const onLoad = async (): Promise<void> => {
const loadSummary = async () => {
setLoading(true);
setError(null);
try {
const response = await loadDashboard(contextId);
setPayload(response);
const payload = await loadDashboard(contextId);
setSummaryPayload(payload);
setPaymentRequest((previous) => ({ ...previous, contextId }));
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown request error';
setError(message);
setPayload(null);
setError(err instanceof Error ? err.message : 'Failed to load transaction summary.');
} finally {
setLoading(false);
}
};
const capturePayment = async () => {
setLoading(true);
setError(null);
try {
const payload = await capturePosPayment(paymentRequest);
setPaymentResponse(payload);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to capture payment.');
} finally {
setLoading(false);
}
};
if (session.status === 'loading') {
return (
<main className="app">
<h1>POS Transactions Web</h1>
<p>React baseline wired to its corresponding BFF via an API adapter module.</p>
<div className="row">
<input value={contextId} onChange={(event) => setContextId(event.target.value)} />
<button type="button" onClick={onLoad} disabled={loading}>
{loading ? 'Loading...' : 'Load'}
</button>
</div>
{error && <p>{error}</p>}
<pre>{JSON.stringify(payload, null, 2)}</pre>
<p className="muted">Restoring session...</p>
</main>
);
}
if (session.status !== 'authenticated' || !session.profile) {
return (
<main className="app">
<h1>POS Transactions Web</h1>
<p className="muted">Sign in with Thalos to access protected routes.</p>
{session.error && <div className="alert">{session.error}</div>}
<LoginCard />
</main>
);
}
return (
<main className="app">
<h1>POS Transactions Web</h1>
<p className="muted">Transaction summary and payment capture MVP workflows.</p>
<section className="card row">
<span className="badge">subject: {session.profile.subjectId}</span>
<span className="badge">tenant: {session.profile.tenantId}</span>
<span className="badge">provider: {providerLabel(session.profile.provider)}</span>
<span className="spacer" />
<button type="button" className="secondary" onClick={() => void session.refresh()}>
Refresh Session
</button>
<button type="button" className="warn" onClick={() => void session.logout()}>
Logout
</button>
</section>
<section className="card tabs" aria-label="route-shell">
<button
type="button"
className={route === 'overview' ? 'active' : undefined}
onClick={() => setRoute('overview')}
>
Summary
</button>
<button
type="button"
className={route === 'actions' ? 'active' : undefined}
onClick={() => setRoute('actions')}
>
Capture Payment
</button>
</section>
{session.error && <div className="alert">{session.error}</div>}
{error && <div className="alert">{error}</div>}
{route === 'overview' && (
<section className="card col">
<div className="row">
<label className="col">
Context Id
<input value={contextId} onChange={(event) => setContextId(event.target.value)} />
</label>
<button type="button" onClick={() => void loadSummary()} disabled={loading}>
{loading ? 'Loading...' : 'Load Summary'}
</button>
</div>
<pre>{JSON.stringify(summaryPayload, null, 2)}</pre>
</section>
)}
{route === 'actions' && (
<section className="card col">
<div className="grid">
<label className="col">
Context Id
<input
value={paymentRequest.contextId}
onChange={(event) => setPaymentRequest((previous) => ({ ...previous, contextId: event.target.value }))}
/>
</label>
<label className="col">
Transaction Id
<input
value={paymentRequest.transactionId}
onChange={(event) => setPaymentRequest((previous) => ({ ...previous, transactionId: event.target.value }))}
/>
</label>
<label className="col">
Amount
<input
type="number"
min={0}
step="0.01"
value={paymentRequest.amount}
onChange={(event) =>
setPaymentRequest((previous) => ({
...previous,
amount: Math.max(0, Number(event.target.value) || 0)
}))
}
/>
</label>
<label className="col">
Currency
<input
value={paymentRequest.currency}
onChange={(event) => setPaymentRequest((previous) => ({ ...previous, currency: event.target.value.toUpperCase() }))}
/>
</label>
<label className="col">
Payment Method
<input
value={paymentRequest.paymentMethod}
onChange={(event) => setPaymentRequest((previous) => ({ ...previous, paymentMethod: event.target.value }))}
/>
</label>
</div>
<button type="button" onClick={() => void capturePayment()} disabled={loading}>
{loading ? 'Capturing...' : 'Capture Payment Now'}
</button>
<pre>{JSON.stringify(paymentResponse, null, 2)}</pre>
</section>
)}
</main>
);
}
function LoginCard() {
const session = useSessionContext();
const [subjectId, setSubjectId] = useState('demo-user');
const [tenantId, setTenantId] = useState('demo-tenant');
const [provider, setProvider] = useState<IdentityProvider>(0);
const [externalToken, setExternalToken] = useState('');
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const onSubmit = async () => {
setSubmitting(true);
setError(null);
try {
await session.login({ subjectId, tenantId, provider, externalToken });
} catch (err) {
setError(err instanceof Error ? err.message : 'Login failed.');
} finally {
setSubmitting(false);
}
};
return (
<section className="card col">
<div className="grid">
<label className="col">
Subject Id
<input value={subjectId} onChange={(event) => setSubjectId(event.target.value)} />
</label>
<label className="col">
Tenant Id
<input value={tenantId} onChange={(event) => setTenantId(event.target.value)} />
</label>
<label className="col">
Provider
<select value={String(provider)} onChange={(event) => setProvider(Number(event.target.value) as IdentityProvider)}>
<option value="0">Internal JWT</option>
<option value="1">Azure AD (simulated)</option>
<option value="2">Google (simulated)</option>
</select>
</label>
</div>
<label className="col">
External Token (optional)
<input value={externalToken} onChange={(event) => setExternalToken(event.target.value)} />
</label>
<button type="button" onClick={() => void onSubmit()} disabled={submitting}>
{submitting ? 'Signing In...' : 'Sign In'}
</button>
{error && <div className="alert">{error}</div>}
</section>
);
}
function providerLabel(provider: IdentityProvider): string {
if (provider === 0 || provider === '0' || provider === 'InternalJwt') {
return 'Internal JWT';
}
if (provider === 1 || provider === '1' || provider === 'AzureAd') {
return 'Azure AD';
}
if (provider === 2 || provider === '2' || provider === 'Google') {
return 'Google';
}
return String(provider);
}
export default App;

View File

@ -1,18 +1,39 @@
import { describe, expect, it, vi } from 'vitest';
vi.mock('./client', () => ({
getJson: vi.fn()
getJson: vi.fn(),
postJson: vi.fn()
}));
import { getJson } from './client';
import { loadDashboard } from './dashboardApi';
import { getJson, postJson } from './client';
import { capturePosPayment, loadDashboard } from './dashboardApi';
describe('loadDashboard', () => {
it('builds encoded endpoint path and delegates to getJson', async () => {
describe('pos transactions dashboard api', () => {
it('builds encoded summary endpoint path', async () => {
vi.mocked(getJson).mockResolvedValue({ ok: true });
await loadDashboard('demo context/1');
await loadDashboard('ctx pos/1');
expect(getJson).toHaveBeenCalledWith('/api/pos/transactions/summary?contextId=demo%20context%2F1');
expect(getJson).toHaveBeenCalledWith('/api/pos/transactions/summary?contextId=ctx%20pos%2F1');
});
it('posts payment capture payload', async () => {
vi.mocked(postJson).mockResolvedValue({ succeeded: true });
await capturePosPayment({
contextId: 'ctx',
transactionId: 'POS-1',
amount: 14.5,
currency: 'USD',
paymentMethod: 'card'
});
expect(postJson).toHaveBeenCalledWith('/api/pos/transactions/payments', {
contextId: 'ctx',
transactionId: 'POS-1',
amount: 14.5,
currency: 'USD',
paymentMethod: 'card'
});
});
});

View File

@ -1,5 +1,29 @@
import { getJson } from './client';
import { getJson, postJson } from './client';
export async function loadDashboard(contextId: string): Promise<unknown> {
return getJson(`/api/pos/transactions/summary?contextId=${encodeURIComponent(contextId)}`);
export type PosTransactionSummaryResponse = {
contextId: string;
summary: string;
};
export type CapturePosPaymentRequest = {
contextId: string;
transactionId: string;
amount: number;
currency: string;
paymentMethod: string;
};
export type CapturePosPaymentResponse = {
contextId: string;
transactionId: string;
succeeded: boolean;
summary: string;
};
export async function loadDashboard(contextId: string): Promise<PosTransactionSummaryResponse> {
return getJson<PosTransactionSummaryResponse>(`/api/pos/transactions/summary?contextId=${encodeURIComponent(contextId)}`);
}
export async function capturePosPayment(request: CapturePosPaymentRequest): Promise<CapturePosPaymentResponse> {
return postJson<CapturePosPaymentResponse>('/api/pos/transactions/payments', request);
}

View File

@ -1,24 +1,26 @@
import { getJson, getThalosAuthBaseUrl, postJson, postNoContent } from './client';
export type IdentityProvider = 0 | 1 | 2 | string | number;
export type SessionProfile = {
isAuthenticated: boolean;
subjectId: string;
tenantId: string;
provider: string;
provider: IdentityProvider;
};
export type SessionLoginRequest = {
subjectId: string;
tenantId: string;
correlationId: string;
provider: string;
provider: IdentityProvider;
externalToken: string;
};
export type SessionLoginResponse = {
subjectId: string;
tenantId: string;
provider: string;
provider: IdentityProvider;
expiresInSeconds: number;
};

120
src/auth/sessionContext.tsx Normal file
View File

@ -0,0 +1,120 @@
import { createContext, type PropsWithChildren, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { ApiError } from '../api/client';
import {
getSessionMe,
loginSession,
logoutSession,
refreshSession,
type SessionLoginRequest,
type SessionProfile
} from '../api/sessionApi';
export type SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';
type SessionContextValue = {
status: SessionStatus;
profile: SessionProfile | null;
error: string | null;
login: (request: Omit<SessionLoginRequest, 'correlationId'> & { correlationId?: string }) => Promise<void>;
refresh: () => Promise<void>;
logout: () => Promise<void>;
revalidate: () => Promise<void>;
};
const SessionContext = createContext<SessionContextValue | undefined>(undefined);
export function SessionProvider({ children }: PropsWithChildren) {
const [status, setStatus] = useState<SessionStatus>('loading');
const [profile, setProfile] = useState<SessionProfile | null>(null);
const [error, setError] = useState<string | null>(null);
const revalidate = useCallback(async () => {
try {
const me = await getSessionMe();
if (me.isAuthenticated) {
setProfile(me);
setStatus('authenticated');
} else {
setProfile(null);
setStatus('unauthenticated');
}
setError(null);
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
setProfile(null);
setStatus('unauthenticated');
setError(null);
return;
}
const message = err instanceof Error ? err.message : 'Session validation failed.';
setProfile(null);
setStatus('unauthenticated');
setError(message);
}
}, []);
useEffect(() => {
void revalidate();
}, [revalidate]);
const login = useCallback<SessionContextValue['login']>(
async (request) => {
setError(null);
await loginSession({
...request,
correlationId: request.correlationId && request.correlationId.length > 0 ? request.correlationId : createCorrelationId()
});
await revalidate();
},
[revalidate]
);
const refresh = useCallback(async () => {
setError(null);
await refreshSession();
await revalidate();
}, [revalidate]);
const logout = useCallback(async () => {
setError(null);
try {
await logoutSession();
} finally {
setProfile(null);
setStatus('unauthenticated');
}
}, []);
const value = useMemo<SessionContextValue>(
() => ({
status,
profile,
error,
login,
refresh,
logout,
revalidate
}),
[status, profile, error, login, refresh, logout, revalidate]
);
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
}
export function useSessionContext(): SessionContextValue {
const value = useContext(SessionContext);
if (!value) {
throw new Error('useSessionContext must be used within SessionProvider.');
}
return value;
}
function createCorrelationId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return `corr-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}

View File

@ -77,6 +77,11 @@ button.warn {
background: #b91c1c;
}
button.ghost {
background: #e2e8f0;
color: #0f172a;
}
button:disabled {
cursor: not-allowed;
opacity: 0.6;
@ -110,6 +115,26 @@ button:disabled {
font-weight: 600;
}
.tabs {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.tabs button {
background: #dbeafe;
color: #1e3a8a;
}
.tabs button.active {
background: #1d4ed8;
color: #ffffff;
}
.spacer {
flex: 1;
}
pre {
margin: 0;
background: #0f172a;