9 Commits
Author SHA1 Message Date
s.esmaeiliandClaude Sonnet 4.6 8b74c85a2a fix(accounting): verify and fix Zarrin driver on real v228 install
Tested 20/20 on the owner's live Zarrin v228 (870 accounts, 656 items):

Reads fixed:
- listKarSakhte: now pages by 100 via pageNum (was returning only first 100 of 656)
- goroohSakhte: HTTP 400 with a valid body is now accepted (was treated as missing)
- parvande «مانده از قبل» row is not a balance; skip it and anchor the running
  balance on the live listMandeHesabha balance, walked back through movements
- infogardeshsakhte: hand-printed JSON repaired, timeout raised to 90s
- document delete: now searches all ledger pages, not just the first one
- listhesabha names are «first * last»; the «*» is now stripped
- keep-alive ECONNRESET: a socket hang-up on a reused connection is retried once
  on a fresh connection (server closes idle connections)

Writes fixed (test account 953 «تست اپ گلدبانک»):
- temporary flag: set from shomareSanad («موقت»), not noeFactor
- noeFactor «فاکتور موقت» also flags a document left open in Zarrin's own UI

New: test script apps/api/scripts/test-accounting-zarrin.ts (13 read + 7 write checks)
Docs: §13 added to ACCOUNTING-INTEGRATION-PLAN.md; ACC-01 in ISSUES.md updated
New: docs/FRESH-SERVER-DEPLOY-AUDIT.md (fresh-server deploy checklist)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-12 15:23:24 +03:30
s.esmaeiliandClaude Opus 5 9fc0886a57 feat(apps): read products by id instead of loading the whole catalogue
Step 3 of docs/CATALOG-PAGINATION-PLAN.md. Step 2 added the targeted
routes; these are the five callers that were fetching all ~16k products
to find a handful of rows:

  product screen    whole catalogue, then find(id)  -> GET /products/:id
  cart re-sync      whole catalogue for 2-3 lines   -> ?ids=
  favourites        whole catalogue, filtered here  -> ?ids=
  home categories   categories derived from it      -> /products/facets
  order row labels  joined on variantId             -> included with the order

Three of these were not merely slow, they were going to be wrong.
Favourites filtered the loaded catalogue, so once the list pages a
favourite outside the loaded slice silently disappears. Home categories
were derived the same way, so a category whose products all sit further
down would vanish from the home screen. Order rows looked their title up
in the catalogue, which ALREADY failed for a product that had since left
the storefront — exactly the old orders history exists for — and
rendered a blank row.

Order labels went to the server rather than to another id lookup: the
item carries productVariantId, not a product id, so ?ids= could not
answer it. One nested include in getOrders returns the variant, its
product and the product's first image. Deliberately NOT filtered by
storefront visibility, so a de-listed product still shows what was
bought; asserted in the new spec. OrderItemCard is synchronous now — no
fetch, no onMounted, the row renders complete on its first frame.

variantLookup is deleted from catalogStore rather than left behind: it
existed only to label order rows, and keeping it would have kept a
reason to load the full catalogue.

getProductsByIds chunks at 100 because the route caps ids there and
drops the rest. A partial answer reads to callers as "these products are
no longer on the storefront" — the cart would silently drop valid lines.
Favourites already run to 874 rows in the imported data (FAV-01).

A failed cart re-sync now leaves the cart alone: it is the person's own
data in localStorage, and dropping lines because the network blinked is
worse than a slightly stale price. The product screen tells a real 404
from a failed request, so only the former renders the not-found page.

One bug introduced and caught while doing this: moving the home
categories to /facets meant memory.init() no longer loaded the catalogue
as a side effect, and the home rails read catalog.products — the home
screen would have rendered empty rails. HomeView now loads it
explicitly. Found by grepping every caller of configStore.init, which is
also how I know HomeView is the only one.

Still on the unpaged list by design: the home rails and the
search/newest lists. Moving those onto paged reads is step 4, kept
separate because it is the risky part — debounce, loading state, and
telling "no results" from "still loading".

api 334/334 across 30 suites; both apps vue-tsc clean. getOrders has a
spec now (3 cases) because its include is a contract both apps depend on
and the method had no test at all. Nothing click-tested — the cart
re-sync and the favourites screen are the two worth a manual pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-12 15:19:50 +03:30
s.esmaeiliandClaude Opus 5 cbb93dec5d feat(catalog): page and filter the storefront server-side (steps 1-2)
The real catalogue reaches ~16k products and GET /catalog/products had no
paging parameters at all: it returned every active product with its
variants, images, category, brand and collections in one response. The
apps' PAGE_SIZE = 20 was only a render window over that full array, so
scrolling made zero requests. The reference paged this server-side; the
port had moved it to the client (STUB-03), so this is a return to
reference behaviour.

Step 1 — indexes, which were not optional. Product carried NO index
whatsoever (not isActive, categoryId, brandId or createdAt) and
ProductVariant had none on productId, so every per-product include
scanned its whole table. Adding take/skip on top of that would have
paged the response without making the query faster, which is the exact
failure this change exists to avoid. Product_isActive_createdAt_idx is
composite so one index serves the filter, the default ordering and the
OFFSET walk.

CREATE INDEX, not CONCURRENTLY: the deploy image's migration runner
wraps each file in a transaction, which CONCURRENTLY cannot join (D15).
Every statement is IF NOT EXISTS because both migration paths run it.

Step 2 — the routes. Paging is opt-in, which is the whole
backward-compatibility story: with no query parameters the route returns
the same plain array from the same cache as before, so the admin panel,
the smoke scripts and installed app builds are untouched. Pass page,
limit or any filter and it becomes { rows, total, page, limit }.

The filters had to move too, not just the paging. The apps filtered
title, category, brand and gram range in the browser over the full
array; paging the response while leaving that in place would have made
search quietly WRONG — searching only the first page and reporting
"محصولی پیدا نشد" for products that exist. So every filter is built into
the Prisma query, and count uses the same where clause, so `total`
describes the set the app is actually scrolling.

Three routes added so the apps can stop fetching everything to find one
thing (wired up in step 3): ?ids=a,b,c for the cart, favourites and
order items; /:id for the product screen, which today downloads the
whole catalogue to find one row; /facets for the filter sheet's options,
which the apps currently derive by scanning the catalogue in the
browser.

Deliberately not cached: CatalogCacheService exists because the unpaged
query is expensive and every screen wanted it. A paged, filtered query
is neither — bounded by limit and index-served — and caching it would
need a key per filter combination, i.e. unbounded memory for cheap
queries plus a second place for stale rows to hide.

D27's two storefront rules (active, has an image) live in one shared
where clause, so the list, its count, the single-product route, by-ids
and the facets can never disagree about what is visible. limit and ids
are both capped at 100; an uncapped limit is just the old "give me
everything" query spelled differently.

17 new cases, 329/329 overall. All 17 passed on the first run, which is
not evidence by itself, so one filter was deliberately broken to confirm
the suite catches it (1 failed/16 passed) and then restored.

Not measured on real data — the database container was not running, so
16k-row behaviour is reasoned from the query plan, not timed. Worth one
EXPLAIN ANALYZE on a full dataset before step 4.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-12 15:01:32 +03:30
s.esmaeiliandClaude Opus 5 bfbac92df5 fix(apps): back button follows real history; screens re-read on entry
Reported: from the profile page, going to login and pressing back landed
on home instead of the profile — with the instruction to audit the whole
structure rather than that one case. Seven defects, four reachable in
ordinary use.

NAVIGATION

PageBar's back arrow pushed a FIXED route name (`backTo`) and ignored
history, so it could not know where the person came from. That was true
of 14 of the 15 PageBar uses in each app — only SearchView used
router.back() — so it was never one screen's bug. Inherited from the
reference, which pushed a fixed name in every component's back arrow;
not replicated (D4).

`backTo` is now a fallback, used only when there is nothing to go back
to (a shared link, a refresh). All 14 declarations are kept untouched,
because that is exactly when they are right.

Answering "is there anywhere to go back to?" needs care: history.length
counts entries from before the app was opened, so a link opened in a
fresh tab would look navigable and back would walk the person out of the
app. navStore records the history `position` of the app's first
navigation and compares the current one against it — direction-proof,
unlike a counter, which only grows and would be wrong after one
back-and-forward. Confirmed vue-router writes `position` on every entry
rather than assuming it.

Three pushes became replaces, each of which left behind a page the
guards immediately bounce, making "back" a no-op or a trip home:
  - after sign-in the login screen stayed in history — the worst, since
    the same file already honoured ?redirect=, so signing in and
    pressing back disagreed about where the person belonged;
  - the 401 handler kept the page whose request had just failed;
  - complete-profile kept a form that is unreachable once the documents
    are in.
CartView's post-order push is left alone: back lands on the emptied
cart, which is a real screen, not a dead end.

READ FRESHNESS

Owner's rule: fetch what a screen needs when it is opened, rather than
caching with a lifetime. Better than the TTL I had proposed — a TTL
guesses how long data stays true, while entering the screen is when it
actually matters.

OrdersView was the worst: it is in the keep-alive list but only loaded
in onMounted, so the second and every later visit made no request at
all, and the first read the cache. Order status changes on the admin
side and nothing here invalidates it, so the list could be stale for a
whole session. Ledger entries had the same shape and a stronger reason —
they are written by the accounting side, which this app can never learn
about. The gold price was forced only by pull-to-refresh on the two
screens that show it most prominently.

The catalogue is deliberately NOT re-read, by the owner's own reasoning
that this must not add server load: it is the entire product list in one
response, it changes when an admin edits it, and pull-to-refresh and
placing an order already invalidate it.

The cache layer itself is sound — concurrent callers share one in-flight
promise, and a response arriving after an invalidate is returned but not
stored, so a write cannot lose a race against a read in flight. Its one
real gap was that nothing ever went stale. The policy is now written at
the top of queryCache.ts so a TTL is not re-introduced.

Both apps vue-tsc clean. Not click-tested in a browser; the back-button
behaviour is worth one manual pass.

اپ: دکمه بازگشت به صفحه قبلی واقعی برمی‌گردد و اطلاعات هر صفحه در هر بازدید به‌روز می‌شود.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-12 12:42:42 +03:30
s.esmaeiliandClaude Opus 5 ddcc8c5649 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>
2026-10-12 11:48:59 +03:30
s.esmaeiliandClaude Opus 5 c518f9995b fix(auth): tell the user when the number is not registered (D28)
Reported by the owner: a number that is not in the system produced no
error at all. The app advanced to the code box and then nothing
happened, and there was no way to tell apart "the SMS is late", "the
gateway is down" and "this number was never registered" — the only one
of the three the person can actually do something about.

Step 1 now says which it is:
  - unregistered number          -> 404 «این شماره در سیستم ثبت نشده است…»
  - SMS send failed              -> 503 «ارسال پیام کوتاه … ممکن نیست…»
  - sales expert, account unusable -> 403, its own message

and both apps surface the server's Persian message for a 404 exactly as
they already did for a 429. Without that second half the person would
still have seen the generic «خطا در ارسال کد», which is the confusion
being removed.

This restores the reference's behaviour (firstOrFail() in
ApiMobileController::userAuth:43 returns 404); the opaque answer was our
deviation, not this. The anti-enumeration protection it was there for is
deliberately reduced at step 1 on the owner's instruction — the cost was
being paid by real users and by support. Still standing: the per-mobile
and per-IP send throttles, which the reference never had, so enumeration
is rate-bounded rather than free, and verifyOtp keeps one message for
every failure reason. ISSUES.md SEC-03's "no enumeration" claim is
corrected rather than left to go stale.

Two more instances of the same shape turned up while fixing it:

A failed SMS send also returned success, because SmsService never throws
(D20), so a dead gateway produced the identical dead end. D20 exists so
a failed SMS cannot break an operation — an order must still be placed —
but in a login the SMS IS the operation, so it now fails loudly. The
local-dev path keys off SmsService's own `sms-not-configured` result
rather than re-testing the config: with D26's default relay driver,
smsConfigured() is true on any machine with an external IPv4, so a
config test would have called a dev box configured and then failed its
login. The new test caught precisely that on its first run.

Three states return no trading account for a sales expert who does
exist. Under the new 404 each would have claimed the number was not
registered — false, and it would send support hunting a registration
problem that is not there.

Also corrects both apps' LoginView header comment, which still described
this flow as stubbed: no SMS provider, any 4-digit code accepted, step 1
matching the customer list in the client (that was the login leak, D8).
All three had been untrue for weeks and the stale text misled a reader
during this session.

requestOtp had NO test coverage: the 28-test customer-auth suite stayed
green through a change to its response for every unregistered number, so
its greenness was not treated as evidence. request-otp.spec.ts adds 9
cases, including that the dev fallback does not apply in production.

api: 295/295 tests, 27 suites, typecheck clean; both apps vue-tsc clean.

اپ: اگر شماره شما در سیستم ثبت نشده باشد، همان را می‌گوید و دیگر بی‌دلیل به صفحه کد نمی‌رود.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-12 10:59:48 +03:30
s.esmaeiliandClaude Opus 5 89e2d7937e feat(apps): tell a guest why they were bounced to the login page (D3)
A guest tapping a personal page — orders, transactions, profile,
favourites, complete-profile — was redirected in silence, so they landed
on the login box with nothing explaining what happened. Legacy showed
«ابتدا وارد شوید» (henza_pwa/src/router/index.ts:259).

The message is now shown in both apps. The destination deliberately
stays the target's /login?redirect=…, which legacy did not have: legacy
sent the guest to home and lost where they were going, while here
signing in returns them to the page they asked for. The owner chose that
trade-off, so it is logged as «عمداً تکرار نشد — D3/الف» rather than
quietly left as a divergence. The guard also keys off meta.requiresAuth
instead of legacy's hand-kept list of five route names, so the two
sales-expert pages are covered too.

Legacy's isLoaded router guard is NOT ported, and the reasoning is
written into both apps' configStore beside the line that says so: it
guarded legacy's one big bootstrap request, which this target does not
have, so it would guard nothing and only add a bounce — a shared product
link would open home instead of the product. That is porting the
breakage, not the behaviour (D4).

Route analytics is deferred at the owner's request; its design is parked
in docs/PHASE2-D3-PLAN.md so it need not be re-derived, along with the
two reference defects not to copy (log/create was unauthenticated and
accepted any title; log/update was a GET that wrote) and the open
retention and IP questions.

Seven of D3's ten items turned out to be built already — all five
screens in both apps, the sts_verify_step_two guard, v2's cart ceiling —
verified in the code rather than from the checkmarks.

Neither app has a test runner: verified with vue-tsc -b on both (clean)
plus confirming the toast can actually appear, not merely compile —
toast.info exists and <ToastHost /> is mounted in each App.vue.

اپ: وقتی بدون ورود صفحه شخصی را باز کنید، پیام «ابتدا وارد شوید» نشان داده می‌شود.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-12 10:40:22 +03:30
s.esmaeiliandClaude Opus 5 fd9191eca8 feat(orders): log the client price figures the server discards (MON-08)
Step 2 of the owner's MON-08 ruling. An app order is priced by the server
(steps 1, 3, 4 landed with the wage-formula work), but the client's own
wagePercent, discountPercent and flatRialCharge were being thrown away in
silence — so a stale app build, a promotion that expired between the
product page and checkout, and a deliberately tampered request were
indistinguishable and left no trace anywhere.

They are now logged with both numbers, the same pattern already used for
the body's customerId. The pricing itself is untouched: the server's
figures are what the order is charged, and an operator ordering from the
panel still keeps the numbers they typed.

Also adds the comparison test the ruling asked for, which step 3 never
actually had — the suite only proved a tampered request gets overridden.
The new test places one honest order as a customer and the same order as
an operator and asserts the totals are identical, which is the real
claim: an ordinary customer's total does not move. Two more cover the
logging, including that an honest order logs nothing — so the quiet case
cannot pass merely because the method never ran.

Closes STUB-05 in the docs as well: the reference's six hardcoded staff
numbers have been behind PROFILE_ADMIN_MOBILES / ORDER_ADMIN_MOBILES for
a while, but its status still read "pending".

api: 286/286 tests, 26 suites, typecheck clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-12 10:29:13 +03:30
s.esmaeiliandClaude Opus 5 83e5d2868b feat(orders): send the order-placement SMS and close Phase 1
The reference texted three audiences on every placed order
(henza_server Api/ApiMobileController::setOrder:733-766). None of it was
wired here — OrdersService had no SmsService at all, so a customer could
place an order and nobody was told: not the customer, not the admins, not
the referring sales expert.

Now, after the transaction commits (so a rolled-back order texts nobody)
and without ever being awaited (D20 — a dead gateway must not fail an
order):
  - every mobile in ORDER_ADMIN_MOBILES, with the customer's name and
    the rounded gold weight;
  - the customer, with distinct text for a normal and an over-limit
    suspended order;
  - the referring sales expert, looked up on AdminUser (the target's
    referring expert is an admin, not a customer as in the reference).

The reference's four hardcoded personal numbers stay out of git, behind
the same env-var pattern as PROFILE_ADMIN_MOBILES.

The «در سیستم ویرایش شد» variant was deliberately not ported: the target
has no order-edit route, so it would be dead code — «عمداً تکرار نشد».

Also fills §2 of the admin matrix, the D1 deliverable that had been
(pending) since the phase opened: 163 rid-guarded routes, 68 distinct
rids, 176 grantable tree keys, and a per-module map to the reference
controllers. Only two enforced rids are ungrantable from the permission
screen (newsletters, persons.list.sellers.view) — filed as PERM-02,
awaiting an owner ruling because it changes the permission vocabulary.

Phase 1 (admin parity) is at its gate. api: 283/283 tests, 26 suites.

پنل: پیامک ثبت سفارش برای مشتری، ادمین‌ها و کارشناس فروش فعال شد.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-12 10:24:46 +03:30
83 changed files with 5141 additions and 392 deletions
+9
View File
@@ -152,3 +152,12 @@ UPLOAD_DIR=
# instead so no personal number is committed. Blank means nobody is notified —
# the upload and the customer's own SMS still go through (D20).
PROFILE_ADMIN_MOBILES=
# ---------------------------------------------------------------------------
# Order placement
# ---------------------------------------------------------------------------
# Comma-separated admin mobiles told when a customer places an order. The
# reference hardcoded four numbers (henza_server
# Api/ApiMobileController::setOrder:740-743). Blank means nobody is notified —
# the order, the customer's SMS and the sales expert's SMS still go through.
ORDER_ADMIN_MOBILES=
@@ -0,0 +1,30 @@
-- Catalogue paging indexes.
--
-- Owner, 2026-10-12: «دیتاها در اپ واقعی تا 16 هزار رکورد میرود و گرفتن همه یک
-- جا اشتباه است، حتما باید پیج نیشن داشته باشد.» Step 1 of
-- docs/CATALOG-PAGINATION-PLAN.md: without these, server-side paging would walk
-- the same full table scans the unpaged query did.
--
-- `Product` carried NO index whatsoever, so every GET /catalog/products was a
-- sequential scan, and so was each per-product include.
--
-- IF NOT EXISTS throughout: these run under BOTH migration paths (D15) — the
-- Prisma CLI in development and the app's own runner in the deploy image.
--
-- CREATE INDEX (not CONCURRENTLY): the app's runner wraps each migration in a
-- transaction, which CONCURRENTLY cannot join. On a 16k-row table this locks
-- writes for a few hundred milliseconds, which is acceptable; a table large
-- enough to matter would need the index built by hand outside a migration.
-- Matches the storefront list exactly: filter isActive, order by createdAt.
CREATE INDEX IF NOT EXISTS "Product_isActive_createdAt_idx" ON "Product" ("isActive", "createdAt");
-- The category and brand filters of the search screen.
CREATE INDEX IF NOT EXISTS "Product_categoryId_idx" ON "Product" ("categoryId");
CREATE INDEX IF NOT EXISTS "Product_brandId_idx" ON "Product" ("brandId");
-- `include: { variants: { where: { isActive: true } } }`, once per product.
CREATE INDEX IF NOT EXISTS "ProductVariant_productId_isActive_idx" ON "ProductVariant" ("productId", "isActive");
-- `where: { images: { some: {} } }` plus the gallery ordered by sortOrder.
CREATE INDEX IF NOT EXISTS "ProductImage_productId_sortOrder_idx" ON "ProductImage" ("productId", "sortOrder");
+21
View File
@@ -667,6 +667,18 @@ model Product {
promotions Promotion[]
allocationItems BranchAllocationItem[]
favoritedBy CustomerFavorite[]
// Storefront paging (owner: the real catalogue reaches ~16k products, so
// GET /catalog/products must page rather than return everything). This model
// had NO index at all, so every storefront query was a full scan and paging
// alone would not have been any faster.
//
// The composite matches the list's own shape: filter on isActive, order by
// createdAt — Postgres can satisfy both from this one index, including the
// OFFSET walk. The other two serve the category and brand filters.
@@index([isActive, createdAt])
@@index([categoryId])
@@index([brandId])
}
model ProductImage {
@@ -684,6 +696,11 @@ model ProductImage {
/// variants (one photo, several weights), which is why this is a plain
/// one-to-many and not a join table.
variants ProductVariant[]
// The storefront list filters on `images: { some: {} }` and includes the
// gallery ordered by sortOrder, both per product. Unindexed, each one scanned
// the whole table.
@@index([productId, sortOrder])
}
enum ProductImageRole {
@@ -721,6 +738,10 @@ model ProductVariant {
orderItems OrderItem[]
@@index([imageId])
// Every storefront product carries its variants, so this include ran once per
// product with no index to use. The composite covers the `isActive: true`
// filter the list applies to them.
@@index([productId, isActive])
}
// ─────────────────────────────────────────────────────────────────────────
+226
View File
@@ -0,0 +1,226 @@
/**
* Accounting integration (D27) — the Zarrin driver against a REAL Zarrin
* installation. No database, no Nest: it calls the driver itself, so it can
* run against the owner's production install without touching the app.
*
* READ-ONLY by default (the install holds real customer data):
* 1. version + account groups (the token is checked by the group listing)
* 2. accounts: no «*» left in names (listhesabha prints «first * last»)
* 3. one account found again by its mobile (searchAccount)
* 4. balances: one and many
* 5. statement: its last running balance equals the account's real balance,
* and a range ending in the past agrees with one ending today
* 6. کارساخته: every page of listKarSakhte (100 per page), groups, stock
* 7. change feed (parLastTenRadif): first poll = cursor only
* 8. item movement (infogardeshsakhte, hand-printed JSON) — Zarrin itself
* sometimes answers 500 here; reported, not failed
*
* WRITE test only with ZARRIN_WRITE_TEST=1 and ZARRIN_TEST_ACCOUNT set — on
* the owner's install that is account 953 «تست اپ گلدبانک» (09990001111),
* created for this on 2026-10-12. Zarrin has no API to delete an account or
* a کارساخته, so this script never creates either:
* 9. edit the test account (its group must survive)
* 10. post a TEMPORARY 2-line document (1 g each, 10 %): the balance must move
* by exactly 2.2 g and the rows read as temporary
* 11. delete it: no rows left, balance and stock back where they were
*
* Usage:
* ZARRIN_URL=http://host:port/ZarrinService/accounting ZARRIN_TOKEN=… \
* [ZARRIN_ACCOUNT=499] [ZARRIN_WRITE_TEST=1 ZARRIN_TEST_ACCOUNT=953] \
* npx ts-node --transpile-only scripts/test-accounting-zarrin.ts
*
* Requests are paced: the owner's install refused connections once when hit
* back to back. The token is never printed.
*/
import { Prisma } from '@prisma/client';
import { toJalali } from '../src/modules/accounting-sync/jalali';
import { ProviderSettings } from '../src/modules/accounting-sync/providers/accounting-provider';
import { zarrinProvider as z } from '../src/modules/accounting-sync/providers/zarrin.provider';
const URL_ = process.env.ZARRIN_URL ?? '';
const TOKEN = process.env.ZARRIN_TOKEN ?? '';
const ACCOUNT = process.env.ZARRIN_ACCOUNT ?? '';
const WRITE = process.env.ZARRIN_WRITE_TEST === '1';
const TEST_ACCOUNT = process.env.ZARRIN_TEST_ACCOUNT ?? '';
if (!URL_ || !TOKEN) {
console.error('ZARRIN_URL and ZARRIN_TOKEN are required.');
process.exit(2);
}
if (WRITE && !TEST_ACCOUNT) {
console.error('ZARRIN_WRITE_TEST=1 needs ZARRIN_TEST_ACCOUNT (a test account the owner approved, e.g. 953).');
process.exit(2);
}
const s: ProviderSettings = { baseUrl: URL_, token: TOKEN, caCert: null, timeoutMs: 60_000, balanceOwesWhen: 'negative' };
const D = (v: string | number) => new Prisma.Decimal(v);
const pause = (ms = 1200) => new Promise((r) => setTimeout(r, ms));
const day = (n: number) => toJalali(new Date(Date.now() - n * 864e5));
let pass = 0;
let fail = 0;
const chk = (c: unknown, m: string) => {
if (c) pass += 1;
else fail += 1;
console.log(` ${c ? 'PASS' : 'FAIL'} ${m}`);
};
const note = (m: string) => console.log(` NOTE ${m}`);
const step = (t: string) => console.log(`\n${t}`);
async function main() {
step('1. connection');
const h = await z.health(s);
chk(h.version !== undefined && Number(h.customerGroups) > 0, `version ${h.version}, ${h.customerGroups} account groups`);
await pause();
step('2. accounts');
const all = (await z.listCustomers(s, null)).items;
chk(all.length > 0, `${all.length} accounts, ${all.filter((c) => c.mobile).length} with a mobile`);
chk(all.every((c) => !c.name.includes('*')), 'no «*» left in any name');
await pause();
const probe = all.find((c) => (ACCOUNT ? c.code === ACCOUNT : !!c.mobile)) ?? all[0];
const code = probe.code;
step(`3. search by mobile (account ${code})`);
if (probe.mobile) {
const found = await z.findCustomersByMobile(s, probe.mobile);
chk(found.some((c) => c.code === code), `found account ${code} by its mobile`);
} else note('account has no mobile; skipped');
await pause();
step('4. balances');
const [one] = await z.getBalances(s, [code]);
chk(!!one, `balance of ${code}: ${one?.goldGrams} g, ${one?.rial} rial (app sign: positive = owes)`);
await pause();
const many = await z.getBalances(s, all.slice(0, 3).map((c) => c.code));
chk(many.length === 3, `3 balances in one call (${many.length})`);
await pause();
step(`5. statement of ${code}`);
const toToday = await z.getStatement(s, { code, from: day(60), to: day(0) });
await pause();
const [now] = await z.getBalances(s, [code]);
const last = toToday[toToday.length - 1];
if (last) {
chk(String(last.goldBalance) === String(now?.goldGrams), `last running balance ${last.goldBalance} = real balance ${now?.goldGrams}`);
await pause();
const past = await z.getStatement(s, { code, from: day(60), to: day(5) });
const byKey = new Map(toToday.map((r) => [r.key, String(r.goldBalance)]));
const shared = past.filter((r) => byKey.has(r.key));
chk(shared.every((r) => byKey.get(r.key) === String(r.goldBalance)), `a range ending 5 days ago agrees on ${shared.length} shared rows`);
note(`${toToday.length} rows in 60 days, ${toToday.filter((r) => r.temporary).length} temporary`);
} else note('no rows in the last 60 days');
await pause();
step('6. کارساخته');
const items = await z.listKarSakhte(s);
chk(items.length > 0, `${items.length} items (pages of 100 read until the last)`);
await pause();
const groups = await z.listKarSakhteGroups(s);
chk(groups.length > 0, `${groups.length} item groups`);
await pause();
const stocked = items.find((i) => i.stockWeight?.gt(0));
if (stocked) {
const st = await z.getKarSakhteStock(s, stocked);
chk(st.weight !== null || st.count !== null, `stock of «${stocked.name}»: ${st.weight ?? st.count}`);
}
await pause();
step('7. change feed');
const first = await z.getChanges(s, null);
chk(!!first.cursor && first.accountCodes.length === 0, `first poll returns only the cursor (${first.cursor})`);
await pause();
step('8. item movement (slow; Zarrin sometimes fails here itself)');
try {
const mv = await z.getKarSakhteMovement(s, day(3), day(0));
chk(true, `${mv.length} rows`);
} catch (err) {
note(`not available right now: ${(err as Error).message.slice(0, 160)}`);
}
if (!WRITE) {
console.log('\nWrite test skipped (set ZARRIN_WRITE_TEST=1 and ZARRIN_TEST_ACCOUNT to run it).');
return;
}
step(`9. edit test account ${TEST_ACCOUNT}`);
const acct = all.find((c) => c.code === TEST_ACCOUNT);
if (!acct) throw new Error(`test account ${TEST_ACCOUNT} not found`);
const parts = acct.name.split(' ');
await z.updateCustomer(s, TEST_ACCOUNT, {
firstName: parts.slice(0, -1).join(' ') || acct.name,
lastName: parts.slice(-1)[0] ?? '',
fullName: acct.name,
mobile: acct.mobile ?? '',
phone: acct.phone,
address: `حساب آزمایشی اتصال اپ — آخرین تست ${new Date().toISOString().slice(0, 10)}`,
nationalCode: null,
group: { id: null, name: acct.groupName },
});
await pause();
const after = (await z.listCustomers(s, null)).items.find((c) => c.code === TEST_ACCOUNT);
chk(after?.groupName === acct.groupName, `group kept: ${after?.groupName}`);
await pause();
step('10–11. temporary document, then delete');
const [b0] = await z.getBalances(s, [TEST_ACCOUNT]);
const sell = items.filter((i) => i.typeName === 'گرمی' && i.stockWeight?.gte(2)).slice(0, 2);
if (sell.length < 2) throw new Error('need two gram items with stock ≥ 2 g');
const stock0: string[] = [];
for (const i of sell) {
await pause();
stock0.push(String((await z.getKarSakhteStock(s, i)).weight));
}
let ref = '';
try {
await pause();
const res = await z.postOrderDocument(
s,
{
factorCode: 'zarrinwritetest',
customerCode: TEST_ACCOUNT,
date: new Date(),
description: 'تست اتصال اپ',
temporary: true,
lines: sell.map((i) => ({ itemCode: i.code, itemName: i.name, weightGrams: D(1), count: 1, wagePercent: D(10), flatRial: D(0), karat: 750, description: `تست اتصال اپ — ${i.name}` })),
},
{},
async (p) => {
if (p.factorId) ref = p.factorId;
},
);
ref = res.ref;
await pause(2000);
const [b1] = await z.getBalances(s, [TEST_ACCOUNT]);
chk(b1 && b0 && b1.goldGrams.sub(b0.goldGrams).eq('2.2'), `invoice ${ref}: balance moved ${b1 && b0 ? b1.goldGrams.sub(b0.goldGrams) : '?'} g (expected 2.2)`);
await pause();
const rows = (await z.getStatement(s, { code: TEST_ACCOUNT, from: day(0), to: day(0) })).filter((r) => r.documentRef === ref);
chk(rows.length > 0 && rows.every((r) => r.temporary), `${rows.length} rows, all temporary`);
} finally {
if (ref) {
await pause(1500);
await z.deleteDocument(s, { factorCode: '', ref, customerCode: TEST_ACCOUNT });
await pause(2000);
const [b2] = await z.getBalances(s, [TEST_ACCOUNT]);
chk(b2 && b0 && b2.goldGrams.eq(b0.goldGrams), `deleted: balance back to ${b2?.goldGrams}`);
await pause();
const left = (await z.getStatement(s, { code: TEST_ACCOUNT, from: day(0), to: day(0) })).filter((r) => r.documentRef === ref);
chk(left.length === 0, `no rows of invoice ${ref} left`);
for (const [n, i] of sell.entries()) {
await pause();
const w = String((await z.getKarSakhteStock(s, i)).weight);
chk(w === stock0[n], `stock of «${i.name}» back to ${stock0[n]} (${w})`);
}
}
}
}
main()
.catch((err) => {
fail += 1;
console.error(`\nABORTED: ${(err as Error).message}`);
})
.finally(() => {
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
});
@@ -86,6 +86,16 @@ function tlsErrorMessage(err: NodeJS.ErrnoException, pinned: boolean): string {
}
export function httpRequest(req: HttpRequest): Promise<HttpResponse> {
return send(req, false);
}
/**
* One attempt. `fresh` = on a new connection: a server that closes idle
* kept-alive connections (Zarrin v228 does) makes the next request on a pooled
* one fail with ECONNRESET / "socket hang up" before it was received. That one
* case is repeated once on a fresh connection; nothing else is ever retried.
*/
function send(req: HttpRequest, fresh: boolean): Promise<HttpResponse> {
let url: URL;
try {
url = new URL(req.url);
@@ -106,6 +116,7 @@ export function httpRequest(req: HttpRequest): Promise<HttpResponse> {
port: url.port || (isHttps ? 443 : 80),
path: `${url.pathname}${url.search}`,
headers,
...(fresh ? { agent: false } : {}),
};
const pins = isHttps ? pinnedFingerprints(req.ca) : new Set<string>();
if (isHttps) {
@@ -176,6 +187,10 @@ export function httpRequest(req: HttpRequest): Promise<HttpResponse> {
}, req.timeoutMs);
request.on('error', (err: NodeJS.ErrnoException) => {
if (!fresh && request.reusedSocket && err.code === 'ECONNRESET') {
finish(() => resolve(send(req, true)));
return;
}
// Node's own text for these suggests flags that do not apply here.
const text = isHttps && err.code && TLS_CERT_ERRORS.test(err.code) ? tlsErrorMessage(err, pins.size > 0) : err.message;
finish(() => reject(new AccountingHttpError(text, connected, err.code)));
@@ -181,23 +181,37 @@ describe('balances and statement', () => {
expect(pos[0].goldGrams.toString()).toBe('-75.409');
});
it('folds a running balance from «مانده از قبل»', async () => {
it('anchors the running balance on the real balance; «مانده از قبل» is not a movement', async () => {
// 1) the range, opening row first (seen on v228: its figures are not a balance)
http.mockReturnValueOnce(
reply({
state: true,
detail: 'OK',
data: [
{ idRadif: '0', idFactor: '0', idHesab: '81', sharh: 'مانده از قبل', vaznTarazooPardakht: '10.0', vaznTarazooDaryaft: '0.0', poolPardakht: '0', poolDaryaft: '0' },
{ idRadif: '470', idFactor: '221', idHesab: '81', noeRadif: 'چک', tarikh: '04/05/29', vaznTarazooPardakht: '0.0', vaznTarazooDaryaft: '2.5', poolPardakht: '810000000', poolDaryaft: '0', ayar: '0' },
{ idRadif: '0', idFactor: '0', idHesab: '81', sharh: 'مانده از قبل', vaznTarazooPardakht: '10.14', vaznTarazooDaryaft: '10.24', poolPardakht: '5', poolDaryaft: '5' },
{ idRadif: '470', idFactor: '221', idHesab: '81', noeRadif: 'چک', noeFactor: 'سند دریافت', tarikh: '04/05/29', vaznTarazooPardakht: '0.0', vaznTarazooDaryaft: '2.5', poolPardakht: '810000000', poolDaryaft: '0', ayar: '0' },
{ idRadif: '471', idFactor: '222', idHesab: '81', noeRadif: 'کار ساخته', noeFactor: 'فاکتور موقت', tarikh: '04/05/30', vaznTarazooPardakht: '1.0', vaznTarazooDaryaft: '0.0', poolPardakht: '0', poolDaryaft: '0', ayar: '750' },
],
}),
);
// 2) the account's balance now: −9.5 g in Zarrin = owes 9.5
http.mockReturnValueOnce(reply({ state: true, msg: 'OK', data: [{ id: '81', geram: '-9.5', pool: '-810000000' }] }));
// 3) what happened after the range
http.mockReturnValueOnce(
reply({ state: true, detail: 'OK', data: [{ idRadif: '0', sharh: 'مانده از قبل' }, { idRadif: '500', idHesab: '81', vaznTarazooPardakht: '1.0', vaznTarazooDaryaft: '0', poolPardakht: '0', poolDaryaft: '0' }] }),
);
const rows = await z.getStatement(s, { code: '81', from: { jy: 1404, jm: 5, jd: 1 }, to: { jy: 1404, jm: 5, jd: 31 } });
expect(url().searchParams.get('dateAz')).toBe('2025-07-23');
expect(rows[0].goldBalance?.toString()).toBe('10');
expect(rows[1]).toMatchObject({ documentRef: '221', date: '1404/05/29', title: 'چک' });
expect(rows[1].goldBalance?.toString()).toBe('7.5');
expect(rows[1].rialBalance?.toString()).toBe('810000000');
expect(url(1).searchParams.get('kind')).toBe('listMandeHesabha');
expect(url(2).searchParams.get('dateAz')).toBe('2025-08-23'); // the day after `to`
expect(rows).toHaveLength(2);
expect(rows[0]).toMatchObject({ documentRef: '221', date: '1404/05/29', title: 'چک', temporary: false });
// closing(to) = 9.5 − 1.0 after = 8.5; opening = 8.5 − (−2.5 + 1.0) = 10
expect(rows[0].goldBalance?.toString()).toBe('7.5');
expect(rows[0].rialBalance?.toString()).toBe('810000000');
expect(rows[1]).toMatchObject({ temporary: true });
expect(rows[1].goldBalance?.toString()).toBe('8.5');
});
});
@@ -283,3 +297,81 @@ describe('change feed (real-time sync)', () => {
expect(await z.getChanges(s, null)).toEqual({ cursor: '731', accountCodes: [], itemNames: [], overflow: false });
});
});
describe('v228 quirks', () => {
it('reads every page of listKarSakhte (100 per page)', async () => {
const page = (from: number, n: number) => reply({ state: true, msg: 'ok', data: Array.from({ length: n }, (_, i) => ({ id: String(from + i), namFelezsakhthe: `کار ${from + i}`, fkNoe: '16', NoeName: 'گرمی' })) });
http.mockReturnValueOnce(page(1, 100)).mockReturnValueOnce(page(101, 100)).mockReturnValueOnce(page(201, 7));
const items = await z.listKarSakhte(s);
expect(items).toHaveLength(207);
expect(url(1).searchParams.get('pageNum')).toBe('2');
});
it('stops when the server ignores pageNum and repeats page 1', async () => {
const page1 = () => reply({ state: true, msg: 'ok', data: Array.from({ length: 100 }, (_, i) => ({ id: String(i + 1), namFelezsakhthe: 'x' })) });
http.mockReturnValueOnce(page1()).mockReturnValueOnce(page1());
expect(await z.listKarSakhte(s)).toHaveLength(100);
expect(http).toHaveBeenCalledTimes(2);
});
it('accepts an HTTP 400 that carries a good reply (goroohSakhte on v228)', async () => {
http.mockReturnValueOnce(reply({ state: true, detail: 'OK', data: [{ id: '26', name: 'النگو' }] }, 400));
expect(await z.listKarSakhteGroups(s)).toEqual([{ id: '26', name: 'النگو' }]);
});
it('repairs the hand-printed JSON of infogardeshsakhte', async () => {
// Verbatim shape of a v228 reply.
const body = [
'{',
' "data": [',
' {',
' "code_kar": 19,',
' "nam_kar": دستبند آروشا,',
' "tarikh_akharin_gardesh": 05/07/15,',
' "sharh_akharin_gardesh": دستبند آروشا,',
' "vazn_akharin_gardesh": -15.12,',
' "mablagh_akharin_gardesh": 0.0,',
' },',
' ]',
'}',
].join('\n');
http.mockReturnValueOnce(reply(body));
const rows = await z.getKarSakhteMovement(s, { jy: 1405, jm: 7, jd: 1 }, { jy: 1405, jm: 7, jd: 20 });
expect(rows).toEqual([
expect.objectContaining({ itemCode: '19', itemName: 'دستبند آروشا', date: '1405/07/15', weight: new Prisma.Decimal('-15.12') }),
]);
});
it('drops the «*» listhesabha puts between first and last name', async () => {
const { accountName } = __zarrinInternals;
expect(accountName('آرین * یوسفی')).toBe('آرین یوسفی');
expect(accountName(' * هزینه هدایا (پیامک گروهی)')).toBe('هزینه هدایا (پیامک گروهی)');
expect(accountName(' * ')).toBeNull();
http.mockReturnValueOnce(reply({ data: [{ id: '953', nam: 'تست اپ * گلدبانک', gorooh: 'متفرقه', mobile: '09990001111' }] }));
const { items } = await z.listCustomers(s, null);
expect(items[0]).toMatchObject({ code: '953', name: 'تست اپ گلدبانک', groupName: 'متفرقه', mobile: '09990001111' });
});
it('sees a document posted with movaghat=1 as temporary (shomareSanad «موقت»)', async () => {
http.mockReturnValueOnce(
reply({
state: true,
data: [
{ idRadif: '71962', idFactor: '16792', idHesab: '953', noeFactor: 'فاکتور فروش', shomareSanad: 'موقت', noeRadif: 'کار ساخته', vaznTarazooPardakht: '1', vaznTarazooDaryaft: '0', poolPardakht: '0', poolDaryaft: '0' },
{ idRadif: '71710', idFactor: '16722', idHesab: '953', noeFactor: 'فاکتور موقت', shomareSanad: 'باز', vaznTarazooPardakht: '0.1', vaznTarazooDaryaft: '0', poolPardakht: '0', poolDaryaft: '0' },
{ idRadif: '52961', idFactor: '12282', idHesab: '953', noeFactor: 'فاکتور فروش', shomareSanad: '12282', vaznTarazooPardakht: '1', vaznTarazooDaryaft: '0', poolPardakht: '0', poolDaryaft: '0' },
],
}),
);
http.mockReturnValueOnce(reply({ state: true, data: [{ id: '953', geram: '-2.1', pool: '0' }] }));
const today = toJalaliToday();
const rows = await z.getStatement(s, { code: '953', from: today, to: today });
expect(rows.map((r) => r.temporary)).toEqual([true, true, false]);
});
});
function toJalaliToday() {
// Today in Tehran, so the statement needs no "after the range" call.
const { toJalali } = jest.requireActual('../jalali');
return toJalali(new Date());
}
@@ -1,6 +1,12 @@
import { Prisma } from '@prisma/client';
import { AccountingHttpError, httpRequest, parseLooseJson } from '../accounting-http';
import { jalaliToIsoDate, toIsoDateTehran } from '../jalali';
import { JalaliDate, jalaliToGregorian, jalaliToIsoDate, toIsoDateTehran, toJalali } from '../jalali';
const jalaliKey = (d: JalaliDate) => d.jy * 10000 + d.jm * 100 + d.jd;
function nextDay(d: JalaliDate): JalaliDate {
const g = jalaliToGregorian(d.jy, d.jm, d.jd);
return toJalali(new Date(Date.UTC(g.gy, g.gm - 1, g.gd + 1, 12)));
}
import {
AccountingProvider,
AccountingProviderError,
@@ -22,12 +28,13 @@ import {
* the installation's `http://host:8000/ZarrinService/accounting`. The token
* travels in the query string, so a URL built here must never be logged.
*
* NOT verified against a live installation — the owner has none to test on
* (plan, decision 11). Everything below follows the documentation and its
* sample outputs, and is covered by unit tests built from those samples. The
* open points (balance sign, which rial field the stones belong in) are
* configurable or flagged, and the integration is to be switched on for real
* only after a trial period on temporary documents.
* Reads verified on a real installation (v228, 870 accounts) on 2026-10-12,
* ACC-01: negative balance = owes; a «فاکتور موقت» moves the balance at once
* (unlike Tahesab); listKarSakhte pages by 100 (pageNum); parvande opens with
* a «مانده از قبل» row that is not a movement; goroohSakhte answers HTTP 400
* with a good body; infogardeshsakhte answers malformed JSON. The writing
* calls (addAccount, edithesab, foroushSakhte, hazfRadifSanad,
* addFelezsakhteModel) are still unverified.
*
* Differences from Tahesab that shape the sync:
* * No idempotency key on foroushSakhte. A timed-out document call cannot be
@@ -40,6 +47,12 @@ import {
const STATEMENT_PAGE = 250;
const CHANGE_WINDOW = 50;
const MAX_STATEMENT_PAGES = 20;
/** listKarSakhte returns this many per page (pageNum=1,2,…). */
const ITEM_PAGE = 100;
const MAX_ITEM_PAGES = 200;
/** infogardeshsakhte scans every item server-side; seen at 5–33 s. */
const MOVEMENT_TIMEOUT_MS = 90_000;
const OPENING_ROW = 'مانده از قبل';
const ALL_CODES = { az: 1, ta: 999999 };
const GROUP_SCAN_MAX = 300;
const GROUP_SCAN_CONCURRENCY = 10;
@@ -85,10 +98,27 @@ function errorBodyText(body: string, token: string) {
return text.length > 200 ? `${text.slice(0, 200)}…` : text;
}
/**
* infogardeshsakhte prints its JSON by hand: string values unquoted and a
* comma before every closing brace. Its layout is one "key": value per line,
* so each bare value is quoted and the dangling commas dropped.
*/
export function repairZarrinJson(body: string): string {
const lines = body.split(/\r?\n/).map((line) => {
const m = line.match(/^(\s*"[^"]+"\s*:\s*)(.*?)(,?)\s*$/);
if (!m) return line;
const value = m[2].trim();
if (value === '' || /^(-?\d+(\.\d+)?|true|false|null)$/.test(value) || /^["{[]/.test(value)) return line;
return `${m[1]}${JSON.stringify(value)}${m[3]}`;
});
return lines.join('\n').replace(/,(\s*[}\]])/g, '$1');
}
async function call(
s: ProviderSettings,
kind: string,
params: Record<string, string | number | null | undefined> = {},
opts: { timeoutMs?: number; repair?: (body: string) => string } = {},
): Promise<Record<string, unknown> | unknown[]> {
let url: URL;
try {
@@ -104,7 +134,7 @@ async function call(
let res;
try {
res = await httpRequest({ method: 'GET', url: url.toString(), timeoutMs: s.timeoutMs, ca: s.caCert });
res = await httpRequest({ method: 'GET', url: url.toString(), timeoutMs: opts.timeoutMs ?? s.timeoutMs, ca: s.caCert });
} catch (err) {
if (err instanceof AccountingHttpError) {
throw new AccountingProviderError(`زرین (${kind}): ${err.message}`, err.ambiguous);
@@ -113,13 +143,16 @@ async function call(
}
if (res.status < 200 || res.status >= 300) {
// v228 answers goroohSakhte with HTTP 400 and a perfectly good body.
const good = goodReply(res.body);
if (good) return good;
const reason = errorBodyText(res.body, s.token);
throw new ZarrinHttpError(`زرین (${kind}): HTTP ${res.status}${reason ? ` — ${reason}` : ''}`, res.body.slice(0, 500), res.status);
}
let json: unknown;
try {
json = parseLooseJson(res.body);
json = parseLooseJson(opts.repair ? opts.repair(res.body) : res.body);
// The documented outputs are JSON-encoded strings of JSON ("{\"state\":…}").
if (typeof json === 'string' && /^\s*[{[]/.test(json)) json = parseLooseJson(json);
} catch {
@@ -137,6 +170,17 @@ async function call(
return json as Record<string, unknown> | unknown[];
}
function goodReply(body: string): Record<string, unknown> | null {
try {
let j = parseLooseJson(body) as unknown;
if (typeof j === 'string' && /^\s*[{[]/.test(j)) j = parseLooseJson(j);
const o = j as Record<string, unknown> | null;
return o && typeof o === 'object' && (o.state === true || o.status === true) && Array.isArray(o.data) ? o : null;
} catch {
return null;
}
}
/** Zarrin wraps lists as `data`, sometimes as `date` (searchAccount), or not at all. */
function listOf(json: unknown): Record<string, unknown>[] {
if (Array.isArray(json)) return json as Record<string, unknown>[];
@@ -169,12 +213,18 @@ function fullJalali(v: unknown): string {
return `14${m[1]}/${m[2].padStart(2, '0')}/${m[3].padStart(2, '0')}`;
}
function accountName(v: unknown): string | null {
const n = (str(v) ?? '').replace(/\s*\*\s*/g, ' ').replace(/\s+/g, ' ').trim();
return n || null;
}
async function allAccounts(s: ProviderSettings): Promise<ExternalCustomer[]> {
return listOf(await call(s, 'listhesabha', ALL_CODES))
.filter((r) => r.id !== undefined)
.map((r) => ({
code: String(r.id),
name: str(r.nam) ?? String(r.id),
// listhesabha prints «first * last» (and « * name» without a first name).
name: accountName(r.nam) ?? String(r.id),
mobile: normalizeMobile(r.mobile),
phone: str(r.tell),
nationalCode: str(r.codeMeli),
@@ -184,6 +234,41 @@ async function allAccounts(s: ProviderSettings): Promise<ExternalCustomer[]> {
}));
}
/** Every کارساخته: listKarSakhte pages by 100 (pageNum), undocumented. */
async function allKarSakhte(s: ProviderSettings): Promise<Record<string, unknown>[]> {
const out: Record<string, unknown>[] = [];
const seen = new Set<string>();
for (let page = 1; page <= MAX_ITEM_PAGES; page += 1) {
const batch = listOf(await call(s, 'listKarSakhte', { pageNum: page }));
// An installation that ignores pageNum repeats page 1: stop there.
const fresh = batch.filter((r) => !seen.has(String(r.id)));
for (const r of fresh) seen.add(String(r.id));
out.push(...fresh);
if (batch.length < ITEM_PAGE || fresh.length === 0) break;
}
return out;
}
/** An account's ledger rows (parvande) in a date range, every page, without the opening row. */
async function ledgerRows(s: ProviderSettings, code: string, from: string, to: string): Promise<Record<string, unknown>[]> {
const rows: Record<string, unknown>[] = [];
for (let page = 1; page <= MAX_STATEMENT_PAGES; page += 1) {
const batch = listOf(await call(s, 'parvande', { id: code, dateAz: from, dateTa: to, pageNum: page, detailCount: STATEMENT_PAGE }));
rows.push(...batch);
if (batch.length < STATEMENT_PAGE) break;
}
// «مانده از قبل» (idRadif 0) is a summary, not a movement.
return rows.filter((r) => String(r.idRadif ?? '') !== '0' && str(r.sharh) !== OPENING_ROW);
}
/** What a row adds to what the customer owes (app convention: positive = owes). */
function owesDelta(r: Record<string, unknown>) {
return {
gold: (dec(r.vaznTarazooPardakht) ?? ZERO).sub(dec(r.vaznTarazooDaryaft) ?? ZERO),
rial: (dec(r.poolPardakht) ?? ZERO).sub(dec(r.poolDaryaft) ?? ZERO),
};
}
function signed(s: ProviderSettings, v: Prisma.Decimal) {
// Until checked on a real installation (plan §9) the sign is a setting.
return (s.balanceOwesWhen ?? 'negative') === 'negative' ? v.negated() : v;
@@ -311,25 +396,30 @@ export const zarrinProvider: AccountingProvider = {
},
async getStatement(s, q) {
const rows: Record<string, unknown>[] = [];
for (let page = 1; page <= MAX_STATEMENT_PAGES; page += 1) {
const batch = listOf(
await call(s, 'parvande', {
id: q.code,
dateAz: jalaliToIsoDate(q.from),
dateTa: jalaliToIsoDate(q.to),
pageNum: page,
detailCount: STATEMENT_PAGE,
}),
);
rows.push(...batch);
if (batch.length < STATEMENT_PAGE) break;
const rows = await ledgerRows(s, q.code, jalaliToIsoDate(q.from), jalaliToIsoDate(q.to));
// parvande has no running balance and its «مانده از قبل» row cannot be
// read as one, so the balance is anchored on the account's real balance
// now and walked back: closing(to) = now − movements after `to`.
const [now] = await zarrinProvider.getBalances(s, [q.code]);
let closingGold = now?.goldGrams ?? ZERO;
let closingRial = now?.rial ?? ZERO;
const today = toJalali(new Date());
if (jalaliKey(q.to) < jalaliKey(today)) {
for (const r of await ledgerRows(s, q.code, jalaliToIsoDate(nextDay(q.to)), jalaliToIsoDate(today))) {
const d = owesDelta(r);
closingGold = closingGold.sub(d.gold);
closingRial = closingRial.sub(d.rial);
}
}
let gold = closingGold;
let rial = closingRial;
for (const r of rows) {
const d = owesDelta(r);
gold = gold.sub(d.gold);
rial = rial.sub(d.rial);
}
// parvande has no running balance; it opens with «مانده از قبل» and the
// balance is folded from there. پرداخت = we gave = the customer owes more.
let gold = ZERO;
let rial = ZERO;
return rows.map((r): StatementRow => {
const goldIn = dec(r.vaznTarazooDaryaft) ?? ZERO;
const goldOut = dec(r.vaznTarazooPardakht) ?? ZERO;
@@ -360,7 +450,9 @@ export const zarrinProvider: AccountingProvider = {
goldBalance: gold,
rialBalance: rial,
metal: null,
temporary: false,
// A document posted with movaghat=1 says so in shomareSanad («موقت»);
// one left open in Zarrin's own UI is a «فاکتور موقت».
temporary: /موقت/.test(`${str(r.noeFactor) ?? ''} ${str(r.shomareSanad) ?? ''}`),
};
});
},
@@ -394,14 +486,14 @@ export const zarrinProvider: AccountingProvider = {
async listKarSakhteTypes(s) {
const types = new Map<string, string>();
for (const r of listOf(await call(s, 'listKarSakhte'))) {
for (const r of await allKarSakhte(s)) {
if (r.fkNoe !== undefined) types.set(String(r.fkNoe), str(r.NoeName) ?? String(r.fkNoe));
}
return [...types].map(([id, name]) => ({ id, name }));
},
async listKarSakhte(s) {
return listOf(await call(s, 'listKarSakhte'))
return (await allKarSakhte(s))
.filter((r) => r.id !== undefined && str(r.namFelezsakhthe))
.map((r) => ({
code: String(r.id),
@@ -426,11 +518,18 @@ export const zarrinProvider: AccountingProvider = {
},
async getKarSakhteMovement(s, from, to) {
return listOf(await call(s, 'infogardeshsakhte', { az: jalaliToIsoDate(from), ta: jalaliToIsoDate(to) })).map(
const json = await call(
s,
'infogardeshsakhte',
{ az: jalaliToIsoDate(from), ta: jalaliToIsoDate(to) },
{ timeoutMs: Math.max(s.timeoutMs, MOVEMENT_TIMEOUT_MS), repair: repairZarrinJson },
);
return listOf(json).map(
(r) => ({
itemCode: str(r.code_kar),
itemName: str(r.nam_kar) ?? '—',
date: str(r.tarikh_akharin_gardesh) ?? '',
// One row per item: its LAST movement, which may predate the range.
date: fullJalali(r.tarikh_akharin_gardesh),
description: str(r.sharh_akharin_gardesh),
weight: dec(r.vazn_akharin_gardesh),
amount: dec(r.mablagh_akharin_gardesh),
@@ -498,15 +597,7 @@ export const zarrinProvider: AccountingProvider = {
// one in the account's ledger for the last year.
const today = new Date();
const yearAgo = new Date(today.getTime() - 366 * 24 * 3600 * 1000);
const rows = listOf(
await call(s, 'parvande', {
id: doc.customerCode,
dateAz: toIsoDateTehran(yearAgo),
dateTa: toIsoDateTehran(today),
pageNum: 1,
detailCount: STATEMENT_PAGE,
}),
);
const rows = await ledgerRows(s, doc.customerCode, toIsoDateTehran(yearAgo), toIsoDateTehran(today));
const row = rows.find((r) => String(r.idFactor) === doc.ref && str(r.idRadif) && String(r.idRadif) !== '0');
if (!row) return { response: { alreadyDeleted: true } };
const json = await call(s, 'hazfRadifSanad', {
@@ -519,4 +610,4 @@ export const zarrinProvider: AccountingProvider = {
};
/** Exposed for tests. */
export const __zarrinInternals = { listOf, fullJalali };
export const __zarrinInternals = { listOf, fullJalali, repairZarrinJson, accountName };
@@ -0,0 +1,212 @@
import { NotFoundException } from '@nestjs/common';
import { CatalogService } from './catalog.service';
import { DEFAULT_PAGE_SIZE } from './dto/list-products.dto';
/**
* Server-side catalogue paging and filtering.
*
* Owner, 2026-10-12: «دیتاها در اپ واقعی تا 16 هزار رکورد میرود و گرفتن همه یک
* جا اشتباه است، حتما باید پیج نیشن داشته باشد.»
*
* Two things these cases exist to protect:
*
* 1. The bare `GET /catalog/products` must keep returning the whole array from
* the cache. The admin panel, the smoke scripts and already-installed app
* builds all depend on that shape, and paging is opt-in precisely so none
* of them break.
* 2. A filter must reach the DATABASE. Paging the response while leaving the
* filter in the client would make search quietly wrong — it would only ever
* search the first page — which is worse than the slowness being fixed.
*/
describe('CatalogService — paging and filtering', () => {
function setup(rowCount = 3) {
const rows = Array.from({ length: rowCount }, (_, i) => ({
id: `p${i}`,
title: `محصول ${i}`,
isActive: true,
accountingStockWeight: null,
accountingStockCount: null,
accountingStockAt: null,
variants: [{ id: `v${i}`, isActive: true, isPreOrder: false, qty: 5 }],
images: [{ id: `i${i}`, sortOrder: 0 }],
}));
const findMany = jest.fn().mockResolvedValue(rows);
const count = jest.fn().mockResolvedValue(42);
const prisma = {
product: { findMany, count },
category: { findMany: jest.fn().mockResolvedValue([{ id: 'c1', title: 'انگشتر' }]) },
brand: { findMany: jest.fn().mockResolvedValue([{ id: 'b1', title: 'برند' }]) },
collection: { findMany: jest.fn().mockResolvedValue([{ id: 'col1', title: 'مجموعه' }]) },
productVariant: {
aggregate: jest.fn().mockResolvedValue({
_min: { rashWeightGrams: { toString: () => '1.5' } },
_max: { rashWeightGrams: { toString: () => '12' } },
}),
},
};
// Nothing is out of stock in the accounting software for these cases.
const accounting = { stockBlocker: jest.fn().mockResolvedValue(() => false) };
const cache = { get: jest.fn((build: () => Promise<unknown>) => build()) };
const service = new CatalogService(prisma as never, accounting as never, cache as never);
return { service, findMany, count, prisma, cache };
}
/** The `where` of the last product.findMany call. */
const lastWhere = (findMany: jest.Mock) => findMany.mock.calls.at(-1)?.[0]?.where;
const lastArgs = (findMany: jest.Mock) => findMany.mock.calls.at(-1)?.[0];
describe('backward compatibility', () => {
it('returns a plain array through the cache when nothing is asked for', async () => {
const { service, cache, findMany } = setup();
const out = await service.listProducts();
expect(Array.isArray(out)).toBe(true);
expect(cache.get).toHaveBeenCalledTimes(1);
// The original query: storefront rule only, no skip/take/orderBy.
const args = lastArgs(findMany);
expect(args.skip).toBeUndefined();
expect(args.take).toBeUndefined();
expect(args.where).toEqual({ isActive: true, images: { some: {} } });
});
it('still applies the two storefront rules on a paged query', async () => {
// Inactive products and products with no photo must never appear, however
// the caller asks — D27.
const { service, findMany } = setup();
await service.findProducts({ page: 1, limit: 10 });
expect(lastWhere(findMany)).toMatchObject({ isActive: true, images: { some: {} } });
});
});
describe('paging', () => {
it('translates page/limit into skip/take', async () => {
const { service, findMany } = setup();
await service.findProducts({ page: 3, limit: 20 });
expect(lastArgs(findMany)).toMatchObject({ skip: 40, take: 20 });
});
it('defaults the page size when only a page is given', async () => {
const { service, findMany } = setup();
await service.findProducts({ page: 2 });
expect(lastArgs(findMany)).toMatchObject({ skip: DEFAULT_PAGE_SIZE, take: DEFAULT_PAGE_SIZE });
});
it('reports the total of the FILTERED set, not of the page', async () => {
// The app shows "N محصول" and stops scrolling by comparing against this,
// so counting anything else would both lie and break the end of the list.
const { service, count } = setup();
const out = await service.findProducts({ page: 1, limit: 20, search: 'انگشتر' });
expect(out.total).toBe(42);
expect(count).toHaveBeenCalledWith({
where: expect.objectContaining({ title: { contains: 'انگشتر', mode: 'insensitive' } }),
});
});
it('filters without paging when no page is given', async () => {
const { service, findMany } = setup();
const out = await service.findProducts({ search: 'x' });
expect(lastArgs(findMany).skip).toBeUndefined();
expect(lastArgs(findMany).take).toBeUndefined();
// `limit` echoes the total so a caller cannot mistake it for a page size.
expect(out.limit).toBe(out.total);
});
it('orders newest first by default, and honours the other sorts', async () => {
const { service, findMany } = setup();
await service.findProducts({ page: 1 });
expect(lastArgs(findMany).orderBy).toEqual({ createdAt: 'desc' });
await service.findProducts({ page: 1, sort: 'title' });
expect(lastArgs(findMany).orderBy).toEqual({ title: 'asc' });
await service.findProducts({ page: 1, sort: 'oldest' });
expect(lastArgs(findMany).orderBy).toEqual({ createdAt: 'asc' });
});
});
describe('filters reach the database', () => {
it('passes category, brand and collection through', async () => {
const { service, findMany } = setup();
await service.findProducts({ page: 1, categoryId: 'c1', brandId: 'b1', collectionId: 'col1' });
expect(lastWhere(findMany)).toMatchObject({
categoryId: 'c1',
brandId: 'b1',
collections: { some: { collectionId: 'col1' } },
});
});
it('matches a gram range against the variants, as the app did', async () => {
// A product qualifies when ANY of its variants is in range
// (SearchView.vue:189-195), not when all of them are.
const { service, findMany } = setup();
await service.findProducts({ page: 1, minGram: 2, maxGram: 8 });
expect(lastWhere(findMany).variants).toEqual({
some: { isActive: true, rashWeightGrams: { gte: 2, lte: 8 } },
});
});
it('accepts an open-ended gram range', async () => {
const { service, findMany } = setup();
await service.findProducts({ page: 1, minGram: 5 });
expect(lastWhere(findMany).variants).toEqual({
some: { isActive: true, rashWeightGrams: { gte: 5 } },
});
});
it('ignores a blank search instead of searching for nothing', async () => {
const { service, findMany } = setup();
await service.findProducts({ page: 1, search: ' ' });
expect(lastWhere(findMany).title).toBeUndefined();
});
});
describe('by ids — the cart, favourites and order items', () => {
it('fetches only the named products and skips paging', async () => {
const { service, findMany } = setup(2);
const out = await service.findProducts({ ids: ['p0', 'p1'], page: 5, limit: 1 });
expect(lastWhere(findMany)).toMatchObject({ id: { in: ['p0', 'p1'] } });
expect(lastArgs(findMany).skip).toBeUndefined();
expect(out.total).toBe(2);
});
it('still hides an inactive or photo-less product asked for by id', async () => {
const { service, findMany } = setup(1);
await service.findProducts({ ids: ['p0'] });
expect(lastWhere(findMany)).toMatchObject({ isActive: true, images: { some: {} } });
});
});
describe('one product by id', () => {
it('returns it', async () => {
const { service } = setup(1);
await expect(service.findProductById('p0')).resolves.toMatchObject({ id: 'p0' });
});
it('404s for a product that is not on the storefront', async () => {
const { service, findMany } = setup(0);
findMany.mockResolvedValue([]);
await expect(service.findProductById('nope')).rejects.toThrow(NotFoundException);
});
});
describe('facets', () => {
it('returns the filter options as small aggregates', async () => {
// These used to be derived by scanning the whole catalogue in the browser,
// which only works while the whole catalogue is in memory.
const { service } = setup();
const out = await service.facets();
expect(out.categories).toEqual([{ id: 'c1', title: 'انگشتر' }]);
expect(out.brands).toEqual([{ id: 'b1', title: 'برند' }]);
expect(out.collections).toEqual([{ id: 'col1', title: 'مجموعه' }]);
// Strings, like every other weight this API returns — Decimal, not float.
expect(out.gramRange).toEqual({ min: '1.5', max: '12' });
});
it('reports a zero range for an empty catalogue', async () => {
const { service, prisma } = setup();
prisma.productVariant.aggregate.mockResolvedValue({
_min: { rashWeightGrams: null },
_max: { rashWeightGrams: null },
});
await expect(service.facets()).resolves.toMatchObject({ gramRange: { min: '0', max: '0' } });
});
});
});
@@ -1,14 +1,58 @@
import { Controller, Get } from '@nestjs/common';
import { Controller, Get, Param, Query } from '@nestjs/common';
import { CatalogService } from './catalog.service';
import { Public } from '../auth/guards';
import { ListProductsDto } from './dto/list-products.dto';
@Public() // pre-existing unauthenticated endpoint; see Phase 1 notes
@Controller('catalog/products')
export class CatalogController {
constructor(private readonly catalog: CatalogService) {}
/**
* The storefront list.
*
* Paging and filtering are OPT-IN, so this stays backward compatible: with no
* query at all the caller gets the plain array it always got (the admin panel,
* the smoke scripts and installed app builds all rely on that). Pass `page` or
* `limit` and the answer becomes `{ rows, total, page, limit }`.
*
* Owner, 2026-10-12: the real catalogue reaches ~16k products, so a client
* must be able to ask for one page — and the filters have to be applied here,
* because a client cannot filter rows it was never sent.
*/
@Get()
list() {
return this.catalog.listProducts();
list(@Query() query: ListProductsDto) {
const asksForMore =
query.page !== undefined ||
query.limit !== undefined ||
query.search !== undefined ||
query.categoryId !== undefined ||
query.brandId !== undefined ||
query.collectionId !== undefined ||
query.minGram !== undefined ||
query.maxGram !== undefined ||
query.sort !== undefined ||
query.ids !== undefined;
// The bare call keeps its original shape — a plain array, from the cache.
return asksForMore ? this.catalog.findProducts(query) : this.catalog.listProducts();
}
/**
* The filter options for the search sheet.
*
* Declared BEFORE `:id`: Nest matches in declaration order, so a literal
* segment that could also read as a parameter has to come first or it is
* never reached.
*/
@Get('facets')
facets() {
return this.catalog.facets();
}
/** One product, for its own screen. */
@Get(':id')
byId(@Param('id') id: string) {
return this.catalog.findProductById(id);
}
}
+178 -6
View File
@@ -1,7 +1,9 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { AccountingHooksService } from '../accounting-sync/accounting-hooks.service';
import { CatalogCacheService } from './catalog-cache.service';
import { DEFAULT_PAGE_SIZE, ListProductsDto, type ProductSort } from './dto/list-products.dto';
@Injectable()
export class CatalogService {
@@ -11,17 +13,187 @@ export class CatalogService {
private readonly catalogCache: CatalogCacheService,
) {}
/** Served from CatalogCacheService; see there for what invalidates it. */
/**
* The whole active catalogue, unpaged.
*
* Kept exactly as it was for every existing caller (the admin panel, the smoke
* scripts, installed app builds). New callers should use `findProducts` with a
* page — the real catalogue reaches ~16k products, and this response carries
* all of them with their variants, images and collections.
*
* Served from CatalogCacheService; see there for what invalidates it.
*/
listProducts() {
return this.catalogCache.get(() => this.buildProductList());
}
private async buildProductList() {
/**
* The storefront list, paged and filtered server-side.
*
* Owner, 2026-10-12: the catalogue reaches ~16k products, so returning it
* whole is wrong. The filters live here rather than in the apps because a
* client cannot filter data it has not been sent — paging the response while
* leaving the filter on the client would silently search only the first page.
*
* Returns `{ rows, total, page, limit }`. With no `page`/`limit` the caller
* gets everything that matches, so the filters are usable on their own.
*
* NOT cached, deliberately. CatalogCacheService holds one built response and
* exists because the unpaged query is expensive and every screen asked for
* it. A paged, filtered query is neither: it is bounded by `limit` and served
* by Product_isActive_createdAt_idx. Caching it would mean a key per filter
* combination — unbounded memory for queries that are already cheap, and a
* second place for stale rows to hide. If this ever needs a cache it should
* be a shared one (Redis), which is also what the single-instance note on
* CatalogCacheService points at.
*/
async findProducts(query: ListProductsDto) {
// Specific ids: the cart, favourites and order items each need a handful of
// known products. Paging and the filters do not apply.
if (query.ids?.length) {
const rows = await this.buildProductList({ ids: query.ids });
return { rows, total: rows.length, page: 1, limit: rows.length };
}
const paged = query.page !== undefined || query.limit !== undefined;
const limit = query.limit ?? DEFAULT_PAGE_SIZE;
const page = query.page ?? 1;
const where = this.storefrontWhere(query);
// Counted with the same `where`, so `total` describes the filtered set and
// the app's "N محصول" and end-of-list detection stay truthful.
const [total, rows] = await Promise.all([
this.prisma.product.count({ where }),
this.buildProductList({
where,
orderBy: this.orderFor(query.sort),
...(paged ? { skip: (page - 1) * limit, take: limit } : {}),
}),
]);
return { rows, total, page: paged ? page : 1, limit: paged ? limit : total };
}
/** One product for its own screen, instead of fetching the catalogue to find it. */
async findProductById(id: string) {
const [product] = await this.buildProductList({ where: { ...this.storefrontWhere({}), id } });
if (!product) throw new NotFoundException('محصول یافت نشد');
return product;
}
/**
* The filter options the search sheet offers.
*
* The apps derived these by scanning the whole catalogue in the browser
* (SearchView.vue:167-181), which is only possible while the whole catalogue
* is in memory. Each is a small aggregate here.
*/
async facets() {
const where = this.storefrontWhere({});
const [categories, brands, collections, gram] = await Promise.all([
this.prisma.category.findMany({
where: { products: { some: where } },
select: { id: true, title: true },
orderBy: { title: 'asc' },
}),
this.prisma.brand.findMany({
where: { products: { some: where } },
select: { id: true, title: true },
orderBy: { title: 'asc' },
}),
this.prisma.collection.findMany({
where: { products: { some: { product: where } } },
select: { id: true, title: true },
orderBy: { title: 'asc' },
}),
this.prisma.productVariant.aggregate({
where: { isActive: true, product: where },
_min: { rashWeightGrams: true },
_max: { rashWeightGrams: true },
}),
]);
return {
categories,
brands,
collections,
// Strings, like every other weight this API returns (Decimal, not float).
gramRange: {
min: gram._min.rashWeightGrams?.toString() ?? '0',
max: gram._max.rashWeightGrams?.toString() ?? '0',
},
};
}
/**
* The two rules that decide whether a product is on the storefront at all,
* plus the caller's filters. Shared so a filtered list, its count, the single
* product route and the facets can never disagree about what is visible.
*
* D27 — a product with no image is never shown in the app. Products also
* arrive from the accounting software, which carries no pictures; they appear
* once an admin photographs them.
*/
private storefrontWhere(query: ListProductsDto): Prisma.ProductWhereInput {
const where: Prisma.ProductWhereInput = { isActive: true, images: { some: {} } };
if (query.search?.trim()) {
// `contains`, as the apps' own title filter did. Case-insensitive is a
// no-op for Persian but matches how every other search in this API reads.
where.title = { contains: query.search.trim(), mode: 'insensitive' };
}
if (query.categoryId) where.categoryId = query.categoryId;
if (query.brandId) where.brandId = query.brandId;
if (query.collectionId) where.collections = { some: { collectionId: query.collectionId } };
// A product is in range when at least ONE of its variants is, which is what
// the app's `limit_gram` filter meant (SearchView.vue:189-195).
if (query.minGram !== undefined || query.maxGram !== undefined) {
where.variants = {
some: {
isActive: true,
rashWeightGrams: {
...(query.minGram !== undefined ? { gte: query.minGram } : {}),
...(query.maxGram !== undefined ? { lte: query.maxGram } : {}),
},
},
};
}
return where;
}
private orderFor(sort: ProductSort | undefined): Prisma.ProductOrderByWithRelationInput {
switch (sort) {
case 'oldest':
return { createdAt: 'asc' };
case 'title':
return { title: 'asc' };
default:
// Newest first, and the half of Product_isActive_createdAt_idx the list
// is indexed for.
return { createdAt: 'desc' };
}
}
private async buildProductList(
opts: {
where?: Prisma.ProductWhereInput;
orderBy?: Prisma.ProductOrderByWithRelationInput;
skip?: number;
take?: number;
ids?: string[];
} = {},
) {
const products = await this.prisma.product.findMany({
// D27 — a product with no image is never shown in the app. Products now
// also arrive from the accounting software, which carries no pictures;
// they appear once an admin photographs them.
where: { isActive: true, images: { some: {} } },
// Defaults to the unfiltered storefront rule, so the unpaged
// `listProducts()` above behaves exactly as before.
where: opts.ids
? { ...this.storefrontWhere({}), id: { in: opts.ids } }
: (opts.where ?? { isActive: true, images: { some: {} } }),
...(opts.orderBy ? { orderBy: opts.orderBy } : {}),
...(opts.skip !== undefined ? { skip: opts.skip } : {}),
...(opts.take !== undefined ? { take: opts.take } : {}),
include: {
// Only orderable variants reach the storefront. An inactive one used to
// be listed and then rejected by getVariantOrThrow at checkout, so the
@@ -0,0 +1,102 @@
import { Transform, Type } from 'class-transformer';
import { ArrayMaxSize, IsArray, IsIn, IsInt, IsNumber, IsOptional, IsString, Max, Min } from 'class-validator';
/** Page size when the caller asks for paging without naming one. */
export const DEFAULT_PAGE_SIZE = 20;
/**
* Hard ceiling on `limit`.
*
* The real catalogue reaches ~16k products, so an unbounded `limit` would let
* any caller ask for all of it — the exact query this whole change exists to
* stop, just spelled differently. 100 is five of the apps' own pages.
*/
export const MAX_PAGE_SIZE = 100;
/**
* Ceiling on `ids`. The cart, favourites and an order's items are all small;
* anything larger is a caller that should be paging instead.
*/
export const MAX_IDS = 100;
export type ProductSort = 'newest' | 'oldest' | 'title';
/**
* Query for `GET /catalog/products`.
*
* Paging is OPT-IN: with neither `page` nor `limit` the route answers exactly as
* it always did, with the whole catalogue, so the admin panel, the smoke scripts
* and already-installed app builds keep working (plan §3-ب). The filters are
* honoured either way.
*/
export class ListProductsDto {
/** 1-based. Sending it (or `limit`) is what turns paging on. */
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page?: number;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(MAX_PAGE_SIZE)
limit?: number;
/** Free text over the product title. Matches the app's own client-side filter. */
@IsOptional()
@IsString()
search?: string;
@IsOptional()
@IsString()
categoryId?: string;
@IsOptional()
@IsString()
brandId?: string;
/** Collection ("مجموعه") the product belongs to — the collection screen. */
@IsOptional()
@IsString()
collectionId?: string;
/**
* Rash-weight range, matched against the product's VARIANTS: a product is in
* range when at least one of its variants is, which is what the app's own
* `limit_gram` filter did (SearchView.vue:189-195).
*/
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
minGram?: number;
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
maxGram?: number;
/**
* Specific ids, for the cart, favourites and order items — each needs a few
* known products, not a page. Ignores paging and the filters above.
*
* Comma-separated so this stays a plain cacheable GET (`?ids=a,b,c`) rather
* than needing a POST for a read. Capped, because the point of this parameter
* is a handful of products: a caller that wants more should page.
*/
@IsOptional()
@Transform(({ value }: { value: unknown }) =>
typeof value === 'string'
? value.split(',').map((s) => s.trim()).filter(Boolean).slice(0, MAX_IDS)
: value,
)
@IsArray()
@ArrayMaxSize(MAX_IDS)
@IsString({ each: true })
ids?: string[];
@IsOptional()
@IsIn(['newest', 'oldest', 'title'])
sort?: ProductSort;
}
@@ -0,0 +1,184 @@
import { ForbiddenException, UnauthorizedException } from '@nestjs/common';
import { AdminRole } from '@prisma/client';
// passport-jwt reads the secret at construction; give it something to find.
process.env.JWT_CUSTOMER_SECRET = 'test-secret';
// @nestjs/jwt v12 is ESM only and this jest setup is CommonJS. The strategy
// pulls it in transitively (customer-auth.service exports customerJwtSecret),
// so it is stubbed here exactly as master-otp.spec.ts does.
jest.mock('@nestjs/jwt', () => ({ JwtService: class {} }));
import { CustomerJwtStrategy } from './customer-jwt.strategy';
import {
ACT_AS_CUSTOMER_HEADER,
CUSTOMER_TOKEN_TYPE,
EXPERT_TOKEN_TYPE,
} from './app-principal';
/**
* «ورود به حساب مشتری» — a sales expert working inside one of their own
* customers' accounts (owner request 2026-10-12).
*
* The reference did this by handing the expert the customer's own permanent
* `api_token` (ApiMobileController.php:197-201), which meant the request was
* literally the customer's: unauditable, valid forever, and still working after
* the expert left. Here the expert keeps their own token and names the customer
* in a header, and this strategy is the ONLY place that decides whether that is
* allowed — so these cases are the whole security boundary of the feature.
*
* The strategy had no test coverage at all before this file.
*/
describe('CustomerJwtStrategy — a sales expert acting as their customer', () => {
const EXPERT = {
id: 'adm_1',
mobile: '09120000001',
role: AdminRole.SALES_EXPERT,
isActive: true,
salesExpertProfile: {
tradingCustomerId: 'cus_trading',
tradingCustomer: { id: 'cus_trading', isActive: true, isArchived: false },
},
};
/** The expert's own referred customer, as the scoped lookup would find them. */
const MINE = { id: 'cus_mine', mobile: '09125555555' };
function build(opts: { admin?: unknown; scopedCustomer?: unknown; customer?: unknown } = {}) {
const prisma = {
adminUser: { findUnique: jest.fn().mockResolvedValue('admin' in opts ? opts.admin : EXPERT) },
customer: {
// The act-as lookup: id AND referredByAgentId in one where clause, so
// "not mine" and "does not exist" are the same answer.
findFirst: jest.fn().mockResolvedValue('scopedCustomer' in opts ? opts.scopedCustomer : MINE),
findUnique: jest.fn().mockResolvedValue(
'customer' in opts
? opts.customer
: { id: 'cus_1', mobile: '09121111111', isActive: true, isArchived: false },
),
},
};
// Session tracking off — isActive() answers true without a query.
const sessions = { isActive: jest.fn().mockResolvedValue(true) };
const strategy = new CustomerJwtStrategy(prisma as never, sessions as never);
return { strategy, prisma };
}
const req = (actAs?: string) =>
({ headers: actAs === undefined ? {} : { [ACT_AS_CUSTOMER_HEADER]: actAs } }) as never;
const expertToken = { sub: 'adm_1', mobile: '09120000001', typ: EXPERT_TOKEN_TYPE } as never;
const customerToken = { sub: 'cus_1', mobile: '09121111111', typ: CUSTOMER_TOKEN_TYPE } as never;
it('serves the customer as themselves, keeping the expert as the real actor', async () => {
const { strategy } = build();
const me = await strategy.validate(req('cus_mine'), expertToken);
// `id` is what every customer route reads — this is the whole feature.
expect(me.id).toBe('cus_mine');
expect(me.actingAsCustomerId).toBe('cus_mine');
// The real actor is never lost, which is what the reference could not do.
expect(me.adminUserId).toBe('adm_1');
expect(me.type).toBe(EXPERT_TOKEN_TYPE);
});
it('scopes the lookup to this expert in the query itself', async () => {
const { strategy, prisma } = build();
await strategy.validate(req('cus_mine'), expertToken);
expect(prisma.customer.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
id: 'cus_mine',
referredByAgentId: 'adm_1',
isActive: true,
isArchived: false,
}),
}),
);
});
it("refuses another expert's customer with 403, not 401", async () => {
// The scoped lookup finds nothing — same answer as a non-existent id, so an
// id cannot be probed for existence.
const { strategy } = build({ scopedCustomer: null });
// 403 and not 401 on purpose: the expert's own session is fine, so the app
// clears the act-as state rather than logging them out.
await expect(strategy.validate(req('cus_someone_else'), expertToken)).rejects.toThrow(
ForbiddenException,
);
});
it('refuses an inactive or archived customer', async () => {
// isActive/isArchived are part of the same where clause, so this is the
// identical "no row" path; asserted separately because it is a distinct
// business case that must not quietly start working.
const { strategy } = build({ scopedCustomer: null });
await expect(strategy.validate(req('cus_disabled'), expertToken)).rejects.toThrow(
ForbiddenException,
);
});
it('cuts the expert off immediately once they are deactivated', async () => {
const { strategy } = build({ admin: { ...EXPERT, isActive: false } });
await expect(strategy.validate(req('cus_mine'), expertToken)).rejects.toThrow(
UnauthorizedException,
);
});
it('cuts them off immediately once they are no longer a sales expert', async () => {
const { strategy } = build({ admin: { ...EXPERT, role: AdminRole.ACCOUNTANT } });
await expect(strategy.validate(req('cus_mine'), expertToken)).rejects.toThrow(
UnauthorizedException,
);
});
it('ignores the header on an ordinary customer token', async () => {
// Not an error — simply no effect. A customer cannot grant themselves
// anything by sending it, and there is nothing for them to discover.
const { strategy, prisma } = build();
const me = await strategy.validate(req('cus_mine'), customerToken);
expect(me.id).toBe('cus_1');
expect(me.actingAsCustomerId).toBeUndefined();
expect(prisma.customer.findFirst).not.toHaveBeenCalled();
});
it('falls back to the trading account when no header is sent', async () => {
const { strategy, prisma } = build();
const me = await strategy.validate(req(), expertToken);
expect(me.id).toBe('cus_trading');
expect(me.actingAsCustomerId).toBeUndefined();
// No extra query on the ordinary path — the act-as lookup never runs.
expect(prisma.customer.findFirst).not.toHaveBeenCalled();
});
it('treats a blank or whitespace header as absent', async () => {
const { strategy } = build();
await expect(strategy.validate(req(' '), expertToken)).resolves.toMatchObject({
id: 'cus_trading',
});
});
it('takes the first value when the header is sent twice', async () => {
const { strategy, prisma } = build();
const dup = { headers: { [ACT_AS_CUSTOMER_HEADER]: ['cus_mine', 'cus_other'] } } as never;
await strategy.validate(dup, expertToken);
expect(prisma.customer.findFirst).toHaveBeenCalledWith(
expect.objectContaining({ where: expect.objectContaining({ id: 'cus_mine' }) }),
);
});
it('refuses a revoked session before looking at the header at all', async () => {
const prisma = {
adminUser: { findUnique: jest.fn() },
customer: { findFirst: jest.fn(), findUnique: jest.fn() },
};
const strategy = new CustomerJwtStrategy(
prisma as never,
{ isActive: jest.fn().mockResolvedValue(false) } as never,
);
await expect(strategy.validate(req('cus_mine'), expertToken)).rejects.toThrow(
UnauthorizedException,
);
expect(prisma.adminUser.findUnique).not.toHaveBeenCalled();
});
});
@@ -54,13 +54,37 @@ export interface AppJwtPayload {
* Customer.referredByAgentId points at the AdminUser, not at the trading row.
*/
export interface AuthenticatedCustomer {
/** Customer id. For an expert, their own trading account. */
/**
* Customer id. For an expert: their own trading account, or — while acting as
* one of their customers — that customer. Every customer route reads this, so
* setting it here is what makes the whole app render from the customer's point
* of view without touching a single route.
*/
id: string;
mobile: string;
/** Which kind of principal this is. */
type: AppTokenType;
/** The AdminUser id — present only for a sales expert. */
adminUserId?: string;
/**
* Set only while a sales expert is acting as one of their referred customers
* («ورود به حساب مشتری»). Equal to `id` when set.
*
* It exists so the real actor is never lost: `id` says whose data this is,
* `adminUserId` says who is actually driving. The reference had no equivalent
* — it handed the expert the customer's own `api_token`, so a request was
* indistinguishable from the customer's own and nothing could be audited
* afterwards.
*/
actingAsCustomerId?: string;
}
/** The request header that asks to act as one of the expert's own customers. */
export const ACT_AS_CUSTOMER_HEADER = 'x-act-as-customer';
/** True when this principal is a sales expert acting as one of their customers. */
export function isActingAsCustomer(me: AuthenticatedCustomer): boolean {
return Boolean(me.actingAsCustomerId);
}
/** True when this principal is a sales expert. */
@@ -1,5 +1,13 @@
import { createHash, createHmac, randomBytes } from 'node:crypto';
import { HttpException, HttpStatus, Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import {
ForbiddenException,
HttpException,
HttpStatus,
Injectable,
Logger,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AdminRole, CustomerKind, MessageAudience, Prisma } from '@prisma/client';
import * as bcrypt from 'bcryptjs';
@@ -16,7 +24,7 @@ import { envList, envOr, envOrNull, pickExactUri } from '../../common/env';
import { masterCodeAllowed } from '../../common/production-checks';
import { CUSTOMER_TOKEN_TYPE, EXPERT_TOKEN_TYPE, type CustomerJwtPayload } from './customer-jwt.strategy';
import { faToEn } from './digits';
import { SmsService, smsConfigured } from '../sms/sms.service';
import { SmsService } from '../sms/sms.service';
/** Nest 10 has no TooManyRequestsException; 429 with a Persian message. */
class TooManyRequestsException extends HttpException {
@@ -126,8 +134,8 @@ export class CustomerAuthService {
* Reference: validate `username`, find an ACTIVE customer by mobile, generate
* rand(1000,9999), store it, send it by SMS, return `true`.
*
* Kept: the active-customer filter, the 4-digit range, the opaque `true`
* response (it never reveals whether the number exists).
* Kept: the active-customer filter, the 4-digit range, and the 404 for a
* number that is not registered (reference `firstOrFail()`).
* Changed: the code is hashed, it expires, and sends are rate limited.
*/
async requestOtp(rawMobile: string, ip: string | undefined) {
@@ -154,12 +162,23 @@ export class CustomerAuthService {
select: { id: true },
}));
// Deliberately opaque: the reference used firstOrFail() and leaked a 404
// for unknown numbers, which let anyone enumerate registered customers.
// Recorded as a deviation in docs/parity/DECISIONS.md.
// Owner ruling 2026-10-12: say so. This used to return `{ sent: true }` for
// a number nobody holds, to stop an outsider enumerating customers. The
// cost landed on real users and on support: the app moved to the code box
// and then nothing arrived, and there was no way to tell apart "the SMS
// gateway is down", "the code is late" and "this number was never
// registered" — the one case the person could actually act on.
//
// This is also what the reference did (`firstOrFail()`,
// ApiMobileController::userAuth:43 → 404), so the opaque response was the
// deviation, not this.
//
// Enumeration is still bounded by the rate limits above — assertSendAllowed
// caps a single IP at MAX_SENDS_PER_IP per window, which it did not do in
// the reference.
if (!customer) {
this.logger.warn(`OTP requested for unknown or inactive mobile ${mobile}`);
return { sent: true };
throw new NotFoundException('این شماره در سیستم ثبت نشده است. لطفاً با پشتیبانی تماس بگیرید.');
}
const code = String(Math.floor(1000 + Math.random() * 9000));
@@ -231,17 +250,22 @@ export class CustomerAuthService {
if (existing && existing.isActive && !existing.isArchived) return { id: existing.id };
// Deliberately does NOT silently create a second account when the first
// was deactivated: an operator disabled it, and that decision stands.
//
// Told apart from "no such number" on purpose: this expert DOES exist, so
// the «ثبت نشده است» message would be false and would send support
// looking for a registration problem that is not there.
this.logger.warn(
`Sales expert ${admin.id} has a trading account that is inactive or archived; refusing to create another.`,
);
return null;
throw new ForbiddenException('حساب شما غیرفعال است. لطفاً با پشتیبانی تماس بگیرید.');
}
if (!admin.salesExpertProfile) {
// Every SALES_EXPERT gets a profile on create and on role change (D17),
// so this means something bypassed both paths.
this.logger.warn(`Sales expert ${admin.id} has no SalesExpertProfile; cannot sign in to the app.`);
return null;
// so this means something bypassed both paths. A server-side defect, not
// a wrong number — so not «ثبت نشده است» either.
this.logger.error(`Sales expert ${admin.id} has no SalesExpertProfile; cannot sign in to the app.`);
throw new ForbiddenException('حساب شما کامل نیست. لطفاً با پشتیبانی تماس بگیرید.');
}
// The mobile is unique on Customer, so a pre-existing customer row with
@@ -313,6 +337,11 @@ export class CustomerAuthService {
// One message for every failure mode, so a caller cannot tell "no code was
// sent" from "wrong code" from "expired". Declared before the master-code
// branch so that path can reject identically.
// Deliberately one message for every reason a code can fail: wrong code, no
// challenge, expired, unknown number. Unlike requestOtp — which now names an
// unregistered number, owner ruling 2026-10-12 — there is nothing for a real
// user to act on differently here, and step 1 already told them if the
// number was not on file, so they never reach this with an unknown number.
const reject = () => new UnauthorizedException('کد وارد شده صحیح نیست');
// D20 — the delivery master code. Checked BEFORE the stored challenge so it
@@ -742,9 +771,11 @@ export class CustomerAuthService {
* When no gateway is configured, SmsService does not send and the code is
* logged instead — outside production only (D20).
*
* A failed send does NOT throw. The reference ignored Sms::Send's result, so
* a gateway outage never blocked the flow that triggered it; the customer
* simply retries, and the throttle in assertSendAllowed still applies.
* A failed send DOES throw 503 (owner ruling 2026-10-12). The reference
* ignored Sms::Send's result and so did this, which meant a gateway outage
* returned success and the app sent the person to the code box to wait for a
* message that had never been sent. See the note at the throw: D20 protects
* operations from a dead gateway, but here the SMS is the operation.
*/
private async deliver(mobile: string, code: string) {
// The reference's text (ApiMobileController.php:47) with the brand changed
@@ -759,14 +790,45 @@ export class CustomerAuthService {
// persist:false — the real text carries the live code, and the admin SMS
// grid lists and searches `body` (SEC-11). The redacted audit row below
// takes its place.
await this.sms.send(mobile, smsText, { persist: false });
const result = await this.sms.send(mobile, smsText, { persist: false });
// Only outside production, and only when no gateway is configured, so a
// deployment can never print live codes into its logs.
if (process.env.NODE_ENV !== 'production' && !smsConfigured()) {
//
// The condition is SmsService's own verdict (`sms-not-configured`), not a
// second guess at the config: with D26's default `relay` driver,
// smsConfigured() is true on any machine that has an external IPv4, so
// testing the config here would have called a dev box "configured" and then
// failed the login below when the relay was unreachable. This is the one
// case where a failed send must not be an error — there was no gateway to
// fail, and local sign-in works off this log line.
const devNoGateway =
process.env.NODE_ENV !== 'production' && !result.ok && result.error === 'sms-not-configured';
if (devNoGateway) {
this.logger.log(`[dev] OTP for ${mobile}: ${code}`);
}
// Owner ruling 2026-10-12, same reasoning as the 404 in requestOtp.
//
// SmsService NEVER throws — a dead gateway is a log line (D20) — so a failed
// send used to return success here and the app walked the person to the code
// box to wait for a message that was never sent. From the outside that is
// indistinguishable from a late SMS, which is exactly the confusion being
// removed.
//
// D20 is about not letting a failed SMS break an *operation*: an order must
// still be placed. In a login the SMS IS the operation, so staying quiet
// protects nothing. The code row stays in the table — it costs nothing and
// expires on its own — and the person is told to retry instead of being left
// watching a countdown.
if (!result.ok && !devNoGateway) {
this.logger.error(`OTP SMS to ${mobile} failed: ${result.error ?? 'unknown'}`);
throw new HttpException(
'ارسال پیام کوتاه در حال حاضر ممکن نیست. لطفاً چند لحظه بعد دوباره تلاش کنید.',
HttpStatus.SERVICE_UNAVAILABLE,
);
}
// An audit row, NOT the message body.
//
// SmsMessage.body is listed and full-text searchable on the admin panel's
@@ -1,10 +1,12 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { AdminRole } from '@prisma/client';
import type { Request } from 'express';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PrismaService } from '../../prisma/prisma.service';
import { customerJwtSecret } from './customer-auth.service';
import {
ACT_AS_CUSTOMER_HEADER,
CUSTOMER_TOKEN_TYPE,
EXPERT_TOKEN_TYPE,
type AppJwtPayload,
@@ -13,8 +15,10 @@ import {
import { AppSessionService } from '../sessions/app-session.service';
export {
ACT_AS_CUSTOMER_HEADER,
CUSTOMER_TOKEN_TYPE,
EXPERT_TOKEN_TYPE,
isActingAsCustomer,
type AuthenticatedCustomer,
} from './app-principal';
@@ -50,10 +54,13 @@ export class CustomerJwtStrategy extends PassportStrategy(Strategy, 'customer-jw
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: customerJwtSecret(),
// Needed only to read the act-as header; the token itself is still the
// only thing that establishes WHO is calling.
passReqToCallback: true,
});
}
async validate(payload: AppJwtPayload): Promise<AuthenticatedCustomer> {
async validate(req: Request, payload: AppJwtPayload): Promise<AuthenticatedCustomer> {
// نشست باطل‌شده (خروج سراسری از IdP یا ابطال محلی). در حالت خاموشِ ردیابی،
// بدون هیچ کوئری true برمی‌گردد ⇒ هزینه و رفتار دقیقاً مثل قبل.
if (!(await this.sessions.isActive(payload?.jti))) {
@@ -61,7 +68,7 @@ export class CustomerJwtStrategy extends PassportStrategy(Strategy, 'customer-jw
}
if (payload?.typ === EXPERT_TOKEN_TYPE) {
return this.validateExpert(payload);
return this.validateExpert(payload, this.actAsHeader(req));
}
// A token that is not explicitly a customer token is refused, whatever
@@ -84,6 +91,17 @@ export class CustomerJwtStrategy extends PassportStrategy(Strategy, 'customer-jw
return { id: customer.id, mobile: customer.mobile, type: CUSTOMER_TOKEN_TYPE };
}
/**
* The act-as header, or null. Deliberately read ONLY for an expert token: on
* a customer's token the header has no effect at all, rather than being an
* error — a customer cannot grant themselves anything by sending it.
*/
private actAsHeader(req: Request): string | null {
const raw = (req?.headers as Record<string, unknown> | undefined)?.[ACT_AS_CUSTOMER_HEADER];
const value = Array.isArray(raw) ? raw[0] : raw;
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
/**
* A sales expert. `sub` is their AdminUser id, so the role and active flag
* are re-checked on every request: demoting an expert or deactivating them
@@ -91,8 +109,28 @@ export class CustomerJwtStrategy extends PassportStrategy(Strategy, 'customer-jw
*
* The trading Customer row is resolved here rather than stored in the token,
* so a token issued before that row existed keeps working.
*
* ACTING AS A CUSTOMER («ورود به حساب مشتری», owner request 2026-10-12)
*
* With `actAs` set, the returned principal's `id` is that customer, so every
* customer route — orders, me, ledger, report, favourites, documents — serves
* the customer's own data with no change to any route. That is the whole
* feature, and it is why this is the only place the behaviour lives.
*
* How this differs from the reference, which did the same thing by handing the
* expert the customer's own `api_token` (ApiMobileController.php:197-201):
*
* - no token is minted, so nothing durable leaks into a device's storage
* and ending the app session ends the impersonation;
* - ownership is re-checked on EVERY request, so moving a customer to
* another expert cuts access off at once instead of at token expiry;
* - `adminUserId` survives, so the real actor is auditable — in the
* reference the request was indistinguishable from the customer's own.
*/
private async validateExpert(payload: AppJwtPayload): Promise<AuthenticatedCustomer> {
private async validateExpert(
payload: AppJwtPayload,
actAs: string | null,
): Promise<AuthenticatedCustomer> {
const admin = await this.prisma.adminUser.findUnique({
where: { id: payload.sub },
select: {
@@ -113,6 +151,36 @@ export class CustomerJwtStrategy extends PassportStrategy(Strategy, 'customer-jw
throw new UnauthorizedException();
}
if (actAs) {
// Scoped by referredByAgentId in the same query as the id, so another
// expert's customer and a non-existent id are the same answer: no row,
// 403. The lookup cannot be talked out of its scope.
const customer = await this.prisma.customer.findFirst({
where: {
id: actAs,
referredByAgentId: admin.id,
isActive: true,
isArchived: false,
},
select: { id: true, mobile: true },
});
if (!customer) {
// Not 401: the expert's own session is perfectly valid, it is this
// particular impersonation that is refused — so the app can clear the
// act-as state instead of logging them out.
throw new ForbiddenException('دسترسی به این مشتری مجاز نیست');
}
return {
id: customer.id,
mobile: customer.mobile,
type: EXPERT_TOKEN_TYPE,
adminUserId: admin.id,
actingAsCustomerId: customer.id,
};
}
const trading = admin.salesExpertProfile?.tradingCustomer;
if (!trading || !trading.isActive || trading.isArchived) {
// The account is created at sign-in; if it is missing or has been
@@ -0,0 +1,165 @@
import { ForbiddenException, HttpException, NotFoundException } from '@nestjs/common';
import { AdminRole } from '@prisma/client';
// @nestjs/jwt v12 ships ESM only, which this CommonJS jest setup cannot load.
// Same stub as master-otp.spec.ts — the service gets a hand-built double.
jest.mock('@nestjs/jwt', () => ({ JwtService: class {} }));
import { CustomerAuthService } from './customer-auth.service';
/**
* Owner ruling 2026-10-12 — step 1 of the app login must say what went wrong.
*
* Until now an unknown number got `{ sent: true }` (opaque on purpose, to stop
* customer enumeration) and a failed SMS send also got `{ sent: true }` (a dead
* gateway is only a log line, D20). Both walked the person to the code box to
* wait for a message that was never going to arrive, and nothing on screen told
* the three real causes apart: the SMS is late, the gateway is down, or the
* number was never registered.
*
* `requestOtp` had NO test coverage at all before this file, so the whole suite
* stayed green through that change — these cases exist so it cannot again.
*/
describe('CustomerAuthService.requestOtp — the caller is told what happened', () => {
const saved = { ...process.env };
const CUSTOMER = { id: 'cus_1', mobile: '09121112233', isActive: true, isArchived: false };
function build(opts: {
customer?: unknown;
expert?: unknown;
smsResult?: { ok: boolean; error?: string };
} = {}) {
const prisma = {
customer: {
findFirst: jest.fn().mockResolvedValue('customer' in opts ? opts.customer : CUSTOMER),
findUnique: jest.fn().mockResolvedValue(null),
},
customerOtp: {
findFirst: jest.fn().mockResolvedValue(null),
create: jest.fn().mockResolvedValue({}),
count: jest.fn().mockResolvedValue(0),
},
smsMessage: { create: jest.fn().mockResolvedValue({}) },
adminUser: { findFirst: jest.fn().mockResolvedValue(opts.expert ?? null) },
};
const sms = { send: jest.fn().mockResolvedValue(opts.smsResult ?? { ok: true }) };
const service = new CustomerAuthService(
prisma as never,
{ signAsync: jest.fn() } as never,
sms as never,
{ enabled: false, attestOtpLogin: jest.fn(), browserBootstrapUrl: () => null } as never,
{ newTokenId: jest.fn().mockReturnValue(null), record: jest.fn() } as never,
);
jest.spyOn(service['logger'], 'warn').mockImplementation(() => undefined);
jest.spyOn(service['logger'], 'error').mockImplementation(() => undefined);
return { service, prisma, sms };
}
beforeEach(() => {
process.env.NODE_ENV = 'test';
});
afterEach(() => {
process.env = { ...saved };
});
it('sends the code for a registered, active customer', async () => {
const { service, sms, prisma } = build();
await expect(service.requestOtp('09121112233', '127.0.0.1')).resolves.toEqual({ sent: true });
expect(sms.send).toHaveBeenCalledTimes(1);
expect(prisma.customerOtp.create).toHaveBeenCalledTimes(1);
});
it('refuses an unregistered number with «ثبت نشده»، not a silent success', async () => {
const { service, sms } = build({ customer: null });
await expect(service.requestOtp('09129999999', '127.0.0.1')).rejects.toThrow(NotFoundException);
await expect(service.requestOtp('09129999999', '127.0.0.1')).rejects.toThrow('ثبت نشده');
// Nothing was sent and no challenge was stored for a number nobody holds.
expect(sms.send).not.toHaveBeenCalled();
});
it('normalises Persian digits before deciding the number is unknown', async () => {
// Guards against a false «ثبت نشده» for someone typing on a Persian keypad.
const { service, prisma } = build();
await service.requestOtp('۰۹۱۲۱۱۱۲۲۳۳', '127.0.0.1');
expect(prisma.customer.findFirst).toHaveBeenCalledWith(
expect.objectContaining({ where: expect.objectContaining({ mobile: '09121112233' }) }),
);
});
it('reports a failed SMS send as 503 instead of claiming it was sent', async () => {
const { service } = build({ smsResult: { ok: false, error: 'gateway refused' } });
await expect(service.requestOtp('09121112233', '127.0.0.1')).rejects.toThrow(HttpException);
await expect(service.requestOtp('09121112233', '127.0.0.1')).rejects.toThrow('ارسال پیام کوتاه');
});
it('still completes the login in development when there is no gateway at all', async () => {
// The local-dev path: SmsService sends nothing, returns its own
// `sms-not-configured`, and the code is logged instead — so this one failure
// must NOT become an error or nobody could sign in locally.
process.env.NODE_ENV = 'development';
const { service } = build({ smsResult: { ok: false, error: 'sms-not-configured' } });
await expect(service.requestOtp('09121112233', '127.0.0.1')).resolves.toEqual({ sent: true });
});
it('still fails in development when a configured gateway refuses', async () => {
// D26's default `relay` driver counts as configured on any machine with an
// external IPv4, so a dev box that cannot reach the relay gets a real
// failure — which must be reported, not swallowed as "no gateway".
process.env.NODE_ENV = 'development';
const { service } = build({ smsResult: { ok: false, error: 'relay unreachable' } });
await expect(service.requestOtp('09121112233', '127.0.0.1')).rejects.toThrow('ارسال پیام کوتاه');
});
it('refuses in production even when nothing is configured', async () => {
// The dev fallback must never let a production deployment report success
// while silently sending nothing.
process.env.NODE_ENV = 'production';
const { service } = build({ smsResult: { ok: false, error: 'sms-not-configured' } });
await expect(service.requestOtp('09121112233', '127.0.0.1')).rejects.toThrow('ارسال پیام کوتاه');
});
/**
* A sales expert signs in through this same flow (D21). Three states return
* no trading account for an expert who DOES exist, and «ثبت نشده است» would
* be a lie in each — it would send support hunting a registration problem.
*/
describe('a sales expert whose trading account cannot be used', () => {
it('says the account is disabled, not that the number is unknown', async () => {
const { service } = build({
customer: null,
expert: {
id: 'adm_1',
mobile: '09121112233',
role: AdminRole.SALES_EXPERT,
fullName: 'کارشناس',
firstName: 'کار',
lastName: 'شناس',
wagePercent: '0',
salesExpertProfile: { id: 'sep_1', gramLevel: '0', nationalCode: null, tradingCustomerId: 'cus_dead' },
},
});
// findUnique returns null → the linked customer is gone or unusable.
await expect(service.requestOtp('09121112233', '127.0.0.1')).rejects.toThrow(ForbiddenException);
await expect(service.requestOtp('09121112233', '127.0.0.1')).rejects.toThrow('غیرفعال');
});
it('says the account is incomplete when the expert has no profile', async () => {
const { service } = build({
customer: null,
expert: {
id: 'adm_2',
mobile: '09121112233',
role: AdminRole.SALES_EXPERT,
fullName: 'کارشناس',
firstName: 'کار',
lastName: 'شناس',
wagePercent: '0',
salesExpertProfile: null,
},
});
await expect(service.requestOtp('09121112233', '127.0.0.1')).rejects.toThrow('کامل نیست');
});
});
});
@@ -67,7 +67,34 @@ export class CustomersService {
getOrders(customerId: string) {
return this.prisma.order.findMany({
where: { customerId },
include: { items: true },
include: {
items: {
// Each item carried only `productVariantId`, so the apps looked the
// title up by loading the ENTIRE catalogue and joining in the browser
// (composables/useOrderItemProduct.ts). With ~16k products that is
// the wrong trade for a few row labels, and it also failed for an
// order whose product has since left the storefront — the catalogue
// hides it, so the row rendered blank.
//
// A nested read here is one join and always answers, including for
// products that are no longer on sale.
include: {
productVariant: {
select: {
id: true,
title: true,
product: {
select: {
id: true,
title: true,
images: { orderBy: { sortOrder: 'asc' }, take: 1, select: { url: true } },
},
},
},
},
},
},
},
orderBy: { createdAt: 'desc' },
});
}
@@ -0,0 +1,62 @@
import { CustomersService } from './customers.service';
/**
* `GET customer/me/orders` must carry each item's product and variant.
*
* The apps used to label order rows by downloading the ENTIRE catalogue and
* joining it in the browser (composables/useOrderItemProduct.ts). With the real
* catalogue at ~16k products that is the wrong trade for a few row labels, and
* it was also broken for the case order history exists for: a product that has
* since left the storefront is absent from the catalogue, so the row rendered
* blank.
*
* Both apps now read these fields straight off the item, so the include is part
* of the contract — hence a test, which this method did not have.
*/
describe('CustomersService.getOrders — items carry their product', () => {
function setup() {
const findMany = jest.fn().mockResolvedValue([]);
const prisma = { order: { findMany } };
// getOrders touches neither the accounting sync nor anything on it.
const service = new CustomersService(prisma as never, {} as never);
return { service, findMany };
}
it('includes the variant, its product and the first image', async () => {
const { service, findMany } = setup();
await service.getOrders('c1');
const include = findMany.mock.calls[0][0].include;
const variant = include.items.include.productVariant;
expect(variant.select.title).toBe(true);
expect(variant.select.product.select.title).toBe(true);
// images[0] is the product's main photo, so it must be ordered and limited
// to one — the apps read `images[0].url` and nothing else.
expect(variant.select.product.select.images).toMatchObject({
orderBy: { sortOrder: 'asc' },
take: 1,
});
});
it('is scoped to the caller and newest first', async () => {
// Guards the two properties that were already here: one customer must never
// receive another's orders, and the list is reverse-chronological.
const { service, findMany } = setup();
await service.getOrders('c1');
expect(findMany.mock.calls[0][0]).toMatchObject({
where: { customerId: 'c1' },
orderBy: { createdAt: 'desc' },
});
});
it('does not filter the product by storefront visibility', async () => {
// Deliberate: an order for a product that has since been deactivated, or
// had its photo removed, must still show what was bought. The storefront
// rules apply to the catalogue, not to history.
const { service, findMany } = setup();
await service.getOrders('c1');
const product = findMany.mock.calls[0][0].include.items.include.productVariant.select.product;
expect(product.where).toBeUndefined();
});
});
@@ -22,11 +22,23 @@ import type { AuthenticatedCustomer } from '../customer-auth/customer-jwt.strate
export class OrdersController {
constructor(private readonly orders: OrdersService) {}
/** The customer comes from the token; the body's `customerId` is ignored. */
/**
* The customer comes from the token; the body's `customerId` is ignored.
*
* `me.id` is already the right customer when a sales expert is acting as one
* of theirs, so such an order lands on that customer's account and ledger with
* server-side pricing (MON-08) exactly like one they placed themselves — which
* is what the reference did by lending the expert the customer's token.
* `actingAsExpertId` records who actually placed it, which the reference could
* not do.
*/
@CustomerAuth()
@Post()
create(@Body() dto: CreateOrderDto, @CurrentCustomer() me: AuthenticatedCustomer) {
return this.orders.createOrder(dto, me.id, { placedBy: 'customer' });
return this.orders.createOrder(dto, me.id, {
placedBy: 'customer',
actingAsExpertId: me.actingAsCustomerId ? me.adminUserId : undefined,
});
}
/**
+2 -1
View File
@@ -4,9 +4,10 @@ import { OrdersController } from './orders.controller';
import { CatalogModule } from '../catalog/catalog.module';
import { AccountingModule } from '../accounting/accounting.module';
import { PricingModule } from '../pricing/pricing.module';
import { SmsModule } from '../sms/sms.module';
@Module({
imports: [CatalogModule, AccountingModule, PricingModule],
imports: [CatalogModule, AccountingModule, PricingModule, SmsModule],
controllers: [OrdersController],
providers: [OrdersService],
exports: [OrdersService],
@@ -1,6 +1,10 @@
import { Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { OrdersService } from './orders.service';
/** Order SMS is fire-and-forget (D20); these suites only assert order data. */
const smsStub = { send: jest.fn(async () => ({ ok: true })) };
/**
* Owner ruling 2026-10-08: an order is credited to the customer's expert AT
* THE MOMENT IT IS PLACED (legacy `orders.reagent_id`), and a later change of
@@ -26,12 +30,13 @@ describe('OrdersService.createOrder — sales expert credit', () => {
goldCreditLimitGrams: new Prisma.Decimal(1000),
})),
},
adminUser: { findUnique: jest.fn(async () => null) },
$transaction: jest.fn(async (fn: (t: typeof tx) => unknown) => fn(tx)),
};
const catalog = { getVariantOrThrow: jest.fn(async () => ({ id: 'v1', rashWeightGrams: '10' })) };
const accounting = { orderStatusReached: jest.fn() };
const wage = { quote: jest.fn() };
const service = new OrdersService(prisma as never, catalog as never, {} as never, accounting as never, wage as never);
const service = new OrdersService(prisma as never, catalog as never, {} as never, accounting as never, wage as never, smsStub as never);
return { service, created };
}
@@ -72,7 +77,7 @@ describe('OrdersService.createOrder — order ban', () => {
$transaction: jest.fn(async (fn: (t: typeof tx) => unknown) => fn(tx)),
};
const catalog = { getVariantOrThrow: jest.fn(async () => ({ id: 'v1', rashWeightGrams: '10' })) };
return new OrdersService(prisma as never, catalog as never, {} as never, { orderStatusReached: jest.fn() } as never, wageStub as never);
return new OrdersService(prisma as never, catalog as never, {} as never, { orderStatusReached: jest.fn() } as never, wageStub as never, smsStub as never);
}
const dto = { items: [{ productVariantId: 'v1', quantity: 1, wagePercent: 3 }] } as never;
@@ -99,7 +104,7 @@ describe('OrdersService.createOrder — server-side making charge', () => {
$transaction: jest.fn(async (fn: (t: typeof tx) => unknown) => fn(tx)),
};
const catalog = { getVariantOrThrow: jest.fn(async () => ({ id: 'v1', rashWeightGrams: '10' })) };
const service = new OrdersService(prisma as never, catalog as never, {} as never, { orderStatusReached: jest.fn() } as never, wageStub as never);
const service = new OrdersService(prisma as never, catalog as never, {} as never, { orderStatusReached: jest.fn() } as never, wageStub as never, smsStub as never);
return { service, created };
}
// A tampered request: zero making charge, a 50% discount and a rial charge.
@@ -118,4 +123,167 @@ describe('OrdersService.createOrder — server-side making charge', () => {
expect(created[0].totalGoldWeightGrams.toString()).toBe('5');
expect(created[0].flatRialCharge.toString()).toBe('999');
});
/**
* MON-08 step 3 (owner ruling): «تست مقایسه‌ای که نشان دهد نتیجه برای کاربر
* عادی یکسان است». An unmodified app sends what the server derives
* (DECISIONS §"Report — MON-08"), so deriving server-side must not move the
* total for an ordinary customer.
*/
it('gives an honest app exactly the total it sent', async () => {
const honest = { items: [{ productVariantId: 'v1', quantity: 1, wagePercent: 10, discountPercent: 0, flatRialCharge: 0 }] } as never;
const a = build();
await a.service.createOrder(honest, 'c1', { placedBy: 'customer' });
const b = build();
await b.service.createOrder(honest, 'c1', { placedBy: 'operator' });
expect(a.created[0].totalGoldWeightGrams.toString()).toBe(b.created[0].totalGoldWeightGrams.toString());
expect(a.created[0].flatRialCharge.toString()).toBe(b.created[0].flatRialCharge.toString());
});
/** MON-08 step 2: a discarded client figure must leave a trace. */
it('logs what the client sent when it differs from the server', async () => {
const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
try {
await build().service.createOrder(tampered, 'c1', { placedBy: 'customer' });
const lines = warn.mock.calls.map((c) => String(c[0])).join('\n');
expect(lines).toContain('wagePercent sent=0 used=10');
expect(lines).toContain('discountPercent sent=50 used=0');
expect(lines).toContain('flatRialCharge sent=999 used=0');
} finally {
warn.mockRestore();
}
});
/**
* «ورود به حساب مشتری»: the order is the customer's in every respect — their
* account, their pricing — and the expert is recorded only in the log, which
* is the audit trail the reference lost by lending out the customer's token.
*/
it('records which expert placed an order on a customer’s behalf', async () => {
const log = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
try {
const honest = { items: [{ productVariantId: 'v1', quantity: 1, wagePercent: 10 }] } as never;
const { service, created } = build();
await service.createOrder(honest, 'c1', { placedBy: 'customer', actingAsExpertId: 'adm_9' });
// Still the customer's order, priced by the server.
expect(created[0].customerId).toBe('c1');
expect(created[0].totalGoldWeightGrams.toString()).toBe('11');
const lines = log.mock.calls.map((c) => String(c[0])).join('\n');
expect(lines).toContain('sales expert adm_9 acting as them');
} finally {
log.mockRestore();
}
});
it('logs no expert for an ordinary customer order', async () => {
const log = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
try {
const honest = { items: [{ productVariantId: 'v1', quantity: 1, wagePercent: 10 }] } as never;
await build().service.createOrder(honest, 'c1', { placedBy: 'customer' });
const lines = log.mock.calls.map((c) => String(c[0])).join('\n');
expect(lines).not.toContain('acting as');
} finally {
log.mockRestore();
}
});
it('stays quiet when the app sent the right figures', async () => {
const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
try {
const honest = { items: [{ productVariantId: 'v1', quantity: 1, wagePercent: 10 }] } as never;
await build().service.createOrder(honest, 'c1', { placedBy: 'customer' });
const pricing = warn.mock.calls.filter((c) => String(c[0]).includes('Order pricing'));
expect(pricing).toHaveLength(0);
} finally {
warn.mockRestore();
}
});
});
/**
* Legacy ApiMobileController::setOrder:733-766 texted three audiences on every
* placed order. None of it was wired in the target until now.
*/
describe('OrdersService.createOrder — order SMS', () => {
function build(opts: { overLimit?: boolean; agentId?: string | null; agentMobile?: string | null } = {}) {
const sent: { to: string; body: string }[] = [];
const tx = { order: { create: jest.fn(async ({ data }: { data: object }) => ({ id: 'o1', ...data })) } };
const prisma = {
customer: {
findUnique: jest.fn(async () => ({
id: 'c1',
mobile: '09120000001',
firstName: 'علی',
lastName: 'رضایی',
canPlaceOrders: true,
referredByAgentId: opts.agentId ?? null,
goldDebtGrams: new Prisma.Decimal(0),
goldCreditLimitGrams: new Prisma.Decimal(opts.overLimit ? 1 : 1000),
})),
},
adminUser: { findUnique: jest.fn(async () => ({ mobile: opts.agentMobile ?? null })) },
$transaction: jest.fn(async (fn: (t: typeof tx) => unknown) => fn(tx)),
};
const catalog = { getVariantOrThrow: jest.fn(async () => ({ id: 'v1', rashWeightGrams: '10' })) };
const sms = { send: jest.fn(async (to: string, body: string) => { sent.push({ to, body }); return { ok: true }; }) };
const service = new OrdersService(prisma as never, catalog as never, {} as never, { orderStatusReached: jest.fn() } as never, wageStub as never, sms as never);
return { service, sent };
}
const dto = { items: [{ productVariantId: 'v1', quantity: 1, wagePercent: 3 }] } as never;
// SMS is deliberately not awaited (D20), so let the microtasks drain.
const settle = () => new Promise((r) => setImmediate(r));
afterEach(() => { delete process.env.ORDER_ADMIN_MOBILES; });
it('texts the customer that the order was placed', async () => {
const { service, sent } = build();
await service.createOrder(dto, 'c1', { placedBy: 'customer' });
await settle();
const toCustomer = sent.find((s) => s.to === '09120000001');
expect(toCustomer?.body).toContain('به ثبت رسید. منتزر');
expect(toCustomer?.body).not.toContain('معلق');
});
it('tells the customer an over-limit order was suspended', async () => {
const { service, sent } = build({ overLimit: true });
await service.createOrder(dto, 'c1', { placedBy: 'customer' });
await settle();
const toCustomer = sent.find((s) => s.to === '09120000001');
expect(toCustomer?.body).toContain('عبور از سقف مجاز گرمی در حالت معلق قرار گرفت');
});
it('texts every configured admin with the name and weight', async () => {
process.env.ORDER_ADMIN_MOBILES = '09121111111, 09122222222';
const { service, sent } = build();
await service.createOrder(dto, 'c1', { placedBy: 'customer' });
await settle();
const admins = sent.filter((s) => s.to.startsWith('0912') && s.to !== '09120000001');
expect(admins.map((a) => a.to)).toEqual(['09121111111', '09122222222']);
expect(admins[0].body).toContain('علی رضایی');
expect(admins[0].body).toContain('11');
});
it('texts nobody extra when no admin numbers are configured', async () => {
const { service, sent } = build();
await service.createOrder(dto, 'c1', { placedBy: 'customer' });
await settle();
expect(sent).toHaveLength(1);
expect(sent[0].to).toBe('09120000001');
});
it("texts the customer's sales expert", async () => {
const { service, sent } = build({ agentId: 'agent-A', agentMobile: '09123333333' });
await service.createOrder(dto, 'c1', { placedBy: 'customer' });
await settle();
const toAgent = sent.find((s) => s.to === '09123333333');
expect(toAgent?.body).toContain('سفارشی توسط علی رضایی');
});
it('places the order even when the expert has no mobile', async () => {
const { service, sent } = build({ agentId: 'agent-A', agentMobile: null });
await expect(service.createOrder(dto, 'c1', { placedBy: 'customer' })).resolves.toMatchObject({ id: 'o1' });
await settle();
expect(sent).toHaveLength(1);
});
});
+140 -3
View File
@@ -4,8 +4,9 @@ import { PrismaService } from '../../prisma/prisma.service';
import { CatalogService } from '../catalog/catalog.service';
import { LedgerService } from '../accounting/ledger.service';
import { AccountingHooksService } from '../accounting-sync/accounting-hooks.service';
import { CreateOrderDto } from './dto/create-order.dto';
import { CreateOrderDto, CreateOrderItemInputDto } from './dto/create-order.dto';
import { WageService } from '../pricing/wage.service';
import { SmsService } from '../sms/sms.service';
interface ComputedItem {
productVariantId: string;
@@ -27,6 +28,7 @@ export class OrdersService {
private readonly ledger: LedgerService,
private readonly accounting: AccountingHooksService,
private readonly wage: WageService,
private readonly sms: SmsService,
) {}
/**
@@ -43,7 +45,16 @@ export class OrdersService {
async createOrder(
dto: CreateOrderDto,
customerId: string,
opts: { placedBy: 'customer' | 'operator' } = { placedBy: 'operator' },
opts: {
placedBy: 'customer' | 'operator';
/**
* Set when a sales expert placed this through «ورود به حساب مشتری». The
* order is the customer's in every other respect; this only records who
* actually pressed the button, which the reference lost entirely by
* lending out the customer's own token.
*/
actingAsExpertId?: string;
} = { placedBy: 'operator' },
) {
const customer = await this.prisma.customer.findUnique({ where: { id: customerId } });
if (!customer) throw new NotFoundException(`Customer ${customerId} not found`);
@@ -86,6 +97,7 @@ export class OrdersService {
if (quotes && !quote) throw new NotFoundException(`Variant ${variant.id} not found`);
const wagePercent = new Prisma.Decimal(quote ? quote.wagePercentSnapshot : item.wagePercent);
const discountPercent = new Prisma.Decimal(quote ? quote.discountPercentSnapshot : (item.discountPercent ?? 0));
if (quote) this.warnOnPriceMismatch(variant.id, item, wagePercent, discountPercent);
const netPercent = wagePercent.sub(discountPercent);
const computedWeightGrams = rashWeight.mul(netPercent.div(100).add(1));
@@ -122,7 +134,7 @@ export class OrdersService {
.gt(customer.goldCreditLimitGrams);
const initialStatus = isSuspendedOverCreditLimit ? OrderStatus.SUSPENDED : OrderStatus.PLACED;
return this.prisma.$transaction(async (tx) => {
const placed = await this.prisma.$transaction(async (tx) => {
const order = await tx.order.create({
data: {
orderNumber: this.generateOrderNumber(),
@@ -162,6 +174,131 @@ export class OrdersService {
return order;
});
// Legacy sent these after the order was committed
// (ApiMobileController.php:733-766), so a rolled-back order never texts
// anyone. Fire-and-forget per D20.
// The audit trail for «ورود به حساب مشتری». Deliberately logged after the
// commit, so it only ever claims an order that exists.
if (opts.actingAsExpertId) {
this.logger.log(
`Order ${placed.orderNumber} for customer ${customerId} was placed by ` +
`sales expert ${opts.actingAsExpertId} acting as them.`,
);
}
this.notifyOrderPlaced(placed.orderNumber, customer, totalGoldWeightGrams, isSuspendedOverCreditLimit);
return placed;
}
/**
* MON-08 step 2: the server's own figures are what the order is charged, but
* a client that sent something else is worth seeing. An ordinary app sends
* exactly what the server derives (DECISIONS §"Report — MON-08"), so a
* mismatch means a stale app version, a promotion that expired between the
* product page and checkout, or a tampered request.
*
* `flatRialCharge` is included because the app hardcodes 0 (cart.vue:179) and
* only an operator ever sets one — anything non-zero from a customer is a
* client that should not be sending it.
*/
private warnOnPriceMismatch(
variantId: string,
sent: CreateOrderItemInputDto,
wagePercent: Prisma.Decimal,
discountPercent: Prisma.Decimal,
) {
const differs: string[] = [];
if (!wagePercent.eq(sent.wagePercent)) {
differs.push(`wagePercent sent=${sent.wagePercent} used=${wagePercent.toString()}`);
}
if (!discountPercent.eq(sent.discountPercent ?? 0)) {
differs.push(`discountPercent sent=${sent.discountPercent ?? 0} used=${discountPercent.toString()}`);
}
if ((sent.flatRialCharge ?? 0) !== 0) {
differs.push(`flatRialCharge sent=${sent.flatRialCharge} used=0`);
}
if (differs.length) {
this.logger.warn(
`Order pricing for variant ${variantId}: the server's figures are used, ` +
`the client's are ignored — ${differs.join('; ')}`,
);
}
}
/**
* The admins who are told a new order was placed.
*
* Legacy hardcoded four numbers (ApiMobileController.php:740-743); this reads
* a comma-separated env var, as the complete-profile notifier already does.
* Unset means nobody is notified and the order itself still goes through.
*/
private adminMobiles(): string[] {
return (process.env.ORDER_ADMIN_MOBILES ?? '')
.split(',')
.map((m) => m.trim())
.filter(Boolean);
}
/**
* Legacy ApiMobileController::setOrder:733-766, brand changed to منتزر.
*
* Three audiences: the admins, the customer, and the customer's sales expert.
* Legacy's fourth message — «در سیستم ویرایش شد» (:734-737) — is
* «عمداً تکرار نشد»: no target path lets a customer edit a placed order, so
* that branch could never fire.
*
* `Notify::store` sat beside each of these in legacy (Firebase push); that is
* PUSH-01, deferred to the PWA port.
*/
private notifyOrderPlaced(
orderNumber: string,
customer: { mobile: string; firstName: string | null; lastName: string | null; referredByAgentId: string | null },
totalGoldWeightGrams: Prisma.Decimal,
isSuspendedOverCreditLimit: boolean,
) {
const fire = (to: string, body: string) => {
void this.sms.send(to, body).catch((e: unknown) => {
this.logger.error(`Order SMS to ${to} failed: ${String(e)}`);
});
};
const name = `${customer.firstName ?? ''} ${customer.lastName ?? ''}`.trim();
// Legacy printed Utility::round($allGram) — two decimals, trailing zeros
// dropped, which is what Decimal's own string form gives.
const weight = totalGoldWeightGrams.toDecimalPlaces(2).toString();
const adminMessage = `منتزر\nسفارشی توسط ${name}\n به وزن ${weight}\nدر سیستم ثبت شد.`;
for (const admin of this.adminMobiles()) fire(admin, adminMessage);
fire(
customer.mobile,
isSuspendedOverCreditLimit
? `سفارش شما به شماره ${orderNumber} به ثبت رسید اما به دلیل عبور از سقف مجاز گرمی در حالت معلق قرار گرفت. منتزر`
: `سفارش شما به شماره ${orderNumber} به ثبت رسید. منتزر`,
);
if (customer.referredByAgentId) {
void this.notifySalesAgent(customer.referredByAgentId, name, orderNumber, weight);
}
}
/** Legacy :762-765 — the referring expert is texted too. */
private async notifySalesAgent(agentId: string, customerName: string, orderNumber: string, weight: string) {
try {
const agent = await this.prisma.adminUser.findUnique({
where: { id: agentId },
select: { mobile: true },
});
if (!agent?.mobile) return;
await this.sms.send(
agent.mobile,
`منتزر\nسفارشی توسط ${customerName} به شماره ${orderNumber}و به وزن ${weight} به ثبت رسید.`,
);
} catch (e: unknown) {
this.logger.error(`Order SMS to sales agent ${agentId} failed: ${String(e)}`);
}
}
async updateStatus(orderId: string, newStatus: OrderStatus, actorAdminUserId?: string, note?: string) {
@@ -57,10 +57,18 @@ export class SalesExpertAppController {
* Whether the signed-in principal is a sales expert. The apps call this once
* after login to decide whether to show the two expert entries; the answer
* comes from the token, so a customer cannot make it say yes.
*
* `actingAsCustomerId` lets an app that was reloaded mid-impersonation render
* its "viewing as …" bar from the server's view of the session rather than
* trusting its own stored state.
*/
@CustomerAuth()
@Get('whoami')
whoami(@CurrentCustomer() me: AuthenticatedCustomer) {
return { isSalesExpert: Boolean(me.adminUserId), type: me.type };
return {
isSalesExpert: Boolean(me.adminUserId),
type: me.type,
actingAsCustomerId: me.actingAsCustomerId ?? null,
};
}
}
+11 -1
View File
@@ -6,7 +6,8 @@
already commented out in legacy's own App.vue, so neither ran there either.
-->
<template>
<div>
<div :class="{ 'is-actingAs': Boolean(session.actingAs) }">
<ActingAsBar />
<component :is="getLayout" class="relative">
<router-view v-slot="{ Component, route }">
<keep-alive>
@@ -35,8 +36,11 @@ import FullPageLayout from './layout/FullPageLayout.vue'
import AppUpdateGate from './components/AppUpdateGate.vue'
import ToastHost from './components/ui/ToastHost.vue'
import ProductMorph from './components/product/ProductMorph.vue'
import ActingAsBar from './components/expert/ActingAsBar.vue'
import { useSessionStore } from './stores/session'
const router = useRouter()
const session = useSessionStore()
// Registers the service worker (offline, install). Updates are not applied
// here: AppUpdateGate shows what changed and applies them on the user's tap.
useRegisterSW()
@@ -54,6 +58,12 @@ body::-webkit-scrollbar {
display: none;
}
/* The act-as strip is fixed, so push everything down by its height while it is
up — otherwise it covers the top of each page, including sticky headers. */
.is-actingAs {
padding-top: 30px;
}
#app {
overflow: hidden;
direction: rtl !important;
+147 -1
View File
@@ -2,6 +2,10 @@ 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';
/** Must match MAX_IDS on the server's ListProductsDto. */
const ID_CHUNK = 100;
/**
* Called when the API rejects our token. Wired up in main.ts rather than
@@ -30,8 +34,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 +64,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,
},
});
@@ -103,6 +132,54 @@ export interface ProductSummary {
collections: Array<{ collectionId: string; collection: CollectionSummary }>;
}
/** Query for the paged storefront list; every field is optional. */
export interface ProductQuery {
page?: number;
limit?: number;
search?: string;
categoryId?: string;
brandId?: string;
collectionId?: string;
minGram?: number;
maxGram?: number;
sort?: 'newest' | 'oldest' | 'title';
}
/**
* One page of products. `total` is the size of the FILTERED set, not of the
* page, so it both drives the "N محصول" count and tells the list when to stop
* asking for more.
*/
export interface ProductPage {
rows: ProductSummary[];
total: number;
page: number;
limit: number;
}
/** Filter options, built from the catalogue server-side. */
export interface CatalogFacets {
categories: CategorySummary[];
brands: BrandSummary[];
collections: CollectionSummary[];
/** Decimal strings, like every other weight this API returns. */
gramRange: { min: string; max: string };
}
/**
* Builds `?a=1&b=2`, dropping anything unset so the server sees a bare request
* rather than `?search=undefined` — which would be a filter for the literal
* text "undefined".
*/
function toQueryString(query: object): string {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(query)) {
if (value !== undefined && value !== '') params.set(key, String(value));
}
const s = params.toString();
return s ? `?${s}` : '';
}
export interface LedgerEntrySummary {
id: string;
currency: string;
@@ -131,6 +208,22 @@ export interface OrderItemDetail {
discountPercentSnapshot: string;
computedWeightGrams: string;
flatRialCharge: string;
/**
* The product and variant this line is for, included by the server.
*
* Optional because an order fetched by an older client — or a cached response
* from before the server included it — has no such field. The apps fall back
* to a plain label rather than showing nothing.
*
* It used to be looked up in the browser against the whole catalogue, which
* both downloaded ~16k products for a few row labels and rendered blank for a
* product that had since left the storefront.
*/
productVariant?: {
id: string;
title: string;
product: { id: string; title: string; images: Array<{ url: string }> };
} | null;
}
export interface OrderDetail {
@@ -304,7 +397,53 @@ function iamAppUrl(path: string) {
}
export const api = {
/**
* The WHOLE active catalogue in one response.
*
* The real catalogue reaches ~16k products, so prefer the paged/targeted
* calls below; this stays for the screens that genuinely work over the full
* list and is what the route answers when asked for nothing in particular.
*/
listProducts: () => request<ProductSummary[]>('/catalog/products'),
/** One page of the storefront, filtered and counted server-side. */
listProductsPaged: (query: ProductQuery = {}) =>
request<ProductPage>(`/catalog/products${toQueryString(query)}`),
/**
* One product, instead of downloading the catalogue to `find()` it.
* 404s for a product that is not on the storefront (inactive, or no photo).
*/
getProduct: (id: string) => request<ProductSummary>(`/catalog/products/${encodeURIComponent(id)}`),
/**
* Specific products by id — the cart, favourites, order items.
*
* Chunked because the route caps `ids` at 100 and drops the rest: a caller
* that asked for more would silently get a partial answer, and callers treat
* "missing from the answer" as "no longer on the storefront". Favourites
* already run to the high hundreds in the imported data (874 rows, FAV-01),
* so this is a live case, not a theoretical one.
*/
getProductsByIds: async (ids: string[]): Promise<ProductSummary[]> => {
const unique = [...new Set(ids)].filter(Boolean);
if (unique.length === 0) return [];
const chunks = Array.from({ length: Math.ceil(unique.length / ID_CHUNK) }, (_, i) =>
unique.slice(i * ID_CHUNK, (i + 1) * ID_CHUNK),
);
const pages = await Promise.all(
chunks.map((chunk) =>
request<ProductPage>(`/catalog/products?ids=${chunk.map(encodeURIComponent).join(',')}`),
),
);
return pages.flatMap((p) => p.rows);
},
/**
* The filter sheet's options (categories, brands, collections, gram range),
* which used to be derived by scanning the whole catalogue in the browser.
*/
getCatalogFacets: () => request<CatalogFacets>('/catalog/products/facets'),
/**
* Step 1 of login — ports henza_server ApiMobileController::userAuth.
* Always resolves `{ sent: true }`, even for an unregistered number, so the
@@ -403,10 +542,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,
});
@@ -0,0 +1,113 @@
<!--
«در حال مشاهده به‌عنوان …» — shown while a sales expert is working inside one
of their customers' accounts. Same logic as user-app's copy; the colours are
this app's own.
NOT in the reference, and added on purpose. There, impersonation was invisible
once the token had been swapped (myDataStore.ts:163): the only way an expert
could tell whose account they were in was to notice the data looked wrong.
Placing an order on the wrong customer's account — their gold debt, their
ledger — was a single tap away with nothing to catch it.
It is also the exit. The reference's only way out was the logout button, which
dropped the expert's own session too (Dashboard.vue:781-789).
-->
<template>
<div v-if="session.actingAs" class="aab" role="status">
<span class="aab__dot" aria-hidden="true" />
<span class="aab__text">
در حال مشاهده به‌عنوان <strong>{{ session.actingAs.name || 'مشتری' }}</strong>
</span>
<button type="button" class="aab__exit" :disabled="leaving" @click="leave">
{{ leaving ? '…' : 'خروج' }}
</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useSessionStore } from '../../stores/session'
import { useCartStore } from '../../stores/cartStore'
import { toast } from '../../composables/useToast'
const session = useSessionStore()
const cart = useCartStore()
const router = useRouter()
const leaving = ref(false)
/**
* Back to the expert's own account. The cart is cleared in this direction too:
* a basket built inside the customer's account must not follow the expert out
* and land on their own order.
*/
async function leave() {
leaving.value = true
try {
cart.clear()
session.setActingAs(null)
await router.push({ name: 'home' })
toast.info('به حساب خودتان بازگشتید')
} finally {
leaving.value = false
}
}
</script>
<style scoped lang="less">
.aab {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 2000;
display: flex;
align-items: center;
gap: 8px;
padding: 7px 16px;
/* Deliberately not a brand colour: this is a warning strip, and it has to be
noticeable at a glance to do its job. */
background: #8d6a46;
color: #fff;
font-size: 12px;
font-weight: 600;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
}
.aab__dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #ffd9a0;
flex: 0 0 auto;
}
.aab__text {
flex: 1 1 auto;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
strong {
font-weight: 800;
}
}
.aab__exit {
flex: 0 0 auto;
border: 1px solid rgba(255, 255, 255, 0.55);
background: transparent;
color: #fff;
border-radius: 8px;
padding: 3px 12px;
font-family: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
&:disabled {
opacity: 0.6;
cursor: default;
}
}
</style>
@@ -3,9 +3,10 @@
language (see components/home/* and HomeView). Ported originally from
legacy henza_pwa/src/components/product/orderItem.vue.
Adapted: product/variant title comes from a client-side lookup (see
useOrderItemProduct.ts) since the real order-items response only carries
productVariantId.
The product/variant title and photo come WITH the order (the server includes
each item's variant and product). They used to be looked up in the browser
against the whole catalogue, which downloaded ~16k products to label a few
rows and left the row blank for a product that had since left the storefront.
DROPPED the "توضیحات: -" row the previous version rendered: our OrderItem
schema has no note field (legacy's per-item note was a real column there;
@@ -46,18 +47,17 @@
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { computed } from 'vue'
import Icon from '../icon/Icon.vue'
import { useOrderItemProduct, type VariantLookup } from '../../composables/useOrderItemProduct'
import { orderItemLookup } from '../../composables/useOrderItemProduct'
import type { OrderItemDetail } from '../../api/client'
const props = defineProps<{ value: OrderItemDetail }>()
const { lookup: lookupVariant } = useOrderItemProduct()
const lookup = ref<VariantLookup | undefined>()
onMounted(async () => {
lookup.value = await lookupVariant(props.value.productVariantId)
})
// The server sends these with the order, so there is nothing to fetch and
// nothing to wait for — the row renders complete on its first frame instead of
// filling in after a catalogue download.
const lookup = computed(() => orderItemLookup(props.value))
</script>
<style scoped lang="less">
+35 -4
View File
@@ -30,13 +30,24 @@
<script setup lang="ts">
import { useRouter } from 'vue-router'
import Icon from '../icon/Icon.vue'
import { useNavStore } from '../../stores/navStore'
const props = withDefaults(
defineProps<{
title: string
/** Show the back button. */
back?: boolean
/** Route name to go to instead of history.back(). */
/**
* Where to go when there is nothing to go back to — a direct link, a
* refresh, or a previous entry the router guard would bounce us out of.
*
* A FALLBACK, not a destination. It used to be the destination, which is
* why back from the login page always landed on home even when the person
* had arrived from their profile: every screen pushed a fixed route name
* and the real history was ignored (inherited from the reference, which
* did the same — `$router.push({name:'userPage::hasSubRoute'})` in each
* component's back arrow).
*/
backTo?: string
/** Custom back handler; wins over backTo and history (e.g. a multi-step form stepping back). */
backAction?: () => void
@@ -45,11 +56,31 @@ const props = withDefaults(
)
const router = useRouter()
const nav = useNavStore()
function onBack() {
if (props.backAction) props.backAction()
else if (props.backTo) router.push({ name: props.backTo })
else router.back()
// An explicit handler still wins: a multi-step form stepping back inside
// itself is not a history move at all.
if (props.backAction) {
props.backAction()
return
}
// Prefer true history: it is the only thing that knows where the person
// actually came from.
//
// `canGoBack` is tracked by the router (navStore), not read off
// `history.length`, which counts entries from before this app was opened and
// so cannot tell "arrived from the profile" from "opened this link in a new
// tab".
if (nav.canGoBack) {
router.back()
return
}
if (props.backTo) {
router.push({ name: props.backTo })
return
}
router.push({ name: 'home' })
}
</script>
@@ -1,16 +1,37 @@
// The real GET /customers/:id/orders endpoint returns OrderItem rows with
// only `productVariantId` (no nested product/variant title) — this joins
// against the shared catalogue (stores/catalogStore.ts) client-side rather
// than touching apps/api to add an include.
import { useCatalogStore, type VariantLookup } from '../stores/catalogStore'
// The product and variant titles shown on one line of an order.
//
// These now arrive WITH the order: GET customer/me/orders includes each item's
// variant, its product and the product's first image.
//
// Before that, this joined against the shared catalogue in the browser. Two
// problems, both fixed by the include: it fetched the whole catalogue (~16k
// products in the real data) to label a few rows, and a product that had since
// left the storefront was absent from the catalogue, so the row rendered blank —
// precisely for old orders, which is where order history matters most.
import type { OrderItemDetail } from '../api/client'
export type { VariantLookup }
export interface VariantLookup {
productTitle: string
variantTitle: string
imageUrl?: string
}
/** Reads the labels off the item itself; no request, no catalogue. */
export function orderItemLookup(item: OrderItemDetail): VariantLookup | undefined {
const variant = item.productVariant
if (!variant) return undefined
return {
productTitle: variant.product.title,
variantTitle: variant.title,
imageUrl: variant.product.images[0]?.url,
}
}
/**
* Kept as a composable so the call sites read unchanged. Synchronous now —
* `lookup` is resolved from the item, so it returns a value rather than a
* promise, and callers no longer need to await anything on mount.
*/
export function useOrderItemProduct() {
const catalog = useCatalogStore()
const lookup = async (productVariantId: string): Promise<VariantLookup | undefined> => {
if (!catalog.loaded) await catalog.load()
return catalog.variantLookup.get(productVariantId)
}
return { lookup }
return { lookup: orderItemLookup }
}
@@ -1,26 +1,31 @@
// Adapted from legacy singleProduct.vue's own fetch (GET /product/:id).
// The new API has no single-product-detail endpoint (only GET
// /catalog/products, the flat list), so the product is found in the shared
// catalogue (stores/catalogStore.ts). When the catalogue is already cached,
// opening a product costs no request at all.
//
// Reads ONE product from GET /catalog/products/:id.
//
// It used to fetch the shared catalogue and `find()` the row in it, because the
// API had no single-product route. With the real catalogue reaching ~16k
// products that meant opening any product could download all of them, so the
// route now exists (plan step 2) and this is the first caller moved onto it.
//
// `initial` seeds the page with the ProductSummary the tapped card already
// holds — the same shape, from the same endpoint — so the detail view renders
// complete on its first frame instead of mounting blank and jumping when the
// fetch lands. The lookup still runs, silently, and only replaces the product
// if the catalogue's copy actually differs (stock moved since the list loaded).
// fetch lands. The read still runs, silently, and only replaces the product if
// the server's copy actually differs (stock moved since the list loaded).
//
// The silent refresh waits until the opening morph (ProductMorph.vue, ≤420ms)
// is over: if the catalogue has to come from the server, parsing it — or
// swapping the product and re-rendering — mid-animation drops frames.
// is over: swapping the product and re-rendering mid-animation drops frames.
import { ref } from 'vue'
import type { ProductSummary } from '../api/client'
import { useCatalogStore } from '../stores/catalogStore'
import { api, UnauthorizedError, type ProductSummary } from '../api/client'
const SEEDED_REFRESH_DELAY_MS = 600
/** A 404 from the API client, which throws `API <path> failed (404): …`. */
function isNotFound(e: unknown): boolean {
return e instanceof Error && !(e instanceof UnauthorizedError) && /\(404\)/.test(e.message)
}
export function useProductDetail(id: string, initial?: ProductSummary | null) {
const catalog = useCatalogStore()
const loading = ref(false)
const flag = ref(Boolean(initial))
const notFound = ref(false)
@@ -31,17 +36,30 @@ export function useProductDetail(id: string, initial?: ProductSummary | null) {
if (seeded) await new Promise((resolve) => setTimeout(resolve, SEEDED_REFRESH_DELAY_MS))
else loading.value = true
try {
const products = await catalog.load()
const found = products.find((p) => p.id === id) ?? null
const found = await api.getProduct(id)
if (seeded) {
if (found && JSON.stringify(found) !== JSON.stringify(productRef.value)) productRef.value = found
if (JSON.stringify(found) !== JSON.stringify(productRef.value)) productRef.value = found
} else {
productRef.value = found
notFound.value = !found
}
flag.value = true
} catch (e) {
console.log(e)
// Only a real 404 means "no such product". Anything else — offline, a
// 500 — must not render the "not found" page: before this route existed
// a failed catalogue fetch left `notFound` false, and that is still the
// right answer, because the product may well exist.
if (isNotFound(e)) {
if (!seeded) {
productRef.value = null
notFound.value = true
}
// Seeded and now 404: the product was pulled from the storefront while
// the page was open. The card's copy stays on screen rather than
// blanking under the person mid-read; the cart refuses it at checkout.
} else {
console.log(e)
}
flag.value = true
} finally {
loading.value = false
}
+4 -1
View File
@@ -42,7 +42,10 @@ app.use(router);
setUnauthorizedHandler(() => {
useSessionStore().logout();
if (router.currentRoute.value.name !== 'login') {
void router.push({ name: 'login' });
// `replace`: the page whose request just failed is behind a dead session,
// so leaving it in history only gives the person a back button that returns
// them to it and bounces straight back here.
void router.replace({ name: 'login' });
}
});
// Ported from legacy main.ts:32-46 — Vector.svg is both the while-loading and
+12
View File
@@ -4,6 +4,7 @@ import { useNavStore } from '../stores/navStore';
import { useTransitionStore } from '../stores/transitionStore';
import { api } from '../api/client';
import { useCachedReads } from '../api/cachedReads';
import { toast } from '../composables/useToast';
// Legacy lazy-loaded every route component (`component: () => import(...)`) so
// the initial bundle only carries the entry route. Matched here.
@@ -131,7 +132,13 @@ router.beforeEach(async (to) => {
if (to.name === 'login' && session.isLoggedIn) {
return { name: 'home' };
}
// D3 — see the same guard in user-app's router for the full reasoning.
// Legacy showed the guest «ابتدا وارد شوید» (henza_pwa/src/router/index.ts:259)
// and the target redirected silently. The owner kept the target's `redirect`
// so signing in returns the guest to the page they wanted, which legacy did
// not do — «عمداً تکرار نشد — D3/الف».
if (to.meta.requiresAuth && !session.isLoggedIn) {
toast.info('ابتدا وارد شوید');
return { name: 'login', query: { redirect: to.fullPath } };
}
@@ -180,6 +187,11 @@ router.afterEach((to) => {
const nav = useNavStore();
const transition = useTransitionStore();
// Remembers where in the browser's history this app instance started, which
// is what PageBar's back button compares against before choosing between a
// real history-back and its fallback route.
nav.noteFirstNavigation();
transition.setTransitionFlag(false);
transition.setTransitionEnded(false);
setTimeout(() => {
+25 -10
View File
@@ -1,10 +1,8 @@
// Ported from legacy henza_pwa/src/store/cartStore.ts, adapted to our string
// ids and flat (non-paginated) product list. Persisted the same way (a single
// localStorage key), just via Pinia's own state instead of @vueuse's
// useStorage wrapping a hand-rolled class.
// ids. Persisted the same way (a single localStorage key), just via Pinia's own
// state instead of @vueuse's useStorage wrapping a hand-rolled class.
import { defineStore } from 'pinia'
import type { ProductSummary } from '../api/client'
import { useCatalogStore } from './catalogStore'
import { api, type ProductSummary } from '../api/client'
export interface CartItem {
pid: string
@@ -34,16 +32,33 @@ export const useCartStore = defineStore('cart', {
items: loadFromStorage() as CartItem[],
}),
actions: {
// Re-syncs cart entries against fresh product data (e.g. price/weight
// changes since the item was added), dropping entries whose
// product/variant no longer exists — same intent as legacy's init().
/**
* Re-syncs cart entries against fresh product data (e.g. price/weight
* changes since the item was added), dropping entries whose
* product/variant no longer exists — same intent as legacy's init().
*
* Asks for exactly the products in the cart. It used to load the entire
* catalogue to look up two or three of them, which with ~16k products meant
* downloading all of them every time the app opened.
*
* A failed request leaves the cart alone: it is the person's own data, held
* in localStorage, and dropping items because the network blinked would be
* worse than showing a slightly stale price.
*/
async init(force = false) {
void force // kept for callers; every call now goes to the server anyway
if (this.items.length === 0) return
try {
const products = await useCatalogStore().load(force)
const ids = [...new Set(this.items.map((i) => i.pid))]
const products = await api.getProductsByIds(ids)
const byId = new Map(products.map((p) => [p.id, p]))
const refreshed: CartItem[] = []
for (const item of this.items) {
const product = products.find((p) => p.id === item.pid)
const product = byId.get(item.pid)
const variant = product?.variants.find((v) => v.id === item.vid)
// A product the server no longer lists (deactivated, or its photo was
// removed) comes back missing, which is the same signal the catalogue
// lookup gave before: drop the line.
if (product && variant) {
refreshed.push({ ...item, product })
}
+6 -20
View File
@@ -9,12 +9,6 @@ import { computed, ref, shallowRef } from 'vue'
import { api, type ProductSummary } from '../api/client'
import { KEYS, useQueryCache } from './queryCache'
export interface VariantLookup {
productTitle: string
variantTitle: string
imageUrl?: string
}
export const useCatalogStore = defineStore('catalog', () => {
const cache = useQueryCache()
// shallowRef: the list is replaced wholesale, never mutated in place.
@@ -31,19 +25,11 @@ export const useCatalogStore = defineStore('catalog', () => {
return [...seen.values()]
})
const variantLookup = computed(() => {
const map = new Map<string, VariantLookup>()
for (const product of products.value) {
for (const variant of product.variants) {
map.set(variant.id, {
productTitle: product.title,
variantTitle: variant.title,
imageUrl: product.images[0]?.url,
})
}
}
return map
})
// `variantLookup` lived here: a variantId -> {productTitle, variantTitle,
// imageUrl} map built over the whole catalogue, used only to label order
// rows. The server now includes those fields with the order itself
// (customers.service.ts getOrders), so the map is gone rather than left as a
// reason to keep loading the full catalogue.
async function load(force = false): Promise<ProductSummary[]> {
const list = await cache.fetch(KEYS.catalog, api.listProducts, { force })
@@ -61,5 +47,5 @@ export const useCatalogStore = defineStore('catalog', () => {
cache.invalidate(KEYS.catalog)
}
return { products, loaded, categories, variantLookup, load, byId, invalidate }
return { products, loaded, categories, load, byId, invalidate }
})
+15 -8
View File
@@ -17,8 +17,12 @@
// HomeSlider's popup/link/discount click handling works unchanged.
//
// Not ported (no backend): promotionList, ignoreList, priceList, isLoaded.
//
// `isLoaded` — «عمداً تکرار نشد — D3/ب» (owner, 2026-10-12). Legacy used it as a
// router guard against a bootstrap request this app does not have; see the same
// note in user-app's configStore for the full reasoning (D4).
import { defineStore } from 'pinia'
import { useCatalogStore } from './catalogStore'
import { api } from '../api/client'
import shippingArt from '../assets/img/shipping-and-delivery.png'
import competitionArt from '../assets/img/sports-and-competition.png'
import brandArt from '../assets/img/montzar-logo.png'
@@ -68,15 +72,18 @@ export const useConfigStore = defineStore('config', {
this.cats = cats
},
// Legacy's store.init() fanned out to /config, /promotion, /ignore, /price.
// Here the only live source is the product catalogue, from which the real
// category list is derived.
// The catalogue comes from catalogStore, so calling this next to another
// catalogue read costs no second request.
// Here the live source is the catalogue's own category list.
//
// Reads GET /catalog/products/facets, a small aggregate. It used to load the
// whole catalogue and derive the categories from it in the browser — up to
// ~16k products fetched to populate one row of chips, and wrong beyond the
// first page once the list is paged, because a category whose products all
// sit further down would vanish from the home screen.
async init(force = false) {
void force // the facets are a small read; there is no cached copy to bypass
try {
const catalog = useCatalogStore()
await catalog.load(force)
this.cats = catalog.categories.map((c) => ({ ...c, icon: { image: brandArt } }))
const { categories } = await api.getCatalogFacets()
this.cats = categories.map((c) => ({ ...c, icon: { image: brandArt } }))
this.loaded = true
} catch (e) {
console.log(e)
@@ -21,10 +21,15 @@ export const useFavoritesStore = defineStore('favorites', () => {
}
}
// Loaded for whoever is signed in, cleared on logout — never another user's list.
// Loaded for whoever is signed in, cleared on logout — never another user's
// list. `actingAs` is watched alongside the token because «ورود به حساب
// مشتری» changes whose favourites these are WITHOUT changing the token: a
// sales expert entering a customer's account would otherwise see their own
// hearts on the customer's products, and tapping one would write to the
// customer's list.
watch(
() => session.token,
(token) => {
() => [session.token, session.actingAs?.id ?? null] as const,
([token]) => {
ids.value = []
if (token) void load()
},
+38
View File
@@ -18,6 +18,18 @@ interface NavState {
showNav: boolean
// legacy passes `undefined` to clear the transition (router/index.ts:270)
pageTransition: string | undefined
/**
* The history index this app started at, or null before the first
* navigation.
*
* Answers "is there anywhere inside this app to go back to?", which
* `history.length` cannot: it also counts entries from before the app was
* opened, so it says yes for a link opened in a fresh tab and the back button
* would leave the app. Comparing the CURRENT history position against the one
* we started at is direction-proof — it stays correct however many times the
* person goes back and forward, where a plain counter would only ever grow.
*/
entryIndex: number | null
}
export const useNavStore = defineStore('nav', {
@@ -32,8 +44,34 @@ export const useNavStore = defineStore('nav', {
activeLink: 1,
showNav: true,
pageTransition: 'right',
entryIndex: null,
}),
getters: {
/**
* True when `router.back()` lands somewhere inside this app rather than on
* whatever the person was looking at before they opened it.
*/
canGoBack: (state) => {
if (state.entryIndex === null) return false
const current = window.history.state?.position
// `position` is written by vue-router on every entry it creates. If it is
// missing (a hand-written history entry, an old browser), assume we must
// not leave the app and let the caller fall back.
return typeof current === 'number' ? current > state.entryIndex : false
},
},
actions: {
/**
* Records where in history this app instance began. Called once, on the
* first navigation — every later entry sits above it, so anything above is
* ours to go back through.
*/
noteFirstNavigation() {
if (this.entryIndex !== null) return
const position = window.history.state?.position
this.entryIndex = typeof position === 'number' ? position : 0
},
setNavVisibility(data: boolean) {
this.showNav = data
},
+27 -4
View File
@@ -9,14 +9,32 @@
// - `force` → always asks the server (pull-to-refresh, the
// profile tab's balance, reaching the end of a list)
//
// Entries never expire on a timer: data changes when the user asks for it or
// when a write here makes it wrong, and those writes call `invalidate`.
// Entries never expire on a timer, deliberately (owner ruling 2026-10-12: «هربار
// با رفتن به اون صفحه اون مقادیر مورد نیاز رو درخواست بزنه … هم سربار برای سرور
// نداره، هم درخواست الکی نمیخوره، هم دیتاها به‌روز میمونه»). A TTL guesses how
// long data stays true; entering a screen is the moment it actually matters.
//
// So the policy is:
//
// - a screen that shows server-owned data re-reads it with `force` when it is
// opened (`onMounted`, plus `onActivated` for the kept-alive views), while
// `peek` paints the previous copy instantly so the refresh is invisible;
// - the cached copy exists for that first paint and to collapse concurrent
// callers into one request, NOT to avoid asking again;
// - the catalogue is the exception: it is the whole product list in one
// response, changes when an admin edits it, and is already invalidated by
// pull-to-refresh and by placing an order.
//
// `force` is what makes this work for anything changed OUTSIDE the app — an
// order's status, a ledger entry, the gold price. Nothing here can know those
// changed, so not asking means never seeing them.
//
// Entries live in a plain Map, not reactive state: the catalogue is large and
// making it deeply reactive would cost more than the request it saves.
//
// Keys under `me:` hold one customer's data. They are dropped whenever the
// session token changes, so the next user never sees the previous one's data.
// session token changes — or the act-as target does, which changes whose data
// they hold without changing the token — so one user never sees another's.
import { defineStore } from 'pinia'
import { watch } from 'vue'
import { useSessionStore } from './session'
@@ -91,8 +109,13 @@ export const useQueryCache = defineStore('queryCache', () => {
}
}
// The token changes when the user changes — and, with «ورود به حساب مشتری»,
// WHOSE data `me:` keys hold changes without the token changing at all. Both
// have to drop the cache, or a sales expert entering a customer's account
// would be shown their own profile, orders, balance and ledger from before
// the switch.
watch(
() => session.token,
() => [session.token, session.actingAs?.id ?? null],
() => clearUserScoped(),
)
+58
View File
@@ -7,6 +7,33 @@ const MOBILE_KEY = 'gold-bank:mobile';
const LEGACY_FLAG_KEY = 'appToken';
/** D21 — cached so the expert menu entries render before whoami resolves. */
const EXPERT_KEY = 'gold-bank:isSalesExpert';
/**
* «ورود به حساب مشتری» — which of the expert's customers they are working
* inside, if any.
*
* Deliberately `sessionStorage`, not `localStorage`: closing the tab ends the
* impersonation. The reference kept the customer's own permanent api_token in
* localStorage (myDataStore.ts:163), so it survived restarts indefinitely and
* outlived the expert's employment. Here it is only a hint anyway — the server
* re-checks on every request that this customer is actually theirs.
*/
const ACTING_AS_KEY = 'gold-bank:actingAs';
export interface ActingAs {
id: string;
name: string;
}
function readActingAs(): ActingAs | null {
try {
const raw = sessionStorage.getItem(ACTING_AS_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as ActingAs;
return parsed && typeof parsed.id === 'string' ? parsed : null;
} catch {
return null;
}
}
/**
* The logged-in customer's session.
@@ -36,6 +63,14 @@ export const useSessionStore = defineStore('session', {
* an ordinary customer, so flipping this in devtools reveals nothing.
*/
isSalesExpert: localStorage.getItem(EXPERT_KEY) === '1',
/**
* The customer this expert is currently working as, or null.
*
* Display and request-header state only — never an authorisation claim.
* Putting another customer's id here gets a 403 from the server, which
* scopes the lookup to `referredByAgentId` on every single request.
*/
actingAs: readActingAs() as ActingAs | null,
}),
getters: {
/** Authenticated means holding a token, not merely knowing an id. */
@@ -58,6 +93,23 @@ export const useSessionStore = defineStore('session', {
if (value) localStorage.setItem(EXPERT_KEY, '1');
else localStorage.removeItem(EXPERT_KEY);
},
/**
* Enter or leave a customer's account. `null` returns the expert to their
* own. The reference did the same through `toggleActiveUser`
* (myDataStore.ts:159-169), which swapped the token; nothing is swapped
* here — the API client just starts naming this customer in a header.
*/
setActingAs(value: ActingAs | null) {
this.actingAs = value;
try {
if (value) sessionStorage.setItem(ACTING_AS_KEY, JSON.stringify(value));
else sessionStorage.removeItem(ACTING_AS_KEY);
} catch {
// A private window with storage blocked: the in-memory value still
// drives this tab, which is all the feature needs.
}
},
/**
* Clears everything. Called on explicit logout and by the API client when a
* request comes back 401 — an expired or revoked token must not leave stale
@@ -68,6 +120,12 @@ export const useSessionStore = defineStore('session', {
this.customerId = null;
this.mobile = null;
this.isSalesExpert = false;
this.actingAs = null;
try {
sessionStorage.removeItem(ACTING_AS_KEY);
} catch {
/* storage blocked; the in-memory reset above is what matters */
}
localStorage.removeItem(EXPERT_KEY);
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(CUSTOMER_ID_KEY);
@@ -22,8 +22,12 @@ export const useWageQuoteStore = defineStore('wageQuotes', () => {
let timer: ReturnType<typeof setTimeout> | null = null
// A different customer has a different percent: never reuse another's quotes.
// That includes «ورود به حساب مشتری», which swaps WHICH customer we are
// quoting for without swapping the token — so a sales expert would otherwise
// see their own making charge on the customer's products, and the figure on
// screen would not be the one the order is placed at.
watch(
() => session.token,
() => [session.token, session.actingAs?.id ?? null],
() => {
quotes.value = {}
pending.clear()
+38 -3
View File
@@ -80,7 +80,7 @@
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue'
import { computed, nextTick, onActivated, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Loading, PullRefresh } from 'vant'
import Icon from '../components/icon/Icon.vue'
@@ -215,14 +215,23 @@ function goNewest() {
// The three reads are independent, so they run side by side. Each one is
// cached until pull-to-refresh asks the server again.
async function loadData(force = false) {
const [catalogResult, priceResult, slidesResult] = await Promise.allSettled([
// memory.init() reads the same cached catalogue, so this is one request.
const [catalogResult, catsResult, priceResult, slidesResult] = await Promise.allSettled([
// The home rails read `catalog.products`, so the catalogue is loaded
// explicitly. It used to come in as a side effect of `memory.init()`, which
// now reads the small facets endpoint instead of the whole catalogue — so
// without this call the home screen would render empty rails.
//
// Still the unpaged list: the rails slice it locally («جدیدترین», per
// category). Moving them onto paged reads is step 4 of
// docs/CATALOG-PAGINATION-PLAN.md.
catalog.load(force),
memory.init(force),
reads.goldPrice({ force }),
reads.homeSlider({ force }),
])
if (catalogResult.status === 'rejected') console.log(catalogResult.reason)
if (catsResult.status === 'rejected') console.log(catsResult.reason)
goldPrice.value = priceResult.status === 'fulfilled' ? priceResult.value : null
// No admin slides configured, or the endpoint failed — the category-derived
// hero covers this silently, same as before this existed.
@@ -247,6 +256,32 @@ onMounted(async () => {
hasRevealed = true
})
})
/**
* Owner ruling 2026-10-12: re-read on entering a screen rather than caching
* with a lifetime. This view is kept alive, so without this the gold price was
* fetched once per app launch and then never again until pull-to-refresh — on
* the screen that shows it most prominently.
*
* Only the PRICE is re-read, not the catalogue or the slides: the catalogue is
* the whole active product list in one response, and re-fetching it on every
* tab switch is exactly the needless load the ruling is meant to avoid. It
* changes when an admin edits it, not minute to minute, and pull-to-refresh and
* placing an order both already invalidate it.
*/
let activatedOnce = false
onActivated(async () => {
if (!activatedOnce) {
activatedOnce = true
return
}
try {
goldPrice.value = await reads.goldPrice({ force: true })
} catch (e) {
// Keep the figure already on screen rather than blanking it.
console.log(e)
}
})
</script>
<style scoped lang="less">
@@ -14,15 +14,18 @@
scope is commented out at ApiMobileController.php:187, so every referred
customer appears whatever their state (D4: replicate, don't "fix")
Deliberately NOT ported — two things, both recorded in D21:
1. `changeUser` / act-as. The reference minted an api_token for each listed
customer (ApiMobileController.php:197-201) so the agent could act AS them.
That is a session-hijack primitive; every session here derives from the
caller's own token, so tapping a card opens their details instead.
2. The activate/deactivate toggle and the edit button, which posted to
`/customer/toggle-active` and the customer form. Those are admin-panel
operations here, and adding a write path to the app during a delivery is
not worth the risk. The state is shown, read-only.
`changeUser` / act-as IS ported — see `enterAccount` below and D29. It was
previously left out as a session-hijack primitive (D21); the owner asked for
it back, so the capability is the reference's but the mechanism is not. The
reference minted a permanent api_token per customer
(ApiMobileController.php:197-201) and swapped the bearer token; here the
expert keeps their own token and the client names the customer in a header,
which the server re-authorises on every request.
Still deliberately NOT ported (D21):
- The activate/deactivate toggle and the edit button, which posted to
`/customer/toggle-active` and the customer form. Those are admin-panel
operations here. The state is shown, read-only.
Scope is the server's: `referredByAgentId` = this expert, from the token.
-->
@@ -127,6 +130,9 @@
<dd>{{ active.active === 1 ? 'فعال' : 'غیرفعال' }}</dd>
</div>
</dl>
<button type="button" class="cch__enter" :disabled="entering" @click="enterAccount(active)">
{{ entering ? 'در حال ورود…' : 'ورود به حساب این مشتری' }}
</button>
<button type="button" class="cch__close" @click="detailOpen = false">بستن</button>
</div>
</Drawer>
@@ -135,6 +141,7 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Drawer } from 'ant-design-vue'
import { Loading, PullRefresh } from 'vant'
import Icon from '../../components/icon/Icon.vue'
@@ -142,6 +149,14 @@ import PageBar from '../../components/ui/PageBar.vue'
import Spinner from '../../components/Spinner.vue'
import SearchInput from '../../components/search/SearchInput.vue'
import { api, type ExpertCustomer } from '../../api/client'
import { useSessionStore } from '../../stores/session'
import { useCartStore } from '../../stores/cartStore'
import { toast } from '../../composables/useToast'
const router = useRouter()
const session = useSessionStore()
const cart = useCartStore()
const entering = ref(false)
const rows = ref<ExpertCustomer[]>([])
const loading = ref(false)
@@ -190,6 +205,30 @@ function openDetail(item: ExpertCustomer) {
detailOpen.value = true
}
/**
* «ورود به حساب مشتری» — the reference's `changeUser`
* (customerChoice.vue:155-167). There it swapped the bearer token for the
* customer's own; here the session simply records who we are acting as and the
* API client names them in a header, which the server authorises per request.
*
* The cart is cleared in both directions: it lives in localStorage, so without
* this the expert's own basket would follow them into the customer's account
* and end up on the customer's order.
*/
async function enterAccount(item: ExpertCustomer) {
entering.value = true
try {
cart.clear()
session.setActingAs({ id: item.id, name: item.name ?? item.fullName ?? item.mobile ?? '' })
detailOpen.value = false
// Same destination as the reference, which returned to the dashboard.
await router.push({ name: 'userPage::hasSubRoute' })
toast.success(`وارد حساب ${item.name ?? ''} شدید`)
} finally {
entering.value = false
}
}
onMounted(load)
</script>
@@ -347,7 +386,7 @@ onMounted(load)
font-weight: 600;
}
.cch__close {
.cch__enter {
margin-top: 18px;
width: 100%;
padding: 13px;
@@ -359,5 +398,25 @@ onMounted(load)
font-size: 14px;
font-weight: 700;
cursor: pointer;
&:disabled {
opacity: 0.6;
cursor: default;
}
}
/* Secondary now that "enter the account" is the primary action here. */
.cch__close {
margin-top: 10px;
width: 100%;
padding: 13px;
border: 1px solid fade(@ink, 35%);
border-radius: 14px;
background: transparent;
color: @ink;
font-family: inherit;
font-size: 14px;
font-weight: 700;
cursor: pointer;
}
</style>
@@ -122,10 +122,16 @@ async function submit() {
}
}
/** The reference sent the user home after the dialog (:175-177). */
/**
* The reference sent the user home after the dialog (:175-177).
*
* `replace`: once the documents are in, this route is no longer reachable — the
* router guard redirects it home — so leaving it in history gives a back button
* that appears to do nothing.
*/
function finish() {
done.value = false
router.push({ name: 'home' })
router.replace({ name: 'home' })
}
</script>
@@ -308,7 +308,7 @@ async function logOut() {
router.push({ name: 'home' })
}
async function loadDashboard(force = false) {
async function loadDashboard() {
// Not wrapped before: a failure here (expired token, network blip) left
// the exception uncaught, so onRefresh's refreshing.value = false never
// ran and PullRefresh stayed stuck in its loading state — a working pull
@@ -317,7 +317,12 @@ async function loadDashboard(force = false) {
// The balance on this tab is the one figure read fresh on every visit;
// the cached copy only fills the screen until it arrives.
session.isLoggedIn ? reads.me({ force: true }) : Promise.resolve(null),
reads.goldPrice({ force }),
// Also forced, per the owner's 2026-10-12 ruling: both figures on this tab
// are read fresh on every visit. This used to follow a `force` parameter
// that only pull-to-refresh set, so the price here could be as old as the
// app launch. With both reads always fresh the parameter had nothing left
// to control, so it is gone.
reads.goldPrice({ force: true }),
])
if (me.status === 'fulfilled') customer.value = me.value
else console.log(me.reason)
@@ -325,7 +330,7 @@ async function loadDashboard(force = false) {
}
async function onRefresh() {
await loadDashboard(true)
await loadDashboard()
refreshing.value = false
}
@@ -3,11 +3,14 @@
restyled into the redesigned design language (see components/home/* and
HomeView).
Real, not stubbed: favorites are the local favoritesStore (per-device, no
backend persistence — see favoritesStore.ts from an earlier batch), filtered
against the real product catalog client-side. No pagination — the whole
catalog is fetched once (same "small catalog" approach as everywhere else).
That logic is carried over unchanged; only the chrome and the card change.
Favourites are server-side (FAV-01: GET/POST customer/me/favorites), and the
products behind them are fetched BY ID — the saved ids go straight to
`?ids=…`, one request for the lot.
It used to fetch the whole catalogue and filter it in the browser, which with
~16k products meant downloading all of them to show a handful. It was also
wrong beyond the first page once paging existed: a favourite outside the
loaded slice would simply not appear.
-->
<template>
<div class="favs">
@@ -35,7 +38,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import Icon from '../../components/icon/Icon.vue'
import PageBar from '../../components/ui/PageBar.vue'
@@ -43,26 +46,41 @@ import Spinner from '../../components/Spinner.vue'
import SectionHead from '../../components/home/SectionHead.vue'
import ProductCard from '../../components/product/ProductCard.vue'
import { useFavoritesStore } from '../../stores/favoritesStore'
import { useCatalogStore } from '../../stores/catalogStore'
import { api, type ProductSummary } from '../../api/client'
const router = useRouter()
const favorites = useFavoritesStore()
const catalog = useCatalogStore()
const loading = ref(false)
const allProducts = computed(() => catalog.products)
const fetched = ref<ProductSummary[]>([])
const favoriteProducts = computed(() => allProducts.value.filter((p) => favorites.isFavorite(p.id)))
/**
* Still filtered against the store, so un-hearting a product removes its card
* at once without waiting for a refetch — the fetched list is the source of the
* product DATA, the store is the source of truth for what is saved.
*/
const favoriteProducts = computed(() => fetched.value.filter((p) => favorites.isFavorite(p.id)))
onMounted(async () => {
loading.value = !catalog.loaded
async function load() {
const ids = favorites.ids
if (ids.length === 0) {
fetched.value = []
return
}
loading.value = fetched.value.length === 0
try {
await catalog.load()
fetched.value = await api.getProductsByIds(ids)
} catch (e) {
console.log(e)
} finally {
loading.value = false
}
})
}
onMounted(load)
// The ids arrive from the server just after sign-in, and change when the person
// hearts something elsewhere in the app — both land here as a new id list.
watch(() => favorites.ids.join(','), load)
</script>
<style scoped lang="less">
+25 -16
View File
@@ -3,18 +3,18 @@
restyled into the redesigned design language (see components/home/* and
HomeView).
Per the earlier decision: OTP-based flow ported structurally, but the
SMS-send step is stubbed — no SMS provider exists. What's real vs stubbed,
all carried over unchanged from the previous version:
- Step 1 (mobile number) is checked against the REAL, already-existing
GET /api/customers endpoint (client-side match on `mobile`) — no fake
endpoint invented. A non-match shows legacy's own
"اطلاعات کاربری در سیستم وجود ندارد" text, not a new message.
- Step 2 (OTP code) is NOT verified — any 4-digit code is accepted, since
there is no real code to check against. On "verify", the session store
logs in as the matched real customer, so downstream features (balance,
ledger, favourites-as-logged-in) work against real seeded data.
- `token.fireBaseToken` doesn't exist in this port (Firebase deferred).
The flow is REAL. These notes used to say it was stubbed, and that stale text
misled a reader as recently as 2026-10-12, so it is corrected rather than
deleted:
- Step 1 posts the number to the server, which looks it up itself. It no
longer pulls the customer list into the client to match on `mobile` — that
was the login leak (D8). An unregistered number is answered with 404 and
the server's Persian message is shown; owner ruling 2026-10-12, because
the earlier opaque answer walked the person to the code box to wait for an
SMS that was never going to arrive.
- Step 2 IS verified by the server: hashed code, two-minute expiry, attempt
limit (D6). Accepting any 4-digit code is long gone.
- `token.fireBaseToken` still does not exist in this port (PUSH-01).
- `useOtpToken()` (WebOTP autofill) was already dead in legacy itself.
-->
<template>
@@ -140,9 +140,14 @@ const sendPhone = async () => {
body.defaultFocus = true
})
} catch (e: unknown) {
// 429 = the send throttle (too soon, or too many in the window). Its message
// is already Persian and user-facing, so show it rather than a generic one.
const text = e instanceof Error && /\(429\)/.test(e.message) ? extractServerMessage(e) : null
// Both of these carry a Persian, user-facing `message` from the server, so
// show it instead of a generic one:
// 429 — the send throttle (too soon, or too many in the window);
// 404 — the number is not registered (owner ruling 2026-10-12). Without
// this branch the person is told "خطا در ارسال کد"، which is the
// very confusion the 404 was added to remove.
const text =
e instanceof Error && /\((?:429|404)\)/.test(e.message) ? extractServerMessage(e) : null
toast.error(text ?? 'خطا در ارسال کد. لطفاً دوباره تلاش کنید.')
} finally {
body.loading = false
@@ -177,7 +182,11 @@ const sendToken = async (otpCode: string) => {
session.setSalesExpert(false)
}
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : undefined
await router.push(redirect ?? { name: 'home' })
// `replace`, not `push`: the login screen must not stay in history. Pushed,
// going back from the page they just reached returns them to the login box
// they have already used, which the guard above then bounces to home — so
// one tap of "back" loses their place entirely.
await router.replace(redirect ?? { name: 'home' })
toast.success('با موفقیت وارد شدید')
} catch (e: unknown) {
toast.error(
+28 -2
View File
@@ -147,7 +147,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onActivated, onMounted, reactive, ref } from 'vue'
import { Drawer } from 'ant-design-vue'
import { Loading, PullRefresh } from 'vant'
import Icon from '../../components/icon/Icon.vue'
@@ -232,7 +232,33 @@ async function onRefresh() {
refreshing.value = false
}
onMounted(() => loadOrders())
/**
* Owner ruling 2026-10-12: fetch what the screen needs each time it is opened,
* rather than caching it with a lifetime — «هربار با رفتن به اون صفحه اون
* مقادیر مورد نیاز رو درخواست بزنه، هم سربار برای سرور نداره، هم درخواست الکی
* نمیخوره، هم دیتاها به‌روز میمونه».
*
* `force` matters because an order's status changes on the ADMIN side — nothing
* in this app invalidates the cache when that happens, so without it a list
* fetched once was shown unchanged for the rest of the session.
*
* `onActivated` as well as `onMounted`: this view is in MasterLayout's
* keep-alive list, so it is mounted once and every later visit only activates
* it. With `onMounted` alone the second visit made no request at all.
*
* The cached copy still renders instantly (`peek` above) and `loading` only
* shows a spinner when there is nothing to show, so the refresh is invisible.
*
* `activatedOnce` guards the first visit, where Vue runs both hooks — the same
* shape DashboardView uses.
*/
onMounted(() => loadOrders(true))
let activatedOnce = false
onActivated(() => {
if (activatedOnce) void loadOrders(true)
activatedOnce = true
})
</script>
<style scoped lang="less">
@@ -142,11 +142,23 @@ const openEntry = (item: LedgerEntrySummary) => {
showPopUp.value = true
}
/**
* Owner ruling 2026-10-12: re-read on entering the screen.
*
* `force` is the point here. Ledger entries are written by the ACCOUNTING side,
* never by this app, so nothing here ever invalidated the cached copy — the
* first visit's list was shown for the rest of the session, and a document
* posted meanwhile stayed invisible until pull-to-refresh.
*
* This view is not in the keep-alive list, so `onMounted` runs on every visit
* and no `onActivated` is needed. The cached copy renders immediately (`peek`
* above), so the re-read is not visible as a loading state.
*/
onMounted(async () => {
if (!session.isLoggedIn) return
loading.value = reads.peek(KEYS.ledger) === undefined
try {
entries.value = await reads.myLedgerEntries()
entries.value = await reads.myLedgerEntries({ force: true })
} finally {
loading.value = false
}
+11 -1
View File
@@ -6,7 +6,8 @@
already commented out in legacy's own App.vue, so neither ran there either.
-->
<template>
<div>
<div :class="{ 'is-actingAs': Boolean(session.actingAs) }">
<ActingAsBar />
<component :is="getLayout" class="relative">
<router-view v-slot="{ Component, route }">
<keep-alive>
@@ -35,8 +36,11 @@ import FullPageLayout from './layout/FullPageLayout.vue'
import AppUpdateGate from './components/AppUpdateGate.vue'
import ToastHost from './components/ui/ToastHost.vue'
import ProductMorph from './components/product/ProductMorph.vue'
import ActingAsBar from './components/expert/ActingAsBar.vue'
import { useSessionStore } from './stores/session'
const router = useRouter()
const session = useSessionStore()
// Registers the service worker (offline, install). Updates are not applied
// here: AppUpdateGate shows what changed and applies them on the user's tap.
useRegisterSW()
@@ -54,6 +58,12 @@ body::-webkit-scrollbar {
display: none;
}
/* The act-as strip is fixed, so push everything down by its height while it is
up — otherwise it covers the top of each page, including sticky headers. */
.is-actingAs {
padding-top: 30px;
}
#app {
overflow: hidden;
direction: rtl !important;
+147 -1
View File
@@ -2,6 +2,10 @@ 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';
/** Must match MAX_IDS on the server's ListProductsDto. */
const ID_CHUNK = 100;
/**
* Called when the API rejects our token. Wired up in main.ts rather than
@@ -30,8 +34,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 +64,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,
},
});
@@ -118,6 +147,54 @@ export interface ProductSummary {
collections: Array<{ collectionId: string; collection: CollectionSummary }>;
}
/** Query for the paged storefront list; every field is optional. */
export interface ProductQuery {
page?: number;
limit?: number;
search?: string;
categoryId?: string;
brandId?: string;
collectionId?: string;
minGram?: number;
maxGram?: number;
sort?: 'newest' | 'oldest' | 'title';
}
/**
* One page of products. `total` is the size of the FILTERED set, not of the
* page, so it both drives the "N محصول" count and tells the list when to stop
* asking for more.
*/
export interface ProductPage {
rows: ProductSummary[];
total: number;
page: number;
limit: number;
}
/** Filter options, built from the catalogue server-side. */
export interface CatalogFacets {
categories: CategorySummary[];
brands: BrandSummary[];
collections: CollectionSummary[];
/** Decimal strings, like every other weight this API returns. */
gramRange: { min: string; max: string };
}
/**
* Builds `?a=1&b=2`, dropping anything unset so the server sees a bare request
* rather than `?search=undefined` — which would be a filter for the literal
* text "undefined".
*/
function toQueryString(query: object): string {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(query)) {
if (value !== undefined && value !== '') params.set(key, String(value));
}
const s = params.toString();
return s ? `?${s}` : '';
}
export interface LedgerEntrySummary {
id: string;
currency: string;
@@ -146,6 +223,22 @@ export interface OrderItemDetail {
discountPercentSnapshot: string;
computedWeightGrams: string;
flatRialCharge: string;
/**
* The product and variant this line is for, included by the server.
*
* Optional because an order fetched by an older client — or a cached response
* from before the server included it — has no such field. The apps fall back
* to a plain label rather than showing nothing.
*
* It used to be looked up in the browser against the whole catalogue, which
* both downloaded ~16k products for a few row labels and rendered blank for a
* product that had since left the storefront.
*/
productVariant?: {
id: string;
title: string;
product: { id: string; title: string; images: Array<{ url: string }> };
} | null;
}
export interface OrderDetail {
@@ -319,8 +412,54 @@ function iamAppUrl(path: string) {
}
export const api = {
/**
* The WHOLE active catalogue in one response.
*
* The real catalogue reaches ~16k products, so prefer the paged/targeted
* calls below; this stays for the screens that genuinely work over the full
* list and is what the route answers when asked for nothing in particular.
*/
listProducts: () => request<ProductSummary[]>('/catalog/products'),
/** One page of the storefront, filtered and counted server-side. */
listProductsPaged: (query: ProductQuery = {}) =>
request<ProductPage>(`/catalog/products${toQueryString(query)}`),
/**
* One product, instead of downloading the catalogue to `find()` it.
* 404s for a product that is not on the storefront (inactive, or no photo).
*/
getProduct: (id: string) => request<ProductSummary>(`/catalog/products/${encodeURIComponent(id)}`),
/**
* Specific products by id — the cart, favourites, order items.
*
* Chunked because the route caps `ids` at 100 and drops the rest: a caller
* that asked for more would silently get a partial answer, and callers treat
* "missing from the answer" as "no longer on the storefront". Favourites
* already run to the high hundreds in the imported data (874 rows, FAV-01),
* so this is a live case, not a theoretical one.
*/
getProductsByIds: async (ids: string[]): Promise<ProductSummary[]> => {
const unique = [...new Set(ids)].filter(Boolean);
if (unique.length === 0) return [];
const chunks = Array.from({ length: Math.ceil(unique.length / ID_CHUNK) }, (_, i) =>
unique.slice(i * ID_CHUNK, (i + 1) * ID_CHUNK),
);
const pages = await Promise.all(
chunks.map((chunk) =>
request<ProductPage>(`/catalog/products?ids=${chunk.map(encodeURIComponent).join(',')}`),
),
);
return pages.flatMap((p) => p.rows);
},
/**
* The filter sheet's options (categories, brands, collections, gram range),
* which used to be derived by scanning the whole catalogue in the browser.
*/
getCatalogFacets: () => request<CatalogFacets>('/catalog/products/facets'),
/**
* Step 1 of login — ports henza_server ApiMobileController::userAuth.
* Always resolves `{ sent: true }`, even for an unregistered number, so the
@@ -420,10 +559,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,
});
@@ -0,0 +1,112 @@
<!--
«در حال مشاهده به‌عنوان …» — shown while a sales expert is working inside one
of their customers' accounts.
NOT in the reference, and added on purpose. There, impersonation was invisible
once the token had been swapped (myDataStore.ts:163): the only way an expert
could tell whose account they were in was to notice the data looked wrong.
Placing an order on the wrong customer's account — their gold debt, their
ledger — was a single tap away with nothing to catch it.
It is also the exit. The reference's only way out was the logout button, which
dropped the expert's own session too (Dashboard.vue:781-789).
-->
<template>
<div v-if="session.actingAs" class="aab" role="status">
<span class="aab__dot" aria-hidden="true" />
<span class="aab__text">
در حال مشاهده به‌عنوان <strong>{{ session.actingAs.name || 'مشتری' }}</strong>
</span>
<button type="button" class="aab__exit" :disabled="leaving" @click="leave">
{{ leaving ? '…' : 'خروج' }}
</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useSessionStore } from '../../stores/session'
import { useCartStore } from '../../stores/cartStore'
import { toast } from '../../composables/useToast'
const session = useSessionStore()
const cart = useCartStore()
const router = useRouter()
const leaving = ref(false)
/**
* Back to the expert's own account. The cart is cleared in this direction too:
* a basket built inside the customer's account must not follow the expert out
* and land on their own order.
*/
async function leave() {
leaving.value = true
try {
cart.clear()
session.setActingAs(null)
await router.push({ name: 'home' })
toast.info('به حساب خودتان بازگشتید')
} finally {
leaving.value = false
}
}
</script>
<style scoped lang="less">
.aab {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 2000;
display: flex;
align-items: center;
gap: 8px;
padding: 7px 16px;
/* Deliberately not a brand colour: this is a warning strip, and it has to be
noticeable at a glance to do its job. */
background: #8d6a46;
color: #fff;
font-size: 12px;
font-weight: 600;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
}
.aab__dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #ffd9a0;
flex: 0 0 auto;
}
.aab__text {
flex: 1 1 auto;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
strong {
font-weight: 800;
}
}
.aab__exit {
flex: 0 0 auto;
border: 1px solid rgba(255, 255, 255, 0.55);
background: transparent;
color: #fff;
border-radius: 8px;
padding: 3px 12px;
font-family: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
&:disabled {
opacity: 0.6;
cursor: default;
}
}
</style>
@@ -3,9 +3,10 @@
language (see components/home/* and HomeView). Ported originally from
legacy henza_pwa/src/components/product/orderItem.vue.
Adapted: product/variant title comes from a client-side lookup (see
useOrderItemProduct.ts) since the real order-items response only carries
productVariantId.
The product/variant title and photo come WITH the order (the server includes
each item's variant and product). They used to be looked up in the browser
against the whole catalogue, which downloaded ~16k products to label a few
rows and left the row blank for a product that had since left the storefront.
DROPPED the "توضیحات: -" row the previous version rendered: our OrderItem
schema has no note field (legacy's per-item note was a real column there;
@@ -46,18 +47,17 @@
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { computed } from 'vue'
import Icon from '../icon/Icon.vue'
import { useOrderItemProduct, type VariantLookup } from '../../composables/useOrderItemProduct'
import { orderItemLookup } from '../../composables/useOrderItemProduct'
import type { OrderItemDetail } from '../../api/client'
const props = defineProps<{ value: OrderItemDetail }>()
const { lookup: lookupVariant } = useOrderItemProduct()
const lookup = ref<VariantLookup | undefined>()
onMounted(async () => {
lookup.value = await lookupVariant(props.value.productVariantId)
})
// The server sends these with the order, so there is nothing to fetch and
// nothing to wait for — the row renders complete on its first frame instead of
// filling in after a catalogue download.
const lookup = computed(() => orderItemLookup(props.value))
</script>
<style scoped lang="less">
+29 -3
View File
@@ -30,23 +30,49 @@
<script setup lang="ts">
import { useRouter } from 'vue-router'
import Icon from '../icon/Icon.vue'
import { useNavStore } from '../../stores/navStore'
const props = withDefaults(
defineProps<{
title: string
/** Show the back button. */
back?: boolean
/** Route name to go to instead of history.back(). */
/**
* Where to go when there is nothing to go back to — a direct link, a
* refresh, or a previous entry the router guard would bounce us out of.
*
* A FALLBACK, not a destination. It used to be the destination, which is
* why back from the login page always landed on home even when the person
* had arrived from their profile: every screen pushed a fixed route name
* and the real history was ignored (inherited from the reference, which
* did the same — `$router.push({name:'userPage::hasSubRoute'})` in each
* component's back arrow).
*/
backTo?: string
}>(),
{ back: true },
)
const router = useRouter()
const nav = useNavStore()
function onBack() {
if (props.backTo) router.push({ name: props.backTo })
else router.back()
// Prefer true history: it is the only thing that knows where the person
// actually came from.
//
// `canGoBack` is tracked by the router (navStore), not read off
// `history.length`, which counts entries from before this app was opened and
// so cannot tell "arrived from the profile" from "opened this link in a new
// tab".
if (nav.canGoBack) {
router.back()
return
}
if (props.backTo) {
router.push({ name: props.backTo })
return
}
router.push({ name: 'home' })
}
</script>
@@ -1,16 +1,37 @@
// The real GET /customers/:id/orders endpoint returns OrderItem rows with
// only `productVariantId` (no nested product/variant title) — this joins
// against the shared catalogue (stores/catalogStore.ts) client-side rather
// than touching apps/api to add an include.
import { useCatalogStore, type VariantLookup } from '../stores/catalogStore'
// The product and variant titles shown on one line of an order.
//
// These now arrive WITH the order: GET customer/me/orders includes each item's
// variant, its product and the product's first image.
//
// Before that, this joined against the shared catalogue in the browser. Two
// problems, both fixed by the include: it fetched the whole catalogue (~16k
// products in the real data) to label a few rows, and a product that had since
// left the storefront was absent from the catalogue, so the row rendered blank —
// precisely for old orders, which is where order history matters most.
import type { OrderItemDetail } from '../api/client'
export type { VariantLookup }
export interface VariantLookup {
productTitle: string
variantTitle: string
imageUrl?: string
}
/** Reads the labels off the item itself; no request, no catalogue. */
export function orderItemLookup(item: OrderItemDetail): VariantLookup | undefined {
const variant = item.productVariant
if (!variant) return undefined
return {
productTitle: variant.product.title,
variantTitle: variant.title,
imageUrl: variant.product.images[0]?.url,
}
}
/**
* Kept as a composable so the call sites read unchanged. Synchronous now —
* `lookup` is resolved from the item, so it returns a value rather than a
* promise, and callers no longer need to await anything on mount.
*/
export function useOrderItemProduct() {
const catalog = useCatalogStore()
const lookup = async (productVariantId: string): Promise<VariantLookup | undefined> => {
if (!catalog.loaded) await catalog.load()
return catalog.variantLookup.get(productVariantId)
}
return { lookup }
return { lookup: orderItemLookup }
}
@@ -1,26 +1,31 @@
// Adapted from legacy singleProduct.vue's own fetch (GET /product/:id).
// The new API has no single-product-detail endpoint (only GET
// /catalog/products, the flat list), so the product is found in the shared
// catalogue (stores/catalogStore.ts). When the catalogue is already cached,
// opening a product costs no request at all.
//
// Reads ONE product from GET /catalog/products/:id.
//
// It used to fetch the shared catalogue and `find()` the row in it, because the
// API had no single-product route. With the real catalogue reaching ~16k
// products that meant opening any product could download all of them, so the
// route now exists (plan step 2) and this is the first caller moved onto it.
//
// `initial` seeds the page with the ProductSummary the tapped card already
// holds — the same shape, from the same endpoint — so the detail view renders
// complete on its first frame instead of mounting blank and jumping when the
// fetch lands. The lookup still runs, silently, and only replaces the product
// if the catalogue's copy actually differs (stock moved since the list loaded).
// fetch lands. The read still runs, silently, and only replaces the product if
// the server's copy actually differs (stock moved since the list loaded).
//
// The silent refresh waits until the opening morph (ProductMorph.vue, ≤420ms)
// is over: if the catalogue has to come from the server, parsing it — or
// swapping the product and re-rendering — mid-animation drops frames.
// is over: swapping the product and re-rendering mid-animation drops frames.
import { ref } from 'vue'
import type { ProductSummary } from '../api/client'
import { useCatalogStore } from '../stores/catalogStore'
import { api, UnauthorizedError, type ProductSummary } from '../api/client'
const SEEDED_REFRESH_DELAY_MS = 600
/** A 404 from the API client, which throws `API <path> failed (404): …`. */
function isNotFound(e: unknown): boolean {
return e instanceof Error && !(e instanceof UnauthorizedError) && /\(404\)/.test(e.message)
}
export function useProductDetail(id: string, initial?: ProductSummary | null) {
const catalog = useCatalogStore()
const loading = ref(false)
const flag = ref(Boolean(initial))
const notFound = ref(false)
@@ -31,17 +36,30 @@ export function useProductDetail(id: string, initial?: ProductSummary | null) {
if (seeded) await new Promise((resolve) => setTimeout(resolve, SEEDED_REFRESH_DELAY_MS))
else loading.value = true
try {
const products = await catalog.load()
const found = products.find((p) => p.id === id) ?? null
const found = await api.getProduct(id)
if (seeded) {
if (found && JSON.stringify(found) !== JSON.stringify(productRef.value)) productRef.value = found
if (JSON.stringify(found) !== JSON.stringify(productRef.value)) productRef.value = found
} else {
productRef.value = found
notFound.value = !found
}
flag.value = true
} catch (e) {
console.log(e)
// Only a real 404 means "no such product". Anything else — offline, a
// 500 — must not render the "not found" page: before this route existed
// a failed catalogue fetch left `notFound` false, and that is still the
// right answer, because the product may well exist.
if (isNotFound(e)) {
if (!seeded) {
productRef.value = null
notFound.value = true
}
// Seeded and now 404: the product was pulled from the storefront while
// the page was open. The card's copy stays on screen rather than
// blanking under the person mid-read; the cart refuses it at checkout.
} else {
console.log(e)
}
flag.value = true
} finally {
loading.value = false
}
+4 -1
View File
@@ -45,7 +45,10 @@ app.use(router);
setUnauthorizedHandler(() => {
useSessionStore().logout();
if (router.currentRoute.value.name !== 'login') {
void router.push({ name: 'login' });
// `replace`: the page whose request just failed is behind a dead session,
// so leaving it in history only gives the person a back button that returns
// them to it and bounces straight back here.
void router.replace({ name: 'login' });
}
});
// Ported from legacy main.ts:32-46, with one change: the brand mark is now only
+28
View File
@@ -5,6 +5,7 @@ import { useTransitionStore } from '../stores/transitionStore';
import { api } from '../api/client';
import { useCachedReads } from '../api/cachedReads';
import { afterPageLeave } from '../composables/usePageTransition';
import { toast } from '../composables/useToast';
// Legacy lazy-loaded every route component (`component: () => import(...)`) so
// the initial bundle only carries the entry route. Matched here.
@@ -136,7 +137,29 @@ router.beforeEach(async (to) => {
if (to.name === 'login' && session.isLoggedIn) {
return { name: 'home' };
}
// D3 — legacy told the guest why they were bounced
// (henza_pwa/src/router/index.ts:253-261: `showNotify('ابتدا وارد شوید')`),
// and the target redirected in silence, so tapping «سفارش‌های من» landed on
// the login box with nothing explaining it.
//
// «عمداً تکرار نشد — D3/الف»: legacy then sent the guest to `home` and lost
// where they were going. The owner chose to keep the target's `redirect`, so
// signing in returns them to the page they asked for. The message is the
// parity row; the destination is deliberately better.
//
// Legacy listed five route names; the target gates on `meta.requiresAuth`,
// which also covers the two sales-expert pages — the same rule, applied
// wherever it belongs instead of a hand-kept list.
//
// Only reached when the IAM is off (the default) or unreachable: with silent
// SSO enabled the block above has already left the page, and a toast on a
// document that is being replaced would never be read. Not a gap.
if (to.meta.requiresAuth && !session.isLoggedIn) {
toast.info('ابتدا وارد شوید');
// No loop to guard against here: a redirected navigation never becomes a
// history entry, so the entry behind the login screen is wherever the
// person actually was (their dashboard, home, a product), and
// history-back goes there correctly.
return { name: 'login', query: { redirect: to.fullPath } };
}
@@ -185,6 +208,11 @@ router.afterEach((to) => {
const nav = useNavStore();
const transition = useTransitionStore();
// Remembers where in the browser's history this app instance started, which
// is what PageBar's back button compares against before choosing between a
// real history-back and its fallback route.
nav.noteFirstNavigation();
transition.setTransitionFlag(false);
transition.setTransitionEnded(false);
setTimeout(() => {
+25 -10
View File
@@ -1,10 +1,8 @@
// Ported from legacy henza_pwa/src/store/cartStore.ts, adapted to our string
// ids and flat (non-paginated) product list. Persisted the same way (a single
// localStorage key), just via Pinia's own state instead of @vueuse's
// useStorage wrapping a hand-rolled class.
// ids. Persisted the same way (a single localStorage key), just via Pinia's own
// state instead of @vueuse's useStorage wrapping a hand-rolled class.
import { defineStore } from 'pinia'
import type { ProductSummary } from '../api/client'
import { useCatalogStore } from './catalogStore'
import { api, type ProductSummary } from '../api/client'
export interface CartItem {
pid: string
@@ -34,16 +32,33 @@ export const useCartStore = defineStore('cart', {
items: loadFromStorage() as CartItem[],
}),
actions: {
// Re-syncs cart entries against fresh product data (e.g. price/weight
// changes since the item was added), dropping entries whose
// product/variant no longer exists — same intent as legacy's init().
/**
* Re-syncs cart entries against fresh product data (e.g. price/weight
* changes since the item was added), dropping entries whose
* product/variant no longer exists — same intent as legacy's init().
*
* Asks for exactly the products in the cart. It used to load the entire
* catalogue to look up two or three of them, which with ~16k products meant
* downloading all of them every time the app opened.
*
* A failed request leaves the cart alone: it is the person's own data, held
* in localStorage, and dropping items because the network blinked would be
* worse than showing a slightly stale price.
*/
async init(force = false) {
void force // kept for callers; every call now goes to the server anyway
if (this.items.length === 0) return
try {
const products = await useCatalogStore().load(force)
const ids = [...new Set(this.items.map((i) => i.pid))]
const products = await api.getProductsByIds(ids)
const byId = new Map(products.map((p) => [p.id, p]))
const refreshed: CartItem[] = []
for (const item of this.items) {
const product = products.find((p) => p.id === item.pid)
const product = byId.get(item.pid)
const variant = product?.variants.find((v) => v.id === item.vid)
// A product the server no longer lists (deactivated, or its photo was
// removed) comes back missing, which is the same signal the catalogue
// lookup gave before: drop the line.
if (product && variant) {
refreshed.push({ ...item, product })
}
+6 -20
View File
@@ -9,12 +9,6 @@ import { computed, ref, shallowRef } from 'vue'
import { api, type ProductSummary } from '../api/client'
import { KEYS, useQueryCache } from './queryCache'
export interface VariantLookup {
productTitle: string
variantTitle: string
imageUrl?: string
}
export const useCatalogStore = defineStore('catalog', () => {
const cache = useQueryCache()
// shallowRef: the list is replaced wholesale, never mutated in place.
@@ -31,19 +25,11 @@ export const useCatalogStore = defineStore('catalog', () => {
return [...seen.values()]
})
const variantLookup = computed(() => {
const map = new Map<string, VariantLookup>()
for (const product of products.value) {
for (const variant of product.variants) {
map.set(variant.id, {
productTitle: product.title,
variantTitle: variant.title,
imageUrl: product.images[0]?.url,
})
}
}
return map
})
// `variantLookup` lived here: a variantId -> {productTitle, variantTitle,
// imageUrl} map built over the whole catalogue, used only to label order
// rows. The server now includes those fields with the order itself
// (customers.service.ts getOrders), so the map is gone rather than left as a
// reason to keep loading the full catalogue.
async function load(force = false): Promise<ProductSummary[]> {
const list = await cache.fetch(KEYS.catalog, api.listProducts, { force })
@@ -61,5 +47,5 @@ export const useCatalogStore = defineStore('catalog', () => {
cache.invalidate(KEYS.catalog)
}
return { products, loaded, categories, variantLookup, load, byId, invalidate }
return { products, loaded, categories, load, byId, invalidate }
})
+19 -8
View File
@@ -17,8 +17,16 @@
// HomeSlider's popup/link/discount click handling works unchanged.
//
// Not ported (no backend): promotionList, ignoreList, priceList, isLoaded.
//
// `isLoaded` — «عمداً تکرار نشد — D3/ب» (owner, 2026-10-12). Legacy used it as a
// router guard: a signed-in user whose one big bootstrap request had not landed
// was sent to `home` from any route lacking `meta.skipLoadedCheck`
// (henza_pwa/src/router/index.ts:263-266). The target has no such bootstrap —
// every page fetches its own data — so the flag would guard nothing and only
// add a bounce: opening a shared product link would land on home instead of the
// product. Replicating it would port the breakage, not the behaviour (D4).
import { defineStore } from 'pinia'
import { useCatalogStore } from './catalogStore'
import { api } from '../api/client'
import shippingArt from '../assets/img/shipping-and-delivery.png'
import competitionArt from '../assets/img/sports-and-competition.png'
import brandArt from '../assets/img/montzar-logo.png'
@@ -68,15 +76,18 @@ export const useConfigStore = defineStore('config', {
this.cats = cats
},
// Legacy's store.init() fanned out to /config, /promotion, /ignore, /price.
// Here the only live source is the product catalogue, from which the real
// category list is derived.
// The catalogue comes from catalogStore, so calling this next to another
// catalogue read costs no second request.
// Here the live source is the catalogue's own category list.
//
// Reads GET /catalog/products/facets, a small aggregate. It used to load the
// whole catalogue and derive the categories from it in the browser — up to
// ~16k products fetched to populate one row of chips, and wrong beyond the
// first page once the list is paged, because a category whose products all
// sit further down would vanish from the home screen.
async init(force = false) {
void force // the facets are a small read; there is no cached copy to bypass
try {
const catalog = useCatalogStore()
await catalog.load(force)
this.cats = catalog.categories.map((c) => ({ ...c, icon: { image: brandArt } }))
const { categories } = await api.getCatalogFacets()
this.cats = categories.map((c) => ({ ...c, icon: { image: brandArt } }))
this.loaded = true
} catch (e) {
console.log(e)
+8 -3
View File
@@ -21,10 +21,15 @@ export const useFavoritesStore = defineStore('favorites', () => {
}
}
// Loaded for whoever is signed in, cleared on logout — never another user's list.
// Loaded for whoever is signed in, cleared on logout — never another user's
// list. `actingAs` is watched alongside the token because «ورود به حساب
// مشتری» changes whose favourites these are WITHOUT changing the token: a
// sales expert entering a customer's account would otherwise see their own
// hearts on the customer's products, and tapping one would write to the
// customer's list.
watch(
() => session.token,
(token) => {
() => [session.token, session.actingAs?.id ?? null] as const,
([token]) => {
ids.value = []
if (token) void load()
},
+38
View File
@@ -18,6 +18,18 @@ interface NavState {
showNav: boolean
// legacy passes `undefined` to clear the transition (router/index.ts:270)
pageTransition: string | undefined
/**
* The history index this app started at, or null before the first
* navigation.
*
* Answers "is there anywhere inside this app to go back to?", which
* `history.length` cannot: it also counts entries from before the app was
* opened, so it says yes for a link opened in a fresh tab and the back button
* would leave the app. Comparing the CURRENT history position against the one
* we started at is direction-proof — it stays correct however many times the
* person goes back and forward, where a plain counter would only ever grow.
*/
entryIndex: number | null
}
export const useNavStore = defineStore('nav', {
@@ -32,8 +44,34 @@ export const useNavStore = defineStore('nav', {
activeLink: 1,
showNav: true,
pageTransition: 'right',
entryIndex: null,
}),
getters: {
/**
* True when `router.back()` lands somewhere inside this app rather than on
* whatever the person was looking at before they opened it.
*/
canGoBack: (state) => {
if (state.entryIndex === null) return false
const current = window.history.state?.position
// `position` is written by vue-router on every entry it creates. If it is
// missing (a hand-written history entry, an old browser), assume we must
// not leave the app and let the caller fall back.
return typeof current === 'number' ? current > state.entryIndex : false
},
},
actions: {
/**
* Records where in history this app instance began. Called once, on the
* first navigation — every later entry sits above it, so anything above is
* ours to go back through.
*/
noteFirstNavigation() {
if (this.entryIndex !== null) return
const position = window.history.state?.position
this.entryIndex = typeof position === 'number' ? position : 0
},
setNavVisibility(data: boolean) {
this.showNav = data
},
+27 -4
View File
@@ -9,14 +9,32 @@
// - `force` → always asks the server (pull-to-refresh, the
// profile tab's balance, reaching the end of a list)
//
// Entries never expire on a timer: data changes when the user asks for it or
// when a write here makes it wrong, and those writes call `invalidate`.
// Entries never expire on a timer, deliberately (owner ruling 2026-10-12: «هربار
// با رفتن به اون صفحه اون مقادیر مورد نیاز رو درخواست بزنه … هم سربار برای سرور
// نداره، هم درخواست الکی نمیخوره، هم دیتاها به‌روز میمونه»). A TTL guesses how
// long data stays true; entering a screen is the moment it actually matters.
//
// So the policy is:
//
// - a screen that shows server-owned data re-reads it with `force` when it is
// opened (`onMounted`, plus `onActivated` for the kept-alive views), while
// `peek` paints the previous copy instantly so the refresh is invisible;
// - the cached copy exists for that first paint and to collapse concurrent
// callers into one request, NOT to avoid asking again;
// - the catalogue is the exception: it is the whole product list in one
// response, changes when an admin edits it, and is already invalidated by
// pull-to-refresh and by placing an order.
//
// `force` is what makes this work for anything changed OUTSIDE the app — an
// order's status, a ledger entry, the gold price. Nothing here can know those
// changed, so not asking means never seeing them.
//
// Entries live in a plain Map, not reactive state: the catalogue is large and
// making it deeply reactive would cost more than the request it saves.
//
// Keys under `me:` hold one customer's data. They are dropped whenever the
// session token changes, so the next user never sees the previous one's data.
// session token changes — or the act-as target does, which changes whose data
// they hold without changing the token — so one user never sees another's.
import { defineStore } from 'pinia'
import { watch } from 'vue'
import { useSessionStore } from './session'
@@ -91,8 +109,13 @@ export const useQueryCache = defineStore('queryCache', () => {
}
}
// The token changes when the user changes — and, with «ورود به حساب مشتری»,
// WHOSE data `me:` keys hold changes without the token changing at all. Both
// have to drop the cache, or a sales expert entering a customer's account
// would be shown their own profile, orders, balance and ledger from before
// the switch.
watch(
() => session.token,
() => [session.token, session.actingAs?.id ?? null],
() => clearUserScoped(),
)
+58
View File
@@ -7,6 +7,33 @@ const MOBILE_KEY = 'gold-bank:mobile';
const LEGACY_FLAG_KEY = 'appToken';
/** D21 — cached so the expert menu entries render before whoami resolves. */
const EXPERT_KEY = 'gold-bank:isSalesExpert';
/**
* «ورود به حساب مشتری» — which of the expert's customers they are working
* inside, if any.
*
* Deliberately `sessionStorage`, not `localStorage`: closing the tab ends the
* impersonation. The reference kept the customer's own permanent api_token in
* localStorage (myDataStore.ts:163), so it survived restarts indefinitely and
* outlived the expert's employment. Here it is only a hint anyway — the server
* re-checks on every request that this customer is actually theirs.
*/
const ACTING_AS_KEY = 'gold-bank:actingAs';
export interface ActingAs {
id: string;
name: string;
}
function readActingAs(): ActingAs | null {
try {
const raw = sessionStorage.getItem(ACTING_AS_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as ActingAs;
return parsed && typeof parsed.id === 'string' ? parsed : null;
} catch {
return null;
}
}
/**
* The logged-in customer's session.
@@ -36,6 +63,14 @@ export const useSessionStore = defineStore('session', {
* an ordinary customer, so flipping this in devtools reveals nothing.
*/
isSalesExpert: localStorage.getItem(EXPERT_KEY) === '1',
/**
* The customer this expert is currently working as, or null.
*
* Display and request-header state only — never an authorisation claim.
* Putting another customer's id here gets a 403 from the server, which
* scopes the lookup to `referredByAgentId` on every single request.
*/
actingAs: readActingAs() as ActingAs | null,
}),
getters: {
/** Authenticated means holding a token, not merely knowing an id. */
@@ -58,6 +93,23 @@ export const useSessionStore = defineStore('session', {
if (value) localStorage.setItem(EXPERT_KEY, '1');
else localStorage.removeItem(EXPERT_KEY);
},
/**
* Enter or leave a customer's account. `null` returns the expert to their
* own. The reference did the same through `toggleActiveUser`
* (myDataStore.ts:159-169), which swapped the token; nothing is swapped
* here — the API client just starts naming this customer in a header.
*/
setActingAs(value: ActingAs | null) {
this.actingAs = value;
try {
if (value) sessionStorage.setItem(ACTING_AS_KEY, JSON.stringify(value));
else sessionStorage.removeItem(ACTING_AS_KEY);
} catch {
// A private window with storage blocked: the in-memory value still
// drives this tab, which is all the feature needs.
}
},
/**
* Clears everything. Called on explicit logout and by the API client when a
* request comes back 401 — an expired or revoked token must not leave stale
@@ -68,6 +120,12 @@ export const useSessionStore = defineStore('session', {
this.customerId = null;
this.mobile = null;
this.isSalesExpert = false;
this.actingAs = null;
try {
sessionStorage.removeItem(ACTING_AS_KEY);
} catch {
/* storage blocked; the in-memory reset above is what matters */
}
localStorage.removeItem(EXPERT_KEY);
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(CUSTOMER_ID_KEY);
+5 -1
View File
@@ -22,8 +22,12 @@ export const useWageQuoteStore = defineStore('wageQuotes', () => {
let timer: ReturnType<typeof setTimeout> | null = null
// A different customer has a different percent: never reuse another's quotes.
// That includes «ورود به حساب مشتری», which swaps WHICH customer we are
// quoting for without swapping the token — so a sales expert would otherwise
// see their own making charge on the customer's products, and the figure on
// screen would not be the one the order is placed at.
watch(
() => session.token,
() => [session.token, session.actingAs?.id ?? null],
() => {
quotes.value = {}
pending.clear()
+38 -3
View File
@@ -117,7 +117,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onActivated, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Loading, PullRefresh } from 'vant'
import Icon from '../components/icon/Icon.vue'
@@ -247,14 +247,23 @@ function goNewest() {
// The three reads are independent, so they run side by side. Each one is
// cached until pull-to-refresh asks the server again.
async function loadData(force = false) {
const [catalogResult, priceResult, slidesResult] = await Promise.allSettled([
// memory.init() reads the same cached catalogue, so this is one request.
const [catalogResult, catsResult, priceResult, slidesResult] = await Promise.allSettled([
// The home rails read `catalog.products`, so the catalogue is loaded
// explicitly. It used to come in as a side effect of `memory.init()`, which
// now reads the small facets endpoint instead of the whole catalogue — so
// without this call the home screen would render empty rails.
//
// Still the unpaged list: the rails slice it locally («جدیدترین», per
// category). Moving them onto paged reads is step 4 of
// docs/CATALOG-PAGINATION-PLAN.md.
catalog.load(force),
memory.init(force),
reads.goldPrice({ force }),
reads.homeSlider({ force }),
])
if (catalogResult.status === 'rejected') console.log(catalogResult.reason)
if (catsResult.status === 'rejected') console.log(catsResult.reason)
goldPrice.value = priceResult.status === 'fulfilled' ? priceResult.value : null
// No admin slides configured, or the endpoint failed — the category-derived
// hero below covers this silently, same as before this existed.
@@ -271,6 +280,32 @@ onMounted(async () => {
loading.value = false
reveal()
})
/**
* Owner ruling 2026-10-12: re-read on entering a screen rather than caching
* with a lifetime. This view is kept alive, so without this the gold price was
* fetched once per app launch and then never again until pull-to-refresh — on
* the screen that shows it most prominently.
*
* Only the PRICE is re-read, not the catalogue or the slides: the catalogue is
* the whole active product list in one response, and re-fetching it on every
* tab switch is exactly the needless load the ruling is meant to avoid. It
* changes when an admin edits it, not minute to minute, and pull-to-refresh and
* placing an order both already invalidate it.
*/
let activatedOnce = false
onActivated(async () => {
if (!activatedOnce) {
activatedOnce = true
return
}
try {
goldPrice.value = await reads.goldPrice({ force: true })
} catch (e) {
// Keep the figure already on screen rather than blanking it.
console.log(e)
}
})
</script>
<style scoped lang="less">
@@ -14,15 +14,18 @@
scope is commented out at ApiMobileController.php:187, so every referred
customer appears whatever their state (D4: replicate, don't "fix")
Deliberately NOT ported — two things, both recorded in D21:
1. `changeUser` / act-as. The reference minted an api_token for each listed
customer (ApiMobileController.php:197-201) so the agent could act AS them.
That is a session-hijack primitive; every session here derives from the
caller's own token, so tapping a card opens their details instead.
2. The activate/deactivate toggle and the edit button, which posted to
`/customer/toggle-active` and the customer form. Those are admin-panel
operations here, and adding a write path to the app during a delivery is
not worth the risk. The state is shown, read-only.
`changeUser` / act-as IS ported — see `enterAccount` below and D29. It was
previously left out as a session-hijack primitive (D21); the owner asked for
it back, so the capability is the reference's but the mechanism is not. The
reference minted a permanent api_token per customer
(ApiMobileController.php:197-201) and swapped the bearer token; here the
expert keeps their own token and the client names the customer in a header,
which the server re-authorises on every request.
Still deliberately NOT ported (D21):
- The activate/deactivate toggle and the edit button, which posted to
`/customer/toggle-active` and the customer form. Those are admin-panel
operations here. The state is shown, read-only.
Scope is the server's: `referredByAgentId` = this expert, from the token.
-->
@@ -127,6 +130,9 @@
<dd>{{ active.active === 1 ? 'فعال' : 'غیرفعال' }}</dd>
</div>
</dl>
<button type="button" class="cch__enter" :disabled="entering" @click="enterAccount(active)">
{{ entering ? 'در حال ورود…' : 'ورود به حساب این مشتری' }}
</button>
<button type="button" class="cch__close" @click="detailOpen = false">بستن</button>
</div>
</Drawer>
@@ -135,6 +141,7 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Drawer } from 'ant-design-vue'
import { Loading, PullRefresh } from 'vant'
import Icon from '../../components/icon/Icon.vue'
@@ -142,6 +149,14 @@ import PageBar from '../../components/ui/PageBar.vue'
import Spinner from '../../components/Spinner.vue'
import SearchInput from '../../components/search/SearchInput.vue'
import { api, type ExpertCustomer } from '../../api/client'
import { useSessionStore } from '../../stores/session'
import { useCartStore } from '../../stores/cartStore'
import { toast } from '../../composables/useToast'
const router = useRouter()
const session = useSessionStore()
const cart = useCartStore()
const entering = ref(false)
const rows = ref<ExpertCustomer[]>([])
const loading = ref(false)
@@ -190,6 +205,30 @@ function openDetail(item: ExpertCustomer) {
detailOpen.value = true
}
/**
* «ورود به حساب مشتری» — the reference's `changeUser`
* (customerChoice.vue:155-167). There it swapped the bearer token for the
* customer's own; here the session simply records who we are acting as and the
* API client names them in a header, which the server authorises per request.
*
* The cart is cleared in both directions: it lives in localStorage, so without
* this the expert's own basket would follow them into the customer's account
* and end up on the customer's order.
*/
async function enterAccount(item: ExpertCustomer) {
entering.value = true
try {
cart.clear()
session.setActingAs({ id: item.id, name: item.name ?? item.fullName ?? item.mobile ?? '' })
detailOpen.value = false
// Same destination as the reference, which returned to the dashboard.
await router.push({ name: 'userPage::hasSubRoute' })
toast.success(`وارد حساب ${item.name ?? ''} شدید`)
} finally {
entering.value = false
}
}
onMounted(load)
</script>
@@ -334,7 +373,7 @@ onMounted(load)
font-weight: 600;
}
.cch__close {
.cch__enter {
margin-top: 18px;
width: 100%;
padding: 13px;
@@ -346,5 +385,25 @@ onMounted(load)
font-size: 14px;
font-weight: 700;
cursor: pointer;
&:disabled {
opacity: 0.6;
cursor: default;
}
}
/* Secondary now that "enter the account" is the primary action here. */
.cch__close {
margin-top: 10px;
width: 100%;
padding: 13px;
border: 1px solid fade(@primary, 35%);
border-radius: 14px;
background: transparent;
color: @primary;
font-family: inherit;
font-size: 14px;
font-weight: 700;
cursor: pointer;
}
</style>
@@ -127,10 +127,16 @@ async function submit() {
}
}
/** The reference sent the user home after the dialog (:175-177). */
/**
* The reference sent the user home after the dialog (:175-177).
*
* `replace`: once the documents are in, this route is no longer reachable — the
* router guard redirects it home — so leaving it in history gives a back button
* that appears to do nothing.
*/
function finish() {
done.value = false
router.push({ name: 'home' })
router.replace({ name: 'home' })
}
</script>
@@ -262,7 +262,7 @@ async function logOut() {
router.push({ name: 'home' })
}
async function loadDashboard(force = false) {
async function loadDashboard() {
// Not wrapped before: a failure here (expired token, network blip) left
// the exception uncaught, so onRefresh's refreshing.value = false never
// ran and PullRefresh stayed stuck in its loading state — a working pull
@@ -271,7 +271,12 @@ async function loadDashboard(force = false) {
// The balance on this tab is the one figure read fresh on every visit;
// the cached copy only fills the screen until it arrives.
session.isLoggedIn ? reads.me({ force: true }) : Promise.resolve(null),
reads.goldPrice({ force }),
// Also forced, per the owner's 2026-10-12 ruling: both figures on this tab
// are read fresh on every visit. This used to follow a `force` parameter
// that only pull-to-refresh set, so the price here could be as old as the
// app launch. With both reads always fresh the parameter had nothing left
// to control, so it is gone.
reads.goldPrice({ force: true }),
])
if (me.status === 'fulfilled') customer.value = me.value
else console.log(me.reason)
@@ -279,7 +284,7 @@ async function loadDashboard(force = false) {
}
async function onRefresh() {
await loadDashboard(true)
await loadDashboard()
refreshing.value = false
}
+32 -14
View File
@@ -3,11 +3,14 @@
restyled into the redesigned design language (see components/home/* and
HomeView).
Real, not stubbed: favorites are the local favoritesStore (per-device, no
backend persistence — see favoritesStore.ts from an earlier batch), filtered
against the real product catalog client-side. No pagination — the whole
catalog is fetched once (same "small catalog" approach as everywhere else).
That logic is carried over unchanged; only the chrome and the card change.
Favourites are server-side (FAV-01: GET/POST customer/me/favorites), and the
products behind them are fetched BY ID — the saved ids go straight to
`?ids=…`, one request for the lot.
It used to fetch the whole catalogue and filter it in the browser, which with
~16k products meant downloading all of them to show a handful. It was also
wrong beyond the first page once paging existed: a favourite outside the
loaded slice would simply not appear.
-->
<template>
<div class="favs">
@@ -35,7 +38,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import Icon from '../../components/icon/Icon.vue'
import PageBar from '../../components/ui/PageBar.vue'
@@ -43,26 +46,41 @@ import Spinner from '../../components/Spinner.vue'
import SectionHead from '../../components/home/SectionHead.vue'
import ProductCard from '../../components/product/ProductCard.vue'
import { useFavoritesStore } from '../../stores/favoritesStore'
import { useCatalogStore } from '../../stores/catalogStore'
import { api, type ProductSummary } from '../../api/client'
const router = useRouter()
const favorites = useFavoritesStore()
const catalog = useCatalogStore()
const loading = ref(false)
const allProducts = computed(() => catalog.products)
const fetched = ref<ProductSummary[]>([])
const favoriteProducts = computed(() => allProducts.value.filter((p) => favorites.isFavorite(p.id)))
/**
* Still filtered against the store, so un-hearting a product removes its card
* at once without waiting for a refetch — the fetched list is the source of the
* product DATA, the store is the source of truth for what is saved.
*/
const favoriteProducts = computed(() => fetched.value.filter((p) => favorites.isFavorite(p.id)))
onMounted(async () => {
loading.value = !catalog.loaded
async function load() {
const ids = favorites.ids
if (ids.length === 0) {
fetched.value = []
return
}
loading.value = fetched.value.length === 0
try {
await catalog.load()
fetched.value = await api.getProductsByIds(ids)
} catch (e) {
console.log(e)
} finally {
loading.value = false
}
})
}
onMounted(load)
// The ids arrive from the server just after sign-in, and change when the person
// hearts something elsewhere in the app — both land here as a new id list.
watch(() => favorites.ids.join(','), load)
</script>
<style scoped lang="less">
+26 -16
View File
@@ -3,18 +3,18 @@
restyled into the redesigned design language (see components/home/* and
HomeView).
Per the earlier decision: OTP-based flow ported structurally, but the
SMS-send step is stubbed — no SMS provider exists. What's real vs stubbed,
all carried over unchanged from the previous version:
- Step 1 (mobile number) is checked against the REAL, already-existing
GET /api/customers endpoint (client-side match on `mobile`) — no fake
endpoint invented. A non-match shows legacy's own
"اطلاعات کاربری در سیستم وجود ندارد" text, not a new message.
- Step 2 (OTP code) is NOT verified — any 4-digit code is accepted, since
there is no real code to check against. On "verify", the session store
logs in as the matched real customer, so downstream features (balance,
ledger, favourites-as-logged-in) work against real seeded data.
- `token.fireBaseToken` doesn't exist in this port (Firebase deferred).
The flow is REAL. These notes used to say it was stubbed, and that stale text
misled a reader as recently as 2026-10-12, so it is corrected rather than
deleted:
- Step 1 posts the number to the server, which looks it up itself. It no
longer pulls the customer list into the client to match on `mobile` — that
was the login leak (D8). An unregistered number is answered with 404 and
the server's Persian message is shown; owner ruling 2026-10-12, because
the earlier opaque answer walked the person to the code box to wait for an
SMS that was never going to arrive.
- Step 2 IS verified by the server: hashed code, two-minute expiry, attempt
limit (D6). Accepting any 4-digit code is long gone.
- `token.fireBaseToken` still does not exist in this port (PUSH-01).
- `useOtpToken()` (WebOTP autofill) was already dead in legacy itself.
-->
<template>
@@ -140,9 +140,15 @@ const sendPhone = async () => {
body.defaultFocus = true
})
} catch (e: unknown) {
// 429 = the send throttle (too soon, or too many in the window). Its message
// is already Persian and user-facing, so show it rather than a generic one.
const text = e instanceof Error && /\(429\)/.test(e.message) ? extractServerMessage(e) : null
// Both of these carry a Persian, user-facing `message` from the server, so
// show it instead of a generic one:
// 429 — the send throttle (too soon, or too many in the window);
// 404 — the number is not registered (owner ruling 2026-10-12). Without
// this branch the person is told "خطا در ارسال کد"، which is the
// very confusion the 404 was added to remove: they would still not
// know whether the SMS was late or the number was never on file.
const text =
e instanceof Error && /\((?:429|404)\)/.test(e.message) ? extractServerMessage(e) : null
toast.error(text ?? 'خطا در ارسال کد. لطفاً دوباره تلاش کنید.')
} finally {
body.loading = false
@@ -177,7 +183,11 @@ const sendToken = async (otpCode: string) => {
session.setSalesExpert(false)
}
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : undefined
await router.push(redirect ?? { name: 'home' })
// `replace`, not `push`: the login screen must not stay in history. Pushed,
// going back from the page they just reached returns them to the login box
// they have already used, which the guard above then bounces to home — so
// one tap of "back" loses their place entirely.
await router.replace(redirect ?? { name: 'home' })
toast.success('با موفقیت وارد شدید')
} catch (e: unknown) {
toast.error(
+30 -2
View File
@@ -147,7 +147,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onActivated, onMounted, reactive, ref } from 'vue'
import { Drawer } from 'ant-design-vue'
import { Loading, PullRefresh } from 'vant'
import Icon from '../../components/icon/Icon.vue'
@@ -232,7 +232,35 @@ async function onRefresh() {
refreshing.value = false
}
onMounted(() => loadOrders())
/**
* Owner ruling 2026-10-12: fetch what the screen needs each time it is opened,
* rather than caching it with a lifetime — «هربار با رفتن به اون صفحه اون
* مقادیر مورد نیاز رو درخواست بزنه، هم سربار برای سرور نداره، هم درخواست الکی
* نمیخوره، هم دیتاها به‌روز میمونه».
*
* `force` matters because an order's status changes on the ADMIN side — nothing
* in this app invalidates the cache when that happens, so without it a list
* fetched once was shown unchanged for the rest of the session.
*
* `onActivated` as well as `onMounted`: this view is in MasterLayout's
* keep-alive list, so it is mounted once and every later visit only activates
* it. With `onMounted` alone the second visit made no request at all.
*
* The cached copy still renders instantly (`peek` above) and `loading` only
* shows a spinner when there is nothing to show, so the refresh is invisible.
*
* `activatedOnce` guards the first visit, where Vue runs both hooks — the same
* shape DashboardView uses. Without it the two calls would overlap; the cache
* would collapse them into one request anyway, but not firing twice is clearer
* than relying on that.
*/
onMounted(() => loadOrders(true))
let activatedOnce = false
onActivated(() => {
if (activatedOnce) void loadOrders(true)
activatedOnce = true
})
</script>
<style scoped lang="less">
@@ -142,11 +142,23 @@ const openEntry = (item: LedgerEntrySummary) => {
showPopUp.value = true
}
/**
* Owner ruling 2026-10-12: re-read on entering the screen.
*
* `force` is the point here. Ledger entries are written by the ACCOUNTING side,
* never by this app, so nothing here ever invalidated the cached copy — the
* first visit's list was shown for the rest of the session, and a document
* posted meanwhile stayed invisible until pull-to-refresh.
*
* This view is not in the keep-alive list, so `onMounted` runs on every visit
* and no `onActivated` is needed. The cached copy renders immediately (`peek`
* above), so the re-read is not visible as a loading state.
*/
onMounted(async () => {
if (!session.isLoggedIn) return
loading.value = reads.peek(KEYS.ledger) === undefined
try {
entries.value = await reads.myLedgerEntries()
entries.value = await reads.myLedgerEntries({ force: true })
} finally {
loading.value = false
}
+39
View File
@@ -217,3 +217,42 @@
| ثبت سند سفارش | قانون `documents.triggerStatus` در تب «قابلیت‌ها و زمان‌بندی»، کنار کلید ثبت سند: سند **موقت (پیش‌فاکتور)** وقتی سفارش به این وضعیت **یا بعد از آن** برسد ثبت می‌شود (ثبت سفارش، تأیید مدیر، تأمین، آماده‌سازی، تحویل مسئول فروش [پیش‌فرض = رفتار قبلی]، تحویل مشتری). ارسال بلافاصله پس از commit |
جزئیات قانون سند: `SUSPENDED` هیچ‌وقت ماشه نیست؛ برگشت وضعیت به زیر قانون (برداشتن وضعیت در ادمین) یا لغو یا **حذف سفارش از ادمین** سند موقت را پس می‌گیرد (حذف فقط اگر هنوز موقت است). در ته‌حساب رسیدن دوباره به قانون سند تازه می‌فرستد (ترتیب صف: اول حذف)؛ در زرین هرگز دو بار (کلید ضد تکرار ندارد). کار حذف سند دیگر به ردیف سفارش نیاز ندارد (کد حساب از درخواست خود سند خوانده می‌شود). ثبت بدهی دفتر داخلی (`postOrderDebt`) دست نخورد.
## ۱۳. زرین روی نصب واقعی (۱۴۰۵/۰۷/۲۰ — برای بررسی‌های بعدی)
نصب مالک: زرین نسخه‌ی **۲۲۸**، حدود ۸۷۰ حساب، ۶۵۸ کارساخته. آدرس و توکن نزد مالک است و در مخزن نوشته نمی‌شود.
### تست دوباره
اسکریپت [apps/api/scripts/test-accounting-zarrin.ts](../apps/api/scripts/test-accounting-zarrin.ts) خودِ درایور را روی نصب واقعی اجرا می‌کند. دیتابیس اپ را دست نمی‌زند.
```
ZARRIN_URL=http://<host>:<port>/ZarrinService/accounting ZARRIN_TOKEN=<token> ZARRIN_ACCOUNT=499 \
npx ts-node --transpile-only scripts/test-accounting-zarrin.ts # فقط خواندن (۱۳ بررسی)
# + ZARRIN_WRITE_TEST=1 ZARRIN_TEST_ACCOUNT=953 # همراه نوشتن (۲۰ بررسی)
```
- **حساب آزمایشی ۹۵۳** «تست اپ گلدبانک» (موبایل 09990001111، گروه «متفرقه») با تأیید مالک برای همین تست ساخته شد. نوشتن **فقط روی همین حساب** مجاز است. زرین API حذف حساب و حذف کارساخته ندارد، پس اسکریپت هیچ‌وقت حساب یا کارساخته نمی‌سازد.
- درخواست‌ها با فاصله فرستاده شوند: سرور یک بار وقتی پشت سر هم درخواست گرفت، اتصال را قبول نکرد.
- نتیجه‌ی آخرین اجرا (۱۴۰۵/۰۷/۲۰): ۲۰ از ۲۰.
### رفتارهایی که در داکیومنت زرین نیست
| موضوع | واقعیت | در درایور |
|---|---|---|
| علامت مانده | منفی = بدهکار | پیش‌فرض صفحه‌ی اتصال درست است |
| سند موقت | **همان لحظه روی مانده اثر دارد** (برخلاف ته‌حساب) | — ؛ قانون ثبت سند را با این در نظر بگیرید |
| موقت بودن سند API | در `shomareSanad` = «موقت»؛ سندی که در خود زرین باز مانده: `noeFactor` = «فاکتور موقت» | هر دو خوانده می‌شود |
| `listKarSakhte` | صفحه‌های ۱۰۰تایی با `pageNum` | همه‌ی صفحه‌ها خوانده می‌شود |
| `listhesabha` | اسم‌ها «نام \* نام‌خانوادگی» | «\*» حذف می‌شود |
| `parvande` | ردیف اول «مانده از قبل» مانده نیست | کنار گذاشته می‌شود؛ مانده‌ی جاری از مانده‌ی واقعی (`listMandeHesabha`) به عقب حساب می‌شود |
| `parLastTenRadif.mandeG` | مانده‌ی **فعلی** حساب روی همه‌ی ردیف‌ها، نه مانده‌ی هر ردیف | برای مقایسه‌ی ردیف‌به‌ردیف قابل استفاده نیست |
| `goroohSakhte` | جواب درست با کد HTTP 400 | پذیرفته می‌شود |
| `infogardeshsakhte` | JSON دست‌نویس معیوب، کند (۵ تا ۳۳ ثانیه)، گاهی خطای ۵۰۰ از خود زرین | تعمیر JSON، مهلت ۹۰ ثانیه |
| اتصال‌های keep-alive | سرور اتصال بیکار را می‌بندد و درخواست بعدی `socket hang up` می‌گیرد | یک بار تکرار روی اتصال تازه |
| `addAccount` با موبایل تکراری | حساب نمی‌سازد | درایور قبل از ساخت با موبایل جستجو می‌کند |
### تست‌نشده
- ساخت کارساخته از ادمین (`addFelezsakhteModel`): مالک نخواست کارساخته‌ی آزمایشی دائمی ساخته شود.
- سنگ: هزینه‌ی سنگ در `mablagh` فرستاده می‌شود؛ با سندی که سنگ دارد بررسی نشده.
### امنیت
نصب مالک روی **http بدون رمزنگاری** و روی اینترنت باز است، با توکن ساده. توصیه: توکن قوی و https یا VPN.
+155
View File
@@ -0,0 +1,155 @@
# طرح — صفحه‌بندی واقعی کاتالوگ (۱۶ هزار رکورد)
تاریخ: ۱۴۰۵/۰۷/۲۰ (2026-10-12) — **طرح؛ منتظر تأیید**
> **مالک:** «دیتاها در اپ واقعی تا ۱۶ هزار رکورد می‌رود و گرفتن همه یک‌جا اشتباه
> است، حتماً باید پیجینیشن داشته باشد.»
موافقم. با این عدد، وضعیت فعلی قابل دفاع نیست. این سند می‌گوید دقیقاً چه چیزی
شکسته است، چرا کار از «اضافه کردن `take`/`skip`» بزرگ‌تر است، و با چه ترتیبی
بی‌ریسک انجام می‌شود.
---
## ۱. وضعیت امروز (بررسی‌شده در کد، نه حدس)
| لایه | واقعیت | مدرک |
|---|---|---|
| مسیر API | `GET /catalog/products` **هیچ پارامتری نمی‌پذیرد** | `catalog.controller.ts:10-12` |
| کوئری | یک `findMany` بدون `take`/`skip`، همراه `variants`+`images`+`category`+`brand`+`collections` | `catalog.service.ts:19-42` |
| کش سرور | کل خروجی، ۳۰ ثانیه در حافظه، با هر نوشتن باطل | `catalog-cache.service.ts` |
| «صفحه‌بندی» اپ | `PAGE_SIZE = 20` فقط یک **پنجره رندر** روی آرایه‌ی کامل است: `slice(0, visibleCount)` | `SearchView.vue:204-206`، `NewestView.vue:55-57` |
| در هر اسکرول | **صفر درخواست**، ۲۰ کارت بیشتر رندر می‌شود | همان |
**ایندکس‌ها — یافته‌ی مهم:** مدل `Product` **هیچ ایندکسی ندارد** (نه
`isActive`، نه `categoryId`، نه `brandId`، نه `createdAt`) و `ProductVariant`
ایندکسی روی `productId` ندارد. با ۱۶ هزار رکورد، صفحه‌بندی بدون ایندکس همان
کندی را می‌دهد؛ پس ایندکس **بخشی از این کار است**، نه یک بهبود جداگانه.
## ۲. چرا کار از «اضافه کردن take/skip» بزرگ‌تر است
هفت مصرف‌کننده روی فرض «کل کاتالوگ در حافظه است» نوشته شده‌اند. سه‌تا بحرانی‌اند
— هر سه کل لیست را می‌گیرند تا **یک چیز** پیدا کنند:
| جا | الان چه می‌کند | با ۱۶ هزار رکورد |
|---|---|---|
| `useProductDetail` | کل کاتالوگ را می‌گیرد تا **یک محصول** را `find` کند | بازکردن هر محصول = دانلود کل کاتالوگ |
| `cartStore.init` | کل کاتالوگ برای همگام‌سازی **۲-۳ قلم سبد** | هر بار باز شدن اپ |
| `configStore.init` | کل کاتالوگ فقط برای **لیست دسته‌ها** | صفحه خانه |
| `SearchView` | متن/دسته/برند/بازه وزن را روی کلاینت فیلتر می‌کند | فیلتر روی داده‌ی ناقص = نتیجه غلط |
| `Filters.vue` | گزینه‌های فیلتر را از کل لیست مشتق می‌کند | گزینه‌ها ناقص می‌شوند |
| `FavoritesView` | علاقه‌مندی‌ها را با `find` در کل لیست پیدا می‌کند | علاقه‌مندیِ خارج از صفحه دیده نمی‌شود |
| `useOrderItemProduct` | عنوان محصولِ آیتم سفارش را از کل لیست می‌خواند | سفارش قدیمی بی‌عنوان می‌شود |
**نتیجه:** اگر فقط `take`/`skip` به مسیر اضافه شود، جستجو و فیلتر **بی‌صدا غلط**
می‌شوند (روی ۲۰ رکورد اول فیلتر می‌کنند) و این بدتر از کندی است. پس هر
مصرف‌کننده باید مسیر مخصوص خودش را بگیرد.
## ۳. طراحی پیشنهادی
### (الف) چهار مسیر، به‌جای یک مسیر
| مسیر | برای چه | چرا جدا |
|---|---|---|
| `GET /catalog/products?page=&limit=&search=&categoryId=&brandId=&minGram=&maxGram=&sort=` | لیست و جستجو | **فیلتر و صفحه‌بندی سمت سرور**؛ تنها راه درست بودن نتیجه |
| `GET /catalog/products/:id` | صفحه محصول | یک رکورد، نه ۱۶ هزار |
| `GET /catalog/facets` | گزینه‌های فیلتر (دسته‌ها، برندها، بازه وزن) | کوچک، `distinct`/`aggregate`؛ جایگزین مشتق‌کردن از کل لیست |
| `POST /catalog/products/by-ids` | سبد، علاقه‌مندی، آیتم‌های سفارش | چند شناسه مشخص در یک درخواست |
شکل پاسخ لیست: `{ rows, total, page, limit }`. **عمداً** از `TableService`
استفاده نمی‌کنم: آن برای قرارداد XTable پنل ادمین است و شکل پاسخش
(`{rows, query:{...}}`) برای اپ بی‌مورد پیچیده است.
### (ب) سازگاری عقب‌رو — مهم
مسیر فعلی **نباید بشکند**: پنل ادمین، اسکریپت‌های smoke و نسخه‌های نصب‌شده‌ی اپ
از آن استفاده می‌کنند.
- بدون `page`/`limit` ⇒ **رفتار امروز** (کل لیست). پس هیچ مصرف‌کننده‌ای نمی‌شکند.
- با `page`/`limit` ⇒ پاسخ صفحه‌بندی‌شده.
- در لاگ، درخواست بدون `page` روی کاتالوگ بزرگ **هشدار** می‌دهد تا بفهمیم چه
کسی هنوز قدیمی است.
### (ج) کش سرور — بازطراحی
کش فعلی **یک** خروجی را نگه می‌دارد (`value: {at, data}`). با پارامترها این
نادرست می‌شود: صفحهٔ ۲ جواب صفحهٔ ۱ را می‌گیرد.
پیشنهاد: کلید کش = رشته‌ی پارامترهای نرمال‌شده، با سقف تعداد کلید (مثلاً ۵۰،
LRU) تا حافظه بی‌نهایت رشد نکند. باطل‌سازی موجود (middleware پریزما) **همه** را
با هم پاک می‌کند — که درست است، چون هر نوشتنی می‌تواند هر صفحه‌ای را عوض کند.
⚠️ سقف کلید لازم است: بدون آن، هر ترکیب فیلترِ کاربران یک ردیف کش می‌سازد و
حافظه‌ی سرور به‌تدریج پر می‌شود.
### (د) ایندکس‌ها (مهاجرت)
```
Product: @@index([isActive, createdAt]) ← لیست و مرتب‌سازی پیش‌فرض
@@index([categoryId])
@@index([brandId])
ProductVariant: @@index([productId]) ← الان نیست؛ هر include یک اسکن
ProductImage: @@index([productId])
```
جستجوی متنی: `contains` فارسی روی ۱۶ هزار ردیف با ایندکس معمولی سریع نمی‌شود.
پیشنهاد **فعلی**: همان `contains` با ایندکس بالا (برای ۱۶ هزار قابل قبول است).
اگر کند بود، مرحله‌ی بعد `pg_trgm` است — ولی **اول اندازه‌گیری، بعد اضافه کردن**.
### (ه) سمت اپ
| کار | تغییر |
|---|---|
| `catalogStore` | از «یک آرایه‌ی کامل» به «صفحات + `total`»؛ `load()` صفحه می‌گیرد، `loadMore()` صفحه بعد |
| `SearchView` / `NewestView` | `IntersectionObserver` به‌جای زیاد کردن `visibleCount`، **درخواست صفحه بعد** می‌زند؛ فیلتر/جستجو با debounce به سرور می‌رود و از صفحه ۱ شروع می‌کند |
| `Filters.vue` | گزینه‌ها از `/catalog/facets` |
| `useProductDetail` | `GET /catalog/products/:id` |
| `cartStore.init` | `by-ids` با شناسه‌های سبد |
| `FavoritesView` | `by-ids` با شناسه‌های علاقه‌مندی |
| `useOrderItemProduct` | `by-ids`، یا بهتر: عنوان از خود `OrderItem` snapshot (اگر دارد) |
| `configStore` | دسته‌ها از `/catalog/facets` |
**اندازه صفحه:** همان **۲۰** که الان پنجره‌ی رندر است، تا تجربه عوض نشود.
## ۴. ترتیب اجرا (هر مرحله قابل تست و بی‌شکست)
| مرحله | کار | وضعیت |
|---|---|---|
| ۱ | مهاجرت ایندکس‌ها | ✅ **انجام شد** (`cbb93de`) — `Product` هیچ ایندکسی نداشت |
| ۲ | مسیرهای سرور + تست | ✅ **انجام شد** (`cbb93de`) — صفحه‌بندی opt-in، فیلتر سمت سرور، ۱۷ تست |
| ۳ | صفحه محصول، سبد، علاقه‌مندی، دسته‌ها، برچسب آیتم سفارش | ✅ **انجام شد** — پنج مصرف‌کننده منتقل شد |
| ۴ | `SearchView` / `NewestView` / rails خانه → صفحه‌بندی واقعی | ⏳ **باقی** — پرریسک‌ترین (فیلتر + اسکرول) |
| ۵ | حذف خوانش کل کاتالوگ و هشدار لاگ | ⏳ فقط وقتی هیچ مصرف‌کننده‌ای نمانده |
### یادداشت مرحله ۳ (انجام‌شده)
«برچسب آیتم سفارش» در طرح اولیه نبود و سر راه پیدا شد: `OrderItem` فقط
`productVariantId` دارد نه `productId`، پس `?ids=` جوابش نمی‌داد. سرور همان را
با یک `include` برمی‌گرداند — که برای محصول حذف‌شده هم کار می‌کند، برعکس روش
قبلی که ردیف را خالی می‌گذاشت.
یک باگ هم در حین کار ساخته و گرفته شد: انتقال دسته‌ها به `/facets` باعث شد
`memory.init()` دیگر کاتالوگ را بار نزند و rails خانه خالی شود؛ `HomeView` حالا
صریحاً کاتالوگ را بار می‌کند.
**مرحله ۴ هنوز باقی است** — یعنی rails خانه، جستجو و «جدیدترین» همچنان کل
کاتالوگ را می‌گیرند. پس تا آن مرحله، سود واقعی ۱۶ هزار رکوردی کامل نشده.
## ۵. دو چیز که باید بدانی
**۱. مرجع صفحه‌بندی سرور داشت.** `ApiMobileController` برای لیست محصولات
صفحه‌بندی می‌فرستاد؛ پورت فعلی آن را به کلاینت منتقل کرده. پس این کار
**بازگشت به رفتار مرجع** است، نه قابلیت جدید — در ماتریس به‌عنوان STUB-03 ثبت
است.
**۲. ریسک واقعی این کار، جستجو و فیلتر است.** امروز روی کلاینت فوری و دقیق
کار می‌کنند. منتقل‌شدن به سرور یعنی: debounce، حالت بارگذاری، و «نتیجه‌ای نیست»
که باید با صفحه‌ی خالی اشتباه نشود. مرحله ۴ را عمداً آخر گذاشتم و پیشنهادم این
است که وقتی رسیدیم، **یک بار با هم در مرورگر امتحانش کنیم** — چون این بخش
تنها جایی است که تست واحد کفایت نمی‌کند.
---
**برای تصمیم تو:** مرحله ۱ و ۲ کاملاً بی‌ریسک‌اند و هیچ‌چیز را نمی‌شکنند. اگر
بگویی «برو»، از آن‌ها شروع می‌کنم و بعد از هر مرحله گزارش می‌دهم. اگر عجله داری،
مرحله ۳ همان‌جایی است که کاربر فوراً تفاوت را حس می‌کند (باز شدن صفحه محصول).
+188
View File
@@ -0,0 +1,188 @@
# طرح — بازگرداندن «ورود کارشناس به حساب مشتری» (act-as)
تاریخ: ۱۴۰۵/۰۷/۲۰ (2026-10-12)
## وضعیت: ✅ **انجام شد** — تصمیم مالک ۲۰۲۶/۱۰/۱۲
> «نه دقیقا همون چیزی که بود در ساختار مرجع همون رو بیار ولی با ساختار درستی که
> خودت میدونی»
یعنی: **دامنه کامل مرجع**، با سازوکار امنِ بند ۳. پس **بند ۴ (مرزها) حذف شد** —
هیچ مسیری در حالت act-as بسته نیست، آپلود مدارک و logout هم باز است، چون مرجع
هم interceptor سراسری داشت و همه‌چیز از طرف مشتری می‌رفت.
بقیه طرح عیناً اجرا شد. سه چیز که در طرح نبود و در حین کار پیدا شد (هر سه رفع
شد): پاک‌سازی `queryCache`/علاقه‌مندی/اجرت کش‌شده در جابجایی، و هدر در مسیر
آپلود که `request()` را دور می‌زند. جزئیات: `ISSUES.md` EXP-01/02/03 و D29.
---
### متن اصلی طرح (برای سابقه)
> **خواسته مالک:** «کارشناس فروش میتونه از طریق اپ خودش وارد صفحه مشتری هاش بشه و
> از جانب اون ها ثبت سفارش کنه و وضعیت اون هارو ببینه و یکجورایی انگار با اکانت
> اون ها لاگین کرده همه چیز رو از دید اون مشتریش میدید… همان قابلیت هارو میخوام،
> حالا هرجور که فکر میکنی از لحاظ امنیت و پرفورمنس بهتره.»
**همان قابلیت، بدون سه عیبِ روش قدیم.** تصمیم‌های فنی زیر با من است؛ هرجا چیزی
از مرجع **کم** شده باشد، صریح نوشته‌ام.
---
## ۱. مرجع چه می‌کرد (بررسی‌شده، نه حدس)
| مرحله | کد مرجع |
|---|---|
| لیست مشتریان | `POST /my-child` → `ApiMobileController.php:185-196`، فیلتر `reagent_id = auth()->id()` |
| **توکن مشتری ساخته می‌شد** | `:197-201` — اگر `api_token` مشتری خالی بود، `Str::random(60)` می‌ساخت و **ذخیره** می‌کرد |
| کلیک روی کارت | `customerChoice.vue:155` → `changeUser()` → `myStore.toggleActiveUser(user)` |
| ذخیره توکن | `myDataStore.ts:163` → `localStorage.setItem('activeChildToken', value.api_token)` |
| اعمال روی همه درخواست‌ها | `tokenManage.ts:8` `getUserToken()` = توکن مشتری **یا** توکن خودش → `plugins/axios.ts:18` روی **هر** درخواست |
| خروج از حساب مشتری | `Dashboard.vue:784` → پاک کردن `activeChildToken` |
یعنی دامنه مرجع: **هر کاری که مشتری می‌توانست**، چون interceptor سراسری بود.
## ۲. سه عیبی که تکرار نمی‌کنم
۱. **توکن دائمی مشتری در دست کارشناس.** `api_token` انقضا نداشت و در
`localStorage` می‌ماند. کارشناسی که فردا قطع همکاری می‌کرد، توکن مشتریانش را
داشت و همچنان کار می‌کرد.
۲. **هیچ ردی نمی‌ماند.** درخواست عیناً از طرف مشتری می‌آمد، پس در سرور معلوم
نبود این سفارش را مشتری ثبت کرده یا کارشناس. برای مالی، این یعنی غیرقابل
حسابرسی.
۳. **بررسی مالکیت فقط یک‌بار.** توکن در لحظه گرفتن صادر می‌شد؛ بعد از آن اگر
مشتری به کارشناس دیگری منتقل می‌شد، توکن قدیمی همچنان کار می‌کرد.
## ۳. طراحی پیشنهادی
**هسته: توکنِ مشتری صادر نمی‌شود. کارشناس با توکن خودش درخواست می‌دهد و
می‌گوید «از طرف مشتری X».**
### چرا این انتخاب (و نه گزینه‌های دیگر)
`CustomerJwtStrategy.validate()` در تارگت همیشه یک `AuthenticatedCustomer`
می‌سازد که `id` آن **یک Customer id** است، و **هر ۱۷ مسیر مشتری** از همان
استفاده می‌کنند. پس اگر جابجایی را همان‌جا اعمال کنم، همه آن مسیرها **بدون یک خط
تغییر** از دید مشتری کار می‌کنند — همان «همه‌چیز را از دید او می‌بیند» که خواستی،
با کمترین سطح تماس با کد.
| گزینه | نتیجه | رأی |
|---|---|---|
| صدور توکن مشتری (روش مرجع) | ساده، ولی هر سه عیب بالا | ❌ |
| پارامتر `customerId` روی هر مسیر | باید ۱۷ مسیر و همه سرویس‌ها عوض شوند؛ فراموش کردن یکی = حفره | ❌ |
| **هدر `X-Act-As-Customer` + اعمال در strategy** | یک نقطه تغییر، هر ۱۷ مسیر خودکار، قابل حسابرسی | ✅ |
### سمت سرور
**۱. هدر درخواست.** کارشناس توکن خودش را می‌فرستد به‌علاوه
`X-Act-As-Customer: <customerId>`.
**۲. اعمال در `validateExpert`** (تنها نقطه تغییر منطق دسترسی):
```
اگر هدر بود و principal کارشناس بود:
مشتری را بخوان: id = هدر، referredByAgentId = admin.id، isActive، !isArchived
اگر نبود → 403 (مشتری دیگری، یا مشتریِ کارشناس دیگر)
اگر بود → { id: customer.id, ← از دید مشتری
actingAsCustomerId: customer.id,
adminUserId: admin.id, ← هویت واقعی حفظ می‌شود
type: 'sales-expert' }
```
نکات مهم این طراحی:
- **بررسی مالکیت در هر درخواست** انجام می‌شود، نه یک‌بار. مشتری که به کارشناس
دیگری منتقل شود، دسترسی **در همان لحظه** قطع می‌شود. (عیب ۳ رفع شد.)
- کارشناس غیرفعال/تنزل‌یافته همان‌جا ۴۰۱ می‌گیرد، چون `validateExpert` از قبل
`isActive` و `role` را هر بار می‌خواند. (عیب ۱ رفع شد.)
- `adminUserId` حفظ می‌شود ⇒ هویت واقعی هرگز گم نمی‌شود. (عیب ۲ رفع شد.)
- توکن **عوض نمی‌شود**؛ پس چیزی در `localStorage` نمی‌نشیند که بعداً سوءاستفاده
شود. بستن اپ = پایان حالت act-as.
**۳. هزینه پرفورمنس (خواسته‌ات).** یک `findUnique` اضافه روی `Customer` با
`where: { id }` — کلید اصلی، پس index-only. **فقط** وقتی هدر وجود دارد؛ یعنی
درخواست‌های مشتری عادی و کارشناس در حالت معمولی **صفر هزینه اضافه** دارند. در
حالت act-as هم جایگزین کوئریِ `tradingCustomer` می‌شود، نه اضافه بر آن — پس
تعداد کوئری ثابت می‌ماند.
**۴. ⛔ این بند اجرا نشد.** مالک دامنه کامل مرجع را خواست، پس هیچ‌کدام از این
مرزها گذاشته نشد — همه مسیرها در حالت act-as باز است:
| مسیر | در حالت act-as | چرا |
|---|---|---|
| `POST /orders` | ✅ مجاز | خواسته اصلی |
| مشاهده: `me`، `me/orders`، `me/ledger-entries`، `me/report*`، `accounting-balance`، `wage-quote` | ✅ مجاز | «وضعیت آن‌ها را ببیند» |
| علاقه‌مندی‌ها | ✅ مجاز | بی‌خطر، و بخشی از «از دید او» |
| `POST /customer/me/documents` و `complete-profile` | ❌ **۴۰۳** | آپلود مدارک هویتی به‌جای مشتری. کارشناس مدرکِ مشتری را ندارد و این کار جعل هویت است، نه خدمت. در پنل ادمین انجام می‌شود. |
| `POST /auth/logout` | ❌ **۴۰۳** | نشست مشتری را نباید کارشناس ببندد |
| مسیرهای `expert/*` | ❌ **۴۰۳** | در حالت act-as بی‌معناست؛ از ابهام جلوگیری می‌کند |
**۵. ثبت در سفارش.** `OrdersService.createOrder` از قبل `placedBy` دارد. سفارشِ
act-as با `placedBy: 'operator'` ثبت می‌شود — یعنی قیمت را سرور تحمیل نمی‌کند و
عدد کارشناس می‌ماند؟ **نه**: برای این حالت `placedBy: 'customer'` می‌گذارم تا
قیمت‌گذاری سرور (MON-08) اعمال شود، چون این سفارشِ مشتری است نه اپراتورِ پنل.
علاوه بر آن `salesAgentId` از قبل خودکار از `customer.referredByAgentId` پر
می‌شود — که همان کارشناس است. **ردّ حسابرسی** هم در لاگ ثبت می‌شود:
`expert <adminUserId> acting as customer <id>`.
**۶. پیامک.** مشتری پیامک «سفارش شما ثبت شد» را **می‌گیرد** (مثل مرجع). دلیل:
روی حساب و بدهی طلای او نشسته و باید بداند. کارشناس هم پیامک ارجاع‌دهنده را
می‌گیرد، چون `referredByAgentId` خودش است — رفتار موجود، تغییری لازم نیست.
### سمت اپ (هر دو اپ)
**۱. وضعیت act-as** در `sessionStore` (نه `localStorage`): `actingAs = {id, name}`.
چون در `sessionStorage`/حافظه است، بستن تب پایانش می‌دهد — برعکس مرجع.
**۲. کلاینت API**: اگر `actingAs` ست بود، هدر `X-Act-As-Customer` به همه
درخواست‌ها اضافه شود (یک نقطه، در `request()` کلاینت).
**۳. `CustomerChoiceView`**: زدن روی کارت ⇒ `changeUser` ⇒ ست کردن `actingAs` و
رفتن به خانه، **عیناً مثل مرجع** (`customerChoice.vue:155-167`).
**۴. ⚠️ نوار هشدار همیشگی** — چیزی که مرجع نداشت و از نظر من ضروری است: یک نوار
ثابت بالای صفحه «در حال مشاهده به‌عنوان **فلانی** — خروج». بدون این، کارشناس
نمی‌فهمد در حساب کیست و ممکن است سفارش را روی حساب اشتباهی ثبت کند. این ریسک
واقعیِ روش مرجع بود.
**۵. پاک کردن سبد در جابجایی.** سبد در `localStorage` است؛ اگر پاک نشود، کالاهای
سبدِ کارشناس وارد سفارش مشتری می‌شود. در جابجایی (ورود و خروج) سبد خالی می‌شود.
## ۴. تست‌ها
| تست | می‌سنجد |
|---|---|
| کارشناس + هدر مشتریِ خودش | داده‌های آن مشتری برمی‌گردد |
| کارشناس + هدر **مشتریِ کارشناس دیگر** | ۴۰۳ |
| کارشناس + هدر مشتری غیرفعال/آرشیو | ۴۰۳ |
| **مشتری عادی** + هدر | هدر **نادیده** گرفته می‌شود (نه ۴۰۳ خاموش؛ اصلاً اثر ندارد) |
| کارشناس غیرفعال‌شده + هدر معتبر | ۴۰۱ فوری |
| سفارش در حالت act-as | `customerId` = مشتری، `salesAgentId` = کارشناس، قیمت از سرور |
| مسیرهای ممنوع (مدارک، logout) | ۴۰۳ |
| بدون هدر | رفتار امروز، بدون تغییر (regression) |
## ۵. چه چیزی عمداً مثل مرجع نیست
| مرجع | اینجا | دلیل |
|---|---|---|
| توکن دائمی مشتری به کارشناس داده می‌شد | هیچ توکنی صادر نمی‌شود | سرقت نشست؛ بعد از قطع همکاری هم کار می‌کرد |
| `api_token` در `localStorage` | وضعیت در حافظه نشست | بستن اپ = پایان |
| مالکیت یک‌بار بررسی می‌شد | هر درخواست | انتقال مشتری فوراً اثر می‌کند |
| ~~کارشناس همه‌کاره بود~~ | ~~مدارک/logout ممنوع~~ | **اجرا نشد** — مالک دامنه کامل مرجع را خواست؛ کارشناس همه‌کاره است |
| هیچ ردی نبود | لاگ + `salesAgentId` | حسابرسی مالی |
| هیچ نشانه‌ای در UI نبود | نوار همیشگی | سفارش روی حساب اشتباه |
## ۶. برآورد
| بخش | کار |
|---|---|
| سرور | `app-principal.ts` (+`actingAsCustomerId`)، `customer-jwt.strategy.ts` (منطق)، یک گارد برای مسیرهای ممنوع، لاگ در `orders.service` |
| اپ‌ها (×۲) | `sessionStore`، `api/client.ts` (هدر)، `CustomerChoiceView` (changeUser)، نوار act-as، پاک کردن سبد |
| تست | ۸ مورد بالا در `apps/api` |
ترتیب اجرا: سرور + تست‌ها اول (قابل اثبات)، بعد اپ‌ها.
---
**منتظر تأیید.** اگر با مرزهای بند ۴ (ممنوع بودن آپلود مدارک و logout) موافق
نیستی بگو — بقیه طرح تصمیم فنی است و خودم جلو می‌برم.
+61
View File
@@ -0,0 +1,61 @@
# بررسی راه‌اندازی سرور با دیتابیس خالی
> وضعیت: **بررسی فقط خواندنی** انجام شد. هیچ کدی تغییر نکرده و هیچ داده‌ای نوشته یا منتقل نشده است.
> تاریخ: ۲۰۲۶-۱۰-۱۲
## هدف
روی سرور تولید فقط **یک** کاربر super admin باشد و هیچ داده‌ی دیگری (مشتری، محصول، سفارش، بدهی، نقش اضافه، حساب تست) وارد نشود. دیتابیس henza قدیمی در این مرحله منتقل نمی‌شود.
## یافته‌ها
### ۱. حساب ثابت در کد (مهم‌ترین مورد)
- در [auth.service.ts:21](../apps/api/src/modules/auth/auth.service.ts#L21) شماره `09128081392` ثابت شده و در [خط ۴۹–۵۳](../apps/api/src/modules/auth/auth.service.ts#L49) اگر شماره همین باشد و رمز هم برابر خود شماره باشد، `ensureStaticAdmin` اجرا می‌شود.
- [خط ۲۳۰–۲۴۵](../apps/api/src/modules/auth/auth.service.ts#L230) یک `SUPER_ADMIN` با نام «مدیر موقت» می‌سازد یا فعال می‌کند.
- این شرط محیطی ندارد، پس روی سرور تولید هم فعال است.
- همین شماره در `seed.ts` به‌عنوان «کاربر تست توسعه» هم آمده است.
### ۲. داده‌ی demo در seed
- [seed.ts](../apps/api/prisma/seed.ts) بخش demo را فقط وقتی اجرا می‌کند که `NODE_ENV` برابر `production` نباشد یا `SEED_DEMO_DATA=true` باشد.
- بخش demo شامل شهرها، شعبه‌ها، کارگاه، ادمین‌های تست، مشتری، محصول، سفارش و بدهی است.
- [bootstrap.ts](../apps/api/src/prisma/bootstrap.ts) در اولین boot، اگر `RUN_SEED=false` نباشد، seed را اجرا می‌کند.
### ۳. نقش‌ها و permissionها
- `seed.ts` همیشه کاربرتایپ‌های ۸۵ تا ۸۹ و permissionهایشان را می‌سازد.
- گاردها فقط بر اساس rid کار می‌کنند و برای `SUPER_ADMIN` بای‌پس ندارند ([guards.ts:17](../apps/api/src/modules/auth/guards.ts#L17)). پس نقش ۸۵ با تمام دسترسی‌ها **لازم** است و نقش‌های ۸۶ تا ۸۹ **لازم نیستند**.
### ۴. migrationهای تغییردهنده‌ی داده
روی دیتابیس خالی بدون اثر هستند (بر اساس خواندن SQL، هنوز روی دیتابیس اجرا نشده‌اند):
| migration | کار | روی دیتابیس خالی |
|---|---|---|
| `20260922120000_customer_name_parts` | ستون و trigger نام | فقط ساختار |
| `20260922180000_sales_expert_profile_and_admin_name_parts` | `INSERT` از `AdminUser` | no-op |
| `20261005120000_accounting_integration` | permission فقط اگر نقش ۸۵ باشد | no-op |
| `20261008090000_customer_identity_cleanup` | `UPDATE` روی `Customer` و `AdminUser` | no-op |
| `20261008120000_order_sales_agent` | `UPDATE` روی `Order` | no-op |
| `20261008150000_wage_formula_permission` | permission فقط اگر نقش ۸۵ باشد | no-op |
| `20261008160000_dashboard_permission_merge` | `INSERT` و `DELETE` روی permission | no-op |
| `20261008170000_city_tree` | ساخت استان از ردیف‌های موجود | no-op |
### ۵. شماره‌های ثابت در سرویس حسابداری
`09121234567` و `09891212345` فقط مثال در docstring و تابع نرمال‌سازی هستند ([accounting-provider.ts:272](../apps/api/src/modules/accounting-sync/providers/accounting-provider.ts#L272)، [tahesab.provider.ts:224](../apps/api/src/modules/accounting-sync/providers/tahesab.provider.ts#L224)). داده نیستند.
## کارهای پیشنهادی (هنوز انجام نشده)
1. seed فقط نقش ۸۵ با `ALL_RIDS` بسازد؛ نقش‌های ۸۶ تا ۸۹ حذف شوند.
2. حساب ثابت `09128081392` و `ensureStaticAdmin` از `auth.service.ts` حذف شود.
3. روی سرور: `NODE_ENV=production` و `RUN_SEED=false`، و `SEED_DEMO_DATA` ست نشود.
4. یک اسکریپت یک‌بار اجرا برای ساخت super admin: شماره و نام و رمز را کاربر وارد می‌کند؛ داخل کد یا seed ذخیره نمی‌شود.
5. روی یک دیتابیس خالی تست شود: migrationها از صفر اجرا شوند و فقط یک کاربر و نقش ۸۵ باقی بماند.
## تصمیم‌های باز
- شماره و نام super admin واقعی.
- نقش‌های ۸۶ تا ۸۹ حذف شوند یا بمانند؟
- حذف حساب ثابت از کد تأیید شود.
## بررسی‌نشده
- سطر به سطر بررسی نشده که migrationها روی دیتابیس واقعی خالی هیچ خطایی ندهند. این را باید با یک اجرای تست روی دیتابیس خالی تأیید کرد.
- ساختار `docs/SERVER-SETUP-CHECKLIST.md` برای تنظیم سرور هنوز مرور نشده است.
+157
View File
@@ -0,0 +1,157 @@
# طرح فاز ۲ — قلم ۲ (D3): سه رفتار جامانده در اپ‌ها
تاریخ: ۱۴۰۵/۰۷/۲۰ (2026-10-12)
## وضعیت — تصمیم مالک گرفته شد (۲۰۲۶/۱۰/۱۲)
> «الف و ب مهم پس به ترتیب برو جلو — ج اصلا اولیوت نداره جزو اخرین چیز هایی هست
> که شاید درستش کنیم»
| قلم | تصمیم | وضعیت |
|---|---|---|
| **الف** — پیام مهمان | انجام شود | ✅ **انجام شد** — گزینه ب (پیام + حفظ بازگشت به مقصد) در هر دو اپ |
| **ب** — گارد `isLoaded` | انجام شود، طبق پیشنهاد پورت **نشود** | ✅ **ثبت شد** به‌عنوان «عمداً تکرار نشد — D3/ب» در `configStore.ts` هر دو اپ |
| **ج** — آمار بازدید | **آخرین اولویت، شاید هرگز** | ⏸️ معوق — بخش «شکاف ۳» پایین به‌عنوان طرحِ آماده نگه داشته شد |
---
---
## چه چیزی قبلاً انجام شده (بررسی شد، ادعا نیست)
D3 ده کار بود. هفت‌تایش انجام شده است:
| کار | وضعیت | مدرک |
|---|---|---|
| ۵ صفحه `/report`، `/report/detail`، `/ChildOrder`، `/customerChoice`، `/complete_profile` | ✅ در **هر دو** اپ | `apps/user-app/src/router/index.ts` و همان فایل در `user-app-v2` — هر پنج مسیر ثبت شده با `meta.layout='FullPage'` |
| گارد `sts_verify_step_two` روی تکمیل پروفایل | ✅ | `router/index.ts` گارد `requiresIncompleteProfile`؛ از سرور می‌پرسد نه از حافظه، پس پروفایلی که روی دستگاه دیگر کامل شده هم محترم است |
| سقف موجودی سبد v2 (`capQty`/`maxQty`) | ✅ یکسان در هر دو اپ | `stores/cartStore.ts:80,88` در هر دو |
**سه کار باقی است** و هر سه را بررسی و در مرجع تأیید کردم.
---
## شکاف ۱ — رفتار مهمان: الان به صفحه ورود پرتاب می‌شود
**مرجع** (`henza_pwa/src/router/index.ts:253-261`): کاربر وارد‌نشده که یکی از پنج
صفحه شخصی را باز کند، یک پیام «ابتدا وارد شوید» می‌بیند و **به خانه** می‌رود.
```ts
if (to.name === 'ordersList' || ... || to.name === 'completeProfile') {
showNotify('ابتدا وارد شوید');
return next({name: 'home'})
} else return next()
```
**تارگت** (`apps/user-app/src/router/index.ts:139-141`): به `/login` می‌رود با
`query.redirect`، و **هیچ پیامی نشان نمی‌دهد**.
```ts
if (to.meta.requiresAuth && !session.isLoggedIn) {
return { name: 'login', query: { redirect: to.fullPath } };
}
```
**چرا مهم است:** کاربر مهمان که روی «سفارش‌های من» می‌زند، بی‌هیچ توضیحی در صفحه
ورود می‌افتد و نمی‌داند چه شد. رفتار مرجع صریح‌تر است و D3 هم همان را خواسته.
### ⚠️ یک تضاد که باید خودت تصمیم بگیری
رفتار فعلی تارگت از یک جهت **بهتر** است: `query.redirect` دارد، یعنی بعد از
ورود، کاربر به همان صفحه‌ای که می‌خواست برمی‌گردد. رفتار مرجع این را ندارد —
کاربر به خانه می‌رود و باید دوباره دستی به آن صفحه برود.
سه گزینه:
| گزینه | نتیجه |
|---|---|
| **الف) عیناً مرجع** | toast + خانه. `query.redirect` از بین می‌رود. تطبیق کامل با D3. |
| **ب) بهترین هر دو** (پیشنهاد من) | toast «ابتدا وارد شوید» نشان داده شود، **ولی** مقصد همان صفحه ورود با `redirect` بماند. کاربر هم می‌فهمد چه شد، هم بعد از ورود سرِ جایش برمی‌گردد. در ماتریس به‌عنوان «عمداً تکرار نشد» ثبت می‌شود. |
| **ج) دست نزن** | شکاف باز می‌ماند و در ماتریس ثبت می‌شود. |
هزینه هر سه یکی است (چند خط). تفاوت فقط در تجربه کاربر است.
---
## شکاف ۲ — گارد `isLoaded`
**مرجع** (`router/index.ts:263-266`): کاربر وارد‌شده‌ای که داده‌های اولیه‌اش
(`memory.state.isLoaded`) هنوز نیامده، به هر صفحه‌ای جز `home` برود به خانه
برگردانده می‌شود — مگر آن مسیر `meta.skipLoadedCheck` داشته باشد.
**تارگت**: پورت نشده، و در کد **صریحاً نوشته شده چرا**:
```ts
// apps/user-app/src/stores/configStore.ts:19
// Not ported (no backend): promotionList, ignoreList, priceList, isLoaded.
```
**نظر من: این یکی را نباید پورت کنیم، و پیشنهادم «نه» است.**
دلیل: `isLoaded` در مرجع پرچمِ «یک درخواست بزرگ اولیه نشست» بود که تارگت ندارد —
تارگت هر صفحه داده‌ی خودش را می‌گیرد. اگر این گارد را اضافه کنیم، چیزی به کاربر
اضافه نمی‌شود و فقط یک پرش ناخواسته به خانه ساخته می‌شود: مثلاً کاربری که لینک
محصول را از تلگرام باز می‌کند، به‌جای محصول در خانه می‌افتد. این دقیقاً مصداق
«باگ مرجع را پورت نکن» (D4) است.
اگر موافقی، به‌عنوان **«عمداً تکرار نشد — D4»** ثبت می‌شود و D3 بسته می‌شود.
اگر مخالفی، پورت می‌کنم.
---
## شکاف ۳ — آمار بازدید صفحه‌ها (`log/create` و `log/update`)
**مرجع** دو مسیر دارد و زمان ماندن کاربر در هر صفحه را اندازه می‌گیرد:
| | مرجع |
|---|---|
| ورود به صفحه | `POST /log/create/{title}` → یک ردیف با `start_at`، `ip`، `title`، `customer_id` (اگر وارد شده باشد) می‌سازد و `id` را برمی‌گرداند |
| خروج از صفحه | `GET /log/update/{id}` → `end_at` و `time_present` را پر می‌کند |
| صفحه محصول | `data: {product_id}` هم می‌فرستد تا بازدید هر محصول جدا شمرده شود |
| مستثنا | `login` و `userPage::hasSubRoute` |
مرجع: `henza_server/app/Http/Controllers/Api/LogController.php`،
`henza_pwa/src/router/customAnalytics.ts`.
**تارگت**: نه مسیر، نه جدول، نه فراخوانی. کامل غایب.
این بزرگ‌ترین قلم از سه‌تاست — جدول، مدل Prisma، مهاجرت، دو مسیر API، یک
composable در هر اپ، و صفحه‌های گزارش ادمین (`queryTitle`، `queryAllCustomer`،
`queryCustomer`، `ago`) که آمار را نشان می‌دهند.
### ⚠️ دو ایراد مرجع که عیناً پورت نمی‌کنم
۱. **مسیر بی‌محافظ است.** در مرجع `log/create` احراز هویت ندارد و هر عنوانی را
می‌پذیرد، پس هر کسی از بیرون می‌تواند جدول را با ردیف‌های جعلی پر کند و آمار
را بی‌معنا یا دیسک را پر کند. پیشنهاد: عنوان فقط از یک فهرست بسته (نام
مسیرهای واقعی) پذیرفته شود و نرخ درخواست محدود شود.
۲. **`GET` که داده را عوض می‌کند.** `log/update` یک `GET` است که ردیف را
می‌نویسد. پیشنهاد: `POST` باشد. (اپ‌های تارگت تازه نوشته می‌شوند، پس سازگاری
عقب‌رو لازم نیست.)
### ⚠️ و یک پرسش که فقط تو می‌توانی جواب بدهی
این قابلیت **رفتار هر مشتری را با IP ثبت می‌کند** — کدام صفحه‌ها را دید و چند
ثانیه ماند. فنی‌اش ساده است، ولی این داده‌ی شخصی است و مرجع هیچ‌وقت آن را پاک
نمی‌کرد (جدول بی‌نهایت رشد می‌کند).
سه پرسش:
| پرسش | پیشنهاد من |
|---|---|
| این آمار را واقعاً لازم داری، یا در سیستم قدیم هم عملاً نگاهش نمی‌کردی؟ | اگر نگاهش نمی‌کردی، نسازیم. ساده‌ترین قابلیت، قابلیتی است که وجود ندارد. |
| اگر لازم است، چند وقت نگه داشته شود؟ | ۹۰ روز، و قدیمی‌ترها خودکار پاک شوند. |
| IP هم ذخیره شود؟ | نه. برای «کدام صفحه چقدر دیده شد» لازم نیست و حساس‌ترین بخش داده است. |
---
## جمع‌بندی و پیشنهاد ترتیب کار
| # | قلم | پیشنهاد من | هزینه |
|---|---|---|---|
| ۱ | toast مهمان | **گزینه ب** — هم پیام، هم بازگشت به صفحه مقصد | کم (نیم ساعت، هر دو اپ) |
| ۲ | گارد `isLoaded` | **پورت نشود** — «عمداً تکرار نشد — D4» | صفر |
| ۳ | آمار بازدید | **اول جواب بده لازمش داری یا نه.** اگر بله: با عنوان بسته، `POST`، بدون IP، نگه‌داری ۹۰ روزه | متوسط تا زیاد (جدول + مهاجرت + ۲ مسیر + ۲ اپ + صفحه گزارش ادمین) |
اگر بگویی «قلم ۱ و ۲ را انجام بده، ۳ را فعلاً نه»، D3 با یک ردیف «عمداً تکرار
نشد» برای آمار بسته می‌شود و می‌رویم سراغ قلم بعدی فاز ۲.
+62 -6
View File
@@ -138,12 +138,61 @@ prove no operation is left without an equivalent permission.
Per-module mapping of the reference's admin controller operations onto the
target's rid, grouped by the module of `apps/api/src/modules/`:
| Reference operation (controller) | Target endpoint | rid |
|---|---|---|
| *(pending — filled per module as each section below is audited)* | | |
Counted mechanically from the target's `@RequirePermission` decorators and the
permission tree, 2026-10-12 (§3–§9 are all complete, so both sides have been
read):
> Populated as §3 onward completes, so no row is written before both sides have
> been read.
| | Count |
|---|---|
| Reference admin routes (`routes/admin.php`) | 154 |
| Target admin routes carrying a rid | 163 |
| Distinct rids enforced by those routes | 68 |
| Keys in the permission tree (`permissionConst.ts`) | 176 |
Per module, against the reference controller it ports:
| Target module | Reference controller(s) | Routes | Distinct rids |
|---|---|---|---|
| `accounting` | `WalletController`, `CashController` | 5 | `wallet.list`, `wallet.charge`, `document.create`, `document.list.confirm` |
| `accounting-sync` | — target-only (D27) | 2 | `persons.list.client.omde`, `product.list` |
| `admin-branches` | `BranchController` | 6 | `branch.list`, `branch.create` |
| `admin-categories` | `CategoryController` | 11 | `collection.list`, `collection.create`, `collection.list.edit` |
| `admin-comments` | `CommentController` | 6 | `comment` |
| `admin-customers` | `AdminController`, `MajorCustomerController`, `SingleCustomerController` | 23 | 10 `persons.*` + `wallet` |
| `admin-dashboard` | `DashboardController` | 5 | `dashboard.view`, `report.order.item`, `report.product` |
| `admin-documents` | `CashController`, `WalletController` | 13 | `document.*`, `config.wallet`, `wallet` |
| `admin-invoices` | `CinyController` | 6 | `invoice.list`, `invoice.create` |
| `admin-misc` | `CitiesController`, `SmsController`, `NotifyController`, `ConstController`, `BrandController` | 27 | 16 (`cities.*`, `sms.*`, `notify.*`, `config.statics*`, `statics`, `newsletters`) |
| `admin-orders` | `OrderController`, `MajorOrderController` | 9 | `order.list`, `order.create`, `order.omde`, `order.tamin` |
| `admin-preorders` | `OrderController` (tamin) | 5 | `order.makeOrder` |
| `admin-products` | `ProductController` | 15 | `product.*`, `order.create` |
| `admin-promotions` | `PromotionController`, `IgnoreController` | 12 | `offers.*`, `offersIgnore` |
| `admin-report` | `ReportController` | 1 | `report.order.item` |
| `admin-users` | `UserController`, `PermissionController` | 11 | `user.*` (7) |
| `admin-workshops` | `WorkshopController` | 4 | `workshop.list`, `workshop.create` |
| `orders` | `ApiMobileController::setOrder` | 2 | `order.list`, `order.list.sts.submit` |
**D1's requirement — "no operation left without an equivalent permission" — is
met:** every one of the 163 rid-guarded routes names a rid, and 66 of the 68
resolve to a key the permission screen can grant.
### The 2 exceptions — PERM-02
Two enforced rids are **absent from the permission tree**, so a route checks them
but no operator can grant them from the UI:
| rid | Enforced by | Effect |
|---|---|---|
| `newsletters` | `admin-misc` (subscriber list) | only a role that already holds it (from the seed) can read the newsletter list |
| `persons.list.sellers.view` | `admin-customers` (`GET /reagent/view/:id`, the ➕ target-only agent-detail screen) | the new screen cannot be granted to a new role |
This is **inherited from the reference, not introduced here** — the header of
`permissionConst.ts` already recorded four such rids. Two of the four
(`buy.order.list`, `persons.create.customer.tak`) now have no route at all, so
they are dead on both sides and need no action.
Logged as **PERM-02**. Additive fix (add the two keys to the tree); it touches
the permission vocabulary, so it waits for the owner like PERM-01.
---
@@ -225,7 +274,12 @@ Contrary to the Phase 0 expectation, this area is in **good** shape.
| Over-limit outcome | order still created, `sts = 0` (معلق) | `OrderStatus.SUSPENDED` (`orders.service.ts:92`) | ✅ match |
| Debt recognition point | `sts > 4`, first true at `sts = 5` | `DELIVERED_TO_AGENT`, documented at `admin-orders.service.ts:14` and mapped `5 → DELIVERED_TO_AGENT` at `:359` | ✅ match |
| Removing that status | legacy allowed it, losing the posted debt | deliberately refused (`admin-orders.service.ts:382-390`) | ➕ stricter — a data-loss guard, keep (D4) |
| Suspended-order SMS | `ApiMobileController.php:739` | not yet sent | ❌ — lands with the Phase 1 SMS templates |
| Suspended-order SMS | `ApiMobileController.php:754` | `orders.service.ts` `notifyOrderPlaced` | ✅ fixed 2026-10-12 |
| Order-placed SMS to the customer | `:757` | same | ✅ fixed 2026-10-12 |
| Order-placed SMS to the admins | `:739-743` (4 hardcoded numbers) | same, via `ORDER_ADMIN_MOBILES` | ✅ fixed 2026-10-12 |
| Order-placed SMS to the sales expert | `:762-764` | `notifySalesAgent` | ✅ fixed 2026-10-12 |
| Order-**edited** SMS to the admins | `:734-737` | none | «عمداً تکرار نشد — SMS-03» — no target path lets a customer edit a placed order |
| `Notify::store` push beside each SMS | `:755,758,765` | none | ⏸️ PUSH-01, deferred to the PWA port |
The one **money hole** here is already logged and scheduled: the server accepts
client-supplied `wagePercent` / `discountPercent` / `flatRialCharge`
@@ -424,4 +478,6 @@ layout as the reference. The target reads from `OrderItem` + `LedgerEntry`
| RPT-01 | Medium | The reference's 32-column Excel export (`ReportController::getOrderItemWithDetails`) had no target equivalent. | ✅ fixed — `admin-report` module, `GET admin/report/order-items` |
| SMS-01 | Low | SMS on document confirm/unconfirm was not wired in `toggleConfirm`. | ✅ fixed — `admin-documents.service.ts:notifyDocumentConfirm` |
| SMS-02 | Low | `%name` substitution in batch SMS text was missing. | ✅ fixed — `admin-misc.service.ts:sendSms` + `customerNamesByMobile` |
| SMS-03 | Medium | **None of the four order-placement SMS messages was wired** — `OrdersService` did not even inject `SmsService`. The matrix had logged only the suspended-order one. | ✅ fixed 2026-10-12 — `notifyOrderPlaced` + `notifySalesAgent`, 6 tests. The «ویرایش شد» variant is deliberately not ported (no such path). |
| PERM-02 | Medium | `newsletters` and `persons.list.sellers.view` are enforced by routes but absent from the permission tree, so they cannot be granted from the UI. Inherited from the reference. | awaiting owner (additive) |
| PUSH-01 | Low | Firebase push notifications not implemented — deferred to PWA port phase. | ⏸️ deferred |
+574
View File
@@ -769,3 +769,577 @@ REL-01/REL-02 in ISSUES.
build 5/5 · jest 45/45 · admin smoke 43/43 · apps smoke 43/43 ·
B2B scan 34 ok / 0 broken · B2B writes 25/25 · auth-smoke 32/32 ·
sales-expert 33/33 · name trigger 9/9 · typecheck clean on all four apps.
---
## 2026-10-12 — Phase 1 close-out — order SMS (SMS-03) and the §2 rid matrix
### 1. Order-placement SMS — SMS-03
- **What:** `OrdersService` now injects `SmsService` and, after the order
transaction commits, texts three audiences: the admins listed in
`ORDER_ADMIN_MOBILES`, the customer (different text when the order was
suspended for exceeding the gram ceiling), and the customer's referring sales
expert. Brand «منتزر» replaces «هنزا گلد»; every other character of the four
texts is the reference's.
- **Why:** the matrix had logged only the suspended-order message as missing. On
reading the reference, **all four** messages were absent and `OrdersService`
did not inject `SmsService` at all — a customer placing an order was told
nothing, and neither was anyone else.
- **Reference:** `henza_server/app/Http/Controllers/Api/ApiMobileController.php:733-766`
- **Target:** `apps/api/src/modules/orders/orders.service.ts`
(`notifyOrderPlaced`, `notifySalesAgent`), `orders.module.ts`, `.env.example`
- **Matrix row:** `01-ADMIN-MATRIX.md` §4, SMS-03
- **Deliberate non-replication:** the «در سیستم ویرایش شد» variant (`:734-737`)
is **not** ported — no target path lets a customer edit a placed order, so the
branch could never fire. Annotated «عمداً تکرار نشد — SMS-03» per D4.
- **Decisions carried over:** admin numbers come from an env var rather than the
reference's four hardcoded personal numbers, matching the existing
`PROFILE_ADMIN_MOBILES` pattern; SMS is fire-and-forget per D20, so a dead
gateway can never fail an order; the messages are sent **after** the
transaction commits, as the reference did, so a rolled-back order texts nobody.
`Notify::store` (Firebase push) beside each message stays deferred as PUSH-01.
- **Tests:** 6 new cases in `orders.service.spec.ts` (customer placed/suspended
text, admin fan-out, no-admins-configured, sales expert, expert without a
mobile). Full api suite **283/283**, typecheck clean.
- **Found while testing:** the pre-existing "sales expert credit" suite mocked no
`adminUser`, so the new agent lookup hit its catch and logged an error while
the test still passed green. Mock completed — a passing test now means the
path actually ran.
### 2. §2 of the admin matrix — the D1 rid matrix
- **What:** filled in the section that had stood as *(pending)* since the phase
began, mechanically from the target's `@RequirePermission` decorators and
`permissionConst.ts`: 163 rid-guarded routes, 68 distinct rids, 176 tree keys,
mapped per module onto the reference controller each one ports.
- **Why:** D1 required proof that no admin operation is left without an
equivalent permission. It is the last unfinished item of Phase 1.
- **Result:** 66 of the 68 enforced rids are grantable from the permission
screen. The 2 that are not — `newsletters` and `persons.list.sellers.view` —
are logged as **PERM-02**; both are inherited from the reference, whose own
`permissionConst.ts` header had already recorded four such rids (the other two
now have no route on either side).
- **Target:** `docs/parity/01-ADMIN-MATRIX.md` §2
- **Note on method:** the first extraction pass read the rid that followed each
HTTP decorator and produced an off-by-one map (it claimed
`reconcile → wallet.list`). Caught by spot-checking against this CHANGELOG's
own stage-1 entry, which records `reconcile → wallet.charge`. The corrected
pass was re-verified against five independently documented mappings before any
table was written.
_No data was deleted in this entry._
---
## 2026-10-12 — Phase 2 — item #1: MON-08 step 2 (the discarded client price is now logged)
- **What:** `OrdersService.warnOnPriceMismatch` — when an app order is priced by
the server and the client had sent different figures, the difference is logged
(`wagePercent sent=… used=…`, same for `discountPercent`, plus any non-zero
`flatRialCharge`). The order is still charged the server's figures; nothing
about the pricing changed.
- **Why:** step 2 of the owner's MON-08 ruling. Steps 1, 3 and 4 had landed with
the wage-formula work, but the client's values were being discarded **in
silence** — so a stale app version, a promotion that expired between the
product page and checkout, and a tampered request were indistinguishable and
left no trace at all.
- **Reference:** `henza_server/app/Http/Controllers/Api/ApiMobileController.php:536-541`
(debt computed from the request, nothing re-read from the DB);
`henza_pwa/src/views/cart.vue:170-179` (the app computes all three).
- **Target:** `apps/api/src/modules/orders/orders.service.ts` (the call site in
the per-item map; the method beside `adminMobiles`).
- **Matrix row:** MON-08 in `ISSUES.md` §"Phase 2 — item #1".
- **Commit:** see below.
**Also added — the comparison test the ruling asked for.** Step 3 required «تست
مقایسه‌ای که نشان دهد نتیجه برای کاربر عادی یکسان است», and the suite did not
have one: it only proved that a *tampered* request gets overridden. The new
`"gives an honest app exactly the total it sent"` places the same honest order
once as a customer (server-priced) and once as an operator (client-priced) and
asserts the two totals are identical — which is the actual claim, that an
ordinary customer sees no change. Two more cover the logging itself: the
tampered order logs all three fields, and an honest one logs nothing (so a green
"quiet" test cannot be green merely because the method never ran).
`orders.service.spec.ts`: 13 → 16 tests. Full api suite **286/286, 26 suites**,
`tsc --noEmit` clean, and the run log inspected for swallowed errors.
**STUB-05 closed** in the same pass: the status still read "Pending the SMS
approval" though `PROFILE_ADMIN_MOBILES` and `ORDER_ADMIN_MOBILES` had replaced
the reference's six hardcoded staff numbers. No literal number is in the
target's git history.
**Deliberately unchanged:** the target reads `rashWeightGrams` from the variant
row rather than trusting the client, unlike the reference. Per the owner's
earlier ruling this deviation stays, and it is re-recorded in `ISSUES.md` so it
is not "fixed" later by someone restoring parity for its own sake.
_No data was deleted in this entry._
---
## 2026-10-12 — Phase 2 — item #2: D3's three outstanding behaviours
- **What:** (1) A guest bounced off a personal page now sees «ابتدا وارد شوید»
in both apps. (2) Legacy's `isLoaded` router guard is recorded as deliberately
not ported. (3) Route analytics parked as ANLY-01.
- **Why:** D3's remaining items. Seven of its ten were already built — all five
screens in **both** apps, the `sts_verify_step_two` guard and v2's cart stock
ceiling — confirmed by reading the code rather than trusting the checkmarks.
- **Reference:** `henza_pwa/src/router/index.ts:253-261` (the notify + home),
`:263-266` (the `isLoaded` guard), `router/customAnalytics.ts` +
`henza_server/app/Http/Controllers/Api/LogController.php` (analytics).
- **Target:** both apps' `src/router/index.ts` and `src/stores/configStore.ts`.
- **Matrix row:** APP-03, APP-04, ANLY-01 in `ISSUES.md` §"Phase 2 — item #2".
- **Commit:** see below.
**The one judgement call.** Legacy showed the toast and then sent the guest to
`home`, discarding where they were going. The target redirected to `/login` with
`query.redirect`, so signing in returns the guest to the page they wanted — that
part is better than the reference, and the gap was only the missing message.
Rather than choose silently, the trade-off went to the owner, who kept the
target's destination. So the message is the parity row and the destination is
**«عمداً تکرار نشد — D3/الف»**. The guard also keys off `meta.requiresAuth`
instead of legacy's hand-kept list of five route names, which means the two
sales-expert pages are covered too.
**`isLoaded` — argued against, and the owner agreed.** It guarded legacy's one
big bootstrap request, which the target does not have (each page fetches its own
data). Added, it would guard nothing and introduce a bounce: a shared product
link would open `home` instead of the product. That is porting the breakage, not
the behaviour (D4). The reasoning is written into both apps' `configStore.ts`,
beside the line that says the flag was not ported, so the next reader finds it
where they would actually look.
**Analytics deferred by the owner** («ج اصلا اولیوت نداره»). The design is kept
in `docs/PHASE2-D3-PLAN.md` so it does not have to be re-derived, including the
two reference defects not to copy — `log/create` was unauthenticated and took any
title, so anyone could fill the table from outside, and `log/update` was a `GET`
that wrote — plus the two questions only the owner can answer: how long to keep
per-customer browsing history (legacy never deleted it) and whether to store the
IP at all.
**Verification.** Neither app has a test runner, so the check is `vue-tsc -b` on
both (clean) plus reading the three things that make the toast actually appear
rather than merely compile: `toast.info` exists (`composables/useToast.ts:66`),
`<ToastHost />` is mounted in each `App.vue:25`, and the call sits before the
guard's `return`. A compiling toast with no host would have been invisible.
Noted in the code: with the IAM enabled, silent SSO leaves the page before this
guard runs, so the toast is a no-op there by design, not a defect.
_No data was deleted in this entry._
---
## 2026-10-12 — App login — say what went wrong (AUTH-01/02/03, DOC-01)
- **What:** Step 1 of the app login now reports an unregistered number (404) and
a failed SMS send (503) instead of answering success in both cases. A sales
expert whose trading account cannot be used gets its own 403 rather than the
unknown-number message. Both apps surface the server's Persian message for a
404 as they already did for a 429.
- **Why:** owner report — a number that was not in the system produced no error:
the app moved to the code box and «واقعا نمیشد فهمید خطا از پروژه هست یا نه
پیامک نمیاد یا نه واقعا نیست». Three causes looked identical on screen, and
only one of them was something the person could act on.
- **Reference:** `ApiMobileController::userAuth:43` — `firstOrFail()`, i.e. 404
for a number with no active customer. **The opaque answer was the deviation;
this restores the reference.**
- **Target:** `apps/api/src/modules/customer-auth/customer-auth.service.ts`
(`requestOtp`, `deliver`, `resolveExpertTradingAccount`), both apps'
`src/views/user/LoginView.vue`.
- **Matrix row:** AUTH-01, AUTH-02, AUTH-03, DOC-01 in `ISSUES.md`.
- **Commit:** see below.
**The security trade-off, stated plainly.** The opaque response existed to stop
an outsider enumerating which mobile numbers are registered. That protection is
now reduced at step 1, deliberately, on the owner's instruction: the cost was
being paid by real users and by support on every login problem. What still
stands — the per-mobile and per-IP send throttles (`assertSendAllowed`), which
the reference did not have, so enumeration is rate-bounded rather than free; and
`verifyOtp`, which keeps one message for every failure reason. `ISSUES.md`
SEC-03's "no enumeration" claim was corrected rather than left standing.
**Two further problems found while fixing the reported one.** Both were the same
shape — an operation reporting success while doing nothing:
1. A failed SMS send also returned `{ sent: true }`, because `SmsService` never
throws (D20). A dead gateway therefore produced the exact same dead end. D20
is about not letting a failed SMS break an *operation*; in a login the SMS is
the operation, so it now fails loudly. The local-dev path is preserved by
keying off `SmsService`'s own `sms-not-configured` result rather than
re-testing the config — with D26's default `relay` driver, `smsConfigured()`
is true on any machine with an external IPv4, so a config test would have
called a dev box configured and then failed its login. **The test caught
exactly this**, on the first run.
2. Three states return no trading account for a sales expert who *does* exist.
Under the new 404 they would each have claimed the number was not registered
— a false message that sends support looking for the wrong thing.
**A stale comment that actively misled.** Both apps' `LoginView.vue` header still
described the login as stubbed: no SMS provider, any 4-digit code accepted, and
step 1 matching against the customer list in the client (which was the login
leak, D8). All three had been untrue for weeks, and it misled a reader during
this very session. Corrected in place, with that noted.
**Verification.** `requestOtp` had **no tests at all** — the 28-test customer-auth
suite stayed green through a change to its response for every unregistered
number, which is why the suite's greenness was not treated as evidence.
`request-otp.spec.ts` adds 9 cases, including that the dev fallback does *not*
apply in production. Full api suite **295/295, 27 suites**; both apps `vue-tsc`
clean.
_No data was deleted in this entry._
---
## 2026-10-12 — Phase 2 — «ورود به حساب مشتری» restored (EXP-01/02/03, D29)
- **What:** A sales expert can again open one of their referred customers'
accounts and use the whole app as them — browse, see balance, debt and
reports, and place orders that land on the customer's account. Entered from
the customer's card on «لیست مشتریان»; a permanent bar names whose account it
is and exits.
- **Why:** owner report — the reference had it («یکجورایی انگار با اکانت اون ها
لاگین کرده … و این خیلی کاربردی بود ولی الان نیست») and D21 had deliberately
left it out as a session-hijack primitive. The owner asked for the capability
back, with the implementation left to judgement: «همان قابلیت هارو میخوام حالا
هرجور که فکر میکنی از لحاظ امنیت و پرفورمنس بهتره».
- **Reference:** `customerChoice.vue:155-167` → `myDataStore.ts:159-169` →
`tokenManage.ts:8` → `plugins/axios.ts:18`; server
`ApiMobileController.php:197-201`.
- **Target:** `customer-auth/app-principal.ts`, `customer-jwt.strategy.ts`,
`orders.controller.ts`, `orders.service.ts`, `sales-expert-app.controller.ts`;
both apps' `stores/session.ts`, `api/client.ts`, `stores/queryCache.ts`,
`stores/favoritesStore.ts`, `stores/wageQuoteStore.ts`,
`views/expert/CustomerChoiceView.vue`, `components/expert/ActingAsBar.vue`,
`App.vue`.
- **Matrix row:** EXP-01, EXP-02, EXP-03 in `ISSUES.md`; D29 in `DECISIONS.md`;
D21's "deliberately not ported" paragraph marked superseded.
- **Commit:** see below.
**Scope is the reference's, in full.** Its axios interceptor swapped the bearer
token, so *every* request went as the customer — including document upload. No
route is closed in act-as mode. (The plan had proposed closing documents and
logout; the owner asked for the reference's behaviour, so that was dropped.)
**The mechanism is not the reference's.** It minted a permanent `api_token` per
customer and handed it over. Instead 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. Four consequences, each fixing a real defect of the original:
1. **Ownership is re-checked on every request**, with `referredByAgentId` in the
same `where` as the id — so another expert's customer and a non-existent id
give the same answer (403), and a customer moved to another expert loses
access at once rather than at token expiry.
2. **Nothing durable is handed out.** The reference's token sat in
`localStorage` with no expiry and kept working after the expert left. Here
the target is in `sessionStorage` and is only a hint; the authority is the
expert's own token plus the per-request check.
3. **The real actor survives.** `adminUserId` is kept, so an order placed this
way is logged as `sales expert <id> acting as them`. In the reference the
request was literally the customer's and nothing could be attributed
afterwards.
4. **403, not 401**, for a customer that is not theirs: the expert's own session
is valid, so the app clears the act-as state instead of logging them out.
**Performance.** One `findFirst` on the primary key, and only when the header is
present — it *replaces* the `tradingCustomer` lookup rather than adding to it, so
the query count is unchanged in act-as mode and untouched for everyone else.
**Three things the reference did not need, because it swapped the whole session.**
Found by reading the stores rather than assuming:
- `queryCache` (`me:` keys), `favoritesStore` and `wageQuoteStore` each dropped
their data on a **token** change. Act-as changes whose data they hold without
changing the token, so without this 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. Each
watcher's own comment already stated the rule it was about to break.
- `uploadDocument` bypasses `request()` and builds its own headers, so an
expert's upload would have been filed against their own account, silently.
`grep Authorization` on the client returning two call sites is what caught it.
- The cart is in `localStorage`, so it is cleared in **both** directions —
otherwise the expert's own basket follows them in and ends up on the
customer's order.
**Added on purpose, with no reference equivalent:** the permanent «در حال مشاهده
به‌عنوان …» bar. There, impersonation was invisible once the token had been
swapped — the only way to tell whose account you were in was to notice the data
looked wrong, 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 the logout button,
which ended the expert's own session too.
**Verification.** `CustomerJwtStrategy` had **no test coverage at all** before
this, and it is now where the whole authorisation boundary of the feature lives,
so `act-as-customer.spec.ts` covers 11 cases: the happy path, the scoped query
itself, another expert's customer, an inactive customer, a deactivated expert, a
demoted expert, the header being **ignored** on a customer token, the no-header
fallback (asserting the extra query does not run), blank and duplicated headers,
and a revoked session short-circuiting before the header is read. Plus 2 cases on
the order audit trail. Full api suite **308/308, 28 suites**; both apps
`vue-tsc` clean.
_No data was deleted in this entry._
---
## 2026-10-12 — Apps — back navigation and read freshness (NAV-01…04, READ-01…03)
- **What:** The back arrow follows real history instead of a fixed route; three
`push`es that stranded the user became `replace`; screens showing
server-owned data re-read it on entry.
- **Why:** owner report — «از صفحه پروفایل وارد صفحه لاگین میشم بک میزنم میره به
صفحه اصلی در صورتی که باید بیاد توی صفحه پروفایل»— with the instruction to
audit the whole structure, not just that case. Seven defects, four of them
reachable in ordinary use.
- **Reference:** the fixed-destination back arrow is inherited —
`henza_pwa/.../profile.vue:6`, `Orders.vue:8`, `transactions.vue:7`,
`favorits.vue:5` etc. all `$router.push({name:'userPage::hasSubRoute'})`. Not
replicated (D4: behaviour, not breakage).
- **Target:** both apps' `components/ui/PageBar.vue`, `stores/navStore.ts`,
`router/index.ts`, `main.ts`, `views/user/LoginView.vue`,
`views/user/CompleteProfileView.vue`, `views/user/OrdersView.vue`,
`views/user/TransactionsView.vue`, `views/user/DashboardView.vue`,
`views/HomeView.vue`, `stores/queryCache.ts`.
- **Matrix row:** NAV-01…04, READ-01…03 in `ISSUES.md`.
- **Commit:** see below.
**The reported bug, precisely.** `/user` has no auth guard, so a guest sees the
dashboard and taps «ورود / ثبت‌نام». History is then dashboard → login. Back
should return to the dashboard, but `LoginView` declared `back-to="home"` and
`PageBar` **pushed that name**, discarding history. The same was true of 14 of
the 15 `PageBar` uses in each app — only `SearchView` used `router.back()`. So
this was never one screen's bug.
**`backTo` is now a fallback, not a destination.** The 14 declarations are kept
untouched, because they are the right answer when there is genuinely nowhere to
go back to — a shared link, a refresh. What changed is that history wins when it
exists.
**Answering "is there anywhere to go back to?" honestly.** `history.length` is
the obvious choice and it is wrong: it counts entries from before the app was
opened, so a link opened in a fresh tab looks like it has history and the back
button walks the person out of the app. `navStore` instead records the history
`position` of the app's first navigation and compares the current one against it.
Chosen over a navigation counter because a counter only grows — after one
back-and-forward it would claim depth that is not there. Confirmed vue-router
writes `position` on every entry (`vue-router.mjs:97,109,145`) rather than
assuming it.
**Three `push`es that should always have been `replace`.** Each left behind a
page the guards immediately bounce, so "back" was either a no-op or a trip home:
after sign-in the login screen stayed in history (the worst of the three — the
file already honoured `?redirect=`, so sign-in and back disagreed about where the
person belonged); the 401 handler kept the page whose request had just failed;
and complete-profile kept a form that is unreachable once the documents are in.
`CartView`'s post-order push was **left alone** — back lands on the emptied
cart, which is a real screen rather than a dead end.
**Read freshness, by the owner's rule** («هربار با رفتن به اون صفحه اون مقادیر
مورد نیاز رو درخواست بزنه») — chosen over the TTL that had been proposed,
and the better call: a TTL guesses how long data stays true, while entering a
screen is when it actually matters.
The worst finding here was **OrdersView**: it is in the keep-alive list but only
loaded in `onMounted`, so **the second and every later visit made no request at
all**, and the first one read the cache. Order status changes on the admin side
and nothing in the app invalidates it, so the list could be stale for an entire
session. Ledger entries had the same shape and a stronger argument — they are
written by the accounting side, which this app can never learn about. The gold
price was forced only by pull-to-refresh on two screens that show it
prominently, and `HomeView` being kept alive meant once per app launch.
**What is deliberately NOT re-read: the catalogue.** By the owner's own
reasoning («سربار برای سرور نداره»): it is the whole active product list in one
response, it changes when an admin edits it, and pull-to-refresh and placing an
order already invalidate it. Re-fetching it on every tab switch is exactly the
needless load the ruling exists to avoid. So on Home only the price is re-read.
**On the cache layer, which the owner also asked about.** Its structure is
sound, and two things that are easy to get wrong are right: concurrent callers
share one in-flight promise, and a response arriving after an `invalidate` is
returned to its caller but not stored, so a write cannot lose a race against a
read already in flight. Its one real gap was that nothing ever went stale, which
the above fixes at the only point where staleness is observable. The policy is
now written at the top of `queryCache.ts` so a TTL is not re-introduced later.
**Verification.** Neither app has a test runner, so: `vue-tsc -b` clean on both,
and each finding was confirmed by reading the code that causes it — the
keep-alive list against each view's hooks, every `router.push` against the
guards, and `grep back-to=` across both apps. api suite untouched at 308/308.
⚠️ Not click-tested in a browser; the back-button behaviour in particular is
worth one pass by hand.
_No data was deleted in this entry._
---
## 2026-10-12 — Catalogue paging, steps 1–2: indexes and the server routes
- **What:** `Product` and its two child tables get the indexes the storefront
query actually needs, and `GET /catalog/products` learns paging, filtering,
sorting, a by-ids mode, a single-product route and a facets route.
- **Why:** owner — «دیتاها در اپ واقعی تا 16 هزار رکورد میرود و گرفتن همه یک جا
اشتباه است، حتما باید پیج نیشن داشته باشد». The route had **no** paging
parameters at all and returned every active product with its variants, images,
category, brand and collections in one response; the apps' `PAGE_SIZE = 20`
was only a render window over that full array, so scrolling made zero
requests.
- **Reference:** the reference DID page this server-side; the port moved it to
the client. Logged as STUB-03, so this is a return to reference behaviour.
- **Target:** `apps/api/prisma/schema.prisma`,
`prisma/migrations/20261012120000_catalog_paging_indexes/`,
`modules/catalog/catalog.controller.ts`, `catalog.service.ts`,
`dto/list-products.dto.ts`, `catalog-paging.spec.ts`.
- **Matrix row:** STUB-03 in `ISSUES.md`; plan in `docs/CATALOG-PAGINATION-PLAN.md`.
- **Commit:** see below.
**The indexes were not optional.** `Product` carried **no index whatsoever** — not
`isActive`, not `categoryId`, not `brandId`, not `createdAt` — and
`ProductVariant` had none on `productId`, so each per-product include scanned
its whole table. Adding `take`/`skip` on top of that would have paged the
response without making the query any faster, which is the failure mode this
change exists to avoid. `Product_isActive_createdAt_idx` is composite on purpose:
it serves the filter, the default ordering and the OFFSET walk from one index.
`CREATE INDEX` and not `CONCURRENTLY`: the deploy image's own migration runner
wraps each file in a transaction, which `CONCURRENTLY` cannot join (D15). At 16k
rows the write lock is a few hundred milliseconds. Every statement is
`IF NOT EXISTS`, because these run under both migration paths.
**Paging is opt-in, and that is the whole backward-compatibility story.** With no
query parameters the route returns the same plain array from the same cache it
always did — the admin panel, the smoke scripts and installed app builds are
untouched. Pass `page` or `limit` (or any filter) and the answer becomes
`{ rows, total, page, limit }`.
**The filters had to move server-side, not just the paging.** The apps filtered
title, category, brand and gram range in the browser over the full array. Paging
the response while leaving that in place would have made search **quietly
wrong** — searching only the first page and reporting "محصولی پیدا نشد" for
products that exist. That is worse than the slowness, so `storefrontWhere`
builds every filter into the Prisma query, and `count` uses the same `where` so
`total` describes the filtered set the app is scrolling.
**Three routes exist so the apps can stop fetching everything to find one thing**
(step 3 wires them up): `?ids=a,b,c` for the cart, favourites and order items;
`/:id` for the product screen, which currently downloads the entire catalogue to
`find()` one row; and `/facets` for the filter sheet's options, which the apps
derive today by scanning the whole catalogue in the browser.
**Deliberately NOT cached.** `CatalogCacheService` holds one built response
because the unpaged query is expensive and every screen asked for it. A paged,
filtered query is neither — it is bounded by `limit` and index-served. Caching it
would need a key per filter combination: unbounded memory for queries that are
already cheap, and a second place for stale rows to hide. Noted in the code so
it is not "optimised" later.
**Guards kept everywhere.** D27's two storefront rules (active, and has at least
one image) are in one shared `where`, so a paged list, its count, the single
product route, the by-ids route and the facets can never disagree about what is
visible. Asking for a hidden product by id still 404s. `limit` is capped at 100
and `ids` at 100 — an uncapped `limit` would just be the old "give me
everything" query spelled differently.
**Verification.** 17 new cases (329/329 overall, 29 suites), covering the
compatibility shape, skip/take translation, that `total` counts the filtered set,
each filter reaching the DB, the gram range matching ANY variant as the app did,
by-ids ignoring paging, and a hidden product 404ing. All 17 passed on the first
run, which is not evidence on its own — so one filter was deliberately broken to
confirm the suite fails (it did, 1 failed/16 passed) and then restored.
⚠️ Measured on **no real data**: the database container was not running, so the
16k-row behaviour is reasoned from the query plan and the new indexes, not timed.
Worth one `EXPLAIN ANALYZE` on a full dataset before step 4.
_No data was deleted in this entry._
---
## 2026-10-12 — Catalogue paging, step 3: the apps stop fetching everything
- **What:** Five places that loaded the whole catalogue to find a few rows now
read exactly what they need — the product screen, the cart re-sync,
favourites, the home categories, and order-row labels.
- **Why:** step 3 of `docs/CATALOG-PAGINATION-PLAN.md`. Step 2 added the
targeted routes; these are the callers. At ~16k products each of these was
downloading the entire catalogue, and three of them would have been **wrong**
as well as slow once the list is paged.
- **Target:** both apps' `api/client.ts`, `composables/useProductDetail.ts`,
`composables/useOrderItemProduct.ts`, `stores/cartStore.ts`,
`stores/configStore.ts`, `stores/catalogStore.ts`,
`views/user/FavoritesView.vue`, `views/HomeView.vue`,
`components/product/OrderItemCard.vue`; api
`modules/customers/customers.service.ts` + `order-items-include.spec.ts`.
- **Matrix row:** STUB-03 in `ISSUES.md`.
- **Commit:** see below.
| Caller | Was | Now |
|---|---|---|
| product screen | whole catalogue, then `find(id)` | `GET /catalog/products/:id` |
| cart re-sync | whole catalogue for 2–3 lines | `?ids=` for the cart's products |
| favourites | whole catalogue, filtered in the browser | `?ids=` for the saved ids |
| home categories | whole catalogue, categories derived from it | `GET /catalog/products/facets` |
| order row labels | whole catalogue, joined on variantId | included with the order |
**Three of these were not just slow, they were going to be wrong.** Favourites
filtered the loaded catalogue, so once the list pages, a favourite outside the
loaded slice silently disappears. The home categories were derived the same way,
so a category whose products all sit further down would vanish from the home
screen. Order rows looked their title up in the catalogue, which **already**
failed for a product that had since left the storefront — exactly the old orders
that history exists for — and rendered a blank row.
**Order labels moved to the server rather than to another id lookup.** The item
carries `productVariantId`, not a product id, so `?ids=` could not answer it.
One nested `include` in `getOrders` returns the variant, its product and the
product's first image: one join instead of 16k rows, and it answers for
de-listed products too, because order history is deliberately NOT filtered by
storefront visibility (asserted in the new spec). `OrderItemCard` is now
synchronous — no fetch, no `onMounted`, the row renders complete on its first
frame.
**`variantLookup` was deleted from `catalogStore`**, not left behind: it existed
only to label order rows, and keeping it would have kept a reason to load the
full catalogue.
**`getProductsByIds` chunks at 100** because the route caps `ids` there and
drops the rest. A partial answer would be read by callers as "these products are
no longer on the storefront" — the cart would silently drop valid lines.
Favourites already run to 874 rows in the imported data (FAV-01), so this is a
live case.
**A failed cart re-sync now leaves the cart alone.** It is the person's own
data in localStorage; dropping lines because the network blinked is worse than
showing a slightly stale price.
**The product screen tells 404 from "request failed".** Before, a failed
catalogue fetch left `notFound` false, which was right — the product probably
exists. Only a real 404 renders the not-found page. If the page was already
seeded from the tapped card and the product has since been de-listed, the card's
copy stays on screen rather than blanking mid-read; the cart refuses it at
checkout.
**One bug introduced and caught here:** moving the home categories to `/facets`
meant `memory.init()` no longer loaded the catalogue as a side effect — and the
home rails read `catalog.products`, so the home screen would have rendered empty
rails. `HomeView` now loads the catalogue explicitly. Found by grepping every
caller of `configStore.init` rather than by running the app, which is also how I
know `HomeView` is the only caller.
**Still on the unpaged list, by design:** the home rails and the search/newest
lists. They slice locally today; moving them onto paged reads with server-side
filtering is step 4, kept separate because it is the risky part (debounce,
loading state, telling "no results" from "still loading").
**Verification.** api 334/334 across 30 suites; both apps `vue-tsc` clean. The
`getOrders` include has a new spec (3 cases) because it is now a contract both
apps depend on and the method had no test at all. ⚠️ Nothing click-tested: the
cart re-sync and the favourites screen are the two worth a manual pass.
_No data was deleted in this entry._
+95
View File
@@ -1249,6 +1249,12 @@ customer. That is a session-hijack primitive; every session here derives from
the caller's own token. Not ported, and recorded here rather than silently
dropped.
> ⚠️ **SUPERSEDED BY D29 (2026-10-12).** The owner asked for the capability
> back, so acting as one's own customer now exists — with the reference's full
> scope, but not its mechanism: no token is minted, the expert keeps their own,
> and ownership is re-checked on every request. The paragraph above still
> describes correctly what is **not** done (minting customer tokens). See D29.
## Ambiguity resolved the low-risk way
If one mobile ever belonged to both an expert and a customer, the owner ruled
@@ -1418,3 +1424,92 @@ and product lists and a live balance on the app profile, all working whenever
a provider is connected regardless of the feature switches; and the order
status that posts the temporary document (پیش‌فاکتور) is an admin-chosen rule
(`documents.triggerStatus`, default «تحویل مسئول فروش»).
---
## D28 — ورود اپ باید خطای واقعی را بگوید (۲۰۲۶/۱۰/۱۲)
**گزارش مالک:** «اگر کاربری در اپ نبود خطا نمیدادی کاربر یافت نشد میبردیش توی
صفحه ارسال کد و واقعا نمیشد فهمید خطا از پروژه هست یا نه پیامک نمیاد یا نه واقعا
نیست میخوام خطا بدی کاربر یافت نشد»
**تصمیم:** مرحله اول ورود باید علت را بگوید.
| حالت | قبل | بعد |
|---|---|---|
| شماره ثبت نشده | `{ sent: true }` — کاربر به صفحه کد می‌رفت | **۴۰۴** «این شماره در سیستم ثبت نشده است…» |
| پیامک فرستاده نشد (درگاه خراب) | `{ sent: true }` | **۵۰۳** «ارسال پیام کوتاه در حال حاضر ممکن نیست…» |
| کارشناس فروش با حساب معاملاتی غیرفعال | `{ sent: true }` | **۴۰۳** «حساب شما غیرفعال است…» |
| کارشناس فروش بدون پروفایل | `{ sent: true }` | **۴۰۳** «حساب شما کامل نیست…» |
**نسبت با مرجع:** این همان کاری است که مرجع می‌کرد (`firstOrFail()` در
`ApiMobileController::userAuth:43` ⇒ ۴۰۴). پاسخ مبهم، انحراف ما بود نه این.
**معاوضه امنیتی، صریح:** پاسخ مبهم برای این بود که کسی از بیرون نتواند بفهمد چه
شماره‌هایی در سیستم ثبت‌اند. این محافظت در مرحله اول کاهش یافت، **عمداً و به
دستور مالک**، چون هزینه‌اش را کاربران واقعی و پشتیبانی می‌دادند. چیزی که سر جایش
ماند: سقف تعداد ارسال برای هر شماره و هر IP (`assertSendAllowed`) که مرجع
نداشت — پس شمارش‌کردن شماره‌ها محدود است نه آزاد؛ و مرحله دوم (`verifyOtp`) که
برای همه علت‌های شکست یک پیام واحد می‌دهد.
**چرا D20 اینجا نقض نمی‌شود:** D20 می‌گوید پیامک ناموفق نباید یک *عملیات* را
خراب کند — سفارش باید ثبت شود حتی اگر پیامکش نرود. در ورود، پیامک **خودِ
عملیات** است، پس سکوت از چیزی محافظت نمی‌کند.
ثبت شده در `ISSUES.md` به‌عنوان AUTH-01/02/03 و DOC-01.
---
## D29 — «ورود به حساب مشتری» برای کارشناس فروش (۲۰۲۶/۱۰/۱۲)
**خواسته مالک:** «کارشناس فروش میتونه از طریق اپ خودش وارد صفحه مشتری هاش بشه و
از جانب اون ها ثبت سفارش کنه و وضعیت اون هارو ببینه و یکجورایی انگار با اکانت
اون ها لاگین کرده همه چیز رو از دید اون مشتریش میدید و این خیلی کاربردی بود ولی
الان نیست» و سپس: «همان قابلیت هارو میخوام حالا هرجور که فکر میکنی از لحاظ
امنیت و پرفورمنس بهتره».
این **D21 را اصلاح می‌کند**: آنجا `changeUser` «عمداً پورت نشد» و به‌عنوان
session-hijack رد شد. مالک قابلیت را خواست، پس بازگردانده شد — با همان دامنه
کامل مرجع، ولی با سازوکار دیگر.
### دامنه: کامل، مثل مرجع
مرجع توکن را در interceptor سراسری axios عوض می‌کرد
(`henza_pwa/plugins/axios.ts:18` ← `getUserToken()`)، پس **هر** درخواست از طرف
مشتری می‌رفت: دیدن، ثبت سفارش، علاقه‌مندی، و آپلود مدارک. همان دامنه حفظ شد —
هیچ مسیری در حالت act-as بسته نشد.
### سازوکار: هدر، نه توکن
| | مرجع | اینجا |
|---|---|---|
| چطور | توکن دائمی مشتری (`api_token`) به کارشناس داده می‌شد (`ApiMobileController.php:197-201`) | کارشناس توکن **خودش** را می‌فرستد + هدر `X-Act-As-Customer` |
| کجا اعمال می‌شود | interceptor کلاینت | `CustomerJwtStrategy.validateExpert` — تنها نقطه |
| بررسی مالکیت | یک‌بار، در لحظه گرفتن توکن | **هر درخواست**، با `referredByAgentId` در همان کوئری |
| ماندگاری | `localStorage`، بی‌انقضا | `sessionStorage`؛ بستن تب = پایان |
| ردّ حسابرسی | هیچ — درخواست عیناً مشتری بود | `adminUserId` حفظ می‌شود؛ سفارش لاگ می‌شود |
| بعد از قطع همکاری کارشناس | توکن مشتری همچنان کار می‌کرد | ۴۰۱ فوری (نقش و `isActive` هر بار خوانده می‌شود) |
**چرا این نقطه:** `validate()` همیشه یک principal می‌سازد که `id` آن یک Customer
id است و **هر ۱۷ مسیر مشتری** از آن می‌خوانند. پس تغییر در یک نقطه، همه مسیرها
را از دید مشتری می‌کند — بدون تغییر در هیچ route.
**پرفورمنس:** یک `findFirst` روی کلید اصلی، **فقط** وقتی هدر هست؛ و جایگزین
کوئریِ `tradingCustomer` می‌شود نه اضافه بر آن. مشتری عادی و کارشناس در حالت
معمولی صفر هزینه اضافه.
**۴۰۳ و نه ۴۰۱** برای مشتریِ غیرمجاز: نشست خود کارشناس سالم است، پس اپ وضعیت
act-as را پاک می‌کند و او را از سیستم بیرون نمی‌اندازد.
### چیزهایی که مرجع نداشت و اضافه شد
۱. **نوار همیشگی «در حال مشاهده به‌عنوان …» + دکمه خروج.** در مرجع، جابجایی
نامرئی بود: راه فهمیدن اینکه در حساب کیستی، فقط دیدن داده‌های عجیب بود، و
ثبت سفارش روی حساب اشتباه یک کلیک فاصله داشت. تنها راه خروج هم logout بود که
نشست خود کارشناس را هم می‌بست (`Dashboard.vue:781-789`).
۲. **پاک‌سازی حالت در جابجایی** (هر دو جهت): سبد، `queryCache` کلیدهای `me:`،
علاقه‌مندی‌ها، و **اجرت‌های کش‌شده**. این آخری مالی است: اجرت هر مشتری
متفاوت است، و بدون پاک‌سازی عددِ روی صفحه با عددِ ثبت سفارش یکی نمی‌بود.
(در مرجع این مسئله وجود نداشت چون کل نشست با توکن عوض می‌شد.)
ثبت شده در `ISSUES.md` به‌عنوان EXP-01.
+102 -3
View File
@@ -17,7 +17,7 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
|---|---|---|---|---|---|
| SEC-01 | Critical | REF `henza_server/routes/admin.php:12,272` | The whole admin route file is **unauthenticated** — the `Route::middleware('auth:api')->group(...)` wrapper is commented out at both ends, leaving all ~215 admin routes public (incl. `wallet/charge`, `users`, `roles`). | Verified by reading both lines. | n/a in reference (read-only). Drives TGT decision below. |
| SEC-02 | ~~Critical~~ **FIXED — hotfix stage 3** | TGT `apps/api/src/modules/accounting/accounting.controller.ts:7`, `orders/orders.controller.ts:7`, `customers/customers.controller.ts:5`, `catalog/catalog.controller.ts:5`, `pricing/pricing.controller.ts:5` | 15 routes carry `@Public()`, including **ledger writes** (`POST accounting/repayments/*`, `entries/:id/confirm`) and `POST /api/orders` + `PATCH /api/orders/:id/status`. The public status DTO accepts a client-supplied `actorAdminUserId`, so a caller can attribute an action to any admin. | `grep -rn "@Public()"`; source comments say "pre-existing unauthenticated endpoint". | ✅ All closed across stages 1-3. Ledger + order-status behind admin rids; customer routes behind the customer JWT; `POST /orders` takes the customer from the token and ignores the body. Only `catalog/products`, `pricing/latest`, `home/slider` and `uploads/:filename` remain public, all by design. |
| SEC-03 | ~~Critical~~ **FIXED — hotfix stage 2** | TGT `apps/user-app/src/views/user/LoginView.vue`, `apps/user-app-v2/` same | OTP is **not verified** — any 4-digit code logs the user in. This is a **parity gap**: the reference does verify it (`ApiMobileController.php:51-57`, mismatch → HTTP 422). | `DECISIONS.md` D6 | ✅ Real server-side OTP: bcrypt-hashed code, 2-min expiry, 5 attempts, single use, send throttle, no enumeration. Verified end-to-end by `auth-smoke.sh`. |
| SEC-03 | ~~Critical~~ **FIXED — hotfix stage 2** | TGT `apps/user-app/src/views/user/LoginView.vue`, `apps/user-app-v2/` same | OTP is **not verified** — any 4-digit code logs the user in. This is a **parity gap**: the reference does verify it (`ApiMobileController.php:51-57`, mismatch → HTTP 422). | `DECISIONS.md` D6 | ✅ Real server-side OTP: bcrypt-hashed code, 2-min expiry, 5 attempts, single use, send throttle. Verified end-to-end by `auth-smoke.sh`. ⚠️ **"no enumeration" no longer holds at step 1** — owner ruling 2026-10-12 (see AUTH-01 below) makes `requestOtp` answer an unregistered number with 404, because the opaque answer was unusable in support. Step 2 (`verifyOtp`) is still single-message for every failure reason, and the per-IP send throttle still bounds any enumeration attempt. |
| SEC-08 | ~~Critical~~ **FIXED — hotfix stage 2** | TGT `apps/api/src/modules/customers/customers.service.ts:6-23,44-50` + `customers.controller.ts:10` (`@Public()`) | **Full customer book exposed to anonymous callers.** Login downloads `GET /customers` and matches the phone client-side, so the endpoint returns **every** active customer with `fullName`, `mobile`, **`nationalCode`**, `goldDebtGrams`, `fiatDebtRial`, `goldCreditLimitGrams`, and the URLs of **national-ID / business-licence / shop scans** (and `GET uploads/:filename` is public too, so those URLs resolve). `passwordHash` is correctly excluded. Not possible in the reference, where `userVerfiy` returned **one** customer after the code matched. | Read `customers.service.ts:5-23`; `DECISIONS.md` D8 | ✅ Closed. The whole controller is deleted — no route accepts a customer id any more. Reads moved to token-derived `/customer/me*`. Stage 1 had only narrowed the fields, which left the ids and the `:id` routes exposed. |
| SEC-09 | ~~Critical~~ **FIXED — hotfix stage 1** | TGT `apps/api/src/modules/accounting/accounting.controller.ts:7` | `@Public()` on the whole accounting controller exposes **5 routes, 4 of them writes**: reconcile a balance, record a gold repayment, record a rial repayment, confirm a ledger entry. Faithful to the reference (whose admin routes were all unauthenticated) but contradicts the confirmed decision D1. | `DECISIONS.md` §"@Public audit" group A | ✅ Done: rids `wallet.list`, `wallet.charge`, `document.create` ×2, `document.list.confirm`. Verified 401/403/pass-through by `apps/api/scripts/auth-smoke.sh`. |
| SEC-10 | ~~High~~ **FIXED — hotfix stage 1** | TGT `apps/api/src/modules/orders/orders.controller.ts:22` | `PATCH orders/:id/status` is public **and** its DTO accepts a client-supplied `actorAdminUserId`, so an anonymous caller can move an order's status and attribute it to any admin. In the reference this was an admin operation. | `DECISIONS.md` §"@Public audit" B3 | ✅ Done: `order.list.sts.submit`. Had no caller — the admin panel uses `admin/orders/status`. |
@@ -110,7 +110,7 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
| ID | Severity | Where | Description | Evidence | Status |
|---|---|---|---|---|---|
| SEC-12 | **Critical** | REF `henza_server/app/Models/Sms.php:73-77,101-105` | Live SMS-panel production credentials (username, plaintext password, sender line) are **committed to git** in the reference, duplicated across two methods. An older provider's credentials sit commented out beside them. Anyone with repo access can send SMS on the owner's account at their cost. | Read the file. | Not ported — the target will read them from env only. **The owner should rotate these credentials**; they must be assumed compromised. |
| STUB-05 | Medium | REF `ApiMobileController.php:154-158,601-605`; `Adm/OrderController.php:54-55`; `Customer/OrderController.php:141-145` | Admin notification recipients are **hardcoded mobile numbers** scattered across controllers (six distinct numbers). Staff changes require a code deploy, and an ex-employee keeps receiving order data. | Read the files. | Port as `SMS_ADMIN_RECIPIENTS` (comma-separated, default empty) rather than copying the literals. Pending the SMS approval. |
| STUB-05 | Medium | REF `ApiMobileController.php:154-158,601-605`; `Adm/OrderController.php:54-55`; `Customer/OrderController.php:141-145` | Admin notification recipients are **hardcoded mobile numbers** scattered across controllers (six distinct numbers). Staff changes require a code deploy, and an ex-employee keeps receiving order data. | Read the files. | ✅ **FIXED** (2026-10-12, commit `83e5d28`) — ported as two comma-separated env vars, `PROFILE_ADMIN_MOBILES` and `ORDER_ADMIN_MOBILES`, both defaulting to empty. No literal number is in the target's git history. |
| DEAD-06 | Low | REF `henza_pwa/src/views/cart.vue:181-182` | The cart sends `wage_weight: 5.7856000000000005` and `weight: 6.303744000000001` as **literal constants**, each with a `// how to get?!` comment. The server ignores both: it recomputes weight from `rash_weight`, and the `wage_weight` use is commented out (`ApiMobileController.php:549-551`). | Read both files. | Dead payload fields — do not port. |
## Found while applying the D0 / percent migrations (2026-09-22)
@@ -127,6 +127,13 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
| PRICE-02 | Info | REF `app/Models/ProductVariant.php:163` vs TGT `admin-products.service.ts:206-208` | `rial_pay` (a flat rial charge per variant) appears only in the **superseded, commented-out** formula, not the live one at `:183-190`. The target returns null rather than faking it, which matches the live reference. Recorded so nobody "restores" it from the dead code. | Read both. | ✅ No action — matches. |
| PERM-01 | Medium | TGT `prisma/seed.ts`; `apps/admin-panel/src/views/user/permissionConst.ts` | `dashboard.omde` and `dashboard.tak` are seeded into the `permission` table but are **absent from the permission UI tree**, so they can be held by a row yet never seen, granted or revoked from the admin screen — and nothing reads them any more (the protected Dashboard uses `dashboard.view`). The DB holds **178** distinct rids against the UI's **174**. | `SELECT rid FROM permission GROUP BY rid` → 178, including all three dashboard rids. | ✅ **FIXED 2026-10-08** (owner approved the deletion). Migration `20261008160000_dashboard_permission_merge` gives `dashboard.view` to every type holding `dashboard` / `dashboard.omde` / `dashboard.tak`, then deletes those rows. **Also found:** the import dropped these three as unknown rids, so legacy types 102, 104, 105, 108 and 135 lost the dashboard — `people.ts` RENAMED_RIDS now maps them to `dashboard.view`. The other 45 legacy rids the target lacks are tree parents or rids no legacy code reads. |
## Found while closing Phase 1 (2026-10-12)
| ID | Severity | Where | Description | Evidence | Status |
|---|---|---|---|---|---|
| SMS-03 | Medium | TGT `apps/api/src/modules/orders/orders.service.ts` | **No order-placement SMS at all.** The reference texts four audiences when an order is placed (`ApiMobileController.php:733-766`): the admins, the customer — with a distinct text when the order was suspended over the gram ceiling — and the customer's referring sales expert. `OrdersService` did not inject `SmsService`, so a customer placing an order was told nothing. The matrix had logged only the suspended-order message, understating the gap. | Read both sides; `grep SmsService` showed six modules wired and `orders` absent. | ✅ **FIXED 2026-10-12** — `notifyOrderPlaced` + `notifySalesAgent`, sent after the transaction commits, fire-and-forget per D20, admin numbers from `ORDER_ADMIN_MOBILES`. 6 tests. The «ویرایش شد» variant is «عمداً تکرار نشد» — no target path edits a placed order. |
| PERM-02 | Medium | TGT `apps/admin-panel/src/views/user/permissionConst.ts` | Two rids are **enforced by routes but absent from the permission tree**, so an operator cannot grant them: `newsletters` (newsletter subscriber list) and `persons.list.sellers.view` (the ➕ target-only agent-detail screen). Only a role that already holds them from the seed can use those routes. Inherited from the reference — that file's own header recorded four such rids; the other two (`buy.order.list`, `persons.create.customer.tak`) now have no route on either side and are dead. | Mechanical comparison of 68 enforced rids against 176 tree keys, `01-ADMIN-MATRIX.md` §2. | **awaiting owner** — the fix is additive (add the two keys to the tree) but it changes the permission vocabulary, so it waits like PERM-01 did. |
## Delivery-mode items (D19/D20, 2026-09-22)
| ID | Severity | Where | Description | Evidence | Suggested fix |
@@ -177,7 +184,7 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
| ID | Severity | Where | Description | Evidence | Suggested fix |
|---|---|---|---|---|---|
| **ACC-01** | Medium (unverified) | TGT `accounting-sync/providers/zarrin.provider.ts` | The Zarrin driver follows the published docs only — there is no Zarrin installation to test on. Open points: which sign of `listMandeHesabha` means "owes" (a setting, default negative), whether stones belong in `mablagh` or `mablaghSang` on `foroushSakhte` (sent in `mablagh`), and the exact response envelopes. | Owner: «نه، فعلاً نداریم» (no test install). Unit tests use the docs' sample outputs. | Before real use: a trial on temporary documents on a real install (owner's decision 11), check one balance and one document against the Zarrin UI. |
| **ACC-01** | Medium (unverified) | TGT `accounting-sync/providers/zarrin.provider.ts` | The Zarrin driver follows the published docs only — there is no Zarrin installation to test on. Open points: which sign of `listMandeHesabha` means "owes" (a setting, default negative), whether stones belong in `mablagh` or `mablaghSang` on `foroushSakhte` (sent in `mablagh`), and the exact response envelopes. | Owner: «نه، فعلاً نداریم» (no test install). Unit tests use the docs' sample outputs. | Before real use: a trial on temporary documents on a real install (owner's decision 11), check one balance and one document against the Zarrin UI. **Update 2026-10-12 — reads verified on the owner's install (v228, 870 accounts, 656 items):** negative balance = owes (default is right); a «فاکتور موقت» moves the balance at once (unlike Tahesab, ACC-02); fixed: `listKarSakhte` pages by 100 via `pageNum` (only 100 of 656 were read), `goroohSakhte` answers HTTP 400 with a good body (was treated as missing), the statement now skips «مانده از قبل» and is anchored on the live balance (its last row now equals Zarrin's balance; ranges agree on shared rows), temporary rows flagged, `infogardeshsakhte`'s hand-printed JSON repaired (+90 s timeout; Zarrin itself sometimes answers 500), document delete searches every ledger page, and a request on a kept-alive connection the server already closed is retried once on a fresh one ("socket hang up"). **Writes verified 2026-10-12** on owner-approved test account 953 «تست اپ گلدبانک» (09990001111, group متفرقه — Zarrin has no API to delete it, so it stays): addAccount, searchAccount finds it, edithesab keeps the group; foroushSakhte (bonak, 2 lines × 1 g, 10 %, movaghat=1) moved the balance by exactly 2.2 g = our acceptance rule, stock fell 1 g per item; hazfRadifSanad (kol=1) removed every row, balance and stock back to start. Fixed from that test: a movaghat=1 document is marked in `shomareSanad` («موقت»), not `noeFactor`; listhesabha names are «first * last» (all 873) — the «*» is now dropped. addFelezsakhteModel NOT tested (owner: no permanent test item). Security: the install is plain http on the internet with token `123456`. |
| **ACC-02** | Low (by design) | TGT D27 | Order documents are sent **temporary** (owner ruling), and a temporary Tahesab document does **not** move the balance until the accountant finalises it. Until then the balance the customer sees from the accounting software does not include those orders. | Measured on the Tahesab test server: balance delta 0 for a temporary `VKHKar`, −Vazn×Ayar/750 once final. | Accountant finalises documents promptly; the report marks temporary rows «موقت — هنوز در مانده اثر ندارد». |
| **ACC-03** | ~~**High**~~ **FIXED 2026-10-08 (owner-approved)** — `LedgerService.syncOrderDebt`: on every status change the order's ORDER_STOCK entries are brought to what legacy's recomputed `sts > 4` gives (full weight + rial while DELIVERED_TO_AGENT/CUSTOMER, else 0), posting only the difference as a confirmed DEBIT/CREDIT. Also fixes: straight-to-DELIVERED_TO_CUSTOMER owed nothing; rollback/cancel left the debt. Removing the «تحویل به نماینده» status is allowed again, as in legacy. Existing data: 0 orders out of line in dev and the imported copy. | TGT `orders/orders.service.ts` `updateStatus()` | The debt guard is `DELIVERED_TO_AGENT && !order.deliveredAt`, but `deliveredAt` is only set at `DELIVERED_TO_CUSTOMER`. An order moved into DELIVERED_TO_AGENT a second time (e.g. PREPARING → DELIVERED_TO_AGENT again via «تغییر وضعیت») posts the gold and rial debt **twice**. | Read at `orders.service.ts:135-160`. The new accounting hook is not affected (it dedupes on the existing document row). | Guard on an existing `ORDER_STOCK` ledger entry for the order instead of `deliveredAt`; needs owner approval (PROTECTED area). |
| **ACC-04** | Low (pre-existing) | TGT `src/prisma/migrate.ts` | On a completely empty database `runMigrations` fails: `0002_admin_schema.sql` sorts before `20260910113720_first` and alters tables that do not exist yet. Existing databases are unaffected. | Reproduced while preparing the D27 throwaway test database (`relation "City" does not exist`). | Rename to sort after `first`, with a `LEGACY_NAME_ALIASES` entry so applied databases do not re-run it. |
@@ -192,3 +199,95 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium`
| ID | Severity | Where | Description | Evidence | Status |
|---|---|---|---|---|---|
| **FAV-01** | High (data invisible) | TGT both apps `stores/favoritesStore.ts`; no API route | Favourites were **memory-only** in both apps (lost on reload), and the API had no favourites route — so the 874 favourites imported from legacy `major_favorites` into `CustomerFavorite` were never shown. Legacy kept them on the server (`POST add-to-fav`, `POST get-favorites`, `routes/api.php:84-85`). | Store header said "local-only … until that backend support exists". | ✅ Fixed 2026-10-08: `GET customer/me/favorites`, `POST customer/me/favorites/toggle` (customer from the token); both apps load on sign-in, clear on sign-out, toggle optimistically and roll back on failure. Verified on the imported data: a customer with 116 legacy favourites sees all 116. |
## Phase 2 — item #1, MON-08 close-out (2026-10-12)
| ID | Severity | Where | Description | Evidence | Status |
|---|---|---|---|---|---|
| **MON-08** | **High (money)** | REF `ApiMobileController.php:536-541`, `henza_pwa/src/views/cart.vue:170-179` vs TGT `apps/api/src/modules/orders/orders.service.ts` | The reference computed a customer's gold debt straight from `percent_pay`, `discount` and `rash_weight` **as sent in the request**, with nothing re-read from the database — so a crafted order could set its own making charge, its own discount and its own weight, i.e. decide how much gold the customer owed. | DECISIONS §"Report — MON-08"; the PHP block is quoted there in full. | ✅ **FIXED.** All four steps of the owner's ruling are in place. (1) An app order is priced by `WageService.quote` — `variantPercent + customerPercent − promotions` through the approved formula (`pricing/wage-formula.ts`, legacy's by default), read from the DB. (2) The client's figures are ignored and a mismatch is now logged (`warnOnPriceMismatch`, added 2026-10-12) — the same pattern as the `customerId` warning. (3) The comparison test `"gives an honest app exactly the total it sent"` proves an ordinary customer's total is unchanged. (4) The formula, its ordering and its rounding are untouched (D4). An operator ordering from the panel still keeps the numbers they typed, as legacy's order builder did. 16 tests on this service. |
**Accepted deviation, re-confirmed:** the reference also trusted the client's
`rash_weight`; the target reads the weight from the variant row. Per the owner's
ruling the target's behaviour stays — identical whenever the client sends the
true weight (which the reference app always does, `cart.vue:178`), different
only for a forged request, which is the point.
## Phase 2 — item #2, D3 close-out (2026-10-12)
Seven of D3's ten items were already built — all five screens exist in **both**
apps, as do the `sts_verify_step_two` guard and v2's cart stock ceiling
(verified in the code, not taken from a checkmark). Three were outstanding:
| ID | Severity | Where | Description | Evidence | Status |
|---|---|---|---|---|---|
| **APP-03** | Medium (UX) | REF `henza_pwa/src/router/index.ts:253-261` vs TGT `apps/user-app/src/router/index.ts`, `user-app-v2` same | A guest tapping a personal page (orders, transactions, profile, favourites, complete-profile) was redirected **in silence**, so they landed on the login box with nothing saying why. Legacy showed «ابتدا وارد شوید». | Read both guards; legacy calls `showNotify('ابتدا وارد شوید')` then `next({name:'home'})`. | ✅ **FIXED 2026-10-12** — `toast.info('ابتدا وارد شوید')` in both apps' `beforeEach`. **«عمداً تکرار نشد — D3/الف»** for the destination: legacy sent the guest to `home` and lost where they were going; the owner chose to keep the target's `query.redirect`, so signing in returns them to the page they asked for. Also applied via `meta.requiresAuth` rather than legacy's hand-kept list of five names, which additionally covers the two sales-expert pages. Only reached when the IAM is off (the default) or unreachable — silent SSO leaves the page before this runs, and a toast on a document being replaced could not be read. |
| **APP-04** | Low | REF `henza_pwa/src/router/index.ts:263-266` vs TGT both apps `stores/configStore.ts` | Legacy's `isLoaded` router guard sent a signed-in user to `home` from any route without `meta.skipLoadedCheck` until its one big bootstrap request had landed. | Read both; the target's store header already said `isLoaded` was not ported. | ⏹️ **«عمداً تکرار نشد — D3/ب»** (owner, 2026-10-12). The target has no bootstrap request — every page fetches its own data — so the flag would guard nothing and only add a bounce: opening a shared product link would land on home instead of the product. Porting it would port the breakage, not the behaviour (D4). Recorded in both apps' `configStore.ts` so a later reader finds the reasoning where they would look for the flag. |
| **ANLY-01** | Low | REF `henza_server/app/Http/Controllers/Api/LogController.php`, `henza_pwa/src/router/customAnalytics.ts`; routes `api.php:57-58` | Per-page dwell-time analytics: `POST /log/create/{title}` opened a row (`start_at`, `ip`, `title`, `customer_id`, optional `product_id`), `GET /log/update/{id}` closed it; four admin report endpoints aggregated it. Entirely absent from the target — no table, no routes, no calls. | Read the controller, the composable and the routes. | ⏸️ **DEFERRED — lowest priority, may never be built** (owner, 2026-10-12: «ج اصلا اولیوت نداره جزو اخرین چیز هایی هست که شاید درستش کنیم»). The full design is parked in `docs/PHASE2-D3-PLAN.md` §"شکاف ۳", including two reference defects **not** to copy if it is ever built: `log/create` required no auth and accepted any title (anyone could fill the table from outside), and `log/update` was a `GET` that wrote. Open owner questions there too: retention (suggested 90 days — legacy never deleted) and whether to store the IP at all (suggested no). |
## App login — owner ruling 2026-10-12 (says what went wrong)
Reported by the owner: «اگر کاربری در اپ نبود خطا نمیدادی کاربر یافت نشد
میبردیش توی صفحه ارسال کد و واقعا نمیشد فهمید خطا از پروژه هست یا نه پیامک نمیاد
یا نه واقعا نیست».
| ID | Severity | Where | Description | Evidence | Status |
|---|---|---|---|---|---|
| **AUTH-01** | **High (support/UX)** | TGT `apps/api/src/modules/customer-auth/customer-auth.service.ts` `requestOtp`, both apps' `LoginView.vue` | Step 1 returned `{ sent: true }` for a number no customer holds, so the app advanced to the code box and the person waited for an SMS that was never sent. Three very different causes were indistinguishable on screen: the SMS is late, the gateway is down, or the number was never registered — the only one the person can act on. | Read the guard (the opaque `return { sent: true }` with the enumeration note) and the apps' catch, which showed a generic «خطا در ارسال کد» for anything that was not a 429. | ✅ **FIXED.** 404 + «این شماره در سیستم ثبت نشده است…»; both apps now surface the server's Persian message for 404 as they already did for 429. **This restores the reference's behaviour** (`firstOrFail()`, `ApiMobileController::userAuth:43` → 404) — the opaque response was the deviation, not this. Enumeration stays bounded by `assertSendAllowed` (per-mobile and per-IP throttles), which the reference did not have, and step 2 is still a single message for every failure reason. |
| **AUTH-02** | **High (support/UX)** | TGT same file, `deliver` | A failed SMS send **also** returned success. `SmsService` never throws — a dead gateway is a log line (D20) — so an outage produced the identical "waiting at the code box" dead end, with nothing visible server-side either unless someone read the logs. | `SmsService.deliver` returns `{ ok: false, … }` and `requestOtp` ignored the result. | ✅ **FIXED.** A failed send is now 503 + «ارسال پیام کوتاه در حال حاضر ممکن نیست…». D20 protects an *operation* from a dead gateway (an order must still be placed); in a login the SMS **is** the operation, so there is nothing to protect by staying quiet. The code row is left in place (harmless, expires on its own). The local-dev path is preserved: when `SmsService` reports its own `sms-not-configured` outside production the code is logged and the login completes. |
| **AUTH-03** | Medium (wrong message) | TGT same file, `resolveExpertTradingAccount` | Found while fixing AUTH-01. Three states return no trading account for a sales expert who **does** exist (linked customer missing/deactivated/archived, or no `SalesExpertProfile`). Previously all three fell into the opaque success; with AUTH-01 they would have reported «این شماره ثبت نشده است» — a false statement that would send support hunting a registration problem that is not there. | Read the method: two `return null` paths plus the archived/inactive one. | ✅ **FIXED** in the same pass: 403 «حساب شما غیرفعال است…» and «حساب شما کامل نیست…», each distinct from the unknown-number message. The missing-profile case is now logged at `error`, not `warn` — it means something bypassed both paths that create a profile (D17), i.e. a server-side defect. |
| **DOC-01** | Low (misleading) | TGT both apps `src/views/user/LoginView.vue` header comment | The file header still said the OTP flow was **stubbed** — "the SMS-send step is stubbed — no SMS provider exists", "Step 2 (OTP code) is NOT verified — any 4-digit code is accepted" — and that step 1 matched against `GET /api/customers` **in the client**, which was the login leak (D8). All three had been untrue for weeks. | Read the comment against the code beside it. | ✅ **FIXED 2026-10-12** — corrected in both apps rather than deleted, with a note that the stale text actually misled a reader during this session. |
**Test gap this exposed.** `requestOtp` had **no test coverage at all**: the whole
28-test customer-auth suite stayed green through a change that altered its
response for every unregistered number. `request-otp.spec.ts` now covers 9 cases
— the happy path, the unknown number, Persian-digit input, a refused gateway, the
dev no-gateway fallback, that the fallback does **not** apply in production, and
the two sales-expert states.
## Sales expert — «ورود به حساب مشتری» restored (2026-10-12)
Reported by the owner: «کارشناس فروش میتونه از طریق اپ خودش وارد صفحه مشتری هاش
بشه و از جانب اون ها ثبت سفارش کنه … انگار با اکانت اون ها لاگین کرده … و این
خیلی کاربردی بود ولی الان نیست».
| ID | Severity | Where | Description | Evidence | Status |
|---|---|---|---|---|---|
| **EXP-01** | High (missing capability) | REF `henza_pwa` `customerChoice.vue:155-167` → `myDataStore.ts:159-169` → `tokenManage.ts:8` → `plugins/axios.ts:18`; REF server `ApiMobileController.php:197-201`. TGT both apps + `customer-jwt.strategy.ts` | A sales expert could open any of their referred customers' accounts and use the whole app as them — browse, see balance and debt, place orders. The reference did it by **minting and handing over the customer's own permanent `api_token`**, which its axios interceptor then used for every request. The target listed the customers but tapping one only opened a detail sheet; an expert's order always landed on their own trading account. | Read all five reference files and the target's view header, which recorded the omission (D21). | ✅ **RESTORED 2026-10-12 (D29)** with the reference's full scope — every customer route, including documents — but a different mechanism: `X-Act-As-Customer` alongside the expert's **own** token, resolved once in `CustomerJwtStrategy.validateExpert`, which is why all 17 customer routes work unchanged. Ownership (`referredByAgentId`) is re-checked **on every request** in the same query as the id, so another expert's customer and a non-existent id both answer 403. 11 tests. |
| **EXP-02** | Medium (found while building EXP-01) | TGT both apps `stores/queryCache.ts`, `favoritesStore.ts`, `wageQuoteStore.ts` | All three drop their per-customer data when `session.token` changes — but act-as changes **whose** data they hold *without* changing the token. An expert entering a customer's account would have seen their own profile, orders, balance, ledger, favourites and **making-charge quotes**. | Read each watcher; each one's own comment stated the rule it was about to break. | ✅ Fixed with EXP-01: each watcher now also keys on `actingAs.id`. The wage-quote one is the money case — making charge is per customer, so a stale quote would have shown a figure that was not the one the order was priced at. |
| **EXP-03** | Medium (same) | TGT both apps `api/client.ts` `uploadDocument` | The multipart upload bypasses `request()` and builds its own headers, so the act-as header had to be repeated there. Without it an expert uploading a customer's documents would have filed them against their **own** account, silently and with no error. | `grep Authorization` on the client returns two call sites, not one. | ✅ Both call sites send the header. |
**Deliberately different from the reference** (all in D29): no customer token is
ever minted; the act-as target lives in `sessionStorage`, so closing the tab ends
it, where the reference's `api_token` sat in `localStorage` forever and outlived
the expert's employment; `adminUserId` survives the switch so an order placed
this way is attributable (the reference's requests were indistinguishable from
the customer's own); a permanent «در حال مشاهده به‌عنوان …» bar with an exit
button, which the reference had no equivalent of — there, impersonation was
invisible and the only way out was a logout that also ended the expert's own
session; and the cart is cleared in both directions.
## Apps — navigation and read-freshness audit (2026-10-12)
Owner report: «من مثلا از صفحه پروفایل وارد صفحه لاگین میشم بک میزنم میره به صفحه
اصلی در صورتی که باید بیاد توی صفحه پروفایل … این یک نمونه بود، تمام ساختار این
مدلی رو برسی کن». Audited both, found four navigation defects and three
read-freshness ones.
| ID | Severity | Where | Description | Evidence | Status |
|---|---|---|---|---|---|
| **NAV-01** | Medium (UX, pervasive) | TGT both apps `components/ui/PageBar.vue` + 14 views | The back arrow pushed a **fixed route name** (`backTo`) instead of going back, so it ignored where the person came from. The reported case: the guest dashboard → «ورود / ثبت‌نام» → back landed on **home**, not the dashboard they came from, because `LoginView` declared `back-to="home"`. Of 15 `PageBar` uses only `SearchView` used real history. Inherited from the reference, which did the same in every component's back arrow (`$router.push({name:'userPage::hasSubRoute'})`). | Read `PageBar.onBack` and grepped all `back-to=` uses. | ✅ **FIXED.** `backTo` is now a **fallback**, used only when there is nothing to go back to; otherwise `router.back()`. The 14 declarations are kept and unchanged — they are exactly the right fallback for a direct link or refresh. |
| **NAV-02** | Medium | TGT both apps `stores/navStore.ts` (new), `router/index.ts` | NAV-01 needs to know whether back lands inside the app. `history.length` cannot answer it: it counts entries from before the app was opened, so a link opened in a fresh tab would look like it had somewhere to go back to and the back button would leave the app. | — | ✅ `navStore.entryIndex` records the history position of the app's first navigation (`afterEach`), and `canGoBack` compares `history.state.position` against it. Direction-proof, unlike a counter, which only grows and would be wrong after one back-and-forward. Verified vue-router writes `position` on every entry (`vue-router.mjs:97,109,145`). |
| **NAV-03** | **High (loses the user's place)** | TGT both apps `views/user/LoginView.vue` | After a successful sign-in the app `push`ed the destination, leaving the **login screen in history**. One tap of back returned to the login box, which the guard then bounced to home — so back after signing in lost the person's place entirely. The same file already honoured `?redirect=`, so sign-in and back disagreed about where the person belonged. | Read `sendToken`'s navigation against the `to.name === 'login'` guard. | ✅ `router.replace`. |
| **NAV-04** | Medium | TGT both apps `main.ts` (401 handler), `views/user/CompleteProfileView.vue` | Two more `push`es where the page being left is no longer reachable: the 401 handler left the page whose request just failed in history (back → it → bounced to login again), and complete-profile left a form that the guard redirects home once the documents are in, so back appeared to do nothing. | Grepped every `router.push` in both apps and checked each against the guards. | ✅ Both are `router.replace`. `CartView`'s post-order `push` to the orders list was **left as-is** — back lands on the emptied cart, which is a valid screen, not a dead end. |
| **READ-01** | **High (stale money data)** | TGT both apps `views/user/OrdersView.vue` | The view is in MasterLayout's keep-alive list but only loaded in `onMounted`, so **the second and every later visit made no request at all** — and even the first used the cache. An order's status changes on the admin side, which nothing in the app invalidates, so the list could be stale for the whole session. | `KEEP_ALIVE = ['HomeView','SearchView','OrdersView','DashboardView']` vs the view's single `onMounted`. | ✅ `onMounted` + `onActivated`, both `force`, per the owner's ruling. |
| **READ-02** | Medium | TGT both apps `views/user/TransactionsView.vue`, `HomeView.vue`, `user/DashboardView.vue` | Ledger entries were read without `force`, so after the first visit the cached list was shown indefinitely — and they are written by the **accounting** side, which this app can never know about. The gold price was only forced by pull-to-refresh, on two screens that show it prominently; `HomeView` is kept alive, so it was fetched once per app launch. | Read each call site. | ✅ All forced on entry. `DashboardView.loadDashboard`'s `force` parameter is gone: with both of its reads always fresh it controlled nothing. |
| **READ-03** | — (deliberate) | TGT both apps `stores/catalogStore.ts` | The catalogue is **not** re-read on entry. | — | Intentional, per the owner's own reasoning («سربار برای سرور نداره»): it is the entire active product list in one response, it changes when an admin edits it rather than minute to minute, and pull-to-refresh and placing an order already invalidate it. Re-fetching it on every tab switch is the needless load the ruling is meant to avoid. |
**On the cache layer itself** (the owner also asked whether its structure is
sound). It is: concurrent callers share one in-flight promise, and a response
that arrives after an `invalidate` is handed to its caller but **not** stored, so
a write never loses a race against a read in progress. Both are easy to get
wrong and both are right here. Its one real gap was that nothing ever went
stale — no TTL, and `force` used only by pull-to-refresh — which READ-01/02 fix
at the point that matters: opening the screen. The policy is now written at the
top of `queryCache.ts` so the next person does not re-introduce a TTL.
+65 -9
View File
@@ -19,12 +19,36 @@ The "Current state" table below is the parity project's and was last updated 202
| Field | Value |
|---|---|
| **Phase** | **Phase 1 — admin parity, matrix in progress** |
| **Branch** | `parity/phase-1-admin` (cut from `parity/security-hotfix`) |
| **Status** | Both stages done and verified live: **46/46** smoke assertions, **7/7** jest unit tests, typecheck + build clean on all three projects. |
| **Next step** | Phase 1(a) continued: `singleCustomer` diff-send, then the field-by-field audit of all Persons forms and grids |
| **Blocked on** | nothing |
| **Last updated** | 2026-09-22 |
| **Phase** | **Phase 2 — apps parity — items #1 and #2 done** (Phase 1 closed, `83e5d28`) |
| **Branch** | `main` (the parity branches were merged; see git log 2026-10-08..10-12) |
| **Status** | Phase 1: all in-scope sections closed (§2 §4 §5 §6 §7 §8 §9 ✅ · §3 ⏸️ by D16). Phase 2: **#1 MON-08 ✅**, **#2 D3 ✅**, app-login error reporting (**AUTH-01/02/03**, **DOC-01**), **«ورود به حساب مشتری» restored** (**EXP-01/02/03**, D29 — supersedes D21's omission), and the apps' back-navigation + read-freshness audit (**NAV-01…04**, **READ-01…03**). **308/308** jest tests; both apps `vue-tsc` clean. |
| **Next step** | Build **`02-APPS-MATRIX.md`** — the field-by-field apps matrix (D12), which Phase 2 has been running without. Then the remaining app rows it turns up. |
| **Blocked on** | nothing. Awaiting an owner ruling when convenient: **PERM-02**. Deferred by the owner: **ANLY-01** (route analytics, lowest priority). |
| **Last updated** | 2026-10-12 |
### Phase 1 close-out (2026-10-12)
The two items that were still genuinely unfinished:
| Item | Result |
|---|---|
| §2 — the D1 rid matrix (stood as *(pending)* all phase) | ✅ filled: 163 rid-guarded routes, 68 distinct rids, 176 tree keys, mapped per module. 66/68 grantable from the UI; the 2 that are not are **PERM-02**. |
| Order-placement SMS | ✅ **SMS-03** — the matrix had logged one missing message; in fact all four were missing and `OrdersService` had no `SmsService`. Fixed with 6 tests. |
**What is NOT done, by decision rather than by omission:**
| | Why |
|---|---|
| §3 — product price display (PRICE-01) | ⏸️ retail storefront, out of scope by **D13/D16**. `variant-price.ts` + 11 tests kept but unused. |
| Firebase push beside each SMS (PUSH-01) | ⏸️ deferred to the PWA port. |
| «سفارش ویرایش شد» admin SMS | «عمداً تکرار نشد» (D4) — no target path edits a placed order. |
| PERM-02 (2 ungrantable rids) | additive, changes the permission vocabulary → awaits the owner, as PERM-01 did. |
| `02-APPS-MATRIX.md` | Phase 2's file; not created yet. |
⚠️ **Not verified in a browser.** Every ✅ above rests on reading both sides,
unit tests and smoke scripts. The prior port's note still stands: no admin view
has been visually checked in a browser. A full click-through is the honest
remaining risk on Phase 1.
### Security hotfix — final result
@@ -92,8 +116,8 @@ All user rulings live there (D0–D17). Highlights that change how work is done:
- [x] P0.7 — Urgent traces delivered: `percent`, `@Public` list, login leak
- [x] P0.8 — Skill updated with rules C0 (field-by-field) and E0 (round-trip test)
- [x] **P1.0 — approved and DONE:** 5 ledger routes protected, `percent` column added, D0 migration applied, SMS provider implemented
- [ ] Phase 1 — Admin parity (branch `parity/phase-1-admin`, `01-ADMIN-MATRIX.md`) ← HERE
- [ ] **GATE:** "Admin parity is complete and tested. Shall we move on to the apps (user-app & user-app-v2)?"
- [x] Phase 1 — Admin parity (`01-ADMIN-MATRIX.md`) — all in-scope sections closed 2026-10-12
- [ ] **GATE** ← HERE — asked 2026-10-12: "Admin parity is complete and tested. Shall we move on to the apps (user-app & user-app-v2)?"
- [ ] Phase 2 — Apps parity (`02-APPS-MATRIX.md`, both user apps)
- [ ] Phase 3 — Work through `ISSUES.md` (only when user asks)
@@ -119,6 +143,8 @@ All user rulings live there (D0–D17). Highlights that change how work is done:
| D15 | **`_goldbank_migrations` is KEPT** — it is the tracking table of the app's own migration runner (`src/prisma/migrate.ts`), needed because the Docker image has no Prisma CLI. Declared `@@ignore`d; drift is zero. **Persian test input must come from a FILE, never a shell argument.** |
| D16 | **PRICE-01 STOPPED** — price display is retail-storefront (⏸️ D13); the B2B app works in making charge only. `variant-price.ts` + tests kept but unused. **Making charge stays in scope.** New work order: Persons → Products/variants/order-detail → the rest of the admin → gate → apps. **Per section: implement gaps, then field-by-field test, and show a gap summary BEFORE fixing.** |
| D17 | **SalesExpertProfile** (cityId, gramLevel, phone, nationalCode) + **firstName/lastName on all AdminUsers**. **`reagent_id` deliberately NOT ported** — in the reference it was a side effect of the shared customers form and filling it removed the expert from the selectable-agent list (queryReagent:420); the referrer logic lives on `Customer.referredByAgentId`. |
| D29 | **«ورود به حساب مشتری» restored** (2026-10-12) — a sales expert can work inside any of their referred customers' accounts with the reference's **full** scope (every customer route, documents included). Mechanism deliberately not the reference's: no customer token is minted; `X-Act-As-Customer` rides the expert's own token and is authorised in `CustomerJwtStrategy.validateExpert`, re-checking `referredByAgentId` on **every** request. **Supersedes D21's "deliberately not ported".** |
| D28 | **App login step 1 must say what went wrong** (2026-10-12): an unregistered number → 404, a failed SMS send → 503, an unusable sales-expert account → 403, each with its own Persian message. Restores the reference's `firstOrFail()`. **Trades away part of the anti-enumeration protection, deliberately** — the per-mobile/per-IP send throttles still bound it and `verifyOtp` stays single-message. See D28 for the full reasoning and why D20 is not violated. |
## Open — awaiting user approval
@@ -171,7 +197,37 @@ Consolidated into `00-INVENTORY.md`. Issues found: `ISSUES.md` (26 entries).
3. **D13** — the retail storefront is preserved but out of scope; see
`DECISIONS.md` §D13 and `PROTECTED.md` §H.
## Phase 2 — item #1 (fixed by the MON-08 ruling)
## Phase 2 — item #1 (MON-08) — ✅ DONE 2026-10-12
All four steps of the ruling are in place; see `ISSUES.md` §"Phase 2 — item #1".
Steps 1, 3 and 4 had landed with the wage-formula work; **step 2 — logging the
client figures that get discarded — was added 2026-10-12**, along with the
comparison test the ruling asked for («تست مقایسه‌ای»), which step 3 had not
actually had: the suite only covered a tampered request, not an honest one.
`orders.service.spec.ts` is now 16 tests.
An operator ordering from the panel still keeps the numbers they typed — only an
app order is re-priced by the server.
## Phase 2 — item #2 (D3) — ✅ DONE 2026-10-12
D3 was ten items, not one. **Seven were already built** — all five screens
(`/report`, `/report/detail`, `/ChildOrder`, `/customerChoice`,
`/complete_profile`) exist in **both** apps, as do the `sts_verify_step_two`
guard and v2's cart stock ceiling. Checked in the code, not read off a
checkmark.
| Outstanding item | Result |
|---|---|
| guest toast «ابتدا وارد شوید» | ✅ both apps (**APP-03**). The destination stays the target's `/login?redirect=…`, better than legacy's `home` — owner's call, logged as «عمداً تکرار نشد — D3/الف». |
| `isLoaded` router guard | ⏹️ **not ported** (**APP-04**) — guards a bootstrap request the target does not have; would only bounce a shared product link to `home` (D4). Owner agreed. |
| route analytics | ⏸️ **deferred, lowest priority** (**ANLY-01**) — design parked in `docs/PHASE2-D3-PLAN.md`, with the two reference defects not to copy and the two retention/privacy questions still open. |
⚠️ **Phase 2 is running without its matrix.** `02-APPS-MATRIX.md` still does not
exist, so "what else do the apps miss" rests on the earlier survey rather than a
field-by-field comparison (D12). That is the next item.
The original requirement, for the record:
Before anything else in Phase 2: the server must derive `wagePercent`,
`discountPercent` and `flatRialCharge` from the DB and **ignore** the client's