feat(apps): a sales expert can work inside their customer's account (D29)

Reported missing by the owner: in the reference an expert could open any
of their referred customers and use the app AS them — browse, see
balance and debt, place orders — «یکجورایی انگار با اکانت اون ها لاگین
کرده». D21 had deliberately left it out as a session-hijack primitive.
The owner asked for the capability back with the implementation left to
judgement, so the scope is the reference's and the mechanism is not.

Scope: everything, as the reference had it. Its axios interceptor
swapped the bearer token, so every request went as the customer,
document upload included. No route is closed in act-as mode.

Mechanism: the reference minted and handed over the customer's own
permanent api_token. Here the expert keeps their own token and sends
X-Act-As-Customer, resolved in one place — CustomerJwtStrategy
.validateExpert. That single point is why all 17 customer routes work
unchanged: validate() already returns a principal whose `id` is a
Customer id and every customer route reads it. It also fixes four real
defects of the original:

  - ownership is re-checked on EVERY request, with referredByAgentId in
    the same where clause as the id, so another expert's customer and a
    non-existent id both answer 403, and a customer moved to another
    expert loses access at once rather than at token expiry;
  - nothing durable is handed out — the reference's token sat in
    localStorage with no expiry and kept working after the expert left;
  - adminUserId survives, so an order placed this way is attributable;
    in the reference the request was literally the customer's;
  - 403 rather than 401, so the app clears the act-as state instead of
    logging a perfectly valid session out.

Performance: one findFirst on the primary key, only when the header is
present, and it replaces the trading-account lookup rather than adding
to it.

Three things the reference never needed, because it swapped the whole
session. queryCache's `me:` keys, favouritesStore and wageQuoteStore all
dropped their data on a TOKEN change, which act-as does not cause — so
an expert would have seen their own profile, orders, balance, ledger and
favourites inside the customer's account. The wage-quote one is the
money case: making charge is per customer, so the figure on screen would
not have been the one the order was priced at. And uploadDocument builds
its own headers, so an expert's upload would have been filed against
their own account, silently.

Added with no reference equivalent: a permanent «در حال مشاهده به‌عنوان
…» bar. There, impersonation was invisible once the token had been
swapped, and placing an order on the wrong customer's gold debt was one
tap away. It is also the exit — the reference's only way out was a
logout that ended the expert's own session too. The cart is cleared in
both directions.

CustomerJwtStrategy had no test coverage at all and is now where this
feature's whole authorisation boundary lives: act-as-customer.spec.ts
covers 11 cases, including the header being ignored on a customer token,
the no-header path asserting the extra query does not run, and a revoked
session short-circuiting before the header is read.

api: 308/308 tests, 28 suites; both apps vue-tsc clean.

اپ: کارشناس فروش می‌تواند وارد حساب مشتریان خود شود، وضعیتشان را ببیند و از طرفشان سفارش ثبت کند.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
s.esmaeili
2026-10-12 11:48:59 +03:30
co-authored by Claude Opus 5
parent c518f9995b
commit ddcc8c5649
28 changed files with 1337 additions and 46 deletions
+35 -1
View File
@@ -2,6 +2,8 @@ import type { CreateOrderDto } from '@gold-bank/shared-types';
const BASE = '/api';
const TOKEN_KEY = 'gold-bank:token';
/** Must match stores/session.ts — the act-as target, if any. */
const ACTING_AS_KEY = 'gold-bank:actingAs';
/**
* Called when the API rejects our token. Wired up in main.ts rather than
@@ -30,8 +32,28 @@ function readToken(): string | null {
}
}
/**
* «ورود به حساب مشتری» — the customer a sales expert is working inside.
*
* Read from storage rather than the store for the same reason as the token: this
* module must not depend on Pinia. The server treats this as a request, not a
* fact: it re-checks on every call that the customer is actually referred by
* this expert, so a forged value is a 403 and reveals nothing.
*/
function readActingAsId(): string | null {
try {
const raw = sessionStorage.getItem(ACTING_AS_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as { id?: unknown };
return typeof parsed?.id === 'string' && parsed.id ? parsed.id : null;
} catch {
return null;
}
}
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const token = readToken();
const actingAs = readActingAsId();
const res = await fetch(`${BASE}${path}`, {
...options,
@@ -40,6 +62,11 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
// Customer JWT from POST /customer/auth/verify-otp. The API derives the
// customer from this, never from an id in the URL.
...(token ? { Authorization: `Bearer ${token}` } : {}),
// Sent on every request while impersonating, which is what makes the whole
// app render from the customer's point of view — the reference achieved
// the same by swapping the bearer token in its axios interceptor
// (henza_pwa plugins/axios.ts:18 via getUserToken()).
...(actingAs ? { 'X-Act-As-Customer': actingAs } : {}),
...options?.headers,
},
});
@@ -420,10 +447,17 @@ export const api = {
body.append('purpose', purpose);
const token = readToken();
// This route bypasses `request()`, so the act-as header has to be repeated
// here — without it an expert uploading a customer's documents would file
// them against their OWN account, silently and with no error.
const actingAs = readActingAsId();
const res = await fetch(`${BASE}/customer/me/documents`, {
method: 'POST',
// No Content-Type: the browser sets it with the boundary.
headers: token ? { Authorization: `Bearer ${token}` } : {},
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(actingAs ? { 'X-Act-As-Customer': actingAs } : {}),
},
body,
});