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
17 changes: 6 additions & 11 deletions app/(shell)/daily-reports/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import type { DailyReportRecord } from "@/lib/storage/types";
import { isHostPrinterAvailable, printHostDocument, type PrintDocumentKind } from "@/lib/host/printing";
import { buildReportPrintDocument } from "@/lib/receipts/thermal-print";
import { warmUpReportPath } from "@/lib/host/warmup";
import { csvLine } from "@/lib/export/csv";

export default function DailyReportsPage() {
const symbol = useAssetSymbol();
Expand Down Expand Up @@ -313,22 +314,16 @@ export default function DailyReportsPage() {
"Timestamp", "Timestamp Formatted", "Terminal ID", "Refund Of",
];

const escCsv = (val: string | null) => {
if (val === null) return "";
if (val.includes(",") || val.includes('"') || val.includes("\n")) {
return `"${val.replace(/"/g, '""')}"`;
}
return val;
};

const rows = selectedReport.transactions.map(tx => [
// Report fields can come from a CID fetched off Bulletin, so every cell
// goes through the shared escaper (formula injection included).
const rows = selectedReport.transactions.map(tx => csvLine([
tx.saleId, tx.status, tx.amount, tx.amountFormatted, tx.asset,
tx.originalMerchant || tx.evmMerchant, tx.originalCustomer || tx.evmCustomer,
tx.txHash, tx.blockNumber, tx.timestamp, tx.timestampFormatted,
tx.terminalId, tx.refundOf ?? "",
].map(escCsv).join(","));
]));

const csv = [headers.join(","), ...rows].join("\n");
const csv = [csvLine(headers), ...rows].join("\n");
const blob = new Blob([csv], { type: "text/csv" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
Expand Down
9 changes: 7 additions & 2 deletions app/(shell)/settings/encryption/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {
getManualPassphrase,
clearManualPassphrase,
manualKeyFingerprint,
restoreManualPassphrase,
MIN_PASSPHRASE_LENGTH,
} from "@/lib/crypto/manual-key";
import { journeyTracker, breadcrumb } from "@/lib/telemetry";

Expand Down Expand Up @@ -81,7 +83,7 @@ export default function EncryptionSettingsPage() {
// Never overwrite a key set since the Clear.
if (!cleared || getManualPassphrase()) return;
if (undoTimer.current) clearTimeout(undoTimer.current);
setManualPassphrase(cleared);
restoreManualPassphrase(cleared);
setCleared(null);
refresh();
};
Expand Down Expand Up @@ -111,6 +113,9 @@ export default function EncryptionSettingsPage() {
<p>
Use the <span className="text-white">same phrase</span> on every device that needs to read the reports. If you change or lose it, older reports can no longer be opened.
</p>
<p>
Reports are stored publicly, so they are never saved without a key. A phrase of a few words ({MIN_PASSPHRASE_LENGTH} characters or more) is hard to guess.
</p>
</section>

{/* Current key fingerprint */}
Expand All @@ -125,7 +130,7 @@ export default function EncryptionSettingsPage() {
<span className="text-xs text-green-400">Set</span>
</div>
) : (
<span className="text-neutral-500 text-sm">No key set — reports will upload as plaintext</span>
<span className="text-neutral-500 text-sm">No key set — reports can&apos;t be saved until you set one</span>
)}
{cleared && (
<div
Expand Down
12 changes: 7 additions & 5 deletions app/(shell)/settings/merchant-profile/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
getManualPassphrase,
manualKeyFingerprint,
setManualPassphrase,
MIN_PASSPHRASE_LENGTH,
} from "@/lib/crypto/manual-key";

/**
Expand Down Expand Up @@ -81,10 +82,10 @@ export default function MerchantProfilePage() {
}

/**
* Report-encryption password. The 32-byte encryption key is derived from it
* (SHA-256, see lib/crypto/manual-key.ts) — the fingerprint shown after
* saving lets two terminals verify they share the same key without revealing
* the password. The secret lives in the manual-key store, never inside the
* Report-encryption password. Each report's key is derived from it with
* scrypt and a fresh salt (see lib/crypto/symmetric-report.ts) — the
* fingerprint shown after saving lets two terminals verify they share the
* same password without revealing it. The secret lives in the manual-key store, never inside the
* merchant profile JSON.
*/
function EncryptionPasswordSection() {
Expand Down Expand Up @@ -133,7 +134,8 @@ function EncryptionPasswordSection() {
</div>

<p className="text-neutral-500 text-xs mt-2">
Your reports are encrypted with a key derived from this password.
Your reports are encrypted with a key derived from this password. Use at
least {MIN_PASSPHRASE_LENGTH} characters.
{fingerprint && (
<>
{" "}
Expand Down
40 changes: 31 additions & 9 deletions app/(shell)/terminal/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ function TerminalPageInner() {
const [paymentReceivedAt, setPaymentReceivedAt] = useState<Date | null>(null);
// Coins claim that credited less than the cheque asked for (the host will
// claim no more) — shown on the completed screen next to the recorded amount.
const [coinsShortfall, setCoinsShortfall] = useState<{ requested: string; credited: string } | null>(null);
const [coinsShortfall, setCoinsShortfall] = useState<{ requested: string; credited: string; missing: string } | null>(null);
const [svgReceipt, setSvgReceipt] = useState<string | null>(null);
const [finalAmount, setFinalAmount] = useState<string>("");
const [showCancelModal, setShowCancelModal] = useState(false);
Expand Down Expand Up @@ -342,7 +342,16 @@ function TerminalPageInner() {
setPaymentReceivedAt(receivedAt);
setSaleId(result.paymentId);
setCoinsShortfall(
result.partial ? { requested: result.requestedAmount, credited: result.amount } : null,
result.partial
? {
requested: result.requestedAmount,
credited: result.amount,
missing: formatAmountFromPlanck(
amountToPlanck(result.requestedAmount, PUSD_DECIMALS) - amountToPlanck(result.amount, PUSD_DECIMALS),
PUSD_DECIMALS,
),
}
: null,
);

const receiptItems: ReceiptItem[] = pendingItems.map((line) => ({
Expand Down Expand Up @@ -393,9 +402,10 @@ function TerminalPageInner() {
setTerminalState("completed");
journeyTracker.complete("terminal-payment");
recordPaymentOutcome({
outcome: "success",
outcome: result.partial ? "partial" : "success",
method: "coins",
amount: result.amount,
...(result.partial ? { reason: `credited ${result.amount} of ${result.requestedAmount}` } : {}),
source: searchParams.get("source") ?? "direct",
saleId: result.paymentId,
terminalId: terminalId ?? undefined,
Expand Down Expand Up @@ -1314,10 +1324,15 @@ function TerminalPageInner() {
whole zone is filled (see .success-burst in globals.css);
overflow-hidden clips the disc to this zone, the details card
below keeps its container surface. */}
{/* A partial claim is not a success: the same burst in the warning
fill, an alert badge and its own title, so nobody at the till
mistakes it for a paid sale. */}
<div className="relative overflow-hidden basis-[40%] grow-0 shrink-0 flex flex-col">
<div
aria-hidden
className="success-burst absolute left-1/2 top-1/2 size-[1200px] rounded-full bg-status-success pointer-events-none"
className={`success-burst absolute left-1/2 top-1/2 size-[1200px] rounded-full pointer-events-none ${
coinsShortfall ? "bg-status-warning" : "bg-status-success"
}`}
/>

<div className="relative flex-1 flex flex-col">
Expand All @@ -1333,11 +1348,17 @@ function TerminalPageInner() {
</header>

<div className="flex-1 flex flex-col items-center justify-center pb-8">
<div className="success-badge size-16 rounded-full bg-status-success text-fg-static-white flex items-center justify-center mb-4">
<Check className="size-6" strokeWidth={3} />
</div>
{coinsShortfall ? (
<div className="warning-badge size-16 rounded-full bg-status-warning text-fg-static-white flex items-center justify-center mb-4">
<TriangleAlert className="size-6" strokeWidth={3} />
</div>
) : (
<div className="success-badge size-16 rounded-full bg-status-success text-fg-static-white flex items-center justify-center mb-4">
<Check className="size-6" strokeWidth={3} />
</div>
)}
<h2 data-testid="payment-completed" className="text-display-l text-fg-primary">
Payment received
{coinsShortfall ? "Partial payment" : "Payment received"}
</h2>
</div>
</div>
Expand Down Expand Up @@ -1371,7 +1392,8 @@ function TerminalPageInner() {
</p>
{coinsShortfall && (
<p data-testid="coins-shortfall" className="text-body-m text-fg-warning -mt-4 mb-6">
Received {coinsShortfall.credited} of {coinsShortfall.requested} {symbol}. The rest didn&apos;t arrive.
Not paid in full: {coinsShortfall.missing} {symbol} is missing. Only{" "}
{coinsShortfall.credited} of {coinsShortfall.requested} {symbol} arrived.
</p>
)}

Expand Down
17 changes: 16 additions & 1 deletion app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,24 @@ body {
.success-badge {
animation: success-badge-invert 0.30s ease-out 0.40s forwards;
}
/* The partial-payment twin: same timing, warning fill. */
@keyframes warning-badge-invert {
from {
background-color: var(--bg-status-warning);
color: var(--fg-static-white);
}
to {
background-color: var(--fg-static-white);
color: var(--bg-status-warning);
}
}
.warning-badge {
animation: warning-badge-invert 0.30s ease-out 0.40s forwards;
}
@media (prefers-reduced-motion: reduce) {
.success-burst,
.success-badge {
.success-badge,
.warning-badge {
animation-duration: 0.01ms;
animation-delay: 0s;
}
Expand Down
11 changes: 6 additions & 5 deletions e2e/payments/coins-outcomes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ async function openHistory(frame: FrameLocator) {
}

async function finishSale(frame: FrameLocator) {
await expect(frame.locator('[data-testid="payment-completed"]')).toHaveText("Payment received");
await expect(frame.locator('[data-testid="payment-completed"]')).toHaveText(/^(Payment received|Partial payment)$/);
await frame.locator('[data-testid="btn-done"]').click();
await expect(frame.locator('[data-testid="terminal-header"]')).toBeVisible();
}

/** The big amount on the "Payment received" screen: the first bare figure in its details card. */
/** The big amount on the completed screen: the first bare figure in its details card. */
const completedAmount = (frame: FrameLocator) => frame.locator('[data-testid="completed-amount"]');

/**
Expand Down Expand Up @@ -83,10 +83,11 @@ test.describe("coins claim outcomes", () => {

await host.emitTopUpStatus(topUp.idHex, { tag: "ClaimedPartially", actualClaimed: planck("5.00").toString() });

await expect(frame.locator('[data-testid="payment-completed"]')).toHaveText("Payment received");
// Not a success: its own title, and the missing part named.
await expect(frame.locator('[data-testid="payment-completed"]')).toHaveText("Partial payment");
await expect(frame.locator('[data-testid="sale-id"]')).toHaveText(`#${req.id.slice(-4)}`);
await expect(frame.locator('[data-testid="coins-shortfall"]')).toHaveText(
"Received 5.00 of 12.50 CASH. The rest didn't arrive.",
"Not paid in full: 7.50 CASH is missing. Only 5.00 of 12.50 CASH arrived.",
);

// Stored at the credited amount, with what was asked for, and final:
Expand Down Expand Up @@ -132,7 +133,7 @@ test.describe("coins claim outcomes", () => {
const { topUp } = await chargeAndPay(host, frame, "12.50");
await host.emitTopUpStatus(topUp.idHex, { tag: "ClaimedPartially", actualClaimed: planck("5.00").toString() });
await expect(frame.locator('[data-testid="coins-shortfall"]')).toHaveText(
"Received 5.00 of 12.50 CASH. The rest didn't arrive.",
"Not paid in full: 7.50 CASH is missing. Only 5.00 of 12.50 CASH arrived.",
);
await expect(completedAmount(frame)).toHaveText("5.00", { timeout: 5_000 });
});
Expand Down
11 changes: 8 additions & 3 deletions e2e/screens/merchant-and-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,15 @@ test.describe("settings", () => {
test("Report Encryption (URL-only): Save shows the key's fingerprint, kept on this device", async ({ host }) => {
await bootTerminal(host);
let frame = await restartOn(host, "/settings/encryption");
await expect(frame.getByText("No key set — reports will upload as plaintext")).toBeVisible();
await expect(frame.getByText("No key set — reports can't be saved until you set one")).toBeVisible();
const input = frame.getByPlaceholder("Enter a secret phrase");
const save = frame.getByRole("button", { name: "Save" });
await expect(save).toBeDisabled();
// Reports are public ciphertext: a short phrase is refused.
await input.fill("short key");
await save.click();
await expect(frame.getByText("Use at least 12 characters — a few words work well.")).toBeVisible();
await expect(frame.getByText("No key set — reports can't be saved until you set one")).toBeVisible();
await input.fill(" correct horse battery ");
await save.click();

Expand Down Expand Up @@ -271,7 +276,7 @@ test.describe("settings", () => {
await expect(frame.getByText(keyFingerprint("lunch shift key"), { exact: true })).toBeVisible();

await frame.getByRole("button", { name: "Clear" }).click();
await expect(frame.getByText("No key set — reports will upload as plaintext")).toBeVisible({ timeout: 5_000 });
await expect(frame.getByText("No key set — reports can't be saved until you set one")).toBeVisible({ timeout: 5_000 });
await expect(frame.getByTestId("encryption-key-cleared")).toContainText("can't be opened");

await frame.getByRole("button", { name: "Undo" }).click();
Expand All @@ -288,6 +293,6 @@ test.describe("settings", () => {
// Clearing for good survives a restart.
await frame.getByRole("button", { name: "Clear" }).click();
const after = await restartOn(host, "/settings/encryption");
await expect(after.getByText("No key set — reports will upload as plaintext")).toBeVisible();
await expect(after.getByText("No key set — reports can't be saved until you set one")).toBeVisible();
});
});
Loading
Loading