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
15 changes: 15 additions & 0 deletions frontend/e2e/cash-close-phase1-ui.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ test.describe('Cash close phase-1 UI', () => {

test('day close modal shows open-shift block from x-report', async ({ page }) => {
const today = new Date().toISOString().slice(0, 10);
await page.route('**/api/reports/daily-sales/export?*', async (route) => {
await route.fulfill({ contentType: 'text/html', body: '<p>Products</p>' });
});
await page.route('**/api/reports/x-report*', async (route) => {
await route.fulfill({
status: 200,
Expand Down Expand Up @@ -63,6 +66,18 @@ test.describe('Cash close phase-1 UI', () => {
await expect(blocker).toContainText('42');
await expect(blocker).toContainText('E2E Cashier');
await expect(dialog.getByRole('button', { name: /Continuar|Continue/i })).toBeDisabled();
await expect(dialog.getByText(/product report covers the full business day/i)).toBeVisible();
await page.evaluate(() => {
Object.defineProperty(window, 'electronAPI', {
value: { saveHtmlAsPdf: async () => ({ success: true }) },
});
});
const request = page.waitForRequest('**/api/reports/daily-sales/export?*');
await dialog.getByRole('button', { name: /Daily Sales Report.*PDF/i }).click();
const query = new URL((await request).url()).searchParams;
expect(query.get('date')).toBe(today);
expect(query.get('format')).toBe('html');
expect(query.has('session_id')).toBe(false);
});

test('shift close modal shows unpaid carry-over warning while keeping close button enabled', async ({
Expand Down
21 changes: 20 additions & 1 deletion frontend/e2e/diagnostics-checkout-recovery.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,7 @@ test('a KOT print failure preserves backend failure_class and sanitized detail i
});
});

const kotCorrelationId = '4a8c9d01-1234-4b5c-89ab-cdef01234567';
let kotCorrelationId = '4a8c9d01-1234-4b5c-89ab-cdef01234567';
await page.route('**/api/printers/print-kot', async (route) => {
await route.fulfill({
status: 502,
Expand Down Expand Up @@ -798,6 +798,25 @@ test('a KOT print failure preserves backend failure_class and sanitized detail i
connection_type: 'usb',
},
});
const queued = supportPanel.getByText('Your support request has been queued');
const dismiss = supportPanel.getByRole('button', { name: 'Dismiss' });
await expect(queued).toBeVisible();
await dismiss.click();
await addOneProduct(page);
await page.getByRole('button', { name: 'Place Order' }).click();
await expect(queued).toBeVisible();
await expect(supportPanel.getByRole('button', { name: 'Get help', exact: true })).toHaveCount(
0,
);
expect(supportSubmissions).toHaveLength(1);

await dismiss.click();
kotCorrelationId = '4a8c9d01-1234-4b5c-89ab-cdef01234568';
await addOneProduct(page);
await page.getByRole('button', { name: 'Place Order' }).click();
await supportPanel.getByRole('button', { name: 'Get help', exact: true }).click();
await expect.poll(() => supportSubmissions.length).toBe(2);
expect(supportSubmissions[1].client_ticket_id).not.toBe(supportSubmissions[0].client_ticket_id);
} finally {
await restoreBusiness(page, originalBusiness);
}
Expand Down
22 changes: 22 additions & 0 deletions frontend/e2e/server-app-ordering.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,28 @@ import { getE2eToken } from './helpers/test-auth';

const TOKEN_KEY = 'flocafe:server-app-token';

test('Server App explains an empty PIN roster and retries a failed roster request', async ({
page,
}) => {
let attempts = 0;
await page.route('**/api/auth/pin-users', async (route) => {
attempts += 1;
if (attempts === 1) {
await route.fulfill({ status: 503, json: {} });
return;
}
await route.fulfill({ json: { users: [] } });
});

await page.goto(`${E2E_SERVER_APP_BASE_URL}/server-standalone`);
await expect(page.getByText('Failed to load staff')).toBeVisible();
await expect(page.getByPlaceholder('Password', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Retry', exact: true }).click();
await expect(page.getByText(/No staff can sign in with a PIN yet/)).toBeVisible();
await expect(page.getByTestId('signin-mode-pin')).toHaveCount(0);
expect(attempts).toBe(2);
});

async function openServerApp(page: Page, serverToken: string): Promise<void> {
await page.goto(`${E2E_SERVER_APP_BASE_URL}/server-standalone`);
await page.evaluate(
Expand Down
21 changes: 15 additions & 6 deletions frontend/src/app/(dashboard)/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -466,18 +466,20 @@ export default function DashboardPage() {
router.replace('/dashboard', { scroll: false });
}, [cashCloseAction, cashCloseView, openCloseModal, router]);

const exportDailySales = async (format: 'xlsx' | 'csv' | 'pdf') => {
const exportDailySales = async (format: 'xlsx' | 'csv' | 'pdf', businessDate?: string) => {
if (isExporting) return;
setIsExporting(true);
try {
const dateParams =
periodMode === 'day'
const dateParams = businessDate
? { date: businessDate }
: periodMode === 'day'
? { date: selectedDate }
: { from: range.startDate, to: range.endDate };
const span =
periodMode === 'day' || range.startDate === range.endDate
businessDate ??
(periodMode === 'day' || range.startDate === range.endDate
? range.startDate
: `${range.startDate}_to_${range.endDate}`;
: `${range.startDate}_to_${range.endDate}`);

if (format === 'pdf') {
await exportReportAsPdf({
Expand Down Expand Up @@ -955,7 +957,14 @@ export default function DashboardPage() {
</div>
</div>

<CashCloseModal model={cashClose} />
<CashCloseModal
model={cashClose}
dailySalesExport={
tenantCan(currentTenant, 'reports.daily-sales.export')
? { busy: isExporting, exportPdf: (date) => void exportDailySales('pdf', date) }
: undefined
}
/>
<SendWhatsAppReportModal
open={dailySalesWhatsAppOpen}
country={currentTenant?.country ?? ''}
Expand Down
64 changes: 53 additions & 11 deletions frontend/src/app/(dashboard)/pos/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ export default function POSPage() {
operationFailure?: SupportOperationFailure;
ticketCorrelationId: string;
clientTicketId: string;
failureKey?: string;
context: SupportErrorContextSnapshot;
presentation: PosFailureSupportMetadata;
payload: Record<string, unknown>;
Expand All @@ -417,6 +418,10 @@ export default function POSPage() {
} | null>(null);
const [supportSubmitting, setSupportSubmitting] = useState(false);
const supportSubmitTokenRef = useRef<symbol | null>(null);
const currentSupportTicketRef = useRef<string | null>(null);
const supportTicketsRef = useRef(
new Map<string, { id: string; status: 'draft' | 'submitting' | 'queued' }>(),
);
const [sentTicketId, setSentTicketId] = useState<string | null>(null);
const delivery = useSupportTicketStatus(sentTicketId);
const activeUserId = user?.id == null ? null : String(user.id);
Expand Down Expand Up @@ -470,6 +475,7 @@ export default function POSPage() {
};
};
const clearSupportErrorState = () => {
currentSupportTicketRef.current = null;
supportSubmitTokenRef.current = null;
setSupportSubmitting(false);
setSupportError(null);
Expand Down Expand Up @@ -509,6 +515,8 @@ export default function POSPage() {
setPrepaidFailure(null);
isSendingToPaymentRef.current = false;
setSubmitting(false);
currentSupportTicketRef.current = null;
supportTicketsRef.current.clear();
supportSubmitTokenRef.current = null;
setSupportSubmitting(false);
setSupportError(null);
Expand Down Expand Up @@ -928,7 +936,23 @@ export default function POSPage() {
? entry.correlationId
: undefined;
const ticketCorrelationId = correlationId || createOperationReference() || '';
const clientTicketId = createOperationReference() || '';
const failureKey = correlationId
? JSON.stringify([
liveContext.storeId,
liveContext.userId,
liveContext.sessionEpoch,
correlationId,
entry.operation,
entry.reasonCode || entry.code,
entry.displayCode,
entry.operationFailure?.capture_point,
])
: undefined;
const existingTicket = failureKey ? supportTicketsRef.current.get(failureKey) : undefined;
const clientTicketId = existingTicket?.id || createOperationReference() || '';
if (failureKey && clientTicketId && !existingTicket) {
supportTicketsRef.current.set(failureKey, { id: clientTicketId, status: 'draft' });
}
const presentation = resolvePosFailureSupportMetadata({
operation: entry.operation,
classification: entry.classification,
Expand All @@ -945,11 +969,14 @@ export default function POSPage() {
correlationId && entry.operationFailure?.operation_id === correlationId
? entry.operationFailure
: undefined;
supportSubmitTokenRef.current = null;
setSupportSubmitting(false);
setSentTicketId(null);
setAttachLog(true);
supportLogSnapshotRef.current = null;
if (currentSupportTicketRef.current !== clientTicketId) {
supportSubmitTokenRef.current = null;
setSupportSubmitting(existingTicket?.status === 'submitting');
setAttachLog(true);
supportLogSnapshotRef.current = null;
currentSupportTicketRef.current = clientTicketId;
}
setSentTicketId(existingTicket?.status === 'queued' ? clientTicketId : null);
setSupportError({
title: entry.title,
subject,
Expand All @@ -966,6 +993,7 @@ export default function POSPage() {
operationFailure: matchedOperationFailure,
ticketCorrelationId,
clientTicketId,
failureKey,
context: {
storeId: liveContext.storeId,
userId: liveContext.userId,
Expand Down Expand Up @@ -4307,6 +4335,10 @@ export default function POSPage() {
return;
}
const submitToken = Symbol('pos-support-submit');
const ticket = targetError.failureKey
? supportTicketsRef.current.get(targetError.failureKey)
: undefined;
if (ticket && ticket.status !== 'draft') return;
supportSubmitTokenRef.current = submitToken;
setSupportSubmitting(true);
try {
Expand All @@ -4326,7 +4358,9 @@ export default function POSPage() {
: undefined,
);
if (!checkSessionCurrent(targetError.context)) {
clearSupportErrorState();
if (supportSubmitTokenRef.current === submitToken) {
clearSupportErrorState();
}
return;
}
if (supportSubmitTokenRef.current !== submitToken) {
Expand All @@ -4339,7 +4373,8 @@ export default function POSPage() {
};
}
if (!checkSessionCurrent(targetError.context)) {
clearSupportErrorState();
if (supportSubmitTokenRef.current === submitToken)
clearSupportErrorState();
return;
}
}
Expand All @@ -4351,29 +4386,36 @@ export default function POSPage() {
attachLog,
logTail,
});
if (ticket) ticket.status = 'submitting';
await api.post('/support-ticket', requestBody, {
headers: liveAuthHeadersFor(targetError.context),
});
if (!checkSessionCurrent(targetError.context)) {
clearSupportErrorState();
if (supportSubmitTokenRef.current === submitToken) clearSupportErrorState();
return;
}
if (ticket) ticket.status = 'queued';
if (currentSupportTicketRef.current === targetError.clientTicketId) {
setSentTicketId(targetError.clientTicketId);
}
if (supportSubmitTokenRef.current !== submitToken) {
return;
}
toast.success(tSupport('queued'));
setSentTicketId(targetError.clientTicketId);
} catch {
if (!checkSessionCurrent(targetError.context)) {
clearSupportErrorState();
if (supportSubmitTokenRef.current === submitToken) clearSupportErrorState();
return;
}
if (supportSubmitTokenRef.current === submitToken) {
toast.error(t('supportRequestQueueFailed'));
}
} finally {
if (ticket?.status === 'submitting') ticket.status = 'draft';
if (supportSubmitTokenRef.current === submitToken) {
supportSubmitTokenRef.current = null;
}
if (currentSupportTicketRef.current === targetError.clientTicketId) {
setSupportSubmitting(false);
}
}
Expand Down
45 changes: 39 additions & 6 deletions frontend/src/app/server-standalone/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
UserRound,
} from 'lucide-react';
import { Drawer, DrawerContent, DrawerTrigger } from '@/components/ui/drawer';
import { Button } from '@/components/ui/button';
import { FormEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { parsePhone } from '@/lib/phone';
import { useSyncServerLanguage } from '@/lib/i18n';
Expand Down Expand Up @@ -210,7 +211,11 @@ export default function ServerStandalonePage() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [rememberMe, setRememberMe] = useState(true);
const [pinUsers, setPinUsers] = useState<PinUser[]>([]);
const [pinRoster, setPinRoster] = useState<
{ status: 'loading' | 'error' } | { status: 'ready'; users: PinUser[] }
>({ status: 'loading' });
const [pinRosterAttempt, setPinRosterAttempt] = useState(0);
const pinUsers = pinRoster.status === 'ready' ? pinRoster.users : [];
const [selectedPinUser, setSelectedPinUser] = useState<PinUser | null>(null);
const [pin, setPin] = useState('');
const [pinError, setPinError] = useState('');
Expand Down Expand Up @@ -451,17 +456,20 @@ export default function ServerStandalonePage() {
api
.get('/api/auth/pin-users')
.then((res) => {
if (!cancelled && Array.isArray(res.data?.users)) {
setPinUsers(res.data.users);
}
if (cancelled) return;
setPinRoster(
Array.isArray(res.data?.users)
? { status: 'ready', users: res.data.users }
: { status: 'error' },
);
})
.catch(() => {
if (!cancelled) setPinUsers([]);
if (!cancelled) setPinRoster({ status: 'error' });
});
return () => {
cancelled = true;
};
}, [api, user, disabled, loading]);
}, [api, user, disabled, loading, pinRosterAttempt]);

useEffect(() => {
if (!api || !userId) return;
Expand Down Expand Up @@ -812,6 +820,7 @@ export default function ServerStandalonePage() {
setPin('');
setPinError('');
activeUserIdRef.current = loggedInUser.id;
setPinRoster({ status: 'loading' });
setUser(loggedInUser);
}

Expand Down Expand Up @@ -1566,6 +1575,30 @@ export default function ServerStandalonePage() {
</form>
)}

{pinUsers.length === 0 && (
<div className="mt-4 space-y-2 text-center text-xs text-muted-foreground">
<p role="status">
{pinRoster.status === 'loading'
? tCommon('loading')
: pinRoster.status === 'error'
? tStaff('failedToLoad')
: t('pinRosterEmpty')}
</p>
{pinRoster.status === 'error' && (
<Button
variant="outline"
size="sm"
onClick={() => {
setPinRoster({ status: 'loading' });
setPinRosterAttempt((attempt) => attempt + 1);
}}
>
{tSettings('retry')}
</Button>
)}
{pinRoster.status === 'ready' && <p>{tStaff('pinHint')}</p>}
</div>
)}
<p className="mt-4 text-center text-xs text-muted-foreground">{t('loginHint')}</p>
</div>
</div>
Expand Down
Loading
Loading